lighter-ts-sdk 1.0.5 → 1.0.7

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 (220) hide show
  1. package/README.md +476 -487
  2. package/dist/api/account-api.d.ts +24 -2
  3. package/dist/api/account-api.d.ts.map +1 -1
  4. package/dist/api/account-api.js +11 -0
  5. package/dist/api/account-api.js.map +1 -1
  6. package/dist/api/announcement-api.d.ts +27 -0
  7. package/dist/api/announcement-api.d.ts.map +1 -0
  8. package/dist/api/announcement-api.js +25 -0
  9. package/dist/api/announcement-api.js.map +1 -0
  10. package/dist/api/api-client.d.ts.map +1 -1
  11. package/dist/api/api-client.js +15 -0
  12. package/dist/api/api-client.js.map +1 -1
  13. package/dist/api/bridge-api.d.ts +78 -0
  14. package/dist/api/bridge-api.d.ts.map +1 -0
  15. package/dist/api/bridge-api.js +137 -0
  16. package/dist/api/bridge-api.js.map +1 -0
  17. package/dist/api/funding-api.d.ts +28 -0
  18. package/dist/api/funding-api.d.ts.map +1 -0
  19. package/dist/api/funding-api.js +25 -0
  20. package/dist/api/funding-api.js.map +1 -0
  21. package/dist/api/notification-api.d.ts +27 -0
  22. package/dist/api/notification-api.d.ts.map +1 -0
  23. package/dist/api/notification-api.js +49 -0
  24. package/dist/api/notification-api.js.map +1 -0
  25. package/dist/api/order-api.d.ts +97 -14
  26. package/dist/api/order-api.d.ts.map +1 -1
  27. package/dist/api/order-api.js +15 -9
  28. package/dist/api/order-api.js.map +1 -1
  29. package/dist/api/referral-api.d.ts +37 -0
  30. package/dist/api/referral-api.d.ts.map +1 -0
  31. package/dist/api/referral-api.js +45 -0
  32. package/dist/api/referral-api.js.map +1 -0
  33. package/dist/api/transaction-api.d.ts +49 -6
  34. package/dist/api/transaction-api.d.ts.map +1 -1
  35. package/dist/api/transaction-api.js +58 -10
  36. package/dist/api/transaction-api.js.map +1 -1
  37. package/dist/api/ws-client.d.ts.map +1 -1
  38. package/dist/api/ws-client.js +7 -9
  39. package/dist/api/ws-client.js.map +1 -1
  40. package/dist/api/ws-order-client.d.ts +8 -2
  41. package/dist/api/ws-order-client.d.ts.map +1 -1
  42. package/dist/api/ws-order-client.js +249 -62
  43. package/dist/api/ws-order-client.js.map +1 -1
  44. package/dist/bridge/l1-bridge-client.d.ts +49 -0
  45. package/dist/bridge/l1-bridge-client.d.ts.map +1 -0
  46. package/dist/bridge/l1-bridge-client.js +187 -0
  47. package/dist/bridge/l1-bridge-client.js.map +1 -0
  48. package/dist/index.d.ts +27 -14
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +52 -18
  51. package/dist/index.js.map +1 -1
  52. package/dist/{utils → signer}/wasm-manager.d.ts +1 -2
  53. package/dist/signer/wasm-manager.d.ts.map +1 -0
  54. package/dist/{utils → signer}/wasm-manager.js +1 -2
  55. package/dist/signer/wasm-manager.js.map +1 -0
  56. package/dist/signer/wasm-signer-client.d.ts +328 -36
  57. package/dist/signer/wasm-signer-client.d.ts.map +1 -1
  58. package/dist/signer/wasm-signer-client.js +1713 -367
  59. package/dist/signer/wasm-signer-client.js.map +1 -1
  60. package/dist/signer/wasm-signer.d.ts +361 -0
  61. package/dist/signer/wasm-signer.d.ts.map +1 -0
  62. package/dist/signer/wasm-signer.js +814 -0
  63. package/dist/signer/wasm-signer.js.map +1 -0
  64. package/dist/types/api.d.ts +181 -0
  65. package/dist/types/api.d.ts.map +1 -0
  66. package/dist/types/api.js +7 -0
  67. package/dist/types/api.js.map +1 -0
  68. package/dist/types/config.d.ts +66 -0
  69. package/dist/types/config.d.ts.map +1 -0
  70. package/dist/types/config.js +7 -0
  71. package/dist/types/config.js.map +1 -0
  72. package/dist/types/generated/openapi.d.ts +5008 -0
  73. package/dist/types/generated/openapi.d.ts.map +1 -0
  74. package/dist/types/generated/openapi.js +7 -0
  75. package/dist/types/generated/openapi.js.map +1 -0
  76. package/dist/types/index.d.ts +31 -129
  77. package/dist/types/index.d.ts.map +1 -1
  78. package/dist/types/index.js +21 -0
  79. package/dist/types/index.js.map +1 -1
  80. package/dist/types/trading.d.ts +43 -0
  81. package/dist/types/trading.d.ts.map +1 -0
  82. package/dist/types/trading.js +25 -0
  83. package/dist/types/trading.js.map +1 -0
  84. package/dist/types/transaction.d.ts +57 -0
  85. package/dist/types/transaction.d.ts.map +1 -0
  86. package/dist/types/transaction.js +29 -0
  87. package/dist/types/transaction.js.map +1 -0
  88. package/dist/utils/exceptions.js +1 -1
  89. package/dist/utils/exceptions.js.map +1 -1
  90. package/dist/utils/index.d.ts +14 -0
  91. package/dist/utils/index.d.ts.map +1 -0
  92. package/dist/utils/index.js +38 -0
  93. package/dist/utils/index.js.map +1 -0
  94. package/dist/utils/logger.js +3 -3
  95. package/dist/utils/logger.js.map +1 -1
  96. package/dist/utils/market-helper.d.ts +62 -0
  97. package/dist/utils/market-helper.d.ts.map +1 -0
  98. package/dist/utils/market-helper.js +100 -0
  99. package/dist/utils/market-helper.js.map +1 -0
  100. package/dist/utils/nonce-cache.d.ts +9 -1
  101. package/dist/utils/nonce-cache.d.ts.map +1 -1
  102. package/dist/utils/nonce-cache.js +28 -1
  103. package/dist/utils/nonce-cache.js.map +1 -1
  104. package/dist/utils/nonce-manager.d.ts +79 -0
  105. package/dist/utils/nonce-manager.d.ts.map +1 -0
  106. package/dist/utils/nonce-manager.js +130 -0
  107. package/dist/utils/nonce-manager.js.map +1 -0
  108. package/dist/utils/order-status-checker.d.ts +29 -0
  109. package/dist/utils/order-status-checker.d.ts.map +1 -0
  110. package/dist/utils/order-status-checker.js +101 -0
  111. package/dist/utils/order-status-checker.js.map +1 -0
  112. package/dist/utils/price-utils.d.ts +86 -0
  113. package/dist/utils/price-utils.d.ts.map +1 -0
  114. package/dist/utils/price-utils.js +229 -0
  115. package/dist/utils/price-utils.js.map +1 -0
  116. package/dist/utils/request-batcher.d.ts.map +1 -1
  117. package/dist/utils/request-batcher.js +4 -7
  118. package/dist/utils/request-batcher.js.map +1 -1
  119. package/docs/API.md +207 -195
  120. package/docs/AccountApi.md +278 -220
  121. package/docs/GettingStarted.md +361 -262
  122. package/docs/MarketHelper.md +214 -0
  123. package/docs/MigrationGuide.md +401 -0
  124. package/docs/OrderApi.md +353 -199
  125. package/docs/SignerClient.md +626 -326
  126. package/docs/TransactionApi.md +474 -312
  127. package/docs/Utilities.md +268 -0
  128. package/docs/WsClient.md +219 -164
  129. package/docs/types/SignerConfig.md +40 -40
  130. package/docs/types/WasmSignerConfig.md +9 -8
  131. package/examples/README.md +202 -216
  132. package/examples/cancel_all_orders.ts +112 -79
  133. package/examples/cancel_order.ts +44 -124
  134. package/examples/change_account_tier.ts +82 -0
  135. package/examples/close_all_positions.ts +378 -43
  136. package/examples/close_position.ts +164 -164
  137. package/examples/create_auth_token.ts +57 -121
  138. package/examples/create_limit_order.ts +178 -67
  139. package/examples/create_market_order.ts +159 -48
  140. package/examples/create_subaccount.ts +78 -0
  141. package/examples/create_twap_order.ts +101 -0
  142. package/examples/create_with_multiple_keys.ts +101 -76
  143. package/examples/deposit_to_subaccount.ts +104 -0
  144. package/examples/market_data.ts +174 -0
  145. package/examples/modify_order.ts +250 -0
  146. package/examples/multi_client_advanced.ts +251 -0
  147. package/examples/public_pool_operations.ts +150 -0
  148. package/examples/send_tx_batch.ts +92 -67
  149. package/examples/spot/README.md +85 -0
  150. package/examples/spot/cancel_spot_order.ts +89 -0
  151. package/examples/spot/create_market_spot_orders.ts +259 -0
  152. package/examples/spot/create_spot_limit_order.ts +122 -0
  153. package/examples/spot/create_spot_twap_order.ts +102 -0
  154. package/examples/system_setup.ts +168 -159
  155. package/examples/update_margin.ts +99 -0
  156. package/examples/update_margin_leverage.ts +110 -0
  157. package/examples/withdraw_to_l1.ts +68 -0
  158. package/examples/ws.ts +67 -64
  159. package/examples/ws_async.ts +107 -40
  160. package/examples/ws_ping_pong.ts +260 -0
  161. package/examples/ws_send_batch_tx.ts +211 -94
  162. package/examples/ws_send_tx.ts +137 -76
  163. package/package.json +1 -1
  164. package/wasm/lighter-signer.wasm +0 -0
  165. package/dist/signer/signer-client.d.ts +0 -79
  166. package/dist/signer/signer-client.d.ts.map +0 -1
  167. package/dist/signer/signer-client.js +0 -212
  168. package/dist/signer/signer-client.js.map +0 -1
  169. package/dist/utils/advanced-cache.d.ts +0 -66
  170. package/dist/utils/advanced-cache.d.ts.map +0 -1
  171. package/dist/utils/advanced-cache.js +0 -199
  172. package/dist/utils/advanced-cache.js.map +0 -1
  173. package/dist/utils/api-key-utils.d.ts +0 -7
  174. package/dist/utils/api-key-utils.d.ts.map +0 -1
  175. package/dist/utils/api-key-utils.js +0 -31
  176. package/dist/utils/api-key-utils.js.map +0 -1
  177. package/dist/utils/memory-pool.d.ts +0 -98
  178. package/dist/utils/memory-pool.d.ts.map +0 -1
  179. package/dist/utils/memory-pool.js +0 -190
  180. package/dist/utils/memory-pool.js.map +0 -1
  181. package/dist/utils/node-wasm-signer.d.ts +0 -163
  182. package/dist/utils/node-wasm-signer.d.ts.map +0 -1
  183. package/dist/utils/node-wasm-signer.js +0 -409
  184. package/dist/utils/node-wasm-signer.js.map +0 -1
  185. package/dist/utils/optimized-http-client.d.ts +0 -29
  186. package/dist/utils/optimized-http-client.d.ts.map +0 -1
  187. package/dist/utils/optimized-http-client.js +0 -142
  188. package/dist/utils/optimized-http-client.js.map +0 -1
  189. package/dist/utils/performance-monitor.d.ts +0 -41
  190. package/dist/utils/performance-monitor.d.ts.map +0 -1
  191. package/dist/utils/performance-monitor.js +0 -168
  192. package/dist/utils/performance-monitor.js.map +0 -1
  193. package/dist/utils/signer-server.d.ts +0 -18
  194. package/dist/utils/signer-server.d.ts.map +0 -1
  195. package/dist/utils/signer-server.js +0 -78
  196. package/dist/utils/signer-server.js.map +0 -1
  197. package/dist/utils/transaction-helper.d.ts +0 -37
  198. package/dist/utils/transaction-helper.d.ts.map +0 -1
  199. package/dist/utils/transaction-helper.js +0 -174
  200. package/dist/utils/transaction-helper.js.map +0 -1
  201. package/dist/utils/wasm-manager.d.ts.map +0 -1
  202. package/dist/utils/wasm-manager.js.map +0 -1
  203. package/dist/utils/wasm-signer.d.ts +0 -158
  204. package/dist/utils/wasm-signer.d.ts.map +0 -1
  205. package/dist/utils/wasm-signer.js +0 -214
  206. package/dist/utils/wasm-signer.js.map +0 -1
  207. package/examples/account_info.ts +0 -15
  208. package/examples/check_transaction_status.ts +0 -159
  209. package/examples/create_cancel_order.ts +0 -113
  210. package/examples/create_market_order_if_slippage.ts +0 -68
  211. package/examples/create_market_order_max_slippage.ts +0 -42
  212. package/examples/create_sl_tp.ts +0 -165
  213. package/examples/deposit_to_subaccounts.ts +0 -146
  214. package/examples/get_info.ts +0 -63
  215. package/examples/get_points.ts +0 -61
  216. package/examples/market_data_json.ts +0 -80
  217. package/examples/nonce_manager.ts +0 -264
  218. package/examples/transfer_update_leverage.ts +0 -52
  219. package/examples/wait_for_transaction.ts +0 -100
  220. package/examples/withdraw.ts +0 -118
package/README.md CHANGED
@@ -1,487 +1,476 @@
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
+ ## 🔐 Signer Integration
8
+
9
+ This SDK uses the **official lighter-go WASM signer** from [elliottech/lighter-go](https://github.com/elliottech/lighter-go) for all cryptographic operations. The WASM signer is automatically compiled from the GitHub repository during the build process.
10
+
11
+ **Key Features:**
12
+ - Uses official lighter-go signer (reference implementation)
13
+ - ✅ Automatic error recovery and nonce management
14
+ - Support for all transaction types
15
+ - ✅ Multiple API key support
16
+ - ✅ Production-ready and battle-tested
17
+
18
+ ## 📦 Installation
19
+
20
+ ```bash
21
+ npm install lighter-ts-sdk
22
+ # or
23
+ yarn add lighter-ts-sdk
24
+ ```
25
+
26
+ ## 🚀 What Does This SDK Do?
27
+
28
+ The Lighter TypeScript SDK provides everything you need to:
29
+ - **Trade perpetual futures** on Lighter Protocol
30
+ - **Create orders** (Market, Limit, TWAP) with automatic SL/TP
31
+ - **Manage positions** (open, close, update leverage)
32
+ - **Transfer funds** between accounts
33
+ - **Monitor transactions** with built-in status tracking
34
+ - **Handle errors** automatically with retry logic
35
+
36
+ ## 🎯 Getting Started
37
+
38
+ ### Step 1: Set Up Your Environment
39
+
40
+ Create a `.env` file in your project root:
41
+
42
+ ```bash
43
+ # Required credentials
44
+ API_PRIVATE_KEY=your_private_key_here
45
+ ACCOUNT_INDEX=0
46
+ API_KEY_INDEX=0
47
+ BASE_URL=https://mainnet.zklighter.elliot.ai
48
+
49
+ # Optional: for specific examples
50
+ MARKET_ID=0
51
+ SUB_ACCOUNT_INDEX=1
52
+ DEPOSIT_AMOUNT=1
53
+ ```
54
+
55
+ ### Step 2: Install the SDK
56
+
57
+ ```bash
58
+ npm install lighter-ts-sdk
59
+ ```
60
+
61
+ ### Step 3: Your First Trade
62
+
63
+ ```typescript
64
+ import { SignerClient, OrderType } from 'lighter-ts-sdk';
65
+ import dotenv from 'dotenv';
66
+
67
+ dotenv.config();
68
+
69
+ async function placeOrder() {
70
+ // Initialize the client
71
+ const signerClient = new SignerClient({
72
+ url: process.env.BASE_URL!,
73
+ privateKey: process.env.API_PRIVATE_KEY!,
74
+ accountIndex: parseInt(process.env.ACCOUNT_INDEX!),
75
+ apiKeyIndex: parseInt(process.env.API_KEY_INDEX!)
76
+ });
77
+
78
+ // Initialize WASM signer (required)
79
+ await signerClient.initialize();
80
+ await signerClient.ensureWasmClient();
81
+
82
+ // Create a market order with SL/TP
83
+ const result = await signerClient.createUnifiedOrder({
84
+ marketIndex: 0, // ETH market
85
+ clientOrderIndex: Date.now(), // Unique ID
86
+ baseAmount: 10000, // 0.01 ETH (scaled: 1 ETH = 1,000,000)
87
+ isAsk: false, // BUY (true = SELL)
88
+ orderType: OrderType.MARKET,
89
+
90
+ // Slip page protection
91
+ idealPrice: 400000, // Ideal price ($4000)
92
+ maxSlippage: 0.001, // Max 0.1% slippage
93
+
94
+ // Automatic stop-loss and take-profit
95
+ stopLoss: {
96
+ triggerPrice: 380000, // Stop loss at $3800
97
+ isLimit: false // Market SL
98
+ },
99
+ takeProfit: {
100
+ triggerPrice: 420000, // Take profit at $4200
101
+ isLimit: false // Market TP
102
+ }
103
+ });
104
+
105
+ // Check if order succeeded
106
+ if (!result.success) {
107
+ console.error('❌ Order failed:', result.mainOrder.error);
108
+ return;
109
+ }
110
+
111
+ console.log('Order created!');
112
+ console.log('Main order hash:', result.mainOrder.hash);
113
+ console.log('SL order hash:', result.stopLoss?.hash);
114
+ console.log('TP order hash:', result.takeProfit?.hash);
115
+
116
+ // Wait for transaction confirmation
117
+ await signerClient.waitForTransaction(result.mainOrder.hash, 30000);
118
+
119
+ await signerClient.close();
120
+ }
121
+
122
+ placeOrder().catch(console.error);
123
+ ```
124
+
125
+ ## 📚 Core Concepts
126
+
127
+ ### Understanding Price Units
128
+
129
+ Lighter uses fixed decimal scaling:
130
+ - **ETH amounts**: 1 ETH = 1,000,000 units
131
+ - **Prices**: $1 = 100 units
132
+
133
+ ```typescript
134
+ // To buy 0.01 ETH at $4000:
135
+ baseAmount: 10000 // 0.01 ETH (10,000 / 1,000,000)
136
+ price: 400000 // $4000 (400,000 / 100)
137
+ ```
138
+
139
+ ### Order Types
140
+
141
+ ```typescript
142
+ OrderType.MARKET // Executes immediately at market price
143
+ OrderType.LIMIT // Executes at your specified price
144
+ OrderType.TWAP // Executes gradually over time
145
+ ```
146
+
147
+ ### Direction (isAsk)
148
+
149
+ ```typescript
150
+ isAsk: false // BUY - You're buying ETH
151
+ isAsk: true // SELL - You're selling ETH
152
+ ```
153
+
154
+ ### Stop-Loss and Take-Profit
155
+
156
+ SL/TP orders are **automatically reduce-only** - they only close positions:
157
+
158
+ ```typescript
159
+ stopLoss: {
160
+ triggerPrice: 380000, // When price hits this, close position
161
+ isLimit: false // false = market SL, true = limit SL
162
+ },
163
+ takeProfit: {
164
+ triggerPrice: 420000, // When price hits this, take profit
165
+ isLimit: false // false = market TP, true = limit TP
166
+ }
167
+ ```
168
+
169
+ **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.
170
+
171
+ **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.
172
+
173
+ ## 🔧 Common Operations
174
+
175
+ ### Create a Market Order
176
+
177
+ ```typescript
178
+ const result = await signerClient.createUnifiedOrder({
179
+ marketIndex: 0,
180
+ clientOrderIndex: Date.now(),
181
+ baseAmount: 10000, // Amount (0.01 ETH)
182
+ idealPrice: 400000, // Your target price ($4000)
183
+ maxSlippage: 0.001, // 0.1% max slippage
184
+ isAsk: false, // BUY
185
+ orderType: OrderType.MARKET
186
+ });
187
+
188
+ if (!result.success) {
189
+ console.error('Failed:', result.mainOrder.error);
190
+ return;
191
+ }
192
+ ```
193
+
194
+ ### Create a Limit Order
195
+
196
+ ```typescript
197
+ const result = await signerClient.createUnifiedOrder({
198
+ marketIndex: 0,
199
+ clientOrderIndex: Date.now(),
200
+ baseAmount: 10000, // Amount (0.01 ETH)
201
+ price: 400000, // Limit price ($4000)
202
+ isAsk: false, // BUY
203
+ orderType: OrderType.LIMIT,
204
+ orderExpiry: Date.now() + (60 * 60 * 1000) // Expires in 1 hour
205
+ });
206
+
207
+ // Wait for it to fill
208
+ if (result.success) {
209
+ await signerClient.waitForTransaction(result.mainOrder.hash);
210
+ }
211
+ ```
212
+
213
+ ### Cancel an Order
214
+
215
+ ```typescript
216
+ const [tx, hash, error] = await signerClient.cancelOrder({
217
+ marketIndex: 0,
218
+ orderIndex: 12345 // Your order's index
219
+ });
220
+
221
+ if (error) {
222
+ console.error('Cancel failed:', error);
223
+ return;
224
+ }
225
+
226
+ await signerClient.waitForTransaction(hash);
227
+ console.log('✅ Order cancelled');
228
+ ```
229
+
230
+ ### Close a Position
231
+
232
+ ```typescript
233
+ const [tx, hash, error] = await signerClient.createMarketOrder({
234
+ marketIndex: 0,
235
+ clientOrderIndex: Date.now(),
236
+ baseAmount: 10000, // Position size to close
237
+ avgExecutionPrice: 400000,
238
+ isAsk: false, // Opposite of position
239
+ reduceOnly: true // IMPORTANT: Only closes, doesn't open new
240
+ });
241
+
242
+ if (error) {
243
+ console.error('Close failed:', error);
244
+ return;
245
+ }
246
+
247
+ await signerClient.waitForTransaction(hash);
248
+ console.log('✅ Position closed');
249
+ ```
250
+
251
+ ### Check Order Status
252
+
253
+ ```typescript
254
+ const status = await signerClient.getTransaction(txHash);
255
+ console.log('Status:', status.status); // 0=pending, 1=queued, 2=committed, 3=executed
256
+ ```
257
+
258
+ ## 🛠️ API Reference
259
+
260
+ ### SignerClient Methods
261
+
262
+ #### Order Management
263
+ ```typescript
264
+ // Create a unified order (main order + SL/TP)
265
+ createUnifiedOrder(params) -> Promise<UnifiedOrderResult>
266
+
267
+ // Create a single order
268
+ createOrder(params) -> Promise<[txInfo, txHash, error]>
269
+
270
+ // Cancel a specific order
271
+ cancelOrder(params) -> Promise<[txInfo, txHash, error]>
272
+
273
+ // Cancel all orders
274
+ cancelAllOrders(timeInForce, time) -> Promise<[txInfo, txHash, error]>
275
+ ```
276
+
277
+ #### Position Management
278
+ ```typescript
279
+ // Close specific position
280
+ createMarketOrder({ reduceOnly: true }) -> Promise<[txInfo, txHash, error]>
281
+
282
+ // Close all positions
283
+ closeAllPositions() -> Promise<[txs[], responses[], errors[]]>
284
+ ```
285
+
286
+ #### Transaction Monitoring
287
+ ```typescript
288
+ // Get transaction details
289
+ getTransaction(txHash) -> Promise<Transaction>
290
+
291
+ // Wait for transaction (with timeout)
292
+ waitForTransaction(txHash, maxWaitTime, pollInterval) -> Promise<Transaction>
293
+ ```
294
+
295
+ ### Order Parameters
296
+
297
+ ```typescript
298
+ interface UnifiedOrderParams {
299
+ marketIndex: number; // Market ID (0 = ETH)
300
+ clientOrderIndex: number; // Unique ID (use Date.now())
301
+ baseAmount: number; // Amount in units (1 ETH = 1,000,000)
302
+ isAsk: boolean; // true = SELL, false = BUY
303
+ orderType: OrderType; // MARKET, LIMIT, or TWAP
304
+
305
+ // For market orders
306
+ idealPrice?: number; // Target price
307
+ maxSlippage?: number; // Max slippage (e.g., 0.001 = 0.1%)
308
+
309
+ // For limit orders
310
+ price?: number; // Limit price
311
+
312
+ // Optional SL/TP (automatically reduce-only)
313
+ stopLoss?: {
314
+ triggerPrice: number;
315
+ isLimit?: boolean;
316
+ };
317
+ takeProfit?: {
318
+ triggerPrice: number;
319
+ isLimit?: boolean;
320
+ };
321
+
322
+ // Optional
323
+ orderExpiry?: number; // Expiry timestamp (milliseconds)
324
+ }
325
+ ```
326
+
327
+ ## 💡 Tips for Beginners
328
+
329
+ ### 1. Always Use Environment Variables
330
+
331
+ ```typescript
332
+ // DON'T hardcode credentials
333
+ const privateKey = '0xabc123...';
334
+
335
+ // DO use environment variables
336
+ const privateKey = process.env.API_PRIVATE_KEY;
337
+ ```
338
+
339
+ ### 2. Handle Errors Properly
340
+
341
+ ```typescript
342
+ try {
343
+ const result = await signerClient.createUnifiedOrder(params);
344
+
345
+ if (!result.success) {
346
+ console.error('Order failed:', result.mainOrder.error);
347
+ return; // Exit early
348
+ }
349
+
350
+ // Success path
351
+ console.log('Order created:', result.mainOrder.hash);
352
+ } catch (error) {
353
+ console.error('Unexpected error:', error);
354
+ }
355
+ ```
356
+
357
+ ### 3. Check Transaction Status
358
+
359
+ ```typescript
360
+ // Wait for transaction to be confirmed
361
+ try {
362
+ await signerClient.waitForTransaction(txHash, 30000, 2000);
363
+ console.log('Transaction confirmed');
364
+ } catch (error) {
365
+ console.error('❌ Transaction failed:', error.message);
366
+ }
367
+ ```
368
+
369
+ ### 4. Close Resources
370
+
371
+ ```typescript
372
+ try {
373
+ // ... use signerClient
374
+ } finally {
375
+ await signerClient.close(); // Always close when done
376
+ }
377
+ ```
378
+
379
+ ## 📖 Examples
380
+
381
+ The `examples/` directory contains working examples for every feature:
382
+
383
+ ```bash
384
+ # Run examples
385
+ npx ts-node examples/create_market_order.ts # Market order with SL/TP
386
+ npx ts-node examples/create_limit_order.ts # Limit order with SL/TP
387
+ npx ts-node examples/cancel_order.ts # Cancel orders
388
+ npx ts-node examples/close_position.ts # Close positions
389
+ npx ts-node examples/deposit_to_subaccount.ts # Fund transfers
390
+ ```
391
+
392
+ ## 🎓 Learning Path
393
+
394
+ 1. **Start Here**: `examples/create_market_order.ts` - Simplest order creation
395
+ 2. **Next**: `examples/create_limit_order.ts` - Learn about limit orders
396
+ 3. **Then**: `examples/cancel_order.ts` - Learn about order management
397
+ 4. **Advanced**: `examples/send_tx_batch.ts` - Batch transactions
398
+
399
+ ## 🔒 Security
400
+
401
+ - Never commit `.env` files
402
+ - ✅ Use environment variables for all credentials
403
+ - ✅ Test with small amounts first
404
+ - ✅ Monitor all transactions
405
+ - ✅ Use proper error handling
406
+
407
+ ## 🔧 Building from Source
408
+
409
+ If you want to build the SDK from source or rebuild the WASM signer:
410
+
411
+ ```bash
412
+ # Clone the repository
413
+ git clone https://github.com/bvvvp009/lighter-ts.git
414
+ cd lighter-ts
415
+
416
+ # Install dependencies
417
+ npm install
418
+
419
+ # Build WASM signer from lighter-go GitHub repo
420
+ npm run build:wasm
421
+
422
+ # Build TypeScript
423
+ npm run build
424
+ ```
425
+
426
+ **Note**: The build script automatically clones/updates the lighter-go repository from GitHub and compiles the WASM signer. No local lighter-go folder is required.
427
+
428
+ ## 🔄 Migration from Previous Versions
429
+
430
+ If you're upgrading from an older version that used `temp-lighter-go`:
431
+
432
+ ### What Changed
433
+
434
+ - **Signer**: Now uses official `lighter-go` from GitHub instead of local `temp-lighter-go`
435
+ - **Build Process**: WASM is compiled directly from GitHub repo
436
+ - **Functions**: All transaction types now supported via lighter-go
437
+ - **Error Handling**: Improved error recovery and nonce management
438
+
439
+ ### Breaking Changes
440
+
441
+ **None!** The API remains the same. The only change is internal - the SDK now uses the official lighter-go signer.
442
+
443
+ ### Removed Functions
444
+
445
+ These functions were never officially supported and have been removed:
446
+ - `getPublicKey()` - Use `generateAPIKey()` instead (returns both keys)
447
+ - `switchAPIKey()` - Use `createClient()` with different `apiKeyIndex` values instead
448
+
449
+ ### Migration Steps
450
+
451
+ 1. **Update your code** (if using removed functions):
452
+ ```typescript
453
+ // Old (removed)
454
+ const publicKey = await client.getPublicKey(privateKey);
455
+
456
+ // New (use generateAPIKey)
457
+ const { privateKey, publicKey } = await client.generateAPIKey();
458
+ ```
459
+
460
+ 2. **Rebuild WASM** (if building from source):
461
+ ```bash
462
+ npm run build:wasm
463
+ ```
464
+
465
+ 3. **Test your integration** - All existing code should work without changes.
466
+
467
+ ## 📞 Getting Help
468
+
469
+ - Check the examples in `examples/` directory
470
+ - Read error messages carefully - they're informative
471
+ - Ensure environment variables are set correctly
472
+ - Start with `examples/create_market_order.ts`
473
+
474
+ ## License
475
+
476
+ MIT License - see LICENSE file for details.