Lux Docs
Lux Skills Reference

Lux EVM Precompiled Contracts

Custom Stateful Precompiles

Overview

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.

Modules

ModuleGoKey Dependencies
github.com/luxfi/evm (precompile/)1.26.1luxfi/geth@v1.16.75, luxfi/crypto@v1.17.40, luxfi/warp@v1.18.5, luxfi/vm@v1.0.38
github.com/luxfi/precompile1.26.1luxfi/geth@v1.16.73, luxfi/fhe@v1.7.6, luxfi/lattice/v7, luxfi/threshold@v1.5.0, luxfi/ringtail@v0.2.0, cloudflare/circl@v1.6.3, consensys/gnark-crypto@v0.19.2

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)

PRangeFamily
0CoreChain config precompiles (deployer, tx, minter, reward)
1LP-1xxxFee management
2LP-2xxxPQ Identity (post-quantum signatures, KEM, hybrid)
3LP-3xxxEVM/Crypto (hashing, classical signatures, encryption)
4LP-4xxxPrivacy/ZK (SNARKs, STARKs, commitments, FHE)
5LP-5xxxThreshold/MPC (FROST, CGGMP21, DKG, secret sharing)
6LP-6xxxBridges (Warp messaging, token bridges, fee collection)
7LP-7xxxAI (GPU attestation, inference, mining sessions)
9LP-9xxxDEX/Markets (AMM, orderbook, lending, liquidation)

Chain Slots (C nibble)

CChainCChain
0P-Chain6Z-Chain
1X-Chain7M-Chain (reserved)
2C-Chain (main EVM)8Zoo
3Q-Chain (quantum)9Hanzo
4A-Chain (AI)ASPC
5B-Chain (bridge)

Helper functions: PrecompileAddress(p, c, ii), ChainSlot(name), FamilyPage(name).

Contract Framework

StatefulPrecompiledContract

The core execution interface. Each precompile implements Run:

// 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:

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:

// 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

const (
    WriteGasCostPerSlot = 20_000
    ReadGasCostPerSlot  = 5_000
    LogGas              = 375
    LogTopicGas         = 375
    LogDataGas          = 8
)

Config Interface

Every precompile has a config implementing precompileconfig.Config:

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:

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

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:

RoleValuePermissions
NoRole0No access
EnabledRole1Can call the precompile
AdminRole2Can modify the allowlist AND call
ManagerRole3Can 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

FieldValue
ConfigKeycontractDeployerAllowListConfig
Address0x10201
GasRead: 5,000 / Write: 20,000

Controls which addresses can deploy contracts. Configured in genesis or via network upgrade.

Transaction AllowList

FieldValue
ConfigKeytxAllowListConfig
Address0x10301
GasRead: 5,000 / Write: 20,000

Controls which addresses can submit transactions.

Native Minter

FieldValue
ConfigKeycontractNativeMinterConfig
Address0x10401
GasMint: 30,000

Allows permissioned addresses to mint native tokens. ABI method: mintNativeCoin(address, uint256). Supports InitialMint map in config for genesis minting.

Fee Manager

FieldValue
ConfigKeyfeeManagerConfig
Address0x13F01
GasSet: ~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

FieldValue
ConfigKeyrewardManagerConfig
Address0x10205
GasRead: 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

FieldValue
ConfigKeywarpConfig
Address0x16201
GasSend: ~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():

// registry/registry.go
    _ "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/ringtail"  // 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)

NameGasDescription
ML-DSA50,000NIST ML-DSA post-quantum signatures (FIPS 204)
ML-KEM25,000NIST ML-KEM key encapsulation (FIPS 203)
SLH-DSA75,000NIST SLH-DSA hash-based signatures (FIPS 205)
HYBRID_SIGN75,000ECDSA+ML-DSA hybrid signatures

EVM/Crypto (P=3, LP-3xxx)

NameGasDescription
BLAKE35,000High-performance hash
ED25519_VERIFY3,000Ed25519 (Solana/TON compat)
ECIES25,000Elliptic Curve Integrated Encryption

Privacy/ZK (P=4, LP-4xxx)

NameGasDescription
GROTH16150,000Groth16 proof verification
PLONK175,000PLONK proof verification
STARK200,000STARK proof verification
KZG50,000KZG polynomial commitments (EIP-4844 extension)
FHE500,000Fully Homomorphic Encryption (TFHE, CKKS, BGV)

Threshold/MPC (P=5, LP-5xxx)

NameGasDescription
FROST25,000Schnorr threshold signatures
CGGMP2150,000ECDSA threshold signatures
RINGTAIL75,000Threshold lattice signatures (post-quantum)

Bridges (P=6, LP-6xxx)

NameGasDescription
WARP_SEND50,000Cross-chain message send
WARP_RECEIVE50,000Cross-chain message receive
TELEPORT100,000Instant token teleport (LP-6010)

AI (P=7, LP-7xxx)

NameGasDescription
GPU_ATTEST100,000GPU compute attestation
TEE_VERIFY75,000TEE attestation verification
INFERENCE150,000AI inference verification
SESSION50,000AI mining session management

DEX/Markets (LP-9xxx -- QuantumSwap Native DEX)

Address SuffixNameGasDescription
0x...9010LX_POOL50,000Uniswap v4-style singleton AMM (PoolManager)
0x...9011LX_ORACLE15,000Multi-source price oracle aggregation
0x...9012LX_ROUTER10,000Optimized swap routing
0x...9013LX_HOOKS10,000Hook contract registry
0x...9014LX_FLASH50,000Flash loan facility
0x...9020LX_BOOK25,000Central limit order book + matching engine
0x...9030LX_VAULT50,000Custody, margin, and position management
0x...9040LX_FEED10,000Computed price feeds (mark/index)
0x...9050LX_LEND25,000Lending pool (Aave-style)
0x...9060LX_LIQUID30,000Self-repaying loans (Alchemix-style)
0x...9070LIQUIDATOR50,000Position liquidation engine
0x...9080LIQUID_FX25,000Transmuter (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

ChainFocusPrecompile Families
C-ChainMain EVMAll families
Q-ChainQuantumPQ Identity, Threshold
A-ChainAIAI, Bridges
B-ChainBridgeBridges, Fee Collection
Z-ChainPrivacyCrypto, Privacy/ZK, FHE
ZooDeFiDEX, Bridges
HanzoAI computeAI (GPU, Inference, Session), Bridges

On this page