Lux Docs
Reference

JavaScript SDK

Complete reference for the @luxfi/sdk JavaScript/TypeScript SDK

JavaScript SDK Reference

The @luxfi/sdk package provides a complete TypeScript/JavaScript client for interacting with Lux Network. It supports all three chains (P-Chain, X-Chain, C-Chain), wallet management, and transaction building.

Installation

npm install @luxfi/sdk

For C-Chain (EVM) interactions, you will also want ethers.js:

npm install ethers

Initialization

import { Lux } from "@luxfi/sdk";

// Mainnet
const lux = new Lux("api.lux.network", 443, "https");

// Testnet
const luxTestnet = new Lux("api.testnet.lux.network", 443, "https");

// Local node
const luxLocal = new Lux("localhost", 9650, "http");

Chain Accessors

const xchain = lux.XChain();  // X-Chain (asset transfers)
const pchain = lux.PChain();  // P-Chain (staking, validators)
const cchain = lux.CChain();  // C-Chain (EVM, contracts)

Key Classes

Lux

The main entry point. Manages network connection and provides chain-specific APIs.

const lux = new Lux(host: string, port: number, protocol: string);

lux.XChain()  // Returns XAPI
lux.PChain()  // Returns PlatformAPI
lux.CChain()  // Returns CAPI
lux.Info()    // Returns InfoAPI
lux.Health()  // Returns HealthAPI

KeyChain

Manages cryptographic keypairs for signing transactions.

const keychain = xchain.keyChain();

// Generate a new key
const keypair = keychain.makeKey();
console.log("Address:", keypair.getAddressString());
console.log("Public Key:", keypair.getPublicKeyString());

// Import an existing key
keychain.importKey("PrivateKey-...");

BN (Big Number)

Used for precise numerical operations with token amounts.

import BN from "bn.js";

const amount = new BN("1000000");  // 1 LUX in microLUX (X/P-Chain)
const wei = new BN("1000000000000000000");  // 1 LUX in Wei (C-Chain)

Wallet Operations

Create a Wallet

import { Lux, BinTools } from "@luxfi/sdk";

const lux = new Lux("api.lux.network", 443, "https");
const xchain = lux.XChain();
const keychain = xchain.keyChain();

// Generate a new keypair
const keypair = keychain.makeKey();
const address = keypair.getAddressString();

console.log("X-Chain Address:", address);
// Output: X-lux1abc123...

Import from Mnemonic

import { Mnemonic } from "@luxfi/sdk";

const mnemonic = Mnemonic.getInstance();
const phrase = mnemonic.generateMnemonic();
console.log("Mnemonic:", phrase);

// Derive key from mnemonic
const seed = mnemonic.mnemonicToSeedSync(phrase);

Import from Private Key

const keychain = xchain.keyChain();
keychain.importKey("PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN");

const addresses = keychain.getAddressStrings();
console.log("Addresses:", addresses);

X-Chain Operations

Get Balance

const balance = await xchain.getBalance(address, "LUX");
console.log("Balance:", balance.balance);
console.log("UTXOs:", balance.utxoIDs.length);

Send LUX

const xchain = lux.XChain();
const keychain = xchain.keyChain();
keychain.importKey(privateKey);

const amount = new BN(1000000); // 1 LUX
const memo = Buffer.from("Payment for services");

const txID = await xchain.send(
  "myuser",              // username
  "mypassword",          // password
  "LUX",                 // asset ID
  amount,                // amount in microLUX
  "X-lux1recipient...",  // destination
  ["X-lux1sender..."],   // from addresses
  "X-lux1change...",     // change address
  memo
);

console.log("Transaction ID:", txID);

Build Unsigned Transaction

For more control, build transactions manually:

const utxos = await xchain.getUTXOs(keychain.getAddressStrings());
const xchainUTXOSet = utxos.utxos;

const unsignedTx = await xchain.buildBaseTx(
  xchainUTXOSet,
  new BN(1000000),
  "LUX",
  ["X-lux1recipient..."],
  keychain.getAddressStrings(),
  keychain.getAddressStrings()
);

const signedTx = unsignedTx.sign(keychain);
const txID = await xchain.issueTx(signedTx);
console.log("TX ID:", txID);

P-Chain Operations

Get Current Validators

const pchain = lux.PChain();

const validators = await pchain.getCurrentValidators();
console.log("Validator count:", validators.validators.length);

for (const v of validators.validators) {
  console.log(`NodeID: ${v.nodeID}, Stake: ${v.stakeAmount}`);
}

Get Staking Info

const balance = await pchain.getBalance("P-lux1...");
console.log("Balance:", balance.balance);
console.log("Locked (stakeable):", balance.lockedStakeable);

Check Bootstrap Status

const info = lux.Info();
const isBootstrapped = await info.isBootstrapped("P");
console.log("P-Chain bootstrapped:", isBootstrapped);

C-Chain Operations

For C-Chain interactions, use ethers.js with the Lux RPC endpoint.

Connect to C-Chain

import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider(
  "https://api.lux.network/ext/bc/C/rpc"
);

const blockNumber = await provider.getBlockNumber();
console.log("Current block:", blockNumber);

Read Contract

const erc20ABI = [
  "function balanceOf(address) view returns (uint256)",
  "function symbol() view returns (string)",
  "function decimals() view returns (uint8)",
];

const contract = new ethers.Contract("0xTokenAddress", erc20ABI, provider);
const symbol = await contract.symbol();
const balance = await contract.balanceOf("0xYourAddress");
console.log(`${symbol} balance:`, ethers.formatUnits(balance, 18));

Send Transaction

const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

const tx = await wallet.sendTransaction({
  to: "0xRecipientAddress",
  value: ethers.parseEther("1.0"),
});

console.log("TX Hash:", tx.hash);
const receipt = await tx.wait();
console.log("Confirmed in block:", receipt.blockNumber);

Deploy Contract

import { ethers } from "ethers";

const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

const factory = new ethers.ContractFactory(abi, bytecode, wallet);
const contract = await factory.deploy(/* constructor args */);
await contract.waitForDeployment();

console.log("Deployed to:", await contract.getAddress());

Event Subscriptions

WebSocket Subscriptions

const wsProvider = new ethers.WebSocketProvider(
  "wss://api.lux.network/ext/bc/C/ws"
);

// Subscribe to new blocks
wsProvider.on("block", (blockNumber) => {
  console.log("New block:", blockNumber);
});

// Subscribe to contract events
const contract = new ethers.Contract("0xAddress", abi, wsProvider);
contract.on("Transfer", (from, to, value) => {
  console.log(`Transfer: ${from} -> ${to}: ${ethers.formatEther(value)} LUX`);
});

Error Handling

try {
  const tx = await xchain.send(/* ... */);
} catch (error) {
  if (error.message.includes("insufficient funds")) {
    console.error("Not enough LUX to complete the transaction");
  } else if (error.message.includes("ECONNREFUSED")) {
    console.error("Cannot connect to node - is it running?");
  } else {
    console.error("Transaction failed:", error.message);
  }
}

TypeScript Types

The SDK ships with full TypeScript type definitions:

import type {
  UTXO,
  UTXOSet,
  KeyPair,
  KeyChain,
  BaseTx,
  TransferableOutput,
  TransferableInput,
} from "@luxfi/sdk";

Further Reading

On this page