lighter-ts-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +440 -0
  3. package/dist/api/account-api.d.ts +89 -0
  4. package/dist/api/account-api.d.ts.map +1 -0
  5. package/dist/api/account-api.js +61 -0
  6. package/dist/api/account-api.js.map +1 -0
  7. package/dist/api/api-client.d.ts +23 -0
  8. package/dist/api/api-client.d.ts.map +1 -0
  9. package/dist/api/api-client.js +129 -0
  10. package/dist/api/api-client.js.map +1 -0
  11. package/dist/api/block-api.d.ts +24 -0
  12. package/dist/api/block-api.d.ts.map +1 -0
  13. package/dist/api/block-api.js +22 -0
  14. package/dist/api/block-api.js.map +1 -0
  15. package/dist/api/candlestick-api.d.ts +27 -0
  16. package/dist/api/candlestick-api.d.ts.map +1 -0
  17. package/dist/api/candlestick-api.js +18 -0
  18. package/dist/api/candlestick-api.js.map +1 -0
  19. package/dist/api/order-api.d.ts +76 -0
  20. package/dist/api/order-api.d.ts.map +1 -0
  21. package/dist/api/order-api.js +102 -0
  22. package/dist/api/order-api.js.map +1 -0
  23. package/dist/api/root-api.d.ts +8 -0
  24. package/dist/api/root-api.d.ts.map +1 -0
  25. package/dist/api/root-api.js +14 -0
  26. package/dist/api/root-api.js.map +1 -0
  27. package/dist/api/transaction-api.d.ts +58 -0
  28. package/dist/api/transaction-api.d.ts.map +1 -0
  29. package/dist/api/transaction-api.js +141 -0
  30. package/dist/api/transaction-api.js.map +1 -0
  31. package/dist/api/ws-client.d.ts +21 -0
  32. package/dist/api/ws-client.d.ts.map +1 -0
  33. package/dist/api/ws-client.js +139 -0
  34. package/dist/api/ws-client.js.map +1 -0
  35. package/dist/index.d.ts +62 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +99 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/signer/signer-client.d.ts +79 -0
  40. package/dist/signer/signer-client.d.ts.map +1 -0
  41. package/dist/signer/signer-client.js +213 -0
  42. package/dist/signer/signer-client.js.map +1 -0
  43. package/dist/signer/wasm-signer-client.d.ts +129 -0
  44. package/dist/signer/wasm-signer-client.d.ts.map +1 -0
  45. package/dist/signer/wasm-signer-client.js +607 -0
  46. package/dist/signer/wasm-signer-client.js.map +1 -0
  47. package/dist/types/index.d.ts +130 -0
  48. package/dist/types/index.d.ts.map +1 -0
  49. package/dist/types/index.js +3 -0
  50. package/dist/types/index.js.map +1 -0
  51. package/dist/utils/api-key-utils.d.ts +7 -0
  52. package/dist/utils/api-key-utils.d.ts.map +1 -0
  53. package/dist/utils/api-key-utils.js +31 -0
  54. package/dist/utils/api-key-utils.js.map +1 -0
  55. package/dist/utils/configuration.d.ts +19 -0
  56. package/dist/utils/configuration.d.ts.map +1 -0
  57. package/dist/utils/configuration.js +55 -0
  58. package/dist/utils/configuration.js.map +1 -0
  59. package/dist/utils/exceptions.d.ts +33 -0
  60. package/dist/utils/exceptions.d.ts.map +1 -0
  61. package/dist/utils/exceptions.js +76 -0
  62. package/dist/utils/exceptions.js.map +1 -0
  63. package/dist/utils/node-wasm-signer.d.ts +126 -0
  64. package/dist/utils/node-wasm-signer.d.ts.map +1 -0
  65. package/dist/utils/node-wasm-signer.js +286 -0
  66. package/dist/utils/node-wasm-signer.js.map +1 -0
  67. package/dist/utils/signer-server.d.ts +18 -0
  68. package/dist/utils/signer-server.d.ts.map +1 -0
  69. package/dist/utils/signer-server.js +79 -0
  70. package/dist/utils/signer-server.js.map +1 -0
  71. package/dist/utils/signer.d.ts +15 -0
  72. package/dist/utils/signer.d.ts.map +1 -0
  73. package/dist/utils/signer.js +68 -0
  74. package/dist/utils/signer.js.map +1 -0
  75. package/dist/utils/wasm-signer.d.ts +130 -0
  76. package/dist/utils/wasm-signer.d.ts.map +1 -0
  77. package/dist/utils/wasm-signer.js +178 -0
  78. package/dist/utils/wasm-signer.js.map +1 -0
  79. package/docs/API.md +195 -0
  80. package/docs/AccountApi.md +220 -0
  81. package/docs/GettingStarted.md +261 -0
  82. package/docs/OrderApi.md +199 -0
  83. package/docs/SignerClient.md +326 -0
  84. package/docs/TransactionApi.md +312 -0
  85. package/docs/WsClient.md +275 -0
  86. package/docs/types/Account.md +67 -0
  87. package/docs/types/ApiKeyPair.md +33 -0
  88. package/docs/types/CreateOrderParams.md +47 -0
  89. package/docs/types/MarketOrderParams.md +36 -0
  90. package/docs/types/SignerConfig.md +40 -0
  91. package/docs/types/WasmSignerConfig.md +30 -0
  92. package/examples/README.md +171 -0
  93. package/examples/account_info.ts +12 -0
  94. package/examples/create_cancel_order.ts +74 -0
  95. package/examples/create_market_order.ts +42 -0
  96. package/examples/create_market_order_max_slippage.ts +43 -0
  97. package/examples/create_sl_tp.ts +61 -0
  98. package/examples/create_with_multiple_keys.ts +58 -0
  99. package/examples/get_info.ts +58 -0
  100. package/examples/send_tx_batch.ts +87 -0
  101. package/examples/system_setup.ts +96 -0
  102. package/examples/transfer_update_leverage.ts +53 -0
  103. package/examples/ws.ts +24 -0
  104. package/examples/ws_async.ts +39 -0
  105. package/examples/ws_send_batch_tx.ts +113 -0
  106. package/examples/ws_send_tx.ts +94 -0
  107. package/package.json +71 -0
  108. package/wasm/lighter-signer.wasm +0 -0
  109. package/wasm/wasm_exec.js +402 -0
  110. package/wasm/wasm_exec_nodejs.js +402 -0
@@ -0,0 +1,261 @@
1
+ # Getting Started Guide
2
+
3
+ This guide will help you get up and running with the Lighter TypeScript SDK quickly.
4
+
5
+ ## Prerequisites
6
+
7
+ - Node.js 16+ installed
8
+ - TypeScript 4.5+ (if using TypeScript directly)
9
+ - A Lighter account with some USDC deposited
10
+
11
+ ## Installation
12
+
13
+ ### Using npm
14
+
15
+ ```bash
16
+ npm install @lighter/typescript-sdk
17
+ ```
18
+
19
+ ### Using yarn
20
+
21
+ ```bash
22
+ yarn add @lighter/typescript-sdk
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ### 1. Basic API Usage
28
+
29
+ ```typescript
30
+ import { ApiClient, AccountApi } from '@lighter/typescript-sdk';
31
+
32
+ async function main() {
33
+ const client = new ApiClient({ host: 'https://mainnet.zklighter.elliot.ai' });
34
+ const accountApi = new AccountApi(client);
35
+
36
+ try {
37
+ const account = await accountApi.getAccount({ by: 'index', value: '123' });
38
+ console.log('Account:', account);
39
+ } catch (error) {
40
+ console.error('Error:', error.message);
41
+ } finally {
42
+ await client.close();
43
+ }
44
+ }
45
+
46
+ main().catch(console.error);
47
+ ```
48
+
49
+ ### 2. Trading with SignerClient
50
+
51
+ ```typescript
52
+ import { SignerClient } from '@lighter/typescript-sdk';
53
+
54
+ async function main() {
55
+ const client = new SignerClient({
56
+ url: 'https://mainnet.zklighter.elliot.ai',
57
+ privateKey: 'your-api-key-private-key',
58
+ accountIndex: 123,
59
+ apiKeyIndex: 0,
60
+ wasmConfig: { wasmPath: 'wasm/lighter-signer.wasm' }
61
+ });
62
+
63
+ try {
64
+ await client.initialize();
65
+ await client.ensureWasmClient();
66
+
67
+ // Create a market order
68
+ const [tx, txHash, err] = await client.createMarketOrder({
69
+ marketIndex: 0, // ETH/USDC
70
+ clientOrderIndex: Date.now(),
71
+ baseAmount: 1000000, // 1 ETH
72
+ avgExecutionPrice: 300000000, // Max $3000
73
+ isAsk: true // Sell order
74
+ });
75
+
76
+ if (err) {
77
+ console.error('Order failed:', err);
78
+ return;
79
+ }
80
+
81
+ console.log('Order created:', txHash);
82
+ } finally {
83
+ await client.close();
84
+ }
85
+ }
86
+
87
+ main().catch(console.error);
88
+ ```
89
+
90
+ ## Setup Process
91
+
92
+ ### Step 1: Get Your Account Information
93
+
94
+ First, you need to obtain your account index and API key information. You can do this through the Lighter web app or by using the system setup example.
95
+
96
+ ### Step 2: Generate API Keys
97
+
98
+ Use the system setup example to generate API keys:
99
+
100
+ ```bash
101
+ npx ts-node examples/system_setup.ts
102
+ ```
103
+
104
+ This will output something like:
105
+ ```
106
+ BASE_URL = 'https://mainnet.zklighter.elliot.ai'
107
+ API_KEY_PRIVATE_KEY = 'ea5d2eca5be67eca056752eaf27b173518b8a5550117c09d2b58c7ea7d306cc4426f913ccf27ab19'
108
+ ACCOUNT_INDEX = 595
109
+ API_KEY_INDEX = 1
110
+ ```
111
+
112
+ ### Step 3: Configure Your Environment
113
+
114
+ Create a `.env` file in your project root:
115
+
116
+ ```env
117
+ BASE_URL=https://mainnet.zklighter.elliot.ai
118
+ PRIVATE_KEY=0xea5d2eca5be67eca056752eaf27b173518b8a5550117c09d2b58c7ea7d306cc4426f913ccf27ab19
119
+ ACCOUNT_INDEX=595
120
+ API_KEY_INDEX=1
121
+ ```
122
+
123
+ ### Step 4: Start Trading
124
+
125
+ Now you can use the SDK to create orders:
126
+
127
+ ```typescript
128
+ import { SignerClient } from '@lighter/typescript-sdk';
129
+ import * as dotenv from 'dotenv';
130
+
131
+ dotenv.config();
132
+
133
+ const client = new SignerClient({
134
+ url: process.env.BASE_URL!,
135
+ privateKey: process.env.API_PRIVATE_KEY!,
136
+ accountIndex: parseInt(process.env.ACCOUNT_INDEX!),
137
+ apiKeyIndex: parseInt(process.env.API_KEY_INDEX!),
138
+ wasmConfig: { wasmPath: 'wasm/lighter-signer.wasm' }
139
+ });
140
+
141
+ // Your trading logic here...
142
+ ```
143
+
144
+ ## Common Patterns
145
+
146
+ ### Error Handling
147
+
148
+ Always check for errors when calling SDK methods:
149
+
150
+ ```typescript
151
+ const [tx, txHash, err] = await client.createOrder(params);
152
+ if (err) {
153
+ console.error('Order creation failed:', err);
154
+ return;
155
+ }
156
+ console.log('Order created successfully:', txHash);
157
+ ```
158
+
159
+ ### Async/Await Pattern
160
+
161
+ The SDK uses async/await throughout. Always use try/catch for error handling:
162
+
163
+ ```typescript
164
+ try {
165
+ const account = await accountApi.getAccount({ by: 'index', value: '123' });
166
+ console.log('Account:', account);
167
+ } catch (error) {
168
+ console.error('Failed to get account:', error.message);
169
+ }
170
+ ```
171
+
172
+ ### Resource Cleanup
173
+
174
+ Always close clients when done:
175
+
176
+ ```typescript
177
+ try {
178
+ // Your code here
179
+ } finally {
180
+ await client.close();
181
+ }
182
+ ```
183
+
184
+ ## Examples
185
+
186
+ The SDK includes comprehensive examples in the `examples/` directory:
187
+
188
+ - `create_market_order.ts` - Basic market order creation
189
+ - `create_cancel_order.ts` - Limit order creation and cancellation
190
+ - `get_info.ts` - API information retrieval
191
+ - `system_setup.ts` - Account setup and API key generation
192
+ - `transfer_update_leverage.ts` - Account management operations
193
+ - `ws.ts` - WebSocket real-time data
194
+
195
+ Run any example with:
196
+
197
+ ```bash
198
+ npx ts-node examples/[example-name].ts
199
+ ```
200
+
201
+ ## WebSocket Usage
202
+
203
+ For real-time data, use the WebSocket client:
204
+
205
+ ```typescript
206
+ import { WsClient } from '@lighter/typescript-sdk';
207
+
208
+ const wsClient = new WsClient({
209
+ url: 'wss://mainnet.zklighter.elliot.ai/ws',
210
+ accountIndex: 123,
211
+ apiKeyIndex: 0,
212
+ privateKey: 'your-api-key-private-key'
213
+ });
214
+
215
+ await wsClient.connect();
216
+
217
+ // Subscribe to order book updates
218
+ wsClient.subscribeOrderBook(0, (data) => {
219
+ console.log('Order book update:', data);
220
+ });
221
+
222
+ // Subscribe to account updates
223
+ wsClient.subscribeAccount((data) => {
224
+ console.log('Account update:', data);
225
+ });
226
+ ```
227
+
228
+ ## Troubleshooting
229
+
230
+ ### Common Issues
231
+
232
+ 1. **"WASM functions not properly registered"**
233
+ - Ensure the WASM binary is built and accessible
234
+ - Check that the `wasmPath` is correct
235
+
236
+ 2. **"Invalid signature" errors**
237
+ - Verify your API key private key is correct
238
+ - Check that account index and API key index match your setup
239
+
240
+ 3. **"Account not found" errors**
241
+ - Ensure you have deposited USDC to create an account
242
+ - Verify your account index is correct
243
+
244
+ 4. **Network errors**
245
+ - Check your internet connection
246
+ - Verify the API URL is correct
247
+ - Ensure you're using the correct network (mainnet vs testnet)
248
+
249
+ ### Getting Help
250
+
251
+ - Check the [API documentation](docs/)
252
+ - Review the [examples](examples/)
253
+ - Join our [Discord community](https://discord.gg/lighter)
254
+ - Visit our [documentation site](https://docs.lighter.xyz)
255
+
256
+ ## Next Steps
257
+
258
+ - Explore the [API documentation](docs/) for detailed method information
259
+ - Check out the [examples](examples/) for more complex use cases
260
+ - Learn about [WebSocket integration](docs/WsClient.md) for real-time data
261
+ - Review the [type definitions](docs/types/) for TypeScript support
@@ -0,0 +1,199 @@
1
+ # OrderApi
2
+
3
+ The `OrderApi` class provides methods for retrieving order book data, exchange statistics, and trade information.
4
+
5
+ ## Constructor
6
+
7
+ ```typescript
8
+ new OrderApi(client: ApiClient)
9
+ ```
10
+
11
+ ## Methods
12
+
13
+ ### getExchangeStats()
14
+
15
+ Gets exchange-wide statistics.
16
+
17
+ **Returns:** `Promise<ExchangeStats>` - Exchange statistics
18
+
19
+ **Example:**
20
+ ```typescript
21
+ const orderApi = new OrderApi(client);
22
+ const stats = await orderApi.getExchangeStats();
23
+ console.log('Exchange stats:', stats);
24
+ ```
25
+
26
+ ### getOrderBookDetails(params: OrderBookParams)
27
+
28
+ Gets detailed order book information for a specific market.
29
+
30
+ **Parameters:**
31
+ - `marketIndex: number` - Market index (0 for ETH/USDC)
32
+
33
+ **Returns:** `Promise<OrderBookDetail>` - Order book details
34
+
35
+ **Example:**
36
+ ```typescript
37
+ const orderBook = await orderApi.getOrderBookDetails({ marketIndex: 0 });
38
+ console.log('Order book:', orderBook);
39
+ ```
40
+
41
+ ### getOrderBooks()
42
+
43
+ Gets order book information for all markets.
44
+
45
+ **Returns:** `Promise<OrderBook[]>` - Array of order books
46
+
47
+ **Example:**
48
+ ```typescript
49
+ const orderBooks = await orderApi.getOrderBooks();
50
+ console.log(`Found ${orderBooks.length} order books`);
51
+ ```
52
+
53
+ ### getRecentTrades(params: TradeParams)
54
+
55
+ Gets recent trades for a specific market.
56
+
57
+ **Parameters:**
58
+ - `marketIndex: number` - Market index
59
+ - `limit?: number` - Maximum number of trades to return
60
+
61
+ **Returns:** `Promise<Trade[]>` - Array of recent trades
62
+
63
+ **Example:**
64
+ ```typescript
65
+ const trades = await orderApi.getRecentTrades({
66
+ marketIndex: 0,
67
+ limit: 50
68
+ });
69
+ console.log(`Found ${trades.length} recent trades`);
70
+ ```
71
+
72
+ ## Types
73
+
74
+ ### OrderBookParams
75
+
76
+ ```typescript
77
+ interface OrderBookParams {
78
+ marketIndex: number;
79
+ }
80
+ ```
81
+
82
+ ### TradeParams
83
+
84
+ ```typescript
85
+ interface TradeParams {
86
+ marketIndex: number;
87
+ limit?: number;
88
+ }
89
+ ```
90
+
91
+ ### ExchangeStats
92
+
93
+ ```typescript
94
+ interface ExchangeStats {
95
+ total_volume: string;
96
+ total_trades: number;
97
+ // ... other statistics
98
+ }
99
+ ```
100
+
101
+ ### OrderBookDetail
102
+
103
+ ```typescript
104
+ interface OrderBookDetail {
105
+ market_index: number;
106
+ bids: PriceLevel[];
107
+ asks: PriceLevel[];
108
+ // ... other order book data
109
+ }
110
+ ```
111
+
112
+ ### OrderBook
113
+
114
+ ```typescript
115
+ interface OrderBook {
116
+ market_id: number;
117
+ symbol: string;
118
+ // ... other order book information
119
+ }
120
+ ```
121
+
122
+ ### Trade
123
+
124
+ ```typescript
125
+ interface Trade {
126
+ trade_id: string;
127
+ market_index: number;
128
+ price: string;
129
+ size: string;
130
+ timestamp: string;
131
+ // ... other trade data
132
+ }
133
+ ```
134
+
135
+ ### PriceLevel
136
+
137
+ ```typescript
138
+ interface PriceLevel {
139
+ price: string;
140
+ size: string;
141
+ }
142
+ ```
143
+
144
+ ## Error Handling
145
+
146
+ All methods throw errors for invalid parameters or network issues:
147
+
148
+ ```typescript
149
+ try {
150
+ const orderBook = await orderApi.getOrderBookDetails({ marketIndex: 0 });
151
+ console.log('Order book:', orderBook);
152
+ } catch (error) {
153
+ console.error('Failed to get order book:', error.message);
154
+ }
155
+ ```
156
+
157
+ ## Complete Example
158
+
159
+ ```typescript
160
+ import { ApiClient, OrderApi } from '@lighter/typescript-sdk';
161
+
162
+ async function main() {
163
+ const client = new ApiClient({ host: 'https://mainnet.zklighter.elliot.ai' });
164
+ const orderApi = new OrderApi(client);
165
+
166
+ try {
167
+ // Get exchange statistics
168
+ const stats = await orderApi.getExchangeStats();
169
+ console.log('Exchange stats:', stats);
170
+
171
+ // Get order book details for ETH/USDC
172
+ const orderBook = await orderApi.getOrderBookDetails({ marketIndex: 0 });
173
+ console.log('ETH/USDC order book:', orderBook);
174
+
175
+ // Get all order books
176
+ const orderBooks = await orderApi.getOrderBooks();
177
+ console.log(`Found ${orderBooks.length} markets`);
178
+
179
+ // Get recent trades
180
+ const trades = await orderApi.getRecentTrades({
181
+ marketIndex: 0,
182
+ limit: 20
183
+ });
184
+ console.log(`Found ${trades.length} recent trades`);
185
+
186
+ // Display recent trades
187
+ trades.forEach(trade => {
188
+ console.log(`Trade: ${trade.size} @ ${trade.price} (${trade.timestamp})`);
189
+ });
190
+
191
+ } catch (error) {
192
+ console.error('Error:', error.message);
193
+ } finally {
194
+ await client.close();
195
+ }
196
+ }
197
+
198
+ main().catch(console.error);
199
+ ```