lighter-sdk
v0.0.17
Published
A TypeScript SDK for Lighter
Maintainers
Readme
Lighter SDK
A TypeScript SDK for interacting with the Lighter protocol. This SDK provides a convenient way to sign transactions and interact with Lighter's decentralized exchange.
Features
- Transaction signing for various Lighter operations
- Combined signing + API client for seamless transaction submission
- Dual package format (CommonJS and ESM)
- WebAssembly or native C library backends
- Full TypeScript support with comprehensive type definitions
Installation
npm install lighter-sdk
# or
pnpm add lighter-sdk
# or
yarn add lighter-sdkQuick Start
Using LighterClient (Recommended)
LighterClient combines transaction signing with API calls - it automatically handles nonce fetching and transaction submission.
import { LighterClient } from "lighter-sdk";
const client = new LighterClient({
url: "https://mainnet.zklighter.elliot.ai",
privateKey: "your-private-key",
chainId: 300,
accountIndex: 123,
apiKeyIndex: 0,
});
await client.initialize();
// Create an order (automatically fetches nonce and submits)
const result = await client.createOrder({
marketIndex: 1,
clientOrderIndex: 1,
baseAmount: 1000,
price: 50000,
isAsk: 0, // 0 = buy, 1 = sell
type: 0,
timeInForce: 0,
reduceOnly: 0,
triggerPrice: 0,
});
console.log("TxHash:", result.txHash);
console.log("Response:", result.response.data);Using LighterSignerClient (Signing Only)
For cases where you only need to sign transactions without submitting them:
import { LighterSignerClient } from "lighter-sdk";
const signer = new LighterSignerClient({
url: "https://mainnet.zklighter.elliot.ai",
privateKey: "your-private-key",
chainId: 300,
apiKeyIndex: 0,
accountIndex: -1,
});
await signer.initialize();
// Sign a transaction (returns signed tx, does not submit)
const signed = await signer.signMintShares(
281474976688087, // publicPoolIndex
1000 // shareAmount
);
console.log("Signed TxInfo:", signed.txInfo);
console.log("TxHash:", signed.txHash);API Reference
LighterClient
The high-level client that combines signing with API calls.
Constructor
new LighterClient({
url: string; // Lighter API endpoint
privateKey: string; // Your private key
chainId: number; // 300 for mainnet, 304 for testnet
accountIndex: number; // Your account index
apiKeyIndex?: number; // API key index (default: 0)
loaderType?: "wasm" | "koffi"; // Backend type (default: "wasm")
libraryPath?: string; // Custom path to library file
})Methods
All methods automatically fetch nonce and submit transactions:
Trading Operations:
createOrder(params)- Create a new ordercancelOrder(marketIndex, orderIndex)- Cancel an ordercancelAllOrders(timeInForce, time)- Cancel all ordersmodifyOrder(params)- Modify an existing ordercreateGroupedOrders(groupingType, orders)- Create batch orders
Account Operations:
getAccount(by?, value?)- Get account informationgetPoolInfo()- Get pool info for all pools with sharestransfer(params)- Transfer funds to another accountwithdraw(usdcAmount, assetIndex?, routeType?)- Withdraw to L1createSubAccount()- Create a sub-accountchangePubKey(pubKeyHex)- Change public keyupdateLeverage(marketIndex, fraction, marginMode)- Update leverageupdateMargin(marketIndex, usdcAmount, direction)- Update margin
Pool Operations:
mintShares(publicPoolIndex, shareAmount)- Deposit into public poolburnShares(publicPoolIndex, shareAmount)- Withdraw from public poolcreatePublicPool(params)- Create a public poolupdatePublicPool(params)- Update a public pool
Response Format
All transaction methods return TxResult<ApiResponse<SendTxData>>:
{
txInfo: string; // Signed transaction info
txHash: string; // Transaction hash
response: { // API response
data: {
code: number;
tx_hash: string;
predicted_execution_time_ms: number;
volume_quota_remaining: number;
};
status: number;
headers: Headers;
};
}LighterSignerClient
Low-level client for signing transactions without submission.
Constructor
new LighterSignerClient({
url: string;
privateKey: string;
chainId: number;
apiKeyIndex?: number; // default: 255
accountIndex?: number; // default: -1
loaderType?: "wasm" | "koffi";
libraryPath?: string;
})Methods
All signing methods return SignedTxResponse:
{
txType?: number;
txInfo?: string;
txHash?: string;
messageToSign?: string;
error?: string;
}Trading:
signCreateOrder(params)- Sign create ordersignCancelOrder(marketIndex, orderIndex, nonce?)- Sign cancel ordersignCancelAllOrders(timeInForce, time, nonce?)- Sign cancel allsignModifyOrder(params)- Sign modify ordersignCreateGroupedOrders(groupingType, orders, nonce?)- Sign batch orders
Account:
signChangePubKey(pubKeyHex, nonce?)- Sign public key changesignCreateSubAccount(nonce?)- Sign sub-account creationsignTransfer(params)- Sign transfersignWithdraw(usdcAmount, assetIndex?, routeType?, nonce?)- Sign withdrawalsignUpdateLeverage(marketIndex, fraction, marginMode, nonce?)- Sign leverage updatesignUpdateMargin(marketIndex, usdcAmount, direction, nonce?)- Sign margin update
Pool:
signCreatePublicPool(params)- Sign pool creationsignUpdatePublicPool(params)- Sign pool updatesignMintShares(publicPoolIndex, shareAmount, nonce?)- Sign mint sharessignBurnShares(publicPoolIndex, shareAmount, nonce?)- Sign burn shares
Utility:
checkClient()- Verify client configurationcreateAuthToken(deadline?)- Create auth token
Static Methods
// Generate API key from seed
const { privateKey, publicKey } = await LighterSignerClient.generateAPIKey(seed);TypeScript Types
The SDK exports comprehensive TypeScript types:
import type {
// Enums
OrderType, // "limit" | "market" | "stop-loss" | ...
OrderStatus, // "open" | "filled" | "canceled" | ...
TimeInForce, // "good-till-time" | "immediate-or-cancel" | ...
MarketType, // "perp" | "spot"
// Data types
Order,
Trade,
OrderBook,
OrderBookDetail,
AccountPosition,
DetailedAccount,
// Response types
OrdersData,
TradesData,
SendTxData,
DetailedAccountsData,
} from "lighter-sdk";Backend Options
The SDK supports two cryptographic backends:
WebAssembly (Default)
Works in Node.js and browsers. Uses wasm/lighter-signer.wasm.
const client = new LighterClient({
// ... config
loaderType: "wasm",
});Native C Library (koffi)
Higher performance, Node.js only. Uses native library in lib/.
const client = new LighterClient({
// ... config
loaderType: "koffi",
libraryPath: "./lib/liblighter.so", // optional custom path
});Development
Prerequisites
- Node.js 20+
- pnpm 10+
Setup
pnpm install
pnpm run build
pnpm run dev # Watch mode
pnpm run clean # Clean artifactsTesting
- Create
.envfile:
API_BASE_URL=https://mainnet.zklighter.elliot.ai
PRIVATE_KEY=your_private_key
CHAIN_ID=304
API_KEY_INDEX=0
ACCOUNT_INDEX=-1- Run tests:
pnpm test # All tests
pnpm test test/e2e/specific.test.ts # Specific testBuild Output
- CommonJS:
dist/cjs/index.cjs - ESM:
dist/esm/index.mjs - Types:
dist/types/
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
