extended-typescript-sdk 0.0.2 → 0.0.4

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 (49) hide show
  1. package/README.md +539 -445
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/perpetual/accounts.d.ts +64 -5
  7. package/dist/perpetual/accounts.d.ts.map +1 -1
  8. package/dist/perpetual/accounts.js +90 -6
  9. package/dist/perpetual/accounts.js.map +1 -1
  10. package/dist/perpetual/crypto/signer.d.ts.map +1 -1
  11. package/dist/perpetual/crypto/signer.js +24 -14
  12. package/dist/perpetual/crypto/signer.js.map +1 -1
  13. package/dist/perpetual/custom-signer.d.ts +51 -0
  14. package/dist/perpetual/custom-signer.d.ts.map +1 -0
  15. package/dist/perpetual/custom-signer.js +18 -0
  16. package/dist/perpetual/custom-signer.js.map +1 -0
  17. package/dist/perpetual/order-object-settlement.d.ts +3 -3
  18. package/dist/perpetual/order-object-settlement.d.ts.map +1 -1
  19. package/dist/perpetual/order-object-settlement.js +2 -2
  20. package/dist/perpetual/order-object-settlement.js.map +1 -1
  21. package/dist/perpetual/order-object.d.ts +1 -1
  22. package/dist/perpetual/order-object.d.ts.map +1 -1
  23. package/dist/perpetual/order-object.js +4 -4
  24. package/dist/perpetual/order-object.js.map +1 -1
  25. package/dist/perpetual/stream-client/stream-client.d.ts +16 -0
  26. package/dist/perpetual/stream-client/stream-client.d.ts.map +1 -1
  27. package/dist/perpetual/stream-client/stream-client.js +28 -0
  28. package/dist/perpetual/stream-client/stream-client.js.map +1 -1
  29. package/dist/perpetual/trading-client/account-module.d.ts.map +1 -1
  30. package/dist/perpetual/trading-client/account-module.js +9 -7
  31. package/dist/perpetual/trading-client/account-module.js.map +1 -1
  32. package/dist/perpetual/trading-client/trading-client.js +1 -1
  33. package/dist/perpetual/trading-client/trading-client.js.map +1 -1
  34. package/dist/perpetual/transfer-object.d.ts +1 -1
  35. package/dist/perpetual/transfer-object.d.ts.map +1 -1
  36. package/dist/perpetual/transfer-object.js +2 -2
  37. package/dist/perpetual/transfer-object.js.map +1 -1
  38. package/dist/perpetual/user-client/user-client.js +4 -4
  39. package/dist/perpetual/user-client/user-client.js.map +1 -1
  40. package/dist/perpetual/withdrawal-object.d.ts +1 -1
  41. package/dist/perpetual/withdrawal-object.d.ts.map +1 -1
  42. package/dist/perpetual/withdrawal-object.js +2 -2
  43. package/dist/perpetual/withdrawal-object.js.map +1 -1
  44. package/package.json +60 -60
  45. package/wasm/stark_crypto_wasm.d-web.ts +34 -26
  46. package/wasm/stark_crypto_wasm.d.ts +34 -26
  47. package/wasm/stark_crypto_wasm.js +125 -112
  48. package/wasm/stark_crypto_wasm_bg-web.wasm +0 -0
  49. package/wasm/stark_crypto_wasm_bg.wasm +0 -0
package/README.md CHANGED
@@ -1,445 +1,539 @@
1
- # Extended TypeScript Trading SDK
2
-
3
- **⚠️ Unofficial SDK**: This is an **unofficial TypeScript SDK** for Extended Exchange, built and maintained by the community. It is not officially supported by Extended.
4
-
5
- TypeScript client for [Extended Exchange API](https://api.docs.extended.exchange/).
6
-
7
- ## About Extended Exchange
8
-
9
- Extended is a perpetual DEX (Decentralized Exchange), built by an ex-Revolut team. As of now, Extended offers perpetual contracts on both crypto and TradFi assets, with USDC as collateral and leverage of up to 100x.
10
-
11
- This SDK provides full type safety and modern async/await patterns for interacting with the Extended Exchange API.
12
-
13
- ## Installation
14
-
15
- ```bash
16
- npm install extended-typescript-sdk
17
- ```
18
-
19
- ## Prerequisites
20
-
21
- - Node.js 18+ or TypeScript 5.3+
22
- - **No Rust required** - The SDK ships with pre-built WASM signer
23
-
24
- ## Quick Start
25
-
26
- ### 1. Initialize the SDK
27
-
28
- The SDK ships with pre-built WASM signer - no build step required!
29
-
30
- ```typescript
31
- import {
32
- initWasm,
33
- TESTNET_CONFIG,
34
- StarkPerpetualAccount,
35
- PerpetualTradingClient,
36
- } from 'extended-typescript-sdk';
37
- import Decimal from 'decimal.js';
38
-
39
- // Initialize WASM module (MUST be called before using any crypto functions)
40
- // Automatically loads the correct WASM for Node.js or browser
41
- await initWasm();
42
-
43
- // Create a Stark account
44
- const starkAccount = new StarkPerpetualAccount(
45
- vaultId, // number
46
- privateKey, // Hex string (e.g., "0x123...")
47
- publicKey, // Hex string
48
- apiKey // string
49
- );
50
-
51
- // Create trading client
52
- const tradingClient = new PerpetualTradingClient(TESTNET_CONFIG, starkAccount);
53
- ```
54
-
55
- ### 2. Place an Order
56
-
57
- ```typescript
58
- import { OrderSide } from 'extended-typescript-sdk';
59
- import Decimal from 'decimal.js';
60
-
61
- const placedOrder = await tradingClient.placeOrder({
62
- marketName: 'BTC-USD',
63
- amountOfSynthetic: new Decimal('1'),
64
- price: new Decimal('63000.1'),
65
- side: OrderSide.SELL,
66
- });
67
-
68
- console.log('Placed order:', placedOrder);
69
-
70
- // Cancel the order
71
- await tradingClient.orders.cancelOrder(placedOrder.id);
72
- ```
73
-
74
- ### 3. Get Account Information
75
-
76
- ```typescript
77
- // Get balance
78
- const balance = await tradingClient.account.getBalance();
79
- console.log('Balance:', balance.toPrettyJson());
80
-
81
- // Get positions
82
- const positions = await tradingClient.account.getPositions();
83
- console.log('Positions:', positions.toPrettyJson());
84
-
85
- // Get open orders
86
- const openOrders = await tradingClient.account.getOpenOrders();
87
- console.log('Open orders:', openOrders.toPrettyJson());
88
- ```
89
-
90
- ### 4. Onboarding (User Client)
91
-
92
- ```typescript
93
- import { UserClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
94
-
95
- // Create user client
96
- const userClient = new UserClient(TESTNET_CONFIG, () => ethPrivateKey);
97
-
98
- // Onboard new account
99
- const account = await userClient.onboard();
100
-
101
- // Get API key
102
- const apiKey = await userClient.createAccountApiKey(account.account, 'My trading key');
103
-
104
- // Use the account
105
- const starkAccount = new StarkPerpetualAccount(
106
- account.account.l2Vault,
107
- account.l2KeyPair.privateHex,
108
- account.l2KeyPair.publicHex,
109
- apiKey
110
- );
111
-
112
- const client = new PerpetualTradingClient(TESTNET_CONFIG, starkAccount);
113
- ```
114
-
115
- ### 5. Stream Data
116
-
117
- ```typescript
118
- import { PerpetualStreamClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
119
-
120
- const streamClient = new PerpetualStreamClient({
121
- apiUrl: TESTNET_CONFIG.streamUrl,
122
- });
123
-
124
- // Subscribe to orderbooks
125
- const orderbookStream = streamClient.subscribeToOrderbooks({ marketName: 'BTC-USD' });
126
- await orderbookStream.connect();
127
-
128
- for await (const update of orderbookStream) {
129
- console.log('Orderbook update:', update);
130
- }
131
-
132
- // Subscribe to account updates
133
- const accountStream = streamClient.subscribeToAccountUpdates(apiKey);
134
- await accountStream.connect();
135
-
136
- for await (const update of accountStream) {
137
- console.log('Account update:', update);
138
- }
139
- ```
140
-
141
- ## WASM Signer
142
-
143
- The SDK includes a pre-built WASM signer that works in both **Node.js** and **browser** environments. **No Rust installation is required to use the SDK.**
144
-
145
- ### Using the Pre-built Signer
146
-
147
- The SDK ships with pre-built WASM files. Simply use the SDK:
148
-
149
- ```typescript
150
- import { initWasm, sign } from 'extended-typescript-sdk';
151
-
152
- await initWasm(); // Automatically loads the correct WASM for your environment
153
- const [r, s] = sign(privateKey, msgHash);
154
- ```
155
-
156
- The signer automatically detects your environment (Node.js or browser) and loads the appropriate WASM module.
157
-
158
- ### Building Your Own WASM Signer
159
-
160
- If you want to build your own WASM signer (requires Rust and wasm-pack):
161
-
162
- ```bash
163
- npm run build:signer:custom
164
- ```
165
-
166
- **Prerequisites:**
167
- 1. Install Rust: https://www.rust-lang.org/tools/install
168
- 2. Install wasm-pack: `cargo install wasm-pack`
169
-
170
- This will build both Node.js and browser targets and replace the shipped WASM signer.
171
-
172
- ### Implementation
173
-
174
- The WASM signer uses `starknet-crypto` crate for cryptographic operations. It's production-ready and tested for compatibility with Extended Exchange API.
175
-
176
- ## API Documentation
177
-
178
- ### Trading Client
179
-
180
- ```typescript
181
- import { PerpetualTradingClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
182
-
183
- const client = new PerpetualTradingClient(config, account);
184
-
185
- // Place order
186
- await client.placeOrder({
187
- marketName: 'BTC-USD',
188
- amountOfSynthetic: new Decimal('1'),
189
- price: new Decimal('63000'),
190
- side: OrderSide.BUY,
191
- });
192
-
193
- // Account module
194
- await client.account.getBalance();
195
- await client.account.getPositions();
196
- await client.account.getOpenOrders();
197
- await client.account.updateLeverage('BTC-USD', new Decimal('10'));
198
-
199
- // Orders module
200
- await client.orders.cancelOrder(orderId);
201
- await client.orders.cancelOrderByExternalId(externalId);
202
- await client.orders.massCancel({ markets: ['BTC-USD'] });
203
-
204
- // Markets module
205
- await client.marketsInfo.getMarkets();
206
- await client.marketsInfo.getMarketStatistics('BTC-USD');
207
- await client.marketsInfo.getOrderbookSnapshot('BTC-USD');
208
- ```
209
-
210
- ### User Client (Onboarding)
211
-
212
- ```typescript
213
- import { UserClient } from 'extended-typescript-sdk';
214
-
215
- const userClient = new UserClient(config, () => ethPrivateKey);
216
-
217
- // Onboard new account
218
- const account = await userClient.onboard();
219
-
220
- // Onboard subaccount
221
- const subaccount = await userClient.onboardSubaccount(1, 'My subaccount');
222
-
223
- // Get all accounts
224
- const accounts = await userClient.getAccounts();
225
-
226
- // Create API key
227
- const apiKey = await userClient.createAccountApiKey(account.account, 'description');
228
- ```
229
-
230
- ### Stream Client
231
-
232
- ```typescript
233
- import { PerpetualStreamClient } from 'extended-typescript-sdk';
234
-
235
- const streamClient = new PerpetualStreamClient({ apiUrl: config.streamUrl });
236
-
237
- // Subscribe to orderbooks
238
- const orderbookStream = streamClient.subscribeToOrderbooks({
239
- marketName: 'BTC-USD',
240
- depth: 10,
241
- });
242
-
243
- // Subscribe to public trades
244
- const tradesStream = streamClient.subscribeToPublicTrades('BTC-USD');
245
-
246
- // Subscribe to funding rates
247
- const fundingStream = streamClient.subscribeToFundingRates('BTC-USD');
248
-
249
- // Subscribe to account updates (requires API key)
250
- const accountStream = streamClient.subscribeToAccountUpdates(apiKey);
251
- ```
252
-
253
- ## Environment Configuration
254
-
255
- The SDK supports different environments:
256
-
257
- ```typescript
258
- import { TESTNET_CONFIG, MAINNET_CONFIG } from 'extended-typescript-sdk';
259
-
260
- // Use testnet
261
- const client = new PerpetualTradingClient(TESTNET_CONFIG, account);
262
-
263
- // Use mainnet
264
- const client = new PerpetualTradingClient(MAINNET_CONFIG, account);
265
- ```
266
-
267
- ## TypeScript Support
268
-
269
- This SDK is written in TypeScript and provides full type definitions. All types are exported:
270
-
271
- ```typescript
272
- import {
273
- OrderSide,
274
- OrderType,
275
- OrderStatus,
276
- TimeInForce,
277
- StarkPerpetualAccount,
278
- PerpetualTradingClient,
279
- UserClient,
280
- PerpetualStreamClient,
281
- // ... and more
282
- } from 'extended-typescript-sdk';
283
- ```
284
-
285
- ## Error Handling
286
-
287
- The SDK provides specific error types:
288
-
289
- ```typescript
290
- import {
291
- X10Error,
292
- RateLimitException,
293
- NotAuthorizedException,
294
- SubAccountExists,
295
- } from 'extended-typescript-sdk';
296
-
297
- try {
298
- await client.placeOrder({ ... });
299
- } catch (error) {
300
- if (error instanceof RateLimitException) {
301
- // Handle rate limit
302
- } else if (error instanceof NotAuthorizedException) {
303
- // Handle authentication error
304
- }
305
- }
306
- ```
307
-
308
- ## Examples
309
-
310
- See `examples/` directory for complete examples:
311
-
312
- - Basic order placement
313
- - Onboarding flow
314
- - Stream subscriptions
315
- - Market data access
316
- - Account management
317
-
318
- ## WASM Performance
319
-
320
- The WASM signer provides ~90-95% of native Rust performance:
321
-
322
- ```
323
- Native Rust: ~50μs per signature
324
- WASM (Rust): ~55μs per signature (10% slower)
325
- Pure JavaScript: ~500μs per signature (10x slower)
326
- ```
327
-
328
- The performance difference is negligible in real-world applications.
329
-
330
- ## Building the SDK
331
-
332
- ### For Users (No Build Required)
333
-
334
- The SDK ships with pre-built WASM signer - just install and use:
335
-
336
- ```bash
337
- npm install extended-typescript-sdk
338
- ```
339
-
340
- ### For Developers
341
-
342
- If you're developing the SDK or want to build your own WASM signer:
343
-
344
- ```bash
345
- # Install dependencies
346
- npm install
347
-
348
- # Build WASM signer (requires Rust and wasm-pack)
349
- npm run build:signer
350
-
351
- # Build TypeScript
352
- npm run build:ts
353
-
354
- # Build everything
355
- npm run build # Builds both WASM signer and TypeScript
356
-
357
- # Build custom WASM signer (for users who want to replace shipped WASM)
358
- npm run build:signer:custom
359
- ```
360
-
361
- ### Build Commands
362
-
363
- - `npm run build` - Builds WASM signer and TypeScript (full build)
364
- - `npm run build:signer` - Builds WASM signer for both Node.js and browser
365
- - `npm run build:signer:custom` - Build your own WASM signer (requires Rust)
366
- - `npm run build:ts` - Build TypeScript only
367
- - `npm run clean` - Clean all build artifacts
368
-
369
- ### Development Commands
370
-
371
- ```bash
372
- # Run tests
373
- npm test
374
-
375
- # Lint
376
- npm run lint
377
-
378
- # Format code
379
- npm run format
380
- ```
381
-
382
- ## Contributing
383
-
384
- 1. Clone the repository
385
- 2. Install dependencies: `npm install`
386
- 3. Install Rust and wasm-pack (only if building WASM signer)
387
- 4. Build: `npm run build`
388
- 5. Run tests: `npm test`
389
-
390
- ## License
391
-
392
- MIT
393
-
394
- ## Support
395
-
396
- For issues and questions:
397
- - GitHub: https://github.com/Bvvvp009/Extended-TS-SDK
398
- - Documentation: https://api.docs.extended.exchange/
399
- - Extended Exchange: https://extended.exchange/
400
-
401
- **Note**: This is an unofficial, community-maintained SDK. For official support, please contact Extended Exchange directly.
402
-
403
- ## API Coverage
404
-
405
- See [API_COVERAGE.md](./API_COVERAGE.md) for complete API endpoint coverage analysis.
406
-
407
- ## Standalone Signer Functions
408
-
409
- The cryptographic signer functions are exported from the main SDK package for standalone use:
410
-
411
- ```typescript
412
- import {
413
- initWasm,
414
- sign,
415
- pedersenHash,
416
- getOrderMsgHash,
417
- getTransferMsgHash,
418
- getWithdrawalMsgHash,
419
- generateKeypairFromEthSignature
420
- } from 'extended-typescript-sdk';
421
-
422
- // Initialize WASM module (required first!)
423
- await initWasm();
424
-
425
- // Sign a message hash
426
- const privateKey = BigInt('0x...');
427
- const msgHash = BigInt('0x...');
428
- const [r, s] = sign(privateKey, msgHash);
429
-
430
- // Compute Pedersen hash
431
- const hash = pedersenHash(BigInt('0x123'), BigInt('0x456'));
432
-
433
- // Generate order message hash (for custom order signing)
434
- const orderHash = getOrderMsgHash({
435
- positionId: 12345,
436
- baseAssetId: '0x...',
437
- baseAmount: '1000000',
438
- // ... other order parameters
439
- });
440
-
441
- // Generate keypair from Ethereum signature (for onboarding)
442
- const [privateKey, publicKey] = generateKeypairFromEthSignature(ethSignature);
443
- ```
444
-
445
- All signer functions are documented with JSDoc comments. See the [signer source code](./src/perpetual/crypto/signer.ts) for detailed documentation.
1
+ # Extended TypeScript Trading SDK
2
+
3
+ **⚠️ Unofficial SDK**: This is an **unofficial TypeScript SDK** for Extended Exchange, built and maintained by the community. It is not officially supported by Extended.
4
+
5
+ TypeScript client for [Extended Exchange API](https://api.docs.extended.exchange/).
6
+
7
+ ## About Extended Exchange
8
+
9
+ Extended is a perpetual DEX (Decentralized Exchange), built by an ex-Revolut team. As of now, Extended offers perpetual contracts on both crypto and TradFi assets, with USDC as collateral and leverage of up to 100x.
10
+
11
+ This SDK provides full type safety and modern async/await patterns for interacting with the Extended Exchange API.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install extended-typescript-sdk
17
+ ```
18
+
19
+ ## Prerequisites
20
+
21
+ - Node.js 18+ or TypeScript 5.3+
22
+ - **No Rust required** - The SDK ships with pre-built WASM signer
23
+
24
+ ## Quick Start
25
+
26
+ ### 1. Initialize the SDK
27
+
28
+ The SDK ships with pre-built WASM signer - no build step required!
29
+
30
+ ```typescript
31
+ import {
32
+ initWasm,
33
+ TESTNET_CONFIG,
34
+ StarkPerpetualAccount,
35
+ PerpetualTradingClient,
36
+ } from 'extended-typescript-sdk';
37
+ import Decimal from 'decimal.js';
38
+
39
+ // Initialize WASM module (MUST be called before using any crypto functions)
40
+ // Automatically loads the correct WASM for Node.js or browser
41
+ await initWasm();
42
+
43
+ // Create a Stark account
44
+ const starkAccount = new StarkPerpetualAccount(
45
+ vaultId, // number
46
+ privateKey, // Hex string (e.g., "0x123...")
47
+ publicKey, // Hex string
48
+ apiKey // string
49
+ );
50
+
51
+ // Create trading client
52
+ const tradingClient = new PerpetualTradingClient(TESTNET_CONFIG, starkAccount);
53
+ ```
54
+
55
+ ### 2. Place an Order
56
+
57
+ ```typescript
58
+ import { OrderSide } from 'extended-typescript-sdk';
59
+ import Decimal from 'decimal.js';
60
+
61
+ const placedOrder = await tradingClient.placeOrder({
62
+ marketName: 'BTC-USD',
63
+ amountOfSynthetic: new Decimal('1'),
64
+ price: new Decimal('63000.1'),
65
+ side: OrderSide.SELL,
66
+ });
67
+
68
+ console.log('Placed order:', placedOrder);
69
+
70
+ // Cancel the order
71
+ await tradingClient.orders.cancelOrder(placedOrder.id);
72
+ ```
73
+
74
+ ### 3. Get Account Information
75
+
76
+ ```typescript
77
+ // Get balance
78
+ const balance = await tradingClient.account.getBalance();
79
+ console.log('Balance:', balance.toPrettyJson());
80
+
81
+ // Get positions
82
+ const positions = await tradingClient.account.getPositions();
83
+ console.log('Positions:', positions.toPrettyJson());
84
+
85
+ // Get open orders
86
+ const openOrders = await tradingClient.account.getOpenOrders();
87
+ console.log('Open orders:', openOrders.toPrettyJson());
88
+ ```
89
+
90
+ ### 4. Onboarding (User Client)
91
+
92
+ ```typescript
93
+ import { UserClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
94
+
95
+ // Create user client
96
+ const userClient = new UserClient(TESTNET_CONFIG, () => ethPrivateKey);
97
+
98
+ // Onboard new account
99
+ const account = await userClient.onboard();
100
+
101
+ // Get API key
102
+ const apiKey = await userClient.createAccountApiKey(account.account, 'My trading key');
103
+
104
+ // Use the account
105
+ const starkAccount = new StarkPerpetualAccount(
106
+ account.account.l2Vault,
107
+ account.l2KeyPair.privateHex,
108
+ account.l2KeyPair.publicHex,
109
+ apiKey
110
+ );
111
+
112
+ const client = new PerpetualTradingClient(TESTNET_CONFIG, starkAccount);
113
+ ```
114
+
115
+ ### 5. Stream Data
116
+
117
+ ```typescript
118
+ import { PerpetualStreamClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
119
+
120
+ const streamClient = new PerpetualStreamClient({
121
+ apiUrl: TESTNET_CONFIG.streamUrl,
122
+ });
123
+
124
+ // Subscribe to orderbooks
125
+ const orderbookStream = streamClient.subscribeToOrderbooks({ marketName: 'BTC-USD' });
126
+ await orderbookStream.connect();
127
+
128
+ for await (const update of orderbookStream) {
129
+ console.log('Orderbook update:', update);
130
+ }
131
+
132
+ // Subscribe to public trades
133
+ const tradesStream = streamClient.subscribeToPublicTrades('BTC-USD');
134
+ await tradesStream.connect();
135
+
136
+ for await (const trade of tradesStream) {
137
+ console.log('Trade:', trade);
138
+ }
139
+
140
+ // Subscribe to funding rates
141
+ const fundingStream = streamClient.subscribeToFundingRates('BTC-USD');
142
+ await fundingStream.connect();
143
+
144
+ for await (const fundingUpdate of fundingStream) {
145
+ console.log('Funding rate:', fundingUpdate);
146
+ }
147
+
148
+ // Subscribe to candles (OHLCV data)
149
+ const candlesStream = streamClient.subscribeToCandles({
150
+ marketName: 'BTC-USD',
151
+ candleType: 'trades', // 'trades', 'mark-prices', or 'index-prices'
152
+ interval: 'PT1M', // ISO 8601 duration (PT1M, PT5M, PT15M, PT1H, etc.)
153
+ });
154
+ await candlesStream.connect();
155
+
156
+ for await (const candle of candlesStream) {
157
+ console.log('Candle:', candle);
158
+ }
159
+
160
+ // Subscribe to mark price updates
161
+ const markPriceStream = streamClient.subscribeToMarkPrice('BTC-USD');
162
+ await markPriceStream.connect();
163
+
164
+ for await (const priceUpdate of markPriceStream) {
165
+ console.log('Mark price:', priceUpdate);
166
+ }
167
+
168
+ // Subscribe to index price updates
169
+ const indexPriceStream = streamClient.subscribeToIndexPrice('BTC-USD');
170
+ await indexPriceStream.connect();
171
+
172
+ for await (const priceUpdate of indexPriceStream) {
173
+ console.log('Index price:', priceUpdate);
174
+ }
175
+
176
+ // Subscribe to account updates (requires API key)
177
+ const accountStream = streamClient.subscribeToAccountUpdates(apiKey);
178
+ await accountStream.connect();
179
+
180
+ for await (const update of accountStream) {
181
+ console.log('Account update:', update);
182
+ }
183
+ ```
184
+
185
+ ## WASM Signer
186
+
187
+ The SDK includes a pre-built WASM signer that works in both **Node.js** and **browser** environments. **No Rust installation is required to use the SDK.**
188
+
189
+ ### Using the Pre-built Signer
190
+
191
+ The SDK ships with pre-built WASM files. Simply use the SDK:
192
+
193
+ ```typescript
194
+ import { initWasm, sign } from 'extended-typescript-sdk';
195
+
196
+ await initWasm(); // Automatically loads the correct WASM for your environment
197
+ const [r, s] = sign(privateKey, msgHash);
198
+ ```
199
+
200
+ The signer automatically detects your environment (Node.js or browser) and loads the appropriate WASM module.
201
+
202
+ ### Custom Signer Support (Privy, Web3Auth, etc.)
203
+
204
+ The SDK supports **custom signers** for integration with remote signing services like Privy, Web3Auth, or hardware wallets:
205
+
206
+ ```typescript
207
+ import {
208
+ CustomStarkSigner,
209
+ createStarkPerpetualAccountWithCustomSigner
210
+ } from 'extended-typescript-sdk';
211
+
212
+ // Implement the CustomStarkSigner interface
213
+ class PrivyStarkSigner implements CustomStarkSigner {
214
+ constructor(private privyClient: any, private walletId: string) {}
215
+
216
+ async sign(msgHash: bigint): Promise<[bigint, bigint]> {
217
+ const msgHashHex = '0x' + msgHash.toString(16);
218
+ const signature = await this.privyClient.signStarknetMessage(
219
+ this.walletId,
220
+ msgHashHex
221
+ );
222
+ return [BigInt(signature.r), BigInt(signature.s)];
223
+ }
224
+ }
225
+
226
+ // Create account with custom signer
227
+ const privySigner = new PrivyStarkSigner(privyClient, walletId);
228
+ const account = createStarkPerpetualAccountWithCustomSigner(
229
+ vaultId,
230
+ publicKeyHex,
231
+ apiKey,
232
+ privySigner
233
+ );
234
+
235
+ // Use normally - signing will be handled by Privy
236
+ const client = new PerpetualTradingClient(TESTNET_CONFIG, account);
237
+ ```
238
+
239
+ See [examples/16_privy_integration.ts](./examples/16_privy_integration.ts) for a complete example.
240
+
241
+ ### Building Your Own WASM Signer
242
+
243
+ If you want to build your own WASM signer (requires Rust and wasm-pack):
244
+
245
+ ```bash
246
+ npm run build:signer:custom
247
+ ```
248
+
249
+ **Prerequisites:**
250
+ 1. Install Rust: https://www.rust-lang.org/tools/install
251
+ 2. Install wasm-pack: `cargo install wasm-pack`
252
+
253
+ This will build both Node.js and browser targets and replace the shipped WASM signer.
254
+
255
+ ### Implementation
256
+
257
+ The WASM signer uses `starknet-crypto` crate for cryptographic operations. It's production-ready and tested for compatibility with Extended Exchange API.
258
+
259
+ ## API Documentation
260
+
261
+ ### Trading Client
262
+
263
+ ```typescript
264
+ import { PerpetualTradingClient, TESTNET_CONFIG } from 'extended-typescript-sdk';
265
+
266
+ const client = new PerpetualTradingClient(config, account);
267
+
268
+ // Place order
269
+ await client.placeOrder({
270
+ marketName: 'BTC-USD',
271
+ amountOfSynthetic: new Decimal('1'),
272
+ price: new Decimal('63000'),
273
+ side: OrderSide.BUY,
274
+ });
275
+
276
+ // Account module
277
+ await client.account.getBalance();
278
+ await client.account.getPositions();
279
+ await client.account.getOpenOrders();
280
+ await client.account.updateLeverage('BTC-USD', new Decimal('10'));
281
+
282
+ // Orders module
283
+ await client.orders.cancelOrder(orderId);
284
+ await client.orders.cancelOrderByExternalId(externalId);
285
+ await client.orders.massCancel({ markets: ['BTC-USD'] });
286
+
287
+ // Markets module
288
+ await client.marketsInfo.getMarkets();
289
+ await client.marketsInfo.getMarketStatistics('BTC-USD');
290
+ await client.marketsInfo.getOrderbookSnapshot('BTC-USD');
291
+ ```
292
+
293
+ ### User Client (Onboarding)
294
+
295
+ ```typescript
296
+ import { UserClient } from 'extended-typescript-sdk';
297
+
298
+ const userClient = new UserClient(config, () => ethPrivateKey);
299
+
300
+ // Onboard new account
301
+ const account = await userClient.onboard();
302
+
303
+ // Onboard subaccount
304
+ const subaccount = await userClient.onboardSubaccount(1, 'My subaccount');
305
+
306
+ // Get all accounts
307
+ const accounts = await userClient.getAccounts();
308
+
309
+ // Create API key
310
+ const apiKey = await userClient.createAccountApiKey(account.account, 'description');
311
+ ```
312
+
313
+ ### Stream Client
314
+
315
+ ```typescript
316
+ import { PerpetualStreamClient } from 'extended-typescript-sdk';
317
+
318
+ const streamClient = new PerpetualStreamClient({ apiUrl: config.streamUrl });
319
+
320
+ // Subscribe to orderbooks
321
+ const orderbookStream = streamClient.subscribeToOrderbooks({
322
+ marketName: 'BTC-USD',
323
+ depth: 10,
324
+ });
325
+
326
+ // Subscribe to public trades
327
+ const tradesStream = streamClient.subscribeToPublicTrades('BTC-USD');
328
+
329
+ // Subscribe to funding rates
330
+ const fundingStream = streamClient.subscribeToFundingRates('BTC-USD');
331
+
332
+ // Subscribe to account updates (requires API key)
333
+ const accountStream = streamClient.subscribeToAccountUpdates(apiKey);
334
+ ```
335
+
336
+ ## Environment Configuration
337
+
338
+ The SDK supports different environments:
339
+
340
+ ```typescript
341
+ import { TESTNET_CONFIG, MAINNET_CONFIG } from 'extended-typescript-sdk';
342
+
343
+ // Use testnet
344
+ const client = new PerpetualTradingClient(TESTNET_CONFIG, account);
345
+
346
+ // Use mainnet
347
+ const client = new PerpetualTradingClient(MAINNET_CONFIG, account);
348
+ ```
349
+
350
+ ## TypeScript Support
351
+
352
+ This SDK is written in TypeScript and provides full type definitions. All types are exported:
353
+
354
+ ```typescript
355
+ import {
356
+ OrderSide,
357
+ OrderType,
358
+ OrderStatus,
359
+ TimeInForce,
360
+ StarkPerpetualAccount,
361
+ PerpetualTradingClient,
362
+ UserClient,
363
+ PerpetualStreamClient,
364
+ // ... and more
365
+ } from 'extended-typescript-sdk';
366
+ ```
367
+
368
+ ## Error Handling
369
+
370
+ The SDK provides specific error types:
371
+
372
+ ```typescript
373
+ import {
374
+ X10Error,
375
+ RateLimitException,
376
+ NotAuthorizedException,
377
+ SubAccountExists,
378
+ } from 'extended-typescript-sdk';
379
+
380
+ try {
381
+ await client.placeOrder({ ... });
382
+ } catch (error) {
383
+ if (error instanceof RateLimitException) {
384
+ // Handle rate limit
385
+ } else if (error instanceof NotAuthorizedException) {
386
+ // Handle authentication error
387
+ }
388
+ }
389
+ ```
390
+
391
+ ## Examples
392
+
393
+ See `examples/` directory for complete examples:
394
+
395
+ - Basic order placement
396
+ - Onboarding flow
397
+ - Stream subscriptions
398
+ - Market data access
399
+ - Account management
400
+
401
+ ## WASM Performance
402
+
403
+ The WASM signer provides ~90-95% of native Rust performance:
404
+
405
+ ```
406
+ Native Rust: ~50μs per signature
407
+ WASM (Rust): ~55μs per signature (10% slower)
408
+ Pure JavaScript: ~500μs per signature (10x slower)
409
+ ```
410
+
411
+ The performance difference is negligible in real-world applications.
412
+
413
+ ## Building the SDK
414
+
415
+ ### For Users (No Build Required)
416
+
417
+ The SDK ships with pre-built WASM signer - just install and use:
418
+
419
+ ```bash
420
+ npm install extended-typescript-sdk
421
+ ```
422
+
423
+ ### For Developers
424
+
425
+ If you're developing the SDK or want to build your own WASM signer:
426
+
427
+ ```bash
428
+ # Install dependencies
429
+ npm install
430
+
431
+ # Build WASM signer (requires Rust and wasm-pack)
432
+ npm run build:signer
433
+
434
+ # Build TypeScript
435
+ npm run build:ts
436
+
437
+ # Build everything
438
+ npm run build # Builds both WASM signer and TypeScript
439
+
440
+ # Build custom WASM signer (for users who want to replace shipped WASM)
441
+ npm run build:signer:custom
442
+ ```
443
+
444
+ ### Build Commands
445
+
446
+ - `npm run build` - Builds WASM signer and TypeScript (full build)
447
+ - `npm run build:signer` - Builds WASM signer for both Node.js and browser
448
+ - `npm run build:signer:custom` - Build your own WASM signer (requires Rust)
449
+ - `npm run build:ts` - Build TypeScript only
450
+ - `npm run clean` - Clean all build artifacts
451
+
452
+ ### Development Commands
453
+
454
+ ```bash
455
+ # Run tests
456
+ npm test
457
+
458
+ # Lint
459
+ npm run lint
460
+
461
+ # Format code
462
+ npm run format
463
+ ```
464
+
465
+ ## Contributing
466
+
467
+ 1. Clone the repository
468
+ 2. Install dependencies: `npm install`
469
+ 3. Install Rust and wasm-pack (only if building WASM signer)
470
+ 4. Build: `npm run build`
471
+ 5. Run tests: `npm test`
472
+
473
+ ## License
474
+
475
+ MIT
476
+
477
+ ## Support
478
+
479
+ For issues and questions:
480
+ - GitHub: https://github.com/Bvvvp009/Extended-TS-SDK
481
+ - Documentation: https://api.docs.extended.exchange/
482
+ - Extended Exchange: https://extended.exchange/
483
+
484
+ **Note**: This is an unofficial, community-maintained SDK. For official support, please contact Extended Exchange directly.
485
+
486
+ ## Environment Support
487
+
488
+ - ✅ Node.js (v18+)
489
+ - ✅ Browsers (Chrome/Firefox/Safari/Edge)
490
+ - ✅ PWAs
491
+ - ✅ React Native (with polyfills or custom signer)
492
+ - ✅ Electron
493
+ - ⚠️ Native iOS/Android (via React Native or WebView)
494
+
495
+ Details and setup notes: see [ENVIRONMENT_SUPPORT.md](ENVIRONMENT_SUPPORT.md).
496
+
497
+ ## API Coverage
498
+
499
+ See [API_COVERAGE.md](./API_COVERAGE.md) for complete API endpoint coverage analysis.
500
+
501
+ ## Standalone Signer Functions
502
+
503
+ The cryptographic signer functions are exported from the main SDK package for standalone use:
504
+
505
+ ```typescript
506
+ import {
507
+ initWasm,
508
+ sign,
509
+ pedersenHash,
510
+ getOrderMsgHash,
511
+ getTransferMsgHash,
512
+ getWithdrawalMsgHash,
513
+ generateKeypairFromEthSignature
514
+ } from 'extended-typescript-sdk';
515
+
516
+ // Initialize WASM module (required first!)
517
+ await initWasm();
518
+
519
+ // Sign a message hash
520
+ const privateKey = BigInt('0x...');
521
+ const msgHash = BigInt('0x...');
522
+ const [r, s] = sign(privateKey, msgHash);
523
+
524
+ // Compute Pedersen hash
525
+ const hash = pedersenHash(BigInt('0x123'), BigInt('0x456'));
526
+
527
+ // Generate order message hash (for custom order signing)
528
+ const orderHash = getOrderMsgHash({
529
+ positionId: 12345,
530
+ baseAssetId: '0x...',
531
+ baseAmount: '1000000',
532
+ // ... other order parameters
533
+ });
534
+
535
+ // Generate keypair from Ethereum signature (for onboarding)
536
+ const [privateKey, publicKey] = generateKeypairFromEthSignature(ethSignature);
537
+ ```
538
+
539
+ All signer functions are documented with JSDoc comments. See the [signer source code](./src/perpetual/crypto/signer.ts) for detailed documentation.