lighter-ts-sdk 1.0.8-beta.0 β†’ 1.0.9-beta-rust.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 (138) hide show
  1. package/README.md +787 -519
  2. package/dist/api/account-api.d.ts +24 -0
  3. package/dist/api/account-api.d.ts.map +1 -1
  4. package/dist/api/account-api.js +10 -3
  5. package/dist/api/account-api.js.map +1 -1
  6. package/dist/api/api-client.d.ts.map +1 -1
  7. package/dist/api/api-client.js +16 -17
  8. package/dist/api/api-client.js.map +1 -1
  9. package/dist/api/bridge-api.d.ts.map +1 -1
  10. package/dist/api/bridge-api.js +0 -1
  11. package/dist/api/bridge-api.js.map +1 -1
  12. package/dist/api/order-api.d.ts.map +1 -1
  13. package/dist/api/order-api.js +2 -1
  14. package/dist/api/order-api.js.map +1 -1
  15. package/dist/api/transaction-api.d.ts +1 -1
  16. package/dist/api/transaction-api.d.ts.map +1 -1
  17. package/dist/api/transaction-api.js +4 -24
  18. package/dist/api/transaction-api.js.map +1 -1
  19. package/dist/api/ws-client.d.ts +0 -1
  20. package/dist/api/ws-client.d.ts.map +1 -1
  21. package/dist/api/ws-client.js +1 -39
  22. package/dist/api/ws-client.js.map +1 -1
  23. package/dist/api/ws-order-client.d.ts +0 -12
  24. package/dist/api/ws-order-client.d.ts.map +1 -1
  25. package/dist/api/ws-order-client.js +1 -48
  26. package/dist/api/ws-order-client.js.map +1 -1
  27. package/dist/bridge/l1-bridge-client.d.ts.map +1 -1
  28. package/dist/bridge/l1-bridge-client.js +0 -11
  29. package/dist/bridge/l1-bridge-client.js.map +1 -1
  30. package/dist/index.d.ts +18 -5
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +20 -5
  33. package/dist/index.js.map +1 -1
  34. package/dist/signer/rust-wasm-adapter.d.ts +99 -0
  35. package/dist/signer/rust-wasm-adapter.d.ts.map +1 -0
  36. package/dist/signer/rust-wasm-adapter.js +186 -0
  37. package/dist/signer/rust-wasm-adapter.js.map +1 -0
  38. package/dist/signer/wasm-signer-client.d.ts +140 -71
  39. package/dist/signer/wasm-signer-client.d.ts.map +1 -1
  40. package/dist/signer/wasm-signer-client.js +799 -839
  41. package/dist/signer/wasm-signer-client.js.map +1 -1
  42. package/dist/signer/wasm-signer.d.ts +9 -8
  43. package/dist/signer/wasm-signer.d.ts.map +1 -1
  44. package/dist/signer/wasm-signer.js +72 -122
  45. package/dist/signer/wasm-signer.js.map +1 -1
  46. package/dist/types/api.d.ts +1 -1
  47. package/dist/types/api.d.ts.map +1 -1
  48. package/dist/types/config.d.ts +0 -11
  49. package/dist/types/config.d.ts.map +1 -1
  50. package/dist/types/generated/openapi.d.ts +0 -1
  51. package/dist/types/generated/openapi.d.ts.map +1 -1
  52. package/dist/utils/configuration.d.ts +1 -2
  53. package/dist/utils/configuration.d.ts.map +1 -1
  54. package/dist/utils/configuration.js +0 -3
  55. package/dist/utils/configuration.js.map +1 -1
  56. package/dist/utils/detect-environment.d.ts +59 -0
  57. package/dist/utils/detect-environment.d.ts.map +1 -0
  58. package/dist/utils/detect-environment.js +133 -0
  59. package/dist/utils/detect-environment.js.map +1 -0
  60. package/dist/utils/order-status-checker.d.ts.map +1 -1
  61. package/dist/utils/order-status-checker.js +0 -2
  62. package/dist/utils/order-status-checker.js.map +1 -1
  63. package/dist/utils/transaction-types.d.ts +36 -0
  64. package/dist/utils/transaction-types.d.ts.map +1 -0
  65. package/dist/utils/transaction-types.js +71 -0
  66. package/dist/utils/transaction-types.js.map +1 -0
  67. package/docs/API.md +206 -207
  68. package/docs/AccountApi.md +278 -278
  69. package/docs/GettingStarted.md +347 -361
  70. package/docs/MarketHelper.md +12 -4
  71. package/docs/MigrationGuide.md +23 -26
  72. package/docs/OrderApi.md +353 -353
  73. package/docs/SignerClient.md +660 -626
  74. package/docs/TransactionApi.md +474 -474
  75. package/docs/Utilities.md +30 -31
  76. package/docs/WsClient.md +6 -6
  77. package/docs/types/SignerConfig.md +40 -40
  78. package/docs/types/WasmSignerConfig.md +6 -6
  79. package/examples/README.md +252 -252
  80. package/examples/cancel_all_orders.ts +122 -112
  81. package/examples/cancel_order.ts +41 -13
  82. package/examples/change_account_tier.ts +110 -82
  83. package/examples/close_all_positions.ts +10 -2
  84. package/examples/close_position.ts +10 -1
  85. package/examples/create_auth_token.ts +57 -57
  86. package/examples/create_grouped_ioc_with_attached_sl_tp.ts +8 -1
  87. package/examples/create_grouped_orders.ts +1 -1
  88. package/examples/create_limit_order.ts +172 -200
  89. package/examples/create_market_order.ts +37 -39
  90. package/examples/create_market_order_max_slippage.ts +8 -1
  91. package/examples/create_position_tied_sl_tp.ts +17 -10
  92. package/examples/create_subaccount.ts +79 -78
  93. package/examples/create_twap_order.ts +111 -98
  94. package/examples/create_with_multiple_keys.ts +102 -101
  95. package/examples/deposit_to_subaccount.ts +154 -113
  96. package/examples/market_data.ts +175 -175
  97. package/examples/market_position.ts +132 -0
  98. package/examples/modify_order.ts +268 -250
  99. package/examples/multi_client_advanced.ts +254 -254
  100. package/examples/onboarding.ts +453 -0
  101. package/examples/public_pool_burn_shares.ts +89 -0
  102. package/examples/public_pool_mint_shares.ts +89 -0
  103. package/examples/public_pool_operations.ts +74 -53
  104. package/examples/revoke_api_key.ts +130 -130
  105. package/examples/send_tx_batch.ts +47 -32
  106. package/examples/spot/README.md +90 -99
  107. package/examples/spot/cancel_spot_order.ts +89 -89
  108. package/examples/spot/create_market_spot_orders.ts +259 -259
  109. package/examples/spot/create_spot_limit_order.ts +122 -122
  110. package/examples/spot/create_spot_limit_order_with_sltp.ts +192 -193
  111. package/examples/spot/create_spot_twap_order.ts +109 -110
  112. package/examples/spot/modify_spot_order.ts +146 -146
  113. package/examples/system_setup.ts +55 -135
  114. package/examples/transfer_spot_perp.ts +19 -70
  115. package/examples/update_margin.ts +160 -99
  116. package/examples/update_margin_leverage.ts +118 -110
  117. package/examples/utils/account-helper.ts +80 -0
  118. package/examples/withdraw_fast.ts +196 -215
  119. package/examples/ws.ts +50 -50
  120. package/examples/ws_async.ts +112 -112
  121. package/examples/ws_ping_pong.ts +267 -267
  122. package/examples/ws_send_batch_tx.ts +91 -117
  123. package/examples/ws_send_tx.ts +196 -154
  124. package/lighter-wasm/BUILD.md +252 -0
  125. package/lighter-wasm/README.md +218 -0
  126. package/lighter-wasm/package.json +53 -0
  127. package/package.json +14 -11
  128. package/dist/signer/wasm-manager.d.ts +0 -29
  129. package/dist/signer/wasm-manager.d.ts.map +0 -1
  130. package/dist/signer/wasm-manager.js +0 -104
  131. package/dist/signer/wasm-manager.js.map +0 -1
  132. package/docs/ProxySupport.md +0 -292
  133. package/examples/generate_api_key.ts +0 -150
  134. package/examples/proxy_advanced.ts +0 -365
  135. package/examples/proxy_order.ts +0 -288
  136. package/examples/proxy_usage.ts +0 -197
  137. package/wasm/lighter-signer.wasm +0 -0
  138. package/wasm/wasm_exec.js +0 -575
package/README.md CHANGED
@@ -1,519 +1,787 @@
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
- ## 🌐 Proxy Support
380
-
381
- The SDK supports HTTP, HTTPS, and SOCKS proxies for both HTTP API requests and WebSocket connections. This is useful for enterprise networks, firewalls, or privacy requirements.
382
-
383
- ### Quick Example
384
-
385
- ```typescript
386
- import { ApiClient, WsClient } from 'lighter-ts-sdk';
387
-
388
- // HTTP API with proxy
389
- const apiClient = new ApiClient({
390
- host: 'https://mainnet.zklighter.elliot.ai',
391
- proxy: {
392
- host: 'proxy.example.com',
393
- port: 8080,
394
- protocol: 'http',
395
- auth: {
396
- username: 'user',
397
- password: 'pass'
398
- }
399
- }
400
- });
401
-
402
- // WebSocket with proxy
403
- const wsClient = new WsClient({
404
- url: 'wss://mainnet.zklighter.elliot.ai/stream',
405
- proxy: {
406
- host: 'proxy.example.com',
407
- port: 8080,
408
- protocol: 'http'
409
- }
410
- });
411
- ```
412
-
413
- **Note**: For WebSocket proxies, install `https-proxy-agent` (HTTP/HTTPS) or `socks-proxy-agent` (SOCKS):
414
- ```bash
415
- npm install https-proxy-agent # For HTTP/HTTPS proxies
416
- npm install socks-proxy-agent # For SOCKS proxies
417
- ```
418
-
419
- See [Proxy Support Documentation](docs/ProxySupport.md) for detailed usage and examples.
420
-
421
- ## πŸ“– Examples
422
-
423
- The `examples/` directory contains working examples for every feature:
424
-
425
- ```bash
426
- # Run examples
427
- npx ts-node examples/create_market_order.ts # Market order with SL/TP
428
- npx ts-node examples/create_limit_order.ts # Limit order with SL/TP
429
- npx ts-node examples/cancel_order.ts # Cancel orders
430
- npx ts-node examples/close_position.ts # Close positions
431
- npx ts-node examples/deposit_to_subaccount.ts # Fund transfers
432
- npx ts-node examples/proxy_usage.ts # Proxy configuration examples
433
- ```
434
-
435
- ## πŸŽ“ Learning Path
436
-
437
- 1. **Start Here**: `examples/create_market_order.ts` - Simplest order creation
438
- 2. **Next**: `examples/create_limit_order.ts` - Learn about limit orders
439
- 3. **Then**: `examples/cancel_order.ts` - Learn about order management
440
- 4. **Advanced**: `examples/send_tx_batch.ts` - Batch transactions
441
-
442
- ## πŸ”’ Security
443
-
444
- - βœ… Never commit `.env` files
445
- - βœ… Use environment variables for all credentials
446
- - βœ… Test with small amounts first
447
- - βœ… Monitor all transactions
448
- - βœ… Use proper error handling
449
-
450
- ## πŸ”§ Building from Source
451
-
452
- If you want to build the SDK from source or rebuild the WASM signer:
453
-
454
- ```bash
455
- # Clone the repository
456
- git clone https://github.com/bvvvp009/lighter-ts.git
457
- cd lighter-ts
458
-
459
- # Install dependencies
460
- npm install
461
-
462
- # Build WASM signer from lighter-go GitHub repo
463
- npm run build:wasm
464
-
465
- # Build TypeScript
466
- npm run build
467
- ```
468
-
469
- **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.
470
-
471
- ## πŸ”„ Migration from Previous Versions
472
-
473
- If you're upgrading from an older version that used `temp-lighter-go`:
474
-
475
- ### What Changed
476
-
477
- - βœ… **Signer**: Now uses official `lighter-go` from GitHub instead of local `temp-lighter-go`
478
- - βœ… **Build Process**: WASM is compiled directly from GitHub repo
479
- - βœ… **Functions**: All transaction types now supported via lighter-go
480
- - βœ… **Error Handling**: Improved error recovery and nonce management
481
-
482
- ### Breaking Changes
483
-
484
- **None!** The API remains the same. The only change is internal - the SDK now uses the official lighter-go signer.
485
-
486
- ### Removed Functions
487
-
488
- These functions were never officially supported and have been removed:
489
- - `getPublicKey()` - Use `generateAPIKey()` instead (returns both keys)
490
- - `switchAPIKey()` - Use `createClient()` with different `apiKeyIndex` values instead
491
-
492
- ### Migration Steps
493
-
494
- 1. **Update your code** (if using removed functions):
495
- ```typescript
496
- // Old (removed)
497
- const publicKey = await client.getPublicKey(privateKey);
498
-
499
- // New (use generateAPIKey)
500
- const { privateKey, publicKey } = await client.generateAPIKey();
501
- ```
502
-
503
- 2. **Rebuild WASM** (if building from source):
504
- ```bash
505
- npm run build:wasm
506
- ```
507
-
508
- 3. **Test your integration** - All existing code should work without changes.
509
-
510
- ## πŸ“ž Getting Help
511
-
512
- - Check the examples in `examples/` directory
513
- - Read error messages carefully - they're informative
514
- - Ensure environment variables are set correctly
515
- - Start with `examples/create_market_order.ts`
516
-
517
- ## License
518
-
519
- MIT License - see LICENSE file for details.
1
+ # Lighter Protocol TypeScript SDK
2
+
3
+ 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.
4
+
5
+ ## Status Overview
6
+
7
+ | Component | Status | Notes |
8
+ |-----------|--------|-------|
9
+ | **Node.js** | Supported | Ready for production use |
10
+ | **Browser (Chrome/Firefox/Safari)** | Supported | Uses Rust WASM in browser |
11
+ | **WASM Cryptography** | Verified | Optimized Rust WASM signer |
12
+ | **Documentation** | Complete | Setup guides included |
13
+
14
+ ---
15
+
16
+ ## Quick Navigation
17
+
18
+ - **[Get Started Quickly](#quick-start)** - 5 minutes (both Node.js & Browser)
19
+ - **[Node.js Setup](#nodejs-setup)** - Install, configure, and verify
20
+ - **[Browser Setup](#browser-setup)** - Vite, HTTP server, or Webpack
21
+ - **Testing** - Not included in release build
22
+ - **[Core Concepts](#-core-concepts)** - API reference and examples
23
+
24
+ ---
25
+
26
+ ## Signer Integration
27
+
28
+ This SDK uses **Rust WASM** for cryptographic signing operations, providing:
29
+
30
+ **Key Features:**
31
+ - **99% smaller binary size** (136 KB vs 13.5 MB)
32
+ - **7x faster initialization** (1.4 ms vs 10+ ms)
33
+ - **Optimized signatures** (0.67 ms per signature)
34
+ - **Production-ready** with verified mainnet transactions
35
+ - Support for all transaction types
36
+ - Multiple API key support
37
+ - Automatic error recovery and nonce management
38
+
39
+ ### Rust WASM Performance
40
+
41
+ | Metric | Value |
42
+ |--------|-------|
43
+ | **Binary Size** | 136 KB |
44
+ | **Initialization** | ~1.4 ms |
45
+ | **Per Signature** | ~0.67 ms |
46
+ | **API Coverage** | 100% |
47
+
48
+ **Architecture**: The SDK uses a single **Rust WASM** signer for all cryptographic operations in both Node.js and Browser environments.
49
+
50
+ For detailed information, see [lighter-wasm/README.md](./lighter-wasm/README.md)
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ npm install lighter-ts-sdk
56
+ # or
57
+ yarn add lighter-ts-sdk
58
+ ```
59
+
60
+ ## Quick Start
61
+
62
+ ### Node.js (5 minutes)
63
+
64
+ ```bash
65
+ # 1. Install
66
+ npm install lighter-ts-sdk
67
+
68
+ # 2. Create .env
69
+ echo "API_PRIVATE_KEY=your_key_here" > .env
70
+
71
+ # 3. Use
72
+ ```
73
+
74
+ ```typescript
75
+ import { SignerClient } from 'lighter-ts-sdk';
76
+
77
+ const client = new SignerClient({
78
+ url: 'https://mainnet.zklighter.elliot.ai',
79
+ privateKey: process.env.API_PRIVATE_KEY!,
80
+ accountIndex: 0,
81
+ apiKeyIndex: 0
82
+ });
83
+
84
+ await client.initialize();
85
+
86
+ // Create an order
87
+ const [tx, hash, error] = await client.createOrder({
88
+ marketIndex: 0,
89
+ baseAmount: 10000,
90
+ isAsk: false
91
+ });
92
+
93
+ console.log(error ? 'Failed' : 'Order created:', hash);
94
+ ```
95
+
96
+ ### Browser (5 minutes)
97
+
98
+ ```bash
99
+ # 1. Start WASM server
100
+ npm run serve:wasm
101
+
102
+ # 2. Create HTML
103
+ ```
104
+
105
+ ```html
106
+ <!DOCTYPE html>
107
+ <html>
108
+ <head><title>Trading</title></head>
109
+ <body>
110
+ <h1>Trading with WASM</h1>
111
+ <button onclick="signOrder()">Sign Order</button>
112
+
113
+ <script type="module">
114
+ import init, { SignerInstance } from 'http://localhost:8080/signer_wasm.js';
115
+
116
+ await init('http://localhost:8080/signer_wasm_bg.wasm');
117
+
118
+ window.signer = new SignerInstance('YOUR_PRIVATE_KEY');
119
+ window.signOrder = () => {
120
+ const sig = window.signer.signCreateOrder('{"action":"create_order"}');
121
+ console.log('Signed:', sig);
122
+ };
123
+ </script>
124
+ </body>
125
+ </html>
126
+ ```
127
+
128
+ ---
129
+
130
+ ## 🌐 Environment Setup Guide
131
+
132
+ ### Node.js Setup
133
+
134
+ **1. Install the SDK**
135
+
136
+ ```bash
137
+ npm install lighter-ts-sdk
138
+ ```
139
+
140
+ **2. Create `.env` file**
141
+
142
+ ```bash
143
+ cp .env.example .env
144
+ ```
145
+
146
+ Then edit `.env` with your values:
147
+
148
+ ```bash
149
+ API_PRIVATE_KEY=your_80_character_hex_private_key
150
+ ACCOUNT_INDEX=0
151
+ API_KEY_INDEX=0
152
+ BASE_URL=https://mainnet.zklighter.elliot.ai
153
+ ```
154
+
155
+ **3. Initialize the client**
156
+
157
+ ```typescript
158
+ import { SignerClient } from 'lighter-ts-sdk';
159
+ import dotenv from 'dotenv';
160
+
161
+ dotenv.config();
162
+
163
+ const signerClient = new SignerClient({
164
+ url: process.env.BASE_URL!,
165
+ privateKey: process.env.API_PRIVATE_KEY!,
166
+ accountIndex: parseInt(process.env.ACCOUNT_INDEX!),
167
+ apiKeyIndex: parseInt(process.env.API_KEY_INDEX!)
168
+ });
169
+
170
+ // Initialize WASM signer (required for cryptographic operations)
171
+ await signerClient.initialize();
172
+ await signerClient.ensureWasmClient();
173
+
174
+ console.log('Client initialized with WASM signer');
175
+ ```
176
+
177
+ **4. Use the client**
178
+
179
+ ```typescript
180
+ // Create an order
181
+ const [tx, hash, error] = await signerClient.createOrder({
182
+ marketIndex: 0,
183
+ clientOrderIndex: Date.now(),
184
+ baseAmount: 10000,
185
+ isAsk: false
186
+ });
187
+
188
+ if (!error) {
189
+ console.log('Order created:', hash);
190
+ await signerClient.waitForTransaction(hash);
191
+ }
192
+ ```
193
+
194
+ **WASM in Node.js:**
195
+ - Location: `wasm/rust-nodejs/`
196
+ - Automatically initialized when using `SignerClient`
197
+ - Direct access: `require('./wasm/rust-nodejs/signer_wasm.js')`
198
+
199
+ ---
200
+
201
+ ### Browser Setup
202
+
203
+ **Option 1: Using Vite/React/Vue**
204
+
205
+ ```bash
206
+ # 1. Create your frontend app
207
+ npm create vite@latest my-app -- --template react
208
+ cd my-app
209
+ npm install
210
+
211
+ # 2. Copy WASM files
212
+ cp -r node_modules/lighter-ts-sdk/wasm/rust-web public/wasm
213
+
214
+ # 3. Create your trading component
215
+ ```
216
+
217
+ ```typescript
218
+ // src/pages/Trade.tsx
219
+ import { useEffect, useState } from 'react';
220
+
221
+ export function Trade() {
222
+ const [signer, setSigner] = useState<any>(null);
223
+ const [publicKey, setPublicKey] = useState<string>('');
224
+
225
+ useEffect(() => {
226
+ async function initWasm() {
227
+ // Load WASM module
228
+ const wasmModule = await import('/wasm/signer_wasm.js');
229
+
230
+ // Initialize WASM
231
+ await wasmModule.default('/wasm/signer_wasm_bg.wasm');
232
+
233
+ // Create signer instance
234
+ const signerInstance = new wasmModule.SignerInstance(
235
+ process.env.REACT_APP_PRIVATE_KEY!
236
+ );
237
+
238
+ setSigner(signerInstance);
239
+ setPublicKey(signerInstance.getPublicKey());
240
+ }
241
+
242
+ initWasm().catch(console.error);
243
+ }, []);
244
+
245
+ const signOrder = () => {
246
+ if (!signer) return;
247
+
248
+ const orderData = {
249
+ action: 'create_order',
250
+ symbol: 'BTC-USD',
251
+ side: 'BUY',
252
+ quantity: 1,
253
+ timestamp: Date.now()
254
+ };
255
+
256
+ const signature = signer.signCreateOrder(JSON.stringify(orderData));
257
+ console.log('Order signed:', signature);
258
+ };
259
+
260
+ return (
261
+ <div>
262
+ <h1>Trading App</h1>
263
+ <p>Account: {publicKey?.substring(0, 20)}...</p>
264
+ <button onClick={signOrder}>Sign Order</button>
265
+ </div>
266
+ );
267
+ }
268
+ ```
269
+
270
+ **4. Serve with `vite` (has correct MIME types)**
271
+
272
+ ```bash
273
+ npm run dev
274
+ ```
275
+
276
+ ---
277
+
278
+ **Option 2: Manual HTTP Server**
279
+
280
+ ```bash
281
+ # Start the included HTTP server
282
+ npm run serve:wasm
283
+
284
+ # Output:
285
+ # WASM HTTP Server
286
+ # Server: http://localhost:8080
287
+ # WASM Directory: .../wasm/rust-web
288
+ ```
289
+
290
+ Then load in your HTML:
291
+
292
+ ```html
293
+ <!DOCTYPE html>
294
+ <html>
295
+ <head>
296
+ <title>Trading App</title>
297
+ </head>
298
+ <body>
299
+ <h1>Trading with WASM</h1>
300
+ <div id="status">Loading WASM...</div>
301
+ <div id="account">Account: -</div>
302
+ <button onclick="signOrder()">Sign Order</button>
303
+
304
+ <script type="module">
305
+ import init, { SignerInstance } from 'http://localhost:8080/signer_wasm.js';
306
+
307
+ // Initialize WASM
308
+ await init('http://localhost:8080/signer_wasm_bg.wasm');
309
+
310
+ // Create signer
311
+ window.signer = new SignerInstance('YOUR_80_HEX_PRIVATE_KEY');
312
+ const publicKey = window.signer.getPublicKey();
313
+
314
+ document.getElementById('status').textContent = 'WASM Ready';
315
+ document.getElementById('account').textContent = `Account: ${publicKey.substring(0, 20)}...`;
316
+
317
+ window.signOrder = function() {
318
+ const orderData = {
319
+ action: 'create_order',
320
+ symbol: 'BTC-USD',
321
+ side: 'BUY',
322
+ quantity: 1,
323
+ timestamp: Date.now()
324
+ };
325
+
326
+ const signature = window.signer.signCreateOrder(JSON.stringify(orderData));
327
+ console.log('Signed:', signature);
328
+ alert('Order signed! Check console.');
329
+ };
330
+ </script>
331
+ </body>
332
+ </html>
333
+ ```
334
+
335
+ **Option 3: Using Webpack/Rollup**
336
+
337
+ 1. Copy `wasm/rust-web/` to your public assets
338
+ 2. Configure your bundler to handle `.wasm` files:
339
+
340
+ ```javascript
341
+ // webpack.config.js
342
+ module.exports = {
343
+ module: {
344
+ rules: [
345
+ {
346
+ test: /\.wasm$/,
347
+ type: 'webassembly/async',
348
+ },
349
+ ],
350
+ },
351
+ };
352
+ ```
353
+
354
+ **WASM in Browser:**
355
+ - Location: `wasm/rust-web/`
356
+ - Must be served over HTTP (not file://)
357
+ - Server must send `Content-Type: application/wasm`
358
+ - Direct WASM file: `signer_wasm_bg.wasm`
359
+ - JS bindings: `signer_wasm.js`
360
+ - TypeScript definitions: `signer_wasm.d.ts`
361
+
362
+ ---
363
+
364
+ ### Troubleshooting
365
+
366
+ | Issue | Solution |
367
+ |-------|----------|
368
+ | **"Cannot load WASM from file://"** | Use HTTP server: `npm run serve:wasm` |
369
+ | **"WASM not found 404"** | Verify `wasm/rust-web/` exists; run `npm run build:wasm` |
370
+ | **"Wrong MIME type"** | Ensure server sends `Content-Type: application/wasm` for `.wasm` files |
371
+ | **Import errors in browser** | Use correct import paths; check module exports |
372
+ | **Signature mismatch** | Ensure same private key used in both environments |
373
+ ## What Does This SDK Do?
374
+
375
+ The Lighter TypeScript SDK provides everything you need to:
376
+ - **Trade perpetual futures** on Lighter Protocol
377
+ - **Create orders** (Market, Limit, TWAP) with automatic SL/TP
378
+ - **Manage positions** (open, close, update leverage)
379
+ - **Transfer funds** between accounts
380
+ - **Monitor transactions** with built-in status tracking
381
+ - **Handle errors** automatically with retry logic
382
+
383
+ ## 🎯 Getting Started
384
+
385
+ ### Step 1: Set Up Your Environment
386
+
387
+ Create a `.env` file in your project root:
388
+
389
+ ```bash
390
+ # Required credentials
391
+ API_PRIVATE_KEY=your_private_key_here
392
+ ACCOUNT_INDEX=0
393
+ API_KEY_INDEX=0
394
+ BASE_URL=https://mainnet.zklighter.elliot.ai
395
+
396
+ # Optional: for specific examples
397
+ MARKET_ID=0
398
+ SUB_ACCOUNT_INDEX=1
399
+ DEPOSIT_AMOUNT=1
400
+ ```
401
+
402
+ ### Step 2: Install the SDK
403
+
404
+ ```bash
405
+ npm install lighter-ts-sdk
406
+ ```
407
+
408
+ ### Step 3: Your First Trade
409
+
410
+ ```typescript
411
+ import { SignerClient, OrderType } from 'lighter-ts-sdk';
412
+ import dotenv from 'dotenv';
413
+
414
+ dotenv.config();
415
+
416
+ async function placeOrder() {
417
+ // Initialize the client
418
+ const signerClient = new SignerClient({
419
+ url: process.env.BASE_URL!,
420
+ privateKey: process.env.API_PRIVATE_KEY!,
421
+ accountIndex: parseInt(process.env.ACCOUNT_INDEX!),
422
+ apiKeyIndex: parseInt(process.env.API_KEY_INDEX!)
423
+ });
424
+
425
+ // Initialize WASM signer (required)
426
+ await signerClient.initialize();
427
+ await signerClient.ensureWasmClient();
428
+
429
+ // Create an order
430
+ const result = await signerClient.createOrder({
431
+ marketIndex: 0,
432
+ clientOrderIndex: Date.now(),
433
+ baseAmount: 10000,
434
+ isAsk: false,
435
+ orderType: OrderType.MARKET
436
+ });
437
+
438
+ // Check if order succeeded
439
+ if (result[2]) {
440
+ console.error('Order failed:', result[2]);
441
+ return;
442
+ }
443
+
444
+ console.log('Order created');
445
+ console.log('Order hash:', result[1]);
446
+
447
+ // Wait for transaction confirmation
448
+ await signerClient.waitForTransaction(result[1], 30000);
449
+
450
+ await signerClient.close();
451
+ }
452
+
453
+ placeOrder().catch(console.error);
454
+ ```
455
+
456
+ ## πŸ“š Core Concepts
457
+
458
+ ### Understanding Price Units
459
+
460
+ Lighter uses fixed decimal scaling:
461
+ - **ETH amounts**: 1 ETH = 1,000,000 units
462
+ - **Prices**: $1 = 100 units
463
+
464
+ ```typescript
465
+ // To buy 0.01 ETH at $4000:
466
+ baseAmount: 10000 // 0.01 ETH (10,000 / 1,000,000)
467
+ price: 400000 // $4000 (400,000 / 100)
468
+ ```
469
+
470
+ ### Order Types
471
+
472
+ ```typescript
473
+ OrderType.MARKET // Executes immediately at market price
474
+ OrderType.LIMIT // Executes at your specified price
475
+ OrderType.TWAP // Executes gradually over time
476
+ ```
477
+
478
+ ### Direction (isAsk)
479
+
480
+ ```typescript
481
+ isAsk: false // BUY - You're buying ETH
482
+ isAsk: true // SELL - You're selling ETH
483
+ ```
484
+
485
+ ### Stop-Loss and Take-Profit
486
+
487
+ SL/TP orders are **automatically reduce-only** - they only close positions:
488
+
489
+ ```typescript
490
+ stopLoss: {
491
+ triggerPrice: 380000, // When price hits this, close position
492
+ isLimit: false // false = market SL, true = limit SL
493
+ },
494
+ takeProfit: {
495
+ triggerPrice: 420000, // When price hits this, take profit
496
+ isLimit: false // false = market TP, true = limit TP
497
+ }
498
+ ```
499
+
500
+ **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.
501
+
502
+ **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.
503
+
504
+ ## Common Operations
505
+
506
+ ### Create a Market Order
507
+
508
+ ```typescript
509
+ const [tx, hash, error] = await signerClient.createOrder({
510
+ marketIndex: 0,
511
+ clientOrderIndex: Date.now(),
512
+ baseAmount: 10000,
513
+ isAsk: false,
514
+ orderType: OrderType.MARKET
515
+ });
516
+
517
+ if (error) {
518
+ console.error('Failed:', error);
519
+ return;
520
+ }
521
+ ```
522
+
523
+ ### Create a Limit Order
524
+
525
+ ```typescript
526
+ const [tx, hash, error] = await signerClient.createOrder({
527
+ marketIndex: 0,
528
+ clientOrderIndex: Date.now(),
529
+ baseAmount: 10000,
530
+ price: 400000,
531
+ isAsk: false,
532
+ orderType: OrderType.LIMIT,
533
+ orderExpiry: Date.now() + (60 * 60 * 1000)
534
+ });
535
+
536
+ if (!error) {
537
+ await signerClient.waitForTransaction(hash);
538
+ }
539
+ ```
540
+
541
+ ### Cancel an Order
542
+
543
+ ```typescript
544
+ const [tx, hash, error] = await signerClient.cancelOrder({
545
+ marketIndex: 0,
546
+ orderIndex: 12345 // Your order's index
547
+ });
548
+
549
+ if (error) {
550
+ console.error('Cancel failed:', error);
551
+ return;
552
+ }
553
+
554
+ await signerClient.waitForTransaction(hash);
555
+ console.log('Order cancelled');
556
+ ```
557
+
558
+ ### Close a Position
559
+
560
+ ```typescript
561
+ const [tx, hash, error] = await signerClient.createMarketOrder({
562
+ marketIndex: 0,
563
+ clientOrderIndex: Date.now(),
564
+ baseAmount: 10000, // Position size to close
565
+ avgExecutionPrice: 400000,
566
+ isAsk: false, // Opposite of position
567
+ reduceOnly: true // IMPORTANT: Only closes, doesn't open new
568
+ });
569
+
570
+ if (error) {
571
+ console.error('Close failed:', error);
572
+ return;
573
+ }
574
+
575
+ await signerClient.waitForTransaction(hash);
576
+ console.log('Position closed');
577
+ ```
578
+
579
+ ### Check Order Status
580
+
581
+ ```typescript
582
+ const status = await signerClient.getTransaction(txHash);
583
+ console.log('Status:', status.status); // 0=pending, 1=queued, 2=committed, 3=executed
584
+ ```
585
+
586
+ ## πŸ› οΈ API Reference
587
+
588
+ ### SignerClient Methods
589
+
590
+ #### Order Management
591
+ ```typescript
592
+ // Create a single order
593
+ createOrder(params) -> Promise<[txInfo, txHash, error]>
594
+
595
+ // Create multiple orders (OTOCO, OTOMA, or OTOTCO grouping)
596
+ createGroupedOrders(groupingType, orders) -> Promise<[txInfo, txHash, error]>
597
+
598
+ // Cancel a specific order
599
+ cancelOrder(params) -> Promise<[txInfo, txHash, error]>
600
+
601
+ // Cancel all orders
602
+ cancelAllOrders(timeInForce, time) -> Promise<[txInfo, txHash, error]>
603
+ ```
604
+
605
+ #### Position Management
606
+ ```typescript
607
+ // Close specific position
608
+ createMarketOrder({ reduceOnly: true }) -> Promise<[txInfo, txHash, error]>
609
+
610
+ // Close all positions
611
+ closeAllPositions() -> Promise<[txs[], responses[], errors[]]>
612
+ ```
613
+
614
+ #### Transaction Monitoring
615
+ ```typescript
616
+ // Get transaction details
617
+ getTransaction(txHash) -> Promise<Transaction>
618
+
619
+ // Wait for transaction (with timeout)
620
+ waitForTransaction(txHash, maxWaitTime, pollInterval) -> Promise<Transaction>
621
+ ```
622
+
623
+ ### Order Parameters
624
+
625
+ ```typescript
626
+ interface UnifiedOrderParams {
627
+ marketIndex: number; // Market ID (0 = ETH)
628
+ clientOrderIndex: number; // Unique ID (use Date.now())
629
+ baseAmount: number; // Amount in units (1 ETH = 1,000,000)
630
+ isAsk: boolean; // true = SELL, false = BUY
631
+ orderType: OrderType; // MARKET, LIMIT, or TWAP
632
+
633
+ // For market orders
634
+ idealPrice?: number; // Target price
635
+ maxSlippage?: number; // Max slippage (e.g., 0.001 = 0.1%)
636
+
637
+ // For limit orders
638
+ price?: number; // Limit price
639
+
640
+ // Optional SL/TP (automatically reduce-only)
641
+ stopLoss?: {
642
+ triggerPrice: number;
643
+ isLimit?: boolean;
644
+ };
645
+ takeProfit?: {
646
+ triggerPrice: number;
647
+ isLimit?: boolean;
648
+ };
649
+
650
+ // Optional
651
+ orderExpiry?: number; // Expiry timestamp (milliseconds)
652
+ }
653
+ ```
654
+
655
+ ## Tips for Beginners
656
+
657
+ ### 1. Always Use Environment Variables
658
+
659
+ ```typescript
660
+ // Do not hardcode credentials
661
+ const privateKey = '0xabc123...';
662
+
663
+ // Use environment variables
664
+ const privateKey = process.env.API_PRIVATE_KEY;
665
+ ```
666
+
667
+ ### 2. Handle Errors Properly
668
+
669
+ ```typescript
670
+ try {
671
+ const [tx, hash, error] = await signerClient.createOrder(params);
672
+
673
+ if (error) {
674
+ console.error('Order failed:', error);
675
+ return; // Exit early
676
+ }
677
+
678
+ // Success path
679
+ console.log('Order created:',
680
+ ```
681
+
682
+ ### 3. Check Transaction Status
683
+
684
+ ```typescript
685
+ // Wait for transaction to be confirmed
686
+ try {
687
+ await signerClient.waitForTransaction(txHash, 30000, 2000);
688
+ console.log('Transaction confirmed');
689
+ } catch (error) {
690
+ console.error('Transaction failed:', error.message);
691
+ }
692
+ ```
693
+
694
+ ### 4. Close Resources
695
+
696
+ ```typescript
697
+ try {
698
+ // ... use signerClient
699
+ } finally {
700
+ await signerClient.close(); // Always close when done
701
+ }
702
+ ```
703
+
704
+ ## Examples
705
+
706
+ The `examples/` directory contains working examples for every feature:
707
+
708
+ ```bash
709
+ # Run examples
710
+ npx ts-node examples/create_market_order.ts # Market order with SL/TP
711
+ npx ts-node examples/create_limit_order.ts # Limit order with SL/TP
712
+ npx ts-node examples/cancel_order.ts # Cancel orders
713
+ npx ts-node examples/close_position.ts # Close positions
714
+ npx ts-node examples/deposit_to_subaccount.ts # Fund transfers
715
+ ```
716
+
717
+ ## πŸŽ“ Learning Path
718
+
719
+ 1. **Start Here**: `examples/create_market_order.ts` - Simplest order creation
720
+ 2. **Next**: `examples/create_limit_order.ts` - Learn about limit orders
721
+ 3. **Then**: `examples/cancel_order.ts` - Learn about order management
722
+ 4. **Advanced**: `examples/send_tx_batch.ts` - Batch transactions
723
+
724
+ ## Security
725
+
726
+ - Never commit `.env` files
727
+ - Use environment variables for all credentials
728
+ - Test with small amounts first
729
+ - Monitor all transactions
730
+ - Use proper error handling
731
+
732
+ ## Building from Source
733
+
734
+ If you want to build the SDK from source or rebuild the WASM signer:
735
+
736
+ ```bash
737
+ # Clone the repository
738
+ git clone https://github.com/bvvvp009/lighter-ts.git
739
+ cd lighter-ts
740
+
741
+ # Install dependencies
742
+ npm install
743
+
744
+ # Build WASM signer
745
+ npm run build:wasm
746
+
747
+ # Build TypeScript
748
+ npm run build
749
+ ```
750
+
751
+ **Note**: The build script compiles the Rust WASM signer from local source if present.
752
+
753
+ ## Migration from Previous Versions
754
+
755
+ If you are upgrading from an older release, review the change log and update any removed or renamed methods. Most integrations should not require code changes.
756
+
757
+ ## WASM Build System
758
+
759
+ The SDK uses **Rust WebAssembly** for cryptographic operations. Pre-compiled binaries are included in the npm package, so you don’t need to build anything unless you want to modify the signer.
760
+
761
+ ### Quick Build Commands
762
+ ```bash
763
+ # Show all WASM commands
764
+ npm run wasm:info
765
+
766
+ # Build from Rust source
767
+ npm run build:wasm
768
+
769
+ # Verify WASM functionality
770
+ npm run verify:wasm
771
+ ```
772
+
773
+ ### Notes
774
+ - Prebuilt WASM binaries are included in `wasm/` for normal usage.
775
+ - To build from source, you must provide the Rust signer source at `lighter-rust/signer-wasm/` (e.g., as a submodule or vendor copy).
776
+
777
+ ## Getting Help
778
+
779
+ - Check the examples in `examples/` directory
780
+ - Read error messages carefully - they're informative
781
+ - Ensure environment variables are set correctly
782
+ - Start with `examples/create_market_order.ts`
783
+
784
+
785
+ ## License
786
+
787
+ MIT License - see LICENSE file for details.