lighter-ts-sdk 1.0.5 → 1.0.6

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 (184) hide show
  1. package/README.md +405 -487
  2. package/dist/api/announcement-api.d.ts +27 -0
  3. package/dist/api/announcement-api.d.ts.map +1 -0
  4. package/dist/api/announcement-api.js +25 -0
  5. package/dist/api/announcement-api.js.map +1 -0
  6. package/dist/api/bridge-api.d.ts +78 -0
  7. package/dist/api/bridge-api.d.ts.map +1 -0
  8. package/dist/api/bridge-api.js +137 -0
  9. package/dist/api/bridge-api.js.map +1 -0
  10. package/dist/api/funding-api.d.ts +28 -0
  11. package/dist/api/funding-api.d.ts.map +1 -0
  12. package/dist/api/funding-api.js +25 -0
  13. package/dist/api/funding-api.js.map +1 -0
  14. package/dist/api/notification-api.d.ts +27 -0
  15. package/dist/api/notification-api.d.ts.map +1 -0
  16. package/dist/api/notification-api.js +49 -0
  17. package/dist/api/notification-api.js.map +1 -0
  18. package/dist/api/order-api.d.ts +97 -14
  19. package/dist/api/order-api.d.ts.map +1 -1
  20. package/dist/api/order-api.js +15 -6
  21. package/dist/api/order-api.js.map +1 -1
  22. package/dist/api/referral-api.d.ts +37 -0
  23. package/dist/api/referral-api.d.ts.map +1 -0
  24. package/dist/api/referral-api.js +45 -0
  25. package/dist/api/referral-api.js.map +1 -0
  26. package/dist/api/transaction-api.d.ts +6 -1
  27. package/dist/api/transaction-api.d.ts.map +1 -1
  28. package/dist/api/transaction-api.js +19 -7
  29. package/dist/api/transaction-api.js.map +1 -1
  30. package/dist/api/ws-order-client.d.ts.map +1 -1
  31. package/dist/api/ws-order-client.js +4 -14
  32. package/dist/api/ws-order-client.js.map +1 -1
  33. package/dist/bridge/l1-bridge-client.d.ts +49 -0
  34. package/dist/bridge/l1-bridge-client.d.ts.map +1 -0
  35. package/dist/bridge/l1-bridge-client.js +187 -0
  36. package/dist/bridge/l1-bridge-client.js.map +1 -0
  37. package/dist/index.d.ts +21 -11
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +49 -18
  40. package/dist/index.js.map +1 -1
  41. package/dist/{utils → signer}/wasm-manager.d.ts +1 -2
  42. package/dist/signer/wasm-manager.d.ts.map +1 -0
  43. package/dist/{utils → signer}/wasm-manager.js +1 -2
  44. package/dist/signer/wasm-manager.js.map +1 -0
  45. package/dist/signer/wasm-signer-client.d.ts +242 -34
  46. package/dist/signer/wasm-signer-client.d.ts.map +1 -1
  47. package/dist/signer/wasm-signer-client.js +800 -312
  48. package/dist/signer/wasm-signer-client.js.map +1 -1
  49. package/dist/{utils/node-wasm-signer.d.ts → signer/wasm-signer.d.ts} +32 -9
  50. package/dist/signer/wasm-signer.d.ts.map +1 -0
  51. package/dist/{utils/node-wasm-signer.js → signer/wasm-signer.js} +179 -127
  52. package/dist/signer/wasm-signer.js.map +1 -0
  53. package/dist/types/api.d.ts +196 -0
  54. package/dist/types/api.d.ts.map +1 -0
  55. package/dist/types/api.js +7 -0
  56. package/dist/types/api.js.map +1 -0
  57. package/dist/types/config.d.ts +65 -0
  58. package/dist/types/config.d.ts.map +1 -0
  59. package/dist/types/config.js +7 -0
  60. package/dist/types/config.js.map +1 -0
  61. package/dist/types/index.d.ts +21 -103
  62. package/dist/types/index.d.ts.map +1 -1
  63. package/dist/types/index.js +23 -0
  64. package/dist/types/index.js.map +1 -1
  65. package/dist/types/trading.d.ts +43 -0
  66. package/dist/types/trading.d.ts.map +1 -0
  67. package/dist/types/trading.js +25 -0
  68. package/dist/types/trading.js.map +1 -0
  69. package/dist/types/transaction.d.ts +56 -0
  70. package/dist/types/transaction.d.ts.map +1 -0
  71. package/dist/types/transaction.js +29 -0
  72. package/dist/types/transaction.js.map +1 -0
  73. package/dist/utils/exceptions.js +1 -1
  74. package/dist/utils/exceptions.js.map +1 -1
  75. package/dist/utils/index.d.ts +14 -0
  76. package/dist/utils/index.d.ts.map +1 -0
  77. package/dist/utils/index.js +38 -0
  78. package/dist/utils/index.js.map +1 -0
  79. package/dist/utils/logger.js +3 -3
  80. package/dist/utils/logger.js.map +1 -1
  81. package/dist/utils/market-helper.d.ts +62 -0
  82. package/dist/utils/market-helper.d.ts.map +1 -0
  83. package/dist/utils/market-helper.js +100 -0
  84. package/dist/utils/market-helper.js.map +1 -0
  85. package/dist/utils/nonce-cache.d.ts +9 -1
  86. package/dist/utils/nonce-cache.d.ts.map +1 -1
  87. package/dist/utils/nonce-cache.js +28 -1
  88. package/dist/utils/nonce-cache.js.map +1 -1
  89. package/dist/utils/nonce-manager.d.ts +79 -0
  90. package/dist/utils/nonce-manager.d.ts.map +1 -0
  91. package/dist/utils/nonce-manager.js +130 -0
  92. package/dist/utils/nonce-manager.js.map +1 -0
  93. package/dist/utils/order-status-checker.d.ts +29 -0
  94. package/dist/utils/order-status-checker.d.ts.map +1 -0
  95. package/dist/utils/order-status-checker.js +101 -0
  96. package/dist/utils/order-status-checker.js.map +1 -0
  97. package/dist/utils/price-utils.d.ts +86 -0
  98. package/dist/utils/price-utils.d.ts.map +1 -0
  99. package/dist/utils/price-utils.js +229 -0
  100. package/dist/utils/price-utils.js.map +1 -0
  101. package/dist/utils/request-batcher.d.ts.map +1 -1
  102. package/dist/utils/request-batcher.js +4 -7
  103. package/dist/utils/request-batcher.js.map +1 -1
  104. package/docs/GettingStarted.md +358 -262
  105. package/docs/MarketHelper.md +214 -0
  106. package/docs/SignerClient.md +406 -326
  107. package/docs/Utilities.md +268 -0
  108. package/docs/types/SignerConfig.md +40 -40
  109. package/examples/README.md +191 -215
  110. package/examples/cancel_all_orders.ts +112 -79
  111. package/examples/cancel_order.ts +106 -156
  112. package/examples/close_all_positions.ts +55 -49
  113. package/examples/close_position.ts +84 -164
  114. package/examples/create_auth_token.ts +57 -121
  115. package/examples/create_limit_order.ts +72 -67
  116. package/examples/create_market_order.ts +143 -68
  117. package/examples/create_twap_order.ts +98 -0
  118. package/examples/create_with_multiple_keys.ts +101 -76
  119. package/examples/deposit_to_subaccount.ts +104 -0
  120. package/examples/market_data.ts +175 -0
  121. package/examples/send_tx_batch.ts +149 -69
  122. package/examples/system_setup.ts +109 -191
  123. package/examples/withdraw_to_l1.ts +68 -0
  124. package/examples/ws.ts +67 -64
  125. package/examples/ws_async.ts +107 -40
  126. package/examples/ws_ping_pong.ts +260 -0
  127. package/examples/ws_send_batch_tx.ts +135 -93
  128. package/examples/ws_send_tx.ts +98 -93
  129. package/package.json +1 -1
  130. package/wasm/wasm_exec.js +575 -575
  131. package/dist/signer/signer-client.d.ts +0 -79
  132. package/dist/signer/signer-client.d.ts.map +0 -1
  133. package/dist/signer/signer-client.js +0 -212
  134. package/dist/signer/signer-client.js.map +0 -1
  135. package/dist/utils/advanced-cache.d.ts +0 -66
  136. package/dist/utils/advanced-cache.d.ts.map +0 -1
  137. package/dist/utils/advanced-cache.js +0 -199
  138. package/dist/utils/advanced-cache.js.map +0 -1
  139. package/dist/utils/api-key-utils.d.ts +0 -7
  140. package/dist/utils/api-key-utils.d.ts.map +0 -1
  141. package/dist/utils/api-key-utils.js +0 -31
  142. package/dist/utils/api-key-utils.js.map +0 -1
  143. package/dist/utils/memory-pool.d.ts +0 -98
  144. package/dist/utils/memory-pool.d.ts.map +0 -1
  145. package/dist/utils/memory-pool.js +0 -190
  146. package/dist/utils/memory-pool.js.map +0 -1
  147. package/dist/utils/node-wasm-signer.d.ts.map +0 -1
  148. package/dist/utils/node-wasm-signer.js.map +0 -1
  149. package/dist/utils/optimized-http-client.d.ts +0 -29
  150. package/dist/utils/optimized-http-client.d.ts.map +0 -1
  151. package/dist/utils/optimized-http-client.js +0 -142
  152. package/dist/utils/optimized-http-client.js.map +0 -1
  153. package/dist/utils/performance-monitor.d.ts +0 -41
  154. package/dist/utils/performance-monitor.d.ts.map +0 -1
  155. package/dist/utils/performance-monitor.js +0 -168
  156. package/dist/utils/performance-monitor.js.map +0 -1
  157. package/dist/utils/signer-server.d.ts +0 -18
  158. package/dist/utils/signer-server.d.ts.map +0 -1
  159. package/dist/utils/signer-server.js +0 -78
  160. package/dist/utils/signer-server.js.map +0 -1
  161. package/dist/utils/transaction-helper.d.ts +0 -37
  162. package/dist/utils/transaction-helper.d.ts.map +0 -1
  163. package/dist/utils/transaction-helper.js +0 -174
  164. package/dist/utils/transaction-helper.js.map +0 -1
  165. package/dist/utils/wasm-manager.d.ts.map +0 -1
  166. package/dist/utils/wasm-manager.js.map +0 -1
  167. package/dist/utils/wasm-signer.d.ts +0 -158
  168. package/dist/utils/wasm-signer.d.ts.map +0 -1
  169. package/dist/utils/wasm-signer.js +0 -214
  170. package/dist/utils/wasm-signer.js.map +0 -1
  171. package/examples/account_info.ts +0 -15
  172. package/examples/check_transaction_status.ts +0 -159
  173. package/examples/create_cancel_order.ts +0 -113
  174. package/examples/create_market_order_if_slippage.ts +0 -68
  175. package/examples/create_market_order_max_slippage.ts +0 -42
  176. package/examples/create_sl_tp.ts +0 -165
  177. package/examples/deposit_to_subaccounts.ts +0 -146
  178. package/examples/get_info.ts +0 -63
  179. package/examples/get_points.ts +0 -61
  180. package/examples/market_data_json.ts +0 -80
  181. package/examples/nonce_manager.ts +0 -264
  182. package/examples/transfer_update_leverage.ts +0 -52
  183. package/examples/wait_for_transaction.ts +0 -100
  184. package/examples/withdraw.ts +0 -118
package/README.md CHANGED
@@ -1,487 +1,405 @@
1
- # Lighter Protocol TypeScript SDK (Unofficial)
2
-
3
- > **⚠️ Disclaimer**: This is an **unofficial** TypeScript SDK for Lighter Protocol, built by the community. It is not officially maintained by the Lighter Protocol team.
4
-
5
- TypeScript SDK for Lighter Protocol - Trade perpetuals with unmatched efficiency and fairness.
6
-
7
- ## Requirements
8
-
9
- - Node.js 16+
10
- - TypeScript 4.5+
11
-
12
- ## Installation & Usage
13
-
14
- ### npm install
15
-
16
- ```sh
17
- npm install lighter-ts-sdk
18
- ```
19
-
20
- ### yarn install
21
-
22
- ```sh
23
- yarn add lighter-ts-sdk
24
- ```
25
-
26
- Then import the package:
27
-
28
- ```typescript
29
- import { SignerClient, ApiClient } from 'lighter-ts-sdk';
30
- ```
31
-
32
- ## Quick Start Examples
33
-
34
- ### 1. Basic API Usage
35
-
36
- ```typescript
37
- import { ApiClient, AccountApi } from 'lighter-ts-sdk';
38
-
39
- async function getAccountInfo() {
40
- const client = new ApiClient({ host: 'https://mainnet.zklighter.elliot.ai' });
41
- const accountApi = new AccountApi(client);
42
-
43
- const account = await accountApi.getAccount({ by: 'index', value: '1' });
44
- console.log('Account:', account);
45
- }
46
-
47
- getAccountInfo().catch(console.error);
48
- ```
49
-
50
- ### 2. Create Market Order (Standalone WASM Signer)
51
-
52
- ```typescript
53
- import { SignerClient } from 'lighter-ts-sdk';
54
-
55
- async function createMarketOrder() {
56
- const client = new SignerClient({
57
- url: 'https://mainnet.zklighter.elliot.ai',
58
- privateKey: 'your-api-key-private-key',
59
- accountIndex: 123,
60
- apiKeyIndex: 0
61
- // No wasmConfig needed - standalone signer auto-resolves paths
62
- });
63
-
64
- await client.initialize();
65
- await (client as any).ensureWasmClient();
66
-
67
- const [tx, txHash, err] = await client.createMarketOrder({
68
- marketIndex: 0,
69
- clientOrderIndex: Date.now(),
70
- baseAmount: 10, // Base amount
71
- avgExecutionPrice: 4500, // Price in cents
72
- isAsk: true // Sell order
73
- });
74
-
75
- if (err) {
76
- console.error('Order failed:', err);
77
- } else {
78
- console.log('Market order created:', { tx, txHash });
79
- }
80
- }
81
-
82
- createMarketOrder().catch(console.error);
83
- ```
84
-
85
- ### 3. Create Limit Order
86
-
87
- ```typescript
88
- import { SignerClient } from 'lighter-ts-sdk';
89
-
90
- async function createLimitOrder() {
91
- const client = new SignerClient({
92
- url: 'https://mainnet.zklighter.elliot.ai',
93
- privateKey: 'your-api-key-private-key',
94
- accountIndex: 123,
95
- apiKeyIndex: 0
96
- });
97
-
98
- await client.initialize();
99
- await (client as any).ensureWasmClient();
100
-
101
- const [tx, txHash, err] = await client.createOrder({
102
- marketIndex: 0,
103
- clientOrderIndex: Date.now(),
104
- baseAmount: 5, // Base amount
105
- price: 4500, // Price in cents
106
- isAsk: false, // Buy order
107
- timeInForce: SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME
108
- });
109
-
110
- if (err) {
111
- console.error('Order failed:', err);
112
- } else {
113
- console.log('Limit order created:', { tx, txHash });
114
- }
115
- }
116
-
117
- createLimitOrder().catch(console.error);
118
- ```
119
-
120
- ### 4. Cancel Order
121
-
122
- ```typescript
123
- import { SignerClient } from 'lighter-ts-sdk';
124
-
125
- async function cancelOrder() {
126
- const client = new SignerClient({
127
- url: 'https://mainnet.zklighter.elliot.ai',
128
- privateKey: 'your-api-key-private-key',
129
- accountIndex: 123,
130
- apiKeyIndex: 0
131
- });
132
-
133
- await client.initialize();
134
- await (client as any).ensureWasmClient();
135
-
136
- const [tx, txHash, err] = await client.cancelOrder({
137
- marketIndex: 0,
138
- orderIndex: 12345
139
- });
140
-
141
- if (err) {
142
- console.error('Cancel failed:', err);
143
- } else {
144
- console.log('Order cancelled:', { tx, txHash });
145
- }
146
- }
147
-
148
- cancelOrder().catch(console.error);
149
- ```
150
-
151
- ### 5. Transfer USDC
152
-
153
- ```typescript
154
- import { SignerClient } from 'lighter-ts-sdk';
155
-
156
- async function transferUSDC() {
157
- const client = new SignerClient({
158
- url: 'https://mainnet.zklighter.elliot.ai',
159
- privateKey: 'your-api-key-private-key',
160
- accountIndex: 123,
161
- apiKeyIndex: 0
162
- });
163
-
164
- await client.initialize();
165
- await (client as any).ensureWasmClient();
166
-
167
- const [tx, txHash, err] = await client.transfer(
168
- 456, // toAccountIndex
169
- 1000000 // usdcAmount in cents ($10,000)
170
- );
171
-
172
- if (err) {
173
- console.error('Transfer failed:', err);
174
- } else {
175
- console.log('USDC transferred:', { tx, txHash });
176
- }
177
- }
178
-
179
- transferUSDC().catch(console.error);
180
- ```
181
-
182
- ### 6. Update Leverage
183
-
184
- ```typescript
185
- import { SignerClient } from 'lighter-ts-sdk';
186
-
187
- async function updateLeverage() {
188
- const client = new SignerClient({
189
- url: 'https://mainnet.zklighter.elliot.ai',
190
- privateKey: 'your-api-key-private-key',
191
- accountIndex: 123,
192
- apiKeyIndex: 0
193
- });
194
-
195
- await client.initialize();
196
- await (client as any).ensureWasmClient();
197
-
198
- const [tx, txHash, err] = await client.updateLeverage(
199
- 0, // marketIndex
200
- SignerClient.CROSS_MARGIN_MODE, // marginMode
201
- 10 // initialMarginFraction (10x leverage)
202
- );
203
-
204
- if (err) {
205
- console.error('Leverage update failed:', err);
206
- } else {
207
- console.log('Leverage updated:', { tx, txHash });
208
- }
209
- }
210
-
211
- updateLeverage().catch(console.error);
212
- ```
213
-
214
- ### 7. Cancel All Orders
215
-
216
- ```typescript
217
- import { SignerClient } from 'lighter-ts-sdk';
218
-
219
- async function cancelAllOrders() {
220
- const client = new SignerClient({
221
- url: 'https://mainnet.zklighter.elliot.ai',
222
- privateKey: 'your-api-key-private-key',
223
- accountIndex: 123,
224
- apiKeyIndex: 0
225
- });
226
-
227
- await client.initialize();
228
- await (client as any).ensureWasmClient();
229
-
230
- const [tx, txHash, err] = await client.cancelAllOrders(
231
- SignerClient.CANCEL_ALL_TIF_IMMEDIATE, // timeInForce
232
- Date.now() // time
233
- );
234
-
235
- if (err) {
236
- console.error('Cancel all failed:', err);
237
- } else {
238
- console.log('All orders cancelled:', { tx, txHash });
239
- }
240
- }
241
-
242
- cancelAllOrders().catch(console.error);
243
- ```
244
-
245
- ### 8. Get Referral Points with Auth Token
246
-
247
- ```typescript
248
- import { SignerClient, ApiClient } from 'lighter-ts-sdk';
249
-
250
- async function getReferralPoints() {
251
- const signerClient = new SignerClient({
252
- url: 'https://mainnet.zklighter.elliot.ai',
253
- privateKey: 'your-api-key-private-key',
254
- accountIndex: 123,
255
- apiKeyIndex: 0
256
- });
257
-
258
- await signerClient.initialize();
259
- await (signerClient as any).ensureWasmClient();
260
-
261
- // Create an authentication token
262
- const authToken = await signerClient.createAuthTokenWithExpiry(600); // 10 minutes
263
- console.log('Auth Token:', authToken);
264
-
265
- // Initialize API client
266
- const apiClient = new ApiClient({ host: 'https://mainnet.zklighter.elliot.ai' });
267
-
268
- // Get referral points using auth token
269
- const response = await apiClient.get('/api/v1/referral/points', {
270
- account_index: 123,
271
- auth: authToken
272
- });
273
-
274
- console.log('Referral points:', response.data);
275
- }
276
-
277
- getReferralPoints().catch(console.error);
278
- ```
279
-
280
- ### 9. WebSocket Real-time Data
281
-
282
- ```typescript
283
- import { WsClient } from 'lighter-ts-sdk';
284
-
285
- async function connectWebSocket() {
286
- const wsClient = new WsClient({
287
- url: 'wss://mainnet.zklighter.elliot.ai/ws',
288
- onOpen: () => console.log('WebSocket connected'),
289
- onMessage: (message) => console.log('Received:', message),
290
- onClose: () => console.log('WebSocket closed'),
291
- onError: (error) => console.error('WebSocket error:', error)
292
- });
293
-
294
- await wsClient.connect();
295
-
296
- // Subscribe to order book updates
297
- wsClient.subscribe('orderbook', { market_id: 0 });
298
-
299
- // Subscribe to account updates
300
- wsClient.subscribe('account', { account_index: 123 });
301
- }
302
-
303
- connectWebSocket().catch(console.error);
304
- ```
305
-
306
- ## Standalone WASM Signer
307
-
308
- The SDK now includes a **standalone WASM signer** that requires no Go installation:
309
-
310
- ```typescript
311
- interface SignerConfig {
312
- url: string; // API endpoint
313
- privateKey: string; // API key private key
314
- accountIndex: number; // Your account index
315
- apiKeyIndex: number; // API key index (usually 0)
316
- // wasmConfig is optional - auto-resolves bundled wasm files
317
- }
318
- ```
319
-
320
- ### Key Features:
321
- - **No Go Required** - Users don't need Go installed
322
- - **Auto Path Resolution** - Automatically finds bundled wasm files
323
- - ✅ **Cross-Platform** - Works on Windows, Linux, macOS
324
-
325
- ## Available Constants
326
-
327
- ```typescript
328
- // Order Types
329
- SignerClient.ORDER_TYPE_LIMIT = 0
330
- SignerClient.ORDER_TYPE_MARKET = 1
331
-
332
- // Time in Force
333
- SignerClient.ORDER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL = 0 // Immediate or Cancel
334
- SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME = 1 // Good Till Time
335
- SignerClient.ORDER_TIME_IN_FORCE_FILL_OR_KILL = 2 // Fill or Kill
336
-
337
- // Margin Modes
338
- SignerClient.CROSS_MARGIN_MODE = 0
339
- SignerClient.ISOLATED_MARGIN_MODE = 1
340
- ```
341
-
342
- ## Documentation
343
-
344
- - [Getting Started Guide](docs/GettingStarted.md)
345
- - [API Reference](docs/API.md)
346
- - [SignerClient Documentation](docs/SignerClient.md)
347
- - [WebSocket Client](docs/WsClient.md)
348
- - [Type Definitions](docs/types/)
349
-
350
- ## Examples
351
-
352
- Check the `examples/` directory for comprehensive usage examples:
353
-
354
- - `create_market_order.ts` - Basic market order creation
355
- - `create_cancel_order.ts` - Order management
356
- - `transfer_update_leverage.ts` - Account operations
357
- - `system_setup.ts` - API key management
358
- - `get_points.ts` - Referral points with auth tokens
359
- - `ws_*.ts` - WebSocket examples
360
-
361
- ## SDK Status Report
362
-
363
- ### **Currently Working & Released**
364
-
365
- #### **Core Trading Functionality**
366
- - ✅ **Market Orders** - Create market buy/sell orders with price limits
367
- - ✅ **Limit Orders** - Create limit orders with GTC/IOC/FOK time in force
368
- - **Order Cancellation** - Cancel individual orders by market and order index
369
- - ✅ **Cancel All Orders** - Cancel all orders for an account
370
- - **USDC Transfers** - Transfer USDC between accounts with memo support
371
- - ✅ **Leverage Updates** - Update leverage for cross/isolated margin modes
372
-
373
- #### **Account Management**
374
- - ✅ **API Key Generation** - Generate new API keys for trading
375
- - ✅ **API Key Management** - Change API keys and manage permissions
376
- - ✅ **Account Information** - Retrieve account details, positions, and balances
377
- - ✅ **Nonce Management** - Automatic nonce handling for transactions
378
-
379
- #### **Real-time Data**
380
- - ✅ **WebSocket Client** - Real-time order book, trades, and account updates
381
- - **Order Book Data** - Live market depth and price levels
382
- - ✅ **Trade Data** - Recent trades and execution information
383
- - **Account Updates** - Real-time position and balance updates
384
-
385
- #### **API Coverage**
386
- - **AccountApi** - Complete account management endpoints
387
- - ✅ **OrderApi** - Order book, trades, and exchange statistics
388
- - **TransactionApi** - Transaction history and nonce management
389
- - ✅ **BlockApi** - Block information and current height
390
- - ✅ **CandlestickApi** - Historical price data and funding rates
391
-
392
- #### **Technical Features**
393
- - ✅ **WASM Signer** - Go-compiled WebAssembly for cryptographic operations
394
- - ✅ **Cross-Platform** - Windows, Linux, macOS support
395
- - ✅ **TypeScript Support** - Complete type definitions and IntelliSense
396
- - **Error Handling** - Comprehensive error handling and validation
397
- - ✅ **Chain ID Support** - Correct mainnet chain ID (304) integration
398
-
399
- ### 🔧 **Technical Implementation**
400
-
401
- #### **WASM Signer Capabilities**
402
- - ✅ **Transaction Signing** - All transaction types properly signed
403
- - ✅ **Signature Validation** - Server-side signature verification working
404
- - ✅ **Order Expiry Handling** - Correct OrderExpiry and ExpiredAt management
405
- - **Field Validation** - Proper field names and types (MarketIndex, USDCAmount, etc.)
406
- - ✅ **Memo Support** - 32-byte memo field for transfers
407
- - ✅ **Margin Mode Support** - Cross and isolated margin mode handling
408
-
409
- #### **API Integration**
410
- - ✅ **sendTxWithIndices** - Correct API endpoint for transaction submission
411
- - ✅ **Authentication** - API key-based authentication working
412
- - ✅ **Rate Limiting** - Proper request handling and retry logic
413
- - ✅ **Error Codes** - Complete error code handling (21120, 21505, etc.)
414
-
415
- ### 📋 **What's Working in Production**
416
-
417
- 1. **Complete Trading Flow**
418
- - Generate API keys → Create orders → Monitor positions → Cancel orders
419
- - All order types (market, limit) with proper time in force
420
- - Real-time order book and trade data via WebSocket
421
-
422
- 2. **Account Operations**
423
- - USDC transfers between accounts
424
- - Leverage updates for risk management
425
- - API key rotation and management
426
-
427
- 3. **Cross-Platform Compatibility**
428
- - Node.js 16+ support across all platforms
429
- - Browser compatibility with WebAssembly
430
- - TypeScript 4.5+ support
431
-
432
- ### 🚀 **Performance Optimizations (v1.0.1)**
433
-
434
- #### **Implemented Optimizations**
435
- - ⚡ **~200ms Performance Improvement** - Optimized WASM initialization and path resolution
436
- - ⚡ **Automatic Path Resolution** - Fixed WASM file path issues in NPM packages
437
- - ⚡ **Enhanced Nonce Caching** - Improved transaction throughput with smart nonce management
438
- - ⚡ **Connection Pooling** - Optimized HTTP client with keep-alive connections
439
- - ⚡ **Memory Pool Management** - Reduced memory allocation overhead
440
- - ⚡ **Request Batching** - Batch multiple operations for better performance
441
- - ⚡ **Advanced Caching** - Intelligent caching for frequently accessed data
442
-
443
- #### **Additional Order Types**
444
- - ✅ **Stop Loss Orders** - Market orders triggered by price levels
445
- - ✅ **Stop Loss Limit Orders** - Limit orders triggered by price levels
446
- - ✅ **Take Profit Orders** - Market orders for profit taking
447
- - ✅ **Take Profit Limit Orders** - Limit orders for profit taking
448
- - ✅ **TWAP Orders** - Time-weighted average price orders
449
-
450
- #### **Enhanced Examples**
451
- - 📚 **Performance Testing** - Comprehensive performance benchmarking
452
- - 📚 **Advanced Order Management** - Stop-loss and take-profit examples
453
- - 📚 **Batch Operations** - Multiple order creation examples
454
- - 📚 **WebSocket Optimization** - Real-time data streaming examples
455
- - 📚 **Error Handling** - Comprehensive error handling patterns
456
-
457
- ### 🔄 **Next Release Features**
458
-
459
- #### **Planned Enhancements**
460
- - 🔄 **Additional Order Types** - More advanced order types
461
- - 🔄 **Enhanced Error Recovery** - Improved error handling and recovery
462
- - 🔄 **Additional WebSocket Subscriptions** - More real-time data streams
463
- - 🔄 **Enhanced Documentation** - More comprehensive guides
464
- - 🔄 **Unit Tests** - Complete test coverage
465
- - 🔄 **Integration Tests** - End-to-end testing
466
- - 🔄 **CI/CD Pipeline** - Automated testing and deployment
467
-
468
- ### 🎯 **Current Version: 1.0.2 (Unofficial Release)**
469
-
470
- **⚠️ Community-Built SDK**
471
- - This is an **unofficial** TypeScript SDK built by the community
472
- - Not officially maintained by Lighter Protocol team
473
- - Built with full feature parity to the official Python SDK
474
- - Ready for production use with comprehensive testing
475
-
476
- **Ready for Production Use**
477
- - All core trading functionality implemented and tested
478
- - Complete API coverage matching Python SDK
479
- - Cross-platform compatibility verified
480
- - Comprehensive documentation and examples
481
- - TypeScript support with full type definitions
482
-
483
- **Installation**: `npm install lighter-ts-sdk`
484
-
485
- **Documentation**: Complete API reference and getting started guides included
486
-
487
- **Support**: Full feature parity with Python SDK, ready for production trading
1
+ # Lighter Protocol TypeScript SDK (Unofficial)
2
+
3
+ > **⚠️ Disclaimer**: This is an **unofficial** TypeScript SDK for Lighter Protocol, built by the community. It is not officially maintained by the Lighter Protocol team.
4
+
5
+ A complete TypeScript SDK for Lighter Protocol - trade perpetual futures with built-in stop-loss and take-profit orders, position management, and comprehensive error handling.
6
+
7
+ ## 📦 Installation
8
+
9
+ ```bash
10
+ npm install lighter-ts-sdk
11
+ # or
12
+ yarn add lighter-ts-sdk
13
+ ```
14
+
15
+ ## 🚀 What Does This SDK Do?
16
+
17
+ The Lighter TypeScript SDK provides everything you need to:
18
+ - **Trade perpetual futures** on Lighter Protocol
19
+ - **Create orders** (Market, Limit, TWAP) with automatic SL/TP
20
+ - **Manage positions** (open, close, update leverage)
21
+ - **Transfer funds** between accounts
22
+ - **Monitor transactions** with built-in status tracking
23
+ - **Handle errors** automatically with retry logic
24
+
25
+ ## 🎯 Getting Started
26
+
27
+ ### Step 1: Set Up Your Environment
28
+
29
+ Create a `.env` file in your project root:
30
+
31
+ ```bash
32
+ # Required credentials
33
+ API_PRIVATE_KEY=your_private_key_here
34
+ ACCOUNT_INDEX=0
35
+ API_KEY_INDEX=0
36
+ BASE_URL=https://mainnet.zklighter.elliot.ai
37
+
38
+ # Optional: for specific examples
39
+ MARKET_ID=0
40
+ SUB_ACCOUNT_INDEX=1
41
+ DEPOSIT_AMOUNT=1
42
+ ```
43
+
44
+ ### Step 2: Install the SDK
45
+
46
+ ```bash
47
+ npm install lighter-ts-sdk
48
+ ```
49
+
50
+ ### Step 3: Your First Trade
51
+
52
+ ```typescript
53
+ import { SignerClient, OrderType } from 'lighter-ts-sdk';
54
+ import dotenv from 'dotenv';
55
+
56
+ dotenv.config();
57
+
58
+ async function placeOrder() {
59
+ // Initialize the client
60
+ const signerClient = new SignerClient({
61
+ url: process.env.BASE_URL!,
62
+ privateKey: process.env.API_PRIVATE_KEY!,
63
+ accountIndex: parseInt(process.env.ACCOUNT_INDEX!),
64
+ apiKeyIndex: parseInt(process.env.API_KEY_INDEX!)
65
+ });
66
+
67
+ // Initialize WASM signer (required)
68
+ await signerClient.initialize();
69
+ await signerClient.ensureWasmClient();
70
+
71
+ // Create a market order with SL/TP
72
+ const result = await signerClient.createUnifiedOrder({
73
+ marketIndex: 0, // ETH market
74
+ clientOrderIndex: Date.now(), // Unique ID
75
+ baseAmount: 10000, // 0.01 ETH (scaled: 1 ETH = 1,000,000)
76
+ isAsk: false, // BUY (true = SELL)
77
+ orderType: OrderType.MARKET,
78
+
79
+ // Slip page protection
80
+ idealPrice: 400000, // Ideal price ($4000)
81
+ maxSlippage: 0.001, // Max 0.1% slippage
82
+
83
+ // Automatic stop-loss and take-profit
84
+ stopLoss: {
85
+ triggerPrice: 380000, // Stop loss at $3800
86
+ isLimit: false // Market SL
87
+ },
88
+ takeProfit: {
89
+ triggerPrice: 420000, // Take profit at $4200
90
+ isLimit: false // Market TP
91
+ }
92
+ });
93
+
94
+ // Check if order succeeded
95
+ if (!result.success) {
96
+ console.error('❌ Order failed:', result.mainOrder.error);
97
+ return;
98
+ }
99
+
100
+ console.log('✅ Order created!');
101
+ console.log('Main order hash:', result.mainOrder.hash);
102
+ console.log('SL order hash:', result.stopLoss?.hash);
103
+ console.log('TP order hash:', result.takeProfit?.hash);
104
+
105
+ // Wait for transaction confirmation
106
+ await signerClient.waitForTransaction(result.mainOrder.hash, 30000);
107
+
108
+ await signerClient.close();
109
+ }
110
+
111
+ placeOrder().catch(console.error);
112
+ ```
113
+
114
+ ## 📚 Core Concepts
115
+
116
+ ### Understanding Price Units
117
+
118
+ Lighter uses fixed decimal scaling:
119
+ - **ETH amounts**: 1 ETH = 1,000,000 units
120
+ - **Prices**: $1 = 100 units
121
+
122
+ ```typescript
123
+ // To buy 0.01 ETH at $4000:
124
+ baseAmount: 10000 // 0.01 ETH (10,000 / 1,000,000)
125
+ price: 400000 // $4000 (400,000 / 100)
126
+ ```
127
+
128
+ ### Order Types
129
+
130
+ ```typescript
131
+ OrderType.MARKET // Executes immediately at market price
132
+ OrderType.LIMIT // Executes at your specified price
133
+ OrderType.TWAP // Executes gradually over time
134
+ ```
135
+
136
+ ### Direction (isAsk)
137
+
138
+ ```typescript
139
+ isAsk: false // BUY - You're buying ETH
140
+ isAsk: true // SELL - You're selling ETH
141
+ ```
142
+
143
+ ### Stop-Loss and Take-Profit
144
+
145
+ SL/TP orders are **automatically reduce-only** - they only close positions:
146
+
147
+ ```typescript
148
+ stopLoss: {
149
+ triggerPrice: 380000, // When price hits this, close position
150
+ isLimit: false // false = market SL, true = limit SL
151
+ },
152
+ takeProfit: {
153
+ triggerPrice: 420000, // When price hits this, take profit
154
+ isLimit: false // false = market TP, true = limit TP
155
+ }
156
+ ```
157
+
158
+ **Important**: SL/TP orders require an existing position. For Market orders, this works immediately. For Limit orders, SL/TP are created in the same batch.
159
+
160
+ **Note for TWAP orders**: TWAP orders execute over time, creating positions gradually. SL/TP cannot be created in the same batch as TWAP orders. You should create SL/TP orders separately after the TWAP has started creating positions.
161
+
162
+ ## 🔧 Common Operations
163
+
164
+ ### Create a Market Order
165
+
166
+ ```typescript
167
+ const result = await signerClient.createUnifiedOrder({
168
+ marketIndex: 0,
169
+ clientOrderIndex: Date.now(),
170
+ baseAmount: 10000, // Amount (0.01 ETH)
171
+ idealPrice: 400000, // Your target price ($4000)
172
+ maxSlippage: 0.001, // 0.1% max slippage
173
+ isAsk: false, // BUY
174
+ orderType: OrderType.MARKET
175
+ });
176
+
177
+ if (!result.success) {
178
+ console.error('Failed:', result.mainOrder.error);
179
+ return;
180
+ }
181
+ ```
182
+
183
+ ### Create a Limit Order
184
+
185
+ ```typescript
186
+ const result = await signerClient.createUnifiedOrder({
187
+ marketIndex: 0,
188
+ clientOrderIndex: Date.now(),
189
+ baseAmount: 10000, // Amount (0.01 ETH)
190
+ price: 400000, // Limit price ($4000)
191
+ isAsk: false, // BUY
192
+ orderType: OrderType.LIMIT,
193
+ orderExpiry: Date.now() + (60 * 60 * 1000) // Expires in 1 hour
194
+ });
195
+
196
+ // Wait for it to fill
197
+ if (result.success) {
198
+ await signerClient.waitForTransaction(result.mainOrder.hash);
199
+ }
200
+ ```
201
+
202
+ ### Cancel an Order
203
+
204
+ ```typescript
205
+ const [tx, hash, error] = await signerClient.cancelOrder({
206
+ marketIndex: 0,
207
+ orderIndex: 12345 // Your order's index
208
+ });
209
+
210
+ if (error) {
211
+ console.error('Cancel failed:', error);
212
+ return;
213
+ }
214
+
215
+ await signerClient.waitForTransaction(hash);
216
+ console.log('✅ Order cancelled');
217
+ ```
218
+
219
+ ### Close a Position
220
+
221
+ ```typescript
222
+ const [tx, hash, error] = await signerClient.createMarketOrder({
223
+ marketIndex: 0,
224
+ clientOrderIndex: Date.now(),
225
+ baseAmount: 10000, // Position size to close
226
+ avgExecutionPrice: 400000,
227
+ isAsk: false, // Opposite of position
228
+ reduceOnly: true // IMPORTANT: Only closes, doesn't open new
229
+ });
230
+
231
+ if (error) {
232
+ console.error('Close failed:', error);
233
+ return;
234
+ }
235
+
236
+ await signerClient.waitForTransaction(hash);
237
+ console.log('✅ Position closed');
238
+ ```
239
+
240
+ ### Check Order Status
241
+
242
+ ```typescript
243
+ const status = await signerClient.getTransaction(txHash);
244
+ console.log('Status:', status.status); // 0=pending, 1=queued, 2=committed, 3=executed
245
+ ```
246
+
247
+ ## 🛠️ API Reference
248
+
249
+ ### SignerClient Methods
250
+
251
+ #### Order Management
252
+ ```typescript
253
+ // Create a unified order (main order + SL/TP)
254
+ createUnifiedOrder(params) -> Promise<UnifiedOrderResult>
255
+
256
+ // Create a single order
257
+ createOrder(params) -> Promise<[txInfo, txHash, error]>
258
+
259
+ // Cancel a specific order
260
+ cancelOrder(params) -> Promise<[txInfo, txHash, error]>
261
+
262
+ // Cancel all orders
263
+ cancelAllOrders(timeInForce, time) -> Promise<[txInfo, txHash, error]>
264
+ ```
265
+
266
+ #### Position Management
267
+ ```typescript
268
+ // Close specific position
269
+ createMarketOrder({ reduceOnly: true }) -> Promise<[txInfo, txHash, error]>
270
+
271
+ // Close all positions
272
+ closeAllPositions() -> Promise<[txs[], responses[], errors[]]>
273
+ ```
274
+
275
+ #### Transaction Monitoring
276
+ ```typescript
277
+ // Get transaction details
278
+ getTransaction(txHash) -> Promise<Transaction>
279
+
280
+ // Wait for transaction (with timeout)
281
+ waitForTransaction(txHash, maxWaitTime, pollInterval) -> Promise<Transaction>
282
+ ```
283
+
284
+ ### Order Parameters
285
+
286
+ ```typescript
287
+ interface UnifiedOrderParams {
288
+ marketIndex: number; // Market ID (0 = ETH)
289
+ clientOrderIndex: number; // Unique ID (use Date.now())
290
+ baseAmount: number; // Amount in units (1 ETH = 1,000,000)
291
+ isAsk: boolean; // true = SELL, false = BUY
292
+ orderType: OrderType; // MARKET, LIMIT, or TWAP
293
+
294
+ // For market orders
295
+ idealPrice?: number; // Target price
296
+ maxSlippage?: number; // Max slippage (e.g., 0.001 = 0.1%)
297
+
298
+ // For limit orders
299
+ price?: number; // Limit price
300
+
301
+ // Optional SL/TP (automatically reduce-only)
302
+ stopLoss?: {
303
+ triggerPrice: number;
304
+ isLimit?: boolean;
305
+ };
306
+ takeProfit?: {
307
+ triggerPrice: number;
308
+ isLimit?: boolean;
309
+ };
310
+
311
+ // Optional
312
+ orderExpiry?: number; // Expiry timestamp (milliseconds)
313
+ }
314
+ ```
315
+
316
+ ## 💡 Tips for Beginners
317
+
318
+ ### 1. Always Use Environment Variables
319
+
320
+ ```typescript
321
+ // DON'T hardcode credentials
322
+ const privateKey = '0xabc123...';
323
+
324
+ // ✅ DO use environment variables
325
+ const privateKey = process.env.API_PRIVATE_KEY;
326
+ ```
327
+
328
+ ### 2. Handle Errors Properly
329
+
330
+ ```typescript
331
+ try {
332
+ const result = await signerClient.createUnifiedOrder(params);
333
+
334
+ if (!result.success) {
335
+ console.error('Order failed:', result.mainOrder.error);
336
+ return; // Exit early
337
+ }
338
+
339
+ // Success path
340
+ console.log('Order created:', result.mainOrder.hash);
341
+ } catch (error) {
342
+ console.error('Unexpected error:', error);
343
+ }
344
+ ```
345
+
346
+ ### 3. Check Transaction Status
347
+
348
+ ```typescript
349
+ // Wait for transaction to be confirmed
350
+ try {
351
+ await signerClient.waitForTransaction(txHash, 30000, 2000);
352
+ console.log('✅ Transaction confirmed');
353
+ } catch (error) {
354
+ console.error('❌ Transaction failed:', error.message);
355
+ }
356
+ ```
357
+
358
+ ### 4. Close Resources
359
+
360
+ ```typescript
361
+ try {
362
+ // ... use signerClient
363
+ } finally {
364
+ await signerClient.close(); // Always close when done
365
+ }
366
+ ```
367
+
368
+ ## 📖 Examples
369
+
370
+ The `examples/` directory contains working examples for every feature:
371
+
372
+ ```bash
373
+ # Run examples
374
+ npx ts-node examples/create_market_order.ts # Market order with SL/TP
375
+ npx ts-node examples/create_limit_order.ts # Limit order with SL/TP
376
+ npx ts-node examples/cancel_order.ts # Cancel orders
377
+ npx ts-node examples/close_position.ts # Close positions
378
+ npx ts-node examples/deposit_to_subaccount.ts # Fund transfers
379
+ ```
380
+
381
+ ## 🎓 Learning Path
382
+
383
+ 1. **Start Here**: `examples/create_market_order.ts` - Simplest order creation
384
+ 2. **Next**: `examples/create_limit_order.ts` - Learn about limit orders
385
+ 3. **Then**: `examples/cancel_order.ts` - Learn about order management
386
+ 4. **Advanced**: `examples/send_tx_batch.ts` - Batch transactions
387
+
388
+ ## 🔒 Security
389
+
390
+ - ✅ Never commit `.env` files
391
+ - ✅ Use environment variables for all credentials
392
+ - Test with small amounts first
393
+ - ✅ Monitor all transactions
394
+ - ✅ Use proper error handling
395
+
396
+ ## 📞 Getting Help
397
+
398
+ - Check the examples in `examples/` directory
399
+ - Read error messages carefully - they're informative
400
+ - Ensure environment variables are set correctly
401
+ - Start with `examples/create_market_order.ts`
402
+
403
+ ## License
404
+
405
+ MIT License - see LICENSE file for details.