@andy-liquid-labs/lighter-ts-sdk
v1.0.5
Published
TypeScript SDK for Lighter - signing & hashing of Lighter transactions
Maintainers
Readme
lighter-ts-sdk
TypeScript SDK for Lighter - signing & hashing of Lighter transactions, plus HTTP and WebSocket clients.
This is the TypeScript equivalent of the lighter-go SDK.
Installation
npm install lighter-ts-sdkQuick Start
import {
createClient,
generateApiKey,
newHttpClient,
InfoClient,
ExchangeClient,
OrderType,
TimeInForce,
} from 'lighter-ts-sdk';
// Generate a new API key pair (optionally with a seed for deterministic generation)
const [privateKey, publicKey] = generateApiKey();
// Or with a seed:
// const [privateKey, publicKey] = generateApiKey('my-seed-string');
console.log('Private Key:', privateKey);
console.log('Public Key:', publicKey);
// Create an HTTP client (for automatic nonce fetching)
const httpClient = newHttpClient('https://mainnet.zklighter.elliot.ai');
// Create a TxClient for signing
const txClient = createClient(
httpClient,
privateKey,
1, // chainId
0, // apiKeyIndex
1n // accountIndex
);
// Use ExchangeClient to create and send orders
const exchangeClient = new ExchangeClient({
baseURL: 'https://mainnet.zklighter.elliot.ai',
txClient,
});
// Create and send an order
const result = await exchangeClient.createOrder({
marketIndex: 0,
clientOrderIndex: 1n,
baseAmount: 1000000n,
price: 50000,
isAsk: 0,
orderType: OrderType.Limit,
timeInForce: TimeInForce.GoodTillTime,
reduceOnly: 0,
triggerPrice: 0,
orderExpiry: BigInt(Date.now() + 3600000), // 1 hour
});
console.log('Transaction hash:', result.tx_hash);Clients
The SDK provides several client classes for different purposes:
InfoClient - Public API
Access public market data without authentication:
import { InfoClient } from 'lighter-ts-sdk';
const infoClient = new InfoClient({
baseURL: 'https://mainnet.zklighter.elliot.ai',
});
// Get order books
const orderBooks = await infoClient.getOrderBooks();
// Get account info
const account = await infoClient.getAccount({ l1_address: '0x...' });
// Get candles
const candles = await infoClient.getCandles({
market_id: 0,
resolution: '1h',
start_time: Date.now() - 86400000,
end_time: Date.now(),
});
// Get recent trades
const trades = await infoClient.getRecentTrades({ market_id: 0 });
// Get funding rates
const fundingRates = await infoClient.getFundingRates({ market_id: 0 });InfoPrivateClient - Authenticated API
Access private account data with authentication:
import { InfoPrivateClient, createClient, newHttpClient } from 'lighter-ts-sdk';
const httpClient = newHttpClient('https://mainnet.zklighter.elliot.ai');
const txClient = createClient(httpClient, privateKey, 1, 0, 1n);
const privateClient = new InfoPrivateClient({
baseURL: 'https://mainnet.zklighter.elliot.ai',
txClient,
});
// Get active orders
const orders = await privateClient.getAccountActiveOrders({ account_index: 1 });
// Get trade history
const trades = await privateClient.getTrades({
account_index: 1,
start_time: Date.now() - 86400000,
});
// Get PnL
const pnl = await privateClient.getPnl({ account_index: 1 });
// Get deposit history
const deposits = await privateClient.getDepositHistory({ account_index: 1 });ExchangeClient - Transactions
Sign and send transactions:
import { ExchangeClient, createClient, newHttpClient } from 'lighter-ts-sdk';
const httpClient = newHttpClient('https://mainnet.zklighter.elliot.ai');
const txClient = createClient(httpClient, privateKey, 1, 0, 1n);
const exchangeClient = new ExchangeClient({
baseURL: 'https://mainnet.zklighter.elliot.ai',
txClient,
});
// Create order
const orderResult = await exchangeClient.createOrder({
marketIndex: 0,
clientOrderIndex: 1n,
baseAmount: 1000000n,
price: 50000,
isAsk: 0,
orderType: 1, // Limit
timeInForce: 1, // GoodTillTime
reduceOnly: 0,
triggerPrice: 0,
orderExpiry: BigInt(Date.now() + 3600000),
});
// Cancel order
const cancelResult = await exchangeClient.cancelOrder({
marketIndex: 0,
orderIndex: 123n,
});
// Cancel all orders
const cancelAllResult = await exchangeClient.cancelAllOrders({
timeInForce: 1,
time: BigInt(Date.now()),
});
// Withdraw
const withdrawResult = await exchangeClient.withdraw({
assetIndex: 0,
routeType: 0,
amount: 1000000n,
});
// Transfer
const transferResult = await exchangeClient.transfer({
toAccountIndex: 2n,
assetIndex: 0,
fromRouteType: 0,
toRouteType: 0,
amount: 1000000n,
usdcFee: 0n,
memo: 'test transfer',
});
// Update leverage
const leverageResult = await exchangeClient.updateLeverage({
marketIndex: 0,
initialMarginFraction: 100,
marginMode: 0,
});WsClient - WebSocket
Real-time data streams with handler callbacks. Subscription methods return an unsubscribe function for easy cleanup:
import { WsClient, createClient, newHttpClient } from 'lighter-ts-sdk';
const httpClient = newHttpClient('https://mainnet.zklighter.elliot.ai');
const txClient = createClient(httpClient, privateKey, 1, 0, 1n);
const wsClient = new WsClient({
url: 'wss://mainnet.zklighter.elliot.ai/stream',
onOpen: () => console.log('Connected'),
onClose: () => console.log('Disconnected'),
onError: (error) => console.error('Error:', error),
onMessage: (data) => console.log('Raw message:', data),
});
// Connect
await wsClient.connect();
// Public subscriptions with handler callbacks (returns unsubscribe function)
const unsubOrderBook = wsClient.subscribeOrderBook(0, (update) => {
console.log('Order book:', update.order_book);
});
const unsubMarketStats = wsClient.subscribeMarketStats('all', (update) => {
console.log('Market stats:', update.market_stats);
});
const unsubTrades = wsClient.subscribeTrades(0, (update) => {
console.log('New trades:', update.trades);
});
const unsubHeight = wsClient.subscribeHeight((update) => {
console.log('Block height:', update.height);
});
// Authenticated subscriptions (generate auth token manually)
const deadline = new Date(Date.now() + 7 * 60 * 60 * 1000); // 7 hours
const authToken = await txClient.getAuthToken(deadline);
const unsubAccountAll = wsClient.subscribeAccountAll(1, (update) => {
console.log('Account data:', update);
});
const unsubAccountMarket = wsClient.subscribeAccountMarket(0, 1, authToken, (update) => {
console.log('Account market:', update);
});
const unsubUserStats = wsClient.subscribeUserStats(1, (update) => {
console.log('User stats:', update.stats);
});
const unsubAccountOrders = wsClient.subscribeAccountAllOrders(1, authToken, (update) => {
console.log('All orders:', update.orders);
});
const unsubAccountAssets = wsClient.subscribeAccountAllAssets(1, authToken, (update) => {
console.log('All assets:', update.assets);
});
const unsubNotifications = wsClient.subscribeNotifications(1, authToken, (update) => {
console.log('Notifications:', update.notifs);
});
// Unsubscribe by calling the returned function
unsubOrderBook();
unsubMarketStats();
// Or disconnect entirely
wsClient.disconnect();Direct Signing (Low-Level)
For advanced use cases, you can sign transactions directly without sending:
import { createClient, newHttpClient } from 'lighter-ts-sdk';
const httpClient = newHttpClient('https://mainnet.zklighter.elliot.ai');
const txClient = createClient(httpClient, privateKey, 1, 0, 1n);
// Sign a create order transaction
const signedOrder = await txClient.signCreateOrder({
marketIndex: 0,
clientOrderIndex: 1n,
baseAmount: 1000000n,
price: 50000,
isAsk: 0,
type: 1,
timeInForce: 1,
reduceOnly: 0,
triggerPrice: 0,
orderExpiry: BigInt(Date.now() + 3600000),
});
console.log('Signed hash:', signedOrder.signedHash);
console.log('Signature:', signedOrder.signature);API Key Generation
import { generateApiKey } from 'lighter-ts-sdk';
// Generate random API key pair
const [privateKey, publicKey] = generateApiKey();
// Generate deterministic API key from seed
const [privKey, pubKey] = generateApiKey('my-seed-string');Auth Tokens
Auth tokens are used for authenticated HTTP & WebSocket endpoints:
// Create an auth token valid for 7 hours
const token = await txClient.getAuthToken(new Date(Date.now() + 7 * 60 * 60 * 1000));Transaction Options
Signing methods accept an optional TransactOpts object:
const tx = await txClient.signCreateOrder(orderReq, {
nonce: 42n, // If undefined, fetched from server
expiredAt: BigInt(Date.now() + 600000), // 10 minutes
apiKeyIndex: 0,
fromAccountIndex: 1n,
});Constants
import {
OrderType,
TimeInForce,
GroupingType,
AssetRouteType,
MarginMode,
MarginDirection,
TxType,
} from 'lighter-ts-sdk';
// Order types
OrderType.Market // 0
OrderType.Limit // 1
OrderType.StopLoss // 2
OrderType.TakeProfit // 3
// Time in force
TimeInForce.ImmediateOrCancel // 0
TimeInForce.GoodTillTime // 1
TimeInForce.PostOnly // 2Development
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Type check
npm run typecheckLicense
MIT
