Regenerate 33 MDX skill pages + add lux-chains, lux-lps to nav

All skills deep-audited from source code. Zero stubs remaining.
75 skills total across 17 categories.
This commit is contained in:
2026-03-13 19:26:15 -07:00
parent 9676420f42
commit 3a8765af93
34 changed files with 10043 additions and 1227 deletions
+237 -71
View File
@@ -1,112 +1,278 @@
---
title: "Lux Bitcoin - Bitcoin Integration Static Site"
description: "## When to use"
title: "Lux Bitcoin"
description: "Bitcoin Integration Static Site"
---
## Overview
Lux Bitcoin is a **static marketing site** for Lux Network's Bitcoin integration. Built with Next.js 15, Tailwind CSS, and Radix UI primitives, it uses MDX for content and pulls from the `@luxfi/ui` and `@hanzo/ui` component libraries. Content covers Lux's energy-efficient approach to Bitcoin, ESG commitments, and global expansion.
Lux Bitcoin is a **static marketing site** for Lux Network's Bitcoin mining and energy operations (branded "LUX Energy"). Built with Next.js 15, Tailwind CSS, and MDX content, it uses the `@hanzo/ui` block system to compose scrollable "screenful" sections. The site covers energy-efficient Bitcoin mining, ESG commitments, and global expansion across North America, Europe, Asia-Pacific, and South America. Deployed as a static export with domain `luxbitco.in`.
## When to use
- Modifying the Lux Bitcoin landing page content or design
- Updating marketing copy about Lux Network's Bitcoin integration
- Working with the `@luxfi/ui` or `@luxfi/data` component libraries
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/bitcoin` |
| Package name | `@luxfi/bitcoin` |
| Version | 0.0.7 |
| Language | TypeScript |
| Framework | Next.js 15.1.6 |
| Package manager | pnpm@10.12.4 |
| License | (not specified) |
| Default branch | main |
| Private | Yes |
| Package | `@luxfi/bitcoin` v0.0.7 |
| Default branch | `main` |
| Framework | Next.js 15.1.6 (App Router) |
| React | 18.3.1 |
| Package manager | pnpm 10.12.4 |
| Output | Static export (`output: 'export'`) |
| Domain | `https://luxbitco.in` |
| Private | No (public repo) |
## Project structure
## Tech Stack
| Layer | Technology | Version |
|-------|------------|---------|
| Framework | Next.js (App Router) | 15.1.6 |
| UI Components | `@luxfi/ui` | 5.5.2 |
| UI Primitives | `@hanzo/ui` | 5.3.22 |
| Auth | `@hanzo/auth` | 2.5.5 |
| Commerce | `@hanzo/commerce` | 7.3.8 |
| Data Models | `@luxfi/data` | 1.1.1 |
| 3D Rendering | `@splinetool/react-spline` | 4.0.0 |
| Icons | `lucide-react` | 0.470.0 |
| MDX | `@next/mdx` 14.1.0, `@mdx-js/loader` 3.x, `@mdx-js/react` 3.x |
| SVG | `@svgr/webpack` 8.x |
| Dark Mode | `next-themes` 0.2.x |
| State | `mobx-react` 9.x, `mobx-react-lite` 4.x |
| CSS | Tailwind CSS 3.4.17, `postcss-import` |
| TypeScript | 5.7.3 |
## Project Structure
```
bitcoin/
public/ # Static assets
src/
app/ # Next.js App Router pages
content/ # MDX and TSX content blocks
about-lux-energy.mdx # Energy efficiency content
commitment-to-esg.mdx # ESG commitment content
global-expansion.mdx # Global expansion content
powering.tsx # Powering section
index.ts # Content barrel export
mdx-components.tsx # Custom MDX component overrides
metadata.ts # Site metadata and SEO
site-def.ts # Site definition constants
next.config.js # Next.js configuration
postcss.config.js # PostCSS with Tailwind
tailwind.config.ts # Tailwind CSS configuration
tsconfig.json # TypeScript configuration
svgr.next.config.js # SVG-as-React-component config
├── src/
│ ├── app/
│ │ ├── layout.tsx # Root layout (dark theme, black bg)
│ │ ├── page.tsx # Landing page ("LUX Bitcoin - Coming soon")
│ │ ├── not-found.tsx # Custom 404 page
│ │ └── globals.css # Tailwind base imports
│ ├── content/
│ │ ├── index.ts # Barrel export of all 4 content blocks
│ │ ├── powering.tsx # "Powering the Future" hero section
│ │ ├── about-lux-energy.tsx # About section wrapper (renders MDX)
│ │ ├── about-lux-energy.mdx # About LUX Energy content
│ │ ├── commitment-to-esg.tsx # ESG section wrapper (renders MDX)
│ │ ├── commitment-to-esg.mdx # ESG content
│ │ ├── global-expansion.tsx # Global expansion wrapper (renders MDX)
│ │ ├── global-expansion.mdx # Expansion content (4 regions)
│ │ └── typography-clx.ts # Typography class overrides for MDX
│ ├── metadata.ts # SEO metadata for luxbitco.in
│ ├── site-def.ts # Site definition (currentAs, nav, footer)
│ └── mdx-components.tsx # MDX component overrides (MDXLink)
├── public/
│ └── assets/
│ └── lux-site-icons/ # Favicons (16x16, 32x32, 192x192, 512x512)
├── next.config.js # Static export, transpilePackages
├── tailwind.config.ts # Lux UI preset
├── postcss.config.js # PostCSS with imports
├── svgr.next.config.js # SVG-as-React-component config
├── tsconfig.json
└── package.json
```
## Key dependencies
## Content Architecture
| Package | Version | Purpose |
|---------|---------|---------|
| `next` | 15.1.6 | React framework |
| `react` | 18.3.1 | UI library |
| `@luxfi/ui` | 5.5.2 | Lux design system components |
| `@luxfi/data` | 1.1.1 | Lux data models |
| `@hanzo/ui` | 5.3.22 | Hanzo shared UI components |
| `@hanzo/auth` | 2.5.5 | Authentication components |
| `@hanzo/commerce` | 7.3.8 | Commerce integration |
| `@splinetool/react-spline` | 4.0.0 | 3D graphics |
| `lucide-react` | 0.470.0 | Icons |
| `tailwindcss` | 3.4.17 | Utility-first CSS |
Content is structured as an array of `@hanzo/ui` Block types, exported from `src/content/index.ts`:
## One-file quickstart
```typescript
import { type Block } from '@hanzo/ui/blocks'
export default [
poweringTheFuture,
aboutLuxEnergy,
globalExpansion,
commitmentToESG
] satisfies Block[]
```
Each section follows a pattern:
1. **TSX wrapper** defines the `ScreenfulBlock` layout (column specifiers, centering)
2. **MDX file** contains the actual marketing copy
3. MDX is rendered inside `<ApplyTypography>` from `@hanzo/ui/primitives`
### Content Sections
#### 1. Powering the Future (`powering.tsx`)
Hero section using `EnhHeadingBlock`:
- Heading: "Powering the Future of Bitcoin Mining" (level 2)
- Byline: "At LUX Energy, we're revolutionizing the Bitcoin mining industry..." (level 4)
- Layout: Centered, `vert-center mobile-vert-center`
No MDX file -- content is inline in the TSX block definition.
#### 2. About LUX Energy (`about-lux-energy.mdx`)
MDX content covering:
- **About LUX Energy** -- Mission statement: sustainable, cost-effective energy solutions for mining
- **Green Energy Sources** -- Solar, wind, hydroelectric portfolio
- **Cost-Effective Power Agreements** -- Long-term strategic partnerships
- **Global Expansion** -- Brief mention of worldwide mining expansion
Rendered via `ElementBlock` wrapping `<ApplyTypography><MDX_About_Lux /></ApplyTypography>`.
#### 3. Commitment to ESG (`commitment-to-esg.mdx`)
MDX content covering:
- **Environmental Sustainability** -- Renewable energy, eco-friendly practices
- **Social Responsibility** -- Employee well-being, community engagement
- **Governance** -- Ethical framework, transparency, compliance
#### 4. Global Expansion (`global-expansion.mdx`)
MDX content covering 4 regions:
- **North America** -- USA and Canada, renewable energy resources
- **Europe** -- Iceland, Norway, Sweden, clean energy infrastructure
- **Asia-Pacific** -- Exploring renewable energy opportunities
- **South America** -- Brazil, Chile, hydroelectric and solar power
## Key Source Files
### `src/app/layout.tsx`
Root layout with dark theme:
```tsx
<html lang='en' className='dark'>
<body className='bg-black text-white flex flex-col min-h-full'>
<main className='flex flex-col grow'>
{children}
</main>
</body>
</html>
```
No `@luxfi/ui` imports -- the layout is intentionally minimal. Viewport theme color adapts to user preference.
### `src/app/page.tsx`
Current landing page is a centered placeholder:
- Heading: "LUX Bitcoin"
- Subtitle: "Coming soon"
- CTA: "Learn More" linking to `lux.network`
The content blocks defined in `src/content/` are prepared but not yet wired into the page.
### `src/app/not-found.tsx`
Custom 404 page with:
- Large "404" heading (96px font)
- "Oops, page not found" message
- "Go to Homepage" button
### `src/metadata.ts`
SEO metadata:
- `metadataBase`: `https://luxbitco.in`
- Title: "Lux Bitcoin" (template: `%s | Lux Bitcoin`)
- Description: Long description about green energy Bitcoin mining, BTC holdings, technology investment
- Application name: `Lux Bitcoin`
- Author: `Lux Partners Limited`
- Keywords: Lux Network, Blockchain Bridge, Multi-Chain, EVM, Solana, Bitcoin, Cross-Chain
- Favicons at `/assets/lux-site-icons/`
- OpenGraph and Twitter cards present but commented out
### `src/site-def.ts`
```typescript
import { footer, mainNav, type SiteDef } from '@luxfi/ui/site-def'
export default {
currentAs: 'https://luxbitco.in',
nav: { common: mainNav },
footer: footer.standard
} satisfies SiteDef
```
### `src/mdx-components.tsx`
Overrides anchor tags in MDX with `MDXLink` from `@hanzo/ui/primitives` for consistent link styling.
## Next.js Configuration
`next.config.js`:
- `output: 'export'` -- static site, no server
- `images: { unoptimized: true }` -- required for static export
- `typescript.ignoreBuildErrors: true`
- `eslint.ignoreDuringBuilds: true`
- `transpilePackages`: `@hanzo/ui`, `@hanzo/auth`, `@hanzo/commerce`, `@luxfi/ui`, `@luxfi/data`, `@luxfi/menu-icons`
## Tailwind Configuration
Uses the `@luxfi/ui` Tailwind preset:
```typescript
import { preset } from '@luxfi/ui/tailwind'
export default {
presets: [preset],
content: {
files: [
'src/**/*.tsx',
'./node_modules/@luxfi/ui/**/*.{ts,tsx}',
'./node_modules/@hanzo/**/*.{ts,tsx}'
]
},
theme: {
extend: {
colors: {
white: "#ffffff",
black: "#000000",
gray: "#e5e7eb",
}
}
}
}
```
## Commands
```bash
git clone https://github.com/luxfi/bitcoin.git
cd bitcoin
# Install dependencies
pnpm install
pnpm dev
```
## Development
```bash
# Dev server
# Development server
pnpm dev
# Production build
# Production build (static export to out/)
pnpm build
# Start production server
# Start production server (pre-export testing)
pnpm prod
# Type check
pnpm tc
# Clean build artifacts
# Clean .next build cache
pnpm cn
# Full clean (remove node_modules)
# Full clean (remove .next and node_modules)
pnpm clean
```
## Content architecture
## Shared Lux Ecosystem Pattern
The site uses MDX files in `src/content/` for marketing copy, paired with TSX files that define layout and component structure. Content is imported via a barrel `index.ts` and rendered through custom `mdx-components.tsx` overrides.
This site follows the standard `@luxfi/*` site pattern identical to `@luxfi/id`, `@luxfi/bridge`, etc.:
Content sections:
- **About Lux Energy** -- Energy efficiency of Lux Bitcoin
- **Commitment to ESG** -- Environmental, social, governance positioning
- **Global Expansion** -- Network growth and partnerships
- **Powering** -- What Lux Bitcoin powers
1. `@luxfi/<name>` package with `[email protected]`
2. Next.js 15.1.6 App Router with static export
3. `@luxfi/ui` 5.5.2 + `@hanzo/ui` 5.3.22
4. `@hanzo/auth` 2.5.5 + `@hanzo/commerce` 7.3.8
5. `@splinetool/react-spline` for 3D elements
6. Dark theme default (`className='dark'`)
7. Site def with `mainNav` + `footer.standard` from `@luxfi/ui/site-def`
8. MDX content wrapped in `ApplyTypography` + `ScreenfulBlock`
## Deployment
Static export deployed via standard hosting (no Docker). The `vercel.json` or equivalent config is not present in this repo -- deployment configuration is managed externally. The domain `luxbitco.in` is the canonical URL.
## Related Skills
- `lux/lux-bridge.md` -- Cross-chain bridge for Bitcoin transfers
- `lux/lux-ui.md` -- Shared UI component libraries
- `lux/lux-bridge.md` -- Cross-chain bridge for Bitcoin transfers to Lux
- `lux/lux-ui.md` -- Shared UI component libraries (`@luxfi/ui`, `@hanzo/ui`)
- `lux/lux-id.md` -- Identity portal (same site pattern)
+338 -86
View File
@@ -1,138 +1,390 @@
---
title: "Lux Bridge - Cross-Chain MPC Bridge"
description: "Lux Bridge is a decentralized cross-chain bridge using Multi-Party Computation (MPC) for secure asset transfers between Lux subnets and external EVM chains. It is a pnpm monorepo with a Next.js/Rea..."
title: "Lux Bridge"
description: "MPC Cross-Chain Bridge"
---
## Overview
Lux Bridge is a **decentralized cross-chain bridge** using Multi-Party Computation (MPC) for secure asset transfers between Lux subnets and external EVM chains. It is a pnpm monorepo with a Next.js/React frontend, Express API server, and shared TypeScript packages.
Lux Bridge is a decentralized cross-chain bridge using Multi-Party Computation (MPC) for secure asset transfers. It supports EVM chains (Ethereum, Base, BSC, Polygon, Arbitrum, Optimism, Avalanche, Lux, Zoo, and 10+ more) plus non-EVM chains (Bitcoin, Solana, TON, XRP). The bridge uses a burn-and-mint model on wrapped token chains and a lock-and-release vault model on native asset chains, with EIP-712 typed data signatures from an MPC oracle network providing cryptographic authorization for all claims.
### Why
Cross-chain asset movement requires trustless signing. Traditional multisigs are brittle (n-of-m key exposure). Lux Bridge replaces this with threshold signatures: no single node ever holds a complete private key. The MPC network generates, stores, and signs with key shares using TSS protocols (LSS for secp256k1/ECDSA, FROST for Ed25519/EdDSA), coordinated via NATS messaging and Consul service discovery.
### Tech Stack
| Layer | Technology |
|-------|-----------|
| UI | Next.js 14, React 18, Tailwind CSS, wagmi/viem, RainbowKit |
| Server | Express 4, TypeScript, Prisma 6, Winston logging |
| MPC Nodes | Go (`lux-mpc`/`mpcd`), BadgerDB, NATS, Consul |
| Contracts | Solidity 0.8.20, OpenZeppelin 5, Hardhat, EIP-712 |
| Database | PostgreSQL (`ghcr.io/hanzoai/sql`) |
| Infra | NATS 2.10, Consul 1.16+, Vault/KMS, Docker |
| Auth | Lux ID (Casdoor) OIDC |
| K8s | StatefulSet (MPC), Deployment (server/UI), NetworkPolicy |
### Key Dependencies
| Package | Version | Purpose |
|---------|---------|---------|
| `@luxfi/core` | 10.0.6 | Core types (Network, Asset, SwapStatus, Contract) |
| `@luxfi/threshold` | 1.0.0 | T-Chain ThresholdVM SDK (keygen, sign, reshare) |
| `@luxfi/ui` | 5.5.1 | Shared UI components |
| `@luxfi/utila` | 3.0.0 | Protobuf/ConnectRPC client, viem utils |
| `@noble/ed25519` | 2.3.0 | Ed25519 crypto primitives |
| `@openzeppelin/contracts` | 5.0.2 | ERC20, AccessControl, EIP-712, Pausable |
| `ethers` | 6.13.4 | Ethereum interaction (server) |
| `nats` | 2.29.3 | MPC node communication |
| `consul` | 2.0.1 | Service discovery and KV store |
| `@prisma/client` | 6.3.1 | Database ORM |
## When to use
- Building or deploying cross-chain asset transfer infrastructure on Lux
- Integrating MPC-based threshold signing into bridge workflows
- Running a bridge UI, explorer, or API server for Lux Network
- Bridging assets between Lux/Zoo and external EVM chains (Ethereum, Base, BSC, etc.)
- Bridging to/from non-EVM chains (Bitcoin, Solana, TON, XRP)
- Operating or deploying the MPC signer network for bridge authorization
- Deploying or managing bridge smart contracts on new chains
- Building white-label bridge UIs (Lux, Zoo, Pars, Hanzo)
- Integrating T-Chain ThresholdVM SDK for custom MPC workflows
## Hard requirements
- Node.js v20+
- pnpm v9.15.0+ (package manager)
- Go 1.22+ (for MPC node binary `lux-mpc`/`mpcd`)
- Docker (infrastructure services: NATS, Consul, PostgreSQL, KMS, Lux ID)
- PostgreSQL 15+ (bridge state database)
- NATS 2.10+ with JetStream enabled (MPC message bus)
- Consul 1.16+ (service discovery and key share storage)
## Quick reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/bridge` |
| Language | TypeScript |
| Package manager | [email protected] |
| Workspaces | `app/*`, `pkg/*` |
| Key deps | `@noble/ed25519`, `@luxfi/core`, `@luxfi/ui`, `next`, `react`, `tailwindcss` |
| License | Lux Ecosystem License v1.2 |
| Default branch | main |
## Monorepo structure
### Apps (`app/`)
| App | Purpose |
|-----|---------|
| `bridge` | Primary bridge UI |
| `bridge3` | Next-generation bridge UI |
| `explorer` | Bridge transaction explorer |
| `server` | Bridge API server |
### Packages (`pkg/`)
| Package | Purpose |
|---------|---------|
| `core` | Core bridge protocol logic |
| `settings` | Configuration and environment |
| `threshold` | MPC threshold signature library |
| `ui` | Shared UI components |
| `utila` | Utility functions |
| Workspaces | `app/*`, `pkg/*`, `contracts` |
| Solidity | 0.8.20 (Hardhat 2.22, optimizer 100 runs, viaIR) |
| License | MIT |
| Bridge UI | `bridge.lux.network` |
| Bridge API | `bridge-api.lux.network` |
| MPC API | `api.mpc.lux.network` |
| White-labels | `bridge.pars.network`, `bridge.hanzo.ai`, `bridge.zoo.ngo` |
| K8s namespace | `lux-bridge` |
| Images | `ghcr.io/luxfi/lux-mpc`, `ghcr.io/luxfi/bridge-server`, `ghcr.io/luxfi/bridge-ui` |
## One-file quickstart
```bash
git clone https://github.com/luxfi/bridge.git
cd bridge
# Clone and install
git clone https://github.com/luxfi/bridge.git && cd bridge
pnpm install
# Start infrastructure (Lux ID, KMS, NATS, Consul, PostgreSQL)
make up
# Start MPC network (3-node, 2-of-3 threshold)
# Install MPC tools (Go binary)
make install-mpc
# Start 3-node MPC network (2-of-3 threshold)
make start-mpc-nodes
# Start API server
cd app/server && pnpm dev
# In separate terminals:
cd app/server && pnpm dev # Bridge API on :5000
cd app/bridge && pnpm dev # Bridge UI on :3000
# Start bridge UI (separate terminal)
cd app/bridge && pnpm dev
# Verify
curl http://localhost:5000/health
# lux-mpc-cli status --url http://localhost:6000
```
## Architecture
## Core Concepts
### Architecture
```
Bridge UI (port 3000) --> Bridge Server (port 5000) --> MPC Nodes --> Blockchain Networks
|
KMS + Lux ID + Consul
+------------------+
| Bridge UI |
| (Next.js :3000) |
+--------+---------+
|
v
+--------+---------+
| Bridge Server |
| (Express :5000) |
+---+------+---+----+
| | |
+----------------+ | +----------------+
| | |
v v v
+-------+-------+ +----------+--------+ +-------+------+
| PostgreSQL | | NATS 2.10 | | Consul |
| (bridge state)| | (MPC msg bus) | | (discovery) |
+---------------+ +----------+--------+ +--------------+
|
+----------------+----------------+
| | |
+-----+-----+ +------+----+ +------+----+
| MPC Node 0| | MPC Node 1| | MPC Node 2|
| :6000 | | :6001 | | :6002 |
| (Go/mpcd) | | (Go/mpcd) | | (Go/mpcd) |
+-----+-----+ +------+----+ +------+----+
| | |
+-----+-----+ +------+----+ +------+----+
| BadgerDB | | BadgerDB | | BadgerDB |
| (shares) | | (shares) | | (shares) |
+-----------+ +-----------+ +-----------+
|
v
+--------+--------+
| Blockchain RPCs |
| (EVM, BTC, SOL) |
+-----------------+
```
### Infrastructure services (via compose.yml)
### MPC Signing Flow
| Service | Port | Purpose |
|---------|------|---------|
| Lux ID (Casdoor) | 8000 | Unified authentication |
| KMS (Vault) | 8200 | Key management |
| NATS | 4223 | Messaging |
| Consul | 8501 | Service discovery |
| PostgreSQL | 5433 | Bridge database |
| Lux ID DB | 5434 | Auth database |
1. **User initiates swap** via Bridge UI. Server creates a Swap record (status: `created`).
2. **Deposit detection**: User deposits tokens. For EVM: direct RPC `eth_getBalance`/ERC20 balance check. For BTC: Blockstream API. For SOL: `getBalance` RPC. For TON: `getAddressBalance`.
3. **MPC wallet creation**: Server calls `POST /keygen` on the MPC API (`mpc-node-0:9800`). The MPC cluster runs distributed key generation (TSS keygen) and returns `wallet_id`, `ecdsa_pub_key`, `eddsa_pub_key`, plus derived addresses (`eth_address`, `btc_address`, `sol_address`).
4. **Signature request**: When payout is needed, bridge server publishes a signing request to NATS topic `mpc.signing_request.<sessionId>`. The request includes the transaction hash, network IDs, token address, and an initiator signature (Ed25519, verified by `event_initiator_pubkey`).
5. **Threshold signing**: Each MPC node receives the request, validates the initiator signature, generates a partial signature share using its key share, and broadcasts it on NATS topic `bridge.mpc.sign.share`. When `threshold` (default: 2) shares are collected, they are combined into a full ECDSA/EdDSA signature.
6. **Signature result**: The combined signature is published to `mpc.mpc_signing_result.<txId>`. Bridge server reconstructs the 65-byte Ethereum signature (`r || s || v`) and returns it to the caller.
7. **On-chain claim**: The signature is submitted to the destination chain's Bridge contract via `bridgeMint()` or `bridgeWithdraw()`, which verifies the EIP-712 typed data signature against the registered ORACLE_ROLE address.
### MPC network
### MPC Protocols (via @luxfi/threshold)
| Node | HTTP | gRPC |
|------|------|------|
| Node 0 | 6000 | 9090 |
| Node 1 | 6001 | 9091 |
| Node 2 | 6002 | 9092 |
| Protocol | Curve | Use Case |
|----------|-------|----------|
| `lss` | secp256k1 | Ethereum, EVM chains, Bitcoin |
| `cggmp21` | secp256k1 | Alternative ECDSA protocol |
| `frost` | Ed25519 | Solana, TON, Cardano |
| `bls` | BLS12-381 | Beacon chain, aggregated sigs |
| `corona` | various | Post-quantum (experimental) |
## Key features
Auto-selection: specify `chain` in keygen request and T-Chain picks the right protocol. Example: `chain: 'ethereum'` selects `lss`, `chain: 'solana'` selects `frost`.
- **MPC Security**: 2-of-3 threshold signatures for bridge transactions
- **Multi-Chain**: Support for EVM and non-EVM chains
- **Unified Auth**: Lux ID (Casdoor) integration
- **Key Management**: Secure key storage via KMS (Vault)
- **Service Discovery**: Consul for dynamic configuration
- **Transaction Explorer**: Built-in explorer for tracking bridge operations
### Contract Architecture
## Development
All contracts target Solidity 0.8.20 with OpenZeppelin 5.
```bash
# Install dependencies
pnpm install
**Bridge.sol** (main contract, deployed per chain):
- Inherits: `AccessControl`, `Pausable`, `ReentrancyGuard`, `EIP712`
- Roles: `ADMIN_ROLE`, `ORACLE_ROLE` (MPC signer address), `PAUSER_ROLE`
- `bridgeBurn()` -- Burns wrapped tokens on source chain, emits `BridgeBurned` with destination data
- `bridgeMint()` -- Mints wrapped tokens on destination chain, requires EIP-712 oracle signature
- `bridgeWithdraw()` -- Withdraws from vault on destination chain, requires EIP-712 oracle signature
- Replay protection: ClaimId-based (immune to ECDSA malleability), not signature-based
- Fee: configurable `feeRate` (basis points, default 100 = 1%, max 1000 = 10%)
# Run tests
pnpm test
**ERC20B.sol** (bridgeable token):
- Inherits: `ERC20`, `AccessControl`, `Pausable`
- `BRIDGE_ROLE` can mint/burn via `bridgeMint()`/`bridgeBurn()`
- Deployed per wrapped asset per chain (e.g., `LETH` on Lux, `ZETH` on Zoo)
# Run tests across all packages
pnpm -r test
**LuxVault.sol / ZooVault.sol** (asset vaults):
- Holds native assets and ERC20s on origin chains
- Uses ERC4626 (`LERC4626`) for ERC20 yield-bearing vaults
- Uses `ETHVault` for native ETH (1:1 share model)
- Owned by Bridge contract
# Stop infrastructure
make down
**XChainVault.sol** (cross-subnet vault):
- For Lux Warp Messenger (cross-subnet) bridging
- Supports ERC20, ERC721, ERC1155
- Uses `IWarpMessenger` precompile at `0x0200000000000000000000000000000000000000`
- `vaultERC20()`, `vaultERC721()`, `vaultERC1155()` with Warp message proof
# Stop MPC nodes
make stop-mpc-nodes
### Chain IDs
| Chain | ID | RPC |
|-------|----|-----|
| Lux Mainnet | 96369 | `api.lux.network/ext/bc/C/rpc` |
| Lux Testnet | 96368 | `api.lux-test.network/ext/bc/C/rpc` |
| Zoo Mainnet | 200200 | `api.zoo.network/ext/bc/Z/rpc` or `api.lux.network/ext/bc/zoo/rpc` |
| Zoo Testnet | 200201 | `api.zoo-test.network/ext/bc/Z/rpc` |
| Ethereum | 1 | `eth.llamarpc.com` |
| Base | 8453 | `mainnet.base.org` |
| BSC | 56 | `bsc-dataseed.binance.org` |
| Polygon | 137 | `polygon-rpc.com` |
| Arbitrum | 42161 | `arb1.arbitrum.io/rpc` |
| Optimism | 10 | `mainnet.optimism.io` |
| Avalanche | 43114 | `api.avax.network/ext/bc/C/rpc` |
| Linea | 59144 | `lineascan.build` |
| Sepolia | 11155111 | `rpc.sepolia.org` |
| Holesky | 17000 | `ethereum-holesky-rpc.publicnode.com` |
### Supported Wrapped Tokens
**On Lux chain** (L-prefix, 29 tokens):
LETH, LBTC, LSOL, LTON, LBNB, LPOL, LAVAX, LUSD, LADA, LFTM, LCELO, LXDAI, LBLAST, LMRB, LZOO, LAI16Z, LBONK, LWIF, LBOME, LPOPCAT, LFWOG, LGIGA, LMEW, LPONKE, LPNUT, LDOGS, LNOT, LMOODENG, LREDO
**On Zoo chain** (Z-prefix, 34 tokens):
ZETH, ZBTC, ZSOL, ZTON, ZBNB, ZPOL, ZAVAX, ZUSD, ZADA, ZFTM, ZCELO, ZXDAI, ZBLAST, ZMRB, ZLUX, ZAI16Z, ZBONK, ZWIF, ZBOME, ZPOPCAT, ZFWOG, ZGIGA, ZMEW, ZPONKE, ZPUNT, ZDOGS, ZNOT, ZMOODENG, ZREDO, plus memecoins: TRUMP, MELANIA, CYRUS, SLOG, Z
### API Endpoints
Server base: `http://localhost:5000` (dev) / `https://bridge-api.lux.network` (prod)
| Method | Path | Description |
|--------|------|-------------|
| GET | `/health` | Health check with MPC network status |
| GET | `/api/swaps` | List swaps (query: `isDeleted`, `version`, `teleport`, `page`, `pageSize`) |
| GET | `/api/swaps/:swapId` | Get swap by ID |
| POST | `/api/swaps` | Create swap (body: `amount`, `source_network`, `destination_network`, `destination_asset`, `destination_address`, `use_deposit_address`, `use_teleporter`, `app_name`) |
| POST | `/api/swaps/transfer/:swapId` | Report user transfer (body: `txHash`, `amount`, `from`, `to`) |
| POST | `/api/swaps/payout/:swapId` | Report payout (body: `txHash`, `amount`, `from`, `to`, `hashedTxId`) |
| POST | `/api/swaps/mpcsign/:swapId` | Request MPC signature for swap |
| POST | `/api/swaps/getsig` | Get signature from MPC oracle network (body: `txId`, `fromNetworkId`, `toNetworkId`, `toTokenAddress`, `msgSignature`, `receiverAddressHash`) |
| PUT | `/api/swaps/expire/:swapId` | Expire a swap (72h no-deposit timeout) |
| GET | `/api/swaps/payout/:swapId` | Trigger payout via MPC wallet |
| GET | `/api/swaps/deposit-check/:swapId` | Manual deposit verification |
| GET | `/api/networks` | List supported networks |
| GET | `/api/tokens` | List supported tokens |
| GET | `/api/settings` | Bridge configuration |
| GET | `/api/quote` | Get bridge quote (fees, slippage, completion time) |
| GET | `/api/rate` | Exchange rates |
| GET | `/api/limits` | Bridge limits per asset |
| GET | `/api/explorer` | Explorer data |
| GET | `/api/exchanges` | Exchange integrations |
### Swap Status Lifecycle
```
Created --> UserTransferPending --> UserDepositPending --> BridgeTransferPending --> Completed
| |
+--> UserTransferDelayed +--> Failed
| |
+--> Expired (72h) +--> Cancelled
|
+--> TeleportProcessPending --> UserPayoutPending --> PayoutSuccess
```
## Compose variants
### Monorepo Structure
| File | Purpose |
|------|---------|
| `compose.yml` | Default development |
| `compose.local.yml` | Local development |
| `compose.testnet.yml` | Testnet deployment |
| `compose.mainnet.yml` | Mainnet deployment |
| `compose.infra.yml` | Infrastructure only |
```
github.com/luxfi/bridge/
app/
bridge/ Next.js 14 bridge UI (wagmi, RainbowKit, Solana wallets, TON Connect)
bridge3/ Remix v2 bridge UI (next-gen, @luxfi/core, MobX)
explorer/ Next.js transaction explorer
server/ Express API server (Prisma, MPC integration)
src/
server.ts Entrypoint (port 5000)
routes/ API route handlers
domain/ Business logic
mpc-bridge.ts NATS-based MPC signing integration
mpc-modern.ts Modern MPC wrapper (replaces Rust impl)
mpc-wallet.ts MPC wallet creation (keygen) and deposit checks
mpc-signer.ts Ed25519 request signing (initiator key)
swaps.ts Swap lifecycle management
teleport-processor.ts Background processor for Lux Teleporter swaps
services/
mpc-service.ts MPC network client (NATS, Consul, key shares)
prisma/
schema.prisma DB schema (Network, Currency, Swap, Transaction, Quote, DepositAction)
pkg/
core/ @luxfi/core v10.0.6 -- types (Network, Asset, SwapStatus, Contract)
threshold/ @luxfi/threshold v1.0.0 -- T-Chain ThresholdVM SDK
settings/ @luxbridge/settings -- shared bridge config
ui/ Shared UI components
utila/ @luxfi/utila v3.0.0 -- Protobuf/ConnectRPC, viem utils
contracts/
contracts/
Bridge.sol Main bridge contract (EIP-712, AccessControl, burn/mint/withdraw)
ERC20B.sol Bridgeable ERC20 (BRIDGE_ROLE mint/burn)
LuxVault.sol ERC4626 vault manager for Lux chain
ZooVault.sol ERC4626 vault manager for Zoo chain
ETHVault.sol Native ETH vault (1:1 shares)
LERC4626.sol ERC4626 wrapper
XChainVault.sol Cross-subnet vault (Warp Messenger, ERC20/721/1155)
lux/ 29 wrapped token contracts (LETH, LBTC, LSOL, ...)
zoo/ 34 wrapped token contracts (ZETH, ZBTC, ZSOL, ...)
DAI.sol, USDC.sol, USDT.sol, WETH.sol -- test stablecoins
hardhat.config.ts 18 network configs (mainnet + testnet)
config/
config.yaml MPC config (threshold, NATS, Consul, BadgerDB)
config.kms.yaml KMS integration config
peers.json MPC node identity UUIDs
casdoor/ Lux ID (Casdoor) config
mpc/ Per-node MPC configs
k8s/
mpc-deployment.yaml Full K8s manifest (StatefulSet, Deployments, Services, Ingress)
mpc-security.yaml NetworkPolicy (MPC node isolation) + MPC API Ingress
compose.yml Local dev (all services)
compose.local.yml Infrastructure only
compose.mainnet.yml Production (TLS, resource limits, monitoring, backups)
compose.testnet.yml Testnet (debug logging, faucet, test endpoints)
scripts/
init.sql PostgreSQL schema (swaps table)
start-mpc-network.sh Start 3 local MPC nodes
stop-mpc-network.sh Stop MPC nodes
install-mpc-tools.sh Install Go MPC binary
init-mpc.sh Initialize MPC keys and identities
launch-mpc-bridge.sh Full bridge launch script
migrate-mpc-keys.sh Key migration between deployments
trigger-keygen.js Programmatic keygen trigger
test/
test-mpc-complete.sh Full MPC integration test
test-mpc-e2e.js End-to-end MPC test
test-bridge-integration.sh Bridge flow integration test
test-full-integration.sh Complete system test
```
### Production K8s Deployment
Namespace: `lux-bridge`
| Component | Kind | Replicas | Image |
|-----------|------|----------|-------|
| MPC nodes | StatefulSet | 5 (3-of-5 threshold) | `ghcr.io/luxfi/mpc:latest` |
| Bridge server | Deployment | 2 | `ghcr.io/luxfi/bridge-server:latest` |
| Bridge UI | Deployment | 2 | `ghcr.io/luxfi/bridge-ui:latest` |
| PostgreSQL | StatefulSet | 1 | `ghcr.io/hanzoai/sql:latest` |
| KV (Valkey) | Deployment | 1 | `hanzoai/kv:latest` |
Production MPC: 5 nodes, 3-of-5 threshold (vs. dev: 3 nodes, 2-of-3).
Secrets managed via KMS (`kms.hanzo.ai`):
- `mpc-identity-keys`: `MPC_NODE{0..4}_PRIVATE_KEY`, `MPC_INITIATOR_KEY`
- `bridge-secrets`: `BRIDGE_DATABASE_URL`, `BRIDGE_DB_PASSWORD`, `MPC_DB_PASSWORD`, `mpc-api-token`, `mpc-wallet-id`, `fee-collector-address`
Network policies isolate MPC nodes: only `bridge-server` pods can reach MPC HTTP API (8080/8081). MPC nodes communicate with each other on ZAP p2p port 9651.
### Compose Variants
| File | Environment | MPC Nodes | Threshold | Extra Services |
|------|------------|-----------|-----------|----------------|
| `compose.yml` | Local dev | 3 | 2-of-3 | Lux ID, KMS, NATS, Consul |
| `compose.local.yml` | Infrastructure only | 0 (run locally) | - | Lux ID, KMS, NATS, Consul |
| `compose.testnet.yml` | Testnet | 3 | 2-of-3 | Prometheus, Grafana, Explorer |
| `compose.mainnet.yml` | Production | 3 | 2-of-3 | Prometheus, Grafana, Backup, TLS |
## Troubleshooting
**MPC nodes not starting**: Ensure NATS is running on port 4223 and Consul on 8501. Run `make up` first, then `make start-mpc-nodes`. Check `logs/node0.log`.
**Keygen timeout**: Default timeout is 120s. Ensure all threshold nodes are healthy: `lux-mpc-cli status --url http://localhost:6000`. Check that `event_initiator_pubkey` in config.yaml matches the key used by the bridge server.
**Signature verification fails on-chain**: Verify the MPC signer address has `ORACLE_ROLE` on the Bridge contract. Check that the EIP-712 domain name/version match between contract constructor and signing code.
**Deposit not detected**: The teleport processor polls every 15s for `TeleportProcessPending` swaps. Check RPC URL availability for the source network. Manual trigger: `GET /api/swaps/deposit-check/:swapId`.
**Database connection**: Server expects `POSTGRES_URL` env var. Local dev: `postgresql://bridge:bridge@localhost:5433/bridge`. Run `pnpm exec prisma db push` to sync schema.
**pnpm install fails**: Ensure `keccak` override is set to `3.0.4` in root `package.json`. Peer dependency warnings for `@hanzo/auth`, `@hanzo/commerce`, `firebase` are expected and ignored.
**Contract deployment**: Copy `.env` from `contracts/example.env`, set `PRIVATE_KEY` and RPC URLs. Run `npx hardhat run scripts/deploy.ts --network <network>`.
## Related Skills
- `lux/lux-node.md` -- Validator nodes that bridge connects to
- `lux/lux-mpc.md` -- MPC node binary, TSS protocols, key management
- `lux/lux-threshold.md` -- T-Chain ThresholdVM SDK details
- `lux/lux-warp.md` -- Warp Messenger for cross-subnet bridging
- `lux/lux-teleport.md` -- Lux Teleporter for subnet-to-subnet transfers
- `lux/lux-evm.md` -- C-Chain where bridge contracts execute
- `lux/lux-wallet.md` -- Wallet integration for bridge users
- `lux/lux-node.md` -- Validator nodes that bridge connects to
- `lux/lux-kms.md` -- Key management service for MPC secrets
Last Updated: 2026-03-13
@@ -0,0 +1,505 @@
---
title: "Lux Chains"
description: "Comprehensive Chain Reference"
---
## Overview
The Lux network is a multi-chain architecture where each blockchain is an instance of a Virtual Machine (VM). The node (`github.com/luxfi/node`) supports 3 core chains (always registered) and 11 optional chains (registered with the `allvms` build tag). All VM IDs and chain IDs are defined in `github.com/luxfi/[email protected]`.
## Chain Summary
| Letter | Name | VM | Build | Purpose |
|--------|------|----|-------|---------|
| P | Platform | PlatformVM | Core | Validators, staking, subnet management |
| X | Exchange | ExchangeVM | Core | UTXO-based asset creation and exchange |
| C | Contract | EVM | Core (plugin) | EVM smart contracts, Solidity |
| Q | Quantum | QuantumVM | Optional | Post-quantum cryptography, Quasar consensus |
| A | Attestation/AI | AIVM | Optional | AI compute tasks, TEE attestation, mining rewards |
| B | Bridge | BridgeVM | Optional | Cross-chain MPC bridge |
| T | Threshold | ThresholdVM | Optional | MPC-as-a-service for all chains |
| Z | Zero-Knowledge | ZKVM | Optional | ZK proofs, privacy, confidential transfers |
| G | Graph | GraphVM | Optional | GraphQL/DGraph unified data layer |
| D | DEX | DexVM | Optional | Native decentralized exchange |
| K | Key | KeyVM | Optional | Post-quantum distributed key management |
| O | Oracle | OracleVM | Optional | Decentralized oracle data feeds |
| R | Relay | RelayVM | Optional | Cross-chain message relay |
| I | Identity | IdentityVM | Optional | Decentralized identity (DID/VC) |
## Build Tags
```bash
# Minimal build (3 core chains: P, X, C)
go build ./...
# Full build (3 core + 11 optional = 14 chains)
go build -tags=allvms ./...
```
The `optionalVMCount` constant is 0 in minimal builds and 11 in `allvms` builds. See `node/vms_allvms.go` and `node/vms_minimal.go`.
## VM ID Definitions
From `github.com/luxfi/[email protected]/vm_ids.go`:
```go
PlatformVMID = ids.ID{'p', 'l', 'a', 't', 'f', 'o', 'r', 'm', 'v', 'm'}
ExchangeVMID = ids.ID{'a', 'v', 'm'}
XVMID = ExchangeVMID // Alias
ContractVMID = ids.ID{'e', 'v', 'm'}
EVMID = ContractVMID // Alias
QuantumVMID = ids.ID{'q', 'u', 'a', 'n', 't', 'u', 'm', 'v', 'm'}
AttestationVMID = ids.ID{'a', 'i', 'v', 'm'}
AIVMID = AttestationVMID // Alias
BridgeVMID = ids.ID{'b', 'r', 'i', 'd', 'g', 'e', 'v', 'm'}
ThresholdVMID = ids.ID{'t', 'h', 'r', 'e', 's', 'h', 'o', 'l', 'd', 'v', 'm'}
KeyVMID = ids.ID{'k', 'e', 'y', 'v', 'm'}
ZKVMID = ids.ID{'z', 'k', 'v', 'm'}
GraphVMID = ids.ID{'g', 'r', 'a', 'p', 'h', 'v', 'm'}
DexVMID = ids.ID{'d', 'e', 'x', 'v', 'm'}
OracleVMID = ids.ID{'o', 'r', 'a', 'c', 'l', 'e', 'v', 'm'}
RelayVMID = ids.ID{'r', 'e', 'l', 'a', 'y', 'v', 'm'}
IdentityVMID = ids.ID{'i', 'd', 'e', 'n', 't', 'i', 't', 'y', 'v', 'm'}
```
## Chain Registry
The `ChainRegistry` in `github.com/luxfi/[email protected]/chain_registry.go` provides dynamic chain ID lookup per network (mainnet, testnet, devnet, custom). All networks use the same `ids.{P,X,C,Q,A,B,T,Z,G,K,D}ChainID` defaults. Chain IDs can be migrated at runtime via `MigrateChain()`.
## Core Chains (Always Registered)
### P-Chain (Platform)
| Property | Value |
|----------|-------|
| VM | PlatformVM |
| VM ID | `platformvm` |
| Package | `github.com/luxfi/node/vms/platformvm` |
| Consensus | Snowman (linear chain) |
| Registration | Direct factory in `node.go` |
| Critical | Yes |
**Purpose:** The P-Chain is the metadata chain that coordinates validators and staking across the entire Lux network. It manages subnet creation, validator registration, delegation, and cross-chain transfers of the LUX token between the P-Chain and other chains.
**Key Features:**
- Validator set management and staking
- Subnet creation and governance
- Single-validator mode support
- Block adapter pattern for compatibility
- Warp messaging (anycast support)
### X-Chain (Exchange)
| Property | Value |
|----------|-------|
| VM | ExchangeVM |
| VM ID | `avm` (alias: `ExchangeVMID`, `XVMID`) |
| Package | `github.com/luxfi/node/vms/exchangevm` |
| Consensus | DAG (Lux consensus, vertex-based) |
| Registration | Direct factory in `node.go` |
| Critical | Yes |
**Purpose:** The X-Chain is a UTXO-based chain for creating and trading digital assets. It uses DAG consensus for high-throughput asset operations. Unlike the C-Chain (account model), the X-Chain uses the UTXO model.
**Key Features:**
- UTXO-based transaction model
- Asset creation (fungible and NFTs)
- DAG consensus engine (`github.com/luxfi/consensus/engine/dag`)
- Transaction indexing by address
- Mempool management
- secp256k1 FX for signature verification
- Wallet client and service
- Configurable transaction fees (`TxFee`, `CreateAssetTxFee`)
- Etna network upgrade support
### C-Chain (Contract)
| Property | Value |
|----------|-------|
| VM | EVM (Lux EVM) |
| VM ID | `evm` (alias: `ContractVMID`, `EVMID`) |
| Package | `github.com/luxfi/evm` (external plugin) |
| Consensus | Snowman (linear chain, block-based) |
| Registration | Plugin binary via ZAP gRPC transport |
| Critical | Yes |
**Purpose:** The C-Chain runs the Ethereum Virtual Machine, supporting Solidity smart contracts, ERC-20 tokens, DeFi protocols, and all standard Ethereum tooling. It is loaded as an external plugin binary placed at `<plugin-dir>/<EVMID>`.
**Key Features:**
- Full EVM compatibility (Solidity, Vyper)
- All Ethereum JSON-RPC APIs (`eth`, `personal`, `txpool`, `debug`)
- 40+ stateful precompiles (see `lux/lux-evm.md`)
- QuantumSwap native DEX precompiles (LP-9xxx)
- FHE precompiles for confidential computing
- Cross-chain atomic transactions (X-Chain <-> C-Chain)
- Warp messaging for subnet interoperability
- Network upgrades: EVM, Durango, Etna, Fortuna, Granite
See `lux/lux-evm.md` for complete precompile addresses and architecture.
## Optional Chains (allvms Build Tag)
### Q-Chain (Quantum)
| Property | Value |
|----------|-------|
| VM | QuantumVM |
| VM ID | `quantumvm` (alias: `QVMID`) |
| Package | `github.com/luxfi/node/vms/quantumvm` |
| Consensus | DAG + Quasar PQ-BFT (hybrid BLS + Corona) |
| Version | 1.0.0 |
**Purpose:** The Q-Chain provides post-quantum cryptographic security using ML-DSA signatures (NIST FIPS 204) and Corona threshold lattice cryptography. It serves as the quantum-safe anchor for the entire Lux network, providing quantum stamps that other chains can reference for PQ finality.
**Key Features:**
- **ML-DSA quantum signatures** (NIST PQC, FIPS 204)
- **Corona threshold** ring-LWE post-quantum signatures
- **Quasar hybrid consensus**: dual BLS + Corona threshold signing
- BLS fast path for classical consensus speed
- Corona path for post-quantum security guarantee
- Parallel transaction processing (configurable batch size and max parallelism)
- Quantum stamp interface (`StampBlock`/`VerifyStamp`) for cross-chain PQ finality
- Block-level quantum signatures
- Configurable: `QuantumAlgorithmVersion`, `CoronaKeySize`, `QuantumStampWindow`, `QuantumSigCacheSize`
**Consensus Architecture:**
```
QuasarBridge
BLS Threshold --> Classical fast-path consensus
Corona --> Post-quantum lattice threshold
Combined --> Dual signature for PQ-BFT finality
```
### A-Chain (Attestation/AI)
| Property | Value |
|----------|-------|
| VM | AIVM |
| VM ID | `aivm` (alias: `AttestationVMID`, `AIVMID`) |
| Package | `github.com/luxfi/node/vms/aivm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The A-Chain handles AI compute task management, provider attestation, and mining reward distribution. Providers register with TEE attestation and are assigned inference/training tasks.
**Key Features:**
- **TEE attestation**: CPU (SGX, SEV-SNP, TDX) and GPU (nvtrust, local, no cloud dependency)
- Task submission, assignment, and result verification
- Provider registration with trust scoring (`MinTrustScore`)
- Mining rewards with epoch-based distribution (`BaseReward`: 1 LUX)
- Merkle root anchoring to Q-Chain (`MerkleAnchorFreq`: every 100 blocks)
- Core AI VM from `github.com/luxfi/ai/pkg/aivm`
- Attestation from `github.com/luxfi/ai/pkg/attestation`
- Model registry and stats
- RPC service at `/rpc`
### B-Chain (Bridge)
| Property | Value |
|----------|-------|
| VM | BridgeVM |
| VM ID | `bridgevm` |
| Package | `github.com/luxfi/node/vms/bridgevm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The B-Chain provides secure cross-chain bridging using MPC (multi-party computation) threshold signatures. Validators act as MPC signers to collectively authorize bridge transfers.
**Key Features:**
- **MPC threshold signing** for cross-chain operations (CGGMP21 protocol)
- Configurable threshold (`MPCThreshold`) and total parties (`MPCTotalParties`)
- **LP-333 Opt-in Signer Set**: first 100 validators join without reshare; reshare only on slot replacement
- Signer set management: active signers (max 100), waitlist, epoch tracking
- Combined threshold public key
- Bridge fee and daily limits
- Validator bond requirement (100M LUX, slashable, NOT staked)
- Supported chains configuration
- Maximum bridge amount per transaction
- Uses `github.com/luxfi/threshold` for MPC protocols
### T-Chain (Threshold)
| Property | Value |
|----------|-------|
| VM | ThresholdVM |
| VM ID | `thresholdvm` |
| Package | `github.com/luxfi/node/vms/thresholdvm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The T-Chain provides MPC-as-a-service for all other Lux chains. Any chain can request threshold signature operations (keygen, signing, key rotation) through the T-Chain.
**Key Features:**
- **MPC keygen and signing** sessions (LSS protocol from `github.com/luxfi/threshold`)
- Per-chain authorization and permissions (`AuthorizedChains`)
- Daily signing quotas per chain (`DailySigningQuota`)
- Concurrent session management (`MaxActiveSessions`, `MaxSessionsPerChain`)
- Key rotation with configurable period and maximum key age
- Session timeout and expiry
- Signing quota enforcement
- secp256k1 key support via `github.com/luxfi/crypto/secp256k1`
### Z-Chain (Zero-Knowledge)
| Property | Value |
|----------|-------|
| VM | ZKVM |
| VM ID | `zkvm` |
| Package | `github.com/luxfi/node/vms/zkvm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The Z-Chain implements a UTXO-based privacy chain with zero-knowledge proofs, confidential transfers, and optional FHE support. It uses nullifier-based double-spend prevention.
**Key Features:**
- **Confidential transfers** with ZK proofs
- **Private addresses** (stealth address support)
- **Proof systems**: Groth16, PLONK (configurable)
- **FHE support**: BFV, CKKS schemes with configurable security level (128/192/256)
- UTXO database with nullifier tracking
- Merkle state tree for state commitments
- Proof verification with caching (`ProofCacheSize`)
- Address manager for private/stealth addresses
- Configurable max UTXOs per block
- Proof verification timeout
### G-Chain (Graph)
| Property | Value |
|----------|-------|
| VM | GraphVM |
| VM ID | `graphvm` |
| Package | `github.com/luxfi/node/vms/graphvm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The G-Chain provides a GraphQL/DGraph unified data layer for cross-chain queries and data indexing across the Lux network.
**Key Features:**
- **DGraph integration** for graph-native storage
- **GraphQL API** with configurable query depth and timeout
- Federation support for cross-chain queries
- Automatic indexing with batch processing
- Query result size limits
- Authentication via API keys
- DEX-specific GraphQL resolvers (`dex_resolvers.go`)
- Schema versioning
### D-Chain (DEX)
| Property | Value |
|----------|-------|
| VM | DexVM |
| VM ID | `dexvm` |
| Package | `github.com/luxfi/node/vms/dexvm` |
| Consensus | Snowman (linear) |
| Version | From `github.com/luxfi/version` |
| Critical | Yes (in allvms builds) |
**Purpose:** The D-Chain runs a native decentralized exchange with an order book, AMM pools, perpetual contracts, and MEV protection. It is marked as critical in `allvms` builds.
**Key Features:**
- **Order book** matching engine (`orderbook` package)
- **AMM liquidity pools** (`liquidity` package)
- **Perpetual contracts** (`perpetuals` package)
- **MEV protection** (`mev` package)
- WebSocket support for real-time market data
- Warp messaging for cross-chain settlement
- Deterministic block results for verifiability
- Network layer for order propagation
- Transaction types for DEX operations (`txs` package)
- Configurable via `config` package
### K-Chain (Key)
| Property | Value |
|----------|-------|
| VM | KeyVM |
| VM ID | `keyvm` (alias: `KVMID`) |
| Package | `github.com/luxfi/node/vms/keyvm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The K-Chain provides distributed key management using post-quantum cryptography (ML-KEM) and threshold secret sharing.
**Key Features:**
- **ML-KEM key encapsulation** (post-quantum, FIPS 203) via `github.com/luxfi/crypto/mlkem`
- **ML-DSA signatures** (post-quantum, FIPS 204) via `github.com/luxfi/crypto/mldsa`
- **BLS key support** via `github.com/luxfi/crypto/bls`
- AES-256 encryption with HKDF key derivation
- Threshold secret sharing for key shares
- Key metadata and share storage with database prefixes
- LRU cache for frequently accessed keys
- Parallel crypto operations (max 100 concurrent)
- RPC service at `/rpc`
- Registered via `NewDefaultFactory()` (unlike other VMs that use `&Factory{}`)
### O-Chain (Oracle)
| Property | Value |
|----------|-------|
| VM | OracleVM |
| VM ID | `oraclevm` (alias: `OVMID`) |
| Package | `github.com/luxfi/node/vms/oraclevm` |
| Consensus | Snowman (linear) |
| Version | 1.0.0 |
**Purpose:** The O-Chain provides decentralized oracle services for external data feeds with cryptographic verification.
**Key Features:**
- **Observe-Commit-Aggregate** pipeline:
1. Operators fetch data from external sources
2. Signed observations submitted on-chain
3. Canonical output computed (median, TWAP, weighted, bounded deviation)
- ZK aggregation proofs for correctness
- Threshold attestation fallback for compatibility
- Configurable observation window and minimum observers
- Per-block feed limits
- Artifact-based block management
### R-Chain (Relay)
| Property | Value |
|----------|-------|
| VM | RelayVM |
| VM ID | `relayvm` (alias: `RVMID`) |
| Package | `github.com/luxfi/node/vms/relayvm` |
| Consensus | Snowman (linear) |
| Version | From `github.com/luxfi/node/vms/artifacts` |
**Purpose:** The R-Chain handles cross-chain message relay with Ed25519 signature verification, providing a general-purpose inter-chain communication layer.
**Key Features:**
- Message lifecycle: pending -> verified -> delivered (or failed)
- Channel-based message routing
- Ed25519 signature verification per message
- Configurable max message size (default 1MB)
- Confirmation depth (default 6 blocks)
- Relay timeout (default 300 seconds)
- Database-backed message and channel state
### I-Chain (Identity)
| Property | Value |
|----------|-------|
| VM | IdentityVM |
| VM ID | `identityvm` (alias: `IVMID`) |
| Package | `github.com/luxfi/node/vms/identityvm` |
| Consensus | Snowman (linear) |
| Version | From `github.com/luxfi/node/vms/artifacts` |
**Purpose:** The I-Chain provides decentralized identity management with W3C-compatible verifiable credentials and zero-knowledge proof support.
**Key Features:**
- Credential lifecycle: pending -> active -> revoked/expired
- Credential TTL (default 1 year)
- Maximum 100 claims per credential
- Issuer authorization tracking
- Revocation registry
- Zero-knowledge proof verification for selective disclosure
- Database-backed identity, credential, issuer, and revocation stores
## Additional VM Components
### FalconFX
| Package | `github.com/luxfi/node/vms/falconfx` |
|---------|--------------------------------------|
Post-quantum transaction signing FX using Falcon lattice signatures. Provides `Credential`, `Transfer`, and `FX` types for Falcon-signed UTXO transactions. Not a standalone chain -- used as an FX plugin by X-Chain and P-Chain.
### ServiceNodeVM
| Package | `github.com/luxfi/node/vms/servicenodevm` |
|---------|------------------------------------------|
Service node registration and management VM. Provides a registry for service nodes with configurable service types. Includes block, config, factory, registry, and service components.
### ExchangeVM (extended)
| Package | `github.com/luxfi/node/vms/exchangevm` |
|---------|---------------------------------------|
The X-Chain VM also supports:
- Block builder pattern for vertex/block construction
- PubSub filtering for transaction notifications
- Static service for genesis utilities
- Wallet service for transaction construction
### ChainAdapter
| Package | `github.com/luxfi/node/vms/chainadapter` |
|---------|----------------------------------------|
Cross-chain adapters for external blockchain integration:
- **Ethereum** adapter (EVM chains)
- **Bitcoin** adapter
- **Cosmos** adapter (IBC)
- **Solana** adapter
- **AppChain** generic adapter
- **Bridge adapter** (MPC wallet integration)
- **FHE-CRDT** adapter (encrypted CRDT with FHE compute, DA layer, and encryption)
### Data Availability (DA)
| Package | `github.com/luxfi/node/vms/da` |
|---------|-------------------------------|
Blob storage and data availability layer. Provides `Blob` and `Store` types for DA commitments used by rollup verification precompiles.
## Chain Registration Flow
### Core Chains (node.go)
```go
// P-Chain: registered directly with internal config
n.VMManager.RegisterFactory(ctx, constants.PlatformVMID, &platformvm.Factory{...})
// X-Chain: registered directly
n.VMManager.RegisterFactory(ctx, constants.XVMID, &exchangevm.Factory{})
// C-Chain: loaded as plugin binary via ZAP transport
// Binary at <plugin-dir>/<EVMID>
```
### Optional Chains (vms_allvms.go)
All 11 optional VMs are registered via `registerOptionalVMs()`:
```go
n.VMManager.RegisterFactory(ctx, constants.QuantumVMID, &qvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.AIVMID, &aivm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.BridgeVMID, &bvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.ThresholdVMID, &tvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.ZKVMID, &zvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.GraphVMID, &graphvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.DexVMID, &dexvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.KeyVMID, keyvm.NewDefaultFactory())
n.VMManager.RegisterFactory(ctx, constants.OracleVMID, &ovm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.RelayVMID, &rvm.Factory{})
n.VMManager.RegisterFactory(ctx, constants.IdentityVMID, &ivm.Factory{})
```
Note: KeyVM uses `NewDefaultFactory()` instead of `&Factory{}`.
## Consensus Engines
| Engine | Type | Used By |
|--------|------|---------|
| Snowman | Linear (block-based) | P, C, A, B, T, Z, G, D, K, O, R, I |
| Lux/DAG | DAG (vertex-based) | X |
| Quasar PQ-BFT | Hybrid DAG + BLS + Corona | Q |
## Related Skills
- `lux/lux-node.md` -- Core node that hosts all VMs
- `lux/lux-evm.md` -- C-Chain EVM with all precompile addresses
- `lux/lux-vm.md` -- VM interface definitions
- `lux/lux-consensus.md` -- Snowman, DAG, Quasar consensus
- `lux/lux-dex.md` -- D-Chain DEX details
- `lux/lux-fhe.md` -- FHE integration (Z-Chain, C-Chain)
- `lux/lux-threshold.md` -- T-Chain MPC details
- `lux/lux-bridge.md` -- B-Chain bridge operations
- `lux/lux-crypto.md` -- Cryptographic primitives
Last Updated: 2026-03-13
+364 -28
View File
@@ -1,46 +1,382 @@
---
title: "Lux CLI - Command-Line Interface"
description: "Lux CLI is the command-line tool for Lux subnet development, local network testing, and validator operations."
title: "Lux CLI"
description: "Developer Toolchain for Blockchain Development"
---
## Overview
Lux CLI is the **command-line tool** for Lux subnet development, local network testing, and validator operations. NEVER use `pkill luxd` — always use CLI for proper shutdown.
`github.com/luxfi/cli` is the command-line tool for Lux blockchain development, local network management, validator operations, key management, DEX trading, MPC wallets, and Kubernetes node deployment. Version 1.22.5, built on `spf13/cobra`.
## Quick reference
## Module
| Item | Value |
|------|-------|
| Field | Value |
|-------|-------|
| Module | `github.com/luxfi/cli` |
| Go | 1.26.1 |
| Version | 1.22.5 (from `cmd/root.go`) / 1.9.9 (from `VERSION` file) |
| Binary | `lux` |
| Config | `$HOME/.lux/cli.json` |
| Data | `$HOME/.lux/` (chains, keys, networks, snapshots, plugins, repos, logs, mpc) |
| Platforms | Linux, macOS |
| Build | `go build -o lux ./cmd/` |
| Build | `go build -o lux ./cmd/` or `make` |
## Commands
### Key Dependencies
```bash
# Network management
lux network create local-net # Create local network
lux network start # Start network
lux network stop # Stop network (proper shutdown!)
lux network status # Check status
lux network clean # Remove network data
| Package | Version | Purpose |
|---------|---------|---------|
| `luxfi/sdk` | v1.16.46 | Lux SDK (wallet, API, tx building) |
| `luxfi/node` | v1.23.21 | Node binary management |
| `luxfi/evm` | v0.8.35 | EVM/Subnet-EVM configuration |
| `luxfi/coreth` | v1.21.48 | C-Chain coreth dependency |
| `luxfi/netrunner` | v1.15.7 | Local network runner |
| `luxfi/genesis` | v1.6.1 | Genesis configuration |
| `luxfi/warp` | v1.18.5 | Cross-chain Warp messaging |
| `luxfi/crypto` | v1.17.42 | Cryptographic operations |
| `luxfi/keychain` | v1.0.2 | Key management |
| `luxfi/ledger` | v1.1.6 | Hardware wallet support |
| `luxfi/config` | v1.1.2 | Configuration management |
| `luxfi/erc20-go` | v0.2.1 | ERC20 token operations |
| `luxfi/lpm` | v1.9.4 | Lux Plugin Manager |
| `spf13/cobra` | v1.10.2 | CLI framework |
| `spf13/viper` | v1.21.0 | Configuration |
| `aws/aws-sdk-go-v2` | v1.41.1 | AWS cloud operations |
| `google.golang.org/api` | v0.256.0 | GCP operations |
| `k8s.io/client-go` | v0.35.1 | Kubernetes API |
# Subnet operations
lux subnet create my-subnet # Create subnet
lux subnet deploy my-subnet # Deploy to local network
lux subnet list # List subnets
## Command Tree
# Validator operations
lux validator list # List validators
lux validator add --node-id=... # Add validator
```
lux
chain Blockchain lifecycle (create/deploy/list/describe/delete/import)
create Create new blockchain configuration (L1/L2/L3)
deploy Deploy to local/testnet/mainnet
list List all configured blockchains
describe Show detailed blockchain information
delete Delete a blockchain configuration
import Import blocks from RLP file
upgrade Manage chain upgrades
generate Generate upgrade config
apply Apply upgrade
export Export upgrade config
import Import upgrade config
print Print upgrade config
validate Validate upgrade config
vm VM upgrade operations
# Key management (NEVER use EWOQ keys!)
lux key create my-key # Generate fresh key
lux key list # List keys
network Manage local network runtime
start Start local network (mainnet/testnet/devnet/dev)
stop Stop and save snapshot
status Show network status and endpoints
clean Stop and delete runtime data
monitor Real-time network monitor
snapshot Manage network snapshots
bootstrap Bootstrap network operations
describe Network describe with genesis info
send C-Chain send convenience
key Manage cryptographic keys
create Generate new key set from mnemonic (EC, BLS, Corona, ML-DSA)
list List all key sets
show Show key set details and addresses
delete Delete a key set
export Export key set (mnemonic or individual keys)
import Import key set from mnemonic
generate Batch generate key sets (-n count, -p prefix)
derive Derive keys from LUX_MNEMONIC env var
genesis Genesis key operations
export-signer Export signer key
lock Lock key (clear from memory), --all supported
unlock Unlock key for use
backend Manage key storage backends (list/set)
kchain K-Chain distributed key management (status/create/sign)
ring Ring signatures for anonymous signing
migrate Migrate plaintext to encrypted storage
validator Manage P-Chain validator balance
list List validators
getBalance Get validator balance
increaseBalance Increase validator balance
node Manage luxd nodes (local + Kubernetes)
link Symlink luxd binary to ~/.lux/bin/luxd
deploy Deploy/update via Helm chart
upgrade Rolling upgrade with zero downtime (partition-based)
status Show pod status, images, health
logs Stream logs from luxd pod
rollback Revert to previous StatefulSet revision
contract Smart contract operations
deploy Deploy contract
deploy-erc20 Deploy ERC20 token
init-validator-manager Initialize validator manager
dev Local development environment
start Start single-node dev mode (K=1 consensus)
stop Stop dev environment
dex Decentralized exchange operations
market Manage markets (list/info/create)
order Manage orders (place/cancel/list/history)
pool Manage liquidity pools (list/create/add/remove/swap)
perp Perpetual futures (markets/open/close/positions/pnl/funding)
account Trading account (balance/deposit/withdraw/history)
status DEX status and statistics
amm Uniswap-style AMM trading
mpc Multi-Party Computation (threshold signing)
node Manage MPC nodes
init Initialize t-of-n network (--threshold, --nodes)
start Start all nodes
stop Stop all nodes
status Check node status
clean Stop and remove data
list List networks
deploy Deploy MPC nodes to cloud (create/status/ssh)
backup Backup and restore
wallet Manage MPC wallets (list/create/show/export)
sign Threshold signing (request/approve/status)
gpu GPU acceleration management
status Check GPU availability (NTT, FHE, lattice ops)
primary Primary network operations
add-validator Add validator to primary network
describe Describe primary network
config CLI configuration
lint Lint configuration
metrics Metrics configuration
vm VM management
install Install VM binary
link Link VM to node
unlink Unlink VM
reload Reload VM plugins
status VM status
warp Cross-chain messaging (ICM/Interchain Messaging)
rpc Direct RPC calls
transfer RPC transfer
self CLI self-management (like nvm for node)
install Install specific CLI version
list List available versions
use Switch to specific version
link Link CLI binary
update Update CLI to latest version
snapshot Manage network snapshots
netrunner Network runner management
link Link netrunner binary
kms Key Management Service integration
link Unified binary linking
backend Hidden backend server commands
spawnServer Spawn backend gRPC server
(per-network backend commands: lux-mainnet-grpc, lux-testnet-grpc, etc.)
```
## Related Skills
## Network Types
- `lux/lux-node.md` - Node management
- `lux/lux-netrunner.md` - Network testing
| Type | Validators | Port | Flag |
|------|-----------|------|------|
| mainnet | 5 | 9630 | `--mainnet, -m` |
| testnet | 5 | 9640 | `--testnet, -t` |
| devnet | 5 | 9650 | `--devnet, -d` |
| dev | 1 (K=1) | varies | `--dev` |
| custom | varies | varies | `--custom` |
## Chain Architecture
| Type | Description |
|------|-------------|
| L1 (Sovereign) | Independent validator set, own tokenomics |
| L2 (Rollup) | Based on L1 sequencing (Lux, Ethereum, OP Stack) |
| L3 (App Chain) | Built on L2 for application-specific use |
Sequencing options: `lux` (100ms blocks, lowest cost), `ethereum` (12s blocks, highest security), `op` (OP Stack compatible).
## Key Management
Keys are stored in `~/.lux/keys/<name>/` with subdirectories per type:
| Type | Algorithm | Purpose |
|------|-----------|---------|
| EC | secp256k1 | Transaction signing, Ethereum compatibility |
| BLS | BLS12-381 | Consensus participation, aggregated signatures |
| Corona | Lattice-based ring | Ring signatures for privacy |
| ML-DSA | NIST Level 3 | Post-quantum digital signatures |
All key types derived from a single BIP39 mnemonic using HKDF. Keys can be locked/unlocked for session management. Backend system supports multiple storage providers (keychain, file, K-Chain distributed).
NEVER use EWOQ keys. Always generate fresh keys with `lux key create`.
## MPC Operations
Threshold signing network for distributed custody:
```bash
# Initialize 3-of-5 network
lux mpc node init --threshold 3 --nodes 5 --devnet
# Start / stop / status
lux mpc node start
lux mpc node status
lux mpc node stop
# Wallet operations
lux mpc wallet create --name "Treasury"
lux mpc wallet list
# Threshold signing
lux mpc sign request --wallet <id> --message "0x..."
lux mpc sign approve <request-id>
```
MPC port ranges: mainnet 9700-9799, testnet 9710-9809, devnet 9720-9819.
Data stored in `~/.lux/mpc/`.
## DEX Operations
Full decentralized exchange with CLOB, AMM, and perpetual futures:
```bash
# Market operations
lux dex market list
lux dex market info LUX/USDT
# Order placement
lux dex order place --market LUX/USDT --side buy --type limit --price 10.50 --amount 100
lux dex order list
lux dex order cancel <order-id>
# AMM liquidity
lux dex pool create --token0 LUX --token1 USDT --amount0 1000 --amount1 10000 --type constant-product --fee 30
lux dex pool swap --from LUX --to USDT --amount 100 --slippage 0.5
# Perpetual futures (up to 100x leverage)
lux dex perp open --market BTC-PERP --side long --size 0.1 --leverage 10
lux dex perp positions
lux dex perp close BTC-PERP --percent 50
# Account management
lux dex account balance
lux dex account deposit --token LUX --amount 1000
```
Pool types: constant-product (Uniswap V2), stableswap (Curve), concentrated (Uniswap V3).
## Kubernetes Node Management
The `node` command manages luxd nodes both locally and on Kubernetes:
```bash
# Local binary linking
lux node link --auto
# K8s deployment via Helm
lux node deploy --mainnet
lux node deploy --testnet --set image.tag=luxd-v1.23.15
# Zero-downtime rolling upgrade
lux node upgrade --mainnet --image ghcr.io/luxfi/node:v1.23.6
# Operations
lux node status --mainnet
lux node logs --mainnet luxd-0 -f
lux node rollback --mainnet
```
All K8s commands accept: `--mainnet`, `--testnet`, `--devnet`, `--namespace`, `--context`.
Uses canonical Helm chart at `~/work/lux/devops/charts/lux/` (configurable via `--chart-path` or `$LUX_CHART_PATH`).
## GPU Acceleration
```bash
lux gpu status
```
Reports availability for: NTT operations (Corona consensus), FHE operations (ThresholdVM), lattice cryptography. Builds with CGO for GPU support (`cgo_enabled.go` / `cgo_disabled.go`).
## Configuration
Config file: `$HOME/.lux/cli.json` (JSON format).
Environment variables:
- `LUX_NODE_PATH` -- path to luxd binary
- `LUX_NETRUNNER_PATH` -- path to netrunner binary
- `LUX_EVM_PATH` -- path to EVM binary
- `LUX_PLUGINS_DIR` -- plugins directory
- `LUX_NON_INTERACTIVE=1` -- disable prompts
- `CI=1` -- also disables prompts
- `LUX_MNEMONIC` -- mnemonic for key derivation
CLI flags: `--config`, `--log-level`, `--skip-update-check`, `--non-interactive`, `--verbose`, `--debug`, `--quiet`.
## Directory Structure
```
$HOME/.lux/
cli.json Configuration file
chains/ Chain configurations (genesis.json, sidecar.json per chain)
keys/ Cryptographic keys (ec/, bls/, rt/, mldsa/ per key name)
mpc/ MPC key shards
networks/ Network runtime data per type
snapshots/ Network snapshots
bin/ Linked binaries (luxd, etc.)
plugins/ VM plugins
repos/ Downloaded repos
logs/ CLI log files
mpc/ MPC network data
```
## Typical Workflows
### Local Development
```bash
lux key create validator1 # Generate keys
lux network start --devnet # Start 5-node network
lux chain create mychain # Create chain config
lux chain deploy mychain --devnet # Deploy to network
lux network status # Check endpoints
lux network stop # Save and stop
lux network clean # Wipe runtime (keeps chains)
```
### Contract Deployment
```bash
lux contract deploy-erc20 # Deploy ERC20
lux contract init-validator-manager # Initialize validator manager
```
### Chain Upgrades
```bash
lux chain upgrade generate # Generate upgrade config
lux chain upgrade validate # Validate config
lux chain upgrade apply # Apply to running chain
```
## Internal Architecture
- `cmd/root.go`: Root cobra command, `createApp` initializer, config loading, update checking
- `cmd/commands.go`: Command name constants
- `pkg/application/`: Core `Lux` application struct
- `pkg/config/`: Configuration management
- `pkg/prompts/`: Interactive/non-interactive prompt system
- `pkg/ux/`: User-facing logger (stdout for user output, stderr for logs)
- `pkg/lpmintegration/`: Lux Plugin Manager integration
- `pkg/mpc/`: MPC node management (NodeManager)
- `pkg/cobrautils/`: Cobra command utilities
- `pkg/utils/`: General utilities (metrics, tracking)
- `internal/migrations/`: Data migration system
The CLI uses `luxfi/log` for structured logging with configurable levels. Logging defaults to WARN display level; file logging at INFO level. Output goes to `$HOME/.lux/logs/`.
+501 -87
View File
@@ -1,131 +1,545 @@
---
title: "Lux Quasar - Post-Quantum Consensus Engine"
description: "Lux Quasar is the post-quantum consensus engine with Photonic Selection — a novel consensus protocol achieving sub-second 2-round finality with dual-certificate security (BLS aggregate + lattice po..."
title: "Lux Quasar -- Post-Quantum Consensus Engine"
description: "Lux Quasar -- Post-Quantum Consensus Engine"
---
## Overview
Lux Quasar is the **post-quantum consensus engine** with Photonic Selection — a novel consensus protocol achieving sub-second 2-round finality with dual-certificate security (BLS aggregate + lattice post-quantum). This is a SEPARATE repository from the node.
Lux Quasar is the consensus engine for the Lux network. It is a unified, leaderless, post-quantum protocol achieving sub-second 2-round finality with dual-certificate security (BLS12-381 aggregate signatures + Corona lattice-based threshold signatures). Quasar runs every chain in the Lux primary network -- Q, C, X, P -- and any dynamically registered subnet.
**This is NOT Snow, Snowball, or Avalanche BFT.** Quasar is an original consensus protocol.
**This is NOT Snow, Snowball, or Avalanche BFT.** Quasar is an original consensus protocol built from first principles around Photonic Selection.
## Quick reference
There are two code locations:
- **Library** (`github.com/luxfi/consensus`): The standalone consensus engine with protocol implementations, multi-language SDKs, and the Quasar protocol stack.
- **Node integration** (`github.com/luxfi/node/consensus`): The node-level wiring that binds Quasar to P-Chain finality events, the ZAP agentic bridge, and Corona coordinator lifecycle.
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/consensus` |
| Version | v1.22.0+ |
| Language | Go 1.26.1 + C + Rust FFI + Python (Cython) |
| Library module | `github.com/luxfi/consensus` |
| Node module | `github.com/luxfi/node` (subpackage `consensus/`) |
| Go version | 1.26.1 |
| Finality | 2-round, sub-second |
| Test coverage | 96%+ |
| Quantum security | 2^160 ops (lattice SVP) |
| BFT threshold | 69% (alpha >= 0.68) |
## Architecture
## Consensus Engines Comparison
### Sub-Protocols
| Engine | Type | Location | Purpose | Status |
|--------|------|----------|---------|--------|
| **Quasar** | Hybrid PQ | `protocol/quasar/` + `node/consensus/quasar/` | Primary consensus for all chains. Dual BLS+Corona signatures run in parallel. 2-round finality. | Production |
| **Nova** | Linear chain | `protocol/nova/` | Linear blockchain consensus mode. Wraps the Ray driver with Wave voting. Used for C-Chain and P-Chain style linear progression. | Production |
| **Wave** | Threshold voting | `protocol/wave/` | Core voting mechanism. Samples K peers, collects votes, checks alpha threshold, builds beta confidence. Supports FPC (Fast Probabilistic Consensus) for dynamic thresholds. | Production |
| **Ray** | Linear driver | `protocol/ray/` | Low-level engine that drives Wave voting for linearly-ordered items. Source/Sink pattern. Nova wraps this. | Production |
| **Prism** | DAG validation | `protocol/prism/` | Peer sampling (Cut interface) and DAG proposal/vote management. Provides the random peer selection primitive used by Wave and Nova. | Production |
| **Photon** | Committee selection | `protocol/photon/` | K-of-N committee selection via Emitter pattern. Luminance tracking weights selection probability by validator performance (10-1000 lux range). | Production |
| **ZAP** | Agentic consensus | `node/consensus/zap/` | Zero-copy Agent Protocol. Bridges W3C DID-based validator identity with Quasar threshold signatures. Query/Response/Vote model for AI agent consensus. | Production |
| **Chain engine** | Block engine | `engine/chain/` | Block-level consensus engine implementing the Engine interface. Handles bootstrapping, syncing, block verification, and vote recording for linear chains. | Production |
| **DAG engine** | Vertex engine | `engine/dag/` | DAG-level consensus engine. Handles vertex processing, bootstrapping, and parallel consensus for X-Chain style workloads. | Production |
| **PQ engine** | Post-quantum | `engine/pq/` | Post-quantum engine variant. Chain engine with `QuantumResistant=true` config enabling Corona certificates on every block. | Production |
| Protocol | Role |
|----------|------|
| **Photon** | K-of-N committee selection (3.03us) |
| **Emitter** | Committee coordination |
| **Wave** | Threshold voting (3.38us per vote round) |
| **Flare** | Certificate generation |
| **Horizon** | Frontier management |
| **Focus** | Confidence tracking |
| **Nova** | DAG-based classical finality |
| **Quasar** | Quantum finality (40.7ns Phase II) |
| **Nebula** | State sync |
| **QZMQ** | Post-quantum transport |
## Quasar Algorithm -- Detailed Steps
### Finality Flow
Quasar achieves hybrid quantum finality through parallel execution of classical and post-quantum signature paths. The full algorithm:
```
1. Transaction proposed
2. Photon selects committee (K-of-N)
3. Wave: threshold voting round
4. Round 1: BLS aggregate signature (fast finality)
5. Round 2: Lattice PQ certificate (quantum-safe finality)
6. Flare generates dual certificate
7. Transaction finalized (<1s)
### Phase 0: Photonic Selection (Committee Formation)
1. **Emitter** selects K validators from the active set using luminance-weighted random sampling via Prism's `Cut.Sample(K)`.
2. **Luminance** tracks each node's brightness (10-1000 lux). Successful votes increase brightness by 10% (cap 1000 lux). Failed votes dim by 10% (floor 10 lux). Higher lux = higher selection probability.
3. Fisher-Yates shuffle with `crypto/rand` ensures cryptographic uniformity in peer selection.
### Phase 1: Wave Voting (Classical Confidence Building)
1. A block/vertex is proposed. Wave performs repeated sampling rounds:
- Sample K peers via Prism Cut
- Request votes from selected peers (transmitted as Chits on the wire)
- Count yes/no votes
2. **Threshold check**: If yes votes >= alpha*K (default alpha=0.69, enforced >= 0.68), register preference. If no votes >= alpha*K, register rejection.
3. **Confidence accumulation**: Each consecutive same-preference round increments a counter. When counter >= beta (default 14 for mainnet), item is **decided**.
4. **FPC mode** (optional): Instead of fixed alpha, threshold theta is selected per-phase using a PRF over `[theta_min=0.5, theta_max=0.8]`, making the protocol more resistant to adaptive adversaries.
5. Classical finality typically completes in 600-700ms.
### Phase 2: Dual Certificate Generation (Quantum Finality)
Both paths execute **in parallel** immediately after classical decision:
**BLS Path (fast, classical):**
1. Each validator signs the finality message (blockID + height + timestamp, 48 bytes) with their BLS12-381 key share.
2. Signature shares are aggregated into a single 96-byte aggregate signature.
3. Verification: reconstruct aggregate public key from signer bitset, verify aggregate signature.
4. Requires 2/3+ validator weight.
**Corona Path (quantum-safe, 2-round):**
1. **Round 1**: Each participating validator generates commitments (D matrix + MACs) using their Corona key share. Broadcast `Round1Data` to all other signers.
2. **Round 2**: Each validator computes partial signatures using collected Round 1 data. Broadcast `Round2Data`.
3. **Finalize**: Any validator aggregates Round 2 data into a threshold signature. Verify against the group public key.
4. Requires t-of-n threshold (typically 2/3+1).
5. Corona adds approximately 200-300ms for quantum finality.
**Block is final ONLY when both certificates are valid:**
```go
type CertBundle struct {
BLSAgg []byte // 96B BLS aggregate signature
PQCert []byte // ~KB Corona threshold signature
}
isFinal := verifyBLS(blsAgg, quorum) && verifyPQ(pqCert, quorum)
```
### Dual Certificate Security
### Quantum Bundle Architecture (Async PQ Anchoring)
Every block requires TWO certificates to validate:
- **BLS12-381 aggregate signature** — fast classical security
- **Lattice post-quantum certificate** — quantum-safe assurance
For high-throughput scenarios, Quasar uses an async two-layer architecture:
Both must pass validation. This ensures security even if one cryptographic scheme is compromised.
```
BLS Layer: [B1]--[B2]--[B3]--[B4]--[B5]--[B6]--[B7]--[B8]--[B9]--...
| 500ms finality per block |
|_____________________________________|
|
Quantum Layer: [QB1: Merkle(B1-B6)]--------[QB2: Merkle(B7-B12)]
| 3-second interval, async Corona signing
```
### Chain Integration
- BLS blocks continue at 500ms pace (unblocked).
- Every 3 seconds (`QuantumCheckpointInterval`), a `QuantumBundle` is created containing a Merkle root of ~6 BLS block hashes.
- The bundle is signed asynchronously with Corona threshold (0.6s online signing, 2.5s total including offline prep).
- Bundles are chained via `PreviousHash` for integrity.
All chains use Quasar:
- **Q-Chain** — quantum-specific operations
- **C-Chain** — EVM-compatible contracts
- **X-Chain** — exchange/UTXO transactions
- **P-Chain** — platform/validator management
- **M-Chain** — MPC custody operations
### Epoch-Based Key Rotation
- **Epoch duration**: 10 minutes minimum (`MinEpochDuration`), 1 hour maximum (`MaxEpochDuration`).
- Corona keys rotate when the validator set changes, rate-limited to at most 1 rotation per 10 minutes.
- Historical epochs are retained (default 6) for cross-epoch signature verification.
- BLS and Corona validator sets are kept synchronized.
- `EpochManager` handles key generation, rotation, and pruning.
### Grouped Threshold Signing (10,000+ Validators)
For large validator sets, `GroupedEpochManager` splits validators into groups (default size 3):
1. Validators are assigned to groups via deterministic Fisher-Yates shuffle using epoch seed (VRF-based).
2. Each group generates its own Corona keys (2-of-3 threshold within group).
3. Groups sign in parallel -- constant signing time regardless of total validator count.
4. 2/3 of groups must produce valid signatures for consensus (`GroupQuorum`).
5. Signing time: ~243ms per group (n=3), independent of total validator count.
## Finality Guarantees
| Security Model | Guarantee |
|----------------|-----------|
| **Pre-quantum** | Attacker must corrupt >= 1/3 stake to fork. Alpha threshold 69% ensures BFT safety. |
| **Q-day (BLS broken)** | Attacker can forge BLS but NOT Corona lattice signatures. Block fails quantum check. Consensus halts rather than accepting unsafe fork. |
| **Post-quantum** | Security rests on lattice SVP hardness (2^160 operations). Corona threshold signatures remain secure. |
| **Attack window** | <= PQ round time (<=50ms on mainnet). |
Both BLS and Corona proofs are **REQUIRED** for Q-Chain validators. No fallback mode. The `Verify` method enforces strict dual-proof validation.
## Validator Selection and Identity
### Photonic Selection
Validators are selected via Photon's luminance-weighted sampling:
| Luminance Level | Lux Value | Analogy | Selection Weight |
|-----------------|-----------|---------|------------------|
| Minimum | 10 lux | Twilight | 0.1x base |
| Default/base | 100 lux | Office lighting | 1.0x base |
| Maximum | 1000 lux | Bright daylight | 10.0x base |
Performance-based weighting: successful consensus participation increases brightness, failed/absent rounds decrease it.
### Key Hierarchy
| Key Type | Usage |
|----------|-------|
| ed25519 | Node identity |
| BLS12-381 | Fast finality signatures |
| Lattice | Post-quantum finality |
| secp256k1 + Lamport | EVM wallet signing |
| secp256k1 + Dilithium | X-Chain UTXO signing |
| Layer | Key Type | Purpose | Storage |
|-------|----------|---------|---------|
| Node-ID | ed25519 | P2P transport authentication | `$HOME/.lux/node.key` |
| Validator-BLS | BLS12-381 | Fast finality votes (classical) | `$HOME/.lux/bls.key` |
| Validator-PQ | Corona (Ring-LWE) | Post-quantum threshold shares | `$HOME/.lux/rt.key` |
| Wallet (EVM) | secp256k1 or Lamport-XMSS | User transaction signatures | In wallet |
| Wallet (X-Chain) | secp256k1 or Dilithium | UTXO locking | In wallet |
## Multi-Language Implementations
The same `rt.key` registered on Q-Chain is reused by all chains -- no extra onboarding.
| Language | Performance | Usage |
### W3C DID Identity (ZAP Bridge)
ZAP provides decentralized identity for validators via W3C DIDs:
| DID Method | Format | Purpose |
|------------|--------|---------|
| `did:lux` | `did:lux:z<base58btc(nodeID)>` | Blockchain-anchored identity from NodeID |
| `did:key` | `did:key:z<base58btc(multicodec+pubkey)>` | Self-certifying identity from ML-DSA-65 public key |
| `did:web` | `did:web:domain:path` | DNS-based identity |
DIDs generate full W3C DID Documents with verification methods, authentication, and ZAP agent service endpoints.
## Post-Quantum Cryptography
### Corona Threshold Signatures
- **Basis**: Ring-LWE (Ring Learning With Errors)
- **Protocol**: Native 2-round threshold signing
- **Library**: `github.com/luxfi/corona` v0.2.0
- **Round 1**: Generate D matrix + MACs, broadcast commitments
- **Round 2**: Compute partial signatures using collected Round 1 data
- **Finalize**: Aggregate partial signatures into threshold signature
- **Verification**: `coronaThreshold.Verify(groupKey, message, signature)`
- **NTT acceleration**: GPU-accelerated Number Theoretic Transform (optional, via `ntt_c.go`)
### Verkle Witness Optimization
Quasar includes a Verkle witness system for hyper-efficient state verification:
- Uses `github.com/luxfi/crypto/ipa/banderwagon` for Verkle tree commitments
- IPA (Inner Product Argument) opening proofs for O(log n) verification
- When PQ finality is assumed, skip heavy BLS re-verification -- just verify Verkle commitment
- Compressed witnesses under 200 bytes for network transmission
- Batch verification for parallel witness checking
### Supported PQ Signature Types
| Type | Algorithm | Usage |
|------|-----------|-------|
| `PQSignatureTypeMLDSA65` | NIST FIPS 204 ML-DSA-65 | Per-validator signatures (1952-byte public key) |
| `PQSignatureTypeCorona` | Ring-LWE threshold | Quasar consensus threshold signatures |
| `PQSignatureTypeHybrid` | Classical + PQ combined | Full Quasar hybrid proofs |
## Configuration Parameters
### Consensus Parameters (`config.Parameters`)
| Parameter | Mainnet | Testnet | Local | X-Chain | Single Validator |
|-----------|---------|---------|-------|---------|-----------------|
| K (sample size) | 21 | 11 | 5 | 5 | 1 |
| Alpha (threshold) | 0.69 | 0.69 | 0.69 | 0.69 | 1.0 |
| Beta (confidence) | 14 | 8 | 4 | 4 | 1 |
| AlphaPreference | 15 | 8 | 4 | 4 | 1 |
| AlphaConfidence | 15 | 8 | 4 | 4 | 1 |
| BetaVirtuous | 15 | 8 | 4 | 4 | 1 |
| BetaRogue | 20 | 20 | 20 | 20 | 1 |
| BlockTime | 200ms | 100ms | 10ms | 1ms | 100ms |
| RoundTO | 400ms | 225ms | 45ms | 5ms | 200ms |
Alpha enforced >= 0.68 (69% BFT threshold). Validation rejects lower values.
### Quasar-Specific Config
| Parameter | Default | Description |
|-----------|---------|-------------|
| `QThreshold` | 3 | Minimum signers for Quasar certificate |
| `QuasarTimeout` | 30s | Timeout for Quasar finalization |
| `MinEpochDuration` | 10 min | Minimum time between Corona key rotations |
| `MaxEpochDuration` | 1 hour | Maximum time before forced key rotation |
| `QuantumCheckpointInterval` | 3s | Interval for async quantum bundle creation |
| `DefaultGroupSize` | 3 | Validators per Corona group |
| `DefaultGroupThreshold` | 2 | Threshold within each group (2-of-3) |
| `DefaultGroupQuorum` | 2/3 | Fraction of groups required |
| `DefaultHistoryLimit` | 6 | Old epochs retained for verification |
## Chain Integration
| Chain | Integration | Rule |
|-------|-------------|------|
| Q-Chain | Q-blocks as internal txs | All chains read Q-blocks for PQ finality |
| C-Chain | Every block has CertBundle | Invalid without both BLS + Corona certificates |
| X-Chain | Vertex metadata references Q-block | Epoch sealed by quantum certificate |
| P-Chain | Validator set changes trigger epoch rotation | BLS and Corona keys synchronized |
| M-Chain | MPC rounds reference Q-block height | Custody requires PQ proof |
| Any subnet | Auto-registered via `RegisterChain()` | Dynamically enters the event horizon |
## Sub-Protocol Architecture
```
consensus/
protocol/
photon/ Emitter + Luminance (committee selection)
wave/ Threshold voting engine + FPC
fpc/ Fast Probabilistic Consensus (dynamic thresholds)
prism/ Peer sampling (Cut interface) + DAG proposal
ray/ Linear consensus driver (Source/Sink pattern)
nova/ Linear chain consensus (wraps Ray)
flare/ Certificate generation for DAG
horizon/ Frontier management
focus/ Confidence tracking
nebula/ State sync protocol
field/ Nebula field operations
quasar/ Post-quantum finality engine
quasar.go Signer (BLS+Corona dual threshold)
core.go Quasar core (multi-chain block aggregator)
engine.go Engine interface implementation
epoch.go Epoch-based Corona key management
quantum_block.go Async quantum bundle production
grouped_threshold.go Grouped signing for 10K+ validators
bls.go DAG event horizon with BLS commitments
witness.go Verkle witness for hyper-efficient verification
types.go Block, BlockCert, Engine interface
config.go QThreshold, QuasarTimeout
metrics.go Prometheus metrics
engine/
chain/ Linear blockchain engine
dag/ DAG consensus engine
pq/ Post-quantum engine variant
core/
dag/ DAG data structures (flare, horizon)
choices/ Decision types
types/ Block, Vote, Certificate, Config
config/ Parameters, presets (Mainnet, Testnet, Local, XChain)
pkg/wire/ Wire protocol (candidate, credentials, sequencer)
node/consensus/
acceptor.go Acceptor callback interface
engine/chain/ Vote message types (wire: Chits)
quasar/ Node-level Quasar integration
quasar.go Binds P-Chain + Q-Chain into hybrid finality
types.go Signature interfaces, CoronaCoordinator
zap/ ZAP agentic consensus bridge
bridge.go Query/Response/Vote consensus
types.go QueryState, FinalityProof, StakeRegistry
did.go W3C DID implementation (did:lux, did:key, did:web)
```
## Key Dependencies (from go.mod)
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/crypto` | v1.17.40 | BLS12-381, threshold signatures, IPA/banderwagon |
| `github.com/luxfi/corona` | v0.2.0 | Ring-LWE post-quantum threshold signatures |
| `github.com/luxfi/database` | v1.17.42 | State storage |
| `github.com/luxfi/ids` | v1.2.9 | Block/node/chain identifiers |
| `github.com/luxfi/p2p` | v1.18.9 | Peer-to-peer networking |
| `github.com/luxfi/warp` | v1.18.5 | Cross-chain messaging |
| `github.com/luxfi/lattice/v7` | v7.0.0 | Post-quantum lattice cryptography |
| `github.com/luxfi/zap` | v0.2.0 | Zero-copy agent protocol |
| `github.com/luxfi/validators` | v1.0.0 | Validator set management |
| `github.com/luxfi/runtime` | v1.0.0 | Chain runtime context |
| `github.com/luxfi/accel` | v1.0.1 | Hardware acceleration |
| `github.com/luxfi/math` | v1.2.3 | Math utilities |
| `github.com/luxfi/metric` | v1.5.0 | Prometheus metrics |
| `github.com/luxfi/log` | v1.4.1 | Structured logging |
| `github.com/luxfi/version` | v1.0.1 | Version management |
| `github.com/luxfi/sampler` | v1.0.0 | Random sampling |
| `github.com/luxfi/vm` | v1.0.27 | Virtual machine interface |
| `github.com/luxfi/geth` | v1.16.73 | EVM compatibility layer |
| `github.com/luxfi/zapdb/v4` | v4.9.1 | ZAP database |
| `github.com/cloudflare/circl` | v1.6.3 | Post-quantum crypto primitives |
| `github.com/supranational/blst` | v0.3.16 | BLS signature performance |
## Performance Benchmarks (Apple M1 Max)
### Consensus Operations
| Component | Operation | Latency | Memory | Allocations |
|-----------|-----------|---------|--------|-------------|
| Wave | Vote Round | 3.38us | 2.3KB | 8 allocs |
| Photon Emitter | K-of-N Selection | 3.03us | 3.0KB | 2 allocs |
| Luminance | Brightness Update | 72ns | 0B | 0 allocs |
| Quasar | Phase I (propose) | 0.33ns | 0B | 0 allocs |
| Quasar | Phase II (commit) | 40.7ns | 0B | 0 allocs |
| AI Consensus | Model Inference | 1.5us | - | - |
| AI Consensus | Consensus Vote | 529ns | - | - |
| Full Consensus | End-to-end | 200-300ms | - | - |
### Corona Signing Performance
| Group Size | Signing Time | Notes |
|------------|-------------|-------|
| n=3 | 243ms | Default group size |
| n=10 | 1.1s | Medium groups |
| n=21 | 3.4s | Full mainnet committee |
| n=100 | 53s | Too slow -- use grouped signing |
### Network Finality
| Network | Validators | Finality | Block Time |
|---------|-----------|----------|------------|
| Mainnet | 21 | 9.63s | 200ms |
| Testnet | 11 | 6.3s | 100ms |
| Local | 5 | 3.69s | 10ms |
| X-Chain | 5 | 5ms | 1ms |
## Multi-Language SDKs
| Language | Performance | Build |
|----------|-------------|-------|
| C | 9M+ blocks/sec | Core engine |
| Rust FFI | High | Integration layer |
| Python (Cython) | 6.7M blocks/sec | SDK/tooling |
| Go (CGO) | Primary | Node integration |
| Go | Primary | `go get github.com/luxfi/consensus` |
| C | 9M+ blocks/sec | `cd consensus/c && make && sudo make install` |
| Rust FFI | High | `lux-consensus = "1.22.0"` in Cargo.toml |
| Python (Cython) | 6.7M blocks/sec | `pip install lux-consensus` |
## Key Dependencies
100% test parity across all 4 implementations. 15 comprehensive test categories.
```
github.com/luxfi/crypto — BLS, secp256k1, certificates
github.com/luxfi/database — State storage
github.com/luxfi/ids — Identifiers
github.com/luxfi/warp — Cross-chain messaging
github.com/luxfi/lattice/v7 — Post-quantum lattice crypto
github.com/luxfi/corona — Ring signatures
github.com/luxfi/zap — Zero-copy protocol
## ZAP Agentic Consensus
ZAP (Zero-copy Agent Protocol) provides consensus for AI agent operations:
### Protocol Flow
1. **SubmitQuery**: Agent submits a query with content and DID identity.
2. **SubmitResponse**: Other agents provide responses with DIDs.
3. **Vote**: Validators vote for responses (one vote per validator, enforced by DID).
4. **Consensus check**: When total votes >= `MinVotes` and a response has `>= ConsensusThreshold` fraction, the query is finalized.
5. **Finality proof**: Signed with Quasar hybrid signatures (BLS + Corona).
### ZAP Bridge Config
| Parameter | Default | Description |
|-----------|---------|-------------|
| `ConsensusThreshold` | 0.5 | Fraction of votes needed |
| `MinResponses` | 1 | Minimum responses before checking |
| `MinVotes` | 3 | Minimum votes before checking |
| `EnablePQCrypto` | true | Enable ML-DSA-65 post-quantum signatures |
### Stake Registry
ZAP includes a `StakeRegistry` interface for stake-weighted voting:
- `GetStake(did)` / `SetStake(did, amount)` / `TotalStake()`
- `HasSufficientStake(did, minimum)` / `StakeWeight(did)` (fraction of total)
## Security Model
### Adversary Model
| Scenario | Security | Mechanism |
|----------|----------|-----------|
| Classical adversary (< 1/3 stake) | Safe | BFT alpha=0.69 threshold prevents fork |
| Classical adversary (>= 1/3 stake) | Unsafe | Same as any BFT system |
| Quantum adversary (BLS breakable) | Safe | Corona lattice certificates prevent acceptance |
| Quantum adversary (both breakable) | Unsafe | Requires both lattice + BLS to be broken simultaneously |
| Adaptive adversary | Safe | FPC dynamic thresholds prevent threshold manipulation |
### QZMQ Transport Security
All consensus messages use QZMQ (Quantum-Secure ZeroMQ):
- **Dilithium signatures** (post-quantum message authentication)
- **Kyber encryption** (quantum-resistant key encapsulation)
- Forward secrecy via ephemeral keys
- Replay protection via session IDs
## Account-Level PQ Options
### EVM (C-Chain)
- Lamport-XMSS multisig contracts
- Gas: ~300K for `VERIFY_LAMPORT`
- EIP-4337 Account Abstraction wrapper available
### X-Chain
- `LatticeOutput` type with PQ public key
- Spend verifies single Corona signature (~1.8KB)
- CLI: `lux-wallet generate --pq`
## Usage Examples
### Library: Single-Import API
```go
import "github.com/luxfi/consensus"
// Create chain with default config
chain := consensus.NewChain(consensus.DefaultConfig())
if err := chain.Start(ctx); err != nil {
return err
}
defer chain.Stop()
// Add a block
block := consensus.NewBlock(id, parentID, 1, payload)
if err := chain.Add(ctx, block); err != nil {
return err
}
```
## Performance Benchmarks
### Library: Quasar Engine
| Operation | Latency |
|-----------|---------|
| Vote round | 3.38us |
| K-of-N selection | 3.03us |
| Quasar Phase II | 40.7ns |
| End-to-end finality | <1s |
```go
import "github.com/luxfi/consensus/protocol/quasar"
## Tuning Parameters
cfg := quasar.Config{QThreshold: 3, QuasarTimeout: 30}
engine, err := quasar.NewEngine(cfg)
if err != nil {
return err
}
engine.Start(ctx)
| Parameter | Description |
|-----------|-------------|
| Committee size (K) | Validators in selection pool |
| Threshold (T) | Required signatures for consensus |
| Vote rounds | Rounds before commitment |
| Certificate mode | `dual` (BLS+Lattice), `classical` (BLS only) |
// Submit blocks
engine.Submit(block)
// Listen for finalized blocks
for block := range engine.Finalized() {
log.Printf("Finalized: height=%d cert=%v", block.Height, block.Cert.Verify(validators))
}
```
### Node: Quasar with Hybrid Finality
```go
import "github.com/luxfi/node/consensus/quasar"
q, err := quasar.NewQuasar(logger, threshold, quorumNum, quorumDen)
q.ConnectPChain(pChainProvider)
q.ConnectQuantumFallback(quantumSigner)
q.InitializeCorona(validatorNodeIDs)
q.Start(ctx)
// Listen for hybrid finality events
for finality := range q.Subscribe() {
log.Printf("Hybrid finality: block=%s BLS=%dms RT=%dms",
finality.BlockID, finality.BLSLatency.Milliseconds(), finality.CoronaLatency.Milliseconds())
}
```
### Node: ZAP Bridge
```go
import "github.com/luxfi/node/consensus/zap"
bridge := zap.NewBridge(logger, zap.DefaultBridgeConfig())
bridge.Initialize(coronaCoordinator)
bridge.RegisterValidator(nodeID, zap.DIDFromNodeID(nodeID))
bridge.SubmitQuery(ctx, queryID, content, submitterNodeID)
bridge.SubmitResponse(ctx, queryID, responseID, responseContent, responderNodeID)
bridge.Vote(ctx, queryID, responseID, voterNodeID)
result, _ := bridge.GetResult(queryID)
```
## Testing
```bash
# All tests
go test ./...
# With coverage
go test -cover ./...
# Benchmarks
go test -bench=. ./...
# Quasar-specific tests
go test ./protocol/quasar/...
# ZAP bridge tests
go test ./consensus/zap/...
```
## Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| Slow finality | Low peer count | Ensure sufficient connected peers |
| Consensus stall | Network partition | Check P2P connectivity |
| Certificate validation fail | Key mismatch | Verify BLS and lattice keys registered |
| Phase II timeout | Lattice computation slow | Check hardware requirements |
| Slow finality | Low peer count | Ensure sufficient connected peers for K sampling |
| Consensus stall | Network partition | Check P2P connectivity, verify alpha threshold reachable |
| Certificate validation fail | Key mismatch | Verify BLS and Corona keys registered for current epoch |
| Phase II timeout | Corona computation slow | Check hardware; consider grouped signing for large sets |
| Epoch rotation rejected | Rate limited | Wait for MinEpochDuration (10 min) between rotations |
| Grouped signing failure | Insufficient group quorum | Ensure 2/3 of groups have threshold signers available |
| DID validation error | Malformed DID | Verify format: `did:method:id` with method in {lux,key,web} |
| Alpha validation error | Threshold too low | Alpha must be >= 0.68 (69% BFT threshold) |
## Related Skills
- `lux/lux-node.md` — Node that imports and runs Quasar
- `lux/lux-p2p.md` — Networking layer
- `lux/lux-crypto.md` — Cryptographic primitives (BLS, lattice)
- `lux/lux-sdk.md` — SDK for querying consensus state
- `lux/lux-node.md` -- Node that imports and runs Quasar
- `lux/lux-p2p.md` -- Networking layer for vote/chit propagation
- `lux/lux-crypto.md` -- BLS12-381, threshold signatures, IPA/banderwagon
- `lux/lux-corona.md` -- Ring-LWE post-quantum threshold signatures
- `lux/lux-lattice.md` -- Lattice cryptography (v7)
- `lux/lux-sdk.md` -- SDK for querying consensus state
- `lux/lux-warp.md` -- Cross-chain messaging
+247 -59
View File
@@ -1,101 +1,289 @@
---
title: "Lux Crypto - Cryptographic Primitives"
description: "Lux Crypto provides the cryptographic primitives for the Lux Network — BLS threshold signatures, SLIP-10 HD wallets, secp256k1, KZG commitments, and post-quantum via gnark-crypto."
title: "Lux Crypto"
description: "Cryptographic Primitives"
---
## Overview
Lux Crypto provides the **cryptographic primitives** for the Lux Network — BLS threshold signatures, SLIP-10 HD wallets, secp256k1, KZG commitments, and post-quantum via gnark-crypto.
Lux Crypto provides the **complete cryptographic foundation** for the Lux Network. It covers classical (secp256k1, ECDSA, BLS12-381), post-quantum (ML-DSA, SLH-DSA, ML-KEM, Lamport), hybrid key encapsulation, ring signatures, threshold signature schemes (FROST, CMP, BLS, Corona), MPC protocols, HPKE, ECIES, KZG polynomial commitments, and EVM crypto precompiles. All post-quantum algorithms use Cloudflare CIRCL under the hood.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/crypto` |
| Go | 1.26.1 |
## Packages
| Package | Purpose |
|---------|---------|
| `bls/` | BLS12-381 threshold signatures (via `blst` v0.3.16) |
| `secp256k1/` | Ethereum-compatible ECDSA |
| `certificate.go` | TLS certificate handling |
## Key Dependencies
```
github.com/supranational/[email protected] — BLS signatures
github.com/cloudflare/[email protected] — PQ crypto (CIRCL)
github.com/consensys/[email protected] — ZK-friendly crypto
ethereum/c-kzg-4844/v2 — KZG polynomial commitments
filippo.io/[email protected] — File encryption
ProjectZKM/Ziren — ZK runtime
```
| Dependency | Version | Purpose |
|------------|---------|---------|
| `github.com/supranational/blst` | v0.3.16 | BLS12-381 (CGO, fast path) |
| `github.com/cloudflare/circl` | v1.6.3 | PQ crypto: ML-DSA, SLH-DSA, ML-KEM, BLS (non-CGO), HPKE |
| `github.com/consensys/gnark-crypto` | v0.19.2 | ZK-friendly crypto, BN256 |
| `github.com/crate-crypto/go-eth-kzg` | v1.5.0 | KZG polynomial commitments (Go) |
| `github.com/ethereum/c-kzg-4844/v2` | v2.1.5 | KZG polynomial commitments (C) |
| `filippo.io/age` | v1.3.1 | File encryption (age format) |
| `github.com/ProjectZKM/Ziren` | latest | ZK runtime (Keccak) |
| `github.com/zeebo/blake3` | v0.2.4 | BLAKE3 hashing |
| `github.com/luxfi/ids` | v1.2.9 | ID types |
| `github.com/jedisct1/go-minisign` | latest | Minisign verification |
| `github.com/leanovate/gopter` | v0.2.11 | Property-based testing |
## API
## Package Map
### Classical Signatures
| Package | Import | Purpose |
|---------|--------|---------|
| `bls/` | `github.com/luxfi/crypto/bls` | BLS12-381 signatures. Dual backend: CGO (blst, `bls_c.go`) and pure-Go (circl, `bls.go`). Types: `SecretKey`, `PublicKey`, `Signature`, `AggregatePublicKey`, `AggregateSignature`. Functions: `NewSecretKey()`, `SecretKeyFromSeed()`, `SecretKeyFromBytes()`, `SecretKeyToBytes()`, `Sign()`, `Verify()`. Domain separation: `BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_` (signing), `BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_` (proof of possession). |
| `bls/signer/` | `.../bls/signer` | BLS signer interface |
| `bls/blstest/` | `.../bls/blstest` | BLS test helpers |
| `bls12381/` | `.../bls12381` | BLS12-381 pairing engine -- dual backend: blst (CGO) and gnark-crypto (pure Go) |
| `secp256k1/` | `.../secp256k1` | Ethereum-compatible ECDSA: key generation, signing, recovery, address derivation. Includes CGO (`secp256k1_c.go`, `scalar_mult_c.go`) and pure-Go (`secp256k1.go`) paths. Recovery cache for performance. |
| `secp256r1/` | `.../secp256r1` | P-256 (NIST) curve verifier |
| `bn256/` | `.../bn256` | BN256 pairing: fast (gnark) and slow (cloudflare/google) backends |
| `signer/` | `.../signer` | Generic signer interface with test suite |
| `signify/` | `.../signify` | Minisign-compatible signature verification |
### Post-Quantum Signatures (FIPS 204/205)
| Package | Import | Modes | Sizes |
|---------|--------|-------|-------|
| `mldsa/` | `.../mldsa` | **ML-DSA-44** (128-bit, NIST L2), **ML-DSA-65** (192-bit, NIST L3), **ML-DSA-87** (256-bit, NIST L5) | PK: 1312/1952/2592, SK: 2560/4032/4896, Sig: 2420/3309/4627 bytes |
| `slhdsa/` | `.../slhdsa` | **SLH-DSA** (FIPS 205, SPHINCS+): 12 modes -- SHA2/SHAKE x 128s/128f/192s/192f/256s/256f | PK: 32/48/64, Sig: 7856-49856 bytes (small vs fast variants) |
ML-DSA API: `GenerateKey(rand, mode)`, `PrivateKey.Sign(rand, msg, opts)`, `PublicKey.Verify(msg, sig, opts)`, `PublicKey.VerifySignature(msg, sig)`, `PrivateKeyFromBytes(mode, data)`, `PublicKeyFromBytes(data, mode)`.
SLH-DSA API: identical interface. Deterministic signing via `slhdsa.SignDeterministic`. 12 modes cover SHA2/SHAKE at 128/192/256-bit security with small (s) or fast (f) signing.
### Post-Quantum Key Encapsulation (FIPS 203)
| Package | Import | Purpose |
|---------|--------|---------|
| `mlkem/` | `.../mlkem` | **ML-KEM** (FIPS 203): ML-KEM-512 (128-bit), ML-KEM-768 (192-bit), ML-KEM-1024 (256-bit). Full encapsulate/decapsulate with CGO optimization. PK: 800/1184/1568, SK: 1632/2400/3168, CT: 768/1088/1568 bytes. |
| `kem/` | `.../kem` | KEM factory: `GetKEM(id)` returns implementation. IDs: `MLKEM768`, `MLKEM1024`, `X25519`, `HybridKEM` (x25519+mlkem768). Interface: `GenerateKeyPair()`, `Encapsulate(pk)`, `Decapsulate(sk, ct)`. |
| `kem/hybrid` | `.../kem` | Hybrid KEM combining X25519 + ML-KEM-768 for PQ-safe key exchange |
### Hash-Based Signatures
| Package | Import | Purpose |
|---------|--------|---------|
| `lamport/` | `.../lamport` | Lamport one-time signatures. Hash functions: SHA256, SHA512, SHA3-256, SHA3-512. `GenerateKey(rng, hashFunc)`, `PrivateKey.Public()`, `Sign()`, `Verify()`. SHA256: PK 16KB, Sig 8KB. |
### Ring Signatures
| Package | Import | Schemes |
|---------|--------|---------|
| `ring/` | `.../ring` | **LSAG** (Linkable Spontaneous Anonymous Group, secp256k1), **LatticeLSAG** (post-quantum, Module-LWE), **DualRing** (efficient ring construction). Key image support for double-spend prevention. Used in Q-Chain for private transactions. |
### Threshold Signatures
| Package | Import | Purpose |
|---------|--------|---------|
| `threshold/` | `.../threshold` | Unified interface for 4 threshold schemes. Interface: `Scheme`, `DKG`, `TrustedDealer`, `Signer`, `Aggregator`, `Verifier`, `KeyRefresh`, `Resharing`. |
| `threshold/bls/` | `.../threshold/bls` | BLS threshold signatures (non-interactive aggregation) |
Threshold schemes:
| SchemeID | Name | Type | PQ-Safe | Non-Interactive |
|----------|------|------|---------|-----------------|
| `SchemeFROST` | FROST | Schnorr threshold (Ed25519-compatible) | No | No |
| `SchemeCMP` | CMP/CGGMP21 | Threshold ECDSA | No | No |
| `SchemeBLS` | BLS | BLS threshold | No | Yes |
| `SchemeCorona` | Corona | Lattice-based threshold | Yes | No |
DKG protocol: up to 3 rounds (`Round1` -> broadcast -> `Round2` -> broadcast -> `Round3` -> `KeyShare`). Also supports `TrustedDealer` for centralized setup.
### MPC (Multi-Party Computation)
| Package | Import | Purpose |
|---------|--------|---------|
| `mpc/` | `.../mpc` | Per-account MPC management. Protocols: `ProtocolGG18`, `ProtocolGG20`, `ProtocolCMP`. `Manager` handles account-to-MPC mapping. Shamir secret sharing with configurable threshold/parties. |
| `cggmp21/` | `.../cggmp21` | CGGMP21 threshold ECDSA with Paillier encryption |
### Aggregated Signatures
| Package | Import | Purpose |
|---------|--------|---------|
| `aggregated/` | `.../aggregated` | Signature aggregation managers: multi-signature aggregation for consensus |
### Encryption
| Package | Import | Purpose |
|---------|--------|---------|
| `ecies/` | `.../ecies` | Elliptic Curve Integrated Encryption Scheme (ECIES) -- asymmetric encryption |
| `hpke/` | `.../hpke` | Hybrid Public Key Encryption (RFC 9180). KEMs: P-256/P-384/P-521/X25519. KDFs: HKDF-SHA256/384/512. AEADs: AES-128-GCM/AES-256-GCM/ChaCha20-Poly1305. |
| `aead/` | `.../aead` | Authenticated Encryption with Associated Data utilities |
| `encryption/` | `.../encryption` | File encryption using `filippo.io/age` |
### Hashing
| Package | Import | Purpose |
|---------|--------|---------|
| `hash/` | `.../hash` | Unified hash interface: `Hasher`, `SHA256`, `SHA256File()`. Mock hasher for testing. |
| `hash/blake3/` | `.../hash/blake3` | BLAKE3 hashing |
| `hash/poseidon2/` | `.../hash/poseidon2` | Poseidon2 ZK-friendly hash |
| `hash/consistent/` | `.../hash/consistent` | Consistent hashing (ring-based distribution) |
| `hashing/` | `.../hashing` | Legacy hashing interface |
| `blake2b/` | `.../blake2b` | BLAKE2b with AVX2 acceleration |
| `keccak.go` | root | Keccak-256 (Ethereum standard) |
| `keccak_ziren.go` | root | Keccak via Ziren ZK runtime |
| `kdf/` | `.../kdf` | Key Derivation Function schedule |
### Polynomial Commitments & ZK
| Package | Import | Purpose |
|---------|--------|---------|
| `kzg4844/` | `.../kzg4844` | KZG polynomial commitments for EIP-4844 blobs. Dual backend: C (ckzg) and Go (gokzg). `BlobToCommitment()`, `ComputeProof()`, `VerifyProof()`. |
| `ipa/` | `.../ipa` | Inner Product Argument (IPA) multiproofs for Verkle trees. Bandersnatch/Banderwagon curves. |
### EVM Precompiles
| Package | Import | Purpose |
|---------|--------|---------|
| `precompile/` | `.../precompile` | Post-quantum EVM precompiles: BLS verification, Lamport verification, SHAKE hashing. Interface: `Precompile` with `Run(input)`. Exported via `precompile/export.go`. |
### Encoding & Utilities
| Package | Import | Purpose |
|---------|--------|---------|
| `cb58/` | `.../cb58` | CB58 encoding (Base58Check, used for Lux addresses) |
| `common/` | `.../common` | `Address` (20 bytes), `Hash` (32 bytes), hex utilities |
| `rlp/` | `.../rlp` | RLP encoding for EVM compatibility |
| `address/` | `.../address` | Address formatting and conversion |
| `bitutil/` | `.../bitutil` | Bit manipulation utilities |
| `certificate.go` | root | TLS certificate handling |
| `random.go` | root | Cryptographic random number generation |
| `gpu/` | `.../gpu` | GPU acceleration stubs |
| `cgo/` | `.../cgo` | CGO linking configuration for C crypto libs |
### Foreign Language Bindings
| Binding | Path | Purpose |
|---------|------|---------|
| C ABI | `bindings/cabi/` | C foreign function interface |
| Python | `bindings/python/` | Python bindings |
| Rust | `bindings/rust/` | Rust FFI bindings |
| TypeScript | `bindings/typescript/` | TypeScript/WASM bindings |
### Data Availability
| Package | Import | Purpose |
|---------|--------|---------|
| `da/` | `.../da` | Data availability layer types |
### Verkle Trees
| Package | Import | Purpose |
|---------|--------|---------|
| `verkle/` | `.../verkle` | Verkle tree cryptographic primitives |
## Key Hierarchy (Lux Consensus)
| Key Type | Package | Usage |
|----------|---------|-------|
| ed25519 | (stdlib) | Node identity |
| BLS12-381 | `bls/` | Fast finality signatures (Quasar) |
| Lattice (ML-DSA) | `mldsa/` | Post-quantum finality certificates |
| secp256k1 + Lamport | `secp256k1/`, `lamport/` | EVM wallet signing (PQ-safe) |
| secp256k1 + ML-DSA | `secp256k1/`, `mldsa/` | X-Chain UTXO signing (PQ-safe) |
| ML-KEM + X25519 | `kem/` | PQ-safe key exchange (hybrid) |
## API Examples
### BLS Signatures
```go
import "github.com/luxfi/crypto/bls"
// Generate key pair
sk, _ := bls.NewSecretKey()
pk := sk.PublicKey()
// Sign and verify
msg := []byte("transaction data")
sig := bls.Sign(sk, msg)
valid := bls.Verify(pk, msg, sig)
// Threshold signatures (t-of-n)
shares := bls.Split(sk, threshold, total)
partialSigs := make([]bls.Signature, threshold)
for i := 0; i < threshold; i++ {
partialSigs[i] = bls.Sign(shares[i], msg)
}
combinedSig := bls.Combine(partialSigs)
```
### HD Key Derivation (SLIP-10)
### ML-DSA (Post-Quantum Signatures)
```go
import "github.com/luxfi/crypto/keychain"
import (
"crypto/rand"
"github.com/luxfi/crypto/mldsa"
)
kc, _ := keychain.NewFromSeed(seed)
child, _ := kc.Derive(keychain.DerivationPath{
44, // purpose
9005, // Lux coin type
0, // account
0, // change
0, // index
})
// NIST Level 5 (256-bit security)
sk, _ := mldsa.GenerateKey(rand.Reader, mldsa.MLDSA87)
sig, _ := sk.Sign(rand.Reader, message, nil)
valid := sk.PublicKey.VerifySignature(message, sig)
// Serialize/deserialize
skBytes := sk.Bytes()
sk2, _ := mldsa.PrivateKeyFromBytes(mldsa.MLDSA87, skBytes)
```
### secp256k1
### SLH-DSA (Stateless Hash-Based Signatures)
```go
import "github.com/luxfi/crypto/slhdsa"
// 256-bit security, small signatures
sk, _ := slhdsa.GenerateKey(rand.Reader, slhdsa.SHA2_256s)
sig, _ := sk.Sign(rand.Reader, message, nil) // 29792 bytes
valid := sk.PublicKey.VerifySignature(message, sig)
```
### ML-KEM (Post-Quantum Key Exchange)
```go
import "github.com/luxfi/crypto/kem"
k, _ := kem.GetKEM(kem.HybridKEM) // X25519 + ML-KEM-768
pk, sk, _ := k.GenerateKeyPair()
ct, sharedSecret, _ := k.Encapsulate(pk)
recovered, _ := k.Decapsulate(sk, ct)
// sharedSecret == recovered
```
### Ring Signatures (Q-Chain Privacy)
```go
import "github.com/luxfi/crypto/ring"
// LSAG: linkable anonymous group signature
// LatticeLSAG: post-quantum ring signature
// Provides sender anonymity with double-spend prevention via key images
```
### Threshold Signatures
```go
import "github.com/luxfi/crypto/threshold"
scheme, _ := threshold.GetScheme(threshold.SchemeFROST)
dkg := scheme.NewDKG(threshold.DKGConfig{
Threshold: 2,
TotalParties: 5,
PartyIndex: 0,
})
// Round1 -> broadcast -> Round2 -> broadcast -> Round3 -> KeyShare
```
### secp256k1 (EVM)
```go
import "github.com/luxfi/crypto/secp256k1"
pk, _ := secp256k1.NewPrivateKey()
addr := pk.EthAddress() // 0x...
sig, _ := pk.Sign(hash)
pk, _ := secp256k1.GenerateKey()
sig, _ := secp256k1.Sign(hash, pk)
pubkey, _ := secp256k1.RecoverPubkey(hash, sig)
```
## Key Hierarchy (Quasar Consensus)
| Key Type | Usage |
|----------|-------|
| ed25519 | Node identity |
| BLS12-381 | Fast finality signatures |
| Lattice | Post-quantum finality |
| secp256k1 + Lamport | EVM wallet signing |
| secp256k1 + ML-DSA | X-Chain UTXO signing |
## Related Skills
- `lux/lux-consensus.md` — Uses BLS for Quasar finality
- `lux/lux-fhe.md` — Fully homomorphic encryption
- `lux/lux-lattice.md` — Post-quantum lattice crypto
- `lux/lux-wallet.md` — HD wallet implementation
- `lux/lux-consensus.md` -- Uses BLS/ML-DSA for Quasar finality
- `lux/lux-fhe.md` -- Fully homomorphic encryption
- `lux/lux-lattice.md` -- Post-quantum lattice HE
- `lux/lux-wallet.md` -- HD wallet implementation
- `lux/lux-sdk.md` -- SDK that consumes this module
+259 -11
View File
@@ -1,18 +1,266 @@
---
title: "Lux Storage Layer - Database & Caching"
description: "Lux storage layer covering database abstractions, ZapDB (BadgerDB-based KV store), caching, compression, and filesystem abstractions."
title: "Lux Database"
description: "Blockchain Storage Abstraction Layer"
---
## Overview
Lux storage layer covering database abstractions, ZapDB (BadgerDB-based KV store), caching, compression, and filesystem abstractions.
Lux Database (`github.com/luxfi/database`) is the Go storage abstraction layer for the Lux blockchain. It defines a unified key-value `Database` interface modeled after Ethereum's database API (enabling direct use of Geth/EVM code) and provides multiple pluggable backends: ZapDB (BadgerDB-based, default), PebbleDB (CockroachDB), LevelDB (Google), and in-memory. Also includes database wrappers for encryption, corruption detection, hooking, prefixing, versioning, metering, and linked-list storage. Used by `github.com/luxfi/node` for all persistent state.
## Components
## Repository
| Component | Path | Purpose |
|-----------|------|---------|
| database/ | ``github.com/luxfi/database`` | Storage abstraction |
| zapdb/ | ``github.com/luxfi/zapdb`` | BadgerDB KV store |
| cache/ | ``github.com/luxfi/cache`` | In-memory + distributed cache |
| compress/ | ``github.com/luxfi/compress`` | Data compression |
| filesystem/ | ``github.com/luxfi/filesystem`` | VFS abstraction |
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/database` |
| Local | `~/work/lux/database/` |
| Go | 1.26.1 |
| License | See LICENSE |
| Build | `go build ./...` |
| Test | `go test ./...` |
## Core Dependencies
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/zapdb/v4` | v4.9.2 | Default KV backend (BadgerDB-based) |
| `github.com/cockroachdb/pebble` | v1.1.5 | PebbleDB backend (build tag) |
| `github.com/syndtr/goleveldb` | v1.0.1 | LevelDB backend (build tag) |
| `github.com/luxfi/codec` | v1.1.3 | Binary serialization |
| `github.com/luxfi/crypto` | v1.17.39 | Encryption for encdb |
| `github.com/luxfi/ids` | v1.2.9 | ID types |
| `github.com/luxfi/log` | v1.4.1 | Structured logging |
| `github.com/luxfi/metric` | v1.5.0 | Prometheus metrics |
| `github.com/luxfi/cache` | v1.2.1 | Caching layer |
| `github.com/luxfi/compress` | v0.0.5 | Data compression |
| `github.com/luxfi/concurrent` | v0.0.3 | Concurrency utilities |
| `github.com/luxfi/math` | v1.2.3 | Math utilities |
| `github.com/stretchr/testify` | v1.11.1 | Testing assertions |
| `go.uber.org/mock` | v0.6.0 | Mock generation |
| `golang.org/x/crypto` | v0.48.0 | Cryptographic primitives |
| `golang.org/x/sync` | v0.19.0 | Sync utilities |
| `github.com/klauspost/compress` | v1.18.4 | Fast compression |
## Core Interface
The `Database` interface in `database.go` composes:
```go
type Database interface {
KeyValueReaderWriterDeleter // Has, Get, Put, Delete
Batcher // NewBatch
Iteratee // NewIterator variants
Compacter // Compact(start, limit)
Syncer // Sync() - flush to disk
io.Closer // Close
HealthCheck(context.Context) (interface{}, error)
Backup(w io.Writer, since uint64) (uint64, error) // Incremental backup
Load(r io.Reader) error // Restore from backup
}
```
### Sub-Interfaces
| Interface | Methods | Purpose |
|-----------|---------|---------|
| `KeyValueReader` | `Has(key)`, `Get(key)` | Read access |
| `KeyValueWriter` | `Put(key, value)` | Write access |
| `KeyValueDeleter` | `Delete(key)` | Delete access |
| `KeyValueReaderWriter` | Reader + Writer | Read/write |
| `KeyValueWriterDeleter` | Writer + Deleter | Write/delete |
| `KeyValueReaderWriterDeleter` | All three | Full access |
| `Compacter` | `Compact(start, limit)` | Storage compaction |
| `Syncer` | `Sync()` | Flush to persistent storage |
| `Batch` | `Size`, `Write`, `Reset`, `Replay`, `Inner` | Atomic batch writes |
| `Batcher` | `NewBatch()` | Batch factory |
| `Iterator` | `Next`, `Error`, `Key`, `Value`, `Release` | Key-value iteration |
| `Iteratee` | `NewIterator[WithStart][WithPrefix]` | Iterator factory |
| `HeightIndex` | `Put(height, value)`, `Get(height)`, `Has`, `Delete`, `Close` | Height-based blockchain state |
### Error Types
```go
var ErrClosed = errors.New("closed")
var ErrNotFound = errors.New("not found")
type ErrBackendDisabled struct { Backend string }
```
### Memory Management
`memory.go` provides `MemoryManager` for controlling database memory usage:
- Configurable percentage of system memory
- Reserve allocation for critical operations
- Prometheus gauge metrics (usage, available, remaining)
### Constants
```go
MaxExcessCapacityFactor = 4 // Above which capacity is excessive
CapacityReductionFactor = 2 // Reduction factor for excess capacity
```
## Storage Backends
### ZapDB (Default)
| Item | Value |
|------|-------|
| Package | `github.com/luxfi/zapdb/v4` |
| Wrapper | `database/badgerdb/` (compatibility) |
| Based on | BadgerDB |
| Build tag | None (always available) |
The `badgerdb/` package is a thin compatibility wrapper that delegates to `zapdb.New()`. Registered as the default backend in `manager/manager.go` via `init()`.
### PebbleDB
| Item | Value |
|------|-------|
| Package | `database/pebbledb/` |
| Based on | CockroachDB Pebble |
| Build tag | `-tags=pebbledb` |
| Features | Bloom filters, batch operations, custom iterators |
8 source files: `db.go`, `batch.go`, `iterator.go`, `constants.go`, `errors.go`, `set.go`, `db_test.go`, `batch_test.go`.
### LevelDB
| Item | Value |
|------|-------|
| Package | `database/leveldb/` |
| Based on | Google LevelDB (syndtr/goleveldb) |
| Build tag | `-tags=leveldb` |
| Features | Metrics collection, configurable constants |
5 source files: `db.go`, `constants.go`, `errors.go`, `metrics.go`, `db_test.go`.
### In-Memory (memdb)
| Item | Value |
|------|-------|
| Package | `database/memdb/` |
| Purpose | Testing, ephemeral storage |
| Build tag | None (always available) |
4 source files: `db.go`, `constants.go`, `iterator.go`, `db_test.go`.
## Database Wrappers
| Package | Purpose | Key Feature |
|---------|---------|-------------|
| `encdb/` | Encrypted database | AES encryption via `golang.org/x/crypto` |
| `corruptabledb/` | Corruption injection | Testing fault tolerance |
| `hookdb/` | Event hooks | Notifiers on write/delete operations |
| `linkeddb/` | Linked-list storage | Ordered traversal over key-value pairs |
| `heightindexdb/` | Height-indexed storage | Blockchain state by block height (big-endian uint64 keys) |
| `codec/` | Serialization layer | Binary codec with `codec/linear/` sub-package |
## Database Infrastructure
### Factory (`factory/`)
Pluggable database creation system:
- `RegisterDatabase(name, factory)` -- Register a backend
- `AvailableDatabases()` -- List available backends
- Default: ZapDB + memdb always available
- PebbleDB/LevelDB available via build tags
### Manager (`manager/`)
Database lifecycle management:
- `NewManager(baseDir, registerer)` -- Create manager
- `RegisterDatabaseType(name, creator)` -- Register backend type
- Supports `zapdb`, `pebbledb`, `leveldb` via files `manager_zapdb.go`, `manager_pebbledb.go`, `manager_leveldb.go`
- Wraps databases with metering, versioning, and prefixing
### Test Suite (`dbtest/`)
Comprehensive test harness:
- `dbtest.go` -- Full interface compliance tests
- `benchmark.go` -- Performance benchmarks
- `testsuite.go` -- Reusable test suite for any backend
### Mocks (`databasemock/`)
Generated mock implementations:
- `batch.go` -- Mock Batch
- `iterator.go` -- Mock Iterator
## Project Structure
```
~/work/lux/database/
go.mod # github.com/luxfi/database, Go 1.26.1
database.go # Core Database/HeightIndex interfaces
batch.go # Batch/Batcher interfaces and BatchOps
iterator.go # Iterator/Iteratee interfaces
errors.go # ErrClosed, ErrNotFound, ErrBackendDisabled
memory.go # MemoryManager (system memory control)
helpers.go # Utility functions
database_util.go # Additional utilities
Makefile # Build/test targets
badgerdb/ # ZapDB compatibility wrapper
pebbledb/ # PebbleDB backend (build tag)
leveldb/ # LevelDB backend (build tag)
memdb/ # In-memory backend
encdb/ # Encrypted database wrapper
corruptabledb/ # Corruption testing wrapper
hookdb/ # Event hook wrapper
linkeddb/ # Linked-list storage
heightindexdb/ # Height-indexed storage
codec/ # Serialization (with linear/ sub-pkg)
factory/ # Pluggable backend factory
manager/ # Database lifecycle management
dbtest/ # Test suite and benchmarks
databasemock/ # Generated mocks
bin/ # Build output
```
## Development
```bash
cd ~/work/lux/database
# Build all packages
go build ./...
# Run all tests
go test ./...
# Run with race detector
go test -race ./...
# Build with PebbleDB support
go build -tags=pebbledb ./...
# Build with LevelDB support
go build -tags=leveldb ./...
# Run benchmarks
go test -bench=. ./dbtest/
# Run specific backend tests
go test ./pebbledb/ -tags=pebbledb -v
go test ./leveldb/ -tags=leveldb -v
go test ./memdb/ -v
```
## Key Design Decisions
1. **Ethereum-compatible interface**: Matches go-ethereum's database API for seamless EVM integration
2. **Build-tag backends**: PebbleDB and LevelDB are compile-time optional to minimize binary size
3. **ZapDB as default**: BadgerDB-based ZapDB is always available, registered in `init()`
4. **Wrapper composition**: Encryption, metering, versioning are separate wrappers that can be composed
5. **HeightIndex**: Specialized interface for blockchain state indexed by block height using big-endian uint64 keys for efficient range queries
6. **Backup/Restore**: Built into the core `Database` interface with incremental backup support
7. **Memory management**: System-level memory control with configurable limits and Prometheus metrics
## Related Packages
| Package | Module | Purpose |
|---------|--------|---------|
| `github.com/luxfi/zapdb` | v4.9.2 | Default storage engine |
| `github.com/luxfi/cache` | v1.2.1 | In-memory caching layer |
| `github.com/luxfi/compress` | v0.0.5 | Data compression |
| `github.com/luxfi/codec` | v1.1.3 | Binary serialization |
| `github.com/luxfi/node` | Latest | Primary consumer of this package |
+253 -11
View File
@@ -1,18 +1,260 @@
---
title: "Lux Deployment - Network Automation"
description: "Lux deployment automation — K8s operators, DevOps tooling, and network deployment scripts."
title: "Lux Deploy"
description: "Blockchain Network Deployment System"
---
## Overview
Lux deployment automation — K8s operators, DevOps tooling, and network deployment scripts.
Lux Deploy (`github.com/luxfi/deploy`) is the production deployment system for Lux blockchain networks. It provides two layers: (1) a comprehensive Makefile-based orchestration system for local and dev network lifecycle management (5-node validator bootstrap, multi-chain deployment, RLP block import, snapshots), and (2) a Go tool (`deploy-subnets`) that programmatically creates subnets and blockchains on remote Lux nodes via P-chain wallet transactions. Supports mainnet and testnet configurations for five chains: C-Chain, Zoo, Hanzo, SPC, and Pars.
## Components
## Repository
| Component | Path | Purpose |
|-----------|------|---------|
| deploy/ | ``github.com/luxfi/deploy`` | Deployment system |
| devops/ | ``github.com/luxfi/devops`` | DevOps automation |
| lux-ops/ | ``github.com/luxfi/lux-ops`` | Operational tooling |
| operator/ | ``github.com/luxfi/operator`` | K8s operator |
| scripts/ | ``github.com/luxfi/scripts`` | Setup scripts |
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/deploy` |
| Local | `~/work/lux/deploy/` |
| Go Module | `github.com/luxfi/deploy-subnets` (Go 1.26.1) |
| Dependencies | `github.com/luxfi/sdk`, `github.com/luxfi/crypto`, `github.com/luxfi/ids` |
| License | See LICENSE |
## Project Structure
```
~/work/lux/deploy/
Makefile # Full deployment orchestration (698 lines)
DESIGN.md # Architecture design document
README.md # Usage documentation
cmd/
deploy-subnets/
main.go # Go tool for P-chain subnet/blockchain creation
go.mod # Module: github.com/luxfi/deploy-subnets
go.sum
deploy-subnets # Compiled binary
config/
networks/
mainnet.json # Mainnet network configuration
testnet.json # Testnet network configuration
node/
default.json # Default node configuration
lib/ # Shell library functions
common.sh # Shared utilities (paths, logging, error handling)
chains.sh # Chain-specific operations
network.sh # Network management
import.sh # RLP block import operations
snapshot.sh # Snapshot create/restore
scripts/ # High-level deployment scripts
deploy.sh # Full deployment orchestration
health.sh # Health check scripts
monitor.sh # Progress monitoring
```
## Makefile Orchestration System
### Architecture Layers
1. **Configuration Layer** -- Environment variables, network/chain configs
2. **Plugin Layer** -- EVM plugin installation and VMID mapping
3. **Network Layer** -- 5-node validator bootstrap, port management, health monitoring
4. **Chain Layer** -- Subnet/L2 deployment, genesis configuration
5. **Data Layer** -- RLP block import, progress monitoring, state verification
6. **Persistence Layer** -- Snapshot creation, restoration, archival
### Network Configuration
| Setting | Mainnet | Testnet |
|---------|---------|---------|
| Network ID | 1 | 2 |
| HTTP Port | 9630 | 9640 |
| Staking Port | 9631 | 9641 |
| gRPC Port | 8369 | 8368 |
### Chain Configuration
| Chain | Mainnet ID | Testnet ID | Notes |
|-------|-----------|-----------|-------|
| C-Chain | 96369 | 96368 | Primary EVM chain |
| Zoo | 200200 | 200201 | Zoo ecosystem chain |
| Hanzo | 36963 | 36962 | Hanzo AI chain |
| SPC | 36911 | -- | Mainnet only |
| Pars | 494949 | -- | Via deploy-subnets tool |
### EVM Plugin
- VMID: `srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy`
- Installed to `~/.lux/plugins/`
- Built from `~/work/lux/evm/` if not present
### Genesis Verification Hashes
| Chain | Network | Hash |
|-------|---------|------|
| C-Chain | Mainnet | `0x3f4fa2a0b0ce089f52bf0ae9199c75ffdd76ecafc987794050cb0d286f1ec61e` |
| C-Chain | Testnet | `0x1c5fe37764b8bc146dc88bc1c2e0259cd8369b07a06439bcfa1782b5d4fb0995` |
| Zoo | Mainnet | `0x7c548af47de27560779ccc67dda32a540944accc71dac3343da3b9cd18f14933` |
| Zoo | Testnet | `0x0652fb2fde1460544a5893e5eba5095ff566861cbc87fcb1c73be2b81d6d1979` |
| SPC | Mainnet | `0x4dc9fd5cf4ee64609f140ba0aa50f320cadf0ae8b59a29415979bc05b17cfac8` |
### Key Make Targets
```bash
# Full lifecycle
make deploy # Full: plugins + network + chains + import
make deploy-quick # Quick: plugins + network + chains (no import)
make dev # Dev setup: testnet + chains, no import
# Network management
make start-mainnet # Start 5-node mainnet (ports 9630-9638)
make start-testnet # Start 5-node testnet (ports 9640-9648)
make stop # Stop all networks
make restart # Stop + start current network
make wait-healthy # Wait for network health
# Chain deployment
make deploy-chains # Deploy all chains (Zoo, Hanzo, SPC)
make deploy-zoo # Deploy Zoo chain
make deploy-hanzo # Deploy Hanzo chain
make deploy-spc # Deploy SPC chain (mainnet only)
# Block import
make import-all # Import all RLP data (background)
make import-cchain # Import C-Chain blocks
make import-zoo # Import Zoo blocks
make import-spc # Import SPC blocks (mainnet only)
make import-status # Show import progress for all chains
# Snapshots
make snapshot # Create point-in-time snapshot
make restore SNAPSHOT=name # Restore from snapshot
make list-snapshots # List available snapshots
# Health and monitoring
make status # Show network and chain status
make health # Run health checks
make verify # Verify chain genesis hashes
make logs # Tail network logs
make logs-import # Show import progress in logs
# Cleanup
make clean # Clean runtime data (preserve snapshots)
make clean-all # Clean everything including snapshots
make clean-chains # Remove chain configurations
# Prerequisites
make check-prerequisites # Verify jq, curl, tar, lux CLI
make install-plugins # Install/update EVM plugin
make build-evm # Build EVM plugin from source
```
### Directory Layout (Runtime)
```
~/.lux/
plugins/ # EVM plugin binary
runs/
mainnet/ # Mainnet node data
testnet/ # Testnet node data
chains/ # Chain configurations
~/work/lux/
state/
rlp/ # RLP block files for import
snapshots/ # Network snapshots
chains/ # Chain genesis files
genesis/configs/ # Genesis configurations
cli/bin/lux # Lux CLI binary
evm/build/evm # Built EVM plugin
```
## deploy-subnets Go Tool
Programmatically deploys subnets and blockchains to remote Lux nodes via P-chain transactions.
### Usage
```bash
LUX_MNEMONIC="word1 word2 ..." ./deploy-subnets \
--endpoint http://24.199.78.71:9650 \
--chains zoo-mainnet,hanzo-mainnet,spc-mainnet \
--state-dir ~/work/lux/state \
--dry-run # Optional: preview without executing
```
### Supported Chain Configurations
| Key | Chain Name | Genesis Path |
|-----|-----------|-------------|
| `zoo-mainnet` | zoo | `chains/zoo-mainnet/genesis.json` |
| `zoo-testnet` | zootest | `chains/zoo-testnet/genesis.json` |
| `zoo-devnet` | zoodev | `chains/zoo-devnet/genesis.json` |
| `hanzo-mainnet` | hanzo | `chains/hanzo-mainnet/genesis.json` |
| `hanzo-testnet` | hanzotest | `chains/hanzo-testnet/genesis.json` |
| `hanzo-devnet` | hanzodev | `chains/hanzo-devnet/genesis.json` |
| `spc-mainnet` | spc | `chains/spc-mainnet/genesis.json` |
| `spc-testnet` | spctest | `chains/spc-testnet/genesis.json` |
| `spc-devnet` | spcdev | `chains/spc-devnet/genesis.json` |
| `pars-mainnet` | pars | `chains/pars-mainnet/genesis.json` |
| `pars-testnet` | parstest | `chains/pars-testnet/genesis.json` |
| `pars-devnet` | parsdev | `chains/pars-devnet/genesis.json` |
### How It Works
1. Derives secp256k1 keys from BIP39 mnemonic (indices 1-4, skip 0 which is staked)
2. Key derivation path: `m/44'/60'/0'/0/{index}`
3. Creates P-chain wallet via `github.com/luxfi/sdk/wallet/primary`
4. For each chain:
- Reads genesis JSON from state directory
- Issues `CreateNetworkTx` (creates subnet with owner key)
- Issues `CreateChainTx` (creates blockchain on subnet with EVM VMID)
5. Reports subnet IDs, blockchain IDs, and RPC endpoints
### Go Dependencies
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/sdk` | v1.16.46 | P-chain wallet and transaction building |
| `github.com/luxfi/crypto` | v1.17.40 | secp256k1 key operations |
| `github.com/luxfi/ids` | v1.2.9 | ID types (SubnetID, BlockchainID, VMID) |
| `github.com/luxfi/go-bip32` | v1.0.2 | HD key derivation |
| `github.com/luxfi/go-bip39` | v1.1.2 | Mnemonic validation and seed generation |
| `github.com/luxfi/utxo` | v0.2.4 | UTXO management (secp256k1fx keychain) |
| `github.com/luxfi/node` | v1.22.81 | Node types (indirect) |
| `github.com/luxfi/consensus` | v1.22.62 | Consensus types (indirect) |
| `github.com/luxfi/geth` | v1.16.73 | Ethereum types (indirect) |
### Subnet EVM VMID
`ag3GReYPNuSR17rUP8acMdZipQBikdXNRKDyFszAysmy3vDXE` (used for all subnet chains)
## Shell Library (lib/)
| Script | Purpose |
|--------|---------|
| `common.sh` | Paths, logging (colors, timestamps), error handling, `set -euo pipefail` |
| `chains.sh` | Chain CRUD, genesis validation, admin API calls |
| `network.sh` | Network start/stop, health polling, port detection |
| `import.sh` | RLP import initiation, progress tracking |
| `snapshot.sh` | Atomic snapshot (stop network, tar, restart) |
## Key Design Decisions
1. **Idempotent operations**: Every Makefile target can run multiple times safely
2. **Parallel imports**: Block imports run in background with monitoring
3. **Atomic snapshots**: Network stopped during snapshot for consistency
4. **Health-first**: Operations verify prerequisites before execution
5. **No EWOQ keys**: Mnemonic-based key derivation only
6. **Network separation**: Mainnet and testnet use different ports, never conflict
7. **CLI-based**: Uses `lux` CLI for network management, never `pkill luxd`
## Related Repos
| Repo | Purpose |
|------|---------|
| `github.com/luxfi/node` | Node software being deployed |
| `github.com/luxfi/evm` | EVM plugin built and installed |
| `github.com/luxfi/cli` | CLI tool for network management |
| `github.com/luxfi/genesis` | Genesis configuration files |
| `github.com/luxfi/sdk` | SDK for P-chain wallet transactions |
+384 -62
View File
@@ -1,85 +1,408 @@
---
title: "Lux DEX (LX) - Ultra-High Performance Order Matching"
description: "LX is an ultra-high performance CLOB (Central Limit Order Book) DEX engine with multi-engine order matching and GPU acceleration."
title: "Lux DEX (LX)"
description: "Ultra-High Performance Order Matching Engine"
---
## Overview
LX is an **ultra-high performance CLOB (Central Limit Order Book) DEX engine** with multi-engine order matching and GPU acceleration. This is a standalone order matching engine — NOT an AMM. Separate product from `luxfi/exchange`.
LX is an **ultra-high performance Central Limit Order Book (CLOB) order matching engine** with multi-backend acceleration (Go, C++, Rust, CUDA, MLX, FPGA). It is a standalone matching engine -- NOT an AMM. It integrates with `luxfi/exchange` for AMM routing but the core is a price-time priority CLOB with a full derivatives stack (perpetuals, margin, lending, vaults, clearing house).
The engine includes a pluggable gateway layer that aggregates liquidity from the native CLOB and external AMM providers (Uniswap V2/V3/V4, Lux AMM) across multiple chains, plus DAG-based consensus for multi-node orderbook synchronization.
**Performance**: 434M+ orders/sec (GPU/MLX), 2ns order latency (GPU), 487ns (CPU).
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/dex` |
| Language | Go 1.26.1 + C++ + Rust + MLX (Apple Metal) |
| Go | 1.26.1 |
| Binary | `luxd` (built to `bin/luxd`) |
| C++ Engine | `luxcpp/dex/` (CMake, C++17, `-O3 -march=native -flto`) |
| License | Proprietary (Lux Industries Inc) |
| Protocol | FIX (Financial Information eXchange) |
## Matching Engines
| Engine | Language | Performance |
|--------|----------|-------------|
| Pure Go | Go | 830K orders/sec |
| C++ | C++ | 800K+ orders/sec |
| Rust | Rust | 585K+ orders/sec |
| MLX GPU | Metal/CUDA | **434M+ orders/sec** |
### Latency
| Mode | Order Latency |
|------|---------------|
| GPU (MLX) | **2ns** |
| CPU | **487ns** |
| gRPC proto | `proto/lxdex.proto` |
| Chains | LUX (96369), Zoo (200200), Ethereum (1), Arbitrum (42161), etc. |
## Architecture
```
Client → FIX Protocol → Order Gateway
↓
┌───────────────┐
│ Order Router │
└───────┬───────┘
┌─────────────┼─────────────┐
↓ ↓ ↓
┌─────────┐ ┌─────────┐ ┌──────────┐
│ Go CLOB │ │ C++ CLOB│ │ GPU CLOB │
└─────────┘ └─────────┘ └──────────┘
↓ ↓ ↓
┌───────────────┐
│ Match Events │
└───────┬───────┘
↓
┌───────────────┐
│ Settlement │
└───────────────┘
+-----------------------------+
| External Clients |
| FIX / REST / WS / gRPC / ZAP|
+------+----------------------+
|
+-------------v------------------------+
| API Gateway (pkg/gateway) |
| Router -> Registry -> Providers |
| (Lux AMM, Uniswap V2/V3/V4, ...) |
+------+------------------+------------+
| |
+----------v---------+ +----v-------------+
| CLOB Engine | | AMM Providers |
| (pkg/lx) | | (pkg/gateway/) |
| +------------+ | | lux/ uniswap/ |
| | OrderBook | | +------------------+
| +------------+ |
| |ClearingHouse| |
| +------------+ |
| | RiskEngine | |
| +------------+ |
| |MarginEngine| |
| +------------+ |
| |FundingEngine| |
| +------------+ |
| |PriceOracle | |
| +------------+ |
+------+-------------+
|
+------------v------------------------------------+
| Matching Backends (pkg/orderbook) |
| +------+ +------+ +------+ +------+ |
| | Go | | C++ | | Rust | | MLX | |
| | Pure | | CGO | | FFI | | GPU | |
| +------+ +------+ +------+ +------+ |
+----+----------------------------------------+---+
|
+----v--------------------------------------------+
| Infrastructure |
| DPDK/XDP NATS ZeroMQ BadgerDB |
| Consensus (DAG/Quasar/Corona) |
+-------------------------------------------------+
```
## FIX Protocol Support
## Matching Engines
| Message | Type |
|---------|------|
| NewOrderSingle | Order submission |
| ExecutionReport | Fill/cancel notifications |
| MarketDataSnapshot | Order book snapshots |
| Engine | Language | Performance | Build Tag |
|--------|----------|-------------|-----------|
| Pure Go | Go | 830K orders/sec | (default, CGO_ENABLED=0) |
| C++ (CGO) | C++ | 800K+ orders/sec | `cpp` (CGO_ENABLED=1) |
| Rust | Rust | 585K+ orders/sec | (ext/) |
| MLX GPU | Apple Metal | **434M+ orders/sec** | `cpp gpu mlx` |
| CUDA GPU | NVIDIA CUDA | **434M+ orders/sec** | `cpp gpu` |
| FPGA | AMD Alveo / AWS F2 | Sub-microsecond | `cgo fpga` |
## Key Dependencies
### Build Variants
```
github.com/luxfi/accel — GPU/FPGA acceleration
github.com/luxfi/czmq/v4 — ZeroMQ messaging
github.com/luxfi/database — State storage
github.com/luxfi/geth — Ethereum types (luxfi, NOT go-ethereum)
github.com/luxfi/rpc — RPC layer
nats-io/nats.go — NATS messaging
google.golang.org/grpc — gRPC API
```bash
make build-go # Pure Go, CGO_ENABLED=0
make build-cpp # C++ acceleration via CGO
make build-gpu # GPU (MLX + CUDA), tags: cpp gpu mlx
make build-fpga # Generic FPGA
make build-fpga-versal # AMD Versal FPGA
make build-fpga-f2 # AWS F2 FPGA
```
## Integration with Exchange
### Backend Auto-Detection
The DEX engine integrates with `github.com/luxfi/exchange` via the DEX precompiles:
At `init()`, the engine detects the best available backend:
1. `CUDA_VISIBLE_DEVICES` set -> `BackendCUDA`
2. macOS arm64 + Metal.framework -> `BackendMLX`
3. `CGO_ENABLED=1` -> `BackendCGO`
4. Default -> `BackendGo`
## Order Types
Defined in `pkg/lx/types.go`:
| Type | Constant | Description |
|------|----------|-------------|
| Limit | `Limit` | Price-time priority limit order |
| Market | `Market` | Immediate execution at best available |
| Stop | `Stop` | Triggers at stop price |
| Stop-Limit | `StopLimit` | Triggers at stop price, places limit |
| Iceberg | `Iceberg` | Hidden size with display quantity, auto-refill |
| Peg | `Peg` | Pegged to BBO with offset |
| Bracket | `Bracket` | OCO with take-profit and stop-loss |
| Hidden | `Hidden` | Dark pool order, fully hidden |
### Order Flags
```go
const (
FlagPostOnly OrderFlags = 1 << iota // Reject if would take liquidity
FlagReduceOnly // Only reduce existing position
FlagImmediate // IOC semantics
FlagHidden // Dark pool order
)
const OrderFlagSTP OrderFlags = 1 << 2 // Self-trade prevention
```
### Time-in-Force
| TIF | Description |
|-----|-------------|
| `TIF_GTC` | Good Till Cancelled |
| `TIF_IOC` | Immediate Or Cancel (partial fills ok) |
| `TIF_FOK` | Fill Or Kill (all or nothing) |
| `TIF_DAY` | Day order (expires end of session) |
## OrderBook Internals (pkg/lx/orderbook.go)
The CLOB uses:
- **Integer prices**: `PriceInt` (int64, 8 decimal precision via `PriceMultiplier = 100_000_000`) for fast map lookups
- **B-tree price index**: `IntBTree` with configurable degree (default 32) for sorted price traversal
- **Lock-free order map**: `sync.Map` for concurrent order lookups alongside `map[uint64]*Order` for API compat
- **Linked list per level**: `OrderLinkedList` for O(1) order insertion/removal at each price
- **Circular trade buffer**: Fixed-capacity ring buffer (initial 1000) for trade history
- **Atomic counters**: Lock-free trade ID, order ID, update ID, sequence generation
- **Cache-line padding**: `_padding [64]byte` to prevent false sharing
- **Optimized price levels**: `OptimizedPriceLevel` with atomic size/count counters
### OrderTree
Each side (bids/asks) is an `OrderTree`:
```go
type OrderTree struct {
side Side
priceLevels map[PriceInt]*OptimizedPriceLevel // Integer keys for fast lookup
priceTree *IntBTree // B-tree for sorted iteration
orders map[uint64]*Order
bestPrice atomic.Int64 // Lock-free best price
}
```
## Package Structure
### `pkg/lx/` - Core Trading Engine (71 files)
| File | Purpose |
|------|---------|
| `types.go` | Core types: Order, Trade, TradingEngine, PriceLevel, OrderBookSnapshot |
| `orderbook.go` | Optimized CLOB: OrderBook, OrderTree, IntBTree, CircularTradeBuffer |
| `orderbook_advanced.go` | Iceberg, hidden, peg, bracket, conditional orders |
| `orderbook_extended.go` | Extended order book features |
| `clearinghouse.go` | ClearingHouse: perps margin, spot balances, multi-source oracle, funding |
| `margin.go` | MarginEngine: cross/isolated/portfolio margin |
| `risk_engine.go` | RiskEngine: pre-trade risk checks, VaR, exposure limits |
| `liquidation.go` | LiquidationEngine: forced position closes, ADL |
| `funding.go` | 8-hour funding rate mechanism for perpetuals |
| `lending.go` | LendingPool: borrow/supply with utilization-based rates |
| `vaults.go` | VaultManager: yield vaults |
| `vault_strategy.go` | Strategy implementations (Sharpe ratio, max drawdown, profit factor) |
| `staking.go` | Token staking with reward distribution |
| `oracle.go` | PriceOracle: multi-source weighted median, TWAP/VWAP |
| `pyth_source.go` | Pyth Network oracle adapter |
| `chainlink_source.go` | Chainlink oracle adapter |
| `alpaca_source.go` | Alpaca Markets oracle adapter |
| `bridge.go` | Cross-chain bridge: multi-validator consensus, daily limits, nonce tracking |
| `x_chain_integration.go` | Lux X-Chain integration |
| `multisig.go` | Multisig governance |
| `compliance.go` | KYC/AML compliance checking |
| `reconciliation.go` | Balance reconciliation |
| `funds.go` | Fund management |
| `fpga_accelerator.go` | FPGA acceleration: parser/risk/match/encoder pipelines, DMA channels |
| `market_config.go` | Per-market configuration |
### `pkg/api/` - API Servers
| File | Purpose |
|------|---------|
| `jsonrpc.go` | JSON-RPC 2.0 server with IP rate limiting (100 req/s/IP) |
| `websocket_server.go` | Real-time WebSocket: auth, subscriptions, per-client rate limit |
| `zap_server.go` | ZAP binary protocol for HFT (zero-copy, cache-aligned wire format) |
### `pkg/orderbook/` - Pluggable OrderBook Backends
| File | Purpose |
|------|---------|
| `factory.go` | Pure Go orderbook factory |
| `factory_cgo.go` | CGO factory (routes to C++ when available) |
| `cpp_orderbook.go` | C++ orderbook binding |
### `pkg/consensus/` - DEX Consensus
DAG-based ordering with Quasar certificate consensus and Corona post-quantum engine. Security levels: 128, 192, 256 bits.
### `pkg/gateway/` - API Gateway
Multi-provider aggregation supporting external DEX routing:
| File | Purpose |
|------|---------|
| `gateway.go` | Main gateway: register/unregister providers, start HTTP server |
| `router.go` | Parallel quote aggregation with fallback |
| `registry.go` | Provider registry |
| `provider.go` | Provider interface: QuoteProvider, LiquidityProvider, PriceProvider |
| `types.go` | Token, SwapQuote, PoolHop, chain IDs |
| `lux/` | Native Lux AMM provider |
| `uniswap/` | Uniswap V2/V3/V4 provider |
### `pkg/fpga/` - FPGA Acceleration
| File | Purpose |
|------|---------|
| `fpga_engine.go` | FPGA matching engine core |
| `fpga_interface.go` | Hardware abstraction layer |
| `amd_versal.go` | AMD Versal FPGA target |
| `aws_f2.go` | AWS F2 FPGA target |
| `stubs.go` | Build stubs when FPGA not available |
Supported cards: AMD Alveo U50 (8GB HBM, 100GbE), Alveo U55C (16GB HBM, 100GbE), Intel Agilex-7 (400GbE). Pipeline stages: Parser -> Risk -> Match -> Encoder with DMA channels and memory pools in BRAM/URAM/HBM.
## Wire Protocols
### ZAP Binary Protocol (`pkg/api/zap_server.go`)
Ultra-low-latency zero-copy binary protocol via `luxfi/rpc`:
| Message | ID | Wire Size | Description |
|---------|----|-----------|-------------|
| PlaceOrder | 1 | 64 bytes | symbol(8)+id(8)+price(8)+size(8)+side(1)+type(1)+flags(2)+ts(8)+user(16)+pad(4) |
| CancelOrder | 2 | 32 bytes | order_id(8)+user(16)+pad(8) |
| ModifyOrder | 3 | - | In-place order modification |
| OrderAck | 8 | 24 bytes | order_id(8)+status(1)+seq(8)+pad(7) |
| Trade | 10 | 48 bytes | id(8)+price(8)+size(8)+buyer(8)+seller(8)+ts(8) |
| Quote | - | 24 bytes | price(8)+size(8)+count(4)+pad(4) |
All messages are cache-line aligned. Pre-allocated 4KB response buffers via `sync.Pool`.
### gRPC Service (`proto/lxdex.proto`)
| RPC | Streaming | Description |
|-----|-----------|-------------|
| PlaceOrder | No | Place order (limit/market/stop/iceberg/peg) |
| CancelOrder | No | Cancel by order ID |
| GetOrder / GetOrders | No | Query orders |
| GetOrderBook | No | Snapshot with configurable depth |
| StreamOrderBook | Server | Real-time incremental updates |
| GetTrades | No | Query executed trades |
| StreamTrades | Server | Real-time trade feed |
| GetBalance | No | Account balance (available/locked/total) |
| GetPositions | No | Open positions with PnL |
| GetNodeInfo | No | Node version, block height, markets, uptime |
| GetPeers | No | P2P peer list |
| Ping | No | Health check |
### FIX Protocol
Standard Financial Information eXchange:
| FIX Message | Tag | Purpose |
|-------------|-----|---------|
| NewOrderSingle | D | Order submission |
| OrderCancelRequest | F | Cancel request |
| ExecutionReport | 8 | Fill/cancel/reject notifications |
| MarketDataSnapshot | W | Full order book snapshot |
| MarketDataIncRefresh | X | Incremental book updates |
### WebSocket API
Real-time trading with per-client authentication, symbol subscriptions, and rate limiting. Integrates with TradingEngine, MarginEngine, LendingPool, PriceOracle, VaultManager, XChainIntegration, and LiquidationEngine.
### JSON-RPC 2.0
Methods: `orderbook.getBestBid`, `orderbook.getBestAsk`, `orderbook.getStats`. Rate-limited to 100 req/s per IP.
## ClearingHouse (pkg/lx/clearinghouse.go)
Manages perpetual margin state and spot balances:
- **Cross margin**: Shared balance across all positions
- **Isolated margin**: Per-position margin allocation
- **Multi-source oracles**: Weighted median from Chainlink, Pyth, Alpaca
- **8-hour funding**: Standard intervals (00:00, 08:00, 16:00 UTC)
- **Per-account locks**: Parallel processing with per-account RWMutex
- **FPGA acceleration flags**: Optional FPGA for order processing and risk checks
## Risk Engine (pkg/lx/risk_engine.go)
Pre-trade risk with VaR, max drawdown, concentration limits. Default max leverage: BTC-USDT/ETH-USDT 100x, BNB-USDT 50x, default 20x.
## Bridge (pkg/lx/bridge.go)
Cross-chain asset bridging with multi-validator signatures, daily volume limits, nonce tracking, confirmation requirements, and expiry times. Status flow: Pending -> Validating -> Confirmed -> Executing -> Completed.
## C++ Engine (`luxcpp/dex/`)
Standalone C++17 matching engine:
| Source | Purpose |
|--------|---------|
| `src/orderbook.cpp` | Core CLOB |
| `src/matching.cpp` | Matching algorithm |
| `src/engine.cpp` | Engine orchestration |
| `src/oracle.cpp` | Price oracle |
| `src/book.cpp` | Book management |
| `src/pool.cpp` | Liquidity pool |
| `src/vault.cpp` | Vault operations |
| `src/feed.cpp` | Market data feed |
| `src/lx.cpp` | Main entry point |
Build: `cmake -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build`
## SDKs
Multi-language SDKs in `sdk/` and `ext/`:
| Language | Path |
|----------|------|
| Go | `sdk/go/`, `sdk/lx-trading-go/` |
| TypeScript | `sdk/typescript/`, `sdk/lx-trading-ts/` |
| Python | `sdk/python/`, `sdk/lx-trading-py/` |
| Rust | `sdk/rust/`, `sdk/lx-trading-rust/` |
| C | `sdk/c/`, `sdk/lx-trading-c/` |
| C++ | `sdk/cpp/`, `sdk/lx-trading-cpp/` |
| Core | `sdk/lx-trading-core/` |
External integrations: Hummingbot market maker connector (`ext/hummingbot/`, `ext/hummingbot-gateway/`).
## Key Dependencies (from go.mod)
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/accel` | v1.0.1 | GPU/FPGA acceleration |
| `github.com/luxfi/czmq/v4` | v4.2.2 | ZeroMQ messaging (C binding) |
| `github.com/luxfi/database` | v1.2.15 | State storage |
| `github.com/luxfi/geth` | v1.16.64 | Ethereum types |
| `github.com/luxfi/log` | v1.2.5 | Structured logging |
| `github.com/luxfi/rpc` | v1.0.0 | Zero-copy RPC (ZAP protocol) |
| `github.com/luxfi/crypto` | v1.17.26 | Cryptographic primitives |
| `github.com/luxfi/ids` | v1.2.5 | ID types (base58) |
| `github.com/nats-io/nats.go` | v1.48.0 | NATS messaging |
| `github.com/shopspring/decimal` | v1.4.0 | Decimal arithmetic |
| `google.golang.org/grpc` | v1.79.1 | gRPC framework |
| `github.com/gorilla/websocket` | v1.5.4 | WebSocket server |
## Build and Run
```bash
# Build
make build # Build luxd + tools
make build-go # Pure Go (CGO_ENABLED=0)
make build-cpp # C++ acceleration (CGO_ENABLED=1, -tags cpp)
make build-gpu # GPU/MLX (-tags "cpp gpu mlx")
# Test
make test # Unit tests (pkg/lx, pkg/api)
make test-all # Full test suite
make test-race # With race detector
make bench # Standard benchmarks (10s)
make bench-all # Comprehensive benchmarks
# Run
make run # Single node (port 8080)
make run-cluster # 3-node cluster
make run-local # Local network
make run-fpc # FPC consensus network
# Docker
make docker-build # Standard image
make docker-cuda # CUDA-enabled image
make up / make down # Docker Compose
# CI/CD
make ci # clean + fmt + vet + test + build
make verify-all # deps + fmt + vet + lint + test-100 + bench
make prod # clean + verify-all + build + docker-build
make proto # Generate gRPC code from proto/
make sdk-all # Build all language SDKs
```
## EVM Precompile Integration
The DEX engine integrates with `github.com/luxfi/exchange` via precompiles:
| Precompile | Address | Purpose |
|------------|---------|---------|
@@ -88,10 +411,9 @@ The DEX engine integrates with `github.com/luxfi/exchange` via the DEX precompil
| HooksRegistry | `0x0402` | Custom swap hooks |
| FlashLoan | `0x0403` | Flash loan facility |
Exchange routes limit/market orders to this CLOB engine for execution.
## Related Skills
- `lux/lux-exchange.md` — AMM frontend (routes orders to DEX)
- `lux/lux-evm.md` — EVM with DEX precompiles
- `lux/lux-accel.md` — GPU/FPGA acceleration
- `lux/lux-exchange.md` -- AMM frontend (routes orders to DEX)
- `lux/lux-evm.md` -- EVM with DEX precompiles
- `lux/lux-accel.md` -- GPU/FPGA acceleration library
- `lux/lux-consensus.md` -- Quasar consensus integration
+143 -6
View File
@@ -1,16 +1,153 @@
---
title: "Lux Documentation - Official Docs Site"
description: "Official Lux Network documentation at `docs.lux.network` — Next.js based (@luxfi/docs)."
title: "Lux Documentation"
description: "Official Docs Site"
---
## Overview
Official Lux Network documentation at `docs.lux.network` — Next.js based (@luxfi/docs).
Official Lux Network documentation platform hosted at `docs.lux.network`. Built as a Turborepo monorepo with 13 independent documentation apps, each powered by Next.js and the `@hanzo/docs` framework. Covers the full Lux ecosystem: node operation, consensus, SDK usage, contract deployment, subnet/L2 architecture, and every major subsystem (bridge, explorer, wallet, HSM, MPC, bootnode, KMS, indexer, netrunner, CLI).
## Quick reference
## Repository
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/docs` |
| Local | `~/work/lux/docs/` |
| URL | `https://docs.lux.network` |
| Tech | Next.js |
| Dev | `pnpm dev` |
| Package Manager | pnpm 10.12.4 |
| Build Orchestrator | Turborepo 2.8.9 |
| Node | 22 (Alpine in Docker) |
| License | See LICENSE |
## Tech Stack
| Technology | Purpose |
|------------|---------|
| Next.js 16 | Static site generation and SSR |
| React 19 | Component rendering |
| Tailwind CSS 4 | Styling |
| `@hanzo/docs` 16.x | Documentation framework (routing, search, layout) |
| `@hanzo/docs-core` 16.x | Core MDX processing and plugins |
| `@hanzo/docs-mdx` 14.x | MDX compilation, `docs-mdx` CLI for codegen |
| `@hanzo/docs-ui` 16.x | Pre-built UI components (sidebar, TOC, nav) |
| `@hanzo/docs-openapi` 10.x | OpenAPI spec rendering |
| `@hanzo/docs-typescript` 5.x | TypeScript type documentation |
| `@hanzo/docs-twoslash` 3.x | Inline TypeScript evaluation in code blocks |
| Shiki 3.x | Syntax highlighting (10 languages configured) |
| Zod 4.x | Runtime schema validation |
| nginx | Production static file serving |
## Project Structure
```
~/work/lux/docs/
package.json # Root workspace (lux-docs v0.1.0)
pnpm-workspace.yaml # Workspace: apps/*
turbo.json # Build/dev/clean/lint/types:check tasks
Dockerfile # Multi-stage: node build + nginx serve
nginx.conf # Static serving config
apps/
docs/ # Main documentation site (port 3000)
bootnode-docs/ # Bootnode setup and operation
bridge-docs/ # Cross-chain bridge documentation
cli-docs/ # Lux CLI reference
explorer-docs/ # Block explorer documentation
hsm-docs/ # Hardware Security Module integration
indexer-docs/ # Chain indexer documentation
kms-docs/ # Key Management Service
mpc-docs/ # Multi-Party Computation custody
netrunner-docs/ # Network testing tool
sdk-docs/ # Go and JS SDK reference
wallet-docs/ # Wallet integration guides
```
## Main Docs App (apps/docs/)
### Content Structure
Content lives in `apps/docs/content/docs/` as MDX files:
| Section | Files | Topics |
|---------|-------|--------|
| `build/` | contracts, sdks, subnets, tutorials | Smart contract deployment, SDK usage, subnet creation |
| `learn/` | architecture, consensus, post-quantum, tokenomics | Core concepts and protocol design |
| `nodes/` | archive, full-node, validator | Node operation and setup guides |
| `reference/` | health, info, json-rpc, platform, sdk-go, sdk-js | API reference documentation |
| `skills/` | 25+ skill pages | Per-component skill documentation |
### Source Configuration
`source.config.ts` uses `@hanzo/docs/mdx/config` with:
- Async document loading
- Rehype code plugin with dual themes (github-light / github-dark)
- Languages: ts, js, html, tsx, mdx, go, rust, bash, json, yaml, toml
- Inline code with tailing-curly-colon syntax
### Dependencies (apps/docs/package.json)
- `@hanzo/docs` 16.2.9 (framework)
- `@hanzo/docs-core` 16.4.3 (core)
- `@hanzo/docs-base-ui` 16.4.3 (base components)
- `@hanzo/docs-ui` 16.4.3 (UI components)
- `@hanzo/docs-mdx` 14.2.5 (MDX processing)
- `@hanzo/docs-openapi` 10.2.3 (API docs)
- `@hanzo/docs-typescript` 5.0.1 (TS docs)
- `@hanzo/docs-twoslash` 3.1.11 (inline eval)
- `@hanzo/docs-docgen` 3.0.5 (doc generation)
- `@hanzo/docs-cli` 1.2.5 (CLI tooling)
- Next.js 16, React 19, Tailwind CSS 4
## Development
```bash
cd ~/work/lux/docs
# Install dependencies
pnpm install
# Start all docs apps in parallel
pnpm dev
# Start main docs only (port 3000)
cd apps/docs && pnpm dev
# Build all apps
pnpm build
# Lint all apps
pnpm lint
# Type check all apps
pnpm types:check
```
## Docker Build
Multi-stage build producing an nginx-served static site:
```dockerfile
FROM node:22-alpine AS build
# pnpm install + build (apps/docs)
FROM nginx:alpine
# Copy built output to /usr/share/nginx/html
EXPOSE 3000
```
## Key Patterns
- Each docs app is independent with its own `package.json`, `source.config.ts`, and content directory
- All apps share the same `@hanzo/docs` framework stack
- Build command runs `docs-mdx` CLI before `next build` to generate MDX metadata
- Static export (`out/` directory) for nginx serving
- Content is MDX with frontmatter, supporting code blocks with syntax highlighting
- Turborepo caches `.next/**` outputs (excluding `.next/cache/**`)
## Related Repos
| Repo | Purpose |
|------|---------|
| `github.com/luxfi/node` | Node software documented here |
| `github.com/luxfi/sdk` | SDK reference source |
| `github.com/luxfi/cli` | CLI command reference |
| `github.com/luxfi/bridge` | Bridge protocol docs |
| `github.com/luxfi/explorer` | Explorer docs |
+550 -60
View File
@@ -1,69 +1,131 @@
---
title: "Lux EVM - Unified Go Execution Engine"
description: "Lux EVM is the unified Go-based EVM execution engine for both C-Chain and L1/L2 Subnet EVM chains."
title: "Lux EVM"
description: "Unified Go EVM Execution Engine"
---
## Overview
Lux EVM is the **unified Go-based EVM execution engine** for both C-Chain and L1/L2 Subnet EVM chains. The former `coreth` codebase has been **merged into this repo** — it is not a separate dependency.
Lux EVM (`github.com/luxfi/evm`) is the unified Go-based EVM execution engine for the Lux Network. It powers both the C-Chain (the primary EVM-compatible chain on the Lux primary network) and all Subnet/L1/L2 EVM chains. The former `coreth` codebase was **merged into this repo** -- `github.com/luxfi/coreth` is deprecated and no longer maintained separately.
## Quick reference
The EVM runs as a **plugin binary** loaded by `luxd` (the Lux node). The binary is built from `plugin/main.go` and communicates with the node via the `rpcchainvm` gRPC interface. It is not a standalone process -- it requires `luxd` to operate.
### Tech Stack
- **Language**: Go 1.26.1
- **Module**: `github.com/luxfi/evm`
- **Ethereum Fork**: `github.com/luxfi/geth` v1.16.75 (NOT `go-ethereum`)
- **Consensus**: Dummy engine (block ordering delegated to Quasar via luxd)
- **Database**: BadgerDB (default), PebbleDB (legacy option)
- **State Sync**: Merkle trie state sync with parallel fetching
- **Cross-Chain**: LP-118 Warp messaging protocol
- **Precompiles**: Stateful precompile framework with allow-list access control
- **Tracing**: OpenTelemetry OTLP traces
- **Metrics**: Prometheus-compatible
- **Build**: `go build` or `make` (produces plugin binary `evm` / `evm.so`)
### When to Use
- Deploying or interacting with smart contracts on C-Chain or any Lux EVM subnet
- Building custom stateful precompiles for EVM chains
- Integrating with C-Chain via JSON-RPC or WebSocket
- Cross-chain messaging between EVM chains using Warp
- Running a custom Subnet-EVM with configurable fees, gas limits, and precompiles
- Migrating from `coreth` to the unified EVM module
### Hard Requirements
1. **ALWAYS** use `github.com/luxfi/evm` -- **NEVER** `github.com/luxfi/coreth` (deprecated, merged here)
2. **ALWAYS** use `github.com/luxfi/geth` -- **NEVER** `go-ethereum` or `ethereum/go-ethereum`
3. **ALWAYS** use `github.com/luxfi/precompile` -- **NEVER** `github.com/luxfi/precompiles` (old, excluded in go.mod)
4. **NEVER** bump Go packages above v1.x.x
5. The EVM is a plugin binary, not a standalone executable -- it must be loaded by `luxd`
6. CGO must be enabled for production builds (BLS signatures, GPU acceleration)
## Quick Reference Table
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/evm` |
| Version | v0.8.35+ |
| Go | 1.26.1 |
| Go version | 1.26.1 |
| C-Chain RPC | `http://<node>:9630/ext/bc/C/rpc` |
| Chain ID | 96369 (mainnet), 96370 (testnet) |
| C-Chain WebSocket | `ws://<node>:9630/ext/bc/C/ws` |
| C-Chain ID (mainnet) | 96369 |
| C-Chain ID (testnet) | 96368 |
| C-Chain ID (devnet) | 96370 |
| Default Chain ID | 43112 (local/custom) |
| Block time target | 2 seconds |
| Gas limit | 8,000,000 |
| Min base fee | 25 gwei (mainnet), 1 wei (test) |
| Database default | BadgerDB |
| Plugin binary | `evm` / `evm.so` |
| Luxd compat | v1.12.0 through v1.13.3 (protocol versions 38-42) |
| RPC gas cap | 50,000,000 |
| RPC tx fee cap | 100 LUX |
## Hard requirements
## Migration from Coreth
1. ALWAYS use `github.com/luxfi/evm` — NEVER `github.com/luxfi/coreth` (deprecated, merged here)
2. ALWAYS use `github.com/luxfi/geth` — NEVER `go-ethereum`
## Migration from coreth
All `coreth` imports become `evm` imports. The API is identical.
```go
// OLD (deprecated):
import "github.com/luxfi/coreth/ethclient"
import "github.com/luxfi/coreth/core"
import "github.com/luxfi/coreth/params"
// NEW (correct):
import "github.com/luxfi/evm/ethclient"
import "github.com/luxfi/evm/core"
import "github.com/luxfi/evm/params"
```
All `coreth` imports become `evm` imports. The API is identical.
## Two Operating Modes
## Two Modes
### C-Chain Mode (Primary Network)
### C-Chain Mode
- Atomic transactions for X-Chain/C-Chain cross-chain transfers
- Shared memory with other chains on the same node
- Integrated with P-Chain validator set
The default mode when running as part of the Lux primary network:
### Subnet EVM Mode
- Configurable fees, gas limits, and precompiles
- No atomic transactions (uses Warp messaging instead)
- Independent validator set per subnet
- **Atomic transactions** for cross-chain transfers between X-Chain and C-Chain via shared memory
- **Integrated validator set** from P-Chain -- no separate staking
- **Network-defined hard forks** (EVM, Durango, Etna, Fortuna, Granite)
- **Chain ID**: 96369 (mainnet), 96368 (testnet), 96370 (devnet)
- **Warp address**: Legacy `0x0200000000000000000000000000000000000005` (also accessible at `0x16201`)
## One-file quickstart
### Subnet EVM Mode (L1/L2 Subnets)
### EVM RPC
When deployed as a subnet/L1/L2 chain:
- **Configurable fees** via FeeManager precompile or genesis JSON
- **Configurable gas limits** and block gas costs
- **Custom precompiles** via the stateful precompile framework
- **No atomic transactions** -- uses Warp messaging for cross-chain
- **Independent validator set** per subnet
- **Simplified hardfork configuration**
## One-File Quickstart
### EVM JSON-RPC
```bash
# Get block number
# Get latest block number
curl -X POST http://localhost:9630/ext/bc/C/rpc \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'
# Get balance
# Get account balance
curl -X POST http://localhost:9630/ext/bc/C/rpc \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_getBalance","params":["0x...","latest"]}'
# Send transaction
# Send raw transaction
curl -X POST http://localhost:9630/ext/bc/C/rpc \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_sendRawTransaction","params":["0x..."]}'
# Get chain ID
curl -X POST http://localhost:9630/ext/bc/C/rpc \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}'
# Get fee config (Lux-specific)
curl -X POST http://localhost:9630/ext/bc/C/rpc \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_feeConfig","params":[]}'
```
### Go Client
@@ -71,62 +133,490 @@ curl -X POST http://localhost:9630/ext/bc/C/rpc \
```go
import "github.com/luxfi/evm/ethclient"
client, _ := ethclient.Dial("http://localhost:9630/ext/bc/C/rpc")
client, err := ethclient.Dial("http://localhost:9630/ext/bc/C/rpc")
if err != nil {
return err
}
blockNum, _ := client.BlockNumber(ctx)
balance, _ := client.BalanceAt(ctx, addr, nil)
chainID, _ := client.ChainID(ctx)
```
### Custom Precompile
```go
import "github.com/luxfi/evm/precompile/contract"
import (
"github.com/luxfi/evm/precompile/contract"
"github.com/luxfi/evm/precompile/modules"
"github.com/luxfi/geth/common"
)
var Module = &contract.Module{
Address: common.HexToAddress("0x0300000000000000000000000000000000000001"),
Configure: configure,
// Register a precompile module at a specific address
var Module = modules.Module{
Address: common.HexToAddress("0x0300000000000000000000000000000000000001"),
Contract: MyPrecompile,
Configurer: &MyConfigurator{},
}
func configure(cfg *contract.StatefulPrecompileConfig) {
cfg.AddFunction("myFunction", myFunctionHandler)
// Use the precompile code generator for boilerplate:
// go run cmd/precompilegen/main.go --abi MyContract.abi --out precompile/contracts/mycontract/
```
## Core Concepts
### Architecture
```
github.com/luxfi/evm
├── plugin/ -- Plugin entry point and VM implementation
│ ├── main.go -- Binary entry point (loaded by luxd)
│ ├── runner/ -- Plugin runner (gRPC server lifecycle)
│ └── evm/ -- Core VM implementation
│ ├── vm.go -- Main VM struct (Initialize, BuildBlock, Verify, Accept)
│ ├── block.go -- Block construction and verification
│ ├── block_builder.go -- Async block building engine
│ ├── config/ -- VM configuration (Config struct, defaults)
│ ├── service.go -- Validators API (gRPC service)
│ ├── admin.go -- Admin API (CPU profiler, logging)
│ ├── admin_api.go -- Admin API (import chain, db operations)
│ ├── gossip/ -- Transaction gossip handlers
│ ├── message/ -- P2P message types
│ ├── header/ -- Custom header verification
│ ├── customtypes/ -- Block extra data types
│ ├── customrawdb/ -- Raw database operations
│ ├── validators/ -- Validator management
│ └── upgrade/ -- EVM-specific upgrade handling
├── core/ -- Core blockchain logic (forked from geth)
│ ├── blockchain.go -- Blockchain state machine
│ ├── state_processor.go -- Transaction execution
│ ├── state_transition.go -- EVM state transitions
│ ├── genesis.go -- Genesis block initialization
│ ├── txpool/ -- Transaction pool management
│ ├── state/ -- State database (StateDB)
│ ├── vm/runtime/ -- EVM runtime
│ └── precompile_overrider.go -- Precompile injection into EVM
├── consensus/ -- Consensus engine interface
│ ├── consensus.go -- Engine interface (ChainHeaderReader, Engine)
│ └── dummy/ -- Dummy engine (delegates ordering to luxd)
├── eth/ -- Ethereum protocol implementation
│ ├── backend.go -- ETH backend (chain access, filters, gas price)
│ ├── api_backend.go -- API backend for eth_* namespace
│ ├── api_debug.go -- Debug API (tracing, stack dumps)
│ ├── api_admin.go -- Admin API (export chain)
│ ├── api_dev.go -- Dev API (mine blocks on demand)
│ ├── ethconfig/ -- ETH configuration
│ ├── filters/ -- Log/block/tx filters
│ ├── gasprice/ -- Gas price oracle
│ ├── gasestimator/ -- Gas estimation
│ └── tracers/ -- EVM execution tracers (JS, native)
├── precompile/ -- Stateful precompile framework
│ ├── contracts/ -- Built-in precompile implementations
│ │ ├── deployerallowlist/ -- Contract deployer allow list (0x10201)
│ │ ├── txallowlist/ -- Transaction sender allow list (0x10301)
│ │ ├── nativeminter/ -- Native token minting (0x10401)
│ │ ├── feemanager/ -- Dynamic fee configuration (0x13F01)
│ │ ├── rewardmanager/ -- Block reward distribution (0x10205)
│ │ └── warp/ -- Warp cross-chain messaging (0x16201)
│ ├── allowlist/ -- Role-based access control framework
│ ├── contract/ -- Precompile contract interface
│ ├── modules/ -- Module registration and LP-aligned addressing
│ ├── precompileconfig/ -- Config interfaces
│ ├── precompiletest/ -- Test utilities
│ └── registry/ -- Auto-registration via init()
├── params/ -- Chain configuration and parameters
│ ├── config.go -- ChainConfig (EVM forks, chain IDs)
│ └── extras/ -- Lux-specific extensions
│ ├── config.go -- FeeConfig, NetworkUpgrades, GenesisPrecompiles
│ ├── network_upgrades.go -- EVM/Durango/Etna/Fortuna/Granite timestamps
│ ├── precompiles.go -- Precompile configuration
│ ├── rules.go -- Chain rules per block
│ └── state_upgrade.go -- State upgrade definitions
├── commontype/ -- Shared types (FeeConfig)
├── ethclient/ -- Go Ethereum client (standard ethclient API)
├── accounts/ -- Account management
├── contracts/ -- Solidity contracts and Hardhat project
│ └── contracts/ -- Precompile Solidity interfaces
│ ├── AllowList.sol
│ ├── ERC20NativeMinter.sol
│ ├── ExampleFeeManager.sol
│ ├── ExampleRewardManager.sol
│ ├── ExampleWarp.sol
│ ├── FeeGovernor.sol
│ └── interfaces/ -- IAllowList, IFeeManager, INativeMinter, IRewardManager, IWarpMessenger
├── miner/ -- Block mining/building
├── node/ -- Ethereum node stack (P2P disabled in Lux)
├── network/ -- Transaction gossip network
├── rpc/ -- JSON-RPC server framework
├── sync/ -- State sync (client/server)
│ ├── client/ -- State trie fetching from peers
│ └── statesync/ -- State sync server
├── warp/ -- Warp messaging (aggregator, signer, verifier)
│ ├── aggregator.go -- Collects BLS signatures from validators
│ ├── backend.go -- Warp backend (message storage)
│ ├── client.go -- Warp client for querying signatures
│ ├── service.go -- Warp RPC service
│ └── validators/ -- Validator set for Warp verification
├── cmd/ -- CLI tools
│ ├── abigen/ -- ABI binding generator
│ ├── evm/ -- EVM execution tool
│ ├── simulator/ -- Local network simulator
│ ├── precompilegen/ -- Precompile code generator
│ ├── export/ -- Chain export tool
│ └── utils/ -- CLI utilities
└── interfaces/ -- Shared interface definitions
```
### Consensus Engine
The EVM uses a **DummyEngine** (`consensus/dummy/`) that does not perform block ordering or leader election. Instead:
1. `luxd` drives consensus via the Quasar hybrid finality engine
2. The DummyEngine validates block headers (timestamp ordering, gas limits, fee calculations)
3. Block production is triggered by `luxd` calling `BuildBlock()` on the VM
4. The DummyEngine's `Finalize` applies block rewards per RewardManager configuration
Key interfaces defined in `consensus/consensus.go`:
- `ChainHeaderReader`: Access chain config, headers, fee config, coinbase
- `ChainReader`: Extends header reader with full block access
- `Engine`: Author, VerifyHeader, VerifyUncles, Prepare, Finalize, FinalizeAndAssemble, CalcDifficulty, Close
### Network Upgrades (Fork Order)
Timestamp-based fork activation in `params/extras/network_upgrades.go`:
| Fork | Eth Equivalent | Notes |
|------|---------------|-------|
| **EVM** | Pre-Shanghai | Always active at genesis (timestamp 0) |
| **Durango** | Shanghai | Warp messaging, EIP-3651/3855/3860/6049 (EIP-4895 excluded) |
| **Etna** | Cancun | EIP-4844 blob schedule configuration required |
| **Fortuna** | -- | Lux-specific, no direct EVM effect |
| **Granite** | -- | Placeholder for next scheduled upgrade |
### Built-in Stateful Precompiles
Registered via `init()` in `precompile/registry/` and activated through genesis or upgrade configuration.
| Address | Package | Config Key | Purpose |
|---------|---------|------------|---------|
| `0x10201` | `deployerallowlist` | `contractDeployerAllowListConfig` | Controls which addresses can deploy contracts |
| `0x10205` | `rewardmanager` | `rewardManagerConfig` | Configures block reward distribution |
| `0x10301` | `txallowlist` | `txAllowListConfig` | Controls which addresses can submit transactions |
| `0x10401` | `nativeminter` | `contractNativeMinterConfig` | Mints native tokens to specified addresses |
| `0x13F01` | `feemanager` | `feeManagerConfig` | Dynamically adjusts fee parameters |
| `0x16201` | `warp` | `warpConfig` | Cross-chain messaging (send/receive Warp messages) |
All precompiles use the **AllowList** access control pattern with roles:
- **Admin**: Can grant/revoke roles and call all functions
- **Manager**: Can call privileged functions but cannot manage roles
- **Enabled**: Can call basic functions
- **None**: No access to privileged functions
### External Precompiles (`github.com/luxfi/[email protected]`)
Registered via `modules.RegisterModule()` in `precompile/registry/registry.go`.
#### Post-Quantum Cryptography (NIST PQC)
| Address | Package | Standard |
|---------|---------|----------|
| `0x0200...0006` | `mldsa` | ML-DSA signature verification (FIPS 204) |
| `0x0200...0007` | `mlkem` | ML-KEM key encapsulation (FIPS 203) |
| `0x0200...000B` | `corona` | Ring-LWE threshold lattice (post-quantum) |
| `0x0600...0001` | `slhdsa` | SLH-DSA stateless hash signatures (FIPS 205) |
| `0x9003` | `pqcrypto` | Unified PQ crypto operations |
#### Privacy/Encryption
| Address | Package | Purpose |
|---------|---------|---------|
| `0x0700...0000` | `fhe` | Fully Homomorphic Encryption (TFHE) |
| `0x0700...0001` | `fhe` (ACL) | FHE access control list |
| `0x0700...0002` | `fhe` (InputVerifier) | FHE input verification |
| `0x0700...0003` | `fhe` (Gateway) | FHE gateway contract |
| `0x9200` | `hpke` | Hybrid Public Key Encryption |
| `0x9201` | `ecies` | Elliptic Curve Integrated Encryption |
| `0x9202` | `ring` | Ring signatures (anonymity) |
#### Zero-Knowledge Proofs
| Address | Package | Purpose |
|---------|---------|---------|
| `0x0900...0000` | `zk` | ZK proof verification (primary) |
| `0x0900...0001` | `zk` (Groth16) | Groth16 proof verifier |
| `0x0900...0002` | `zk` (PLONK) | PLONK proof verifier |
| `0x0900...0003` | `zk` (fflonk) | fflonk proof verifier |
| `0x0900...0004` | `zk` (Halo2) | Halo2 proof verifier |
| `0x0900...0010` | `zk` (KZG) | KZG commitment verifier |
| `0x0900...0020` | `zk` (PrivacyPool) | Privacy pool operations |
| `0x0900...0021` | `zk` (Nullifier) | Nullifier tracking |
#### DEX: QuantumSwap Native DEX (LP-9xxx)
| Address | Name | Purpose |
|---------|------|---------|
| `0x0...9010` | LXPool | Singleton AMM pool manager (Uniswap v4 style) |
| `0x0...9011` | LXOracle | Multi-source price aggregation |
| `0x0...9012` | LXRouter | Swap routing |
| `0x0...9013` | LXHooks | Hook contract registry |
| `0x0...9014` | LXFlash | Flash loan facility |
| `0x0...9020` | LXBook | Central limit order book (CLOB) |
| `0x0...9030` | LXVault | Custody and margin |
| `0x0...9040` | LXFeed | Computed price feeds |
| `0x0...9050` | LXLend | Lending pool |
### Precompile Solidity Interfaces
Located in `contracts/contracts/interfaces/`:
```solidity
// IAllowList.sol -- base for all precompiles with access control
interface IAllowList {
function readAllowList(address addr) external view returns (uint256);
function setAdmin(address addr) external;
function setManager(address addr) external;
function setEnabled(address addr) external;
function setNone(address addr) external;
}
// IFeeManager.sol -- dynamic fee configuration
interface IFeeManager is IAllowList {
function getFeeConfig() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
function getFeeConfigLastChangedAt() external view returns (uint256);
function setFeeConfig(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) external;
}
// INativeMinter.sol -- native token minting
interface INativeMinter is IAllowList {
function mintNativeCoin(address addr, uint256 amount) external;
}
// IWarpMessenger.sol -- cross-chain messaging
interface IWarpMessenger {
function sendWarpMessage(bytes calldata payload) external returns (bytes32);
function getVerifiedWarpMessage(uint32 index) external view returns (WarpMessage memory, bool);
function getVerifiedWarpBlockHash(uint32 index) external view returns (WarpBlockHash memory, bool);
function getBlockchainID() external view returns (bytes32);
}
```
### Fee Configuration
The dynamic fee algorithm adjusts base fees based on network utilization:
| Parameter | Default (Mainnet) | Default (Test) | Description |
|-----------|-------------------|----------------|-------------|
| `GasLimit` | 8,000,000 | 8,000,000 | Maximum gas per block |
| `TargetBlockRate` | 2 seconds | 2 seconds | Target block production rate |
| `MinBaseFee` | 25 gwei | 1 wei | Floor for EIP-1559 base fee |
| `TargetGas` | 15,000,000 | 15,000,000 | Target gas consumption per 10s window |
| `BaseFeeChangeDenominator` | 36 | 36 | Controls base fee adjustment speed |
| `MinBlockGasCost` | 0 | 0 | Minimum block gas cost |
| `MaxBlockGasCost` | 1,000,000 | 1,000,000 | Maximum block gas cost |
| `BlockGasCostStep` | 200,000 | 200,000 | Block gas cost adjustment step |
### State Sync
Fast state sync for new nodes joining the network:
- **Client** (`sync/client/`): Fetches state trie from peers in parallel
- **Server** (`sync/statesync/`): Serves state trie data to syncing peers
- **Threshold**: Activates when the chain is 300,000+ blocks ahead of local state
- **Request size**: 1024 key/value pairs per peer request
### Warp Messaging
Cross-chain communication via LP-118 Warp protocol (`warp/`):
- **Aggregator** (`aggregator.go`): Collects BLS signatures from validators for message attestation
- **Signer** (`signer_adapter.go`): Signs outgoing Warp messages
- **Verifier** (`verifier_backend.go`): Validates incoming Warp messages against validator signatures
- **Contract**: The Warp precompile at `0x16201` provides `sendWarpMessage()` and `getVerifiedWarpMessage()`
- **Legacy address**: `0x0200000000000000000000000000000000000005` (C-Chain backward compat)
## API Namespaces
| Namespace | Enabled | Purpose |
| Namespace | Default | Purpose |
|-----------|---------|---------|
| `eth` | Default | Standard Ethereum JSON-RPC |
| `personal` | Manual | Account management |
| `txpool` | Manual | Transaction pool inspection |
| `debug` | Manual | Debugging and tracing |
| `eth` | Enabled | Standard Ethereum JSON-RPC (blocks, txs, receipts, logs) |
| `eth-filter` | Enabled | Log and block filter subscriptions |
| `net` | Enabled | Network info (version, peer count) |
| `web3` | Enabled | Client version, SHA3 |
| `internal-eth` | Enabled | Internal Ethereum APIs |
| `internal-blockchain` | Enabled | Internal blockchain APIs |
| `internal-transaction` | Enabled | Internal transaction APIs |
| `debug` | Disabled | Tracing, stack dumps, memory stats |
| `admin` | Enabled | Import/export chain, CPU profiling |
| `personal` | Disabled | Account management (sign, unlock) |
| `txpool` | Disabled | Transaction pool inspection |
## Key Dependencies
### Lux-Specific API Endpoints
```
github.com/luxfi/[email protected] — Quasar consensus
github.com/luxfi/[email protected] — Cryptographic primitives
github.com/luxfi/[email protected] — Go Ethereum fork (NOT go-ethereum)
github.com/luxfi/[email protected] — Storage
github.com/luxfi/[email protected] — Precompile framework
github.com/luxfi/[email protected] — Cross-chain messaging
github.com/luxfi/[email protected] — FHE support in EVM
github.com/luxfi/[email protected] — Node integration
POST /ext/bc/C/rpc -- Standard EVM JSON-RPC
WS /ext/bc/C/ws -- WebSocket subscriptions
POST /ext/bc/C/lux -- Lux-specific APIs (validators)
POST /ext/bc/C/admin -- Admin APIs (import/export, profiling)
```
## DEX Precompiles
## Key Dependencies (go.mod verified)
Native DEX precompiles at reserved addresses:
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/geth` | v1.16.75 | Go Ethereum fork (core EVM, types, RLP, trie) |
| `github.com/luxfi/consensus` | v1.22.67 | Quasar consensus engine integration |
| `github.com/luxfi/crypto` | v1.17.40 | BLS, secp256k1, ML-KEM, ML-DSA |
| `github.com/luxfi/database` | v1.17.43 | Storage layer (BadgerDB, PebbleDB, VersionDB) |
| `github.com/luxfi/precompile` | v0.4.6 | External precompile registry |
| `github.com/luxfi/warp` | v1.18.5 | Cross-chain Warp messaging |
| `github.com/luxfi/p2p` | v1.19.2-zap | ZAP P2P transport for gossip |
| `github.com/luxfi/vm` | v1.0.39 | VM interface (ChainVM) |
| `github.com/luxfi/fhe` | v1.7.6 | FHE coprocessor support (TFHE) |
| `github.com/luxfi/node` | v1.23.4 | Node integration (version, constants) |
| `github.com/luxfi/ids` | v1.2.9 | ID types (BlockID, TxID, ChainID) |
| `github.com/luxfi/lattice/v7` | v7.0.0 | Post-quantum lattice cryptography |
| `github.com/luxfi/log` | v1.4.1 | Structured logging |
| `github.com/luxfi/upgrade` | v1.0.0 | Upgrade activation management |
| Address | Precompile | Purpose |
|---------|------------|---------|
| `0x0400` | PoolManager | AMM pool management |
| `0x0401` | SwapRouter | Swap routing |
| `0x0402` | HooksRegistry | Custom hooks |
| `0x0403` | FlashLoan | Flash loans |
## CLI Tools
| Tool | Path | Purpose |
|------|------|---------|
| `abigen` | `cmd/abigen/` | Generate Go bindings from Solidity ABI |
| `evm` | `cmd/evm/` | Standalone EVM execution and testing |
| `precompilegen` | `cmd/precompilegen/` | Generate precompile boilerplate from ABI |
| `simulator` | `cmd/simulator/` | Local network simulator for testing |
| `export` | `cmd/export/` | Export chain data |
## Configuration
### VM Configuration (JSON)
Passed via chain config in `luxd`:
```json
{
"pruning-enabled": true,
"commit-interval": 4096,
"trie-clean-cache": 512,
"trie-dirty-cache": 512,
"snapshot-cache": 256,
"rpc-gas-cap": 50000000,
"rpc-tx-fee-cap": 100,
"metrics-expensive-enabled": true,
"admin-api-enabled": true,
"validator-api-enabled": true,
"enabled-eth-apis": ["eth", "eth-filter", "net", "web3", "internal-eth", "internal-blockchain", "internal-transaction"],
"log-level": "info",
"db-type": "badgerdb",
"state-sync-min-blocks": 300000,
"state-sync-request-size": 1024,
"batch-request-limit": 1000,
"batch-response-max-size": 25000000
}
```
### Genesis Configuration
```json
{
"config": {
"chainId": 96369,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"muirGlacierBlock": 0,
"berlinBlock": 0,
"londonBlock": 0,
"shanghaiTime": 0,
"cancunTime": 0,
"feeConfig": {
"gasLimit": 8000000,
"targetBlockRate": 2,
"minBaseFee": 25000000000,
"targetGas": 15000000,
"baseFeeChangeDenominator": 36,
"minBlockGasCost": 0,
"maxBlockGasCost": 1000000,
"blockGasCostStep": 200000
},
"contractDeployerAllowListConfig": {
"adminAddresses": ["0x..."]
}
},
"alloc": {
"0x...": { "balance": "0x..." }
}
}
```
## Block Format Differences from Ethereum
- `BaseFee`: Present (EIP-1559)
- `BlockGasCost`: Surcharge for producing a block faster than the target rate (Lux-specific)
- No uncle/ommer blocks (Lux consensus does not produce forks)
- No difficulty (Quasar finality engine replaces PoW)
## Compatibility
Compatible with standard Ethereum tooling: Remix, MetaMask, Foundry, Hardhat, ethers.js, web3.js, viem.
## Building
```bash
cd ~/work/lux/evm
# Build plugin binary
go build -o evm ./plugin/
# Build with race detector (development)
go build -race -o evm ./plugin/
# Run tests
go test ./...
# Run specific package tests
go test ./core/... -v
go test ./precompile/... -v
# Generate precompile from ABI
go run cmd/precompilegen/main.go --abi path/to/Contract.abi --out precompile/contracts/mycontract/
# Generate ABI bindings
go run cmd/abigen/main.go --abi path/to/Contract.abi --pkg mypackage --out bindings.go
# Run Hardhat tests for Solidity precompile interfaces
cd contracts && npx hardhat test
```
## Troubleshooting
| Problem | Cause | Fix |
|---------|-------|-----|
| `import "github.com/luxfi/coreth"` fails | Deprecated module | Change to `github.com/luxfi/evm` |
| `import "go-ethereum"` fails | Wrong fork | Use `github.com/luxfi/geth` |
| Plugin crashes on startup | Wrong luxd version | Check compat matrix (v1.12.0-v1.13.3) |
| State sync not starting | Chain not far enough behind | Must be 300,000+ blocks behind |
| `unauthorized` on precompile call | Missing AllowList role | Add address as Admin/Enabled via genesis |
| High base fee | Network congestion | Adjust FeeConfig via FeeManager precompile |
| `insufficient gas` errors | Gas limit too low | Increase `GasLimit` in FeeConfig |
| Transaction pool full | Too many pending txs | Increase pool limits or raise gas price |
| Warp message not verified | Insufficient validator sigs | Need 67%+ of validator weight |
| `EVM fork block timestamp` error | Genesis upgrade mismatch | Ensure upgrade timestamps are consistent |
| `github.com/luxfi/precompiles` error | Old excluded module | Use `github.com/luxfi/precompile` (singular) |
## Related Skills
- `lux/lux-node.md` — Core node (runs EVM)
- `lux/lux-dex.md` — CLOB engine integrated via precompiles
- `lux/lux-exchange.md` — DEX frontend
- `lux/lux-bridge.md` — Cross-chain to/from C-Chain
- `lux/lux-node.md` -- Core node that loads and runs the EVM plugin
- `lux/lux-chains.md` -- All chain types in the Lux multi-chain architecture
- `lux/lux-dex.md` -- QuantumSwap DEX engine integrated via precompiles
- `lux/lux-precompile.md` -- Precompile development guide
- `lux/lux-fhe.md` -- FHE coprocessor integration
- `lux/lux-warp.md` -- Cross-chain Warp messaging protocol
- `lux/lux-bridge.md` -- Cross-chain bridging to/from C-Chain
- `lux/lux-sdk.md` -- Go SDK for interacting with the EVM
+680 -61
View File
@@ -1,88 +1,707 @@
---
title: "Lux Exchange - DEX Frontend & Omnichain Routing"
description: "Lux Exchange is the DEX frontend and routing layer — a Uniswap-based interface with native EVM DEX precompiles and CLOB integration via `github.com/luxfi/dex`."
title: "Lux Exchange"
description: "DEX Frontend, Matching Engine & Omnichain Routing"
---
## Overview
Lux Exchange is the **DEX frontend and routing layer** — a Uniswap-based interface with native EVM DEX precompiles and CLOB integration via `github.com/luxfi/dex`. Supports AMM swaps, limit orders via CLOB, and cross-chain routing via Warp/Teleport.
Lux Exchange is the full-stack decentralized exchange infrastructure for the Lux Network. It consists of four repositories that together provide: a Uniswap-fork web/mobile frontend, a GraphQL API proxy that unifies on-chain data from V2/V3 subgraphs and Blockscout, a CORS proxy for upstream Uniswap API access, and an in-memory CLOB matching engine SDK. The system supports AMM V2 (constant product), V3 (concentrated liquidity), native DEX precompiles (V4-style singleton PoolManager), and private cross-chain swaps via Z-Chain privacy layer with Pedersen commitments and FHE-encrypted reserves.
This is the **frontend/routing layer**. The high-performance order matching engine is at `github.com/luxfi/dex` (separate skill).
## Repository Map
## Quick reference
| Repo | Path | Module | Language | Purpose |
|------|------|--------|----------|---------|
| **exchange** | `~/work/lux/exchange/` | `github.com/luxfi/exchange` | TypeScript | Nx monorepo: web/mobile/extension frontend + all SDK packages |
| **exchange-api** | `~/work/lux/exchange-api/` | `@luxfi/exchange-api` v0.1.0 | TypeScript | GraphQL proxy: routes Lux/Zoo queries to subgraphs, proxies rest to Uniswap |
| **exchange-sdk** | `~/work/lux/exchange-sdk/` | `@hanzo/matching-engine` v1.0.1 | TypeScript | CLOB order book engine with Fibonacci heap matching |
| **exchange-proxy** | `~/work/lux/exchange-proxy/` | `github.com/luxfi/exchange-proxy` | Go 1.23 | CORS reverse proxy to Uniswap API endpoints with in-memory TTL cache |
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/exchange` |
| Language | TypeScript |
| Runtime | Bun (required) |
| Build | Nx workspace |
| URL | lux.exchange |
| Frontend URL | `lux.exchange` |
| API Proxy Port | `:4000` (exchange-api) |
| CORS Proxy Port | `:8088` (exchange-proxy) |
| CLOB Engine Port | `:4000` (exchange-sdk server) |
| Runtime | Bun 1.3.1+ / Node 22.13.1 |
| Build System | Nx 22.2.0 with bun workspaces |
| Framework | Next.js (App Router) / Vite SPA for production |
| React | 19.0.3 |
| Web3 | wagmi, viem 2.30.5 |
| UI | Tamagui (cross-platform) + Tailwind CSS 4.1.18 |
| State | Zustand (persisted) |
| Data | React Query (@tanstack/query-core 5.90.20) |
| Container | `node:22-alpine`, serve@14, port 3000 |
| Solidity | 0.8.20 (Shanghai EVM, Foundry) |
| License | GPL-3.0-or-later |
## Components
| Component | Repo | Purpose |
|-----------|------|---------|
| exchange | `github.com/luxfi/exchange` | DEX web/mobile UI |
| exchange-api | `github.com/luxfi/exchange-api` | DEX API service |
| exchange-proxy | `github.com/luxfi/exchange-proxy` | DEX router |
| exchange-sdk | `github.com/luxfi/exchange-sdk` | Exchange SDK |
## DEX Precompiles (Native EVM)
Lux C-Chain includes native DEX precompiles at reserved addresses:
| Precompile | Address | Purpose |
|------------|---------|---------|
| **PoolManager** | `0x0400` | AMM pool creation and management |
| **SwapRouter** | `0x0401` | Swap routing (AMM + CLOB) |
| **HooksRegistry** | `0x0402` | Custom swap hooks (fees, oracles, etc.) |
| **FlashLoan** | `0x0403` | Flash loan facility |
These precompiles execute at native speed (no EVM interpretation overhead).
## Omnichain Routing
## Architecture
```
User Order
↓
┌──────────────────┐
│ Omnichain Router │
├──────────────────┤
│ 1. Check AMM pools│ → PoolManager (0x0400)
│ 2. Check CLOB │ → luxfi/dex engine
│ 3. Cross-chain │ → Warp/Teleport messaging
│ 4. Best execution │ → Route to optimal venue
└──────────────────┘
↓
Execution Report
lux.exchange (frontend)
|
+------------+------------+
| |
exchange-api (:4000) exchange-proxy (:8088)
GraphQL proxy CORS reverse proxy
| |
+---------+---------+ +-------+-------+
| | | | | |
Subgraph Subgraph Blockscout Uniswap APIs (4 upstreams)
V2 V3 Explorer api / liquidity / gateway / conversion
| | |
Lux C-Chain (96369)
V2 Factory V3 Factory DEX Precompiles (LP-9xxx)
|
exchange-sdk (CLOB engine)
In-memory order book matching
```
## Key Dependencies
### Request Routing (exchange-api)
The API proxy inspects every GraphQL request's `variables.chain` field:
- **`LUX` or `ZOO`**: Handled natively by querying V2/V3 subgraphs at `subgraph.lux.network` and Blockscout at `api-explore.lux.network`
- **All other chains**: Proxied to `interface.gateway.uniswap.org` with `Origin: https://app.uniswap.org`
Supported native operations: `TopTokens`, `Token`, `TokenPrice`, `TopV2Pairs`, `TopV3Pools`, `V2Transactions`, `V3Transactions`, `HistoricalProtocolVolume`, `DailyProtocolTvl`, `IsV3SubgraphStale`
### CORS Proxy Upstreams (exchange-proxy)
| Path Prefix | Upstream | Cache TTL |
|-------------|----------|-----------|
| `/uniswap/` | `api.uniswap.org` | 15s default |
| `/liquidity/` | `liquidity.backend-prod.api.uniswap.org` | 15s default |
| `/gateway/` | `interface.gateway.uniswap.org` | 15s default |
| `/conversion/` | `entry-gateway.backend-prod.api.uniswap.org` | 15s default |
Cache strategy: tokens/chains 5min, pools/positions 30s, quotes/prices 5s, GraphQL 10s.
## Monorepo Structure (exchange)
```
@uniswap/router-sdk — Uniswap routing logic
@uniswap/sdk-core — Core DEX types
@uniswap/v2-sdk — V2 AMM integration
react@19 — UI framework
[email protected] — Mobile app
[email protected] — Ethereum client
tamagui — Cross-platform UI
~/work/lux/exchange/
+-- apps/
| +-- web/ Next.js App Router (swap/, pool/, tokens/ pages)
| +-- mobile/ React Native 0.79.5
| +-- extension/ Browser extension
| +-- market/ Market data app
| +-- build/ Build tooling
| +-- cli/ CLI tools
| +-- api-self-serve/ Self-serve API
+-- packages/
| +-- exchange/ Core DEX logic: tokens, hooks, stores, ABIs, bridge
| +-- config/ Chain definitions, contract addresses, wagmi config
| +-- ui/ Tamagui components (Button, Card, TokenLogo)
| +-- api/ React Query client + data hooks
| +-- lx/ Business logic (swap utils, G-Chain integration, i18n)
| +-- wallet/ Wallet connection logic
| +-- luxamm-sdk-core/ @luxamm/sdk-core (pre-built Uniswap SDK fork)
| +-- luxamm-v2-sdk/ @luxamm/v2-sdk (pre-built)
| +-- luxamm-v3-sdk/ @luxamm/v3-sdk (pre-built)
| +-- luxamm-v4-sdk/ @luxamm/v4-sdk (pre-built)
| +-- luxdex-sdk/ @luxdex/sdk (pre-built router SDK)
| +-- luxdex-analytics/ Analytics package
| +-- prices/ Price service
| +-- sessions/ Session management
| +-- notifications/ Push notifications
| +-- gating/ Feature gating
| +-- mycelium/ PubSub/messaging
| +-- websocket/ WebSocket service
| +-- utilities/ Shared utilities
| +-- biome-config/ Code formatting config
| +-- eslint-config/ Lint config
+-- contracts/
| +-- LuxToken.sol Mintable ERC20 for bridged assets (LETH, LBTC, LUSD)
| +-- WLUX.sol Wrapped LUX (WETH-style deposit/withdraw)
+-- config/ Build configuration
```
## DeFi Ecosystem
### Package Dependency Graph
```
@luxfi/web (apps/web)
+-- @luxfi/exchange (packages/exchange)
| +-- @luxfi/config
| +-- viem, wagmi
+-- @luxfi/ui (packages/ui)
| +-- @luxfi/config
+-- @luxfi/api (packages/api)
+-- lx (packages/lx)
+-- @apollo/client
+-- @luxamm/sdk-core, v2-sdk, v3-sdk, v4-sdk
+-- @luxdex/sdk
```
## Core Concepts
### 1. Supported Chains
| Chain | Chain ID | Native Token | RPC | Explorer |
|-------|----------|-------------|-----|----------|
| Lux Mainnet | 96369 | LUX | `https://api.lux.network/mainnet/ext/bc/C/rpc` | `explore.lux.network` |
| Lux Testnet | 96368 | LUX | `https://api.lux.network/testnet/ext/bc/C/rpc` | `explore.lux-test.network` |
| Zoo Mainnet | 200200 | ZOO | `https://api.zoo.network/rpc` | `explore.zoo.network` |
| Zoo Testnet | 200201 | ZOO | `https://api.zoo-test.network/rpc` | `explore.zoo-test.network` |
| Hanzo Network | 36963 | HANZO | Lux subnet RPC | `explore-hanzo.lux.network` |
| SPC Network | 36911 | SPC | Lux subnet RPC | `explore-spc.lux.network` |
| Pars Network | 494949 | PARS | Lux subnet RPC | `explore-pars.lux.network` |
| Lux Dev | 1337 | LUX | `http://localhost:8545/ext/bc/C/rpc` | local |
All chain definitions are in `packages/config/src/chains.ts` using viem's `defineChain()`.
### 2. Contract Addresses
#### AMM V2 (Constant Product) - Lux Mainnet (96369)
| Contract | Address |
|----------|---------|
| V2 Factory | `0xD173926A10A0C4eCd3A51B1422270b65Df0551c1` |
| V2 Router | `0xAe2cf1E403aAFE6C05A5b8Ef63EB19ba591d8511` |
#### AMM V3 (Concentrated Liquidity) - Lux Mainnet (96369)
| Contract | Address |
|----------|---------|
| V3 Factory | `0x80bBc7C4C7a59C899D1B37BC14539A22D5830a84` |
| SwapRouter | `0xE8fb25086C8652c92f5AF90D730Bac7C63Fc9A58` |
| SwapRouter02 | `0x939bC0Bca6F9B9c52E6e3AD8A3C590b5d9B9D10E` |
| Quoter | `0x12e2B76FaF4dDA5a173a4532916bb6Bfa3645275` |
| QuoterV2 | `0x15C729fdd833Ba675edd466Dfc63E1B737925A4c` |
| NonfungiblePositionManager | `0x7a4C48B9dae0b7c396569b34042fcA604150Ee28` |
#### AMM V2 - Lux Testnet (96368)
| Contract | Address |
|----------|---------|
| V2 Factory | `0x1DD4e6cbC6B8FD032fCAD5A3B0a45e446A014637` |
| V2 Router | `0xb06B31521Afc434F87Fe4852c98FC15A26c92aE8` |
#### AMM V2 - Zoo Mainnet (200200)
| Contract | Address |
|----------|---------|
| V2 Factory | `0xF034942c1140125b5c278aE9cEE1B488e915B2FE` |
| V2 Router | `0x2cd306913e6546C59249b48d7c786A6D1d7ebE08` |
#### AMM V2 - Hanzo Network (36963)
| Contract | Address |
|----------|---------|
| V2 Factory | `0xDc384E006BAec602b0b2B2fe6f2712646EFb1e9D` |
| V2 Router | `0x191067f88d61f9506555E88CEab9CF71deeD61A9` |
#### AMM V2 - Pars Network (494949)
| Contract | Address |
|----------|---------|
| V2 Factory | `0x84CF0A13db1be8e1F0676405cfcBC8b09692FD1C` |
| V2 Router | `0x2382F7A49FA48E1F91Bec466c32e1D7F13ec8206` |
#### AMM V2 - Lux Dev (1337)
| Contract | Address |
|----------|---------|
| V2 Factory | `0x959922bE3CAee4b8Cd9a407cc3ac1C251C2007B1` |
| V2 Router | `0x9A9f2CCfdE556A7E9Ff0848998Aa4a0CFD8863AE` |
#### Governance & DeFi - Lux Mainnet
| Contract | Address | Purpose |
|----------|---------|---------|
| Staked LUX | `0xc606302cd0722DD42c460B09930477d09993F913` | Staking |
| vLUX | `0x55833074AD22E2aAE81ad377A600340eC0bc7cbd` | Vote-escrowed LUX |
| KARMA | `0xc3d1efb6Eaedd048dDfE7066F1c719C7B6Ca43ad` | Rewards token |
| dLUX | `0xAAbD65c4Fe3d3f9d54A7C3C7B95B9eD359CC52A8` | Delegated LUX |
| Markets | `0x308EBD39eB5E27980944630A0af6F8B0d19e31C6` | Lending/Borrowing |
| Perp | `0x82312E295533Ab5167B306d5aBF7F3eB2C0D95fD` | Perpetual futures |
All contract addresses are in `packages/config/src/contracts.ts`. Use `getContracts(chainId)` to look up by chain.
### 3. DEX Precompiles (Native AMM)
Native Go precompiles at reserved addresses for sub-microsecond execution. V4-style singleton PoolManager design.
| Precompile | LP | Address | Purpose |
|------------|-----|---------|---------|
| PoolManager | LP-9010 | `0x...9010` | Pool creation and state management |
| OracleHub | LP-9011 | `0x...9011` | Multi-source price aggregation |
| SwapRouter | LP-9012 | `0x...9012` | Swap execution and routing |
| HooksRegistry | LP-9013 | `0x...9013` | Custom swap hooks |
| FlashLoan | LP-9014 | `0x...9014` | Flash loan facility |
| CLOB | LP-9020 | `0x...9020` | Central Limit Order Book |
| Vault | LP-9030 | `0x...9030` | Vault management |
| PriceFeed | LP-9040 | `0x...9040` | Price feed oracle |
| Teleport | LP-6010 | `0x...6010` | Cross-chain teleportation |
Enable in `~/.lux/chain-configs/C/config.json`:
```json
{
"dexConfig": {
"upgrade": { "blockTimestamp": 0 },
"enableFlashLoans": true,
"enableHooks": true,
"maxPools": 10000
}
}
```
### 4. Fee Structure
AMM fees are expressed in hundredths of a basis point:
| Fee Tier | Value | Percentage | Tick Spacing | Use Case |
|----------|-------|-----------|--------------|----------|
| LOWEST | 100 | 0.01% | 1 | Stablecoin pairs |
| LOW | 500 | 0.05% | 10 | Correlated assets |
| MEDIUM | 3000 | 0.30% | 60 | Standard pairs |
| HIGH | 10000 | 1.00% | 200 | Exotic/volatile |
Default fee tier for swap hooks: 3000 (0.30%).
### 5. Token Registry
#### Lux Mainnet Native/Wrapped Tokens
| Symbol | Address | Decimals | Type |
|--------|---------|----------|------|
| LUX | `0x0000...0000` (native) | 18 | Gas token |
| WLUX | `0x4888E4a2Ee0F03051c72d2BD3ACf755eD3498B3E` | 18 | Wrapped native |
| USDC | `0xF85CF66Fd0189C435033056edeC5e525F39374a6` | 6 | Bridged stablecoin |
| LETH | `0x60E0a8167FC13dE89348978860466C9ceC24B9ba` | 18 | Bridged ETH |
| LBTC | `0x1E48D32a4F5e9f08DB9aE4959163300FaF8A6C8e` | 8 | Bridged BTC |
| LSOL | `0x26B40f650156C7EbF9e087Dd0dca181Fe87625B7` | 18 | Bridged SOL |
| LTON | `0x3141b94b89691009b950c96e97Bff48e0C543E3C` | 9 | Bridged TON |
| LAVAX | `0x0e4bD0DD67c15dECfBBBdbbE07FC9d51D737693D` | 18 | Bridged AVAX |
| LBNB | `0x6EdcF3645DeF09DB45050638c41157D8B9FEa1cf` | 18 | Bridged BNB |
| LPOL | `0x28BfC5DD4B7E15659e41190983e5fE3df1132bB9` | 18 | Bridged POL |
| LUSD | `0x848Cff46eb323f323b6Bbe1Df274E40793d7f2c2` | 18 | Lux Dollar |
Full token list with 20+ tokens in `exchange-api/src/lux-tokens.ts`.
#### Zoo Mainnet Tokens
| Symbol | Address | Decimals |
|--------|---------|----------|
| ZOO | `0x0000...0000` (native) | 18 |
| WZOO | `0x5491216406daB99b7032b83765F36790E27F8A61` | 18 |
| LETH | `0x4870621EA8be7a383eFCfdA225249d35888bD9f2` | 18 |
| LBTC | `0x6fc44509a32E513bE1aa00d27bb298e63830C6A8` | 8 |
| LUSD | `0xb2ee1CE7b84853b83AA08702aD0aD4D79711882D` | 18 |
### 6. Swap Routing
The frontend uses a layered routing strategy:
1. **LuxGatewayClient** wraps TradingApiClient to intercept Lux/Zoo chain queries
2. For chainId 96369 (Lux) or 200200 (Zoo): route to Lux DEX Gateway (`dex.lux.network`)
3. For all other chains: forward to Uniswap TradingAPI
4. On gateway failure: fallback to TradingAPI
Gateway endpoints:
```
POST /v1/quote -- Get swap quote
POST /v1/quotes -- Batch quotes
POST /v1/swap -- Build swap transaction
GET /v1/pools -- List pools
GET /v1/tokens -- List tokens
GET /v1/price -- Token price
```
Quote request format:
```json
{
"tokenIn": "0x0000000000000000000000000000000000000000",
"tokenOut": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"amount": "1000000000000000000",
"isExactIn": true,
"chainId": 96369
}
```
### 7. Liquidity Pool Operations
V3 pools support concentrated liquidity positions with NFT-based position management.
#### Pool Key (V4-style)
```typescript
interface PoolKey {
currency0: Address // Lower address token
currency1: Address // Higher address token
fee: number // Fee in hundredths of a bip
tickSpacing: number // Tick spacing for the fee tier
hooks: Address // Hook contract (0x0 = no hooks)
}
```
Pool ID is computed as `keccak256(abi.encode(currency0, currency1, fee, tickSpacing, hooks))`.
#### Position Management
Positions are NFTs managed by the NonfungiblePositionManager:
- `balanceOf(owner)` returns position count
- `tokenOfOwnerByIndex(owner, i)` returns NFT token ID
- `positions(tokenId)` returns full position state (token0, token1, fee, tickLower, tickUpper, liquidity, tokensOwed0, tokensOwed1)
### 8. SDK Usage (@luxfi/exchange)
```typescript
import { useSwap, useSwapQuote, usePools, usePositions } from '@luxfi/exchange'
import { useSwapStore } from '@luxfi/exchange'
import { getContracts, getTokensForChain } from '@luxfi/exchange'
import { createPoolKey, computePoolId } from '@luxfi/exchange'
// Get swap quote from V3 QuoterV2
const { data: quote } = useSwapQuote({
tokenIn: NATIVE_LUX,
tokenOut: LETH,
amountIn: parseUnits('1', 18),
chainId: 96369,
})
// Execute swap via V3 SwapRouter02
const { swap, isPending } = useSwap()
await swap({
tokenIn: NATIVE_LUX,
tokenOut: LETH,
amountIn: parseUnits('1', 18),
amountOutMinimum: quote.amountOut * 995n / 1000n, // 0.5% slippage
recipient: address,
deadline: BigInt(Math.floor(Date.now() / 1000) + 1800),
chainId: 96369,
})
// Zustand swap store (persisted slippage/deadline settings)
const { tokenIn, setTokenIn, slippageTolerance, switchTokens } = useSwapStore()
// Get all V3 pools for a pair (queries all 4 fee tiers)
const { pools, bestPool } = usePools(token0, token1, 96369)
// Get user positions
const { data: positions } = usePositions(userAddress, 96369)
```
### 9. Cross-Chain Bridge (Warp/Teleport)
Standard cross-chain minting:
```typescript
import { useCrossChainMint } from '@luxfi/exchange/bridge'
const { mint } = useCrossChainMint()
await mint({
sourceAsset: xvmAssetId,
amount: 1000000n,
recipient: cChainAddress,
targetToken: tokenAddress, // Optional swap on arrival
minReceive: 990000n,
deadline: Math.floor(Date.now() / 1000) + 3600,
})
```
Status flow: `idle` -> `initiating` -> `locking` -> `waiting_confirmation` -> `minting` -> `swapping` -> `complete`
Warp precompile: `0x0200000000000000000000000000000000000005`
Bridge contract: `0x0000000000000000000000000000000000000410`
### 10. Private Teleport (Z-Chain Privacy Layer)
Fully shielded cross-chain swaps using:
- **Pedersen Commitments**: Hide amounts
- **FHE-encrypted reserves**: Z-Chain AMM pools have encrypted state
- **ZNotes**: UTXO-style shielded notes with Merkle tree membership
- **Bulletproof range proofs**: For withdrawal verification
- **Nullifiers**: Prevent double-spending
Flow: `XVM UTXO -> Warp -> ZNote (shielded) -> Z-Chain AMM (private swap) -> C-Chain/XVM`
Contract addresses:
| Contract | Address |
|----------|---------|
| PrivateTeleport | `0x...0420` |
| ZNote | `0x...0421` |
| ZChainAMM | `0x...0422` |
| PrivateBridge | `0x...0423` |
Teleport states: `INITIATED(0)` -> `SHIELDED(1)` -> `SWAP_COMPLETE(2)` -> `EXPORTED(3)` -> `COMPLETED(4)`
```typescript
import { usePrivateTeleport } from '@luxfi/exchange/bridge'
const { teleport, executeSwap, exportToDestination } = usePrivateTeleport()
const teleportId = await teleport({
sourceChain: LUX_CHAINS.xChain.chainId,
destChain: LUX_CHAINS.cChain.chainId,
sourceAsset: assetId,
amount: 1000000n, // Will be encrypted
recipient: address,
deadline: Math.floor(Date.now() / 1000) + 3600,
privateSwap: true,
})
await executeSwap(teleportId, poolId, minOutput)
await exportToDestination(teleportId)
```
### 11. CLOB Matching Engine (exchange-sdk)
The `@hanzo/matching-engine` package provides a full order book implementation:
- **Data structures**: Fibonacci heaps for bid/ask priority queues, AVL trees for order book rendering
- **Order types**: `LIMIT` and `MARKET`
- **Order sides**: `BID` and `ASK`
- **Matching**: Price-time priority. Aggressive limit orders take the older order's price
- **Partial fills**: Remainder orders are re-inserted into the book
- **Candles**: OHLCV aggregation at 1m/1h/1d/1w intervals using AVL trees
- **Real-time**: Socket.IO server broadcasts order book and trade data at 500ms intervals
- **HTTP API**: REST endpoints for order submission and order book queries
- **Precision**: `decimal.js` for all price/quantity calculations
```typescript
import { Book, Order, OrderSide, OrderType, Candle, CandleAVL } from '@hanzo/matching-engine'
const book = new Book('LUX/USDC')
book.addOrder(new Order('ext-1', OrderSide.BID, OrderType.LIMIT, 100, '42.50'))
book.addOrder(new Order('ext-2', OrderSide.ASK, OrderType.LIMIT, 50, '42.50'))
const trades = book.settle()
// trades[0].fillPrice = 42.50, fillQuantity = 50
// Continuous execution loop (uses requestAnimationFrame)
const ctx = book.start((book, trades) => {
console.log(`Trades: ${trades.length}, Spread: ${book.displaySpread}`)
})
ctx.stop() // Stop execution
```
HTTP endpoints (`:4000`):
```
POST /:name/orders -- Submit order { externalId, side, type, quantity, price }
PUT /:name/orders -- Same as POST
GET /:name/orders -- Get order book { bids: [[price, qty]], asks: [[price, qty]] }
GET /:name/candles/:interval -- Get candles (1m, 1h, 1d)
```
Socket.IO events:
```
book.subscribe { name } -- Subscribe to order book updates
book.data -- Order book broadcast (every 500ms)
trade.subscribe { name } -- Subscribe to trade feed
trade.data -- Trade executions
order.create -- Submit order via WebSocket
candles.get -- Request historical candles
```
### 12. Data Sources
| Source | URL | Data |
|--------|-----|------|
| V2 Subgraph | `subgraph.lux.network/subgraphs/name/luxfi/uniswap-v2` | Pairs, reserves, swaps, token prices |
| V3 Subgraph | `subgraph.lux.network/subgraphs/name/luxfi/uniswap-v3` | Pools, ticks, positions, concentrated liquidity |
| Blockscout | `api-explore.lux.network/api/v2/tokens` | ERC-20 token metadata, holder counts |
| G-Chain GraphQL | `localhost:9630/ext/bc/G/graphql` | Native blockchain data (blocks, accounts, balances) |
| DEX Gateway | `dex.lux.network` | Unified quote/swap API |
### 13. Smart Contracts
#### LuxToken.sol
Mintable ERC20 for bridged assets. Owner-only `mint()`, public `burn()`, unlimited approval support (`type(uint256).max`). Used for LETH, LBTC, LUSD, LSOL, etc.
#### WLUX.sol
Standard WETH-style wrapper for native LUX. `deposit()` via payable function or `receive()` fallback. `withdraw(wad)` returns native LUX. `totalSupply()` returns contract's native balance.
## Development
### Prerequisites
```bash
# Required: Bun 1.3.1+, Node 22.13.1
bun --version # Must be >= 1.3.1
node --version # Must be 22.13.1
```
### Exchange (Frontend)
```bash
cd ~/work/lux/exchange
bun install
bun run g:prepare # Generate code
bun run web dev # Start web dev server
# Build for production (Vite SPA)
cd apps/web && ../../node_modules/.bin/vite build
# Run tests
bun run g:test
bun run g:typecheck
# Docker build
docker build -f Dockerfile.k8s -t lux-exchange .
```
### Exchange API
```bash
cd ~/work/lux/exchange-api
npm install
npm run dev # tsx watch mode on :4000
npm run build && npm start # Production
# Environment
BLOCKSCOUT_API=https://api-explore.lux.network
SUBGRAPH_URL=https://subgraph.lux.network/subgraphs/name/luxfi/uniswap-v2
SUBGRAPH_V3_URL=https://subgraph.lux.network/subgraphs/name/luxfi/uniswap-v3
UNISWAP_API=https://interface.gateway.uniswap.org/v1/graphql
PORT=4000
```
### Exchange SDK (CLOB Engine)
```bash
cd ~/work/lux/exchange-sdk
npm install
npm test # Jest unit tests
npm run build # Rollup build (CJS + ESM + UMD + types)
npm run serve # Start CLOB server on :4000
npm run watch # Dev mode with auto-rebuild
```
### Exchange Proxy
```bash
cd ~/work/lux/exchange-proxy
go build -o exchange-proxy .
./exchange-proxy -addr :8088
./exchange-proxy -addr :8088 -redis redis://localhost:6379 # With distributed cache
```
### Local Dev Network
```bash
lux dev start # Single-node, port 8545, chain ID 1337
# Pre-funded account: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
```
## Subgraph Data Layer
### Caching Strategy (exchange-api)
| TTL | Seconds | Data Type |
|-----|---------|-----------|
| SHORT | 30 | Prices, volumes, swaps |
| MEDIUM | 300 | Token lists, pool lists |
| LONG | 3600 | Token metadata, logos |
| PROXY | 60 | Proxied Uniswap responses |
In-memory `Map<string, CacheEntry>` with periodic janitor cleanup every 60 seconds.
### Price Computation
1. Query V3 bundle for `ethPriceUSD`, fallback to V2 bundle `ethPrice` (these are LUX/USD prices)
2. Token price = `derivedETH * ethPrice`
3. Stablecoins (USDT, USDC, LUSD, DAI, BUSD) force-pinned to $1.00
4. Prices > $1T and volumes > $1T are zeroed (decimal overflow protection)
## Key Dependencies (Exact Versions)
### Exchange (root package.json)
| Package | Version | Purpose |
|---------|---------|---------|
| react | 19.0.3 | UI framework (resolution) |
| react-dom | 19.0.3 | DOM rendering |
| viem | 2.30.5 | Ethereum client |
| typescript | 5.8.3 | Type system |
| nx | 22.2.0 | Build orchestration |
| tailwindcss | 4.1.18 | CSS framework |
| @biomejs/biome | 2.2.0 | Code formatting |
| zod | 4.3.6 | Schema validation (patched for CSP) |
| react-native | 0.79.5 | Mobile framework |
### LuxAMM SDK Packages
| Package | Version | Base |
|---------|---------|------|
| @luxamm/sdk-core | pre-built | Uniswap SDK Core fork |
| @luxamm/v2-sdk | pre-built | Uniswap V2 SDK fork |
| @luxamm/v3-sdk | pre-built | Uniswap V3 SDK fork |
| @luxamm/v4-sdk | pre-built | Uniswap V4 SDK fork |
| @luxdex/sdk | pre-built | Uniswap Router SDK fork |
### Exchange API
| Package | Version |
|---------|---------|
| express | ^4.21.0 |
| node-fetch | ^2.7.0 |
| tsx | ^4.19.0 |
| typescript | ^5.6.0 |
### Exchange SDK (Matching Engine)
| Package | Version | Purpose |
|---------|---------|---------|
| decimal.js | 10.2.0 | Arbitrary precision math |
| mnemonist | 0.30.0 | Fibonacci heap |
| avl | 1.4.4 | AVL tree (order book) |
| socket.io | ^2.3.0 | Real-time WebSocket |
| express | 4.17.1 | HTTP server |
| fast-memoize | 2.5.1 | Candle time slice caching |
| moment | 2.24.0 | Time handling |
### Exchange Proxy
| Dependency | Version |
|------------|---------|
| Go | 1.23 |
| stdlib only | net/http, crypto/sha256, sync |
## Deployment
### Docker (K8s)
Exchange frontend deploys as a static SPA served by `serve@14`:
```dockerfile
# Build: bun install + vite build
# Run: serve -s public -l 3000
```
Key build-time env vars:
```
NEXT_PUBLIC_LXD_GATEWAY_URL=https://dex.lux.network
REACT_APP_AWS_API_ENDPOINT=https://api-exchange.lux.network/v1/graphql
```
### K8s Ingress
```
lux.exchange -> exchange frontend (:3000)
api-exchange.lux.network -> exchange-api (:4000)
```
## DeFi Ecosystem Integration
| Component | Repo | Description |
|-----------|------|-------------|
| Markets | `github.com/luxfi/markets` | Morpho Blue lending/borrowing |
| V2 Subgraph | `github.com/luxfi/uni-v2-subgraph` | V2 AMM indexer |
| V3 Subgraph | `github.com/luxfi/uni-v3-subgraph` | V3 concentrated liquidity indexer |
| Standard Contracts | `github.com/luxfi/standard` | V2/V3 AMM deployment scripts |
| Markets (Morpho Blue) | `github.com/luxfi/markets` | Lending/borrowing protocol |
| V2 Subgraph | `github.com/luxfi/uni-v2-subgraph` | V2 pair indexer |
| V3 Subgraph | `github.com/luxfi/uni-v3-subgraph` | V3 pool indexer |
| V4 Subgraph | `github.com/luxfi/uni-v4-subgraph` | V4 hooks indexer |
| DEX Gateway | `github.com/luxfi/dex` | Go gateway service |
## Known Issues
- `@uniswap/router-sdk` internally depends on `@uniswap/*` SDKs, causing TypeScript errors when types cross boundaries with `@luxamm/*`. Workaround: type assertions (`as unknown as`) in swap analytics and trading utilities.
- ~212 type errors remain in UI components due to SDK type mismatches (do not affect runtime).
- SPC Mainnet (36911) deployment blocked -- genesis key unknown.
- Backend API URLs (`api.uniswap.org`, `liquidity.backend-prod.api.uniswap.org`) still point to Uniswap infrastructure for non-Lux chains.
## Related Skills
- `lux/lux-dex.md` — CLOB engine (434M orders/sec)
- `lux/lux-evm.md` — EVM with DEX precompiles
- `lux/lux-oracle.md` — Price feeds
- `lux/lux-bridge.md` — Cross-chain routing
- `lux/lux-dex.md` -- CLOB engine and DEX gateway (Go)
- `lux/lux-evm.md` -- EVM with DEX precompiles
- `lux/lux-oracle.md` -- Price feed oracles
- `lux/lux-bridge.md` -- Cross-chain routing via Warp
- `lux/lux-standard.md` -- AMM contract deployments
- `lux/lux-teleport.md` -- Teleporter protocol
+230 -14
View File
@@ -1,23 +1,239 @@
---
title: "Lux Explorer - Block Explorer"
description: "## Components"
title: "Lux Explorer"
description: "Multi-Chain Block Explorer"
---
## Overview
Lux Explorer is a **Blockscout-based block explorer** for browsing transactions, contracts, tokens, and network activity on Lux Network.
Lux Explorer is a **Blockscout-based block explorer** for browsing transactions, contracts, tokens, and network activity across the Lux ecosystem. It is an Elixir/OTP umbrella application forked from Blockscout v10.0.1, extended with multi-chain compose files, Lux branding, and per-network JSON configuration for LUX, Zoo, SPC, Hanzo, and testnet deployments.
## Components
**Repository**: `github.com/luxfi/explorer`
**License**: GPL-3.0
| Component | Path | Purpose |
|-----------|------|---------|
| explorer/ | ``github.com/luxfi/explorer`` | Blockscout backend |
| explore/ | ``github.com/luxfi/explore`` | Next.js frontend |
## Technology Stack
## Features
| Component | Version | Notes |
|-----------|---------|-------|
| Elixir | ~> 1.19 | All umbrella apps pin `elixir: "~> 1.19"` |
| Erlang/OTP | 27.3.4.6 | Docker base: `hexpm/elixir:1.19.4-erlang-27.3.4.6-alpine-3.22.2` |
| Phoenix | 1.6.16 | Exact pin in `block_scout_web/mix.exs` |
| Phoenix LiveView | ~> 1.1 | Real-time UI updates |
| Ecto | ~> 3.3 | PostgreSQL ORM, override for cross-app compatibility |
| PostgreSQL | 14+ | One database per chain (e.g., `explorer_luxnet`, `explorer_zoonet`) |
| Blockscout | 10.0.1 | All umbrella apps at version 10.0.1 |
| Alpine Linux | 3.22.2 | Runtime image base |
- Transaction search and details
- Contract verification and source code
- Token tracking (ERC20/721/1155)
- Network statistics and charts
- API for programmatic access
## Architecture
### Umbrella Apps
The project is an OTP umbrella with 6 apps under `apps/`:
| App | Module | Purpose |
|-----|--------|---------|
| `block_scout_web` | `BlockScoutWeb` | Phoenix web API and UI (GraphQL, REST v2, WebSocket) |
| `ethereum_jsonrpc` | `EthereumJSONRPC` | JSON-RPC client for EVM nodes (HTTP, WebSocket) |
| `explorer` | `Explorer` | Data layer -- Ecto schemas, chain queries, caches |
| `indexer` | `Indexer` | Fetchers that pull data from RPC and write to DB |
| `utils` | `Utils` | Shared utilities (HTTP, MIME, Tesla) |
| `nft_media_handler` | `NFTMediaHandler` | NFT image/video processing (S3, eVision) |
### Database Schema
318 Ecto migrations from `20180117` through `20260305`. Core tables include:
- `addresses`, `blocks`, `transactions`, `logs`, `internal_transactions`
- `tokens`, `token_transfers`, `address_current_token_balances`
- `smart_contracts` (verified sources with ABI)
- Chain-specific modules: Arbitrum, Optimism, ZkSync, Beacon, Celo, Filecoin, Polygon zkEVM
### Supported Chain Types
The `CHAIN_TYPE` build arg / env var selects chain-specific modules at compile time:
- Default (EVM-compatible)
- `optimism` -- L2 deposits, withdrawals, output roots
- `arbitrum` -- L2 batches, cross-chain messages
- `polygon_zkevm` -- ZK proofs, batches
- `zksync` -- ZK batches, reader
- `filecoin` -- Filecoin-specific
- `celo` -- Celo-specific
- `blackfort` -- BlackFort-specific
## Supported Networks
### Chain Configurations (`configs/chains/`)
| Network | Chain ID | Currency | Frontend Host | Backend Host |
|---------|----------|----------|--------------|--------------|
| LUX Mainnet | 96369 | LUX | explore.lux.network | api-explore.lux.network |
| LUX Testnet | 96368 | LUX | testnet.explore.lux.network | api-testnet.explore.lux.network |
| Zoo Mainnet | 200200 | ZOO | explore.zoo.network | api-explore.zoo.network |
| SPC Mainnet | 36911 | SPC | explore.spc.network | api-explore.spc.network |
| Hanzo AI | 36963 | HZO | -- | -- |
### Compose Files
Per-network compose files bring up backend, frontend, visualizer, sig-provider, and stats:
| File | Network | Backend Port | Frontend Port |
|------|---------|-------------|---------------|
| `compose.luxnet.yml` | LUX Mainnet | 4000 | 3000 |
| `compose.luxtest.yml` | LUX Testnet | 4010 | 3010 |
| `compose.zoonet.yml` | Zoo Mainnet | 4001 | 3001 |
| `compose.zootest.yml` | Zoo Testnet | 4011 | 3011 |
| `compose.hanzonet.yml` | Hanzo AI | 4003 | 3003 |
### Multi-Chain All-In-One (`docker-compose.all-chains.yml`)
Brings up C-Chain (Blockscout) plus Go indexers for all native chains:
- **C-Chain**: Blockscout backend on port 4000, frontend on port 3000
- **Native chains**: `ghcr.io/luxfi/indexer` image for A, B, P, Q, T, X, Z chains (ports 4100-4700)
- Shared visualizer (8050), sig-provider (8051)
### Microservices (`docker-compose/services/`)
Backend, DB, frontend, NFT media handler, Nginx, Redis, sig-provider, smart-contract-verifier, stats, user-ops-indexer, visualizer.
## Core Concepts
### RPC Integration
The `EthereumJSONRPC` app connects to Lux nodes via SubnetEVM-compatible endpoints:
```
ETHEREUM_JSONRPC_HTTP_URL = http://<luxd>:9650/ext/bc/<blockchain-id>/rpc
ETHEREUM_JSONRPC_WS_URL = ws://<luxd>:9650/ext/bc/<blockchain-id>/ws
ETHEREUM_JSONRPC_VARIANT = geth
```
Each Lux subnet chain has a unique blockchain ID (e.g., `dnmzhuf6poM6PUNQCe7MWWfBdTJEnddhHRNXz2x7H6qSmyBEJ` for LUX mainnet C-Chain).
### Branding
Custom branding lives in `branding/` (logos, favicon) and is applied via:
1. **Dockerfile.luxfi** -- extends official Blockscout image with logo overlays and env defaults
2. **Environment variables** -- `FOOTER_LOGO`, `FOOTER_CHAT_LINK`, `FOOTER_GITHUB_LINK`
### API Surface
- **REST API v2**: `/api/v2/` (blocks, transactions, addresses, tokens, stats)
- **GraphQL**: Absinthe-based (`/graphql`), with Relay-compatible pagination
- **WebSocket**: Phoenix PubSub for real-time block/transaction updates
- **Prometheus**: `/metrics` endpoint via `prometheus_plugs`
### Key Dependencies
| Library | Purpose |
|---------|---------|
| `absinthe` ~> 1.5 | GraphQL toolkit |
| `tesla` ~> 1.16.0 | HTTP client (shared across all apps) |
| `bcrypt_elixir` ~> 3.0 | Password hashing (explorer app) |
| `ex_keccak` ~> 0.7.5 | Keccak-256 hashing |
| `redix` ~> 1.1 | Redis client for caching |
| `hammer` ~> 7.0 | Rate limiting |
| `ueberauth_auth0` ~> 2.0 | Auth0 authentication |
| `spandex` ~> 3.0 | Datadog tracing |
| `ezstd` ~> 1.2 | ZSTD compression |
| `cloak_ecto` ~> 1.3.0 | Ecto field encryption |
### Embedded Go Indexers (`indexers/`)
A small Go module (`github.com/luxfi/explorer-indexers`, Go 1.24.0) inside the explorer repo provides native-chain indexer code for non-EVM chains (A, B, P, Q, T, X, Z). These are lightweight companions to the full Go indexer at `github.com/luxfi/indexer`.
Dependencies: `gorilla/mux` 1.8.1, `gorilla/websocket` 1.5.4, `lib/pq` 1.11.2.
## Development
### Prerequisites
- Elixir 1.19+, Erlang/OTP 27+
- PostgreSQL 14+
- Node.js 16+ (for frontend)
- Running Lux node (luxd) with SubnetEVM
### Build
```bash
# Fetch deps and compile
mix deps.get
mix compile
# Create and migrate database
mix ecto.create
mix ecto.migrate
# Start development server
mix phx.server
```
### Docker
```bash
# Build Lux-branded image
docker build -f docker/Dockerfile.luxfi .
# Or from scratch
docker build -f docker/Dockerfile \
--build-arg CHAIN_TYPE="" \
--build-arg RELEASE_VERSION=10.0.1 \
-t luxfi/explorer:latest .
# Run a network
docker compose -f compose.luxnet.yml up -d
```
### Tests
```bash
# Run all tests (umbrella-wide)
mix test --no-start
# Run specific app tests
cd apps/explorer && mix test
cd apps/block_scout_web && mix test
```
### Environment Variables
Key variables (see `docker-compose/envs/common-blockscout.env`):
| Variable | Purpose | Example |
|----------|---------|---------|
| `DATABASE_URL` | PostgreSQL connection | `postgresql://blockscout:pass@host:5432/explorer_luxnet` |
| `ETHEREUM_JSONRPC_HTTP_URL` | RPC endpoint | `http://luxd:9650/ext/bc/.../rpc` |
| `ETHEREUM_JSONRPC_WS_URL` | WebSocket endpoint | `ws://luxd:9650/ext/bc/.../ws` |
| `ETHEREUM_JSONRPC_VARIANT` | Client type | `geth` |
| `CHAIN_ID` | EVM chain ID | `96369` |
| `COIN_NAME` | Native currency display | `LUX` |
| `PORT` | HTTP server port | `4000` |
| `SECRET_KEY_BASE` | Phoenix secret | 64-char random string |
| `API_V2_ENABLED` | Enable REST v2 | `true` |
| `CHAIN_TYPE` | Chain-specific modules | (empty for default) |
| `DISABLE_WEBAPP` | API-only mode | `true` |
## File Structure
```
explorer/
apps/
block_scout_web/ # Phoenix web app (API + UI)
ethereum_jsonrpc/ # JSON-RPC client library
explorer/ # Data layer (Ecto schemas, 318 migrations)
indexer/ # Data fetchers (blocks, txs, tokens, traces)
nft_media_handler/ # NFT media processing (S3, eVision)
utils/ # Shared utilities
branding/ # Lux logos and favicon
config/ # Elixir config (dev/test/prod/runtime)
configs/chains/ # Per-network JSON config (lux, zoo, spc, lux-testnet)
compose.*.yml # Per-network Docker Compose files
docker/ # Dockerfiles (standard + Lux-branded)
docker-compose/ # Shared compose services and env files
docker-*-mainnet/ # Per-chain Docker Compose dirs (a/b/p/q/t/x/z/zoo)
docker-*-testnet/ # Per-chain testnet Docker Compose dirs
indexers/ # Embedded Go indexers for native chains
mix.exs # Umbrella project (Elixir ~> 1.19, v10.0.1)
Dockerfile # Root Dockerfile (Node.js 16 for frontend)
```
+227 -15
View File
@@ -1,24 +1,236 @@
---
title: "Lux Governance - On-Chain Voting & DAO"
description: "Lux Governance covers on-chain voting, treasury management, and DAO infrastructure for the Lux Network."
title: "Lux Governance"
description: "On-Chain Voting, DAO & Treasury"
---
## Overview
Lux Governance covers **on-chain voting, treasury management, and DAO infrastructure** for the Lux Network. The voting platform is published as `@pars/vote` (under Pars organization, not @luxfi directly).
Lux Governance covers **on-chain voting, treasury management, fractal DAO infrastructure, and identity-based reputation** for the Lux Network. The platform implements a political-terminology governance stack with fractal (nested) DAO support, OHM-style bonding, and soulbound identity integration.
## Components
## Repositories
| Component | Repo | Purpose |
|-----------|------|---------|
| Vote | `github.com/luxfi/vote` | Web voting platform (`@pars/vote`) |
| Treasury | `github.com/luxfi/treasury` | Treasury management |
| DAO | `github.com/luxfi/dao` | DAO infrastructure |
| Repo | Module/Package | Purpose |
|------|----------------|---------|
| `github.com/luxfi/dao` | `@luxfi/contracts`, `@pars/vote` | Full DAO platform (React + Solidity) |
| `github.com/luxfi/lps` | N/A | Lux Proposals (governance specs) |
| `github.com/luxfi/standard` | `@luxfi/standard` | Core governance Solidity contracts (ABIs) |
| `github.com/luxfi/vote` | `@pars/vote` | Web voting frontend |
| `github.com/luxfi/treasury` | N/A | Treasury management |
## Proposals
## Technology Stack
Governance changes are tracked via **LPs** (Lux Proposals) at `github.com/luxfi/lps`:
- **1xxx**: P-Chain proposals (validators, staking)
- **2xxx**: C-Chain proposals (EVM, precompiles)
- **3xxx**: X-Chain proposals (assets)
- **4xxx**: Network proposals (consensus, P2P)
| Layer | Technology |
|-------|------------|
| Frontend | React 18, TypeScript, Vite, Chakra UI |
| Web3 | Wagmi v2, Viem v2, RainbowKit v2 |
| Wallet | `@luxfi/wallet` (omnichain: EVM + Solana) |
| Contracts | Solidity, Hardhat, Foundry (Forge) |
| Testing | Playwright (E2E), Vitest |
| Indexing | The Graph (subgraph) |
| Package Manager | pnpm |
## Contract Architecture (Political Terminology)
The governance stack uses political/diplomatic terms that governments and NGOs understand:
| Contract | Political Analog | Solidity File |
|----------|------------------|---------------|
| `Council` | Legislative Body / Board | `governance/Council.sol` |
| `Charter` | Constitution / Bylaws | `governance/Charter.sol` |
| `Safe` | Treasury / Execution | Gnosis Safe (custody) |
| `Veto` | Veto Power | `governance/Veto.sol` |
| `Sanction` | Enforcement / Sanctions | `governance/Sanction.sol` |
| `Identity` | Citizenship / Voting Rights | `tokens/VotesERC20V1.sol` |
| `Secretariat` | Administrative Office | `governance/Secretariat.sol` |
**Legacy names to avoid**: Azorius, Governor, Strategy, FreezeGuard, FreezeVoting, SubDAO, GnosisSafe.
## Voting Weight Adapters
| Adapter | Mechanism |
|---------|-----------|
| `VotingWeightERC20V1` | ERC20 token-based voting |
| `VotingWeightERC721V1` | NFT-based voting (one-NFT-one-vote) |
| `ProposerAdapterHatsV1` | Hats Protocol role-based proposing |
## Fractal Governance (Nested DAOs)
The same governance pattern repeats at every scale:
- **L1 DAO (Sovereign)**: Full autonomy, can create child DAOs
- **L2+ DAO (Nested)**: Own Safe, may have parent Veto/Sanction
- Each level: Council + Charter + Safe
- Fork freedom: disagreement leads to new DAO, no permission needed
- Exit liquidity: members can always withdraw
## Treasury Contracts (OHM-Style Bonding)
| Contract | Purpose |
|----------|---------|
| `LiquidBond.sol` | OHM-style bonding for ASHA with multi-collateral |
| `CollateralRegistry.sol` | Registry for bondable assets with risk tiers |
| `Bond.sol` | DAO treasury bond issuance with vesting |
| `Recall.sol` | Parent DAO fund recall (ALLOCATED only, not BONDED) |
| `FeeRouter` | Automatic fee distribution by policy |
| `GaugeController` | Epoch-based allocation voting |
| `VaultRegistry` | Multi-vault management |
| `SpendingTimelock` | Tiered spending delays (24h-168h) |
### Collateral Tiers
| Tier | Assets | Bond Discount |
|------|--------|---------------|
| TIER_1 | Native ecosystem (LUSD, LETH, CYRUS, MIGA, PARS) | 25% |
| TIER_2 | Major assets (ETH, BTC wrappers, stables) | 20% |
| TIER_3 | LP tokens (ASHA pairs) | 15% |
| TIER_4 | Other volatile assets | 10% |
## Identity System (LP-3006)
Three-layer identity for governance:
| Layer | Contract | Purpose |
|-------|----------|---------|
| DID | `DIDRegistry.sol` | W3C DID (`did:lux:<id>`) |
| SoulID | `SoulID.sol` | Soulbound NFT with reputation fields |
| Karma | `Karma.sol` + `KarmaController.sol` | Non-transferable reputation token |
### Reputation Scores (0-100)
| Score | Purpose |
|-------|---------|
| `humanityScore` | Sybil resistance, humanity verification |
| `governanceParticipation` | Voting and proposal activity |
| `communityContribution` | Community involvement |
| `protocolUsage` | DeFi/protocol activity |
| `trustLevel` | Composite score for voting weight |
### Voting Power Formula
```
votingPower = karma * (50 + trustLevel / 2) / 100
canPropose = karma >= 100 KARMA
isHuman = humanityScore >= 50
```
## Lux Proposals (LPs)
Governance changes tracked via **LPs** at `github.com/luxfi/lps`:
| Range | Chain | Examples |
|-------|-------|---------|
| LP-0xxx | Network-wide | Architecture, governance, philosophy, licensing |
| LP-1xxx | P-Chain | Validators, staking |
| LP-2xxx | C-Chain | EVM, precompiles |
| LP-3xxx | X-Chain / Identity | Assets, DID, SoulID |
| LP-4xxx | Network | Consensus, P2P |
| LP-6xxx | Cross-chain | Teleport bridge |
| LP-9xxx | DEX | AMM precompiles |
Currently 350+ proposals in the repository.
## Deployed Contract Addresses (localhost:1337)
| Contract | Address | Role |
|----------|---------|------|
| Council | `0x4A679253410272dd5232B3Ff7cF5dbB88f295319` | Legislative Body |
| Charter | `0xa85233C63b9Ee964Add6F2cffe00Fd84eb32338f` | Constitution |
| Identity | `0x322813Fd9A801c5507c9de605d63CEA4f2CE6c44` | Voting Rights |
| Sanction | `0x7a2088a1bFc9d81c55368AE168C2C02570cB814F` | Enforcement |
| Veto | `0x09635F643e140090A9A8Dcd712eD6285858ceBef` | Veto Power |
| SafeL2 | `0x3Aa5ebB10DC797CAC828524e59A333d0A371443c` | Treasury |
## Package Architecture
```
@luxfi/standard Core ABIs (Council, Charter, Identity, Veto, Sanction)
^
| re-exports
@luxfi/contracts DAO-specific ABIs + per-network addresses
^
| imports
@luxfi/wallet Omnichain wallet SDK (RainbowKit + Solana)
```
### Import Usage
```typescript
// From @luxfi/contracts (DAO apps)
import { GovernorAbi, StrategyAbi, abis, addresses } from '@luxfi/contracts';
// From @luxfi/standard directly (general use)
import { GovernorAbi, StrategyAbi } from '@luxfi/standard';
// Wallet SDK
import { LuxWalletProvider, ConnectButton } from '@luxfi/wallet';
```
## Directory Structure
```
dao/
app/ # React frontend (Vite + Chakra UI)
src/
components/ # React components
pages/ # Route pages
providers/ # Context providers (wagmi, rainbowkit)
hooks/ # useIdentity, useSoulID, useKarma
contracts/ # Solidity contracts (@luxfi/contracts)
contracts/ # .sol files
ignition/ # Hardhat Ignition deployment modules
publish/ # ABIs and deployed addresses
api/ # Backend API
sdk/ # TypeScript SDK
subgraph/ # The Graph indexing
packages/
wallet/ # @luxfi/wallet SDK
e2e/ # Playwright E2E tests
stack/ # Docker Compose full stack
```
## Development
```bash
# Install and run locally
make install # Install all dependencies
make up # Start local dev (Anvil + frontend)
make test # Run all tests
make down # Stop services
# Docker (full stack)
make build-docker # Build Docker images
make up-docker # Start with Docker Compose
make logs-docker # View logs
# Contract deployment
cd ~/work/lux/standard
forge script script/DeployLocal.s.sol --rpc-url http://127.0.0.1:8545 --broadcast
```
### Docker Stack Services
| Service | Port | Purpose |
|---------|------|---------|
| Anvil | 8545 | Local blockchain (chain ID 1337) |
| Frontend | 3000 | React app |
| API | 4000 | Backend |
| PostgreSQL | 5432 | Database |
| Redis | 6379 | Cache |
| IPFS | 8080/5001 | Decentralized storage |
## Production Deployment
| Domain | Purpose |
|--------|---------|
| `lux.vote` | Lux DAO voting platform |
| `pars.vote` | Pars DAO (GitHub Pages via `parsdao/pars.vote`) |
## Network Configuration
| Network | Chain ID | Consensus Time |
|---------|----------|----------------|
| Lux Mainnet | 96369 | 9.63s |
| Lux Testnet | 96368 | 6.3s |
| Localhost | 1337 | Instant (Anvil) |
Multichain support: Ethereum, Optimism, Polygon, Base, Sepolia.
+146 -59
View File
@@ -1,71 +1,103 @@
---
title: "Lux ID - Web3 Identity Frontend"
description: "## Quick reference"
title: "Lux ID"
description: "Web3 Identity Frontend"
---
## Overview
Lux ID (`lux.id`) is the **Web3 identity portal** for the Lux ecosystem -- authentication, account management, and identity pages. It is a static Next.js site built on `@luxfi/ui` and `@hanzo/auth`, deployed as a static export.
Lux ID (`lux.id`) is the **Web3 identity portal** for the Lux ecosystem. It is a statically exported Next.js 15 site built on the `@luxfi/ui` design system and `@hanzo/auth` authentication components. The site is currently a minimal landing page ("LUX id -- Coming soon") with the shared Lux ecosystem chrome (navigation, footer, theming) ready for identity and account management features to be built out.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/id` |
| Package | `@luxfi/id` v0.0.6 |
| Framework | Next.js 15.1.6 |
| Domain | `https://lux.id` |
| License | BSD-3-Clause |
| Author | Lux Partners Limited (`[email protected]`) |
| Framework | Next.js 15.1.6 (App Router) |
| React | 18.3.1 |
| Package Manager | pnpm 10.12.4 |
| Output | Static export (`next export`) |
| Output | Static export (`output: 'export'`) |
| Domain | `https://lux.id` |
| Default branch | `main` |
| Private | No (public repo) |
| Homepage | `https://hanzo.id` (GitHub metadata) |
## Tech Stack
| Layer | Technology |
|-------|------------|
| Framework | Next.js 15.1.6 (App Router) |
| UI | `@luxfi/ui` 5.5.2, `@hanzo/ui` 5.3.22, Radix UI, Tailwind CSS |
| Auth | `@hanzo/auth` 2.5.5 |
| Commerce | `@hanzo/commerce` 7.3.8 |
| 3D | `@splinetool/react-spline` 4.0.0 |
| Icons | Lucide React 0.470.0 |
| Theming | `next-themes` (dark mode) |
| State | MobX (`mobx-react`, `mobx-react-lite`) |
| Layer | Technology | Version |
|-------|------------|---------|
| Framework | Next.js (App Router) | 15.1.6 |
| UI Components | `@luxfi/ui` | 5.5.2 |
| UI Primitives | `@hanzo/ui` | 5.3.22 |
| Auth | `@hanzo/auth` | 2.5.5 |
| Commerce | `@hanzo/commerce` | 7.3.8 |
| Data Models | `@luxfi/data` | (transitive via @luxfi/ui) |
| 3D Rendering | `@splinetool/react-spline` | 4.0.0 |
| Icons | `lucide-react` | 0.470.0 |
| MDX | `@next/mdx` 14.1.0, `@mdx-js/loader` 3.x, `@mdx-js/react` 3.x |
| SVG | `@svgr/webpack` 8.x |
| Dark Mode | `next-themes` | 0.2.x |
| State | `mobx-react` 9.x, `mobx-react-lite` 4.x |
| CSS | Tailwind CSS 3.4.17, `postcss-import` |
| TypeScript | 5.7.3 |
## Architecture
## Project Structure
```
luxfi/id
luxfi/id/
├── src/
│ ├── app/
│ │ ├── layout.tsx # Root layout
│ │ └── page.tsx # Landing page
│ ├── site-def.ts # Site definition (nav, footer from @luxfi/ui)
│ ├── metadata.ts # SEO metadata for lux.id
│ └── mdx-components.tsx # MDX component overrides
├── public/ # Static assets (favicons, images)
├── next.config.js # Next.js config (static export, transpilePackages)
├── tailwind.config.ts # Tailwind configuration
├── postcss.config.js # PostCSS with imports
└── package.json # @luxfi/id
│ │ ├── layout.tsx # Root layout (html lang='en', dark class, black bg)
│ │ └── page.tsx # Landing page ("LUX id - Coming soon")
│ ├── metadata.ts # SEO metadata for lux.id
│ ├── site-def.ts # Site definition (currentAs, nav, footer)
│ └── mdx-components.tsx # MDX component overrides (custom link via MDXLink)
├── public/
│ └── assets/
│ └── lux-site-icons/ # Favicons (16x16, 32x32, 192x192, 512x512, apple-touch)
├── next.config.js # Static export, transpilePackages
├── tailwind.config.ts # Lux UI preset, content paths
├── postcss.config.js # PostCSS with imports
├── tsconfig.json
└── package.json
```
## One-file quickstart
## Key Source Files
```bash
git clone https://github.com/luxfi/id.git
cd id
pnpm install
pnpm dev
### `src/app/layout.tsx`
Root layout with dark theme defaults:
```tsx
<html lang='en' className='dark'>
<body className='bg-black text-white flex flex-col min-h-full'>
{children}
</body>
</html>
```
## Key Configuration
Metadata title: `"id - LUX"`. Viewport theme color adapts to user preference (light: white, dark: black).
### next.config.js
### `src/app/page.tsx`
- `output: 'export'` -- static site generation, no server
- `transpilePackages`: `@hanzo/ui`, `@hanzo/auth`, `@hanzo/commerce`, `@luxfi/ui`, `@luxfi/data`, `@luxfi/menu-icons`
- TypeScript and ESLint errors ignored during build (WIP)
Current landing page -- a centered "LUX id / Coming soon" placeholder with a link to `lux.network`. This is where the identity portal UI will be built.
### Site Definition
### `src/metadata.ts`
SEO metadata configuration:
- `metadataBase`: `https://lux.id`
- Title template: `%s | Lux ID`
- Description: "Lux ID is your Web3 Identity. Authentication and account pages for Lux Ecosystem."
- Application name: `Lux ID`
- Author: `Lux Partners Limited`
- Favicons at `/assets/lux-site-icons/` (16x16, 32x32, 192x192, 512x512, apple-touch-icon)
- OpenGraph and Twitter card configs present but commented out
### `src/site-def.ts`
Site definition for the shared Lux navigation chrome:
```typescript
import { footer, mainNav, type SiteDef } from '@luxfi/ui/site-def'
@@ -77,30 +109,85 @@ export default {
} satisfies SiteDef
```
## Key Dependencies
The `currentAs` property highlights the current site in the shared ecosystem navigation bar.
```
@luxfi/[email protected] — Lux design system components
@hanzo/[email protected] — Hanzo shared UI primitives
@hanzo/[email protected] — Authentication components
@hanzo/[email protected] — Commerce/payment integration
@splinetool/[email protected] — 3D scene rendering
[email protected] — Icon set
next-themes — Dark mode
mobx-react / mobx-react-lite — State management
### `src/mdx-components.tsx`
Overrides MDX link rendering to use `MDXLink` from `@hanzo/ui/primitives`:
```typescript
import { MDXLink } from '@hanzo/ui/primitives'
export function useMDXComponents(components: MDXComponents): MDXComponents {
return { a: (props) => <MDXLink {...props}/>, ...components }
}
```
## Features
## Next.js Configuration
- Web3 identity and authentication pages
- Static site (no server-side rendering)
- Shared Lux ecosystem navigation and footer
- Dark mode support via `next-themes`
- 3D elements via Spline
- Content from static JSON in `/src/content`
`next.config.js` settings:
- `output: 'export'` -- static site generation, no server required
- `images: { unoptimized: true }` -- required for static export
- `typescript.ignoreBuildErrors: true` -- WIP, build proceeds despite TS errors
- `eslint.ignoreDuringBuilds: true` -- WIP, build proceeds despite lint errors
- `transpilePackages`: `@hanzo/ui`, `@hanzo/auth`, `@hanzo/commerce`, `@luxfi/ui`, `@luxfi/data`, `@luxfi/menu-icons`
## Tailwind Configuration
Uses the `@luxfi/ui` Tailwind preset with content scanning across:
- `src/**/*.tsx` (local components)
- `./node_modules/@luxfi/ui/**/*.{ts,tsx}` (Lux UI library)
- `./node_modules/@hanzo/**/*.{ts,tsx}` (Hanzo UI library)
## Commands
```bash
# Install dependencies
pnpm install
# Development server (with hot reload)
pnpm dev
# Production build (static export to out/)
pnpm build
# Start production server (if not using static export)
pnpm prod
# Type check
pnpm tc
# Clean .next build cache
pnpm cn
# Full clean (remove .next and node_modules)
pnpm clean
```
## Relationship to Lux Login
`lux.id` (this repo) is the **identity portal** -- a static marketing/profile site for Web3 identity.
`luxfi/login` is the **authentication portal** -- the actual login/signup/forgot-password flow that authenticates users against Hanzo IAM (Casdoor). The login portal proxies to `iam.hanzo.ai` for authentication and redirects to `cloud.lux.network` after success.
Both share the `lux.id` domain conceptually but serve different purposes. The login portal runs as a standalone Next.js server (Docker, port 3000), while this identity portal is statically exported.
## Shared Lux UI Pattern
This site follows the standard pattern used across all Lux ecosystem sites (`@luxfi/bitcoin`, `@luxfi/bridge`, etc.):
1. **Package**: `@luxfi/<name>` with `[email protected]`
2. **Framework**: Next.js 15.1.6 App Router
3. **UI**: `@luxfi/ui` 5.5.2 + `@hanzo/ui` 5.3.22
4. **Auth**: `@hanzo/auth` 2.5.5
5. **Commerce**: `@hanzo/commerce` 7.3.8
6. **3D**: `@splinetool/react-spline` 4.0.0
7. **Output**: Static export
8. **Dark theme**: Default `className='dark'` on `<html>`
9. **Site def**: Imports `mainNav` and `footer.standard` from `@luxfi/ui/site-def`
## Related Skills
- `lux/lux-login.md` -- Authentication portal (login/signup/OAuth2 flows)
- `lux/lux-wallet.md` -- Wallet integration
- `lux/lux-ui.md` -- Shared UI components
- `lux/lux-ui.md` -- Shared UI component libraries (@luxfi/ui, @hanzo/ui)
- `lux/lux-bridge.md` -- Bridge uses identity
+331 -11
View File
@@ -1,18 +1,338 @@
---
title: "Lux Indexer - Blockchain Data Indexing"
description: "Lux Indexer for blockchain data extraction and Uniswap subgraph integration (The Graph)."
title: "Lux Indexer"
description: "Multi-Chain Blockchain Data Indexing"
---
## Overview
Lux Indexer for blockchain data extraction and Uniswap subgraph integration (The Graph).
Lux Indexer is a **Go-based blockchain data indexing system** that covers all Lux native chains (DAG and linear), EVM chains across the Lux subnet ecosystem, and a universal multi-chain indexer supporting 100+ blockchains across EVM, Solana, Bitcoin, Cosmos, Move, and other runtimes. It works alongside Blockscout (which handles C-Chain EVM indexing) to provide complete data access for the Lux multi-chain architecture.
## Components
**Repository**: `github.com/luxfi/indexer`
**License**: MIT
| Component | Path | Purpose |
|-----------|------|---------|
| indexer/ | ``github.com/luxfi/indexer`` | Core indexer |
| exports/ | ``github.com/luxfi/exports`` | Data extraction |
| uni-v2-subgraph/ | ``github.com/luxfi/uni-v2-subgraph`` | Uniswap V2 |
| uni-v3-subgraph/ | ``github.com/luxfi/uni-v3-subgraph`` | Uniswap V3 |
| uni-v4-subgraph/ | ``github.com/luxfi/uni-v4-subgraph`` | Uniswap V4 |
## Technology Stack
| Component | Version | Notes |
|-----------|---------|-------|
| Go | 1.26.1 | Module: `github.com/luxfi/indexer` |
| PostgreSQL | 14+ | Partitioned tables by chain_id |
| SQLite | v2.0.3 | Via `mattn/go-sqlite3` (embedded/local mode) |
| Ginkgo | v2.28.1 | BDD test framework |
| Gomega | v1.39.1 | Test matchers |
| `github.com/luxfi/database` | v1.17.43 | Lux database abstraction |
| `github.com/luxfi/crypto` | v1.17.39 | Lux cryptographic primitives |
| `github.com/luxfi/ids` | v1.2.9 | Lux ID types |
| `gorilla/mux` | v1.8.1 | HTTP routing |
| `gorilla/websocket` | v1.5.4 | WebSocket for live DAG streaming |
| Docker | Alpine 3.19 | Runtime image (`golang:1.26-alpine` builder) |
## Architecture
### Three Binaries
The indexer ships three CLI binaries:
| Binary | Source | Purpose |
|--------|--------|---------|
| `indexer` | `cmd/indexer/` | Single-chain indexer (native DAG, linear, or EVM) |
| `evmchains` | `cmd/evmchains/` | Multi-EVM indexer (all 5 Lux subnets in one process) |
| `multichain` | `cmd/multichain/` | Universal indexer (100+ chains, all runtimes) |
### Chain Types
#### DAG-based Chains (Vertex/Parent model)
Uses `github.com/luxfi/indexer/dag` -- multiple parents per vertex for fast consensus convergence.
| Chain | Port | Database | RPC Method | Description |
|-------|------|----------|-----------|-------------|
| X-Chain | 4200 | explorer_xchain | `xvm` | Asset exchange, UTXOs |
| A-Chain | 4500 | explorer_achain | `avm` | AI compute, attestations |
| B-Chain | 4600 | explorer_bchain | `bvm` | Cross-chain bridge |
| Q-Chain | 4300 | explorer_qchain | `qvm` | Quantum finality proofs |
| T-Chain | 4700 | explorer_tchain | `tvm` | MPC threshold signatures |
| Z-Chain | 4400 | explorer_zchain | `zvm` | ZK transactions, privacy |
| K-Chain | 4900 | explorer_kchain | `kvm` | Post-quantum key management |
#### Linear Chains (Block/Parent model)
Uses `github.com/luxfi/indexer/chain` -- single parent per block for strict ordering.
| Chain | Port | Database | RPC Method | Description |
|-------|------|----------|-----------|-------------|
| P-Chain | 4100 | explorer_pchain | `pvm` | Platform, validators, staking |
#### EVM Chains
Uses `github.com/luxfi/indexer/evm` -- full EVM block/transaction indexing with Blockscout-compatible API.
| Chain | Port | Database | Description |
|-------|------|----------|-------------|
| C-Chain (Go) | 4000 | explorer_cchain | Smart contracts (lightweight Go alternative to Blockscout) |
### EVM Multi-Chain Process (`evmchains`)
A single-process server that indexes all 5 Lux mainnet EVM subnet chains concurrently, sharing one PostgreSQL database with table prefixes. Configured via `configs/evmchains.yaml`.
| Slug | Name | Chain ID | Port |
|------|------|----------|------|
| `cchain` | Lux C-Chain | 96369 | 4000 |
| `zoo` | Zoo | 200200 | 5000 |
| `hanzo` | Hanzo | 36963 | 5100 |
| `spc` | SPC | 36911 | 5200 |
| `pars` | Pars | 494949 | 5300 |
Management API on port 9000 (`/health`, `/chains`).
### Universal Multi-Chain Indexer (`multichain`)
The `multichain` package and `cmd/multichain` binary provide a universal indexer covering 100+ chains. Configured via `config/chains.yaml` (1450-line YAML). Supported runtime types:
| Runtime Type | Examples |
|-------------|----------|
| `evm` | Ethereum, Arbitrum, Base, Optimism, BSC, Polygon, zkSync, Linea, Scroll, 30+ more |
| `solana` | Solana mainnet/devnet |
| `bitcoin` | Bitcoin mainnet/testnet (ordinals, runes, BRC-20, stamps, atomicals, RGB) |
| `cosmos` | Cosmos Hub, Osmosis, Injective, dYdX, Celestia, Sei, Neutron, 10+ more |
| `move` | Aptos, Sui |
| `starknet` | StarkNet |
| `near` | NEAR |
| `tron` | TRON |
| `ton` | TON |
| `substrate` | Polkadot, Kusama |
| `flow` | Flow |
| `tezos` | Tezos |
| `algorand` | Algorand |
| `cardano` | Cardano |
| `icp` | Internet Computer |
| `stacks` | Stacks |
| `hedera` | Hedera |
| `multiversx` | MultiversX |
| `filecoin` | Filecoin |
| `hyperliquid` | Hyperliquid |
| `lux_ai` | Lux A-Chain |
| `lux_bridge` | Lux B-Chain |
| `lux_threshold` | Lux T-Chain |
| `lux_zk` | Lux Z-Chain |
| `lux_graph` | Lux G-Chain |
| `lux_identity` | Lux I-Chain |
| `lux_key` | Lux K-Chain |
| `lux_dex` | Lux D-Chain |
DeFi protocol indexing per chain (Uniswap, Aave, Compound, GMX, Curve, PancakeSwap, Jupiter, Raydium, etc.).
HTTP endpoints: `/stats`, `/health`, `/chains`, `/chain/{id}`, `/metrics` (Prometheus).
## Core Concepts
### Storage Layer
The `storage/` package provides a unified storage interface:
- `storage.Store` interface -- abstract storage backend
- `storage.NewUnified()` -- creates KV-backed storage from `storage/kv/`
- `storage/query/` -- query builders for indexed data
- Default data dir: `~/.lux/indexer/<chain>/`
### Database Schema (PostgreSQL)
4 migration files in `migrations/`. Tables are **partitioned by chain_id** for multi-chain isolation:
**Core tables** (each partitioned for chain IDs 96369, 96368, 200200, 200201, 36963):
- `chains` -- chain registry (chain_id, name, symbol, rpc_url)
- `blocks` -- block headers with Lux-specific fields (ext_data_hash, ext_data_gas_used, block_gas_cost)
- `transactions` -- full tx data (EIP-1559, EIP-4844 blob fields)
- `internal_transactions` -- traces (call, create, selfdestruct, reward)
- `logs` -- event logs with 4 indexed topics
- `addresses` -- address balances and stats
- `tokens` -- ERC-20/721/1155 token metadata
- `token_transfers` -- transfer events (batch support for ERC-1155)
- `address_token_balances` / `address_current_token_balances` -- historical and current balances
- `address_coin_balances` -- native coin balance history
- `smart_contracts` -- verified contract sources with ABI
- `block_rewards` -- validator/uncle/emission rewards
- `indexer_status` -- per-chain indexer progress tracking
- `transaction_actions` / `logs_actions` -- 4-byte selector and topic0 signature database
PostgreSQL extensions: `pg_trgm` (fuzzy search), `btree_gist`, `pg_stat_statements`.
### DAG Schema (Native Chains)
For non-EVM DAG chains, separate table structures:
```sql
{chain}_vertices (id, type, parent_ids JSONB, timestamp, status, data JSONB)
{chain}_edges (source, target, type)
```
For linear native chains:
```sql
{chain}_blocks (id, parent_id, height, timestamp, status, data JSONB)
```
### API Compatibility
All indexers expose **Blockscout-compatible `/api/v2/` endpoints**:
**DAG chains**: `/api/v2/stats`, `/api/v2/vertices`, `/api/v2/vertices/:id`, `/api/v2/edges`, `WS /api/v2/dag/subscribe`
**Linear chains**: `/api/v2/stats`, `/api/v2/blocks`, `/api/v2/blocks/:id`, `/api/v2/blocks/height/:height`, `WS /api/v2/blocks/subscribe`
**EVM chains**: Full Blockscout API v2 compatibility (blocks, transactions, addresses, tokens, stats, search).
### EVM Module (`evm/`)
Rich EVM indexing with subpackages:
| Package | Purpose |
|---------|---------|
| `evm/api/` | Blockscout-compatible REST API server |
| `evm/account/` | Account balance tracking |
| `evm/contracts/` | Contract verification and ABI decoding |
| `evm/defi/` | DeFi protocol indexing |
| `evm/search/` | Full-text search |
| `evm/stats/` | Chain statistics |
| `evm/charts/` | Chart data generation |
| `evm/blob.go` | EIP-4844 blob transaction support |
| `evm/erc4337.go` | Account abstraction (ERC-4337) UserOp indexing |
| `evm/mev.go` | MEV transaction detection |
| `evm/uncle.go` | Uncle/ommer block handling |
| `evm/pending.go` | Pending transaction tracking |
| `evm/multichain.go` | Multi-chain EVM coordination |
| `evm/enhanced.go` | Enhanced transaction decoding |
### DEX Module (`dex/`)
DEX adapter for Uniswap-style protocol indexing on Lux subnets.
### Testing
- **Unit tests**: `go test -v ./...` (Ginkgo/Gomega BDD style)
- **E2E tests**: `e2e/` directory with tests for C-Chain, X-Chain, P-Chain, client, node, funding
- **Integration tests**: `go test -v -tags=integration ./test/...`
- **Coverage**: `go test -coverprofile=coverage.out ./...`
## Related Repositories
### Uniswap Subgraphs (The Graph Protocol)
Three subgraph repos for DEX data on Lux C-Chain, deployed to The Graph:
| Repo | Package | Graph CLI | Graph TS | Network |
|------|---------|-----------|----------|---------|
| `github.com/luxfi/uni-v2-subgraph` | `@luxfi/uniswap-v2-subgraph` v1.0.0 | ^0.64.1 | ^0.32.0 | `lux` |
| `github.com/luxfi/uni-v3-subgraph` | `@luxfi/uniswap-v3-subgraph` v1.0.0 | ^0.64.1 | ^0.32.0 | `lux` |
| `github.com/luxfi/uni-v4-subgraph` | `lux-v4-subgraph` v1.0.0 | ^0.64.1 | ^0.32.0 | `lux` |
**V2 contracts**: Factory at `0xeac0a50112b5ee20cc18e42ba4d37777012afd0d` (startBlock 0)
**V3 contracts**: Factory at `0x80bBc7C4C7a59C899D1B37BC14539A22D5830a84` (startBlock 1)
**V4 contracts**: PoolManager at `0x0000000000000000000000000000000000009010`, PositionManager at `0x0000000000000000000000000000000000009011` (startBlock 1)
Subgraph infrastructure:
- Graph Node: `graph.lux.network` / `graph-admin.lux.network`
- IPFS: `ipfs.lux.network`
- K8s services: `graph-node.lux-mainnet.svc`, `graph-ipfs.lux-mainnet.svc`
- Deploy targets: `lux`, `lux-testnet`, `lux-devnet`, `zoo`, `zoo-testnet`
V3 `networks.json` includes Lux alongside Ethereum, Arbitrum, Base, BSC, Polygon, and 10+ other networks.
### Blockchain Data Exports (`github.com/luxfi/exports`)
Pre-exported JSONL blockchain data for bootstrapping:
| Dataset | Blocks | Size | Format |
|---------|--------|------|--------|
| LUX Mainnet (96369) | 0 -- 1,082,780 | 4.2 GB | 44 JSONL chunks |
| Zoo Mainnet (200200) | 0 -- 799 | 3.5 MB | Single JSONL file |
Each line contains: block number, hash, parentHash, stateRoot, timestamp, gasLimit, gasUsed, baseFee, headerRLP, bodyRLP, receiptsRLP, and stateChanges (genesis only).
Genesis treasury: `0x9011E888251AB053B7bD1cdB598Db4f9DEd94714` with 2,000,000,000,000 LUX.
Alternative import: direct BadgerDB copy from `~/.luxd-mainnet/chainData/` (34M keys, 7.1 GB state).
## Development
### Build
```bash
# Build single-chain indexer
make build # -> bin/indexer
# Build Docker image
make docker # -> luxfi/indexer:latest
# Run locally
make dev-xchain # X-Chain DAG indexer on port 4200
make dev-pchain # P-Chain linear indexer on port 4100
make dev-zchain # Z-Chain DAG indexer on port 4400
```
### Run
```bash
# Single native chain
./bin/indexer -chain xchain -rpc http://localhost:9630/ext/bc/X -port 4200
# All Lux EVM subnets (single process)
./bin/evmchains -config configs/evmchains.yaml
# Universal multi-chain
./bin/multichain -config config/chains.yaml -port 5000 -max-chains 100
# List available chains
./bin/indexer -list
```
### Docker
```bash
# Dockerfile builds both binaries (cross-compile, CGO_ENABLED=0)
docker build --build-arg VERSION=$(git describe --tags) -t luxfi/indexer .
# Ports exposed: 4000-4900, 5000-5300, 9000
# Entrypoint: indexer
```
### Environment Variables
| Variable | Purpose | Default |
|----------|---------|---------|
| `RPC_ENDPOINT` | Chain RPC URL | chain-specific |
| `DATABASE_URL` | PostgreSQL connection | -- |
| `HTTP_PORT` | API server port | chain-specific |
| `POLL_INTERVAL` | Stats poll interval | `30s` |
| `DATA_DIR` | Local storage directory | `~/.lux/indexer/<chain>` |
| `LOG_LEVEL` | Logging verbosity | `info` |
### Subgraph Development
```bash
# V2/V3/V4 subgraphs
cd ~/work/lux/uni-v{2,3,4}-subgraph
pnpm install # or npm install
npm run codegen # Generate AssemblyScript types
npm run build # Compile subgraph
npm run deploy-lux # Deploy to Lux Graph Node
```
## File Structure
```
indexer/
cmd/
indexer/ # Single-chain CLI (DAG/linear/EVM)
evmchains/ # Multi-EVM subnet CLI
multichain/ # Universal 100+ chain CLI
dag/ # DAG vertex/edge indexer library
chain/ # Linear block indexer library
evm/ # EVM indexer (api/, account/, contracts/, defi/, search/, stats/)
dex/ # DEX protocol adapter
multichain/ # Universal multi-chain manager
storage/ # Unified storage (kv/, query/)
achain/ bchain/ kchain/ pchain/ qchain/ tchain/ xchain/ zchain/ # Per-chain adapters
config/chains.yaml # Universal chain config (1450 lines, 100+ chains)
configs/evmchains.yaml # Lux EVM subnet config (5 chains)
migrations/ # PostgreSQL schema (4 files)
e2e/ # End-to-end tests (cchain, xchain, pchain, node, client)
Makefile # Build, test, dev, Docker targets
go.mod # github.com/luxfi/indexer, Go 1.26.1
```
+306 -48
View File
@@ -1,60 +1,282 @@
---
title: "Lux Lattice - Post-Quantum Lattice Cryptography"
description: "Lattice-based multiparty homomorphic encryption library."
title: "Lux Lattice"
description: "Post-Quantum Lattice Cryptography"
---
## Overview
Lattice-based **multiparty homomorphic encryption** library. Full-RNS RLWE-based HE supporting BFV, BGV, and CKKS schemes. Originally from EPFL Laboratory for Data Security, maintained by Lux Industries.
Lattice-based **multiparty homomorphic encryption** library. Full-RNS RLWE-based HE supporting BFV, BGV, and CKKS schemes with N-out-of-N and t-out-of-N threshold access structures. Pure Go, C++-competitive performance, WASM-compatible. Originally from EPFL Laboratory for Data Security, maintained by Lux Partners Limited.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/lattice/v7` |
| Version | v7.0.0 |
| Go | 1.26.1 |
| Upstream | EPFL Laboratory for Data Security |
| License | Apache 2.0 |
| Ring degree | 2^4 (16) to 2^20 (1M) |
| Max modulus bits | 60 per prime |
| Default error | Discrete Gaussian, sigma=3.2, bound=19.2 |
| Default secret | Ternary, P=2/3 |
**NOTE**: Module is at v7 (inherited from upstream EPFL convention). All consumers (`node`, `evm`, `fhe`, `consensus`) import `lattice/v7`.
## Schemes
## Dependencies
| Scheme | Type | Use Case |
|--------|------|----------|
| **BFV** | Exact integer | Counting, comparison, small integers |
| **BGV** | Exact modular | Modular arithmetic circuits |
| **CKKS** | Approximate real | Floating-point, ML inference |
```
github.com/ALTree/bigfloat v0.2.0 # Arbitrary-precision floating point
github.com/google/go-cmp v0.7.0 # Struct comparison (tests + params equality)
github.com/stretchr/testify v1.11.1 # Test assertions
golang.org/x/crypto v0.48.0 # Cryptographic primitives
golang.org/x/exp v0.0.0-20260212183809 # Experimental math
```
## Packages
## Encryption Schemes
### BFV (Fan-Vercauteren)
- **Type**: Exact integer arithmetic (scale-invariant)
- **Use case**: Counting, comparison, small integer circuits
- **Implementation**: Unified with BGV in `schemes/bgv/` package. Instantiate BGV evaluator with `ScaleInvariant=true`
- **Difference from textbook BFV**: Only `Mul`, `MulNew`, `MulRelin`, `MulRelinNew`, `Rescale` are replaced with scale-invariant variants
- **Constraint**: Plaintext modulus T must be coprime with ciphertext modulus Q (T cannot divide Q, otherwise not IND-CPA secure)
- **Noise**: ~0.5 bit less than textbook BFV due to rounded (not floored) RNS division
### BGV (Brakerski-Gentry-Vaikuntanathan)
- **Type**: Exact modular arithmetic
- **Use case**: Modular arithmetic circuits, integer SIMD
- **Package**: `github.com/luxfi/lattice/v7/schemes/bgv`
- **Plaintext space**: Z_T where T is the plaintext modulus
- **Slots**: For slot encoding, slots = largest n where T = 1 mod 2n. For coefficient encoding, slots = N
- **SIMD layout**: 2 x (N/2) matrix (Standard ring) or 1 x N matrix (Conjugate Invariant)
- **Operations**: Add, Sub, Mul, MulRelin, MulThenAdd, Rescale, column rotation, row rotation, inner sum, replicate, trace
**Example parameter set** (`ExampleParameters128BitLogN14LogQP438`):
```
LogN=14, Q=40+11*29 bits, P=40+39 bits, T=0x10001 (16-bit), 128-bit security
```
### CKKS (Cheon-Kim-Kim-Song)
- **Type**: Approximate real/complex arithmetic
- **Use case**: Floating-point ML inference, signal processing, statistics
- **Package**: `github.com/luxfi/lattice/v7/schemes/ckks`
- **Precision modes**: PREC64 (LogDefaultScale <= 64) and PREC128 (LogDefaultScale <= 128)
- **Levels consumed per rescale**: 1 (PREC64) or 2 (PREC128)
- **Slots**: N/2 complex (Standard ring) or N real (Conjugate Invariant)
- **Ring types**: Standard Z[X]/(X^N+1) or Conjugate Invariant Z[X+X^-1]/(X^2N+1) with bridge between them
- **Operations**: Add, Sub, Mul, MulRelin, Rescale, rotation, complex conjugation, inner sum, replicate, trace
- **Bootstrapping**: Full approximate CKKS bootstrapping in `circuits/ckks/bootstrapping/`
**Example parameter set** (`ExampleParameters128BitLogN14LogQP438`):
```
LogN=14, Q[0]=55-bit + 6*45-bit, P=2*55-bit, LogDefaultScale=45, 128-bit security
```
### Scheme-Agnostic Interface
The `schemes` package defines `Encoder` and `Evaluator` interfaces that all three schemes implement:
```go
type Evaluator interface {
Add, AddNew, Sub, SubNew, Mul, MulNew, MulRelin, MulRelinNew,
MulThenAdd, Relinearize, Rescale
}
```
## Package Architecture
### Ring Layer (`ring/`)
RNS-accelerated polynomial ring arithmetic:
| Component | Purpose |
|-----------|---------|
| `ring.Ring` | RNS polynomial ring with SubRing decomposition |
| `ring.Poly` | Polynomial with multi-level RNS coefficients |
| `ring.SubRing` | Single-prime modular arithmetic with NTT |
| `ring/ringqp/` | Q*P extended ring for key-switching |
| NTT | Number Theoretic Transform (Standard + Conjugate Invariant) |
| Samplers | Uniform, Ternary (fixed-H or probability), Discrete Gaussian |
| Basis Extension | RNS basis extension for cross-modulus operations |
| Modular Reduction | Montgomery and Barrett reduction |
**Ring types**: `Standard` = Z[X]/(X^N+1), `ConjugateInvariant` = Z[X+X^-1]/(X^2N+1)
### Core RLWE Layer (`core/rlwe/`)
Scheme-agnostic RLWE encryption primitives:
| Component | Purpose |
|-----------|---------|
| `Parameters` | Immutable RLWE parameter set (logN, Q, P, distributions, ring type) |
| `ParametersLiteral` | User-facing parameter specification |
| `KeyGenerator` | Generates SK, PK, RelinKey, GaloisKey, EvaluationKey |
| `Encryptor` | Public-key and secret-key encryption |
| `Decryptor` | Secret-key decryption |
| `Evaluator` | Automorphism, key-switching, gadget product |
| `Ciphertext` | Encrypted data with metadata |
| `Plaintext` | Unencrypted ring element |
| `SecretKey` | Secret key (ringqp.Poly) |
| `PublicKey` | Public encryption key |
| `RelinearizationKey` | Compact multiplication key |
| `GaloisKey` | Automorphism key (rotation/conjugation) |
| `EvaluationKey` | Generic re-encryption key |
| `GadgetCiphertext` | RNS/base-2 decomposed ciphertext for key-switching |
| `Scale` | Arbitrary-precision scaling factor |
| Ring Packing | Pack/unpack ring elements across dimensions |
### Core RGSW Layer (`core/rgsw/`)
| Component | Purpose |
|-----------|---------|
| `rgsw.Encryptor` | RGSW encryption |
| `rgsw.Evaluator` | External product |
| `rgsw/blindrot/` | LMKCDEY blind rotations for FHEW bootstrapping |
### Circuits (`circuits/`)
High-level homomorphic operations built on top of schemes:
| Circuit | Schemes | Purpose |
|---------|---------|---------|
| `circuits/common/lintrans/` | All | Linear transformations (matrix-vector products) |
| `circuits/common/polynomial/` | All | Polynomial evaluation (power basis) |
| `circuits/bgv/lintrans/` | BGV | BGV-specific linear transforms |
| `circuits/bgv/polynomial/` | BGV | BGV polynomial evaluation with simulation |
| `circuits/ckks/lintrans/` | CKKS | CKKS-specific linear transforms |
| `circuits/ckks/polynomial/` | CKKS | CKKS polynomial evaluation with simulation |
| `circuits/ckks/dft/` | CKKS | Discrete Fourier Transform |
| `circuits/ckks/inverse/` | CKKS | Multiplicative inverse approximation |
| `circuits/ckks/comparison/` | CKKS | Comparison operations (>, <, ==) |
| `circuits/ckks/minimax/` | CKKS | Minimax composite polynomial approximation |
| `circuits/ckks/mod1/` | CKKS | Mod-1 evaluator (used in bootstrapping) |
| `circuits/ckks/bootstrapping/` | CKKS | Full CKKS bootstrapping (level refresh) |
### DAG Scheduler (`dag/`)
Directed acyclic graph scheduler for FHE operation optimization:
| Component | Purpose |
|-----------|---------|
| `dag.Graph` | Computation graph with cycle detection |
| `dag.Node` | Single FHE operation (18 op types: Add, Sub, Mul, NTT, Relinearize, Rotate, Rescale, Bootstrap, etc.) |
| `dag.Builder` | Fluent API for graph construction |
| `dag.Scheduler` | Topological scheduling with batch grouping |
| `dag.Executor` | Parallel CPU + GPU batch execution |
| `dag.CiphertextPool` | Thread-safe buffer pool for intermediates |
| `dag.ExecutionContext` | Runtime state with GPU context support |
Features: operation fusion for element-wise ops, batch size limits, critical path analysis, memory estimation, Kahn's topological sort.
### Multiparty Protocols (`multiparty/`)
RLWE-based multiparty homomorphic encryption with two access structures:
#### N-out-of-N Threshold
Secret key s = sum(s_i) where each party holds s_i. All N parties must collaborate. No trusted dealer needed.
| Protocol | Rounds | Purpose |
|----------|--------|---------|
| `PublicKeyGenProtocol` | 1 | Collective public key generation |
| `RelinearizationKeyGenProtocol` | 2 | Collective relinearization key (only 2-round protocol) |
| `GaloisKeyGenProtocol` | 1 | Collective Galois/rotation key |
| `EvaluationKeyGenProtocol` | 1 | Generic collective evaluation key |
| `KeySwitchProtocol` | 1 | Re-encrypt between known collective keys (noise flooding) |
| `PublicKeySwitchProtocol` | 1 | Re-encrypt to arbitrary public key (external receiver) |
#### t-out-of-N Threshold
Extension of N-out-of-N using Shamir Secret Sharing. Based on Mouchet et al. 2022 (ePrint 2022/780).
| Type | Purpose |
|------|---------|
| `Thresholdizer` | Generates Shamir polynomials and distributes shares |
| `ShamirPolynomial` | Degree-(t-1) polynomial with ringqp.Poly coefficients |
| `ShamirSecretShare` | A party's share S(alpha_i) |
| `ShamirPublicPoint` | Party identity (uint64) |
| `Combiner` | Converts t-out-of-N shares to t-out-of-t additive shares via Lagrange interpolation |
The trick: each party evaluates F(a, S(alpha_i) * l_i) locally (not F(a, S(alpha_i)) then multiply by l_i), avoiding large error amplification from Lagrange coefficients.
#### Scheme-Specific Multiparty (`multiparty/mpbgv/`, `multiparty/mpckks/`)
| Package | Features |
|---------|----------|
| `mpbgv` | BGV threshold refresh, sharing, transform |
| `mpckks` | CKKS threshold refresh, sharing, transform |
Both provide interactive bootstrapping for their respective schemes.
#### Protocol Infrastructure
- **CRS** (Common Reference String): Interface wrapping `sampling.PRNG` -- all parties share the same seed
- **CRP** (Common Random Polynomial): Sampled from CRS for each protocol round
- **Noise Flooding**: Statistical security parameter for key-switching/decryption (prevents leakage through error)
- **Serialization**: All shares implement `io.WriterTo`, `io.ReaderFrom`, `encoding.BinaryMarshaler/Unmarshaler`
### Utilities (`utils/`)
| Package | Purpose |
|---------|---------|
| `ring/` | Polynomial ring with NTT (Number Theoretic Transform) |
| `core/rlwe/` | RLWE encryption primitives |
| `core/rgsw/` | RGSW encryption |
| `schemes/bfv/` | BFV scheme implementation |
| `schemes/bgv/` | BGV scheme implementation |
| `schemes/ckks/` | CKKS scheme implementation |
| `circuits/` | High-level operations |
| `circuits/lintrans/` | Linear transformations |
| `circuits/polynomial/` | Polynomial evaluation |
| `circuits/minimax/` | Min/max approximation |
| `circuits/comparison/` | Comparison operations |
| `circuits/dft/` | Discrete Fourier Transform |
| `circuits/bootstrapping/` | CKKS bootstrapping |
| `multiparty/` | Threshold/multiparty key generation and decryption |
| `utils/bignum/` | Arbitrary-precision arithmetic, Chebyshev/minimax approximation, Remez algorithm |
| `utils/buffer/` | Efficient binary serialization (Reader/Writer interfaces) |
| `utils/sampling/` | PRNG (crypto/rand seeded), keyed PRNG for deterministic sampling |
| `utils/structs/` | Generic Vector, Matrix, Map, ConcurrentBuffer |
| `utils/cosine/` | Cosine function approximation |
| `utils/factorization/` | Integer factorization, Weierstrass products |
## Features
## MHE-MPC Protocol Flow
- RGSW and external product
- LMKCDEY blind rotations
- CKKS bootstrapping (approximate)
- Multiparty (threshold) key generation
- WASM compilation support
The full Multiparty Homomorphic Encryption - Secure Multiparty Computation protocol:
## Usage
```
1. Setup Phase (input-independent, reusable)
1.1 Each party: keygen.GenSecretKeyNew() -> sk_i
1.2 [if t<N] Thresholdizer: Shamir re-sharing of sk_i
1.3 PublicKeyGenProtocol: CRS -> CRP -> GenShare -> Aggregate -> GenPublicKey
1.4 RelinKeyGenProtocol: CRS -> CRP -> Round1 -> Aggregate -> Round2 -> Aggregate -> GenRelinKey
1.5 GaloisKeyGenProtocol: CRS -> CRP -> GenShare -> Aggregate -> GenGaloisKey (per rotation)
1.6 EvalKeyGenProtocol: CRS -> CRP -> GenShare -> Aggregate -> GenEvaluationKey
2. Evaluation Phase
2.1 Input: parties encrypt with collective PK using standard Encoder + Encryptor
2.2 Compute: standard single-party Evaluator on ciphertexts (can be outsourced)
2.3 Output:
a. KeySwitchProtocol or PublicKeySwitchProtocol: re-encrypt to receiver's key
b. Receiver decrypts locally with standard Decryptor
```
## Key Generation API
```go
import (
"github.com/luxfi/lattice/v7/core/rlwe"
"github.com/luxfi/lattice/v7/schemes/ckks"
)
// Parameters from literal
params, _ := ckks.NewParametersFromLiteral(ckks.ExampleParameters128BitLogN14LogQP438)
// Key generation
keygen := rlwe.NewKeyGenerator(params)
sk := keygen.GenSecretKeyNew()
pk := keygen.GenPublicKeyNew(sk)
rlk := keygen.GenRelinearizationKeyNew(sk)
gk := keygen.GenGaloisKeyNew(galoisElement, sk)
evk := keygen.GenEvaluationKeyNew(skIn, skOut)
// Key pair shorthand
sk, pk := keygen.GenKeyPairNew()
// Custom Hamming weight secret
sk = keygen.GenSecretKeyWithHammingWeightNew(192)
```
## CKKS Usage Example
```go
import (
@@ -62,38 +284,74 @@ import (
"github.com/luxfi/lattice/v7/core/rlwe"
)
// Generate parameters
params, _ := ckks.NewParametersFromLiteral(ckks.PN14QP438)
params, _ := ckks.NewParametersFromLiteral(ckks.ExampleParameters128BitLogN14LogQP438)
// Key generation
keygen := rlwe.NewKeyGenerator(params)
sk := keygen.GenSecretKeyNew()
pk := keygen.GenPublicKeyNew(sk)
sk, pk := keygen.GenKeyPairNew()
rlk := keygen.GenRelinearizationKeyNew(sk)
// Encrypt
encoder := ckks.NewEncoder(params)
encryptor := rlwe.NewEncryptor(params, pk)
decryptor := rlwe.NewDecryptor(params, sk)
evaluator := ckks.NewEvaluator(params, rlwe.NewMemEvaluationKeySet(rlk))
values := []complex128{1.0 + 0i, 2.0 + 0i, 3.0 + 0i}
// Encode and encrypt
values := []complex128{1.0+0i, 2.0+0i, 3.0+0i}
pt := encoder.EncodeNew(values, params.MaxLevel())
ct := encryptor.EncryptNew(pt)
// Homomorphic operations
evaluator := ckks.NewEvaluator(params, nil)
ctResult := evaluator.AddNew(ct, ct) // encrypted(values + values)
// Homomorphic addition
ctResult := evaluator.AddNew(ct, ct)
// Decrypt
decryptor := rlwe.NewDecryptor(params, sk)
// Decrypt and decode
ptResult := decryptor.DecryptNew(ctResult)
result := encoder.Decode(ptResult, params.LogSlots())
```
## DAG Scheduler Usage
```go
import "github.com/luxfi/lattice/v7/dag"
b := dag.NewBuilder()
b.Input(5) // Node 1: load ct at level 5
id1 := b.LastNodeID()
b.Input(5) // Node 2: load ct at level 5
id2 := b.LastNodeID()
b.Add(id1, id2) // Node 3: add
id3 := b.LastNodeID()
b.Rescale(id3) // Node 4: rescale
b.Output()
graph, _ := b.Build()
scheduler := dag.NewScheduler(graph, dag.WithFuseSimilarOps(true))
schedule, _ := scheduler.Schedule()
stats := schedule.Stats()
// stats.CriticalPath, stats.MaxBatchSize, stats.Parallelism
```
## Security Defaults
| Parameter | Value |
|-----------|-------|
| Error distribution (Xe) | DiscreteGaussian{Sigma: 3.2, Bound: 19.2} |
| Secret distribution (Xs) | Ternary{P: 2/3} (~0.816 std dev) |
| MaxLogN | 20 (ring degree up to 2^20) |
| MinLogN | 4 (ring degree at least 16) |
| MaxModuliSize | 60 bits per prime |
## Consensus Integration
The `github.com/luxfi/consensus` module uses lattice crypto for post-quantum certificates in Quasar 2-round finality (second round: lattice PQ certificate).
## References
1. Multiparty Homomorphic Encryption from Ring-Learning-with-Errors (ePrint 2020/304)
2. An Efficient Threshold Access-Structure for RLWE-Based Multiparty Homomorphic Encryption (ePrint 2022/780)
3. Efficient FHEW Bootstrapping with Small Evaluation Keys (ePrint 2022/198) -- blind rotations
## Related Skills
- `lux/lux-fhe.md` — Higher-level FHE API (uses lattice internally)
- `lux/lux-crypto.md` — Other cryptographic primitives
- `lux/lux-consensus.md` — Quasar PQ certificates
- `lux/lux-fhe.md` -- Higher-level FHE API (uses lattice internally)
- `lux/lux-crypto.md` -- Other cryptographic primitives
- `lux/lux-consensus.md` -- Quasar PQ certificates
+210 -61
View File
@@ -1,11 +1,11 @@
---
title: "Lux Login - Custom Auth Portal for lux.id"
description: "## Quick Reference"
title: "Lux Login"
description: "Custom Auth Portal for lux.id"
---
## Overview
Lux Login is the **custom authentication portal** for Lux Network, providing a monochrome dark-themed sign-in experience at `lux.id`. It supports both direct password login (via Casdoor/IAM API) and OAuth2 Authorization Code flow against `lux.id` IAM.
Lux Login is the **custom authentication portal** for Lux Network, providing a monochrome dark-themed sign-in experience. It supports direct password login (proxied to Casdoor/IAM API), user registration, password reset, and OAuth2 Authorization Code flow against `lux.id` IAM. Built with Next.js 15 (App Router), it runs as a standalone Docker container and is deployed to GHCR via GitHub Actions.
## Quick Reference
@@ -14,94 +14,243 @@ Lux Login is the **custom authentication portal** for Lux Network, providing a m
| Repo | `github.com/luxfi/login` |
| Package | `@luxfi/login` v0.1.0 |
| Default branch | `main` |
| Framework | Next.js 15 (App Router) |
| Framework | Next.js 15 (App Router, `output: 'standalone'`) |
| Package manager | pnpm 9.15.4 |
| Node | 22 |
| Docker image | `ghcr.io/luxfi/login:latest` |
| Port | 3000 |
| Private | Yes |
## Architecture
## Tech Stack
| Layer | Technology | Version |
|-------|------------|---------|
| Framework | Next.js (App Router, standalone output) | 15.1.x |
| React | react, react-dom | 19.0.x |
| CSS | Tailwind CSS | 3.4.17 |
| Font | Inter (Google Fonts, weights 400/500/600) |
| TypeScript | 5.7.x |
Notably minimal -- no `@luxfi/ui`, no `@hanzo/ui`, no `@hanzo/auth`. This is a standalone auth portal with zero shared component library dependencies.
## Project Structure
```
login/
├── app/
│ ├── page.tsx # Login page (email/password + OAuth)
│ ├── signup/page.tsx # Sign up page
│ ├── forgot/page.tsx # Forgot password page
│ ├── callback/page.tsx # OAuth callback handler
│ ├── layout.tsx # Root layout (dark theme)
│ ├── globals.css # Tailwind styles
│ ├── api/
│ │ ├── login/route.ts # POST /api/login (Casdoor proxy)
│ │ ├── signup/route.ts # POST /api/signup
│ │ └── forgot/route.ts # POST /api/forgot
│ ├── page.tsx # Login page (email/password + OAuth2)
│ ├── signup/
│ │ └── page.tsx # Sign up page (name/email/password + OAuth2)
│ ├── forgot/
│ │ └── page.tsx # Forgot password page (email → reset link)
│ ├── callback/
│ │ └── page.tsx # OAuth2 callback handler (code → token exchange)
│ ├── layout.tsx # Root layout (dark theme, centered flex)
│ ├── globals.css # Tailwind + Inter font + autofill fix
│ └── api/
│ ├── login/route.ts # POST /api/login (proxies to IAM)
│ ├── signup/route.ts # POST /api/signup (proxies to IAM)
│ └── forgot/route.ts # POST /api/forgot (sends verification code)
├── components/
│ └── lux-wordmark.tsx # LUX SVG wordmark component
│ └── lux-wordmark.tsx # LUX SVG wordmark (126x34, white fill)
├── lib/
│ └── oauth.ts # OAuth2 helpers (authorize URL, token exchange)
├── Dockerfile # Multi-stage Node 22 Alpine build
├── next.config.ts
├── tailwind.config.ts
└── package.json
│ └── oauth.ts # OAuth2 helpers (authorize URL, token exchange)
├── Dockerfile # Multi-stage Node 22 Alpine (standalone output)
├── next.config.ts # { output: 'standalone' }
├── tailwind.config.ts # Custom colors: surface #141414, border #262626
├── postcss.config.mjs
├── tsconfig.json
├── package.json
└── .github/
└── workflows/
└── ci.yml # Build + typecheck + GHCR push
```
## Auth Flows
### Direct Password Login
1. User submits email + password on `/`
2. `POST /api/login` proxies to IAM: `${IAM_URL}/api/login`
3. Payload: `{ application: "app-lux", organization: "lux", username, password, type: "login" }`
4. On success, redirects to `NEXT_PUBLIC_REDIRECT_URL` (default: `cloud.lux.network`)
### Direct Password Login (`/`)
1. User submits email + password on the login page
2. Client POSTs to `/api/login` with `{ email, password }`
3. Server-side route handler proxies to IAM: `POST ${IAM_URL}/api/login`
4. Payload sent to IAM:
```json
{
"application": "app-lux",
"organization": "lux",
"username": "<email>",
"password": "<password>",
"type": "login"
}
```
5. IAM returns `{ status: "ok", data: "<token>" }` on success
6. API route returns `{ redirect: REDIRECT_URL, token: data.data }`
7. Client redirects to `REDIRECT_URL` (default: `cloud.lux.network`)
### User Registration (`/signup`)
1. User submits name + email + password (min 8 chars)
2. Client POSTs to `/api/signup` with `{ name, email, password }`
3. Server proxies to IAM: `POST ${IAM_URL}/api/signup`
4. Payload:
```json
{
"application": "app-lux",
"organization": "lux",
"username": "<email>",
"name": "<name>",
"email": "<email>",
"password": "<password>",
"type": "signup"
}
```
5. On success, redirects to `REDIRECT_URL`
### Password Reset (`/forgot`)
1. User submits email
2. Client POSTs to `/api/forgot` with `{ email }`
3. Server proxies to IAM: `POST ${IAM_URL}/api/send-verification-code`
4. Payload: `{ application: "app-lux", organization: "lux", dest: email, type: "reset" }`
5. **Always returns success** (`{ ok: true }`) regardless of whether the email exists, to prevent email enumeration
### OAuth2 Authorization Code Flow
### OAuth2 Authorization Code
1. User clicks "Sign in with Lux ID"
2. Redirects to `lux.id/oauth/authorize` with `response_type=code`
3. After IAM login, callback to `/callback` with authorization code
4. `/callback` exchanges code for token via `lux.id/oauth/token`
5. Stores `access_token` + `refresh_token` in sessionStorage
6. Redirects to target URL
2. `getOAuthAuthorizeUrl()` constructs URL:
```
https://lux.id/oauth/authorize?client_id=...&response_type=code&redirect_uri=.../callback&scope=openid+profile+email&state=<uuid>
```
3. User authenticates on IAM
4. IAM redirects back to `/callback?code=<code>`
5. `CallbackHandler` component calls `exchangeCodeForToken(code)`:
- POSTs to `IAM_TOKEN_URL` with `grant_type=authorization_code`
- Content-Type: `application/x-www-form-urlencoded`
6. On success, stores tokens in `sessionStorage`:
- `lux_access_token` -- access token
- `lux_refresh_token` -- refresh token (if present)
7. Redirects to `REDIRECT_URL` (default: `cloud.lux.network`)
8. Error handling: displays error description with "Back to sign in" link
## Environment Variables
```bash
# IAM backend (server-side)
IAM_URL=https://iam.hanzo.ai # Casdoor API endpoint
IAM_APP=app-lux # Casdoor application name
### Server-side (API routes)
# OAuth (client-side)
NEXT_PUBLIC_IAM_CLIENT_ID=lux-cloud-client-id
NEXT_PUBLIC_IAM_AUTHORIZE_URL=https://lux.id/oauth/authorize
NEXT_PUBLIC_IAM_TOKEN_URL=https://lux.id/oauth/token
NEXT_PUBLIC_REDIRECT_URL=https://cloud.lux.network
NEXT_PUBLIC_IAM_ORG=lux
| Variable | Default | Purpose |
|----------|---------|---------|
| `IAM_URL` | `https://iam.hanzo.ai` | Casdoor API base URL |
| `IAM_APP` | `app-lux` | Casdoor application name |
### Client-side (OAuth2 + redirect)
| Variable | Default | Purpose |
|----------|---------|---------|
| `NEXT_PUBLIC_IAM_CLIENT_ID` | `lux-cloud-client-id` | OAuth2 client ID |
| `NEXT_PUBLIC_IAM_AUTHORIZE_URL` | `https://lux.id/oauth/authorize` | OAuth2 authorize endpoint |
| `NEXT_PUBLIC_IAM_TOKEN_URL` | `https://lux.id/oauth/token` | OAuth2 token endpoint |
| `NEXT_PUBLIC_REDIRECT_URL` | `https://cloud.lux.network` | Post-auth redirect target |
| `NEXT_PUBLIC_IAM_ORG` | `lux` | Casdoor organization name |
The callback URL is derived at runtime: `${window.location.origin}/callback`.
## OAuth2 Helper (`lib/oauth.ts`)
Exports 5 functions:
| Function | Purpose |
|----------|---------|
| `getOAuthAuthorizeUrl(state?)` | Constructs authorize URL with client_id, response_type=code, redirect_uri, scope, state |
| `exchangeCodeForToken(code)` | POSTs to token endpoint, returns `{ access_token, token_type, expires_in, refresh_token? }` |
| `getRedirectUrl()` | Returns `NEXT_PUBLIC_REDIRECT_URL` |
| `getIamOrg()` | Returns `NEXT_PUBLIC_IAM_ORG` |
| `getIamClientId()` | Returns `NEXT_PUBLIC_IAM_CLIENT_ID` |
## UI Design
### Theme
- **Background**: Pure black (`#000000`)
- **Text**: White (`#ffffff`)
- **Surface color**: `#141414` (input backgrounds, cards)
- **Border color**: `#262626` (input borders, dividers)
- **Font**: Inter (400, 500, 600) via Google Fonts CDN
- **Layout**: Centered card (`max-w-sm`), full-height flex
- **Autofill fix**: WebKit autofill background forced to `#141414` with white text
### Branding
`LuxWordmark` component -- SVG wordmark, 126x34 viewport (63x17 actual), white fill. Renders "LUX" with the geometric L, connected U, and crossing X from the official Lux brand.
### Pages
| Route | Title | Content |
|-------|-------|---------|
| `/` | Sign in | Email + password form, "Forgot password?" link, "Sign in with Lux ID" OAuth button, "Sign up" link |
| `/signup` | Create account | Name + email + password (min 8 chars), "Sign up with Lux ID" OAuth button, "Sign in" link |
| `/forgot` | Reset password | Email form, success confirmation message, "Back to sign in" link |
| `/callback` | -- | Spinner ("Completing sign in...") or error display with back link |
All pages use the `LuxWordmark` component centered at top. Error messages display in red (`text-red-400`) on `bg-surface` with `border-red-900/50`.
## Docker Build
Multi-stage build on Node 22 Alpine:
```dockerfile
# Stage 1: Install deps
FROM node:22-alpine AS deps
RUN corepack enable && corepack prepare [email protected] --activate
COPY package.json pnpm-lock.yaml* ./
RUN pnpm install --frozen-lockfile || pnpm install
# Stage 2: Build
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build
# Stage 3: Runtime (standalone output)
FROM node:22-alpine AS runtime
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME="0.0.0.0"
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=build /app/public ./public
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
```
## Commands
```bash
pnpm install
pnpm dev # Next.js dev server
pnpm build # Production build
pnpm start # Start production server
pnpm typecheck # TypeScript check
pnpm lint # ESLint
```
Uses Next.js `standalone` output for minimal image size.
## CI/CD
`.github/workflows/ci.yml`:
- Triggers on push/PR to `main`
- Runs `pnpm typecheck` + `pnpm build`
- On main push: builds and pushes Docker image to GHCR
- Tags: `ghcr.io/luxfi/login:latest` + `ghcr.io/luxfi/login:<sha>`
## Design
- **Triggers**: Push to `main`, PRs to `main`
- **Build steps**: `pnpm install --frozen-lockfile` -> `pnpm typecheck` -> `pnpm build`
- **Docker push** (main branch only): Builds and pushes to GHCR
- **Tags**: `ghcr.io/luxfi/login:latest` + `ghcr.io/luxfi/login:<commit-sha>`
- **Auth**: `GITHUB_TOKEN` (built-in, no external secrets needed)
- **Theme**: Monochrome dark (black background, white text)
- **Branding**: Production LUX wordmark SVG (126x34)
- **UI**: Tailwind CSS, minimal, centered card layout
- **Pages**: Login, Sign up, Forgot password, OAuth callback
## Commands
```bash
pnpm install # Install dependencies
pnpm dev # Next.js dev server (port 3000)
pnpm build # Production build (standalone output)
pnpm start # Start production server
pnpm typecheck # TypeScript check (tsc --noEmit)
pnpm lint # ESLint (next lint)
```
## Security Notes
- Password reset endpoint always returns success to prevent email enumeration
- API routes validate required fields before proxying to IAM
- Signup enforces minimum 8-character password on server side
- Tokens stored in `sessionStorage` (cleared on tab close), not `localStorage`
- IAM credentials (`IAM_URL`) are server-side only, not exposed to client
## Related Skills
- `lux/lux-id.md` -- Web3 identity portal (static marketing site at lux.id)
- `lux/lux-brand.md` -- Brand assets and design system
+517
View File
@@ -0,0 +1,517 @@
---
title: "Lux Proposals (LPs)"
description: "Governance and Standardization Framework"
---
## Overview
Lux Proposals (LPs) are the governance and standardization framework for the Lux Network blockchain ecosystem. They define technical specifications, protocol changes, token standards, and governance processes through community-driven proposals. LPs serve the same role as Ethereum's EIPs or Bitcoin's BIPs, adapted for Lux Network's 8-chain architecture.
**Repository**: `github.com/luxfi/lps`
**Local Path**: `~/work/lux/lps/`
**Documentation Site**: `lps.lux.network`
**Forum**: `forum.lux.network`
## Quick Reference
| Item | Value |
|------|-------|
| Repository | `github.com/luxfi/lps` |
| Total LPs | 348 numbered proposals |
| LP File Format | `LPs/lp-NNNN-title-slug.md` |
| Template | `LPs/TEMPLATE.md` |
| License | BSD 3-Clause (specs), Ecosystem License (specialized chains) |
| Docs Framework | Next.js 16 with Tailwind CSS |
| Docs Port | 3002 |
## LP Lifecycle
LPs follow a structured progression from idea to finalized standard:
```
Idea (Forum) --> Draft --> Review --> Last Call (14 days) --> Final
| | |
v v v
Withdrawn Stagnant Stagnant
```
| Status | Meaning | Duration | Allowed Changes |
|--------|---------|----------|-----------------|
| **Draft** | Initial proposal, actively edited | Until ready | Any changes |
| **Review** | Open for community feedback | Varies | Clarifications only |
| **Last Call** | Final review period before acceptance | 14 days | Critical fixes only |
| **Final** | Accepted and immutable | Permanent | Errata via new LP only |
| **Withdrawn** | Abandoned by author | -- | -- |
| **Stagnant** | No activity for 60+ days | -- | Can be revived |
| **Superseded** | Replaced by a newer LP | -- | -- |
### Progression Rules
- **Draft to Review**: All required sections complete, initial feedback addressed.
- **Review to Last Call**: Community support demonstrated, concerns resolved.
- **Last Call to Final**: No critical objections raised, reference implementations exist.
- Editors review for **format and completeness**, not technical merit. Community consensus determines acceptance.
## LP Types
| Type | Purpose | Test Cases Required |
|------|---------|---------------------|
| **Standards Track** | Technical specifications requiring implementation | Yes |
| **Meta** | Process and governance proposals | No |
| **Informational** | Guidelines, best practices, research | No |
## LP Categories (Standards Track)
Standards Track LPs are further categorized by the chain or domain they affect:
| Category | Description | Examples |
|----------|-------------|---------|
| **Core** | Consensus rules, protocol-level changes | LP-0110 (Quasar), LP-1181 (Epoching) |
| **Networking** | P2P protocols, transport layer | LP-0120 (ZAP Transport), LP-6420 (GossipSub) |
| **Interface** | APIs, RPC specifications, precompiles | LP-3500 (ML-DSA Precompile), LP-9002 (DEX API) |
| **LRC** | Application standards (tokens, NFTs, DeFi) | LP-3020 (LRC-20), LP-3721 (LRC-721) |
| **Bridge** | Cross-chain protocols and interoperability | LP-6332 (Teleport), LP-6602 (Warp) |
## Chain-Based Number Allocation
LPs are organized by number range corresponding to Lux Network's 8 chains plus cross-cutting concerns:
| Range | Chain/Domain | Focus |
|-------|-------------|-------|
| **0000-0099** | Network | Architecture, governance, developer tools |
| **0100-0199** | Consensus | Photon, Flare, Quasar, Wave, Horizon |
| **0200-0299** | Privacy/FHE | FHEVM, ZKVM architectures |
| **0300-0599** | Cryptography | ZK precompiles, receipt registry, data seals |
| **1000-1199** | P-Chain | Platform coordination, validators, staking |
| **1200-1299** | C-Chain (alt) | EVM specification, compatibility |
| **1600-1699** | P-Chain (ext) | Elastic validators, L1 chains |
| **2000-2399** | Q-Chain | Post-quantum crypto, quantum-safe operations |
| **2500-2999** | LRC Standards | Token extensions (LRC-1155, LRC-1271, etc.) |
| **3000-3899** | C-Chain/EVM | Token standards, precompiles, VM, state mgmt |
| **4000-4599** | Z-Chain | ZKVM, FHE, L2 rollups |
| **5000-5799** | T-Chain | Threshold sigs, MPC, key management |
| **6000-6599** | B-Chain | Bridge, Teleport, Warp, LuxDA, messaging |
| **7000-7699** | A-Chain | AI/Attestation, TEE, GPU, LLM gateway |
| **8800-8999** | Governance/ESG | DAO, fund management, impact metrics |
| **9000-9499** | DEX/Finance | Trading, oracle, DeFi, derivatives |
| **9500-9999** | Application | Token-bound accounts, marketplace |
| **10000-10199** | Learning/Research | Learning paths, research papers |
## Complete LP Index
### Core & Meta (0xxx)
| LP | Title |
|----|-------|
| 0000 | Network Architecture and Community Framework |
| 0001 | Primary Chain Native Tokens and Tokenomics |
| 0002 | Network Architecture |
| 0003 | Governance Framework |
| 0004 | Philosophy |
| 0005 | Open Source |
| 0006 | Security |
| 0007 | Supply Chain Control |
| 0008 | Plugin Architecture |
| 0009 | CLI Tool Specification |
| 0010 | Technology Portfolio (Patent Pending) |
| 0011 | Chain Types L1/L2/L3 Specification |
| 0012 | Ecosystem Licensing |
| 0015 | Ecosystem Overview |
| 0016 | Fee Pricing Protocol |
| 0038 | Native Chain Indexer Architecture |
| 0039 | Lx Python SDK |
| 0040 | Network Runner and Testing Framework |
| 0041 | Wallet Standards |
| 0042 | Multi-Signature Wallet Standard |
| 0042 | Session VM Specification (duplicate number) |
| 0050 | Developer Tools Overview |
| 0051 | Enterprise Licensing |
| 0070 | Key Management System |
| 0085 | Security Audit Framework |
| 0086 | Security Practices and Responsible Disclosure |
| 0098 | GraphDB and GraphQL Engine Integration |
| 0099 | LP Numbering Scheme and Chain Organization |
### Consensus (01xx)
| LP | Title |
|----|-------|
| 0100 | Optimistic Oracle Integration |
| 0101 | Prediction Markets Framework |
| 0102 | Oracle Dispute Resolution |
| 0110 | Quasar Consensus |
| 0111 | Photon Selection |
| 0112 | Flare Finalization |
| 0113 | Wave Voting |
| 0114 | Focus Confidence |
| 0115 | Horizon Finality |
| 0116 | Prism Geometry |
| 0118 | Warp Signature Aggregation Protocol |
| 0120 | ZAP Transport Protocol |
| 0150 | Dead Precompile |
### Privacy & ZK Architecture (02xx-05xx)
| LP | Title |
|----|-------|
| 0200 | FHEVM Architecture |
| 0201 | ZKVM Architecture |
| 0202 | Z-Chain GPU Acceleration |
| 0203 | Threshold FHE Integration |
| 0300 | (Unlabeled specification) |
| 0510 | STARK Verifier Precompile |
| 0530 | Receipt Registry |
| 0535 | Verifiable Data Integrity Seal |
| 0536 | Seal Finality Quantum Horizon |
### P-Chain Platform (1xxx)
| LP | Title |
|----|-------|
| 1000 | P-Chain Core Platform Specification |
| 1024 | Parallel Validation and Shared Mempool |
| 1033 | P-Chain State Rollup to C-Chain EVM |
| 1034 | P-Chain as Superchain L2 (OP Stack) |
| 1100 | X-Chain Exchange Chain Specification |
| 1136 | X-Chain Order Book DEX API and RPC |
| 1137 | Native Swap Integration (T/X/Z-Chain) |
| 1181 | Epoching |
| 1200 | C-Chain EVM Specification |
| 1226 | C-Chain EVM Equivalence and Core EIPs |
| 1227 | Standard Ethereum Precompiles |
| 1605 | Elastic Validator Chains |
### Q-Chain Quantum (2xxx)
| LP | Title |
|----|-------|
| 2000 | Q-Chain Quantum Specification |
| 2004 | Quantum-Resistant Cryptography Integration |
| 2005 | Quantum-Safe Wallets and Multisig |
| 2099 | Quasar Consensus Protocol Family |
| 2105 | Lamport One-Time Signatures for Lux Safe |
| 2106 | (Specification in progress) |
| 2155 | LRC-1155 Multi-Token Standard |
| 2157 | LRC-1155 Supply Extension |
| 2200 | Post-Quantum Cryptography Suite |
| 2201 | Hybrid Classical-Quantum Crypto Transitions |
| 2202 | Cryptographic Agility Framework |
| 2210 | PQ Hybrid Transport |
| 2211 | PQXDH DM Handshake |
| 2212 | PQ MLS Group Chat |
| 2213 | PQ DA Certificates |
| 2214 | PQ DKG Protocol |
| 2271 | LRC-1271 Signature Validation |
| 2303 | Lux Q-Security P-Chain Integration |
| 2316 | ML-DSA Post-Quantum Digital Signatures |
| 2317 | SLH-DSA Hash-Based Digital Signatures |
| 2318 | ML-KEM Post-Quantum Key Encapsulation |
| 2363 | LRC-1363 Payable Token |
| 2967 | LRC-1967 Proxy Storage Slots |
### C-Chain EVM / Token Standards (3xxx)
| LP | Title |
|----|-------|
| 3000 | Standard Library Registry |
| 3001 | Teleport Bridge MPC |
| 3002 | Governance Token Stack (K, dLUX, vLUX) |
| 3003 | Liquid Protocol Self-Repaying Loans |
| 3004 | Teleport Protocol Cross-Chain Bridge |
| 3009 | LRC-3009 Transfer with Authorization |
| 3020 | LRC-20 Fungible Token Standard |
| 3021-3030 | LRC-20 Extensions (Burnable, Mintable, Bridgable, Capped, Votes, Permit, FlashMint, x402 Payment, Adoption Guide, Wrapper) |
| 3093 | Decentralized Identity (DID) |
| 3165 | LRC-165 Interface Detection |
| 3173 | LRC-173 Contract Ownership |
| 3201 | LRC-7201 Namespaced Storage Layout |
| 3210 | NFT Staking Standard |
| 3211 | Media Content NFT Standard |
| 3310 | Safe Multisig Standard |
| 3320 | Lamport Signatures for Safe |
| 3338 | Paymaster Standard |
| 3500-3521 | Precompile Suite (ML-DSA, SLH-DSA, Quasar, Fee Manager, Overview, PQ Implementation Guide) |
| 3550 | Verkle Proof Precompile |
| 3572 | LRC-7572 Contract-Level Metadata |
| 3579 | LRC-7579 Modular Smart Accounts |
| 3600 | Virtual Machine and Execution Environment |
| 3601 | VM SDK Specification |
| 3620 | C-Chain Rollup Plugin Architecture |
| 3621 | Stage-Sync Pipeline for Coreth |
| 3630 | Random Number Generation Standard |
| 3640-3641 | C-Chain Upgrade Mapping, ChainVM Compatibility |
| 3650-3668 | Precompiles (Dynamic Gas, secp256r1, Block Times, BLS12-381, Ed25519, SHA3, Blake2/3, VRF, Poseidon2, ChaCha20, HPKE, ECIES, Ring Sigs, KZG4844, secp256k1, Gas Limit, Pedersen) |
| 3670-3674 | EVM Upgrades (EOA Code, Execution Requests, Max Balance, Calldata Cost, Blob Throughput) |
| 3675 | LRC-4675 Multi-Fractional NFT |
| 3680 | CLZ Count Leading Zeros Opcode |
| 3690-3691 | EVM Security Hardening, Developer Improvements |
| 3700-3704 | State Management (Sync/Pruning, Verkle Trees, Verkle Transition, Statelessness Gas, Historical Hashes) |
| 3721-3723 | LRC-721 NFT Standard + Extensions (Burnable, Enumerable) |
| 3777 | LRC-777 Advanced Token |
| 3800 | Bridged Asset Standard |
| 3810 | Teleport Token Standard |
| 3820 | L2 to Sovereign L1 Ascension |
### Z-Chain Zero-Knowledge (4xxx)
| LP | Title |
|----|-------|
| 4000 | Z-Chain ZKVM Specification |
| 4045 | Encrypted Execution Layer Interface |
| 4100 | FHE Precompiles and Infrastructure |
| 4101 | FHE Patent Strategy |
| 4169 | LRC-5169 Client Script URI |
| 4192 | LRC-5192 Soulbound Tokens |
| 4500-4505 | L2 Rollup Framework (DA Layer, Fraud Proofs, Validity Proofs, Sequencer Registry, Block Format) |
| 4528 | LRC-5528 Refundable Token |
### T-Chain Threshold (5xxx)
| LP | Title |
|----|-------|
| 5000 | T-Chain Threshold Specification |
| 5013 | MPC Custody and Swap-Signature Layer |
| 5014 | CGG21 Threshold ECDSA |
| 5103 | MPC-LSS Linear Secret Sharing |
| 5104 | FROST Threshold Signatures |
| 5321-5325 | Precompiles (FROST, CGGMP21, LSS-MPC, Corona, KMS/HSM) |
| 5330-5341 | ThresholdVM, FHE Guide, Signer Rotation, Per-Asset Keys, K-Chain, Account Abstraction, Crypto Library, TypeScript SDK |
| 5350 | MPC Node Cluster |
| 5626-5627 | LRC-4626 Tokenized Vault + Multi-Vault Extensions |
| 5700-5704 | GPU Acceleration, Lattice Crypto, FHE Implementation, Threshold Crypto, Composable Architecture |
### B-Chain Bridge / Data Availability (6xxx)
| LP | Title |
|----|-------|
| 6000 | B-Chain Bridge Specification |
| 6017-6019 | Bridge Asset Registry, Message Format, Security Framework |
| 6022-6023 | Warp 2.0 Native Transfers, NFT Interchain Transfer |
| 6156 | LRC-3156 Flash Loans |
| 6315 | Enhanced Cross-Chain Communication |
| 6329-6341 | Teleport Bridge Suite (Index, BridgeVM, Architecture, Smart Contracts, Security/Emergency, SDK, Secrets Mgmt) |
| 6350-6353 | Bridge Verification (Light Client, Receipt Proofs, ZK State Proofs, Privacy Range Proofs) |
| 6400-6413 | LuxDA Bus (Glossary, Namespaces, Headers, Batching, Finality) |
| 6420-6422 | LuxRelay (GossipSub, Persistence, Abuse Controls) |
| 6430-6433 | Blob Layer (API, Availability Certs, Erasure Coding, DAS Upgrade) |
| 6440-6442 | LuxStore (Content Addressing, Retrieval Markets) |
| 6460-6463 | Messaging (Key Directory, DM Sessions, Group Chat, Attachments) |
| 6470-6475 | TFHE (Sidecar, Orchestration, Key Registry, DKG, Threshold Decrypt, Sealed Messages) |
| 6480-6482 | Operations (Operator Roles, Fee Markets, Slashing) |
| 6490-6491 | Infrastructure (Node Modularization, Observability SLOs) |
| 6495-6502 | Cross-Chain (Namespaces, DeFi Integration, Conformance Tests, fheCRDT Architecture, DocReceipts, DAReceipts) |
| 6525 | LRC-3525 Semi-Fungible Token |
### A-Chain AI/Attestation (7xxx)
| LP | Title |
|----|-------|
| 7000 | A-Chain AI/Attestation Specification |
| 7075 | TEE Integration Standard |
| 7101 | Solidity GraphQL Extension |
| 7102 | Immutable Training Ledger |
| 7106 | LLM Gateway Integration with Hanzo AI |
| 7110 | AI Media Content Provenance |
| 7200 | AI Mining Standard |
| 7302 | Privacy AI Attestation Layer |
| 7601 | Dynamic Gas Fee with AI Compute Pricing |
| 7607 | GPU Acceleration Framework |
| 7610 | AI Confidential Compute Tiers |
| 7981 | LRC-2981 NFT Royalties |
### DAO & Governance (8xxx)
| LP | Title |
|----|-------|
| 8800-8805 | Lux DAO (Platform, Azorius Module, Voting, Freeze Guard, Account Abstraction, SDK) |
| 8850 | DAO Governance Index |
| 8860 | Fund Management Index |
| 8900-8903 | ESG (Vision Fund Framework, Environmental Policy, Social Benefit, Governance Architecture) |
| 8910 | Lux Network Impact Thesis |
| 8920-8921 | ESG Principles, Carbon Accounting |
| 8930-8995 | ESG/Impact Suite (Green Compute, Energy Transparency, Risk, Anti-Greenwashing, Standards, Evidence Locker, Impact Framework, Measurement, Stakeholder Engagement, Community Grants, Financial Inclusion, Impact Index) |
### DEX & Finance (9xxx)
| LP | Title |
|----|-------|
| 9000 | DEX Core Specification |
| 9001-9006 | Trading (Engine, API/RPC, High-Performance Protocol, Oracle, HFT Venues) |
| 9010-9011 | DEX Precompile, Oracle Precompile |
| 9014 | QuantumSwap HFT |
| 9015 | Precompile Registry |
| 9018-9030 | DeFi (Liquidity Mining, Fee Distribution, LXBook, MEV Protection, LXVault) |
| 9040 | Perpetuals and Derivatives Protocol |
| 9060 | DeFi Protocols Overview |
| 9073-9074 | Multicall Standard, CREATE2 Factory |
| 9099 | DEX Series Overview |
| 9101-9109 | DeFi Integration, NFT Marketplace, Compound Lending |
| 9400-9403 | Privacy DeFi (Private AMM, Confidential Lending, ZK Swap, Private Staking) |
| 9551 | LRC-6551 Token-Bound Accounts |
| 9701 | Reticulum Network Stack |
| 9909 | LRC-6909 Minimal Multi-Token |
### Learning & Research (10xxx)
| LP | Title |
|----|-------|
| 10000-10009 | Learning Paths (Index, Core, Developer, Validator, Trading, Security, MPC, Privacy, Investor, Researcher) |
| 10100-10106 | Research Papers (Index, Payments, Cross-Chain, Governance, Stablecoins, MEV, Data Availability) |
## How to Submit a New LP
### Step-by-Step Process
1. **Discuss your idea** on the Lux Forum (`forum.lux.network`) or GitHub Discussions (`github.com/luxfi/lps/discussions`).
2. **Create a draft** using the interactive wizard:
```bash
cd ~/work/lux/lps
make new
```
Or manually copy the template:
```bash
cp LPs/TEMPLATE.md LPs/lp-draft.md
```
3. **Fill out required sections** (see below).
4. **Validate** your proposal:
```bash
make validate FILE=LPs/lp-draft.md
make pre-pr # full validation suite
```
5. **Submit a Pull Request** -- the PR number becomes your LP number.
6. **Rename** your file to `lp-N.md` where N is the assigned PR number.
7. **Address editor feedback** and iterate until consensus.
### Required YAML Frontmatter
```yaml
lp: <number>
title: <descriptive title>
description: <one-line description>
author: <Name (@github-username)>
discussions-to: <URL to discussion>
status: Draft
type: Standards Track|Meta|Informational
category: Core|Networking|Interface|LRC|Bridge
created: YYYY-MM-DD
```
### Required Content Sections
1. **Abstract** -- approximately 200 words summarizing the proposal.
2. **Motivation** -- why this LP is needed.
3. **Specification** -- precise technical details.
4. **Rationale** -- explanation of design decisions.
5. **Backwards Compatibility** -- impact on existing systems.
6. **Test Cases** -- required for Standards Track.
7. **Reference Implementation** -- optional but recommended.
8. **Security Considerations** -- potential risks and mitigations.
9. **Copyright** -- must be CC0.
## Key Makefile Commands
```bash
make new # Interactive LP creation wizard
make validate # Validate a single LP (FILE=LPs/lp-N.md)
make validate-all # Validate all LP files
make check-links # Verify all links in LP documents
make update-index # Regenerate the LP index in README.md
make stats # Show LP statistics by status and type
make list # List all LPs with titles
make pre-pr # Run full validation suite before submitting PR
make draft # Create lp-draft.md from template
make decision # Create an Informational Decision LP draft
make docs-dev # Run documentation site on localhost:3002
make docs-build # Build static documentation site
```
## Development Phases
The Lux Network follows a phased roadmap defined in `phases/`:
| Phase | Period | Focus |
|-------|--------|-------|
| Phase 1 | Q1 2025 | Foundational Governance and Core Protocol |
| Phase 2 | Q2 2025 | Execution Environment and Asset Standards |
| Phase 3 | Q3 2025 | Cross-Chain Interoperability |
| Phase 4 | Q4 2025 | Attestations and Compliance |
| Phase 5 | Q1 2026 | Privacy and Zero-Knowledge |
| Phase 6 | Q2 2026 | Data Availability and Scalability |
| Phase 7 | Q3 2026+ | Application Layer Standards |
## Notable LRC Standards (Ethereum-Compatible)
LRC standards maintain compatibility with Ethereum ERCs:
| LRC Standard | LP Number | Ethereum Equivalent |
|-------------|-----------|---------------------|
| LRC-20 | LP-3020 | ERC-20 (Fungible Token) |
| LRC-721 | LP-3721 | ERC-721 (NFT) |
| LRC-777 | LP-3777 | ERC-777 (Advanced Token) |
| LRC-1155 | LP-2155 | ERC-1155 (Multi-Token) |
| LRC-4337 | LP-5337 | ERC-4337 (Account Abstraction) |
| LRC-4626 | LP-5626 | ERC-4626 (Tokenized Vault) |
| LRC-6551 | LP-9551 | ERC-6551 (Token-Bound Accounts) |
## Relationship to HIPs (Hanzo Improvement Proposals)
LPs and HIPs (Hanzo Improvement Proposals) are separate governance systems for different ecosystems that integrate at the AI/attestation boundary:
- **LPs** govern the Lux blockchain protocol, consensus, chain specifications, and on-chain standards.
- **HIPs** govern Hanzo AI infrastructure including LLM Gateway, MCP, agent frameworks, and AI services.
- **LP-7106** (LLM Gateway Integration with Hanzo AI) is the primary bridge LP, connecting Lux's A-Chain to the Hanzo LLM Gateway defined in HIP-4.
- LP-7000 series (A-Chain) covers AI attestation and compute that interoperates with Hanzo services.
- ZIPs (Zoo Improvement Proposals at `zips.zoo.ngo`) handle the Zoo Labs Foundation's DeSci and frontier AI research governance.
## Repository Structure
```
~/work/lux/lps/
LPs/ # 348 numbered proposals (lp-NNNN-slug.md)
TEMPLATE.md # Template for new proposals
phases/ # 7 development phases (phase-1 through phase-7)
docs/ # Next.js documentation site + governance docs
FAQ.md, TAXONOMY.md # Reference documentation
EDITORS.md # Editor guidelines
examples/ # Example implementations (content-provenance, data-seal, etc.)
licenses/ # Lux Ecosystem License v1.2
scripts/ # 24 automation scripts (validation, indexing, renumbering)
research/ # External research (Polymarket, UMA)
_config.yml # GitHub Pages config (lps.lux.network)
Makefile # Build automation and LP management
CONTRIBUTING.md # Contribution guidelines
```
## Governance Structure
### Roles
- **Authors**: Write and champion LP proposals.
- **Editors**: Review for format, completeness, and proper structure. Do not judge technical merit.
- **Community**: Provides technical feedback, determines acceptance through consensus.
- **Validators**: Implement accepted standards on-chain.
### Discussion Categories
| Category | Scope |
|----------|-------|
| Consensus | Photon, Flare, Quasar, finality protocols |
| Threshold Crypto | FROST, CGGMP, Corona, distributed signing |
| MPC | Secure computation (not signing) |
| PQC | Post-quantum: ML-KEM, ML-DSA, SLH-DSA |
| Chains | P, C, X, T, Q, Z, A, B chain specifications |
| DeFi | AMMs, lending, oracles |
| Governance | DAOs, voting, treasury |
| Ideas | New concepts not yet categorized |
### Key Distinction
Subjects describe knowledge. Chains describe deployment. An LP about FROST threshold signatures (subject: threshold crypto) may be deployed on the T-Chain (chain: threshold). These are independent axes.
## Important Conventions
- All LP files use `github.com/luxfi/*` import paths -- never go-ethereum or ava-labs.
- While some LPs adopt Avalanche ACP specifications, all Lux implementations use **LP naming** (LP-181, not ACP-181).
- Go package names follow `lpNNN` convention (e.g., `lp176`, `lp226`).
- Implementation imports: `github.com/luxfi/node/vms/evm/lp176`.
- LP content is licensed under CC0 (public domain). Specifications are BSD 3-Clause. Specialized chain implementations use the Lux Ecosystem License.
+185 -8
View File
@@ -1,17 +1,194 @@
---
title: "Lux Marketplace - NFT Trading & AMM"
description: "Lux Marketplace is the NFT trading platform on Lux Network — Genesis NFTs, AMM integration, and marketplace features."
title: "Lux Market"
description: "Multi-Chain NFT Marketplace"
---
## Overview
Lux Marketplace is the **NFT trading platform** on Lux Network — Genesis NFTs, AMM integration, and marketplace features. Live at `markets.lux.network`.
Lux Market (`@luxfi/market`) is the NFT trading platform for the Lux Network ecosystem. It supports NFT listings, offers, purchases, and AMM-based NFT trading (sudoswap/LSSVM) across all five Lux EVM chains: Lux (C-Chain), Zoo, Hanzo, SPC, and Pars. Built with Next.js 15, React 19, wagmi 2, and viem 2 for full on-chain interaction.
## Quick reference
## Repository
| Item | Value |
|------|-------|
| URL | `https://markets.lux.network` |
| Tech | Node.js |
| market/ | ``github.com/luxfi/market`` |
| marketplace/ | ``github.com/luxfi/marketplace`` |
| Repo | `github.com/luxfi/market` |
| Local | `~/work/lux/market/` |
| Package | `@luxfi/market` v1.0.0 |
| License | GPL-3.0-or-later |
| Dev Port | 3100 |
| Live URL | `https://markets.lux.network` |
## Tech Stack
| Technology | Version | Purpose |
|------------|---------|---------|
| Next.js | 15.5.0 | App router, SSR, standalone output |
| React | 19.1.0 | UI rendering |
| TypeScript | 5.8.3 | Type safety |
| Tailwind CSS | 4.1.18 | Styling |
| wagmi | 2.15.5 | React hooks for Ethereum |
| viem | 2.43.3 | Low-level EVM client |
| TanStack Query | 5.77.2 | Async state management |
| Radix UI | Dialog, Dropdown, Slot | Accessible UI primitives |
| lucide-react | 0.511.0 | Icons |
| class-variance-authority | 0.7.x | Component variants |
| next-themes | 0.4.x | Dark/light mode |
## Supported Chains
All chains defined via `viem.defineChain()` in `src/lib/chains.ts`:
| Chain | ID | Symbol | RPC | Explorer |
|-------|-----|--------|-----|----------|
| Lux (C-Chain) | 96369 | LUX | `api.lux.network/mainnet/ext/bc/C/rpc` | `explore.lux.network` |
| Zoo | 200200 | ZOO | `api.lux.network/mainnet/ext/bc/zoo/rpc` | `explore-zoo.lux.network` |
| Hanzo | 36963 | HNZ | `api.lux.network/mainnet/ext/bc/hanzo/rpc` | `explore-hanzo.lux.network` |
| SPC | 36911 | SPC | `api.lux.network/mainnet/ext/bc/spc/rpc` | `explore-spc.lux.network` |
| Pars | 494949 | PARS | `api.lux.network/mainnet/ext/bc/pars/rpc` | `explore-pars.lux.network` |
Explorer API base URLs follow `https://explore[-chain].lux.network/api/v2` for on-chain data queries.
## Smart Contracts
Contracts are deployed on all five chains. Addresses in `src/lib/contracts.ts`:
### Contract Types
| Contract | Purpose |
|----------|---------|
| `markets` | Seaport-based NFT marketplace (list, buy, offer, accept) |
| `lssvmPairFactory` | LSSVM pair factory for NFT AMM pools (sudoswap model) |
| `linearCurve` | Linear bonding curve for AMM pricing |
| `exponentialCurve` | Exponential bonding curve for AMM pricing |
### Market Contract ABI (Seaport-based)
Key functions:
- `list(nftContract, tokenId, paymentToken, price, duration)` -- Create listing
- `buy(listingId)` -- Purchase listed NFT (payable)
- `makeOffer(nftContract, tokenId, paymentToken, amount, duration)` -- Make offer (payable)
- `acceptOffer(offerId)` -- Accept an offer
- `cancelListing(listingId)` / `cancelOffer(offerId)` -- Cancel
- `getListing(listingId)` -- View listing details
Events: `Listing`, `Sale`, `OfferMade`
### LSSVM AMM ABI
Key functions for NFT AMM trading:
- `swapTokenForSpecificNFTs(nftIds, maxInput, recipient, ...)` -- Buy specific NFTs from pool
- `swapNFTsForToken(nftIds, minOutput, recipient, ...)` -- Sell NFTs to pool
- `getBuyNFTQuote(assetId, numNFTs)` -- Get buy price quote
- `getSellNFTQuote(assetId, numNFTs)` -- Get sell price quote
- `spotPrice()` -- Current spot price
- `nft()` -- NFT contract address for the pair
### Token Standards
Full ABI support for:
- **ERC-721**: name, symbol, tokenURI, ownerOf, balanceOf, approve, setApprovalForAll, Transfer event
- **ERC-1155**: balanceOf, uri, setApprovalForAll
## Project Structure
```
~/work/lux/market/
package.json # @luxfi/market v1.0.0
next.config.ts # Standalone output, IPFS/Arweave image domains
Dockerfile # Multi-stage Next.js standalone build
src/
app/ # Next.js App Router pages
page.tsx # Homepage
layout.tsx # Root layout with providers
client-providers.tsx # wagmi + query + theme providers
providers.tsx # Server-side providers
genesis/ # Genesis NFT collection pages
collection/ # Collection detail pages
collections/ # Collection listing pages
nft/ # Individual NFT detail pages
activity/ # Trading activity feed
portfolio/ # User portfolio pages
globals.css # Global styles
components/
Header.tsx # Site header with navigation
NFTCard.tsx # NFT display card
CollectionCard.tsx # Collection summary card
ActivityRow.tsx # Activity feed row
ListingForm.tsx # Create listing form
OfferForm.tsx # Make offer form
SearchBar.tsx # Search functionality
TraitFilter.tsx # Filter by NFT traits
ui/ # Shared UI primitives
hooks/
useChain.ts # Chain selection and switching
useNFTData.ts # NFT metadata and ownership queries
lib/
chains.ts # Chain definitions (viem defineChain)
contracts.ts # Contract addresses and ABIs per chain
explorer.ts # Explorer API integration
utils.ts # Utility functions
wagmi.ts # wagmi client configuration
```
## Development
```bash
cd ~/work/lux/market
# Install dependencies
pnpm install
# Start development server (port 3100)
pnpm dev
# Production build
pnpm build
# Start production server
pnpm start
# Type checking
pnpm typecheck
# Lint
pnpm lint
```
## Docker Build
Multi-stage standalone Next.js build:
```dockerfile
FROM node:22-alpine AS builder
# pnpm install + next build (standalone output)
FROM node:22-alpine AS runner
# Copy standalone + static + public
USER nextjs
EXPOSE 3000
```
## Image Handling
`next.config.ts` allows remote images from:
- `*.lux.network` (explorer thumbnails)
- `ipfs.io`, `*.ipfs.io`, `cloudflare-ipfs.com` (IPFS gateways)
- `arweave.net` (Arweave storage)
- `gateway.pinata.cloud`, `dweb.link`, `w3s.link` (decentralized storage)
- `nft-cdn.alchemy.com`, `*.nftstorage.link` (NFT CDNs)
## Key Patterns
- All chain interactions go through wagmi hooks backed by viem
- Contract addresses are per-chain-ID maps -- adding a new chain means adding entries to `CONTRACTS`, `supportedChains`, `EXPLORER_API`, and `CHAIN_INFO`
- Explorer API v2 is used for collection/activity data fetching
- LSSVM AMM pools provide instant liquidity for NFT collections without order book
- Standalone Next.js output for container deployment
## Related Repos
| Repo | Purpose |
|------|---------|
| `github.com/luxfi/explorer` | Block explorer providing API v2 for NFT data |
| `github.com/luxfi/evm` | EVM execution engine running the chains |
| `github.com/luxfi/node` | Node software hosting the RPC endpoints |
| `github.com/luxfi/ui` | Shared component library |
+233 -59
View File
@@ -1,76 +1,235 @@
---
title: "Lux Monitoring - Full Observability Stack"
description: "Lux Monitoring provides a complete observability stack for Lux validators and network services — metrics, logs, traces, and alerting."
title: "Lux Monitoring"
description: "Full Observability Stack"
---
## Overview
Lux Monitoring provides a **complete observability stack** for Lux validators and network services — metrics, logs, traces, and alerting.
Lux Monitoring provides a **complete observability stack** for Lux validators and network services. It ships two Docker Compose configurations -- one for Lux mainnet node monitoring and one for DEX-specific monitoring -- with pre-built Grafana dashboards, Prometheus scrape targets, Loki log aggregation, and Alertmanager routing. There is also a standalone `monitoring-installer.sh` shell script for bare-metal Ubuntu validators that installs Prometheus, Grafana, and node_exporter via systemd.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/monitoring` |
| Stack | Docker Compose |
| Public URL | monitor.lux.network |
| Public URL | `monitor.lux.network` |
| Grafana default creds | `admin` / `luxnetwork` |
| Grafana port | `3100` (mapped from container `3000`) |
| Prometheus port | `9090` |
| Loki port | `3101` (mapped from container `3100`) |
| Alertmanager port | `9093` |
| Node Exporter port | `9100` |
| Postgres Exporter port | `9187` |
| TSDB retention | 30 days |
| Loki retention | 30 days (`720h`) |
## Components
## Compose Files
| Component | Port | Purpose |
|-----------|------|---------|
| **Grafana** | 3100 | Dashboards and visualization |
| **Prometheus** | 9090 | Metrics collection and querying |
| **Loki** | 3101 | Log aggregation |
| **Promtail** | — | Log shipping agent |
| **Node Exporter** | 9100 | System metrics (CPU, RAM, disk) |
| **Postgres Exporter** | 9187 | PostgreSQL metrics |
| **Alertmanager** | 9093 | Alert routing and notification |
There is **no root `compose.yml`**. Two compose files exist:
### `compose.luxnet.yml` -- Lux Network Monitoring
The primary stack. Starts 8 services:
| Service | Image | Container Name | Purpose |
|---------|-------|----------------|---------|
| `luxd` | `ubuntu:22.04` | `lux-node` | Lux node (network-id 96369, ports 9630/9631/8546) |
| `prometheus` | `prom/prometheus:latest` | `lux-prometheus` | Metrics TSDB, 30d retention |
| `grafana` | `grafana/grafana:latest` | `lux-grafana` | Dashboard UI |
| `loki` | `grafana/loki:latest` | `lux-loki` | Log aggregation (TSDB schema v13) |
| `promtail` | `grafana/promtail:latest` | `lux-promtail` | Log shipping (Docker, luxd, syslog, Blockscout) |
| `node-exporter` | `prom/node-exporter:latest` | `lux-node-exporter` | System metrics |
| `postgres-exporter` | `prometheuscommunity/postgres-exporter:latest` | `lux-postgres-exporter` | PostgreSQL metrics |
| `alertmanager` | `prom/alertmanager:latest` | `lux-alertmanager` | Alert routing |
Networks: `lux-monitoring` (internal bridge), `hanzo-network` (external, shared with other Hanzo services).
Volumes: `prometheus_data`, `grafana_data`, `loki_data`, `alertmanager_data`, `luxd_data`.
### `compose.dex.yml` -- DEX Extension
Extends the main stack with DEX-specific services:
| Service | Container Name | Purpose |
|---------|----------------|---------|
| `dex-exporter` | `lux-dex-exporter` | Node exporter for DEX host (port 9101) |
| `dex-metrics-aggregator` | `lux-dex-metrics` | Collects DEX engine/consensus/HFT metrics |
| `vector` | `lux-dex-vector` | High-perf log aggregation (Vector, port 8686) |
| `jaeger` | `lux-dex-jaeger` | Distributed tracing (Jaeger UI port 16686) |
| `cadvisor` | `lux-dex-cadvisor` | Container metrics (port 8088) |
Additional Grafana plugins installed: `grafana-piechart-panel`, `grafana-worldmap-panel`.
## Pre-configured Dashboards
7 dashboards included:
1. **C-Chain** — EVM block production, gas usage, transaction throughput
2. **P-Chain** — Validator set, staking metrics, subnet creation
3. **X-Chain** — UTXO transactions, asset creation
4. **Machine Metrics** — CPU, memory, disk I/O, network bandwidth
5. **Database** — PostgreSQL query performance, connections, replication
6. **Logs** — Structured log search via Loki
7. **Overview** — Network-wide health summary
13 dashboard JSON files across three directories:
## Key Metrics
### Core Dashboards (`grafana/dashboards/`)
### Consensus
- Finality time (target: <1s)
- Transactions per second
- Vote round latency
- Certificate generation time
| File | Dashboard | Key Panels |
|------|-----------|------------|
| `c_chain.json` | C-Chain | EVM block production, gas usage, tx throughput |
| `c_chain_load.json` | C-Chain Load | Block gas utilization, pending tx pool depth |
| `p_chain.json` | P-Chain | Validator set size, staking metrics, subnet creation |
| `x_chain.json` | X-Chain | UTXO transactions, asset creation rates |
| `machine.json` | Machine Metrics | CPU, memory, disk I/O, network bandwidth |
| `database.json` | Database | PostgreSQL connections, query perf, replication |
| `logs.json` | Logs | Structured log search via Loki datasource |
| `main.json` | Main Overview | Network-wide health summary, peer count |
| `network.json` | Network | P2P message latency, bandwidth in/out, warp delivery |
| `subnets.json` | Subnets | Subnet health, validator participation |
| `lux-comprehensive.json` | Comprehensive | All-in-one overview dashboard |
### Networking
- Peer count and churn
- Message latency (P2P)
- Bandwidth in/out
- Warp message delivery
### DEX Dashboard (`grafana/dashboards/dex/`)
### VM Performance
- Blocks produced per minute
- Gas used vs gas limit
- Transaction pool depth
| File | Dashboard |
|------|-----------|
| `dex-performance.json` | Order matching latency (p50/p95/p99/p999), throughput, DPDK/RDMA metrics |
### System
- CPU utilization
- Memory usage
- Disk I/O and capacity
- Network interface throughput
### MorpheusVM Dashboard (`grafana/dashboards/morpheusvm/`)
## Alerts
| File | Dashboard |
|------|-----------|
| `performance.json` | MorpheusVM execution performance |
Pre-configured alert rules:
- **Node down** — validator unreachable for >30s
- **Chain sync** — block height falling behind peers
- **Block rejection** — high rejection rate
- **Low peers** — peer count below threshold
- **Resource usage** — CPU/memory/disk above 80%
## Grafana Provisioning
### Datasources (`grafana/provisioning/datasources/datasources.yml`)
| Name | Type | URL |
|------|------|-----|
| Prometheus | `prometheus` | `http://prometheus:9090` (default, POST method) |
| Loki | `loki` | `http://loki:3100` (max 5000 lines) |
| Lux Node | `prometheus` | `http://host.docker.internal:9650/ext/metrics` |
| PostgreSQL | `postgres` | `lux-postgres:5432`, database `explorer_luxnet` |
### Dashboard Provider (`grafana/provisioning/dashboards/dashboards.yml`)
Provider name: `Lux Network Dashboards`, folder: `Lux Network`, uid: `lux-network`. Auto-updates every 10s and allows UI edits.
## Prometheus Scrape Configuration
### Main Config (`prometheus/prometheus.yml`)
Global scrape interval: **15s**. Evaluation interval: **15s**.
| Job Name | Metrics Path | Target | Instance Label |
|----------|-------------|--------|----------------|
| `prometheus` | `/metrics` | `localhost:9090` | -- |
| `node` | `/metrics` | `node-exporter:9100` | -- |
| `luxd` | `/ext/metrics` | `luxd:9630`, `host.docker.internal:9630` | `lux-mainnet` |
| `c-chain` | `/ext/bc/C/metrics` | `luxd:9630` | `c-chain-mainnet` |
| `c-chain-rpc` | `/ext/bc/C/rpc` | `luxd:9630` | `c-chain-rpc` |
| `x-chain` | `/ext/bc/X/metrics` | `luxd:9630` | `x-chain-mainnet` |
| `p-chain` | `/ext/bc/P/metrics` | `luxd:9630` | `p-chain-mainnet` |
| `lux-health` | `/ext/health` | `luxd:9630` | `lux-health` |
| `blockscout-lux` | `/metrics` | `host.docker.internal:4000` | `blockscout-lux-mainnet` |
| `postgres` | `/metrics` | `postgres-exporter:9187` | -- |
| `grafana` | `/metrics` | `grafana:3000` | -- |
| `loki` | `/metrics` | `loki:3100` | -- |
### DEX Config (`prometheus/dex-prometheus.yml`)
16 additional scrape jobs for DEX monitoring with intervals down to **100ms** for HFT metrics:
| Job | Scrape Interval | Target | Purpose |
|-----|----------------|--------|---------|
| `dex-engine` | 15s | `lux-dex-node:9090` | Order book engine |
| `dex-matching` | **1s** | `lux-dex-node:8080` | Match latency (HFT) |
| `dex-websocket` | 15s | `lux-dex-node:8081` | WebSocket feed |
| `dex-consensus` | 15s | `lux-dex-node:5000` | FPC consensus (K=1) |
| `dex-quantum` | 15s | `lux-dex-node:8080` | Corona-BLS signatures |
| `dex-hft` | **100ms** | `lux-dex-node:8080` | Ultra-HF trading |
| `dex-dpdk` | 15s | `lux-dex-node:8080` | Kernel bypass (DPDK) |
| `dex-rdma` | 15s | `lux-dex-node:8080` | Zero-copy replication |
| `dex-gpu` | 15s | `lux-dex-node:8080` | MLX/CUDA acceleration |
### DEX Recording Rules (`prometheus/dex-rules.yml`)
Evaluated every **5s**:
| Rule | Expression |
|------|-----------|
| `dex:matching_latency:p50` | `histogram_quantile(0.50, rate(dex_matching_latency_bucket[1m]))` |
| `dex:matching_latency:p95` | `histogram_quantile(0.95, ...)` |
| `dex:matching_latency:p99` | `histogram_quantile(0.99, ...)` |
| `dex:matching_latency:p999` | `histogram_quantile(0.999, ...)` |
| `dex:orders_per_second` | `rate(dex_orders_processed_total[1m])` |
| `dex:trades_per_second` | `rate(dex_trades_executed_total[1m])` |
| `dex:consensus_round_time` | avg rate of `dex_consensus_round_duration_seconds` |
| `dex:consensus_finality_time` | `histogram_quantile(0.95, rate(dex_consensus_finality_bucket[1m]))` |
## Alert Rules
### Chain Alerts (`prometheus/alerts/chain-alerts.yml`)
Evaluated every **30s**:
| Alert | Expression | For | Severity |
|-------|-----------|-----|----------|
| `LuxNodeDown` | `up{job="luxd"} == 0` | 5m | critical |
| `CChainNotSyncing` | `rate(avalanche_C_last_accepted_height[5m]) == 0` | 10m | warning |
| `CChainHighRejectionRate` | rejection > 10% of accepted | 5m | warning |
| `PChainNotSyncing` | `rate(avalanche_P_last_accepted_height[5m]) == 0` | 10m | warning |
| `XChainNotSyncing` | `rate(avalanche_X_last_accepted_height[5m]) == 0` | 10m | warning |
| `LowPeerCount` | `avalanche_network_peers < 5` | 10m | warning |
| `HighCPUUsage` | `process_cpu_seconds_total > 80%` | 10m | warning |
| `HighMemoryUsage` | `MemAvailable < 10%` | 10m | critical |
| `PostgresDown` | `up{job="postgres"} == 0` | 5m | critical |
### DEX Alerts (`prometheus/dex-rules.yml`)
| Alert | Threshold | Severity |
|-------|-----------|----------|
| `DEXHighLatency` | p99 > 1ms | critical |
| `DEXElevatedLatency` | p95 > 500us | warning |
| `DEXLowThroughput` | < 1M trades/sec | warning |
| `DEXConsensusFailure` | consensus node down | critical |
| `DEXHighMemoryUsage` | > 90% memory | warning |
| `DEXDatabaseDown` | PostgreSQL down | critical |
| `DEXWebSocketDrops` | > 10 disconnects/sec | warning |
| `DEXOrderBookDesync` | sync errors > 0 | critical |
| `DEXPacketDrops` | > 100 DPDK drops/sec | warning |
| `DEXGPUFailure` | GPU unavailable | warning |
### Alertmanager Configuration (`alertmanager/alertmanager.yml`)
- Route grouping: by `alertname`, `cluster`, `service`
- Group wait: 10s, repeat interval: 12h
- Critical alerts route to `critical` receiver (configure webhook/email)
- Inhibition: critical suppresses warning for same `alertname`/`instance`
## Loki Configuration
- Schema: TSDB v13 with filesystem storage
- Ingestion rate: 16 MB/s (burst 32 MB/s)
- Per-stream rate limit: 2 MB/s (burst 4 MB/s)
- Max entries per query: 5000
- Reject samples older than 168h (7 days)
- Retention: 720h (30 days)
- Query cache: 100 MB embedded cache
## Promtail Log Sources
| Job | Path Pattern | Pipeline |
|-----|-------------|----------|
| `docker` | `/var/lib/docker/containers/*/*log` | JSON parse, container name extraction |
| `luxd` | `/avalanche-logs/network_current/node*/logs/*.log` | Multiline, regex for timestamp/level/logger |
| `syslog` | `/var/log/syslog` | Regex for hostname/program/pid |
| `blockscout` | Docker container logs | JSON parse, stream filtering |
## Bare-metal Installer
`grafana/monitoring-installer.sh` -- 5-step installer for Ubuntu validators:
1. `--1` Install Prometheus (systemd service)
2. `--2` Install Grafana (systemd service)
3. `--3` Install node_exporter (systemd service)
4. `--4` Install Lux Grafana dashboards
5. `--5` Install additional dashboards (optional)
Supports both `amd64` and `arm64` architectures. Run without arguments to download latest dashboards only.
## Quickstart
@@ -78,19 +237,34 @@ Pre-configured alert rules:
git clone https://github.com/luxfi/monitoring.git
cd monitoring
# Network-specific compose files (no root compose.yml):
# compose.dex.yml — DEX monitoring
# compose.luxnet.yml — Lux network monitoring
# Create external network if needed
docker network create hanzo-network
# Start via helper script:
# Start the full Lux monitoring stack
./start-monitoring.sh
# Or directly:
docker compose -f compose.luxnet.yml up -d
# Grafana: http://localhost:3100 (default admin/admin)
# Prometheus: http://localhost:9090
# Alertmanager: http://localhost:9093
# Start with DEX monitoring extension
docker compose -f compose.luxnet.yml -f compose.dex.yml up -d
# Access points:
# Grafana: http://localhost:3100 (admin/luxnetwork)
# Prometheus: http://localhost:9090
# Loki: http://localhost:3101
# Alertmanager: http://localhost:9093
# Jaeger (DEX): http://localhost:16686
```
## Production Deployment
`deploy-monitor-nginx.sh` configures nginx reverse proxy for `monitor.lux.network`:
1. Symlinks nginx config to `/etc/nginx/sites-enabled/`
2. Tests and reloads nginx
3. Requires Cloudflare DNS A record pointing to the server
4. Public URL: `https://monitor.lux.network`
## Related Skills
- `lux/lux-node.md` — Node that exports metrics
- `lux/lux-universe.md` — Production K8s infrastructure
- `lux/lux-node.md` -- Node that exports metrics at `/ext/metrics`
- `lux/lux-universe.md` -- Production K8s infrastructure
+343 -24
View File
@@ -1,44 +1,363 @@
---
title: "Lux Netrunner - Network Testing & Simulation"
description: "Lux Netrunner is a network simulation and testing tool for local development."
title: "Lux Netrunner"
description: "Multi-Engine Network Orchestrator"
---
## Overview
Lux Netrunner is a **network simulation and testing tool** for local development. Spin up multi-node networks, run performance benchmarks, and test consensus behavior.
Lux Netrunner is a **multi-engine network orchestration and testing tool** for the Lux blockchain. It manages local multi-node validator networks via a gRPC/REST control plane, supports heterogeneous consensus engines (Lux, Geth, OP Stack, Eth2), and provides snapshot-based state management with incremental BadgerDB backups.
## Quick reference
Not just a test runner -- Netrunner orchestrates full L1/L2/L3 stacks with cross-chain bridging, multi-network management with shared BadgerDB for cross-chain ACID transactions, and YAML-based stack manifests for reproducible environments.
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/netrunner` |
| SDK | `github.com/luxfi/netrunner-sdk` |
| gRPC | Port 8080 |
| HTTP Gateway | Port 8081 |
| Go | 1.26.1 |
| Version | 1.15.0 |
| RPC Version | 42 |
| gRPC Port | 8080 |
| HTTP Gateway | 8081 |
| Default Nodes | 5 |
| License | BSD-3-Clause |
## One-file quickstart
## Architecture
```
┌──────────────────────────────────┐
│ CLI / Client SDK │
└──────────┬───────────────────────┘
│ gRPC / REST
┌──────────▼───────────────────────┐
│ Control Server (server/) │
│ PingService + ControlService │
└──┬───────────┬───────────────────┘
│ │
┌────────────▼──┐ ┌─────▼──────────────────┐
│ Local Network │ │ Multi-Engine Host │
│ (local/) │ │ (orchestrator/) │
│ Lux nodes │ │ Lux/Geth/OP/Eth2 │
└────────┬───────┘ └──────┬─────────────────┘
│ │
┌────────▼───────┐ ┌──────▼─────────────────┐
│ Snapshot Mgr │ │ MultiNet Manager │
│ BadgerDB/zstd │ │ (multinet/) │
└────────────────┘ │ Cross-chain ACID txs │
└────────────────────────┘
```
## gRPC API (rpcpb/rpc.proto)
### PingService
| RPC | HTTP | Description |
|-----|------|-------------|
| `Ping` | `POST /v1/ping` | Health check, returns server PID |
### ControlService
| RPC | HTTP | Description |
|-----|------|-------------|
| `RPCVersion` | `POST /v1/control/rpcversion` | Returns RPC protocol version (42) |
| `Start` | `POST /v1/control/start` | Start a network with config |
| `Stop` | `POST /v1/control/stop` | Stop all nodes |
| `Health` | `POST /v1/control/health` | Check cluster health |
| `WaitForHealthy` | `POST /v1/control/waitforhealthy` | Block until healthy |
| `Status` | `POST /v1/control/status` | Get cluster status |
| `StreamStatus` | `POST /v1/control/streamstatus` | Server-streaming status updates |
| `URIs` | `POST /v1/control/uris` | Get all node URIs |
| `AddNode` | `POST /v1/control/addnode` | Add node to running network |
| `RemoveNode` | `POST /v1/control/removenode` | Remove node from network |
| `RestartNode` | `POST /v1/control/restartnode` | Restart node with new config |
| `PauseNode` | `POST /v1/control/pausenode` | Pause node (preserves state) |
| `ResumeNode` | `POST /v1/control/resumenode` | Resume paused node |
| `CreateBlockchains` | `POST /v1/control/createblockchains` | Deploy custom VM chains |
| `CreateChains` | `POST /v1/control/createchains` | Create participant groups |
| `TransformElasticChains` | `POST /v1/control/transformelasticchains` | Transform to elastic chains |
| `AddPermissionlessValidator` | `POST /v1/control/addpermissionlessvalidator` | Add elastic chain validator |
| `RemoveChainValidator` | `POST /v1/control/removechainvalidator` | Remove chain validator |
| `AttachPeer` | `POST /v1/control/attachpeer` | Attach test peer to node |
| `SendOutboundMessage` | `POST /v1/control/sendoutboundmessage` | Send P2P message via peer |
| `SaveSnapshot` | `POST /v1/control/savesnapshot` | Save network snapshot |
| `SaveHotSnapshot` | `POST /v1/control/savehotsnapshot` | Hot snapshot (no stop) |
| `LoadSnapshot` | `POST /v1/control/loadsnapshot` | Restore from snapshot |
| `RemoveSnapshot` | `POST /v1/control/removesnapshot` | Delete snapshot |
| `GetSnapshotNames` | `POST /v1/control/getsnapshotnames` | List all snapshots |
### StartRequest Fields
```protobuf
message StartRequest {
string network_name = 1; // "mainnet", "testnet", "devnet", "custom"
string node_type = 2; // "luxd", "avalanchego", "geth", "op-node", "custom"
string exec_path = 4;
optional uint32 num_nodes = 5;
optional string global_node_config = 7;
optional string root_data_dir = 8;
string plugin_dir = 9;
repeated BlockchainSpec blockchain_specs = 10;
map<string, string> custom_node_configs = 11;
map<string, string> chain_configs = 12;
map<string, string> upgrade_configs = 13;
optional bool reassign_ports_if_used = 14;
optional bool dynamic_ports = 15;
}
```
## Client SDK
```go
import "github.com/luxfi/netrunner-sdk"
import "github.com/luxfi/netrunner/client"
// Create 5-node local network
network, _ := netrunner.New(netrunner.Config{
NodeCount: 5,
LogLevel: "info",
})
cli, _ := client.New(client.Config{
Endpoint: "localhost:8080",
DialTimeout: 10 * time.Second,
}, logger)
defer cli.Close()
// Start network
network.Start(ctx)
defer network.Stop(ctx)
// Start 5-node local network
resp, _ := cli.Start(ctx, "/usr/local/bin/luxd",
client.WithNumNodes(5),
client.WithDynamicPorts(true),
client.WithPluginDir("/path/to/plugins"),
client.WithChainSpecs([]*rpcpb.BlockchainSpec{{
VmName: "chainevm",
Genesis: "/path/to/genesis.json",
}}),
)
// Wait for health
cli.WaitForHealthy(ctx)
// Get node URIs
uris := network.GetNodeURIs()
// ["http://localhost:9650", "http://localhost:9652", ...]
uris, _ := cli.URIs(ctx)
// Run benchmark
results, _ := network.Benchmark(ctx, netrunner.BenchmarkConfig{
Duration: 60 * time.Second,
TxRate: 1000,
// Manage nodes
cli.PauseNode(ctx, "node3")
cli.ResumeNode(ctx, "node3")
cli.RestartNode(ctx, "node1", client.WithExecPath("/new/luxd"))
cli.AddNode(ctx, "node6", "/usr/local/bin/luxd")
cli.RemoveNode(ctx, "node6")
// Snapshots (incremental BadgerDB + zstd compression)
cli.SaveSnapshot(ctx, "pre-upgrade")
cli.SaveHotSnapshot(ctx, "live-backup") // No network stop
cli.LoadSnapshot(ctx, "pre-upgrade")
// P2P testing
attachResp, _ := cli.AttachPeer(ctx, "node1")
cli.SendOutboundMessage(ctx, "node1", attachResp.AttachedPeerInfo.Id, 0, msgBytes)
// Elastic chains
cli.TransformElasticChains(ctx, []*rpcpb.ElasticChainSpec{{
ChainId: "chain-id",
AssetName: "TEST",
AssetSymbol: "TST",
MinValidatorStake: 1000,
}})
cli.AddPermissionlessValidator(ctx, []*rpcpb.PermissionlessValidatorSpec{{
ChainId: "chain-id",
NodeName: "node1",
StakedTokenAmount: 5000,
}})
cli.Stop(ctx)
```
## Multi-Engine Orchestrator (orchestrator/)
The orchestrator runs heterogeneous consensus engines in a single host.
### Supported Engines
| Engine | Type | Description |
|--------|------|-------------|
| Lux | `lux` | Lux Snow consensus (luxd) |
| Geth | `geth` | Go-Ethereum execution client |
| OP Stack | `op` | Optimism OP node (L2) |
| Eth2 | `eth2` | Ethereum 2.0 beacon + execution |
### Engine Interface
```go
type Engine interface {
Name() string
Type() EngineType
Start(ctx context.Context, config *NodeConfig) error
Stop(ctx context.Context) error
Restart(ctx context.Context) error
Health(ctx context.Context) (*HealthStatus, error)
IsRunning() bool
Uptime() time.Duration
NetworkID() uint32
ChainID() ids.ID
RPCEndpoint() string
WSEndpoint() string
P2PEndpoint() string
ParentChain() *ChainInfo // nil for L1s
Metrics() map[string]interface{}
}
```
### Stack Manifests (stacks/)
YAML-based definitions for multi-engine stacks:
```yaml
# stacks/lux-local.yaml
name: lux-local
version: 1.0.0
description: Local Lux L1 for testing
engines:
- name: lux-node-1
type: lux
network_id: 96369
http_port: 9650
staking_port: 9651
log_level: info
wait_healthy: true
extra:
dev-mode: true
networks:
- name: lux-local
type: l1
engine: lux-node-1
chain_id: 96369
```
Predefined stacks: `lux-local`, `lux-mainnet-5node`, `lux-testnet-5node`, `lux-mainnet-alt`, `lux-l1-l2-local`, `lux-avalanche-bridge`.
Bridge config supports types: `awm`, `ibc`, `ccip`.
## Multi-Network Manager (multinet/)
Runs multiple heterogeneous networks in parallel with shared BadgerDB for cross-chain ACID transactions.
```go
mgr, _ := multinet.NewMultiNetworkManager(logger, "/tmp/shared-db")
defer mgr.Shutdown()
mgr.AddNetwork(multinet.NetworkConfig{
NetworkID: 1, Name: "mainnet", Type: multinet.NetworkTypePrimary,
Validators: 5,
})
fmt.Printf("TPS: %.0f, Finality: %v\n", results.TPS, results.AvgFinality)
mgr.AddNetwork(multinet.NetworkConfig{
NetworkID: 2, Name: "chain-a", Type: multinet.NetworkTypeChain,
ParentID: 1,
})
mgr.StartAll()
// Cross-chain ACID transaction
mgr.SubmitCrossChainTx(&multinet.CrossChainTx{
ID: "tx-1", SourceNet: 1, DestNet: 2,
Amount: 1000, Asset: "LUX",
})
```
Consensus params are configurable per network (K, Alpha, BetaVirtuous, BetaRogue, ConcurrentPolls).
## Snapshot System
Snapshots use native BadgerDB incremental backup with zstd compression.
| Feature | Detail |
|---------|--------|
| Format | BadgerDB native backup + zstd |
| Manifest | `manifest.json` (version 2) |
| Incremental | Yes, tracks `db_version` per node |
| Hot snapshot | Supported (no network stop) |
| Admin API | `admin.snapshot` / `admin.load` |
| Storage | `~/.netrunner/snapshots/lux-snapshot-{name}/` |
Snapshot contents: `network.json` (full config), `state.json` (elastic chain mapping), `{nodeName}.backup.zst` (per-node compressed backup), `manifest.json`.
## Local Network (local/)
Core local network implementation managing luxd processes:
| Constant | Value |
|----------|-------|
| Default nodes | 5 |
| Health check interval | 100ms |
| Stop timeout | 30s |
| Peer start timeout | 30s |
| Staking key file | `luxtls.key` |
| Staking cert file | `luxtls.crt` |
| Signer key file | `signer.key` |
The `network.Network` interface provides:
- Node lifecycle: `AddNode`, `RemoveNode`, `PauseNode`, `ResumeNode`, `RestartNode`
- Chain management: `CreateChains`, `CreateParticipantGroups`, `TransformChain`
- Elastic chains: `AddPermissionlessValidators`, `RemoveChainValidators`
- Snapshots: `SaveSnapshot`, `SaveHotSnapshot`, `LoadSnapshot`
## Key Dependencies (from go.mod)
| Package | Version | Purpose |
|---------|---------|---------|
| `github.com/luxfi/node` | v1.23.21 | Lux node types |
| `github.com/luxfi/sdk` | v1.16.46 | Client SDK (admin API) |
| `github.com/luxfi/p2p` | v1.19.2-zap | P2P networking |
| `github.com/luxfi/consensus` | v1.22.69 | Consensus engine |
| `github.com/luxfi/crypto` | v1.17.42 | BLS/secp256k1 keys |
| `github.com/luxfi/genesis` | v1.6.1 | Genesis generation |
| `github.com/luxfi/ids` | v1.2.9 | ID types (NodeID, etc) |
| `github.com/luxfi/evm` | v0.8.30 | EVM plugin |
| `github.com/luxfi/vm` | v1.0.38 | VM interface |
| `github.com/luxfi/config` | v1.1.1 | Node configuration |
| `github.com/luxfi/tls` | v1.0.3 | TLS certificate handling |
| `github.com/luxfi/rpc` | v1.0.0 | RPC layer |
| `github.com/dgraph-io/badger/v4` | v4.9.0 | Database (shared DB) |
| `google.golang.org/grpc` | v1.79.1 | gRPC framework |
| `k8s.io/client-go` | v0.35.1 | K8s engine support |
| `github.com/klauspost/compress` | v1.18.4 | zstd compression |
| `github.com/spf13/cobra` | v1.10.2 | CLI commands |
## CLI Commands
| Command | Description |
|---------|-------------|
| `netrunner server` | Start gRPC + HTTP gateway server |
| `netrunner control start` | Start network via RPC |
| `netrunner control stop` | Stop network via RPC |
| `netrunner ping` | Ping server |
| `netrunner genkeys` | Generate staking keys |
| `netrunner testkeys` | Generate test keys |
## Build
```bash
make build # Build netrunner binary
make test # Run tests
make test-race # Tests with race detector
make bench # Run benchmarks
make build-all # Cross-compile (linux/darwin/windows, amd64/arm64)
make install # Install to /usr/local/bin
make lint # golangci-lint
make release # Generate release artifacts
```
## Directory Structure
```
netrunner/
main.go # Entry point
cmd/ # CLI commands (server, control, ping, genkeys)
server/ # gRPC + HTTP gateway server
client/ # Go client SDK
rpcpb/ # Protobuf definitions
local/ # Local network implementation (process management)
network/ # Network interface + config + genesis generation
orchestrator/ # Multi-engine host (Lux/Geth/OP/Eth2)
engines/ # Engine interface + implementations (lux, geth, k8s, opstack, eth2)
multinet/ # Multi-network manager with shared BadgerDB
stacks/ # YAML stack manifests
api/ # API client wrapper
utils/ # Utilities (color picker, JSON helpers)
tests/ # Integration tests
examples/ # Usage examples
build/ # Build output
```
+355 -16
View File
@@ -1,25 +1,364 @@
---
title: "Lux P2P - Peer-to-Peer Networking"
description: "Lux P2P networking layer — libp2p integration, mDNS peer discovery, publish-subscribe messaging for consensus and state propagation."
title: "Lux P2P Networking"
description: "Node-to-Node Communication Layer"
---
## Overview
Lux P2P networking layer — libp2p integration, mDNS peer discovery, publish-subscribe messaging for consensus and state propagation.
The Lux P2P layer handles all node-to-node communication across the Lux consensus network. It is split across two complementary Go modules: `github.com/luxfi/node/network` (the node-integrated networking stack with TLS peer management, throttling, and health checks) and `github.com/luxfi/p2p` (application-level protocol abstraction for gossip, request-response, bloom filter set reconciliation, and validator-aware routing). Together they provide peer discovery, message routing, gossip propagation, bandwidth-aware peer selection, and multi-layer throttling.
## Components
## Modules
| Component | Path | Purpose |
|-----------|------|---------|
| net/ | ``github.com/luxfi/net`` | Core networking |
| p2p/ | ``github.com/luxfi/p2p`` | P2P protocols |
| libp2p/ | ``github.com/libp2p/go-libp2p`` | libp2p integration |
| mdns/ | ``github.com/luxfi/mdns`` | mDNS peer discovery |
| pubsub/ | ``github.com/luxfi/pubsub`` | PubSub messaging |
| Module | Go Version | Key Dependencies |
|--------|-----------|-----------------|
| `github.com/luxfi/node/network` | 1.26.1 | `luxfi/consensus`, `luxfi/crypto/bls`, `luxfi/ids`, `luxfi/warp`, `luxfi/node/message`, `luxfi/validators`, `luxfi/compress` |
| `github.com/luxfi/p2p` | 1.26.1 | `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `google.golang.org/[email protected]` |
## Key Concepts
## Node Network Layer (luxfi/node/network)
- **Peer discovery**: mDNS for local, DHT for global
- **Message routing**: Gossip protocol for block/tx propagation
- **PubSub topics**: Per-chain topic subscriptions
- **Connection management**: Peer scoring, rate limiting
### Network Config
The `Config` struct in `network/config.go` controls all networking parameters:
```go
type Config struct {
HealthConfig // Health check parameters
PeerListGossipConfig // Peer list gossip settings
TimeoutConfig // Ping/pong, handshake timeouts
DelayConfig // Reconnect delay (exponential backoff)
ThrottlerConfig // Inbound/outbound message throttling
ProxyEnabled bool // PROXY protocol support
ProxyReadHeaderTimeout time.Duration
MyNodeID ids.NodeID
MyIPPort *utils.Atomic[netip.AddrPort]
NetworkID uint32
MaxClockDifference time.Duration
PingFrequency time.Duration
AllowPrivateIPs bool
SupportedLPs set.Set[uint32] // LP proposals this node supports
ObjectedLPs set.Set[uint32] // LP proposals this node objects to
CompressionType compression.Type
TLSKey crypto.Signer
BLSKey bls.Signer
TrackedChains set.Set[ids.ID]
Beacons validators.Manager
Validators validators.Manager
// SequencerIDForChain returns the validator-set identity that sequences chainID
// Examples: C-Chain -> PrimaryNetworkID, Zoo L2 -> ZooChainID
SequencerIDForChain func(chainID ids.ID) ids.ID
GenesisBytes []byte
UptimeCalculator uptime.Calculator
UptimeMetricFreq time.Duration
UptimeRequirement float64
RequireValidatorToConnect bool
MaximumInboundMessageTimeout time.Duration
PeerReadBufferSize int
PeerWriteBufferSize int
ResourceTracker consensustracker.ResourceTracker
CPUTargeter tracker.Targeter
DiskTargeter tracker.Targeter
}
```
### Health Checks
The `HealthConfig` enables continuous network health monitoring:
```go
type HealthConfig struct {
Enabled bool
NoIngressValidatorConnectionGracePeriod time.Duration
MinConnectedPeers uint // Minimum peers for healthy
MaxTimeSinceMsgReceived time.Duration // Max silence before unhealthy
MaxTimeSinceMsgSent time.Duration
MaxPortionSendQueueBytesFull float64 // (0,1]
MaxSendFailRate float64 // [0,1]
SendFailRateHalflife time.Duration
}
```
Health check keys exposed: `"primary network validator health"`, `"connectedPeers"`, `"timeSinceLastMsgReceived"`, `"timeSinceLastMsgSent"`, `"sendFailRate"`.
### Peer List Gossip
```go
type PeerListGossipConfig struct {
PeerListNumValidatorIPs uint32 // Validator IPs per gossip round
PeerListPullGossipFreq time.Duration // How often to request IPs
PeerListBloomResetFreq time.Duration // Bloom filter recalculation interval
}
```
### IP Tracker
`ip_tracker.go` maintains a bloom filter of known peer IPs for efficient gossip deduplication. Tracks claimed and connected IPs with timestamped entries. Supports gossip-based peer discovery via signed IP announcements.
### No-Ingress Connection Alert
`no_ingress_conn_alert.go` monitors validator nodes that have no inbound connections (indicates firewall/NAT issues). Reports unhealthy after the configured grace period.
## Application Protocol Layer (luxfi/p2p)
### Package Layout
```
github.com/luxfi/p2p/
network.go Network (top-level coordinator), Peers, PeerSampler, ClientOption
handler.go Handler interface (Gossip/Request), NoOpHandler, ValidatorHandler, responder
router.go router (message dispatch by handlerID), ParseMessage, metrics
client.go Client (RequestAny, Request, Gossip), ResponseCallback, PrefixMessage
sender.go Sender interface (SendRequest/SendResponse/SendError/SendGossip), SendConfig
error.go Error type with codes: ErrUnexpected(-1), ErrUnregisteredHandler(-2),
ErrNotValidator(-3), ErrThrottled(-4)
validators.go Validators (ValidatorSet/ValidatorSubset/NodeSampler), stake-weighted sampling
node_sampler.go NodeSampler interface (Sample)
peer_tracker.go PeerTracker (bandwidth-based peer selection), bandwidthHeap, exponential decay
throttler.go SlidingWindowThrottler (per-node rate limiting)
gossip/
gossipable.go Gossipable interface (GossipID), Marshaller, Set
gossip.go PullGossiper, PushGossiper, ValidatorGossiper, BranchingFactor, Every()
bloom.go BloomFilter (probabilistic membership, auto-reset)
handler.go Gossip protocol handler
message.go MarshalAppRequest/ParseAppResponse/MarshalAppGossip/ParseAppGossip
throttling/
bandwidth_throttler.go Token-bucket bandwidth throttler (rate.Limiter)
inbound_msg_throttler.go Composite inbound message throttler
inbound_msg_byte_throttler.go Byte-level inbound throttling
inbound_msg_buffer_throttler.go Buffer-level throttling
inbound_conn_throttler.go Connection rate throttling
inbound_conn_upgrade_throttler.go TLS upgrade throttling
inbound_resource_throttler.go Resource-based throttling
outbound_msg_throttler.go Outbound message throttling
dial_throttler.go Outbound dial throttling
peer/
peer.go Peer connection management (~33KB, largest file)
config.go Peer configuration
set.go Peer set with thread-safe operations
info.go Peer metadata (NodeID, version, IP)
gossip_tracker.go Per-peer gossip tracking
ip.go Peer IP management
ip_signer.go IP signature for peer identity
tls_config.go TLS configuration for peer connections
message_queue.go Priority message queue per peer
bounded_queue.go Bounded queue implementation
upgrader.go Connection upgrade (TCP -> TLS)
validator_id.go Validator identity
message/
ops.go Message operation types (all consensus + app messages)
messages.go Message serialization/deserialization
inbound_msg_builder.go Inbound message construction
outbound_msg_builder.go Outbound message construction
internal_msg_builder.go Internal message construction
creator.go Message creator
lp118/
lp118.go LP-118 signature request protocol
aggregator.go Signature aggregation
tracker/
resource_tracker.go CPU/bandwidth resource tracking
targeter_impl.go Target selection for throttling
proto/
pb/p2p/p2p.pb.go Protobuf-generated message types
```
### Network
`Network` is the top-level coordinator. It tracks connected peers, routes messages, and creates protocol-specific clients.
```go
import "github.com/luxfi/p2p"
// Create network with metrics
net, err := p2p.NewNetwork(logger, sender, registerer, "myvm")
// Register a handler for a protocol
err = net.AddHandler(p2p.TxGossipHandlerID, myHandler)
// Create a client for sending messages
client := net.NewClient(p2p.TxGossipHandlerID)
// Peer connect/disconnect callbacks (implements validators.Connector)
net.Connected(ctx, nodeID, version)
net.Disconnected(ctx, nodeID)
```
### Handler Interface
Server-side protocol logic. Two methods: `Gossip` (fire-and-forget) and `Request` (request-response with deadline).
```go
type Handler interface {
Gossip(ctx context.Context, nodeID ids.NodeID, gossipBytes []byte)
Request(ctx context.Context, nodeID ids.NodeID, deadline time.Time, requestBytes []byte) ([]byte, *Error)
}
```
Standard handler IDs: `TxGossipHandlerID=0`, `AtomicTxGossipHandlerID=1`, `SignatureRequestHandlerID=2` (LP-118).
`ValidatorHandler` wraps any handler and drops messages from non-validators. `NoOpHandler` drops everything.
### Client
Client-side message sending. Messages are prefixed with a varint-encoded handler ID for routing.
```go
// Request to a random peer
client.RequestAny(ctx, requestBytes, func(ctx context.Context, nodeID ids.NodeID, response []byte, err error) {
// handle response
})
// Request to specific peers
client.Request(ctx, nodeIDs, requestBytes, onResponse)
// Gossip to peers
client.Gossip(ctx, p2p.SendConfig{
Validators: 3,
NonValidators: 5,
Peers: 2,
}, gossipBytes)
```
Request IDs use odd numbers (SDK invariant), incremented by 2 per request.
### Sender Interface
Transport abstraction with four operations: `SendRequest`, `SendResponse`, `SendError`, `SendGossip`.
`SendConfig` controls gossip fanout: specific `NodeIDs`, random `Validators`, `NonValidators`, and `Peers` counts.
### Router
Internal message dispatch. Routes by handler ID prefix (varint). Tracks pending requests with callbacks. Fatal on protocol errors (unrequested responses, etc.). Collects per-handler metrics (message time, count).
### PeerTracker
Bandwidth-aware peer selection using a max-heap ordered by exponentially-weighted moving average (EWMA) bandwidth. Halflife: 5 minutes. Parameters:
- `desiredMinResponsivePeers = 20` -- below this, always prefer untracked peers
- `newPeerConnectFactor = 0.1` -- exponential decay for new peer probability
- `randomPeerProbability = 0.2` -- 20% chance of random peer (avoid local optima)
Selection priority: untracked peers (exploration) > bandwidth heap (exploitation) > responsive peers (random) > any tracked peer.
### Throttling
`SlidingWindowThrottler` uses a two-window sliding algorithm for per-node rate limiting. Estimates hit count by weighting the previous window proportionally to elapsed time.
The `throttling/` package provides comprehensive transport-level throttling:
- **Bandwidth**: Token-bucket per peer (refill rate + burst size)
- **Inbound messages**: Byte-level, buffer-level, connection-level, and resource-based
- **Outbound messages**: Per-peer rate limiting
- **Connections**: Dial throttling, upgrade throttling
## Gossip Subsystem
### PullGossiper
Polls peers for unknown gossipables using bloom filter set difference. Configurable `pollSize` (number of parallel requests per cycle).
### PushGossiper
Broadcasts new gossipables proactively. Maintains two queues: `toGossip` (unsent) and `toRegossip` (already-sent). Features:
- **BranchingFactor**: `StakePercentage` (top validators by stake), `Validators` (uniform sample), `NonValidators`, `Peers`
- **Regossip**: Separate branching factor, max frequency limit, LRU discarded cache
- **Target size**: Batches gossipables up to `targetGossipSize` bytes per cycle
### BloomFilter
Probabilistic membership testing for efficient set reconciliation. Auto-resets when false positive rate exceeds threshold. Parameters: `minTargetElements`, `targetFalsePositiveProbability`, `resetFalsePositiveProbability`. Uses SHA-256 with random salt, 1-16 hash functions.
### Gossipable Interface
```go
type Gossipable interface {
GossipID() ids.ID
}
type Set[T Gossipable] interface {
Add(T) error
Has(ids.ID) bool
Iterate(func(T) bool)
GetFilter() (bloom []byte, salt []byte)
}
```
## Validators
`Validators` implements `ValidatorSet`, `ValidatorSubset`, and `NodeSampler`. Refreshes validator set from consensus state with configurable staleness (`maxValidatorSetStaleness`). Sorts validators by descending weight. `Top()` returns validators covering a target stake percentage. `Sample()` returns connected validators. `Has()` checks membership (connected + in validator set).
## Peer Management (peer/)
The `peer/` package in `luxfi/node/network/peer` handles individual peer connections:
- **TLS-based identity**: Certificate = node ID (32 bytes from TLS cert hash)
- **Priority message queuing**: Bounded buffers with priority levels
- **Per-peer gossip tracking**: Which gossipables each peer knows about
- **Connection upgrade**: TCP to TLS with rate limiting
- **IP signing**: Signed IP announcements for peer discovery
- **Metrics**: Per-peer message counts, bandwidth, latency
Key files:
- `peer.go` (32KB): Full peer connection lifecycle, message send/receive, keepalive
- `set.go`: Thread-safe peer set with O(1) lookup and iteration
- `gossip_tracker.go`: Tracks which gossipable items each peer has seen
- `endpoint_signer.go`: Signs IP/port pairs for verifiable peer announcements
- `host.go`: Peer host identity management
## Message Layer (message/)
The `message/` package handles serialization of all consensus and application messages using protobuf. Defines operation types for all message categories:
- **Consensus**: Chits, PullQuery, PushQuery, Put, Get, Accepted, AcceptedFrontier
- **App**: AppRequest, AppResponse, AppGossip, AppError
- **State Sync**: StateSummaryFrontier, AcceptedStateSummary
Builders for inbound, outbound, and internal messages with creator pattern.
## LP-118 Protocol
`lp118/` implements the LP-118 signature request protocol for cross-chain Warp messaging. The aggregator collects BLS signatures from validators and combines them for cross-chain message verification.
## Error Codes
| Code | Constant | Meaning |
|------|----------|---------|
| -1 | `ErrUnexpected` | Generic handler failure |
| -2 | `ErrUnregisteredHandler` | No handler for protocol ID |
| -3 | `ErrNotValidator` | Sender is not a validator |
| -4 | `ErrThrottled` | Rate limit exceeded |
## Metrics
Both modules expose Prometheus metrics:
- `{namespace}_msg_time` (gauge vec): Handler message processing time in nanoseconds
- `{namespace}_msg_count` (counter vec): Handler message count
- `{namespace}_num_tracked_peers` (gauge): PeerTracker tracked count
- `{namespace}_num_responsive_peers` (gauge): PeerTracker responsive count
- `{namespace}_average_bandwidth` (gauge): PeerTracker average bandwidth
- `{namespace}_gossip_count` (counter vec): Gossip message count by io/type
- `{namespace}_gossip_bytes` (counter vec): Gossip bytes by io/type
- `{namespace}_gossip_tracking` (gauge vec): Currently tracked gossipables
- `{namespace}_bloom_*` (gauge/counter): Bloom filter statistics
## Testing
Test utilities in `p2ptest/`:
- `client.go`: Test client with mock sender
- `app_sender.go`: In-memory app sender for tests
- `warp_sender.go`: In-memory warp sender for tests
+165 -11
View File
@@ -1,22 +1,176 @@
---
title: "Lux Research Papers - Academic & Technical Whitepapers"
description: "Academic and technical whitepapers covering Lux consensus proofs, cryptographic protocols, and network design."
title: "Lux Papers"
description: "Academic and Technical Whitepapers"
---
## Overview
Academic and technical whitepapers covering Lux consensus proofs, cryptographic protocols, and network design.
The Lux papers repository (`github.com/luxfi/papers`) contains 35+ LaTeX research papers and technical specifications covering the full breadth of the Lux Network: consensus protocols, post-quantum cryptography, DeFi protocols, governance frameworks, privacy systems, cross-chain communication, and application-specific chains. Also includes a dedicated FHE (Fully Homomorphic Encryption) sub-directory with four specialized papers. All papers are authored in LaTeX with BibTeX references.
## Quick reference
## Repository
| Item | Value |
|------|-------|
| Format | LaTeX, PDF |
| Repo | `github.com/luxfi/papers` |
| Local | `~/work/lux/papers/` |
| Format | LaTeX (.tex), BibTeX (.bib), PDF |
| License | See LICENSE |
## Key Papers
## Paper Catalog
- Snow consensus family proof of safety and liveness
- Post-quantum lattice-based signature schemes
- FHE coprocessor architecture
- Subnet security model
- Cross-chain warp messaging protocol
### Consensus
| File | Title | Topic |
|------|-------|-------|
| `lux-consensus.tex` | (Lux Consensus) | Core Snow consensus family: safety and liveness proofs |
| `lux-fpc-consensus.tex` | (FPC Consensus) | Fast Probabilistic Consensus variant |
| `lux-quantum-consensus.tex` | Lux Quantum Consensus: Post-Quantum Secure Multi-Consensus Architecture | Quantum-resistant consensus with multiple engines |
| `lux-quasar-consensus.tex` | Quasar: Quantum-Secure Multi-Engine Consensus with Dual-Certificate Finality | Dual-certificate finality with quantum security |
### Cryptography and Post-Quantum
| File | Title | Topic |
|------|-------|-------|
| `lux-ethfalcon-post-quantum.tex` | ETHFALCON: EVM-Optimized Post-Quantum Signatures | Lattice-based signatures optimized for EVM execution |
| `lux-universal-threshold-signatures.tex` | Universal Threshold Signatures: Multi-Chain Cryptographic Infrastructure with Post-Quantum Security | Threshold signature schemes across chains |
| `lux-ntt-transform.tex` | (NTT Transform) | Number Theoretic Transform for post-quantum operations |
### Cross-Chain and Interoperability
| File | Title | Topic |
|------|-------|-------|
| `lux-bridge.tex` | Lux Bridge: Zero-Knowledge Cross-Chain Communication with Sub-Second Finality | ZK bridge protocol with fast finality |
| `lux-interchain-transfers.tex` | (Interchain Transfers) | Cross-chain asset transfer protocol |
| `lux-warp-messaging.tex` | (Warp Messaging) | Cross-subnet message passing |
### Application-Specific Chains
| File | Title | Topic |
|------|-------|-------|
| `lux-achain-attestation.tex` | A-Chain: Unified Trusted Execution Environment Attestation for Decentralized AI Compute | TEE attestation for AI compute |
| `lux-gchain-graphql.tex` | G-Chain: Unified GraphQL Query Engine with Decentralized Indexing for Multi-Chain State | Decentralized GraphQL indexing chain |
| `lux-mchain-mpc.tex` | M-Chain: Decentralized Multi-Party Computation Custody with Quantum-Safe Threshold Signatures | MPC custody with quantum safety |
| `lux-zchain.tex` | Lux Z-Chain: Privacy-Preserving Smart Contracts with Zero-Knowledge Proofs | Private smart contract execution |
### DeFi Protocols
| File | Title | Topic |
|------|-------|-------|
| `lux-lightspeed-dex.tex` | Lux Lightspeed DEX: High-Frequency Trading at the Speed of Light | High-frequency DEX design |
| `lux-credit-lending.tex` | Lux Credit: Zero-Interest Self-Repaying Lending Protocol with 90% LTV and Cross-Chain Collateral | Self-repaying lending protocol |
| `lux-liquid-staking.tex` | (Liquid Staking) | Liquid staking derivatives |
| `lux-perpetuals-derivatives.tex` | (Perpetuals and Derivatives) | On-chain perpetual futures |
| `lux-restaking.tex` | Restaking Protocol for Lux Network Security Extension | Restaking for extended security |
| `lux-market-nft.tex` | (NFT Market) | NFT marketplace protocol |
### Governance and Identity
| File | Title | Topic |
|------|-------|-------|
| `lux-governance-dao.tex` | Lux Governance: Unified DAO Framework for Multi-Ecosystem Coordination | DAO governance framework |
| `lux-dao-governance-framework.tex` | (DAO Governance Framework) | Extended governance specification |
| `lux-id-did-specification.tex` | (Lux ID DID Specification) | Decentralized Identifier standard |
| `lux-id-iam.tex` | (Lux ID IAM) | Identity and Access Management protocol |
### Economics
| File | Title | Topic |
|------|-------|-------|
| `lux-economics.tex` | Appchain Economics: Incentive Design for Application-Specific Chains | Economic model for app chains |
| `lux-tokenomics.tex` | (Tokenomics) | Token distribution and supply model |
| `lux-validator-economics.tex` | (Validator Economics) | Validator reward and slashing mechanics |
### Infrastructure and Scaling
| File | Title | Topic |
|------|-------|-------|
| `lux-data-availability.tex` | (Data Availability) | DA layer design |
| `lux-state-sync.tex` | (State Sync) | Fast state synchronization protocol |
| `lux-verkle-trees.tex` | (Verkle Trees) | Verkle tree state commitments |
| `lux-fraud-proofs.tex` | (Fraud Proofs) | Fraud proof system for rollups |
| `lux-evm-precompiles.tex` | (EVM Precompiles) | Custom EVM precompiled contracts |
| `lux-oracle-infrastructure.tex` | (Oracle Infrastructure) | Decentralized oracle design |
### Privacy and Security
| File | Title | Topic |
|------|-------|-------|
| `lux-privacy-pool.tex` | (Privacy Pool) | Privacy-preserving transaction pool |
| `lux-tee-computing-mesh.tex` | (TEE Computing Mesh) | Trusted Execution Environment compute network |
## FHE (Fully Homomorphic Encryption) Papers
Located in `~/work/lux/papers/fhe/` with four sub-directories, each containing `main.tex`, `main.pdf`, and `references.bib`:
| Directory | Topic |
|-----------|-------|
| `fhe/fhevm/` | FHE Virtual Machine -- encrypted smart contract execution |
| `fhe/fhecrdt/` | FHE CRDTs -- conflict-free replicated data types with homomorphic encryption |
| `fhe/voting/` | FHE Voting -- privacy-preserving on-chain voting |
| `fhe/ml-privacy/` | FHE ML Privacy -- machine learning with encrypted data |
### FHE Shared Resources
`fhe/shared/` contains common LaTeX macros and BibTeX entries shared across all FHE papers.
## Additional Documents
| File | Purpose |
|------|---------|
| `AUTHORSHIP_STANDARD.md` | Paper authorship guidelines |
| `LUX_ID_SUMMARY.md` | Summary of Lux ID specifications |
| `lux-dao-paper-summary.md` | DAO governance paper summary |
| `LLM.md` | AI assistant guidance for the repo |
## Research Areas Summary
The papers span seven major research domains:
1. **Consensus** (4 papers): Snow family, FPC, quantum-secure consensus, Quasar dual-certificate
2. **Cryptography** (3 papers): Post-quantum signatures (ETHFALCON), threshold signatures, NTT
3. **Cross-Chain** (3 papers): ZK bridge, interchain transfers, warp messaging
4. **App Chains** (4 papers): A-Chain (TEE/AI), G-Chain (GraphQL), M-Chain (MPC), Z-Chain (ZK privacy)
5. **DeFi** (6 papers): DEX, lending, liquid staking, perpetuals, restaking, NFT market
6. **Governance/Identity** (4 papers): DAO framework, DID specification, IAM
7. **Infrastructure** (8 papers): DA, state sync, verkle trees, fraud proofs, precompiles, oracles, privacy pools, TEE mesh
8. **FHE** (4 papers): FHEVM, CRDTs, voting, ML privacy
## Building Papers
```bash
cd ~/work/lux/papers
# Build a specific paper
pdflatex lux-consensus.tex
bibtex lux-consensus
pdflatex lux-consensus.tex
pdflatex lux-consensus.tex
# Build FHE papers
cd fhe/fhevm
pdflatex main.tex
bibtex main
pdflatex main.tex
pdflatex main.tex
# Build all FHE papers
cd fhe && make
```
## Key Themes Across Papers
- **Post-quantum readiness**: Multiple papers address quantum resistance (ETHFALCON, Quasar, universal threshold sigs, quantum consensus)
- **Multi-chain architecture**: Papers define how subnets/L2s interact (warp messaging, interchain transfers, bridge)
- **Application-specific chains**: Dedicated chain designs for specific workloads (AI compute, MPC custody, privacy, GraphQL)
- **Privacy**: Z-Chain ZK proofs, privacy pools, FHE for computation privacy
- **Economic sustainability**: Tokenomics, validator economics, appchain incentive design
## Related Repos
| Repo | Purpose |
|------|---------|
| `github.com/luxfi/node` | Node implementation of consensus protocols |
| `github.com/luxfi/evm` | EVM execution engine (precompiles paper) |
| `github.com/luxfi/bridge` | Bridge implementation (bridge paper) |
| `github.com/luxfi/crypto` | Cryptographic library (ETHFALCON, threshold sigs) |
| `github.com/luxfi/docs` | Documentation referencing these papers |
+279 -44
View File
@@ -1,97 +1,332 @@
---
title: "Lux Plugins Core - VM & Subnet Plugin Registry"
description: "## Quick reference"
title: "Lux Plugins Core"
description: "VM & Subnet Plugin Registry"
---
## Overview
Lux Plugins Core is the **official plugin repository** for the Lux Plugin Manager (LPM). It contains YAML definitions for virtual machines and subnets that LPM uses to download, install, and manage VM binaries on Lux nodes.
Lux Plugins Core is the **official plugin repository** for the Lux Plugin Manager (LPM). It ships with LPM as the default repository and contains YAML definitions for virtual machines and subnets. LPM uses these definitions to download, install, verify, and manage VM binaries on Lux nodes. Community-driven -- anyone can submit a new VM or subnet via pull request.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/plugins-core` |
| Local | `~/work/lux/plugins-core/` |
| Branch | `master` |
| Format | YAML definition files |
| Tool | Lux Plugin Manager (LPM) |
| Maintainer | `[email protected]` |
| License | Open |
## Repository Structure
```
plugins-core/
├── vms/ — VM definitions
│ ├── blobvm.yaml — Content-addressable KV store VM
│ ├── spacesvm.yaml — Hierarchical storage VM
│ └── subnet-evm.yaml — Subnet EVM (Solidity smart contracts)
├── subnets/ — Subnet definitions
│ ├── spaces.yaml — Spaces Subnet Demo
│ └── zoo.yaml — Zoo subnet
└── examples/ — Template files
├── vm.yaml — VM definition template
└── subnet.yaml — Subnet definition template
vms/ -- VM definitions (one YAML per VM)
blobvm.yaml Content-addressable KV store VM
spacesvm.yaml Hierarchical storage VM
subnet-evm.yaml Subnet EVM (Solidity smart contracts)
subnets/ -- Subnet definitions (one YAML per subnet)
spaces.yaml Spaces Subnet Demo (SpacesVM)
wagmi.yaml Zoo EVM Demo (high-throughput testbed)
examples/ -- Template files for contributors
vm.yaml VM definition template
subnet.yaml Subnet definition template
README.md -- Contributing guide
LICENSE
```
## Registered VMs
| VM | Alias | ID | Version |
|----|-------|----|---------|
| BlobVM | `blobvm` | `kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8` | 0.0.6 |
| SpacesVM | `spacesvm` | `sqja3uK17MJxfC7AN8nGadBw9JK5BcrsNwNynsqP5Gih8M5Bm` | 0.0.3 |
| Subnet EVM | `subnet-evm` | `srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy` | 0.2.7 |
### BlobVM
| Field | Value |
|-------|-------|
| Alias | `blobvm` |
| VM ID | `kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8` |
| Version | 0.0.6 |
| Homepage | `https://github.com/luxdefi/blobvm` |
| Description | Content-Addressable Key-Value Store with EIP-712 compatibility and fee-based metering |
| Install Script | `scripts/build.sh` |
| Binary Path | `build/kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8` |
| Release URL | `https://github.com/luxdefi/blobvm/archive/refs/tags/v0.0.6.tar.gz` |
| SHA256 | `72d1b8fa3ee89412b406e7b0e9a968ca06746ea1bb5dd02c2b87f1ad1eaa4ca6` |
BlobVM provides a content-addressable key-value store chain. Keys are derived from content hashes, data is stored on-chain with EIP-712 signature verification, and fees are calculated based on data size (metered storage).
### SpacesVM
| Field | Value |
|-------|-------|
| Alias | `spacesvm` |
| VM ID | `sqja3uK17MJxfC7AN8nGadBw9JK5BcrsNwNynsqP5Gih8M5Bm` |
| Version | 0.0.3 |
| Homepage | `https://tryspaces.xyz` |
| Description | Virtual machine that processes the Spaces subnet |
| Install Script | `scripts/build.sh` |
| Binary Path | `build/sqja3uK17MJxfC7AN8nGadBw9JK5BcrsNwNynsqP5Gih8M5Bm` |
| Release URL | `https://github.com/luxdefi/spacesvm/archive/refs/tags/v0.0.3.tar.gz` |
| SHA256 | `1ac250f6c40472f22eaf0616fc8c886078a4eaa9b2b85fbb4fb7783a1db6af3f` |
SpacesVM provides authenticated, hierarchical key-value storage using any EIP-712 compatible wallet. It powers the Spaces subnet where users can claim hierarchical namespaces (like DNS) and store arbitrary key/value data under them.
### Subnet EVM
| Field | Value |
|-------|-------|
| Alias | `subnet-evm` |
| VM ID | `srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy` |
| Version | 0.2.7 |
| Homepage | `https://github.com/luxdefi/subnet-evm` |
| Description | Subnet EVM -- simplified Coreth VM for Subnet Contract Chains with full Ethereum Virtual Machine and Solidity smart contract support |
| Install Script | `scripts/build.sh build/srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy` |
| Binary Path | `build/srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy` |
| Release URL | `https://github.com/luxdefi/subnet-evm/archive/refs/tags/v0.2.7.tar.gz` |
| SHA256 | `c0d63b56031820007cce5fa8ea635628b8b9a5897111290a78b60538838509f8` |
Subnet EVM is the primary VM for creating new EVM-compatible blockchains on Lux. It is a simplified version of Coreth (C-Chain VM), parameterizable for different throughput and gas configurations.
## Registered Subnets
### Spaces Subnet
| Field | Value |
|-------|-------|
| Alias | `spaces` |
| Subnet ID | `Ai42MkKqk8yjXFCpoHXw7rdTWSHiKEMqh5h8gbxwjgkCUfkrk` |
| Homepage | `https://tryspaces.xyz` |
| VM | `spacesvm` |
| Description | Authenticated, hierarchical storage of arbitrary keys/values using any EIP-712 compatible wallet |
**Consensus parameters**:
```
k: 20 -- Sample size
alpha: 15 -- Quorum size
betaVirtuous: 15 -- Confidence threshold (virtuous)
betaRogue: 20 -- Confidence threshold (rogue)
concurrentRepolls: 4 -- Concurrent repolls
optimalProcessing: 50 -- Optimal processing buffer
maxOutstandingItems: 1024 -- Max outstanding items
maxItemProcessingTime: 120s -- Max processing time per item
parents: 5 -- Parent count
batchSize: 30 -- Batch size
validatorOnly: false -- Open to non-validators
```
### Zoo EVM Demo (WAGMI)
| Field | Value |
|-------|-------|
| Alias | `wagmi` |
| Subnet ID | `28nrH5T2BMvNrWecFcV3mfccjs6axM1TVyqe79MCv2Mhs8kxiY` |
| Homepage | `https://github.com/luxfi/evm` |
| VM | `evm` (Coreth/Subnet-EVM) |
| Description | High-throughput testbed for EVM optimizations, parameterized to run at higher capacity than mainnet C-Chain |
| Maintainer | `[email protected]` |
Used to experiment with EVM release candidates before they ship as official Coreth releases.
## VM Definition Format
Complete YAML schema for a VM definition (`vms/<name>.yaml`):
```yaml
vm:
id: "<base58 encoded VM ID>"
alias: "<unique alias>"
homepage: "<project URL>"
description: "<description>"
# Required: Base58-encoded VM ID (deterministic from build)
id: "kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8"
# Required: Unique human-readable alias (used in LPM commands)
alias: "blobvm"
# Required: Project homepage URL
homepage: "https://github.com/luxdefi/blobvm"
# Required: Human-readable description
description: "Content-Addressable Key-Value Store w/EIP-712 Compatibility"
# Required: Maintainer contact emails
maintainers:
- "<email>"
installScript: "<path to build script>"
binaryPath: "<path to built binary>"
url: "<release tarball URL>"
sha256: "<checksum>"
- "[email protected]"
# Required: Path to build script (relative to extracted source)
# LPM clones the repo and runs this script to build the binary
installScript: "scripts/build.sh"
# Required: Path to the built binary (relative to extracted source)
# Must match the VM ID for the node to load it correctly
binaryPath: "build/kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8"
# Required: URL to release tarball (for pre-built download)
url: "https://github.com/luxdefi/blobvm/archive/refs/tags/v0.0.6.tar.gz"
# Required: SHA256 checksum of the release tarball
sha256: "72d1b8fa3ee89412b406e7b0e9a968ca06746ea1bb5dd02c2b87f1ad1eaa4ca6"
# Required: Semantic version
version:
major: 0
minor: 0
patch: 1
patch: 6
```
## Subnet Definition Format
Subnet definitions reference VMs by alias and include network-specific configuration (subnet ID, blockchain IDs, genesis).
Complete YAML schema for a subnet definition (`subnets/<name>.yaml`):
```yaml
subnet:
# Required: Base58-encoded Subnet ID (from P-Chain)
id: "Ai42MkKqk8yjXFCpoHXw7rdTWSHiKEMqh5h8gbxwjgkCUfkrk"
# Required: Unique human-readable alias
alias: "spaces"
# Required: Project homepage
homepage: "https://tryspaces.xyz"
# Required: Description
description: |
Spaces enables authenticated, hierarchical storage of arbitrary
keys/values using any EIP-712 compatible wallet.
# Required: Maintainer emails
maintainers:
- "[email protected]"
# Optional: Install script (empty if no additional setup needed)
installScript: ""
# Required: List of VM aliases this subnet uses
vms:
- "spacesvm"
# Optional: Subnet-specific configuration
config:
# Gossip settings
gossipAcceptedFrontierValidatorSize: 0
gossipAcceptedFrontierNonValidatorSize: 0
gossipAcceptedFrontierPeerSize: 35
gossipOnAcceptValidatorSize: 0
gossipOnAcceptNonValidatorSize: 0
gossipOnAcceptPeerSize: 20
appGossipValidatorSize: 10
appGossipNonValidatorSize: 0
appGossipPeerSize: 0
# Access control
validatorOnly: false
# Consensus parameters
consensusParameters:
k: 20 # Sample size
alpha: 15 # Quorum threshold
betaVirtuous: 15 # Virtuous confidence
betaRogue: 20 # Rogue confidence
concurrentRepolls: 4
optimalProcessing: 50
maxOutstandingItems: 1024
maxItemProcessingTime: 120_000_000_000 # 120 seconds in nanoseconds
parents: 5
batchSize: 30
```
## How LPM Works
The Lux Plugin Manager (LPM) uses this repository to:
1. **Discover VMs**: LPM reads `vms/*.yaml` to list available virtual machines
2. **Download**: Fetches the release tarball from the `url` field
3. **Verify**: Checks the SHA256 checksum against the `sha256` field
4. **Build** (if needed): Runs the `installScript` to compile from source
5. **Install**: Copies the binary to the node's plugin directory at the path matching the VM ID
6. **Track**: Records installed version for upgrade tracking
### Binary Naming Convention
VM binaries must be named with their base58-encoded VM ID. The Lux node discovers plugins by scanning its plugin directory for files whose names match registered VM IDs. Example:
```
~/.lux/plugins/kM6h4LYe3AcEU1MB2UNg6ubzAiDAALZzpVrbX8zn3hXF6Avd8 # BlobVM
~/.lux/plugins/sqja3uK17MJxfC7AN8nGadBw9JK5BcrsNwNynsqP5Gih8M5Bm # SpacesVM
~/.lux/plugins/srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy # Subnet EVM
```
## Usage with LPM
```bash
# Install a VM via LPM using this repository
lpm install --vm spacesvm
# Add this repository (ships as default with LPM)
lpm add-repository --alias luxfi --url https://github.com/luxfi/plugins-core.git
# List available VMs
# List all available VMs
lpm list-vms
# Install from a specific plugin repository
lpm add-repository --alias luxfi --url https://github.com/luxfi/plugins-core.git
# Install a VM by alias
lpm install --vm blobvm
lpm install --vm spacesvm
lpm install --vm subnet-evm
# Update a VM to latest version
lpm update --vm subnet-evm
# Install a subnet (installs all referenced VMs)
lpm install --subnet spaces
# List installed VMs
lpm list-installed
```
## Adding a New VM
1. Create a YAML file in `vms/` following the example template
2. Include: VM ID, alias, install script, binary path, release URL, and sha256 checksum
3. Submit a pull request
1. **Generate a VM ID**: Build your VM binary; its name is the base58 VM ID
2. **Create release**: Tag a release on GitHub and note the tarball URL
3. **Compute checksum**: `sha256sum <tarball>` to get the SHA256 hash
4. **Write YAML**: Create `vms/<alias>.yaml` following the format above
5. **Test locally**: Verify LPM can install from your fork
6. **Submit PR**: Open a pull request to `github.com/luxfi/plugins-core`
Required fields checklist:
- `id`: Base58 VM ID (matches binary name)
- `alias`: Unique short name (lowercase, hyphens ok)
- `homepage`: URL to project
- `description`: What the VM does
- `maintainers`: At least one email
- `installScript`: Build script path
- `binaryPath`: Built binary path
- `url`: Release tarball URL
- `sha256`: Checksum of tarball
- `version`: Semantic version (major/minor/patch)
## Adding a New Subnet
1. Create a YAML file in `subnets/` following the example template
2. Reference the VM alias, subnet ID, and blockchain configuration
3. Submit a pull request
1. **Create subnet on P-Chain**: Deploy via `lux subnet create` CLI command
2. **Note Subnet ID**: Base58-encoded ID from the P-Chain transaction
3. **List VM dependencies**: Which VMs the subnet uses (by alias)
4. **Configure consensus**: Set Snow consensus parameters appropriate for your use case
5. **Write YAML**: Create `subnets/<alias>.yaml` following the format above
6. **Submit PR**: Open a pull request
## Consensus Parameter Reference
These parameters control Snow consensus behavior for subnets:
| Parameter | Description | Default |
|-----------|-------------|---------|
| `k` | Sample size (number of validators polled per round) | 20 |
| `alpha` | Quorum size (required agreement to accept) | 15 |
| `betaVirtuous` | Confidence threshold for virtuous transactions | 15 |
| `betaRogue` | Confidence threshold for conflicting transactions | 20 |
| `concurrentRepolls` | Number of concurrent polls | 4 |
| `optimalProcessing` | Target number of in-flight transactions | 50 |
| `maxOutstandingItems` | Maximum unprocessed items | 1024 |
| `maxItemProcessingTime` | Timeout per item (nanoseconds) | 120,000,000,000 (120s) |
| `parents` | Number of parents per vertex (DAG depth) | 5 |
| `batchSize` | Transactions per batch | 30 |
| `validatorOnly` | Restrict to validators only | false |
## Related Skills
- `lux/lux-node.md` — Core node that runs VM plugins
- `lux/lux-evm.md` — Subnet EVM execution engine
- `lux/lux-spacesvm.md` — SpacesVM storage chain
- `lux/lux-node.md` -- Core node that loads and runs VM plugins
- `lux/lux-evm.md` -- Subnet EVM execution engine
- `lux/lux-spacesvm.md` -- SpacesVM storage chain
- `lux/lux-cli.md` -- CLI for subnet creation and management
+363 -16
View File
@@ -1,28 +1,375 @@
---
title: "Lux Precompiled Contracts & Smart Contract VM"
description: "Custom EVM precompiled contracts for Lux-specific operations, SessionVM smart contract VM, and Foundry-based Solidity development."
title: "Lux EVM Precompiled Contracts"
description: "Custom Stateful Precompiles"
---
## Overview
Custom **EVM precompiled contracts** for Lux-specific operations, SessionVM smart contract VM, and Foundry-based Solidity development.
The Lux EVM provides two layers of precompiled contracts: **chain-integrated precompiles** in `github.com/luxfi/evm/precompile/contracts/` (deployer allowlist, fee manager, native minter, reward manager, tx allowlist, warp) and **extended precompiles** in `github.com/luxfi/precompile` (50+ contracts spanning post-quantum cryptography, zero-knowledge proofs, threshold signatures, FHE, AI mining, cross-chain bridges, and a native DEX). All precompiles follow the LP (Lux Proposal) address scheme defined in LP-0099.
## Components
## Modules
| Component | Path | Purpose |
|-----------|------|---------|
| precompile/ | ``github.com/luxfi/precompile`` | Custom precompiles |
| session/ | ``github.com/luxfi/session`` | SessionVM |
| liquid/ | ``github.com/luxfi/liquid`` | Foundry Solidity template |
| erc20-go/ | ``github.com/luxfi/erc20-go`` | ERC20 in Go |
| Module | Go | Key Dependencies |
|--------|------|-----------------|
| `github.com/luxfi/evm` (precompile/) | 1.26.1 | `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/[email protected]` |
| `github.com/luxfi/precompile` | 1.26.1 | `luxfi/[email protected]`, `luxfi/[email protected]`, `luxfi/lattice/v7`, `luxfi/[email protected]`, `luxfi/[email protected]`, `cloudflare/[email protected]`, `consensys/[email protected]` |
## Precompile Development
## Address Scheme (LP-0099)
All Lux-native precompiles use 20-byte addresses with an LP-aligned encoding:
```
Format: 0x0000000000000000000000000000000000PCIIR
P = Family page (LP-Pxxx first digit)
C = Chain slot (0-A)
II = Item/function (8 bits)
```
### Family Pages (P nibble)
| P | Range | Family |
|---|-------|--------|
| 0 | Core | Chain config precompiles (deployer, tx, minter, reward) |
| 1 | LP-1xxx | Fee management |
| 2 | LP-2xxx | PQ Identity (post-quantum signatures, KEM, hybrid) |
| 3 | LP-3xxx | EVM/Crypto (hashing, classical signatures, encryption) |
| 4 | LP-4xxx | Privacy/ZK (SNARKs, STARKs, commitments, FHE) |
| 5 | LP-5xxx | Threshold/MPC (FROST, CGGMP21, DKG, secret sharing) |
| 6 | LP-6xxx | Bridges (Warp messaging, token bridges, fee collection) |
| 7 | LP-7xxx | AI (GPU attestation, inference, mining sessions) |
| 9 | LP-9xxx | DEX/Markets (AMM, orderbook, lending, liquidation) |
### Chain Slots (C nibble)
| C | Chain | C | Chain |
|---|-------|---|-------|
| 0 | P-Chain | 6 | Z-Chain |
| 1 | X-Chain | 7 | M-Chain (reserved) |
| 2 | C-Chain (main EVM) | 8 | Zoo |
| 3 | Q-Chain (quantum) | 9 | Hanzo |
| 4 | A-Chain (AI) | A | SPC |
| 5 | B-Chain (bridge) | | |
Helper functions: `PrecompileAddress(p, c, ii)`, `ChainSlot(name)`, `FamilyPage(name)`.
## Contract Framework
### StatefulPrecompiledContract
The core execution interface. Each precompile implements `Run`:
```go
import "github.com/luxfi/evm/precompile/contract"
var MyPrecompile = &contract.Module{
Address: common.HexToAddress("0x0300000000000000000000000000000000000001"),
Gas: contract.GasCost{Base: 2000},
// github.com/luxfi/evm/precompile/contract/interfaces.go
type StatefulPrecompiledContract interface {
Run(accessibleState AccessibleState, caller common.Address, addr common.Address,
input []byte, suppliedGas uint64, readOnly bool) (ret []byte, remainingGas uint64, err error)
}
```
### AccessibleState
Provides precompiles with EVM state access:
```go
type AccessibleState interface {
GetStateDB() StateDB
GetBlockContext() BlockContext
GetConsensusContext() context.Context
GetChainConfig() precompileconfig.ChainConfig
}
```
`StateDB` exposes: `GetState`, `SetState`, `GetBalance`, `AddBalance`, `GetNonce`, `SetNonce`, `CreateAccount`, `Exist`, `AddLog`, `GetPredicateStorageSlots`, `GetTxHash`, `Snapshot`, `RevertToSnapshot`.
### Function Selector Dispatch
Contracts are built from `StatefulPrecompileFunction` entries, dispatched by 4-byte ABI selector:
```go
// github.com/luxfi/evm/precompile/contract/contract.go
contract, err := contract.NewStatefulPrecompileContract(
fallback, // optional: called when input is empty
[]*contract.StatefulPrecompileFunction{
contract.NewStatefulPrecompileFunction(selector, executeFunc),
contract.NewStatefulPrecompileFunctionWithActivator(selector, executeFunc, activationFunc),
},
)
```
`ActivationFunc` allows gating functions behind network upgrades (e.g., `IsDurangoActivated`).
### Gas Constants
```go
const (
WriteGasCostPerSlot = 20_000
ReadGasCostPerSlot = 5_000
LogGas = 375
LogTopicGas = 375
LogDataGas = 8
)
```
### Config Interface
Every precompile has a config implementing `precompileconfig.Config`:
```go
type Config interface {
Key() string
Timestamp() *uint64 // nil = never enabled, 0 = genesis, n = enable at timestamp >= n
IsDisabled() bool
Equal(Config) bool
Verify(ChainConfig) error
}
```
### Module Registration
Precompiles self-register in `init()` via `modules.RegisterModule`:
```go
var Module = modules.Module{
ConfigKey: "contractDeployerAllowListConfig",
Address: common.HexToAddress("0x10201"),
Contract: ContractDeployerAllowListPrecompile,
Configurator: &configurator{},
}
func init() {
if err := modules.RegisterModule(Module); err != nil {
panic(err)
}
}
```
Modules are stored sorted by address for deterministic iteration. Registration validates: not blackhole address, within a reserved range, no duplicate key or address.
### Configurator Interface
```go
type Configurator interface {
MakeConfig() precompileconfig.Config
MakeGenesisConfig() precompileconfig.Config
Configure(chainConfig ChainConfig, cfg Config, state StateDB, blockContext ConfigurationBlockContext) error
}
```
## Chain-Integrated Precompiles (luxfi/evm)
### AllowList Pattern
The AllowList abstraction (`precompile/allowlist/`) provides role-based access control used by multiple precompiles:
| Role | Value | Permissions |
|------|-------|-------------|
| `NoRole` | 0 | No access |
| `EnabledRole` | 1 | Can call the precompile |
| `AdminRole` | 2 | Can modify the allowlist AND call |
| `ManagerRole` | 3 | Can add/remove Enabled only (Durango+) |
ABI methods: `setAdmin(address)`, `setManager(address)`, `setEnabled(address)`, `setNone(address)`, `readAllowList(address)`.
Role modification rules:
- Admin can modify anyone to any role
- Manager can only toggle between Enabled and NoRole
- Enabled and NoRole cannot modify the list
Events are emitted on role changes (Durango+) with gas cost `AllowListEventGasCost`.
### Contract Deployer AllowList
| Field | Value |
|-------|-------|
| ConfigKey | `contractDeployerAllowListConfig` |
| Address | `0x10201` |
| Gas | Read: 5,000 / Write: 20,000 |
Controls which addresses can deploy contracts. Configured in genesis or via network upgrade.
### Transaction AllowList
| Field | Value |
|-------|-------|
| ConfigKey | `txAllowListConfig` |
| Address | `0x10301` |
| Gas | Read: 5,000 / Write: 20,000 |
Controls which addresses can submit transactions.
### Native Minter
| Field | Value |
|-------|-------|
| ConfigKey | `contractNativeMinterConfig` |
| Address | `0x10401` |
| Gas | Mint: 30,000 |
Allows permissioned addresses to mint native tokens. ABI method: `mintNativeCoin(address, uint256)`. Supports `InitialMint` map in config for genesis minting.
### Fee Manager
| Field | Value |
|-------|-------|
| ConfigKey | `feeManagerConfig` |
| Address | `0x13F01` |
| Gas | Set: ~160,000 / Get: ~40,000 / GetLastChangedAt: 5,000 |
Controls dynamic fee configuration. Fee config fields: `gasLimit`, `targetBlockRate`, `minBaseFee`, `targetGas`, `baseFeeChangeDenominator`, `minBlockGasCost`, `maxBlockGasCost`, `blockGasCostStep`. Stores `feeConfigLastChangedAt` timestamp. Supports `InitialFeeConfig` in config or falls back to chain genesis fee config.
### Reward Manager
| Field | Value |
|-------|-------|
| ConfigKey | `rewardManagerConfig` |
| Address | `0x10205` |
| Gas | Read: 5,000 / Write: 20,000 |
Controls block reward distribution. Three modes: `AllowFeeRecipients` (validators set fee recipient), `DisableFeeRewards` (burn all fees), or custom `InitialRewardConfig`.
### Warp Messenger
| Field | Value |
|-------|-------|
| ConfigKey | `warpConfig` |
| Address | `0x16201` |
| Gas | Send: ~41,000 base + 8/byte / GetVerified: 2 base + per-signer/byte costs |
Cross-chain messaging via BLS aggregate signatures. ABI methods: `sendWarpMessage(bytes)`, `getVerifiedWarpMessage(uint32)`, `getVerifiedWarpBlockHash(uint32)`, `getBlockchainID()`.
Gas breakdown for verification:
- `GasCostPerWarpSigner`: 500
- `GasCostPerWarpMessageBytes`: 100
- `GasCostPerSignatureVerification`: 200,000
Implements `Predicater` (validates warp predicates in access lists) and `Accepter` (writes messages on block acceptance).
## Extended Precompiles (luxfi/precompile)
Registered via `registry/registry.go` force-imports in `init()`:
```go
// registry/registry.go
import (
_ "github.com/luxfi/precompile/mldsa" // ML-DSA (FIPS 204)
_ "github.com/luxfi/precompile/mlkem" // ML-KEM (FIPS 203)
_ "github.com/luxfi/precompile/pqcrypto" // Unified PQ crypto
_ "github.com/luxfi/precompile/slhdsa" // SLH-DSA (FIPS 205)
_ "github.com/luxfi/precompile/ecies" // EC Integrated Encryption
_ "github.com/luxfi/precompile/fhe" // Fully Homomorphic Encryption
_ "github.com/luxfi/precompile/hpke" // Hybrid Public Key Encryption
_ "github.com/luxfi/precompile/ring" // Ring signatures
_ "github.com/luxfi/precompile/cggmp21" // Threshold ECDSA
_ "github.com/luxfi/precompile/frost" // Threshold Schnorr
_ "github.com/luxfi/precompile/corona" // Threshold lattice (PQ)
_ "github.com/luxfi/precompile/kzg4844" // KZG commitments
_ "github.com/luxfi/precompile/zk" // ZK proofs
_ "github.com/luxfi/precompile/secp256r1" // P-256 verification
_ "github.com/luxfi/precompile/ai" // AI mining
_ "github.com/luxfi/precompile/dex" // Native DEX
_ "github.com/luxfi/precompile/graph" // GraphQL query
_ "github.com/luxfi/precompile/blake3" // Blake3 hash
_ "github.com/luxfi/precompile/dead" // Dead/burn address
)
```
### PQ Identity (P=2, LP-2xxx)
| Name | Gas | Description |
|------|-----|-------------|
| ML-DSA | 50,000 | NIST ML-DSA post-quantum signatures (FIPS 204) |
| ML-KEM | 25,000 | NIST ML-KEM key encapsulation (FIPS 203) |
| SLH-DSA | 75,000 | NIST SLH-DSA hash-based signatures (FIPS 205) |
| HYBRID_SIGN | 75,000 | ECDSA+ML-DSA hybrid signatures |
### EVM/Crypto (P=3, LP-3xxx)
| Name | Gas | Description |
|------|-----|-------------|
| BLAKE3 | 5,000 | High-performance hash |
| ED25519_VERIFY | 3,000 | Ed25519 (Solana/TON compat) |
| ECIES | 25,000 | Elliptic Curve Integrated Encryption |
### Privacy/ZK (P=4, LP-4xxx)
| Name | Gas | Description |
|------|-----|-------------|
| GROTH16 | 150,000 | Groth16 proof verification |
| PLONK | 175,000 | PLONK proof verification |
| STARK | 200,000 | STARK proof verification |
| KZG | 50,000 | KZG polynomial commitments (EIP-4844 extension) |
| FHE | 500,000 | Fully Homomorphic Encryption (TFHE, CKKS, BGV) |
### Threshold/MPC (P=5, LP-5xxx)
| Name | Gas | Description |
|------|-----|-------------|
| FROST | 25,000 | Schnorr threshold signatures |
| CGGMP21 | 50,000 | ECDSA threshold signatures |
| CORONA | 75,000 | Threshold lattice signatures (post-quantum) |
### Bridges (P=6, LP-6xxx)
| Name | Gas | Description |
|------|-----|-------------|
| WARP_SEND | 50,000 | Cross-chain message send |
| WARP_RECEIVE | 50,000 | Cross-chain message receive |
| TELEPORT | 100,000 | Instant token teleport (LP-6010) |
### AI (P=7, LP-7xxx)
| Name | Gas | Description |
|------|-----|-------------|
| GPU_ATTEST | 100,000 | GPU compute attestation |
| TEE_VERIFY | 75,000 | TEE attestation verification |
| INFERENCE | 150,000 | AI inference verification |
| SESSION | 50,000 | AI mining session management |
### DEX/Markets (LP-9xxx -- QuantumSwap Native DEX)
| Address Suffix | Name | Gas | Description |
|----------------|------|-----|-------------|
| `0x...9010` | LX_POOL | 50,000 | Uniswap v4-style singleton AMM (PoolManager) |
| `0x...9011` | LX_ORACLE | 15,000 | Multi-source price oracle aggregation |
| `0x...9012` | LX_ROUTER | 10,000 | Optimized swap routing |
| `0x...9013` | LX_HOOKS | 10,000 | Hook contract registry |
| `0x...9014` | LX_FLASH | 50,000 | Flash loan facility |
| `0x...9020` | LX_BOOK | 25,000 | Central limit order book + matching engine |
| `0x...9030` | LX_VAULT | 50,000 | Custody, margin, and position management |
| `0x...9040` | LX_FEED | 10,000 | Computed price feeds (mark/index) |
| `0x...9050` | LX_LEND | 25,000 | Lending pool (Aave-style) |
| `0x...9060` | LX_LIQUID | 30,000 | Self-repaying loans (Alchemix-style) |
| `0x...9070` | LIQUIDATOR | 50,000 | Position liquidation engine |
| `0x...9080` | LIQUID_FX | 25,000 | Transmuter (liquid token conversion) |
## Predicates and Accepters
Optional interfaces precompiles can implement:
- **Predicater**: `PredicateGas(bytes) (uint64, error)` + `VerifyPredicate(ctx, bytes) error` -- validate access list entries before execution. Gas is added to intrinsic gas. Verification results are stored in the block as a bitset.
- **Accepter**: `Accept(ctx, blockHash, blockNum, txHash, logIndex, topics, data) error` -- triggered when block is accepted, for each log matching the precompile address.
## How to Add a New Precompile
1. Create package under `precompile/contracts/` (chain-integrated) or as separate `luxfi/precompile/` subpackage (extended)
2. Define a `Module` with unique `ConfigKey` and LP-aligned `Address`
3. Implement `contract.StatefulPrecompiledContract` with function selectors
4. Implement `contract.Configurator` with `MakeConfig`, `MakeGenesisConfig`, `Configure`
5. Register in `init()` via `modules.RegisterModule(Module)`
6. Add force-import to `registry/registry.go`
7. Create ABI file (embedded via `//go:embed contract.abi`)
8. Optionally implement `Predicater` and/or `Accepter`
9. Write config with AllowList if access control is needed
## Chain Precompile Assignments
| Chain | Focus | Precompile Families |
|-------|-------|-------------------|
| C-Chain | Main EVM | All families |
| Q-Chain | Quantum | PQ Identity, Threshold |
| A-Chain | AI | AI, Bridges |
| B-Chain | Bridge | Bridges, Fee Collection |
| Z-Chain | Privacy | Crypto, Privacy/ZK, FHE |
| Zoo | DeFi | DEX, Bridges |
| Hanzo | AI compute | AI (GPU, Inference, Session), Bridges |
+230 -52
View File
@@ -1,79 +1,242 @@
---
title: "Lux Safe - Multisig Smart Accounts"
description: "Lux Safe provides multisig smart account contracts — fork of Safe (Gnosis Safe) with ERC-4337 account abstraction support. Multi-chain deployment on Lux C-Chain and subnets."
title: "Lux Safe"
description: "Multisig Smart Accounts + Wallet UI"
---
## Overview
Lux Safe provides **multisig smart account contracts** — fork of Safe (Gnosis Safe) with ERC-4337 account abstraction support. Multi-chain deployment on Lux C-Chain and subnets.
Lux Safe is a **multisig smart account platform** combining Safe v1.5.0 contracts (fork of safe-global/safe-smart-account) with a legacy React wallet UI and a Next.js static docs/landing site. Supports ERC-4337 account abstraction, EIP-7702 delegation detection, and secp256r1 signature verification via EIP-7951/RIP-7212 precompiles.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/safe` |
| Package | `@luxfi/safe` |
| Version | v0.0.7 |
| Language | Solidity >=0.7.0 <0.9.0 |
| Framework | Hardhat |
| Contract Version | Safe v1.5.0 |
| Solidity | >=0.7.0 <0.9.0 |
| Framework | Hardhat 2.27+ / hardhat-deploy |
| Compiler | solc 0.7.6 (default) |
| Upstream | safe-global/safe-smart-account |
| License | BSD-3-Clause |
## Features
## Repository Structure
- **M-of-N multisig**: Configurable threshold signatures
- **ERC-4337**: Account abstraction compatibility
- **Deterministic deployment**: Same address across all chains
- **Module system**: Extensible via Safe modules
- **Guard system**: Transaction validation hooks
```
safe/
contracts/ # Solidity source (Safe v1.5.0)
src/
app/ # Next.js 15 landing/docs site (static export)
deploy/ # Hardhat deployment scripts (7 scripts)
tasks/ # Custom Hardhat tasks
utils/ # TypeScript utilities
react/ # Legacy Safe React wallet UI (v3.32.1, React 17)
app/ # Legacy CRA app shell (service worker, mocks)
test/ # Hardhat test suite (10 categories)
benchmark/ # Gas benchmarks (6 specs)
certora/ # Certora formal verification (14 specs)
modules/ # Safe module stubs (dutchx_seller, recurring_transfers)
modules-deployments/ # Module deployment artifacts
docs/ # Audit reports (PDFs), docs site (Next.js/MDX)
types/ # TypeScript type definitions
```
## Contracts
### Core
| Contract | File | Purpose |
|----------|------|---------|
| `Safe` | `Safe.sol` | Core multisig (1487 LOC). EIP-712 typed data signing, M-of-N threshold, gas refund, module/guard system. Inherits EIP7951 for secp256r1 |
| `SafeL2` | `SafeL2.sol` | L2-optimized variant that emits events for indexing (mainnet Safe does not emit for gas savings) |
| `SafeProxy` | `proxies/SafeProxy.sol` | Minimal proxy (EIP-1167 style) delegating to singleton |
| `SafeProxyFactory` | `proxies/SafeProxyFactory.sol` | Deterministic proxy deployment via CREATE2 |
### Base Modules
| Contract | Purpose |
|----------|---------|
| `Safe.sol` | Core multisig account |
| `SafeProxyFactory.sol` | Deterministic proxy deployment |
| `CompatibilityFallbackHandler.sol` | ERC-1271 + token receiver |
| `SafeL2.sol` | L2-optimized (emits events for indexing) |
| `TokenCallbackHandler.sol` | ERC721/ERC1155 receiver |
| `Executor` | Low-level CALL/DELEGATECALL execution |
| `FallbackManager` | Configurable fallback handler routing |
| `GuardManager` | Pre/post transaction guard hooks |
| `ModuleManager` | Module registration and execution (linked list) |
| `OwnerManager` | Owner add/remove/swap with threshold management |
## Usage
### EIP Support
```solidity
// Deploy new Safe with 2-of-3 threshold
SafeProxyFactory factory = SafeProxyFactory(FACTORY_ADDRESS);
| Contract | Standard | Purpose |
|----------|----------|---------|
| `EIP7702` | EIP-7702 | Detects EOA delegation context via EXTCODECOPY (0xef0100 prefix) |
| `EIP7951` | EIP-7951/RIP-7212 | secp256r1 (P-256) signature verification via precompile at 0x100 |
address[] memory owners = new address[](3);
owners[0] = 0x1234...;
owners[1] = 0x5678...;
owners[2] = 0xabcd...;
### Handlers
bytes memory initializer = abi.encodeWithSelector(
Safe.setup.selector,
owners,
2, // threshold
address(0), // to
"", // data
FALLBACK_HANDLER,
address(0), // paymentToken
0, // payment
address(0) // paymentReceiver
);
| Contract | Purpose |
|----------|---------|
| `CompatibilityFallbackHandler` | ERC-1271 signature validation + ERC-721/ERC-1155 token receiver |
| `ExtensibleFallbackHandler` | Fully extensible fallback with pluggable sub-handlers |
| `TokenCallbackHandler` | ERC-721 + ERC-1155 receiver callbacks |
| `HandlerContext` | Provides msg.sender context for fallback handler calls |
SafeProxy proxy = factory.createProxyWithNonce(
SAFE_SINGLETON,
initializer,
salt
);
### Extensible Handler System
| Contract | Purpose |
|----------|---------|
| `ERC165Handler` | ERC-165 interface detection with per-Safe overrides |
| `FallbackHandler` | Custom method routing per Safe |
| `SignatureVerifierMuxer` | Domain-specific ERC-1271 signature verification |
| `TokenCallbacks` | Token receive hooks |
| `MarshalLib` | ABI encoding utilities for handler data |
### Libraries
| Contract | Purpose |
|----------|---------|
| `CreateCall` | CREATE/CREATE2 from Safe context |
| `MultiSend` | Batch multiple transactions in one call |
| `MultiSendCallOnly` | Batch CALL-only transactions (no DELEGATECALL) |
| `SafeMigration` | Singleton upgrade with optional fallback handler update |
| `SafeStorage` | Storage slot layout (singleton at slot 0) |
| `SafeToL2Setup` | Setup helper for L2 Safe initialization |
| `SignMessageLib` | EIP-191/EIP-712 message signing from Safe |
| `SimulateTxAccessor` | Simulate transaction for gas estimation |
### Guards (Examples)
| Guard | Purpose |
|-------|---------|
| `DebugTransactionGuard` | Logs all transaction details for debugging |
| `DelegateCallTransactionGuard` | Blocks DELEGATECALL operations |
| `OnlyOwnersGuard` | Restricts execution to Safe owners only |
| `ReentrancyTransactionGuard` | Prevents reentrancy during execution |
## Deployment Scripts
7 Hardhat deploy scripts in `src/deploy/`:
| Script | Tags | Deploys |
|--------|------|---------|
| `deploy_safe_singleton.ts` | `singleton, main-suite` | Safe implementation |
| `deploy_safe_l2.ts` | `l2, main-suite` | SafeL2 implementation |
| `deploy_factories.ts` | `factory, main-suite` | SafeProxyFactory |
| `deploy_handlers.ts` | `handlers, main-suite` | Fallback handlers |
| `deploy_libraries.ts` | `libraries, main-suite` | MultiSend, CreateCall, etc. |
| `deploy_accessors.ts` | `accessors, main-suite` | SimulateTxAccessor |
| `deploy_migrations.ts` | `migrations, main-suite` | SafeMigration |
All deployments use deterministic deployment (safe-singleton-factory) for identical addresses cross-chain.
## Hardhat Tasks
| Task | Purpose |
|------|---------|
| `deploy_contracts` | Deploy all contracts to a network |
| `local_verify` | Verify contract source on local explorer |
| `show_codesize` | Display contract bytecode sizes |
## Test Suite
Tests organized in `test/` with 10+ categories:
| Directory | Coverage |
|-----------|----------|
| `core/` | Execution, signatures, storage, setup, owner/module/guard/fallback management |
| `factory/` | Proxy creation, deterministic deployment |
| `guards/` | Guard hook behavior |
| `handlers/` | Fallback handler routing, extensible handlers |
| `integration/` | End-to-end workflows |
| `l2/` | SafeL2 event emission |
| `libraries/` | MultiSend, CreateCall, migration |
| `migration/` | Singleton upgrade paths |
| `json/` | ABI/JSON compatibility |
| `utils/` | Test utilities |
Benchmark specs in `benchmark/`: Creation, ERC1155, ERC20, Ether, MultiSend, Proxy.
Test commands:
```bash
npm run test:hardhat # All Hardhat tests
npm run test:L1 # L1-specific tests (chainId=1)
npm run test:L2 # L2 tests (SafeL2)
npm run test:secp256r1 # EIP-7951 P-256 precompile tests
npm run benchmark # Gas benchmarks
npm run coverage # Coverage report
```
## Audits
## Formal Verification (Certora)
Security audits from versions 0.0.1 through 1.5.0:
- Certora (formal verification)
- Ackee Blockchain
- G0 Group
- Runtime Verification
14 CVL specs in `certora/specs/`:
| Spec | Verifies |
|------|----------|
| `Execute.spec` | Transaction execution invariants |
| `Signatures.spec` | Signature validation correctness |
| `Setup.spec` | Initialization safety |
| `Safe.spec` | Core Safe properties |
| `SafeMigration.spec` | Migration correctness |
| `OwnerReach.spec` | Owner linked list reachability |
| `ModuleReach.spec` | Module linked list reachability |
| `Guards.spec` | Guard hook execution |
| `Fallback.spec` | Fallback routing |
| `Hash.spec` | EIP-712 hash computation |
| `NativeTokenRefund.spec` | Gas refund in native token |
| `SafeToL2Setup.spec` | L2 setup correctness |
| `Extensible.spec` | Extensible handler properties |
## Audit History
Audit reports in `docs/` covering versions 1.0.0 through 1.5.0:
| Version | Auditor | Type |
|---------|---------|------|
| 1.0.0 | G0 Group | Security audit |
| 1.0.0 | Runtime Verification | Formal verification |
| 1.1.0 | G0 Group | Security audit |
| 1.1.1 | G0 Group | Security audit |
| 1.2.0 | G0 Group | Security audit |
| 1.3.0 | G0 Group | Security audit (initial + final) |
| 1.4.0 | Certora | Formal verification |
| 1.4.1 | Ackee Blockchain | Library contracts |
| 1.5.0 | Ackee Blockchain | Security audit |
| 1.5.0 | Certora | Formal verification |
## React Wallet UI (Legacy)
Located in `react/`, version 3.32.1. React 17 + Redux + Material-UI application.
| Item | Value |
|------|-------|
| Framework | CRA (rescripts) |
| State | Redux + redux-thunk |
| Web3 | web3.js 1.7, @gnosis.pm/safe-core-sdk |
| UI | Material-UI v4 |
| Testing | Jest, Cypress |
| Node | 16 (.nvmrc) |
## Next.js Landing/Docs Site
Located in `src/app/`, uses Next.js with static export (`output: 'export'`).
| Item | Value |
|------|-------|
| Framework | Next.js 15, React 18 |
| Styling | Tailwind CSS |
| Dependencies | `@luxfi/ui`, `@luxfi/data`, `@luxfi/menu-icons`, `@hanzo/auth`, `@hanzo/commerce` |
| Deployment | GitHub Pages (static) |
## Hardhat Network Configuration
| Network | URL |
|---------|-----|
| hardhat | Local (chainId configurable via `HARDHAT_CHAIN_ID`, default 31337) |
| mainnet | Infura (requires `INFURA_KEY`) |
| sepolia | Infura (requires `INFURA_KEY`) |
| gnosis | `rpc.gnosischain.com` |
| zksync | `mainnet.era.zksync.io` |
| custom | Any URL via `NODE_URL` env var |
RIP-7212 precompile enabled via `HARDHAT_SECP256R1_PRECOMPILE=1`.
## Development
@@ -81,12 +244,27 @@ Security audits from versions 0.0.1 through 1.5.0:
git clone https://github.com/luxfi/safe.git
cd safe
npm install
npx hardhat compile
npx hardhat test
npx hardhat compile # Compile contracts
npx hardhat test # Run all tests
npm run test:secp256r1 # Test P-256 verification
npm run coverage # Coverage report
npm run codesize # Check bytecode sizes
npm run deploy-all custom # Deploy to custom network (NODE_URL)
```
## Key Interfaces
| Interface | Purpose |
|-----------|---------|
| `ISafe` | Full Safe API (setup, execTransaction, checkSignatures, approveHash, nonce) |
| `IModuleManager` | Module enable/disable/execute |
| `IOwnerManager` | Owner add/remove/swap, threshold |
| `IGuardManager` | Guard set/get |
| `IFallbackManager` | Fallback handler set |
| `ISignatureValidator` | ERC-1271 isValidSignature |
## Related Skills
- `lux/lux-wallet.md` — Wallet integration with Safe
- `lux/lux-crypto.md` — Cryptographic primitives
- `lux/lux-governance.md` — DAO treasury management
- `lux/lux-wallet.md` -- Wallet integration with Safe
- `lux/lux-crypto.md` -- Cryptographic primitives
- `lux/lux-governance.md` -- DAO treasury management via Safe
+220 -81
View File
@@ -1,129 +1,268 @@
---
title: "Lux SDK - Official Go SDK"
description: "Lux SDK is the official Go SDK for building and managing Lux networks — unified interface wrapping CLI, netrunner, and node APIs."
title: "Lux SDK"
description: "Official Go SDK"
---
## Overview
Lux SDK is the **official Go SDK** for building and managing Lux networks — unified interface wrapping CLI, netrunner, and node APIs. Supports all 5 chain types.
Lux SDK is the **official Go SDK** for building and managing Lux networks. It provides a unified interface for network lifecycle management, blockchain creation and deployment (L1/L2/L3), multi-chain wallet operations, validator management, smart contract interaction, and cross-chain messaging via Warp. The SDK wraps CLI, netrunner, and direct node APIs into a single coherent library.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Module | `github.com/luxfi/sdk` |
| Go | 1.26.1 |
| Entry point | `sdk.go` (`LuxSDK` struct) |
| Main API | `sdk.New(cfg)` returns `*LuxSDK` |
## Key Dependencies
## Core luxfi Dependencies
```
github.com/luxfi/[email protected]
github.com/luxfi/[email protected]
github.com/luxfi/[email protected]
github.com/luxfi/node@v1.23.4
github.com/luxfi/[email protected]
github.com/luxfi/[email protected]
github.com/luxfi/[email protected]
github.com/luxfi/l[email protected]
```
| Dependency | Version | Purpose |
|------------|---------|---------|
| `github.com/luxfi/consensus` | v1.22.63 | Snow consensus engine |
| `github.com/luxfi/evm` | v0.8.35 | C-Chain EVM |
| `github.com/luxfi/node` | v1.23.4 | Lux node implementation |
| `github.com/luxfi/netrunner` | v1.15.11 | Network testing orchestrator |
| `github.com/luxfi/genesis` | v1.6.1 | Genesis configuration |
| `github.com/luxfi/warp` | v1.18.5 | Cross-chain Warp messaging |
| `github.com/luxfi/ledger` | v1.1.6 | Hardware wallet support |
| `github.com/luxfi/lpm` | v1.9.4 | Lux Plugin Manager |
| `github.com/luxfi/crypto` | v1.17.40 | Cryptographic primitives |
| `github.com/luxfi/geth` | v1.16.75 | Go-Ethereum fork (EVM) |
| `github.com/luxfi/ids` | v1.2.9 | ID types (ID, ShortID, NodeID) |
| `github.com/luxfi/protocol` | v0.0.3 | P-Chain protocol types |
| `github.com/luxfi/rpc` | v1.0.0 | JSON-RPC client |
| `github.com/luxfi/utxo` | v0.2.4 | UTXO management |
| `github.com/luxfi/vm` | v1.0.33 | Virtual machine interfaces |
| `github.com/luxfi/validators` | v1.0.0 | Validator types |
| `github.com/luxfi/constants` | v1.4.4 | Network constants |
| `github.com/luxfi/database` | v1.17.40 | Storage layer |
| `github.com/luxfi/codec` | v1.1.4 | Serialization codec |
| `github.com/luxfi/formatting` | v1.0.1 | Encoding utilities |
| `github.com/luxfi/keychain` | v1.0.2 | Key management |
| `github.com/luxfi/address` | v1.0.1 | Bech32 address formatting |
| `github.com/luxfi/api` | v1.0.1 | API types |
| `github.com/luxfi/bft` | v0.1.5 | BFT consensus |
| `github.com/luxfi/go-bip32` | v1.0.2 | BIP-32 HD keys |
| `github.com/luxfi/go-bip39` | v1.1.2 | BIP-39 mnemonics |
| `github.com/luxfi/runtime` | v1.0.1 | VM runtime |
| `github.com/luxfi/upgrade` | v1.0.0 | Upgrade management |
| `github.com/luxfi/tls` | v1.0.3 | TLS certificate utilities |
| `github.com/luxfi/net` | v0.0.2 | Network utilities |
| `github.com/luxfi/math` | v1.2.3 | Math utilities |
| `github.com/luxfi/utils` | v1.1.4 | General utilities |
| `github.com/luxfi/p2p` | v1.19.2-zap | P2P networking |
## Package Map
### Top-Level SDK
| Package | Import | Purpose |
|---------|--------|---------|
| `sdk` | `github.com/luxfi/sdk` | `LuxSDK` struct -- entry point with `New(cfg)`, `Networks()`, `Blockchains()`, `LaunchNetwork()`, `CreateAndDeployBlockchain()` |
| `config` | `.../sdk/config` | `Config` struct with `Default()` factory |
| `constants` | `.../sdk/constants` | SDK-level constants |
### Network Management
| Package | Import | Purpose |
|---------|--------|---------|
| `network` | `.../sdk/network` | `NetworkManager` -- create/start/stop networks. Types: `NetworkType` (mainnet/testnet/local/custom), `NetworkStatus`, `NodeType` (validator/api/full/light), `NetworkParams` |
| `network` (legacy) | `.../sdk/network` | `LegacyNetwork` with predefined `MainnetNetwork` (api.lux.network), `TestnetNetwork` (api-test.lux.network), `LocalNetwork` (127.0.0.1:9630) |
| `netrunner` | `.../sdk/netrunner` | Wraps `github.com/luxfi/netrunner` for test network orchestration |
| `connect` | `.../sdk/connect` | Node connection utilities |
### Blockchain Creation
| Package | Import | Purpose |
|---------|--------|---------|
| `blockchain` | `.../sdk/blockchain` | `Builder` -- `CreateBlockchain()`, `Deploy()`. Types: `BlockchainType` (L1/L2/L3), `VMType` (evm/wasm/custom/tokenvm/morpheusvm), `Blockchain`, `Net`, `GenesisAccount`, `GenesisValidator` |
| `chainconfig` | `.../sdk/chainconfig` | Chain config and genesis generation/parsing |
| `configspec` | `.../sdk/configspec` | Configuration specification utilities |
| `fees` | `.../sdk/fees` | Fee configuration |
### Chain Clients
| Package | Import | Purpose |
|---------|--------|---------|
| `platformvm` | `.../sdk/platformvm` | P-Chain client: `GetHeight()`, `GetBalance()`, `GetUTXOs()`, `GetCurrentValidators()`, `GetNet()`, `GetNets()`, `GetStakingAssetID()`, `GetL1Validator()` |
| `exchangevm` | `.../sdk/exchangevm` | X-Chain client: `Client`, `WalletClient`, `StaticClient` -- UTXO transfers, asset creation |
| `evm` | `.../sdk/evm` | C-Chain EVM utilities |
| `health` | `.../sdk/health` | Node health client with `Health(ctx)` |
| `admin` | `.../sdk/admin` | Admin API client |
| `info` | `.../sdk/info` | Node info client |
| `indexer` | `.../sdk/indexer` | Transaction indexer client |
### Wallet & Key Management
| Package | Import | Purpose |
|---------|--------|---------|
| `wallet` | `.../sdk/wallet` | `Wallet` struct -- multi-chain wallet with `ImportKey()`, BLS key support for validator ops, UTXO tracking |
| `wallet/primary` | `.../sdk/wallet/primary` | Primary network wallet operations |
| `wallet/chain` | `.../sdk/wallet/chain` | Per-chain wallet backends |
| `wallet/crypto` | `.../sdk/wallet/crypto` | Wallet cryptographic operations |
| `wallet/keychain` | `.../sdk/wallet/keychain` | Wallet keychain management |
| `key` | `.../sdk/key` | `Key` struct (ed25519/bls/secp256k1), `Keychain` with `Add()`, `Sign()`, `Get()`, `Addresses()` |
| `keychain` | `.../sdk/keychain` | Extended keychain utilities |
| `ledger` | `.../sdk/ledger` | Ledger hardware wallet integration |
| `crypto` | `.../sdk/crypto` | Ed25519 key operations |
| `multisig` | `.../sdk/multisig` | Multi-signature transaction support |
### Validator Management
| Package | Import | Purpose |
|---------|--------|---------|
| `validator` | `.../sdk/validator` | Validator configuration and context |
| `validatormanager` | `.../sdk/validatormanager` | L1 validator lifecycle: PoA and PoS manager contracts, registration, removal, weight updates, uptime tracking. Embeds deployed contract bytecodes (ValidatorMessages, PoAValidatorManager, PoSValidatorManager, TransparentUpgradeableProxy) |
| `validatormanager/txs` | `.../sdk/validatormanager/txs` | Validator manager transaction types |
| `validatormanager/warp` | `.../sdk/validatormanager/warp` | Warp message handling for validator ops |
### Smart Contracts
| Package | Import | Purpose |
|---------|--------|---------|
| `contract` | `.../sdk/contract` | Smart contract interaction: `Deploy()`, `Chain()`, ABI parsing, receipt status handling, allocation management. Uses `github.com/luxfi/evm/accounts/abi/bind` |
| `contract/contracts` | `.../sdk/contract/contracts` | Precompiled contract interfaces |
| `contracts/bin` | `.../sdk/contracts/bin` | Compiled contract binaries |
### Cross-Chain
| Package | Import | Purpose |
|---------|--------|---------|
| `warp` | `.../sdk/warp` | Warp cross-chain messaging utilities |
### Infrastructure
| Package | Import | Purpose |
|---------|--------|---------|
| `lpm` | `.../sdk/lpm` | Lux Plugin Manager -- VM plugin installation |
| `models` | `.../sdk/models` | Data models: `Network`, `Sidecar`, `L2`, `Host`, `ClustersConfig`, `BootstrapValidator`, `NodeConfig`, `VM`, `Cloud`, `Docker` |
| `publicarchive` | `.../sdk/publicarchive` | Public archive downloader for chain data |
| `profiles` | `.../sdk/profiles` | Node configuration profiles |
| `trace` | `.../sdk/trace` | OpenTelemetry tracing |
| `utils` | `.../sdk/utils` | General utilities |
| `utils/fs` | `.../sdk/utils/fs` | Filesystem utilities |
| `ux` | `.../sdk/ux` | User experience helpers (output formatting) |
| `prompts` | `.../sdk/prompts` | Interactive prompt utilities |
| `flags` | `.../sdk/flags` | CLI flag mutex support |
| `assets` | `.../sdk/assets` | Embedded asset files |
| `chain` | `.../sdk/chain` | Chain type definitions |
## Chain Support
| Chain | Type | Operations |
|-------|------|-----------|
| P-Chain | Platform | Staking, validators, L1 creation |
| X-Chain | Exchange | UTXO transfers, asset creation |
| C-Chain | Contract | EVM transactions, contract deployment |
| Q-Chain | Quantum | PQ-specific operations |
| M-Chain | MPC | Multi-party custody |
| Chain | Type | SDK Package | Operations |
|-------|------|-------------|-----------|
| P-Chain | Platform | `platformvm` | Staking, validators, L1/net creation, UTXOs, balance |
| X-Chain | Exchange | `exchangevm` | UTXO transfers, asset creation/minting |
| C-Chain | Contract | `evm` | EVM transactions, contract deployment |
| Q-Chain | Quantum | (via node API) | PQ-specific operations |
| M-Chain | MPC | (via node API) | Multi-party custody |
## Capabilities
## Network Endpoints
- Network management (start, stop, health)
- L1/L2/L3 blockchain creation
- Staking and validator management
- Cross-chain transfers (Warp messaging)
- Wallet management
- Custom VM deployment
- WASM support
## Auto-Selection
SDK auto-selects the best available backend:
1. CLI (if installed)
2. Netrunner (if running)
3. Direct node APIs
4. Built-in fallback
| Network | ID | Endpoint |
|---------|-----|----------|
| Mainnet | `constants.MainnetID` | `https://api.lux.network` |
| Testnet | `constants.TestnetID` | `https://api-test.lux.network` |
| Local | `constants.LocalID` | `http://127.0.0.1:9630` |
| Devnet | custom | custom |
## API Examples
### Node Client
### Initialize SDK
```go
import "github.com/luxfi/sdk/client"
import "github.com/luxfi/sdk"
import "github.com/luxfi/sdk/config"
c := client.New("http://localhost:9630")
cfg := config.Default()
s, err := sdk.New(cfg)
// s.Networks() -> *network.NetworkManager
// s.Blockchains() -> *blockchain.Builder
```
// Node info
nodeID, _ := c.Info().GetNodeID(ctx)
peers, _ := c.Info().Peers(ctx)
fmt.Printf("Node: %s, Peers: %d\n", nodeID, len(peers))
### Launch Network
// P-Chain: Validators
validators, _ := c.Platform().GetCurrentValidators(ctx, nil)
```go
net, err := s.LaunchNetwork(ctx, "local", 5)
```
// Health
health, _ := c.Health().Health(ctx)
### Create & Deploy Blockchain
```go
bc, err := s.CreateAndDeployBlockchain(ctx, &sdk.BlockchainParams{
Name: "my-chain",
Type: blockchain.TypeL1,
VMType: blockchain.VMTypeEVM,
ChainID: big.NewInt(43114),
Network: net,
})
```
### P-Chain Client
```go
import "github.com/luxfi/sdk/platformvm"
client := platformvm.NewClientWithNetworkID("http://localhost:9630", 1)
height, err := client.GetHeight(ctx)
validators, err := client.GetCurrentValidators(ctx, chainID, nil)
balance, err := client.GetBalance(ctx, addrs)
```
### Wallet Operations
```go
import "github.com/luxfi/sdk/wallet"
import "github.com/luxfi/sdk/key"
w, _ := wallet.New(ctx, wallet.Config{
URI: "http://localhost:9630",
NetworkID: 1, // mainnet
})
// Get balances
balance, _ := w.P().GetBalance(ctx)
fmt.Printf("P-Chain: %d nLUX\n", balance)
// Transfer on X-Chain
txID, _ := w.X().Transfer(ctx, wallet.TransferArgs{
To: "X-lux1...",
Amount: 1_000_000_000, // 1 LUX
AssetID: "LUX",
})
w := wallet.New(networkID, chainID)
addr, err := w.ImportKey(privateKey)
```
### Transaction Building
### Key Management
```go
import "github.com/luxfi/sdk/tx"
import "github.com/luxfi/sdk/key"
// Add validator (stake)
stakeTx, _ := tx.NewAddValidatorTx(tx.AddValidatorTxArgs{
NodeID: nodeID,
Start: time.Now().Add(1 * time.Minute),
End: time.Now().Add(365 * 24 * time.Hour),
StakeAmount: 2000 * units.Lux, // 2000 LUX minimum
RewardAddress: rewardAddr,
})
kc := key.NewKeychain()
err := kc.Add(privateKey)
sig, err := kc.Sign(message, address)
```
### C-Chain (EVM)
### Smart Contract Deployment
```go
import "github.com/luxfi/evm/ethclient"
import "github.com/luxfi/sdk/contract"
ethClient, _ := ethclient.Dial("http://localhost:9630/ext/bc/C/rpc")
block, _ := ethClient.BlockNumber(ctx)
// Contract interaction uses luxfi/evm/accounts/abi/bind
// and luxfi/geth types for EVM compatibility
```
### Validator Manager (L1)
```go
import "github.com/luxfi/sdk/validatormanager"
// Deploys embedded PoA/PoS validator manager contracts
// Handles registration, removal, weight updates via Warp
```
## VM Types
| VM | Constant | Description |
|----|----------|-------------|
| EVM | `VMTypeEVM` | Ethereum Virtual Machine (via luxfi/evm) |
| WASM | `VMTypeWASM` | WebAssembly VM |
| Custom | `VMTypeCustom` | User-provided VM |
| TokenVM | `VMTypeTokenVM` | HyperSDK token VM |
| MorpheusVM | `VMTypeMorpheusVM` | HyperSDK general VM |
## Related Skills
- `lux/lux-node.md` — Node that SDK connects to
- `lux/lux-cli.md` — CLI tool (SDK wraps CLI)
- `lux/lux-netrunner.md` — Network testing (SDK wraps netrunner)
- `lux/lux-node.md` -- Node that SDK connects to
- `lux/lux-cli.md` -- CLI tool (SDK wraps CLI)
- `lux/lux-netrunner.md` -- Network testing (SDK wraps netrunner)
- `lux/lux-crypto.md` -- Cryptographic primitives used by SDK
- `lux/lux-evm.md` -- EVM implementation
+199 -13
View File
@@ -1,24 +1,210 @@
---
title: "Lux Stack - Local Development Environment"
description: "Full local integration environment for Lux development — nodes, EVM, explorer, gateway, and monitoring via Docker Compose."
title: "Lux Stack"
description: "Sovereign L1 White-Label Ecosystem"
---
## Overview
Full local integration environment for Lux development — nodes, EVM, explorer, gateway, and monitoring via Docker Compose.
Lux Stack is a **Docker Compose-based white-label L1 blockchain ecosystem**. Deploy a complete sovereign chain with explorer, DEX, marketplace, bridge, wallet, DeFi platform, and subgraph indexing in a single `docker compose up`. Post-quantum cryptography is enabled by default via Lux precompiles.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Path | ``github.com/luxfi/stack`` |
| Stack | Docker Compose |
| Start | `docker compose up` or `make up` |
| Repo | `github.com/luxfi/stack` |
| Orchestration | Docker Compose (`compose.yml`) |
| Start | `docker compose up -d` |
| Dev mode | `docker compose --profile dev up` |
| Indexers | `docker compose --profile indexers up` |
| Config | `.env` (copy from `.env.example`) |
## Included Services
## Services
- Lux nodes (validators)
- EVM (C-Chain)
- Block explorer
- KrakenD API gateway
- Prometheus + Grafana monitoring
### Core Infrastructure
| Service | Image | Port | Purpose |
|---------|-------|------|---------|
| `node` | `ghcr.io/luxfi/node:latest` | 9650 (HTTP), 9651 (staking) | Lux consensus blockchain node |
| `redis` | `ghcr.io/hanzoai/kv:latest` | 6380 | Cache (2GB max, allkeys-lru) |
| `ipfs` | `ipfs/kubo:latest` | 5001 (API), 8081 (gateway), 4002 (swarm) | Decentralized storage |
### Databases (all `ghcr.io/hanzoai/sql:latest`)
| Service | Default User | Default DB | Purpose |
|---------|-------------|------------|---------|
| `explorer-db` | `explorer` | `explorer` | Block explorer data |
| `exchange-db` | `exchange` | `exchange` | DEX/exchange data |
| `graph-postgres` | `graph` | `graph-node` | The Graph indexer |
### Applications
| Service | Image | Port | Purpose |
|---------|-------|------|---------|
| `explorer` | `ghcr.io/blockscout/blockscout:latest` | 4000 | Block explorer (Blockscout) |
| `exchange` | `ghcr.io/luxfi/exchange:latest` | 3000 | DEX / Token exchange |
| `exchange-api` | `ghcr.io/luxfi/exchange-api:latest` | 3010 | Exchange backend API |
| `marketplace` | `ghcr.io/luxfi/marketplace:latest` | 3001 | NFT marketplace |
| `bridge` | `ghcr.io/luxfi/bridge:latest` | 3002 | Cross-chain bridge (to Lux mainnet) |
| `finance` | `ghcr.io/luxfi/finance:latest` | 3003 | DeFi platform |
| `wallet` | `ghcr.io/luxfi/wallet:latest` | 3004 | Web wallet |
| `graph-node` | `graphprotocol/graph-node:latest` | 8000 (HTTP), 8001 (WS), 8020 (admin) | Subgraph indexing |
### Optional: Chain Indexers (`--profile indexers`)
| Service | Port | Purpose |
|---------|------|---------|
| `pchain-indexer` | 4100 | P-Chain block indexer |
| `xchain-indexer` | 4200 | X-Chain block indexer |
### Optional: Dev Tools (`--profile dev`)
| Service | Port | Purpose |
|---------|------|---------|
| `adminer` | 8082 | Database admin UI |
| `redis-commander` | 8083 | Redis admin UI |
| `mailhog` | 8025 (UI), 1025 (SMTP) | Email testing |
## Chain Configuration
All chain identity is configured via `.env`:
```bash
# Chain identity
NETWORK_NAME="My Chain" # Display name
NETWORK_SLUG=mychain # Container prefix
COIN_NAME=MYC # Native coin name
COIN_SYMBOL=MYC # Coin ticker
COIN_DECIMALS=18 # Token decimals
CHAIN_ID=99999 # EVM chain ID (unique)
NETWORK_ID=12345 # Lux network ID
# Lux mainnet connection (bridge + PQ safety)
LUX_MAINNET_RPC=https://api.lux.network/mainnet/ext/bc/C/rpc
# Node
LOG_LEVEL=info
NODE_HTTP_PORT=9650
NODE_STAKING_PORT=9651
# Image registry (override for custom builds)
IMAGE_REGISTRY=ghcr.io/luxfi
```
## Port Allocation Summary
```
9650: Node RPC 3000: Exchange 8000: GraphQL
9651: Node Staking 3001: Marketplace 8001: GraphQL WS
5001: IPFS API 3002: Bridge 8020: Graph Admin
8081: IPFS Gateway 3003: Finance 8082: Adminer
6380: Redis 3004: Wallet 8083: Redis Commander
4000: Explorer 3010: Exchange API 8025: Mailhog UI
4100: P-Chain Indexer 4200: X-Chain Indexer
```
## Startup Order
Services start in dependency order:
1. **Redis** -- cache layer
2. **PostgreSQL databases** -- explorer-db, exchange-db, graph-postgres
3. **IPFS** -- decentralized storage
4. **Lux Node** -- blockchain (waits for health check)
5. **Explorer** -- depends on node + explorer-db
6. **Graph Node** -- depends on node + graph-postgres + IPFS
7. **Exchange API** -- depends on node + exchange-db + redis
8. **Application frontends** -- exchange, marketplace, bridge, finance, wallet
Health checks are configured on all critical services (node, redis, all databases, explorer).
## Explorer Configuration
The Blockscout explorer connects to the C-Chain:
```
RPC: http://node:9650/ext/bc/C/rpc
Trace: http://node:9650/ext/bc/C/rpc
WebSocket: ws://node:9650/ext/bc/C/ws
```
Environment variables control chain display: `COIN`, `COIN_NAME`, `NETWORK`, `CHAIN_ID`.
## Development Workflow
```bash
# Initial setup
cp .env.example .env # Configure your chain
# Edit .env with your chain identity
# Production stack
docker compose up -d # Start all services
docker compose logs -f node # Follow node logs
docker compose ps # Check status
# Development stack (with admin tools)
docker compose --profile dev up -d
# With P/X chain indexers
docker compose --profile indexers up -d
# Selective services
docker compose up -d node redis explorer # Core only
# Teardown
docker compose down # Stop services
docker compose down -v # Stop + remove volumes
```
### Dev Mode Overlay
For hot-reloading during development:
```bash
docker compose -f compose.yml -f compose.dev.yml up
```
## Networking
- All services run on Docker bridge network `chain-network`
- Internal communication uses container names (e.g., `http://node:9650`)
- External access via mapped host ports
- CORS and SSL are not configured (development only)
## Makefile Targets
```bash
make up # Start production stack
make down # Stop all services
make dev # Start with dev tools
make logs # Follow all logs
make status # Check service health
make clean # Remove volumes and data
make build # Build local images
make validate # Validate compose config
make test # Run integration tests
make health # Check all health endpoints
```
## Architecture Decisions
| Decision | Rationale |
|----------|-----------|
| Docker Compose | Simple orchestration, easy to customize |
| Separate databases | Service isolation, independent scaling |
| Blockscout | Most complete open-source EVM explorer |
| The Graph | Standard subgraph indexing for DApps |
| `ghcr.io/hanzoai/sql` | Hanzo PostgreSQL image (consistent infra) |
| `ghcr.io/hanzoai/kv` | Hanzo Redis/Valkey image (consistent infra) |
| Bridge to Lux mainnet | Shared validator security, PQ signatures |
## White-Label Customization
To create your own sovereign L1:
1. Copy `.env.example` to `.env`
2. Set `NETWORK_NAME`, `COIN_NAME`, `COIN_SYMBOL`, `CHAIN_ID`
3. Optionally customize `IMAGE_REGISTRY` for your own container images
4. Run `docker compose up -d`
5. Access explorer at `http://localhost:4000`, exchange at `http://localhost:3000`
The stack is designed so that every configurable value flows from `.env` into container names, database credentials, and application environment -- a single file controls the entire chain identity.
+161 -53
View File
@@ -1,102 +1,210 @@
---
title: "Lux Tokens - Bridge, Exchange & Wallet Token Registry"
description: "## Quick reference"
title: "Lux Tokens"
description: "Bridge, Exchange & Wallet Token Registry"
---
## Overview
Lux Tokens is the **canonical token registry** for the Lux ecosystem. It contains bridge mappings between Ethereum and Lux tokens, token logos, and condensed token lists (top 100/150). Used by Lux Bridge, Lux Exchange, and Lux Wallet.
Lux Tokens is the **canonical token registry** for the Lux ecosystem. It stores bridge mappings between Ethereum and Lux C-Chain tokens, token logos for DeFi frontends, and ranked condensed lists (top 100/150 by market cap via CoinGecko). The registry is consumed by Lux Bridge, Lux Exchange, and Lux Wallet. Hosted on Vercel with a root redirect to `lux.network`.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/tokens` |
| Branch | `main` |
| Language | Python (scripts only) |
| Hosting | Vercel (redirects root to lux.network) |
| Logo format | `<token-address>/logo.png` |
| Language | Python 3 (scripts only, data is JSON/CSV) |
| Hosting | Vercel (root redirects to `lux.network`) |
| Total Ethereum bridgeable tokens | **368** |
| Total bridge mappings (CSV) | **368** (penultimate.csv) |
| Lux token logo directories | **432** |
| Ethereum token logo directories | **1** (minimal, most logos referenced by Lux address) |
| Logo format | `<chain>-tokens/<checksummed-address>/logo.png` |
| Logo URL pattern | `https://raw.githubusercontent.com/luxfi/wallet/main/tokens/lux-tokens/<address>/logo.png` |
| Python dependencies | `pandas`, `pycoingecko`, `GitPython` |
## Structure
## Repository Structure
```
tokens/
├── lux-tokens/ # Token logos by Lux address
│ └── <address>/logo.png
├── ethereum-tokens/ # Bridged token logos by Ethereum address
│ └── <address>/logo.png
├── ethereum.config # All bridgeable tokens on Ethereum (full list)
├── ethereum100.config # Top 100 bridgeable Ethereum tokens
├── ethereum150.config # Top 150 bridgeable Ethereum tokens
├── lux.config # All bridged tokens on Lux (full list)
├── lux100.config # Top 100 Lux tokens
├── lux150.config # Top 150 Lux tokens
├── lux-tokens/ # 432 directories, one per Lux C-Chain token
│ └── <checksummed-address>/
│ └── logo.png
├── ethereum-tokens/ # Bridged token logos by Ethereum address
│ └── <address>/
│ └── logo.png
├── ethereum.config # All 368 bridgeable Ethereum tokens (JSON)
├── ethereum100.config # Top 100 by market cap (JSON)
├── ethereum150.config # Top 150 by market cap (JSON)
├── lux.config # All 368 bridged Lux tokens (JSON)
├── lux100.config # Top 100 by market cap (JSON)
├── lux150.config # Top 150 by market cap (JSON)
├── data/
│ ├── eth_token_mapping.csv # Ethereum token mapping data
│ ├── current_mapping_libre.csv # Current libre mapping
│ ├── penultimate.csv # Previous mapping snapshot
│ └── penultimate.json # Previous mapping (JSON)
│ ├── penultimate.csv # Master bridge mapping (368 entries, 11 columns)
│ ├── penultimate.json # Same mapping as JSON
│ ├── eth_token_mapping.csv # Ethereum token mapping source
│ └── current_mapping_libre.csv # Previous mapping (used by swapLogos.py)
├── scripts/
│ ├── generateAssets.py # Generate token asset files
│ ├── smallConfig.py # Generate condensed 100/150 lists
│ └── swapLogos.py # Swap logo files between chains
├── vercel.json # Redirect root to lux.network
│ ├── generateAssets.py # Generate config files from CSV
│ ├── smallConfig.py # Generate ranked top-100/150 lists
│ └── swapLogos.py # Swap logo directories between mappings
├── vercel.json # Root redirect to lux.network
└── README.md
```
## Config File Format
Each config file (ethereum.config, lux.config) is a JSON array of token entries:
Each `.config` file is a JSON object with a single `data` array:
```json
{
"data": [
{
"address": "0x69A95185ee2a045CDC4bCd1b1Df10710395e4e23",
"name": "$Poolz Finance",
"symbol": "POOLZ",
"imageUri": "https://raw.githubusercontent.com/luxfi/wallet/main/tokens/lux-tokens/0x96CE.../logo.png",
"resourceId": "0x000000000000000000000069a95185ee2a045cdc4bcd1b1df10710395e4e2301"
}
]
}
```
| Field | Description |
|-------|-------------|
| `Address` | Token contract address on the respective chain |
| `Name` | Token name |
| `Symbol` | Token ticker symbol |
| `ImageURI` | Location of the token logo |
| `ResourceId` | Mapping ID to link Ethereum token to its Lux counterpart |
| `address` | Token contract address on the respective chain (checksummed) |
| `name` | Human-readable token name |
| `symbol` | Ticker symbol (e.g., `POOLZ`, `AAVE`, `1INCH`) |
| `imageUri` | Absolute URL to logo PNG (hosted on GitHub raw) |
| `resourceId` | 66-character hex string (32 bytes) -- bridge mapping key linking Ethereum token to its Lux counterpart |
The `ResourceId` field is the bridge mapping key -- it links an Ethereum token to its corresponding Lux token and vice versa.
The `resourceId` is the **bridge mapping key**. The same `resourceId` appears in both `ethereum.config` and `lux.config`, linking the two sides of a bridged token pair.
## Master Mapping CSV
`data/penultimate.csv` -- the source of truth for all bridge mappings.
### Columns (11)
| Column | Example |
|--------|---------|
| `Resource ID` | `000000000000000000000069a95185ee2a045cdc4bcd1b1df10710395e4e2301` |
| `Ethereum Token Address` | `0x69A95185ee2a045CDC4bCd1b1Df10710395e4e23` |
| `Ethereum Handler Address` | `0xdAC7Bb7Ce4fF441A235F08408e632FA1D799A147` |
| `Ethereum Token Name` | `$Poolz Finance` |
| `Ethereum Token Symbol` | `POOLZ` |
| `Ethereum Token Decimals` | `18` |
| `Lux Token Address` | `0x96CE026f10890f4836937e6FDe75f13252fdf414` |
| `Lux Handler Address` | `0x6147F5a1a4eEa5C529e2F375Bd86f8F58F8Bc990` |
| `Lux Token Name` | `$Poolz Finance` |
| `Lux Token Symbol` | `POOLZ` |
| `Lux Token Decimals` | `18` |
Handler addresses are the bridge contract handler on each chain:
- Ethereum handler: `0xdAC7Bb7Ce4fF441A235F08408e632FA1D799A147`
- Lux handler: `0x6147F5a1a4eEa5C529e2F375Bd86f8F58F8Bc990`
## Token Logos
Logos stored at `<chain>-tokens/<address>/logo.png`:
- `lux-tokens/` -- Logos by Lux C-Chain address (checksummed)
- `ethereum-tokens/` -- Logos by Ethereum address (for bridged tokens)
Logos stored at `<chain>-tokens/<checksummed-address>/logo.png`:
- `lux-tokens/` -- 432 token logo directories, indexed by Lux C-Chain address
- `ethereum-tokens/` -- Logos by Ethereum address (sparse, most logos are referenced by Lux address)
These logos are displayed on Lux DeFi apps (DEX, analytics, wallet).
Logo URLs served from GitHub raw content:
```
https://raw.githubusercontent.com/luxfi/wallet/main/tokens/lux-tokens/<address>/logo.png
```
Requirements for logo files:
- Format: PNG
- Shape: Square (recommended 256x256 or 512x512)
- Background: Transparent preferred
- Directory name: Checksummed address (EIP-55)
## Adding a Token Logo
1. Create directory: `lux-tokens/<checksummed-address>/`
2. Add `logo.png` (square, transparent background recommended)
2. Add `logo.png` (square PNG, transparent background)
3. Open PR to `main` branch
Adding a logo here does NOT make a token bridgeable. Bridge support requires separate configuration.
Adding a logo here does **not** make a token bridgeable. Bridge support requires separate bridge contract configuration and deployment.
## Scripts
All scripts require Python 3 with `pandas` and `GitPython`. The `smallConfig.py` script additionally requires `pycoingecko`.
### `scripts/generateAssets.py`
Reads `data/penultimate.csv` and generates:
- `ethereum.config` -- full Ethereum token list
- `lux.config` -- full Lux token list
Also has (commented out) functions to:
- Copy logos from a `Logos/` directory to `lux-tokens/`
- Batch-commit and push logos to git
```bash
# Generate asset files from mapping data
python scripts/generateAssets.py
# Generate condensed top-100/150 lists from full configs
python scripts/smallConfig.py
# Swap logos between chain directories
python scripts/swapLogos.py
cd data && python ../scripts/generateAssets.py
```
### `scripts/smallConfig.py`
Generates ranked top-100 and top-150 lists using CoinGecko market cap data:
1. Fetches market data via `CoinGeckoAPI().get_coins_markets('usd', per_page=250, order='market_cap_desc')`
2. Matches tokens by symbol (case-insensitive) against `penultimate.csv`
3. Generates 4 files: `ethereum100.config`, `ethereum150.config`, `lux100.config`, `lux150.config`
4. Handles symbol collisions by logging and skipping duplicates
```bash
cd data && python ../scripts/smallConfig.py
```
### `scripts/swapLogos.py`
Used during bridge contract migrations. Compares `current_mapping_libre.csv` against `penultimate.csv` by token symbol and renames logo directories from old Lux addresses to new ones.
```bash
cd data && python ../scripts/swapLogos.py
```
## Notable Tokens in Registry
Some well-known tokens in the bridge mapping (by symbol):
`AAVE`, `1INCH`, `UNI`, `SUSHI`, `COMP`, `MKR`, `SNX`, `YFI`, `LINK`, `BAT`, `ZRX`, `CRV`, `BAL`, `ALPHA`, `AMP`, `DYDX`, `ENJ`, `MANA`, `SAND`, `AXS`, `GALA`, `IMX`, `LRC`, `MATIC`
## Consumers
| Service | Domain | Usage |
|---------|--------|-------|
| Lux Bridge | bridge.lux.network | Bridge mapping configs + logos |
| Lux Exchange | lux.exchange | Token logos + lists |
| Lux Wallet | wallet.lux.network | Token logos + metadata |
| Lux Bridge | `bridge.lux.network` | Reads `ethereum.config` + `lux.config` for bridge mapping; displays logos |
| Lux Exchange | `lux.exchange` | Uses condensed 100/150 lists for token selectors; displays logos |
| Lux Wallet | `wallet.lux.network` | Full token list for balance display; shows logos |
| DeFi analytics | Various | Token logos referenced by address |
## Vercel Configuration
```json
{
"redirects": [
{ "source": "/", "destination": "https://lux.network", "permanent": true }
]
}
```
The repo is deployed on Vercel but only serves as a redirect. Token data is consumed directly from GitHub raw URLs.
## Updating the Registry
1. Update `data/penultimate.csv` with new token mapping entries
2. Run `scripts/generateAssets.py` to regenerate full config files
3. Run `scripts/smallConfig.py` to regenerate ranked lists (requires CoinGecko API access)
4. Add logo files under `lux-tokens/<address>/logo.png`
5. Open PR to `main`
## Related Skills
- `lux/lux-bridge.md` -- Cross-chain bridge (uses ResourceId mappings)
- `lux/lux-exchange.md` -- DEX frontend (displays token logos)
- `lux/lux-wallet.md` -- Wallet (token list + logos)
- `lux/lux-bridge.md` -- Cross-chain bridge (consumes ResourceId mappings)
- `lux/lux-exchange.md` -- DEX frontend (displays token logos from this registry)
- `lux/lux-wallet.md` -- Wallet (uses token list and logos)
+222 -10
View File
@@ -1,17 +1,229 @@
---
title: "Lux UI - Component Library & Visualization"
description: "Lux UI provides React components, chart visualizations, status dashboards, and terminal tools for the Lux ecosystem."
title: "Lux UI"
description: "Multi-Framework Component Library"
---
## Overview
Lux UI provides **React components, chart visualizations, status dashboards, and terminal tools** for the Lux ecosystem.
Lux UI (`@luxfi/ui`) is a comprehensive design system and component library for the Lux ecosystem. It is a pnpm monorepo built on top of shadcn/ui, extended with domain-specific packages for commerce, web3, finance, 3D, animation, and agent UI. Supports React, Vue, Svelte, and React Native via multi-framework registry system. Published to npm as `@luxfi/ui` at version 5.3.37.
## Components
## Repository
| Component | Path | Purpose |
|-----------|------|---------|
| ui/ | ``github.com/luxfi/ui`` | @lux/ui React components |
| charts/ | ``github.com/luxfi/charts`` | Chart visualizations |
| status/ | ``github.com/luxfi/status`` | Status monitoring dashboard |
| tui/ | ``github.com/luxfi/tui`` | Terminal UI tools (Go) |
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/ui` |
| Local | `~/work/lux/ui/` |
| Package | `@luxfi/ui` v5.3.37 |
| License | MIT |
| Homepage | `https://ui.lux.finance` |
| Package Manager | pnpm 9.0.6 |
| Build Orchestrator | Turborepo 2.x |
| Node | 22+ |
## Tech Stack
| Technology | Version | Purpose |
|------------|---------|---------|
| React | 19.2.x | Primary rendering framework |
| Next.js | 14-16 | App framework for demo sites |
| Tailwind CSS | 4.1.x | Utility-first styling |
| TypeScript | 5.9.x | Type safety |
| Radix UI | Latest | Accessible primitives |
| Vitest | 4.0.x | Unit testing |
| Playwright | 1.56.x | E2E and visual regression testing |
| tsup | 8.5.x | Library bundling |
| Changeset | 2.29.x | Version management and changelogs |
| motion (Framer) | 12.12.x | Animation library |
| Recharts | 3.3.x | Chart components |
| dnd-kit | 6.x | Drag and drop |
| Lucide | 0.544.x | Icon system |
## Project Structure
```
~/work/lux/ui/
package.json # Root workspace (@luxfi/ui v0.1.0)
pnpm-workspace.yaml # app, apps/*, packages/*, pkg/*
brand.config.ts # Theme: pure black/white monochrome
components.json # shadcn/ui component registry config
playwright.config.ts # E2E test configuration
app/ # Main docs/registry app (@luxfi/ui-web)
components/ # 60+ component implementations
registry/ # Component registry system
hooks/ # 13 React hooks
lib/ # Utilities
scripts/ # Build scripts
__registry__/ # Auto-generated registry data
__tests__/ # Test suites
apps/
v4/ # v4 preview app (port 4000, Turbopack)
www/ # Marketing site
packages/
shadcn/ # shadcn CLI fork (v3.8.4) -- component installer
og/ # Open Graph image generation
tests/ # Shared test utilities
pkg/ # Domain-specific packages
ui/ # Core component library (@luxfi/ui v5.3.37)
brand/ # Brand assets and tokens
commerce/ # E-commerce components
checkout/ # Checkout flow components
shop/ # Shop/storefront components
web3/ # Web3/wallet components
react/ # React-specific utilities
data/ # Data display components
agent-ui/ # AI agent interface components
menu-icons/ # Menu icon set
ui-templates/ # Page templates
```
## Core Component Library (pkg/ui/)
Published as `@luxfi/ui` v5.3.37 to npm. Source in `pkg/ui/src/`:
### Component Categories
| Category | Path | Contents |
|----------|------|----------|
| `ui/` | Core UI | announcement, avatar-group, banner, cursor, marquee, pill, spinner, tags, ticker |
| `3d/` | 3D rendering | Three.js/Spline integrations |
| `animation/` | Motion | Framer Motion wrappers and presets |
| `auth/` | Authentication | Login/signup forms |
| `billing/` | Billing | Subscription and payment UI |
| `calendar-ext/` | Calendar | Extended calendar components |
| `charts/` | Data viz | Chart wrappers (Recharts) |
| `code/` | Code display | Syntax highlighting, code blocks |
| `desktop/` | Desktop | Desktop app chrome components |
| `device/` | Device frames | Phone/tablet/desktop device frames |
| `dock/` | App dock | macOS-style dock component |
| `form/` | Form elements | Input, select, checkbox, radio, etc. |
| `hooks/` | React hooks | Shared hook utilities |
| `kanban/` | Kanban board | Drag-and-drop board (dnd-kit) |
| `mcp/` | MCP UI | Model Context Protocol interfaces |
| `mermaid/` | Diagrams | Mermaid.js diagram rendering |
| `models/` | Data models | TypeScript model definitions |
| `navigation/` | Nav components | Sidebar, breadcrumbs, tabs |
| `pattern/` | Background | Decorative background patterns |
| `project/` | Project mgmt | Project management components |
| `registry/` | Registry system | Component registry infrastructure |
| `spline/` | Spline 3D | Spline.design integrations |
| `primitives-export.ts` | Primitives | Container, Box, Heading, Text, Button, Link, Stack, Grid |
### Domain Packages
| Package | Path | Purpose |
|---------|------|---------|
| `@luxfi/ui` | `pkg/ui/` | Core library (5.3.37) |
| Brand | `pkg/brand/` | Brand tokens, logos, colors |
| Commerce | `pkg/commerce/` | Product cards, cart, pricing |
| Checkout | `pkg/checkout/` | Payment flow, address, summary |
| Shop | `pkg/shop/` | Storefront layouts |
| Web3 | `pkg/web3/` | Wallet connect, chain selector, tx status |
| Agent UI | `pkg/agent-ui/` | Chat bubbles, tool calls, agent status |
| React | `pkg/react/` | React-specific wrappers |
| Data | `pkg/data/` | Data tables, lists, grids |
## Brand Configuration
Defined in `brand.config.ts`:
```typescript
{
name: "Lux UI",
siteUrl: "https://ui.lux.network",
company: "Lux Partners Limited",
github: { org: "luxfi", repo: "ui" },
theme: {
primary: "#1a1a1a", // Near black
darkBackground: "#000000", // Pure black
darkForeground: "#fafafa" // Near white
}
}
```
Pure black/white monochrome design language.
## Development
```bash
cd ~/work/lux/ui
# Install dependencies
pnpm install
# Start all apps in parallel
pnpm dev
# Start specific apps
pnpm v4:dev # v4 preview (port 4000)
pnpm www:dev # Marketing site
pnpm hanzo-ui:dev # Hanzo UI variant
# Build
pnpm build # Build all
pnpm v4:build # Build v4 app
pnpm cli:build # Build CLI
# Testing
pnpm test # Unit tests (Vitest)
pnpm test:e2e # E2E tests (Playwright)
pnpm test:visual # Visual regression tests
pnpm health-check # Component health validation
# Registry
pnpm build:registry # Build component registry
pnpm registry:build # Alternative registry build
pnpm registry:capture # Capture component screenshots
# Code quality
pnpm lint # ESLint
pnpm lint:fix # Auto-fix lint issues
pnpm format:write # Prettier formatting
pnpm typecheck # TypeScript type checking
pnpm check # lint + typecheck + format:check
# Publishing
pnpm pub:beta # Publish beta to npm
pnpm pub:release # Publish release to npm
pnpm release # Changeset version bump
```
## shadcn CLI (packages/shadcn/)
Forked shadcn CLI (v3.8.4) for component installation:
- Adds components from the Lux UI registry
- Supports multiple frameworks (React, Vue, Svelte, React Native)
- Handles Tailwind CSS 4 configuration
- Includes tests (Vitest)
## Testing Strategy
| Type | Tool | Command |
|------|------|---------|
| Unit | Vitest 4.0.6 | `pnpm test` |
| E2E | Playwright 1.56 | `pnpm test:e2e` |
| Visual | Playwright | `pnpm test:visual` |
| Accessibility | jest-axe / vitest-axe | Integrated in unit tests |
| Health | Custom script | `pnpm health-check` |
| Registry | Custom validator | `pnpm validate:registries` |
## Key Patterns
- Components follow shadcn/ui patterns: copy-paste, customizable, no runtime dependency lock-in
- Registry system auto-generates component metadata for the CLI installer
- Multi-framework support via separate registry entries per framework
- All components use Tailwind CSS with the monochrome theme tokens
- Domain packages (commerce, web3, agent-ui) extend the core primitives
- Changeset-based versioning with GitHub changelog generation
## Related Repos
| Repo | Purpose |
|------|---------|
| `github.com/luxfi/market` | NFT marketplace using these components |
| `github.com/luxfi/docs` | Documentation site using these components |
| `github.com/luxfi/explorer` | Block explorer using these components |
| `github.com/luxfi/bridge` | Bridge UI using these components |
+279 -28
View File
@@ -1,46 +1,297 @@
---
title: "Lux Universe - Production K8s Infrastructure"
description: "Lux Universe is the production Kubernetes infrastructure for the Lux Network — validators, gateways, markets, and supporting services on DOKS."
title: "Lux Universe"
description: "Production Network Infrastructure"
---
## Overview
Lux Universe is the **production Kubernetes infrastructure** for the Lux Network — validators, gateways, markets, and supporting services on DOKS.
Lux Universe is the **production-grade infrastructure monorepo** for running the Lux Network. It orchestrates triple 5-node validator networks (mainnet, testnet, devnet) using `lux cli` for node management and Docker Compose for supporting services (explorers, indexers, graph nodes, exchange, bridge, wallet, bank). The repo uses Git submodules to pin versions of core components (node, geth, evm, cli, netrunner, consensus).
**NOTE**: This is a private repository. Public details are limited to architecture overview.
## Quick Reference
| Item | Value |
|------|-------|
| Module | `luxpatch` (Go 1.26, minimal) |
| Networks | mainnet, testnet, devnet |
| Nodes per network | 5 validators |
| Node management | `lux cli` (not Docker) |
| Services | Docker Compose profiles |
| Chains | C-Chain (96369), Zoo (200200), Hanzo (36963) |
| State dir | `~/work/lux/state` |
| Snapshot dir | `~/.lux/snapshots/` |
## Architecture
### Services
```
┌────────────────────────────────────────┐
│ lux universe │
│ ┌──────────┐ ┌────────┐ ┌──────────┐ │
│ │ mainnet │ │testnet │ │ devnet │ │
│ │ 5 nodes │ │5 nodes │ │ 5 nodes │ │
│ │9630-9638 │ │9640-48 │ │ 9650-58 │ │
│ └────┬─────┘ └───┬────┘ └────┬─────┘ │
│ │ │ │ │
│ ┌────▼───────────▼────────────▼─────┐ │
│ │ Docker Services │ │
│ │ Explorers Graph Exchange IAM │ │
│ │ Indexers IPFS Bridge Bank │ │
│ │ Postgres Redis Pricing Wallet │ │
│ └───────────────────────────────────┘ │
└────────────────────────────────────────┘
```
| Service | Description |
|---------|-------------|
| Validators | Consensus validator nodes |
| API Gateway | KrakenD gateway at api.lux.network |
| Markets | DeFi/NFT marketplace at markets.lux.network |
| Lux Cloud | Cloud management at cloud.lux.network |
| PostgreSQL | In-cluster database |
| Redis | Caching layer |
| Datastore | Vector/KV store |
## Port Allocation
### Key Domains
| Network | HTTP Ports | Staking Ports | Chain ID | Zoo Chain ID |
|---------|-----------|---------------|----------|-------------|
| Mainnet | 9630-9638 (even) | 9631-9639 (odd) | 96369 | 200200 |
| Testnet | 9640-9648 (even) | 9641-9649 (odd) | 96368 | 200201 |
| Devnet | 9650-9658 (even) | 9651-9659 (odd) | 1337 | 1338 |
| Domain | Service |
|--------|---------|
| api.lux.network | KrakenD Gateway |
| cloud.lux.network | Lux Cloud |
| markets.lux.network | Markets |
Service ports: PostgreSQL 5432, Redis 6380, LUX Explorer 4010, Zoo Explorer 4011, Hanzo Explorer 4012, Graph Node 8000, IPFS 5001, Pricing API 8085, LXD Gateway 8080.
### Database Strategy
## Network Operations
In-cluster PostgreSQL (no managed databases). Serves cloud, commerce, console, gateway, and KMS databases.
```bash
# Start/stop individual networks
make start network=main # or test, dev
make stop network=main
make restart network=main
## Access
# Start everything (all 3 networks + Docker services)
make all
make stop-all
This is a **private repository**. Contact the infrastructure team for access.
# Health checks
make health network=main
make status network=main
make status-all # All networks + Docker services
## Related Skills
# Chain tracking (ensure tracked chains are deployed)
make track network=main
```
- `lux/lux-node.md` - Validator node software
- `lux/lux-monitoring.md` - Cluster monitoring
- `lux/lux-stack.md` - Local dev environment
## Snapshot Management
```bash
# Save/load snapshots
make snapshot network=main name=pre-upgrade
make resume network=main name=pre-upgrade
# Bootstrap from pre-built snapshots
make bootstrap network=main
make bootstrap-start network=main
# Manual snapshot operations
make snapshot-save network=main name=checkpoint
make snapshot-load network=main name=checkpoint
make snapshot-list
make snapshot-clean
```
## Docker Compose Profiles
The `compose.yml` uses profiles to selectively start service groups:
| Profile | Services |
|---------|----------|
| (default) | 5 validator nodes, postgres, redis, pricing, IPFS, LUX explorer |
| `explorers` | Zoo explorer, Hanzo explorer |
| `graph` | Graph Protocol node |
| `indexers` | P-Chain indexer, X-Chain indexer |
| `bridge` | Bridge NATS, Consul, KMS (Vault) |
| `ui` | Exchange UI, Wallet, Bridge UI, LXD Gateway, Explorer Frontend |
| `bank` | Bank API, Dashboard, Admin, Docs, Marketing Site |
| `iam` | Hanzo IAM (lux.id) |
| `dev` | Adminer (DB admin), Redis Commander |
```bash
# Start with profiles
docker compose up -d # Default services
docker compose --profile explorers up -d # Add explorers
docker compose --profile graph up -d # Add Graph Protocol
docker compose --profile ui up -d # Add frontend UIs
docker compose --profile bank up -d # Add Lux Bank (lux.financial)
```
## Validator Nodes (Docker)
5 validator nodes run as Docker containers with:
- Image: `ghcr.io/luxfi/node:latest`
- Network: `lux-network` (172.30.0.0/16)
- Static IPs: 172.30.0.10-14
- Bootstrap: Node 1 (172.30.0.10) is the bootstrap node
- Keys: Mounted from `~/.lux/keys/node{0-4}/`
- Genesis: Mounted from `~/work/lux/genesis/configs/mainnet/`
- Health checks: `curl http://localhost:9630/ext/health` every 30s
## Blockchain Explorers
| Explorer | Chain | Chain ID | Port | Image |
|----------|-------|----------|------|-------|
| LUX Explorer | C-Chain | 96369 | 4010 | Blockscout |
| Zoo Explorer | Zoo Network | 200200 | 4011 | Blockscout |
| Hanzo Explorer | AI Chain | 36963 | 4012 | Blockscout |
| Explorer Frontend | C-Chain | 96369 | 3100 | `ghcr.io/luxfi/explore` |
All explorers use shared PostgreSQL with separate databases (`explorer_lux`, `explorer_zoo`, `explorer_hanzo`).
## Chain Import
```bash
# Import chain data from RLP files
make import network=main # Imports C-Chain + Zoo via admin_importChain RPC
make import network=test
```
RLP files stored at `~/work/lux/state/rlp/`.
## AMM Testing
```bash
make amm network=main # Test AMM on C-chain
make amm-zoo network=main # Test AMM on Zoo chain
```
## Submodules
### Core
| Submodule | Description |
|-----------|-------------|
| `node` | Lux consensus node (luxd) |
| `geth` | Go-Ethereum fork (luxfi/geth) |
| `evm` | EVM plugin for Lux |
| `cli` | Lux CLI tool |
| `netrunner` | Network testing/orchestration |
| `consensus` | Consensus engine library |
### Application
| Submodule | Description |
|-----------|-------------|
| `bridge` | Cross-chain bridge |
| `exchange` | AMM DEX frontend |
| `explorer-lux` | LUX block explorer |
| `explorer-zoo` | Zoo block explorer |
| `explore-lux` | Explorer frontend |
| `graph-node-lux` | Graph Protocol node |
| `v2-subgraph` | Uniswap V2 subgraph |
| `v3-subgraph` | Uniswap V3 subgraph |
### Data
| Submodule | Description |
|-----------|-------------|
| `state` | Network state data (snapshots, RLP, keys) |
```bash
make init # Initialize all submodules
make update # Pull latest for all
make sync # Sync URLs from .gitmodules
make list # List submodules with commits
```
## Infrastructure Layer
### Database
Shared PostgreSQL (ghcr.io/hanzoai/sql) with databases: `explorer_lux`, `explorer_zoo`, `explorer_hanzo`, `explorer_pchain`, `explorer_xchain`, `graph_node`, `iam`, `bank`.
### Caching
Redis (ghcr.io/hanzoai/kv) with appendonly, 2GB max memory, allkeys-lru eviction.
### K8s Manifests (k8s/)
Production Kubernetes manifests for DOKS clusters:
| Directory | Purpose |
|-----------|---------|
| `lux-k8s/` | Main Lux services cluster |
| `lux-mainnet/` | Mainnet validator deployment |
| `lux-testnet/` | Testnet validator deployment |
| `lux-devnet/` | Devnet deployment |
| `lux-gateway/` | KrakenD API gateway |
| `lux-explorer/` | Block explorer |
| `lux-bridge/` | Bridge infrastructure |
| `lux-mpc/` | MPC key management |
| `lux-ns/` | Namespace definitions |
| `bootnode/` | Bootstrap node |
| `dns/` | DNS configuration |
| `hanzo-k8s/` | Hanzo services on Lux cluster |
### Configuration (configs/)
- `genesis.json` -- Network genesis configuration
- `validators.json` -- Validator definitions
- `node1.json` - `node5.json` -- Per-node configurations
- `node-template.json` -- Node config template
- `chains/` -- Chain-specific configurations
- `gateway/` -- API gateway configuration
- `chain-configs/C/` -- C-Chain configuration
## Lux Bank (lux.financial)
B2B stablecoin infrastructure with:
- Bank API (port 4000) -- Backend services with Currency Cloud integration
- Dashboard (port 3500) -- Client portal
- Admin (port 3502) -- Admin dashboard
- Docs (port 3503) -- Documentation
- Site (port 3501) -- Marketing site
Domains: `lux.financial`, `app.lux.financial`, `api.lux.financial`, `admin.lux.financial`, `docs.lux.financial`.
## Build & Test
```bash
make build # Build node + CLI
make build-node # Build lux node only
make build-cli # Build lux CLI only
make build-evm # Build EVM plugin
make build-docker # Build Docker images
make test # Run tests for node/geth/evm/cli
make fmt # Format Go code
make lint # Run go vet
```
## Key Endpoints (Running)
| Endpoint | URL |
|----------|-----|
| Mainnet C-Chain RPC | `http://127.0.0.1:9630/ext/bc/C/rpc` |
| Testnet C-Chain RPC | `http://127.0.0.1:9640/ext/bc/C/rpc` |
| Devnet C-Chain RPC | `http://127.0.0.1:9650/ext/bc/C/rpc` |
| LUX Explorer | `http://127.0.0.1:4010` |
| Zoo Explorer | `http://127.0.0.1:4011` |
| Graph Node | `http://127.0.0.1:8000` |
| LXD Gateway | `http://127.0.0.1:8080` |
## Directory Structure
```
universe/
compose.yml # Main Docker Compose (all services)
compose.mainnet.yml # Mainnet-specific overrides
compose.testnet.yml # Testnet-specific overrides
compose.devnet.yml # Devnet overrides
compose.local.yml # Local development
compose.services.yml # Services-only
compose.server.yml # Server deployment
Makefile # Network + service management
configs/ # Node configs, genesis, validators
chain-configs/ # Chain-specific configs (C/)
docker/ # Dockerfiles, init SQL, genesis
k8s/ # Production K8s manifests
iam/ # IAM init data
scripts/ # Operational scripts
docs/ # Documentation
node -> (submodule) # luxfi/node
geth -> (submodule) # luxfi/geth
evm -> (submodule) # luxfi/evm
cli -> (submodule) # luxfi/cli
netrunner -> (submodule) # luxfi/netrunner
consensus -> (submodule) # luxfi/consensus
explore -> (symlink) # Explorer frontend
explorer -> (symlink) # Explorer backend
```
+377 -60
View File
@@ -1,87 +1,404 @@
---
title: "Lux Wallet - Multi-Platform HD Wallet"
description: "Lux Wallet is a multi-platform hardware wallet application — `@luxwallet/monorepo` supporting Desktop, Web, Mobile (iOS/Android), and Browser Extension from a single codebase."
title: "Lux Wallet"
description: "Multi-Platform HD Wallet"
---
## Overview
Lux Wallet is a **multi-platform hardware wallet application** — `@luxwallet/monorepo` supporting Desktop, Web, Mobile (iOS/Android), and Browser Extension from a single codebase. Fork of OneKey, extensively customized for Lux chain support.
Lux Wallet is a **multi-platform HD wallet application** built as a Yarn Berry monorepo (`@luxwallet/monorepo` v1.0.0). It ships Desktop (Electron), Web, Mobile (iOS/Android), and Browser Extension from a single TypeScript codebase. Fork of OneKey v5, extensively customized with `@luxfi/*` packages for Lux Network integration, supporting **27 blockchain families** and hardware wallet signing.
## Quick reference
## Quick Reference
| Item | Value |
|------|-------|
| Repo | `github.com/luxfi/wallet` |
| Package | `@luxwallet/monorepo` v1.0.0 |
| Package manager | Yarn 4.1.0 (Berry) — NOT pnpm |
| Workspace packages | `@onekeyfe/*`, `@luxwallet/*` |
| Local path | `~/work/lux/wallet/` |
| Root package | `@luxwallet/monorepo` v1.0.0 |
| Package manager | Yarn 4.1.0 (Berry) -- NOT pnpm |
| Node requirement | >= 20 |
| License | BSD 3-Clause (Lux Industries Inc. 2020-2025) |
| TypeScript | Strict mode, ES6 target, CommonJS module |
| React | 18.x (root), 17.x (ext app) |
| React Native | 0.73.7 |
| Expo | 50.0.5 |
| UI framework | Tamagui 1.79.19 (cross-platform) |
| EVM libs | viem 2.9.x, ethers 5.4.x, ethereumjs-util |
| Local DB | IndexedDB (web/ext), Realm (native) -- `OneKeyV5` |
## Architecture
```
@luxwallet/monorepo
|
+-- apps/
| +-- ext/ @luxwallet/x v0.92.79 (Chrome/Firefox/Safari extension)
| +-- desktop/ @onekeyhq/desktop (Electron 27)
| +-- mobile/ @onekeyhq/mobile (React Native + Expo)
| +-- web/ @onekeyhq/web (SPA, webpack, port 3000)
| +-- web-embed/ @onekeyhq/web-embed (Embedded webview, port 3008)
|
+-- packages/
+-- core/ @onekeyhq/core (Chain APIs, crypto, HD derivation)
+-- kit/ @onekeyhq/kit (UI views, Redux state, navigation)
+-- kit-bg/ @onekeyhq/kit-bg (Background services, vaults, DB)
+-- shared/ @onekeyhq/shared (Constants, config, utils, platform)
+-- components/ @onekeyhq/components (Tamagui UI component library)
+-- qr-wallet-sdk/ @onekeyhq/qr-wallet-sdk (Air-gapped QR signing, Keystone)
```
### Layer Diagram
```
+---------------------------------------------------------+
| App Layer (apps/*) |
| ext | desktop | mobile | web | web-embed |
+---------------------------------------------------------+
| UI Layer (packages/kit) |
| Views: Home, Send, Receive, Swap, Staking, DApp, ... |
| State: Redux Toolkit + jotai + redux-persist |
+---------------------------------------------------------+
| Background Layer (packages/kit-bg) |
| Services: 40+ background services |
| Vaults: Per-chain keyring + vault implementations |
| DB: IndexedDB (web) / Realm (native) |
+---------------------------------------------------------+
| Core Layer (packages/core) |
| Chains: 27 chain implementations |
| Secret: BIP-32/39/340, AES-256-CBC, curves |
| Base: CoreChainApiBase, ChainSigner |
+---------------------------------------------------------+
| Shared Layer (packages/shared) |
| Config, constants, preset networks, platform env |
+---------------------------------------------------------+
```
## Core Concepts
### HD Key Derivation
The wallet implements BIP-32 (SLIP-0010 variant) hierarchical deterministic key derivation with three elliptic curves:
| Curve | Seed Key | Used By |
|-------|----------|---------|
| `secp256k1` | `Bitcoin seed` | BTC, EVM, Cosmos, Tron, XRP, Doge, LTC, BCH, Kaspa, CKB |
| `ed25519` | `ed25519 seed` | SOL, Aptos, SUI, NEAR, Algo, Cardano, Polkadot, Nostr |
| `nistp256` | `Nist256p1 seed` | (Reserved, supported but not primary for any chain) |
**Key derivation flow:**
```
Mnemonic (BIP-39, English wordlist)
|
v
mnemonicToSeedSync(mnemonic, passphrase?) -- 512-bit seed
|
v
HMAC-SHA512(curve_seed_key, seed) -- master key + chain code
|
v
CKDPriv(parent, index) -- child key derivation
| hardened: index >= 2^31
| ed25519: hardened only (SLIP-0010)
v
Per-chain address generation
```
**Master key generation** follows SLIP-0010 retry logic: if the derived key is invalid (>= group order or zero), re-derive using `HMAC-SHA512(key, I)` recursively.
**Entropy storage:** Mnemonic entropy is stored with a 2-byte prefix (language code + length) padded to 32 bytes with random data, then encrypted. Supports 12/15/18/21/24-word mnemonics (entropy lengths 16/20/24/28/32 bytes).
### BIP Path Templates by Chain
| Chain | Default Template | Coin Type | Address Encoding |
|-------|-----------------|-----------|-----------------|
| **BTC Nested SegWit** | `m/49'/0'/{i}'/0/0` | 0 | P2SH_P2WPKH |
| **BTC Taproot** | `m/86'/0'/{i}'/0/0` | 0 | P2TR |
| **BTC Native SegWit** | `m/84'/0'/{i}'/0/0` | 0 | P2WPKH |
| **BTC Legacy** | `m/44'/0'/{i}'/0/0` | 0 | P2PKH |
| **EVM (standard)** | `m/44'/60'/0'/0/{i}` | 60 | keccak256 |
| **EVM (Ledger Live)** | `m/44'/60'/{i}'/0/0` | 60 | keccak256 |
| **SOL (standard)** | `m/44'/501'/{i}'/0'` | 501 | ed25519 pubkey |
| **SOL (Ledger Live)** | `m/44'/501'/{i}'` | 501 | ed25519 pubkey |
| **Cosmos** | `m/44'/118'/0'/0/{i}` | 118 | bech32 |
| **Cardano** | `m/1852'/1815'/{i}'` | 1815 | bech32 |
| **Polkadot** | `m/44'/354'/0'/0/{i}` | 354 | SS58 |
| **Tron** | `m/44'/195'/0'/0/{i}` | 195 | base58check |
| **XRP** | `m/44'/144'/0'/0/{i}` | 144 | base58 |
| **Aptos** | `m/44'/637'/{i}'` | 637 | hex |
| **SUI** | `m/44'/784'/{i}'/0'/0'` | 784 | hex |
| **NEAR** | `m/44'/397'/{i}'` | 397 | implicit/named |
| **Filecoin** | `m/44'/461'/0'/0/{i}` | 461 | f1/f3 |
| **Kaspa** | `m/44'/111111'/{i}'` | 111111 | bech32 |
| **Lightning** | `m/44'/81297820149147'/0'/0/{i}` | 81297820149147 | invoice |
### Supported Chains (27 Families)
Production-enabled chain implementations with vault + keyring + core API:
| # | Impl ID | Chain | Account Type | Curve | UTXO | NFT |
|---|---------|-------|-------------|-------|------|-----|
| 1 | `evm` | Ethereum + all EVM (Avalanche C-Chain, BSC, Polygon, Arbitrum, Optimism, etc.) | SIMPLE | secp256k1 | No | Yes |
| 2 | `btc` | Bitcoin | UTXO | secp256k1 | Yes | No |
| 3 | `tbtc` | Bitcoin Testnet | UTXO | secp256k1 | Yes | No |
| 4 | `sol` | Solana | SIMPLE | ed25519 | No | Yes |
| 5 | `ada` | Cardano | UTXO | ed25519 | Yes | No |
| 6 | `dot` | Polkadot / Substrate | VARIANT | ed25519 | No | No |
| 7 | `cosmos` | Cosmos Hub, Osmosis, Juno, Akash, Fetch, Celestia, Secret Network, Crypto.org | VARIANT | secp256k1 | No | No |
| 8 | `near` | NEAR Protocol | VARIANT | ed25519 | No | No |
| 9 | `algo` | Algorand | SIMPLE | ed25519 | No | No |
| 10 | `aptos` | Aptos | SIMPLE | ed25519 | No | No |
| 11 | `sui` | Sui | SIMPLE | ed25519 | No | No |
| 12 | `tron` | TRON | SIMPLE | secp256k1 | No | No |
| 13 | `xrp` | XRP Ledger | SIMPLE | secp256k1 | No | No |
| 14 | `doge` | Dogecoin | UTXO | secp256k1 | Yes | No |
| 15 | `ltc` | Litecoin | UTXO | secp256k1 | Yes | No |
| 16 | `bch` | Bitcoin Cash | UTXO | secp256k1 | Yes | No |
| 17 | `neurai` | Neurai | UTXO | secp256k1 | Yes | No |
| 18 | `fil` | Filecoin | SIMPLE | secp256k1 | No | No |
| 19 | `cfx` | Conflux | SIMPLE | secp256k1 | No | No |
| 20 | `kaspa` | Kaspa | SIMPLE | secp256k1 | No | No |
| 21 | `nexa` | Nexa | UTXO | secp256k1 | Yes | No |
| 22 | `lightning` | Lightning Network | SIMPLE | secp256k1 | No | No |
| 23 | `tlightning` | Lightning Testnet | SIMPLE | secp256k1 | No | No |
| 24 | `nostr` | Nostr | SIMPLE | secp256k1 | No | No |
| 25 | `dynex` | Dynex | SIMPLE | ed25519 | No | No |
| 26 | `nervos` | Nervos CKB | SIMPLE | secp256k1 | No | No |
| 27 | `xmr` | Monero | SIMPLE | ed25519 | No | No |
EVM networks include: Ethereum, Avalanche C-Chain, BSC, Polygon, Arbitrum, Optimism, Fantom, Mantle, Manta Pacific, Blast, and many more via the preset networks configuration.
### Key Management and Encryption
**At-rest encryption**: All private keys and seed material are encrypted with AES-256-CBC before storage.
```
Encryption: AES-256-CBC
KDF: PBKDF2-HMAC-SHA256 (5000 iterations, 32-byte salt)
Key length: 256-bit (32 bytes)
IV: 128-bit (16 bytes, random per encrypt)
Storage: salt(32) || iv(16) || ciphertext
```
**Password encoding**: Passwords are never passed as raw strings in non-production builds. A `SENSITIVE_ENCODE` prefix mechanism encrypts passwords with a per-session random key (UUID-based) so they cannot be read from debugger breakpoints.
**Credential types:**
- `|RP|` prefix: HD credential (recovery phrase -- encrypted `{entropyWithLangPrefixed, seed}` JSON)
- `|PK|` prefix: Imported credential (encrypted `{privateKey}` JSON)
- `|VS|` prefix: Verify string (encrypted known plaintext for password verification)
**Additional encryptors:**
- RSA (1024-bit, PKCS8) for inter-process secure key exchange
- BIP-340 Schnorr (Taproot tagged hashes: TapLeaf, TapBranch, TapSighash, TapTweak)
### Keyring Architecture
Each chain vault has 6 keyring types:
| Keyring | Class | Purpose |
|---------|-------|---------|
| `KeyringHd` | `KeyringHdBase` | HD wallet (mnemonic-derived) |
| `KeyringImported` | `KeyringImportedBase` | Imported private key |
| `KeyringHardware` | `KeyringHardwareBase` | Hardware wallet (OneKey, Ledger, Trezor) |
| `KeyringWatching` | `KeyringWatchingBase` | Watch-only (address or xpub) |
| `KeyringQr` | `KeyringQrBase` | Air-gapped QR signing (Keystone) |
| `KeyringExternal` | `KeyringExternalBase` | External wallet (WalletConnect, injected) |
All keyrings implement:
- `prepareAccounts()` -- derive or import accounts
- `signTransaction()` -- sign and return `ISignedTxPro`
- `signMessage()` -- sign arbitrary messages
- `getPrivateKeys()` / `exportAccountSecretKeys()` (HD/imported only)
### Hardware Wallet Integration
Hardware support via `@onekeyfe/hd-core` v1.0.3 SDK:
| Device | Transport | SDK Package |
|--------|-----------|-------------|
| OneKey Classic/Touch/Mini/Pro | BLE, USB | `@onekeyfe/hd-ble-sdk`, `@onekeyfe/hd-web-sdk` |
| Ledger | WebHID | `@ledgerhq/hw-app-eth` v6.34.9, `@ledgerhq/hw-transport-webhid` v6.27.20 |
| Trezor | WebExtension | `@trezor/connect-webextension` v9.2.2 |
| Keystone | QR (air-gapped) | `@keystonehq/keystone-sdk` v0.4.1 |
| BitBox | WebUSB | `bitbox-api` v0.3.2 |
| GridPlus Lattice | HTTP | `@luxfi/eth-lattice-keyring` v1.1.1 |
**Hardware signing flow** (EVM example):
1. `KeyringHardware.signTransaction()` gets SDK instance and account path
2. Encodes transaction as `EVMTransaction` or `EVMTransactionEIP1559`
3. Calls `sdk.evmSignTransaction(connectId, deviceId, {path, transaction})`
4. Receives `{v, r, s}` signature from device
5. `buildSignedTxFromSignatureEvm()` assembles and serializes the signed tx
6. Returns `{txid, rawTx, encodedTx}`
### Transaction Building
The wallet uses a typed transaction system:
```typescript
IUnsignedTxPro = {
encodedTx: IEncodedTx; // Chain-specific encoded transaction
feeInfo?: IFeeInfoUnit; // Gas/fee estimation
swapInfo?: ISwapTxInfo; // DEX swap metadata
stakingInfo?: IStakingInfo; // Staking operation metadata
transfersInfo?: ITransferInfo[];
}
ISignedTxPro = {
txid: string;
rawTx: string;
encodedTx: IEncodedTx | null;
signature?: string;
publicKey?: string;
}
```
Each chain's `CoreChainSoftware` handles:
1. `packUnsignedTxForSign()` -- serialize tx to signing digest
2. `signer.sign(digest)` -- ECDSA/EdDSA signature with recovery
3. `buildSignedTx()` -- attach signature, compute txid
### DApp Connection
The wallet supports DApp interaction via:
- **Injected provider**: `@onekeyfe/cross-inpage-provider-*` packages inject `window.ethereum` (EVM), `window.solana`, etc.
- **WalletConnect v2**: `@walletconnect/universal-provider` v2.11.2, `@walletconnect/web3wallet` v1.10.2
- **Coinbase Wallet SDK**: `@coinbase/wallet-sdk` v3.8.x
- **Gnosis Safe**: `@gnosis.pm/safe-core-sdk` v1.1.1, `@luxfi/eth-gnosis-keyring` v0.0.2
The `ServiceDApp` (946 lines) manages connection lifecycle, permission grants, and method routing.
### Database Layer
| Platform | Engine | DB Name |
|----------|--------|---------|
| Web / Extension | IndexedDB | `OneKeyV5` |
| iOS / Android | Realm | `OneKeyV5` |
**Account types stored:**
- `SIMPLE` -- single address (EVM, SOL, etc.)
- `UTXO` -- multi-address (BTC, DOGE, LTC, BCH)
- `VARIANT` -- address varies by network (Cosmos, NEAR)
**Store names include:** Wallet, Account, Device, Credential, SignedMessage, SignedTransaction, ConnectedSite, and more.
## Lux-Specific Packages
The browser extension (`apps/ext`) uses `@luxfi/*` packages for Lux Network integration:
| Package | Version | Purpose |
|---------|---------|---------|
| `@luxfi/common` | ^0.3.61 | Shared Lux utilities |
| `@luxfi/lux-api` | 0.7.23 | Lux Network RPC client |
| `@luxfi/lux-security-engine` | 2.0.4 | Transaction security analysis |
| `@luxfi/lux-swap` | 0.0.39 | DEX aggregation |
| `@luxfi/eth-hd-keyring` | 4.3.2 | HD keyring for EVM |
| `@luxfi/eth-simple-keyring` | 5.0.1 | Simple key import |
| `@luxfi/eth-trezor-keyring` | 2.5.2 | Trezor hardware signing |
| `@luxfi/eth-lattice-keyring` | 1.1.1 | GridPlus Lattice signing |
| `@luxfi/eth-walletconnect-keyring` | 2.1.3 | WalletConnect keyring |
| `@luxfi/eth-coinbase-keyring` | 0.0.1 | Coinbase wallet keyring |
| `@luxfi/eth-gnosis-keyring` | 0.0.2 | Gnosis Safe multisig |
| `@luxfi/eth-watch-keyring` | 1.0.0 | Watch-only addresses |
| `@luxfi/gnosis-sdk` | 1.3.6 | Gnosis Safe SDK |
| `@luxfi/festats` | 1.0.1 | Frontend analytics |
| `@luxfi/page-provider` | 0.3.5 | DApp page injection |
| `@luxfi/widgets` | 1.0.9 | Embeddable UI widgets |
| `blake2b-lux` | github:luxfi/blake2b-lux | Blake2b hash (resolution) |
## Platforms
| Platform | Technology | Status |
|----------|-----------|--------|
| **iOS** | React Native 0.73.7 | Production |
| **Android** | React Native 0.73.7 | Production |
| **Desktop** | Electron 27 | Production |
| **Chrome/Firefox/Edge/Brave** | Extension | Production |
| **Web** | React 18, Expo 50 | Production |
| Platform | App Package | Technology | Key Deps |
|----------|------------|-----------|----------|
| **Chrome/Firefox/Safari** | `@luxwallet/x` v0.92.79 | Webpack 5, MV2/MV3, Tailwind | antd 4.x, styled-components |
| **Desktop** | `@onekeyhq/desktop` | Electron 27, webpack | electron-root-path, keytar |
| **iOS** | `@onekeyhq/mobile` | React Native 0.73.7, Expo 50 | expo-camera, react-native-ble |
| **Android** | `@onekeyhq/mobile` | React Native 0.73.7, Expo 50 | expo-camera, react-native-ble |
| **Web** | `@onekeyhq/web` | webpack-dev-server, port 3000 | -- |
| **Web Embed** | `@onekeyhq/web-embed` | webpack, port 3008 | Cardano WASM agent |
## Chain Support
## Background Services (40+)
Lux native chains plus multi-chain:
- **Lux**: P-Chain, X-Chain, C-Chain, Q-Chain, M-Chain
- **EVM**: Ethereum and all EVM-compatible chains
- **Polkadot**: Substrate-based chains
- **Sui/Aptos**: Move-based chains
- **Cardano**: Via `@emurgo` libraries
- **Bitcoin**: Via `btcsuite`
Key services in `packages/kit-bg/src/services/`:
## Hardware Wallet Support
| Service | Purpose |
|---------|---------|
| `ServiceAccount` | Account creation, derivation, management |
| `ServicePassword` | Password encoding, biometric auth |
| `ServiceSend` | Transaction construction and broadcasting |
| `ServiceSwap` | DEX swap routing and execution |
| `ServiceStaking` | Staking delegation and rewards |
| `ServiceDApp` | DApp connection and method dispatch |
| `ServiceHardware` | Hardware device management, firmware updates |
| `ServiceNetwork` | Network configuration and switching |
| `ServiceToken` | Token discovery, balances, prices |
| `ServiceNFT` | NFT indexing and display |
| `ServiceHistory` | Transaction history (local + on-chain) |
| `ServiceDiscovery` | DApp browser and discovery |
| `ServiceCloudBackup` | iCloud/Google Drive backup |
| `ServiceLightning` | Lightning Network invoice management |
| `ServiceNostr` | Nostr key and event signing |
| `ServiceWalletConnect` | WalletConnect v2 session management |
| `ServiceFirmwareUpdate` | Hardware wallet firmware OTA |
| `ServiceQrWallet` | Air-gapped QR wallet protocol |
| `ServiceValidator` | Address and transaction validation |
Hardware wallet integration via `@onekeyfe/hd-*` SDK packages:
- OneKey Classic/Touch/Mini/Pro
- Ledger (via `github.com/luxfi/ledger-go`)
## UI Views
## Key Dependencies
Primary views in `packages/kit/src/views/`:
```
react@18, [email protected]
expo@50
[email protected] — Cross-platform UI
[email protected] — WalletConnect protocol
viem, wagmi — EVM client libraries
`Home` | `Send` | `Receive` | `Swap` | `Staking` | `Market` | `Discovery` (DApp browser) | `AssetList` | `AssetDetails` | `AccountManagerStacks` | `Setting` | `Onboarding` | `FirmwareUpdate` | `LightningNetwork` | `ScanQrCode` | `AddressBook` | `FiatCrypto` | `CloudBackup` | `KeyTag` | `LiteCard` | `UniversalSearch`
## Development
```bash
# Install (requires Node >= 20, git-lfs)
yarn
# Development
yarn app:web # Web on port 3000
yarn app:ext # Browser extension (MV3 dev build)
yarn app:desktop # Electron desktop
yarn app:ios # iOS via USB
yarn app:android # Android
# Building
yarn app:ext:build # Production extension
yarn app:web:build # Production web
# Testing
yarn test # Jest test suite
# Linting
yarn lint # TSC + ESLint + folder lint + i18n check
# Clean
yarn clean # Full workspace clean
yarn reinstall # Clean + install
```
## Related Repos
## Security Model
| Component | Repo | Purpose |
|-----------|------|---------|
| BIP32 HD keys | `github.com/luxfi/go-bip32` | HD key derivation (Go) |
| BIP39 mnemonics | `github.com/luxfi/go-bip39` | Mnemonic phrases (Go) |
| Ledger integration | `github.com/luxfi/ledger-go` | Hardware wallet (Go) |
1. **Mnemonic never stored in plaintext** -- encrypted as `IBip39RevealableSeed` with AES-256-CBC
2. **Private keys encrypted at rest** -- PBKDF2 KDF with 5000 iterations
3. **Password verification** -- encrypted known string (`DEFAULT_VERIFY_STRING`) used to check password correctness without storing the password
4. **Session encoding** -- passwords encoded with per-session random key to prevent debugger interception
5. **Extension isolation** -- `decodePassword()` throws if called from extension UI process (must use background)
6. **Hardware signing** -- private keys never leave the hardware device
7. **QR air-gap** -- Keystone SDK for fully offline signing via animated QR codes
## Go SDK Wallet
## Patches
```go
import (
"github.com/luxfi/go-bip39"
"github.com/luxfi/wallet"
)
// Generate mnemonic
mnemonic, _ := bip39.NewMnemonic(256) // 24 words
// Create wallet
w, _ := wallet.FromMnemonic(mnemonic)
// Get addresses for each chain
xAddr := w.X().Address() // X-lux1...
pAddr := w.P().Address() // P-lux1...
cAddr := w.C().Address() // 0x...
```
15 patch-package patches maintained in `/patches/`:
- `@kaspa/core-lib`, `coinselect` (UTXO selection fix)
- `@tamagui/animate`, `@tamagui/switch` (UI fixes)
- `@walletconnect/modal-react-native` (RN compat)
- `react-native-*` (various RN fixes)
- `expo-camera`, `metro` (build fixes)
- `protobufjs` (serialization fix)
## Related Skills
- `lux/lux-crypto.md` — Cryptographic primitives
- `lux/lux-safe.md` — Multisig wallets (Safe fork)
- `lux/lux-sdk.md` — Go SDK wallet utilities
- `lux/lux-crypto.md` -- Cryptographic primitives and curves
- `lux/lux-safe.md` -- Multisig wallets (Gnosis Safe fork)
- `lux/lux-sdk.md` -- Go SDK wallet utilities
- `lux/lux-ledger.md` -- Ledger hardware integration
+4 -2
View File
@@ -1,6 +1,6 @@
{
"title": "Lux Skills Reference",
"description": "Comprehensive reference for all 72+ Lux skills",
"description": "Comprehensive reference for all 75 Lux skills",
"icon": "BookOpen",
"pages": [
"index",
@@ -14,6 +14,7 @@
"lux-spacesvm",
"lux-session",
"lux-p2p",
"lux-chains",
"lux-genesis",
"lux-staking",
"---Cryptography & Security---",
@@ -91,6 +92,7 @@
"lux-upgrade",
"---Research---",
"lux-faucet",
"lux-papers"
"lux-papers",
"lux-lps"
]
}