@ultrade/ultrade-js-sdk 2.0.4 → 2.0.5

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.
package/README.md CHANGED
@@ -5,6 +5,12 @@ JavaScript/TypeScript SDK for Ultrade platform integration.
5
5
 
6
6
  The `@ultrade/ultrade-js-sdk` package provides a JavaScript/TypeScript interface for interacting with ULTRADE's V2 platform, the Native Exchange (NEX) with Bridgeless Crosschain Orderbook technology. It offers a simple interface for creating and managing orders, as well as for interacting with the Ultrade API and WebSocket streams.
7
7
 
8
+ ### Dependencies
9
+
10
+ This package uses [`@ultrade/shared`](https://github.com/ultrade-org/ultrade-shared) as a core dependency. Many types, interfaces, enums, and utility functions are imported from the shared package, which provides common code, utilities, and types for Ultrade platform packages.
11
+
12
+ **Shared Package Repository:** [https://github.com/ultrade-org/ultrade-shared](https://github.com/ultrade-org/ultrade-shared)
13
+
8
14
  ### Key Features
9
15
 
10
16
  - **Deposits**: Always credited to the logged in account
@@ -84,14 +90,14 @@ const client = new Client({
84
90
  ## Table of Contents
85
91
 
86
92
  1. [Authentication & Wallet](#authentication--wallet)
87
- 2. [Market Data](#market-data)
88
- 3. [Trading](#trading)
89
- 4. [Account & Balances](#account--balances)
90
- 5. [Wallet Operations](#wallet-operations)
91
- 6. [Whitelist & Withdrawal Wallets](#whitelist--withdrawal-wallets)
92
- 7. [KYC](#kyc)
93
- 8. [WebSocket](#websocket)
94
- 9. [System](#system)
93
+ 2. [System](#system)
94
+ 3. [Market Data](#market-data)
95
+ 4. [Trading](#trading)
96
+ 5. [Account & Balances](#account--balances)
97
+ 6. [Wallet Operations](#wallet-operations)
98
+ 7. [Whitelist & Withdrawal Wallets](#whitelist--withdrawal-wallets)
99
+ 8. [KYC](#kyc)
100
+ 9. [WebSocket](#websocket)
95
101
  10. [Notifications](#notifications)
96
102
  11. [Affiliates](#affiliates)
97
103
  12. [Social](#social)
@@ -105,18 +111,23 @@ const client = new Client({
105
111
 
106
112
  Authenticate a user with their wallet.
107
113
 
114
+ **Type imports:**
115
+ ```typescript
116
+ import { PROVIDERS, ILoginData } from '@ultrade/shared/browser/interfaces';
117
+ ```
118
+
108
119
  **Parameters:**
109
120
 
110
121
  | Name | Type | Required | Description |
111
122
  |------|------|----------|-------------|
112
123
  | `data` | `ILoginData` | Yes | Login data object |
113
124
 
114
- **ILoginData interface:**
125
+ **ILoginData interface** (from `@ultrade/shared`):
115
126
 
116
127
  | Property | Type | Required | Description |
117
128
  |----------|------|----------|-------------|
118
129
  | `address` | `string` | Yes | Wallet address |
119
- | `provider` | `PROVIDERS` | Yes | Wallet provider (PERA, METAMASK, etc.) |
130
+ | `provider` | `PROVIDERS` | Yes | Wallet provider enum (imported from `@ultrade/shared/browser/interfaces`, see [`PROVIDERS` enum](https://github.com/ultrade-org/ultrade-shared)) |
120
131
  | `chain` | `string` | No | Blockchain chain |
121
132
  | `referralToken` | `string` | No | Referral token |
122
133
  | `loginMessage` | `string` | No | Custom login message |
@@ -126,7 +137,7 @@ Authenticate a user with their wallet.
126
137
  **Example:**
127
138
 
128
139
  ```typescript
129
- import { PROVIDERS } from '@ultrade/ultrade-js-sdk';
140
+ import { PROVIDERS, ILoginData } from '@ultrade/shared/browser/interfaces';
130
141
  import algosdk from 'algosdk';
131
142
  import { encodeBase64 } from '@ultrade/shared/browser/helpers';
132
143
 
@@ -187,29 +198,34 @@ client.mainWallet = {
187
198
 
188
199
  Create a new trading key for automated trading.
189
200
 
201
+ **Type imports:**
202
+ ```typescript
203
+ import { ITradingKeyData, TradingKeyType } from '@ultrade/shared/browser/interfaces';
204
+ ```
205
+
190
206
  **Parameters:**
191
207
 
192
208
  | Name | Type | Required | Description |
193
209
  |------|------|----------|-------------|
194
210
  | `data` | `ITradingKeyData` | Yes | Trading key data object |
195
211
 
196
- **ITradingKeyData interface:**
212
+ **ITradingKeyData interface** (from `@ultrade/shared`):
197
213
 
198
214
  | Property | Type | Required | Description |
199
215
  |----------|------|----------|-------------|
200
216
  | `tkAddress` | `string` | Yes | Trading key address |
201
- | `device` | `string` | Yes | Device identifier |
202
- | `type` | `TradingKeyType` | Yes | Key type (User or Bot) |
217
+ | `device` | `string` | No | Device identifier (user agent string, e.g., "Chrome 123.0.0.0 Blink Linux, desktop", "Chrome 121.0.0.0 Blink Android, mobile") |
218
+ | `type` | `TradingKeyType` | No | Key type enum (imported from `@ultrade/shared/browser/interfaces`, see [`TradingKeyType` enum](https://github.com/ultrade-org/ultrade-shared)) |
203
219
  | `expiredDate` | `number` | No | Expiration timestamp (ms) |
204
220
  | `loginAddress` | `string` | Yes | Login wallet address |
205
- | `loginChainId` | `string \| number` | Yes | Login chain ID |
221
+ | `loginChainId` | `number` | Yes | Login chain ID |
206
222
 
207
223
  **Returns:** `Promise<TradingKeyView>`
208
224
 
209
225
  **Example:**
210
226
 
211
227
  ```typescript
212
- import { TradingKeyType } from '@ultrade/ultrade-js-sdk';
228
+ import { ITradingKeyData, TradingKeyType } from '@ultrade/shared/browser/interfaces';
213
229
  import algosdk from 'algosdk';
214
230
 
215
231
  // Generate new trading key account
@@ -219,21 +235,19 @@ const mnemonic = algosdk.secretKeyToMnemonic(generatedAccount.sk);
219
235
  // Expiration: 30 days from now (in milliseconds)
220
236
  const expirationTime = Date.now() + 30 * 24 * 60 * 60 * 1000;
221
237
 
222
- // Get device info
223
- const getDeviceInfo = () => {
224
- const ua = navigator.userAgent;
225
- if (/mobile/i.test(ua)) return 'mobile';
226
- if (/tablet/i.test(ua)) return 'tablet';
227
- return 'desktop';
228
- };
238
+ // Get device info (returns full user agent string)
239
+ // Examples: "Chrome 123.0.0.0 Blink Linux, desktop",
240
+ // "Chrome 121.0.0.0 Blink Android, mobile",
241
+ // "Miui 14.4.0 Blink Android, mobile"
242
+ const device = navigator.userAgent;
229
243
 
230
244
  // Create trading key data
231
245
  const tkData = {
232
246
  tkAddress: generatedAccount.addr,
233
247
  expiredDate: expirationTime,
234
248
  loginAddress: client.mainWallet.address,
235
- loginChainId: 'algorand',
236
- device: getDeviceInfo(),
249
+ loginChainId: 1, // Chain ID (e.g., 1 for Algorand)
250
+ device: device, // e.g., "Chrome 123.0.0.0 Blink Linux, desktop"
237
251
  type: TradingKeyType.User
238
252
  };
239
253
 
@@ -261,33 +275,40 @@ client.mainWallet.tradingKey = generatedAccount.addr;
261
275
 
262
276
  Revoke an existing trading key.
263
277
 
278
+ **Type imports:**
279
+ ```typescript
280
+ import { ITradingKeyData, TradingKeyType } from '@ultrade/shared/browser/interfaces';
281
+ ```
282
+
264
283
  **Parameters:**
265
284
 
266
285
  | Name | Type | Required | Description |
267
286
  |------|------|----------|-------------|
268
287
  | `data` | `ITradingKeyData` | Yes | Trading key data object |
269
288
 
270
- **ITradingKeyData interface:**
289
+ **ITradingKeyData interface** (from `@ultrade/shared`):
271
290
 
272
291
  | Property | Type | Required | Description |
273
292
  |----------|------|----------|-------------|
274
293
  | `tkAddress` | `string` | Yes | Trading key address to revoke |
275
- | `device` | `string` | Yes | Device identifier |
276
- | `type` | `TradingKeyType` | Yes | Key type |
294
+ | `device` | `string` | No | Device identifier (user agent string, e.g., "Chrome 123.0.0.0 Blink Linux, desktop", "Chrome 121.0.0.0 Blink Android, mobile") |
295
+ | `type` | `TradingKeyType` | No | Key type enum (imported from `@ultrade/shared/browser/interfaces`, see [`TradingKeyType` enum](https://github.com/ultrade-org/ultrade-shared)) |
277
296
  | `loginAddress` | `string` | Yes | Login wallet address |
278
- | `loginChainId` | `string \| number` | Yes | Login chain ID |
297
+ | `loginChainId` | `number` | Yes | Login chain ID |
279
298
 
280
299
  **Returns:** `Promise<IRevokeTradingKeyResponse>`
281
300
 
282
301
  **Example:**
283
302
 
284
303
  ```typescript
304
+ import { ITradingKeyData, TradingKeyType } from '@ultrade/shared/browser/interfaces';
305
+
285
306
  await client.revokeTradingKey({
286
307
  tkAddress: 'TK_ADDRESS_HERE',
287
- device: 'web-browser',
308
+ device: navigator.userAgent, // e.g., "Chrome 123.0.0.0 Blink Linux, desktop"
288
309
  type: TradingKeyType.User,
289
310
  loginAddress: client.mainWallet?.address || '',
290
- loginChainId: 'algorand'
311
+ loginChainId: 1 // Chain ID (e.g., 1 for Algorand)
291
312
  });
292
313
 
293
314
  console.log('Trading key revoked');
@@ -295,6 +316,207 @@ console.log('Trading key revoked');
295
316
 
296
317
  ---
297
318
 
319
+ ## System
320
+
321
+ ### getSettings
322
+
323
+ Get platform settings.
324
+
325
+ **Returns:** `Promise<SettingsInit>`
326
+
327
+ **Note:** Returns an object with dynamic keys based on `SettingIds` enum. Common properties include:
328
+ - `partnerId`: Partner ID
329
+ - `isUltrade`: Whether it's Ultrade platform
330
+ - `companyId`: Company ID
331
+ - `currentCountry`: Current country (optional)
332
+ - Various setting values indexed by `SettingIds` enum keys
333
+
334
+ **Example:**
335
+
336
+ ```typescript
337
+ const settings = await client.getSettings();
338
+
339
+ console.log('Company ID:', settings.companyId);
340
+ console.log('Partner ID:', settings.partnerId);
341
+ console.log('Is Ultrade:', settings.isUltrade);
342
+ console.log('Current country:', settings.currentCountry);
343
+ // Access specific settings by SettingIds enum
344
+ console.log('App title:', settings[SettingIds.APP_TITLE]);
345
+ ```
346
+
347
+ ### getVersion
348
+
349
+ Get API version information.
350
+
351
+ **Returns:** `Promise<ISystemVersion>`
352
+
353
+ **ISystemVersion interface:**
354
+
355
+ | Property | Type | Description |
356
+ |----------|------|-------------|
357
+ | `version` | `string \| null` | API version string |
358
+
359
+ **Example:**
360
+
361
+ ```typescript
362
+ const version = await client.getVersion();
363
+
364
+ console.log('API version:', version.version);
365
+ ```
366
+
367
+ ### getMaintenance
368
+
369
+ Get maintenance status.
370
+
371
+ **Returns:** `Promise<ISystemMaintenance>`
372
+
373
+ **ISystemMaintenance interface:**
374
+
375
+ | Property | Type | Description |
376
+ |----------|------|-------------|
377
+ | `mode` | `MaintenanceMode` | Maintenance mode enum |
378
+
379
+ **Example:**
380
+
381
+ ```typescript
382
+ import { MaintenanceMode } from '@ultrade/ultrade-js-sdk';
383
+
384
+ const maintenance = await client.getMaintenance();
385
+
386
+ if (maintenance.mode === MaintenanceMode.ACTIVE) {
387
+ console.log('Platform is under maintenance');
388
+ }
389
+ ```
390
+
391
+ ### ping
392
+
393
+ Check latency to the server.
394
+
395
+ **Returns:** `Promise<number>` - Latency in milliseconds
396
+
397
+ **Example:**
398
+
399
+ ```typescript
400
+ const latency = await client.ping();
401
+
402
+ console.log(`Server latency: ${latency}ms`);
403
+ ```
404
+
405
+ ### getChains
406
+
407
+ Get supported blockchain chains.
408
+
409
+ **Returns:** `Promise<Chain[]>`
410
+
411
+ **Chain interface:**
412
+
413
+ | Property | Type | Description |
414
+ |----------|------|-------------|
415
+ | `chainId` | `number` | Chain ID |
416
+ | `whChainId` | `string` | Wormhole chain ID |
417
+ | `tmc` | `string` | TMC identifier |
418
+ | `name` | `BLOCKCHAINS` | Blockchain name enum |
419
+
420
+ **Example:**
421
+
422
+ ```typescript
423
+ const chains = await client.getChains();
424
+
425
+ chains.forEach(chain => {
426
+ console.log(`${chain.name} (Chain ID: ${chain.chainId}, WH Chain ID: ${chain.whChainId})`);
427
+ });
428
+ ```
429
+
430
+ ### getDollarValues
431
+
432
+ Get USD values for assets.
433
+
434
+ **Parameters:**
435
+
436
+ | Name | Type | Required | Description |
437
+ |------|------|----------|-------------|
438
+ | `assetIds` | `number[]` | No | Array of asset IDs (default: empty array for all) |
439
+
440
+ **Returns:** `Promise<IGetDollarValues>`
441
+
442
+ **Note:** Returns an object with dynamic keys (`[key: string]: number`), where keys are asset IDs and values are USD prices.
443
+
444
+ **Example:**
445
+
446
+ ```typescript
447
+ // Get prices for specific assets
448
+ const prices = await client.getDollarValues([0, 1, 2]);
449
+
450
+ // Get prices for all assets
451
+ const allPrices = await client.getDollarValues();
452
+
453
+ // Access prices by asset ID
454
+ Object.keys(prices).forEach(assetId => {
455
+ console.log(`Asset ${assetId}: $${prices[assetId]}`);
456
+ });
457
+ ```
458
+
459
+ ### getTransactionDetalis
460
+
461
+ Get detailed transaction information.
462
+
463
+ **Parameters:**
464
+
465
+ | Name | Type | Required | Description |
466
+ |------|------|----------|-------------|
467
+ | `transactionId` | `number` | Yes | Transaction ID |
468
+
469
+ **Returns:** `Promise<ITransactionDetails>`
470
+
471
+ **Example:**
472
+
473
+ ```typescript
474
+ const details = await client.getTransactionDetalis(12345);
475
+
476
+ console.log('Transaction:', {
477
+ id: details.id,
478
+ primaryId: details.primaryId,
479
+ actionType: details.action_type,
480
+ amount: details.amount,
481
+ status: details.status,
482
+ targetAddress: details.targetAddress,
483
+ timestamp: details.timestamp,
484
+ createdAt: details.createdAt,
485
+ fee: details.fee
486
+ });
487
+ ```
488
+
489
+ ### getWithdrawalFee
490
+
491
+ Get withdrawal fee for an asset.
492
+
493
+ **Parameters:**
494
+
495
+ | Name | Type | Required | Description |
496
+ |------|------|----------|-------------|
497
+ | `assetAddress` | `string` | Yes | Asset address |
498
+ | `chainId` | `number` | Yes | Chain ID |
499
+
500
+ **Returns:** `Promise<IWithdrawalFee>`
501
+
502
+ **IWithdrawalFee interface:**
503
+
504
+ | Property | Type | Description |
505
+ |----------|------|-------------|
506
+ | `fee` | `string` | Withdrawal fee amount |
507
+ | `dollarValue` | `string` | Fee value in USD |
508
+
509
+ **Example:**
510
+
511
+ ```typescript
512
+ const fee = await client.getWithdrawalFee('ASSET_ADDRESS', 1);
513
+
514
+ console.log('Withdrawal fee:', fee.fee);
515
+ console.log('Fee in USD:', fee.dollarValue);
516
+ ```
517
+
518
+ ---
519
+
298
520
  ## Market Data
299
521
 
300
522
  ### getPairList
@@ -447,7 +669,7 @@ Get list of trading pairs matching a pattern.
447
669
 
448
670
  | Name | Type | Required | Description |
449
671
  |------|------|----------|-------------|
450
- | `mask` | `string` | No | Search mask (e.g., 'ALGO*') |
672
+ | `mask` | `string` | No | Search mask (e.g., 'ALGO') |
451
673
 
452
674
  **Returns:** `Promise<IGetSymbols>`
453
675
 
@@ -462,7 +684,7 @@ Get list of trading pairs matching a pattern.
462
684
  **Example:**
463
685
 
464
686
  ```typescript
465
- const symbols = await client.getSymbols('ALGO*');
687
+ const symbols = await client.getSymbols('ALGO');
466
688
 
467
689
  symbols.forEach(symbol => {
468
690
  console.log('Pair:', symbol.pairKey);
@@ -564,9 +786,9 @@ Place a new order.
564
786
 
565
787
  | Name | Type | Required | Description |
566
788
  |------|------|----------|-------------|
567
- | `order` | `CreateOrderArgs` | Yes | Order creation data object |
789
+ | `order` | `CreateSpotOrderArgs` | Yes | Order creation data object |
568
790
 
569
- **CreateOrderArgs interface:**
791
+ **CreateSpotOrderArgs interface:**
570
792
 
571
793
  | Property | Type | Required | Description |
572
794
  |----------|------|----------|-------------|
@@ -1086,6 +1308,12 @@ console.log('Pending transactions:', pending.length);
1086
1308
 
1087
1309
  Get user's trading keys.
1088
1310
 
1311
+ **Type imports:**
1312
+ ```typescript
1313
+ import { ITradingKey } from '@ultrade/ultrade-js-sdk';
1314
+ import { TradingKeyType } from '@ultrade/shared/browser/interfaces';
1315
+ ```
1316
+
1089
1317
  **Returns:** `Promise<ITradingKey>`
1090
1318
 
1091
1319
  **Note:** Returns a single `ITradingKey` object, not an array.
@@ -1098,12 +1326,14 @@ Get user's trading keys.
1098
1326
  | `createdAt` | `Date` | Creation timestamp |
1099
1327
  | `expiredAt` | `Date` | Expiration timestamp |
1100
1328
  | `orders` | `number` | Number of orders |
1101
- | `device` | `string` | Device identifier |
1102
- | `type` | `TradingKeyType` | Key type (optional) |
1329
+ | `device` | `string` | Device identifier (user agent string, e.g., "Chrome 123.0.0.0 Blink Linux, desktop", "Chrome 121.0.0.0 Blink Android, mobile") |
1330
+ | `type` | `TradingKeyType` | Key type enum (optional, imported from `@ultrade/shared/browser/interfaces`, see [`TradingKeyType` enum](https://github.com/ultrade-org/ultrade-shared)) |
1103
1331
 
1104
1332
  **Example:**
1105
1333
 
1106
1334
  ```typescript
1335
+ import { TradingKeyType } from '@ultrade/shared/browser/interfaces';
1336
+
1107
1337
  const tradingKey = await client.getTradingKeys();
1108
1338
 
1109
1339
  console.log('Trading key address:', tradingKey.address);
@@ -1453,207 +1683,6 @@ client.unsubscribe(handlerId);
1453
1683
 
1454
1684
  ---
1455
1685
 
1456
- ## System
1457
-
1458
- ### getSettings
1459
-
1460
- Get platform settings.
1461
-
1462
- **Returns:** `Promise<SettingsInit>`
1463
-
1464
- **Note:** Returns an object with dynamic keys based on `SettingIds` enum. Common properties include:
1465
- - `partnerId`: Partner ID
1466
- - `isUltrade`: Whether it's Ultrade platform
1467
- - `companyId`: Company ID
1468
- - `currentCountry`: Current country (optional)
1469
- - Various setting values indexed by `SettingIds` enum keys
1470
-
1471
- **Example:**
1472
-
1473
- ```typescript
1474
- const settings = await client.getSettings();
1475
-
1476
- console.log('Company ID:', settings.companyId);
1477
- console.log('Partner ID:', settings.partnerId);
1478
- console.log('Is Ultrade:', settings.isUltrade);
1479
- console.log('Current country:', settings.currentCountry);
1480
- // Access specific settings by SettingIds enum
1481
- console.log('App title:', settings[SettingIds.APP_TITLE]);
1482
- ```
1483
-
1484
- ### getVersion
1485
-
1486
- Get API version information.
1487
-
1488
- **Returns:** `Promise<ISystemVersion>`
1489
-
1490
- **ISystemVersion interface:**
1491
-
1492
- | Property | Type | Description |
1493
- |----------|------|-------------|
1494
- | `version` | `string \| null` | API version string |
1495
-
1496
- **Example:**
1497
-
1498
- ```typescript
1499
- const version = await client.getVersion();
1500
-
1501
- console.log('API version:', version.version);
1502
- ```
1503
-
1504
- ### getMaintenance
1505
-
1506
- Get maintenance status.
1507
-
1508
- **Returns:** `Promise<ISystemMaintenance>`
1509
-
1510
- **ISystemMaintenance interface:**
1511
-
1512
- | Property | Type | Description |
1513
- |----------|------|-------------|
1514
- | `mode` | `MaintenanceMode` | Maintenance mode enum |
1515
-
1516
- **Example:**
1517
-
1518
- ```typescript
1519
- import { MaintenanceMode } from '@ultrade/ultrade-js-sdk';
1520
-
1521
- const maintenance = await client.getMaintenance();
1522
-
1523
- if (maintenance.mode === MaintenanceMode.ACTIVE) {
1524
- console.log('Platform is under maintenance');
1525
- }
1526
- ```
1527
-
1528
- ### ping
1529
-
1530
- Check latency to the server.
1531
-
1532
- **Returns:** `Promise<number>` - Latency in milliseconds
1533
-
1534
- **Example:**
1535
-
1536
- ```typescript
1537
- const latency = await client.ping();
1538
-
1539
- console.log(`Server latency: ${latency}ms`);
1540
- ```
1541
-
1542
- ### getChains
1543
-
1544
- Get supported blockchain chains.
1545
-
1546
- **Returns:** `Promise<Chain[]>`
1547
-
1548
- **Chain interface:**
1549
-
1550
- | Property | Type | Description |
1551
- |----------|------|-------------|
1552
- | `chainId` | `number` | Chain ID |
1553
- | `whChainId` | `string` | Wormhole chain ID |
1554
- | `tmc` | `string` | TMC identifier |
1555
- | `name` | `BLOCKCHAINS` | Blockchain name enum |
1556
-
1557
- **Example:**
1558
-
1559
- ```typescript
1560
- const chains = await client.getChains();
1561
-
1562
- chains.forEach(chain => {
1563
- console.log(`${chain.name} (Chain ID: ${chain.chainId}, WH Chain ID: ${chain.whChainId})`);
1564
- });
1565
- ```
1566
-
1567
- ### getDollarValues
1568
-
1569
- Get USD values for assets.
1570
-
1571
- **Parameters:**
1572
-
1573
- | Name | Type | Required | Description |
1574
- |------|------|----------|-------------|
1575
- | `assetIds` | `number[]` | No | Array of asset IDs (default: empty array for all) |
1576
-
1577
- **Returns:** `Promise<IGetDollarValues>`
1578
-
1579
- **Note:** Returns an object with dynamic keys (`[key: string]: number`), where keys are asset IDs and values are USD prices.
1580
-
1581
- **Example:**
1582
-
1583
- ```typescript
1584
- // Get prices for specific assets
1585
- const prices = await client.getDollarValues([0, 1, 2]);
1586
-
1587
- // Get prices for all assets
1588
- const allPrices = await client.getDollarValues();
1589
-
1590
- // Access prices by asset ID
1591
- Object.keys(prices).forEach(assetId => {
1592
- console.log(`Asset ${assetId}: $${prices[assetId]}`);
1593
- });
1594
- ```
1595
-
1596
- ### getTransactionDetalis
1597
-
1598
- Get detailed transaction information.
1599
-
1600
- **Parameters:**
1601
-
1602
- | Name | Type | Required | Description |
1603
- |------|------|----------|-------------|
1604
- | `transactionId` | `number` | Yes | Transaction ID |
1605
-
1606
- **Returns:** `Promise<ITransactionDetails>`
1607
-
1608
- **Example:**
1609
-
1610
- ```typescript
1611
- const details = await client.getTransactionDetalis(12345);
1612
-
1613
- console.log('Transaction:', {
1614
- id: details.id,
1615
- primaryId: details.primaryId,
1616
- actionType: details.action_type,
1617
- amount: details.amount,
1618
- status: details.status,
1619
- targetAddress: details.targetAddress,
1620
- timestamp: details.timestamp,
1621
- createdAt: details.createdAt,
1622
- fee: details.fee
1623
- });
1624
- ```
1625
-
1626
- ### getWithdrawalFee
1627
-
1628
- Get withdrawal fee for an asset.
1629
-
1630
- **Parameters:**
1631
-
1632
- | Name | Type | Required | Description |
1633
- |------|------|----------|-------------|
1634
- | `assetAddress` | `string` | Yes | Asset address |
1635
- | `chainId` | `number` | Yes | Chain ID |
1636
-
1637
- **Returns:** `Promise<IWithdrawalFee>`
1638
-
1639
- **IWithdrawalFee interface:**
1640
-
1641
- | Property | Type | Description |
1642
- |----------|------|-------------|
1643
- | `fee` | `string` | Withdrawal fee amount |
1644
- | `dollarValue` | `string` | Fee value in USD |
1645
-
1646
- **Example:**
1647
-
1648
- ```typescript
1649
- const fee = await client.getWithdrawalFee('ASSET_ADDRESS', 1);
1650
-
1651
- console.log('Withdrawal fee:', fee.fee);
1652
- console.log('Fee in USD:', fee.dollarValue);
1653
- ```
1654
-
1655
- ---
1656
-
1657
1686
  ## Notifications
1658
1687
 
1659
1688
  ### getNotifications
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Trading-related method arguments
3
3
  */
4
- import { CreateOrderArgs, CancelOrderArgs } from '../interface/index.ts';
5
- export interface ICreateOrderArgs extends CreateOrderArgs {
4
+ import { CreateSpotOrderArgs, CancelOrderArgs } from '../interface/index.ts';
5
+ export interface ICreateSpotOrderArgs extends CreateSpotOrderArgs {
6
6
  }
7
7
  export interface ICancelOrderArgs extends CancelOrderArgs {
8
8
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Wallet-related method arguments
3
3
  */
4
- import { CreateWithdrawalWallet, UpdateWithdrawalWallet, IWhiteList } from '../../../shared/dist/browser/interfaces';
4
+ import { CreateWithdrawalWallet, UpdateWithdrawalWallet, IWhitelist } from '../../../shared/dist/browser/interfaces';
5
5
  export interface IGetWalletTransactionsArgs {
6
6
  type: string;
7
7
  page: number;
@@ -12,7 +12,7 @@ export interface IGetTransfersArgs {
12
12
  limit?: number;
13
13
  }
14
14
  export interface IAddWhitelistArgs {
15
- data: IWhiteList;
15
+ data: IWhitelist;
16
16
  }
17
17
  export interface IDeleteWhitelistArgs {
18
18
  whitelistId: number;
package/dist/client.d.ts CHANGED
@@ -4,7 +4,7 @@ import { CreateWithdrawalWallet, UpdateWithdrawalWallet } from "../../shared/dis
4
4
  import { ISafeWithdrawalWallets } from "../../shared/dist/browser/interfaces";
5
5
  import { PaginatedResult } from "../../shared/dist/browser/interfaces";
6
6
  import { SocketManager } from "./sockets";
7
- import { AuthCredentials, ClientOptions, CancelOrderArgs, CreateOrderArgs, Signer, SubscribeOptions, TelegramData, WalletCredentials, UserNotification, IPairDto, IGetDepth, SettingsInit, IGetLastTrades, CodexBalanceDto, IOrderDto, Order, Chain, MappedCCTPAssets, CCTPUnifiedAssets, IGetKycStatus, IGetKycInitLink, IGetDollarValues, ITransactionDetails, IClient, IGetPrice, IGetSymbols, IGetHistoryResponse, IWithdrawalFee, ITransaction, ITradingKey, ITransfer, IPendingTxn, IGetWhiteList, IWhiteList, ISystemVersion, ISystemMaintenance, IUnreadNotificationsCount, UpdateUserNotificationDto, IAffiliateDashboardStatus, IAffiliateProgress, DashboardInfo, ISocialAccount, ILeaderboardItem, IUnlock, IAction, IActionHistory, ISocialSettings, ISocialSeason, ITelegramConnectResponse, ICompanyTweet, IAIStyle, IAIGeneratedComment, IWithdrawResponse, IRevokeTradingKeyResponse, ICancelOrderResponse, ICancelMultipleOrdersResponse } from "./interface/index.ts";
7
+ import { AuthCredentials, ClientOptions, CancelOrderArgs, CreateSpotOrderArgs, Signer, SubscribeOptions, TelegramData, WalletCredentials, UserNotification, IPairDto, IGetDepth, SettingsInit, IGetLastTrades, CodexBalanceDto, IOrderDto, Order, Chain, MappedCCTPAssets, CCTPUnifiedAssets, IGetKycStatus, IGetKycInitLink, IGetDollarValues, ITransactionDetails, IClient, IGetPrice, IGetSymbols, IGetHistoryResponse, IWithdrawalFee, ITransaction, ITradingKey, ITransfer, IPendingTxn, IGetWhiteList, IWhiteList, ISystemVersion, ISystemMaintenance, IUnreadNotificationsCount, UpdateUserNotificationDto, IAffiliateDashboardStatus, IAffiliateProgress, DashboardInfo, ISocialAccount, ILeaderboardItem, IUnlock, IAction, IActionHistory, ISocialSettings, ISocialSeason, ITelegramConnectResponse, ICompanyTweet, IAIStyle, IAIGeneratedComment, IWithdrawResponse, IRevokeTradingKeyResponse, ICancelOrderResponse, ICancelMultipleOrdersResponse } from "./interface/index.ts";
8
8
  export declare class Client implements IClient {
9
9
  private client;
10
10
  private algodNode;
@@ -102,7 +102,7 @@ export declare class Client implements IClient {
102
102
  revokeTradingKey(data: ITradingKeyData): Promise<IRevokeTradingKeyResponse>;
103
103
  withdraw(withdrawData: IWithdrawData, prettyMsg?: string): Promise<IWithdrawResponse>;
104
104
  transfer(transferData: ITransferData): Promise<ITransfer>;
105
- createOrder(order: CreateOrderArgs): Promise<IOrderDto>;
105
+ createSpotOrder(order: CreateSpotOrderArgs): Promise<IOrderDto>;
106
106
  cancelOrder(order: CancelOrderArgs): Promise<ICancelOrderResponse>;
107
107
  cancelMultipleOrders({ orderIds, pairId }: {
108
108
  orderIds?: number[];
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var er=Object.defineProperty;var tr=(i,e)=>{for(var t in e)er(i,t,{get:e[t],enumerable:!0})};function Ke(){throw new Error("setTimeout has not been defined")}function je(){throw new Error("clearTimeout has not been defined")}var U=Ke,W=je;typeof globalThis.setTimeout=="function"&&(U=setTimeout);typeof globalThis.clearTimeout=="function"&&(W=clearTimeout);function He(i){if(U===setTimeout)return setTimeout(i,0);if((U===Ke||!U)&&setTimeout)return U=setTimeout,setTimeout(i,0);try{return U(i,0)}catch{try{return U.call(null,i,0)}catch{return U.call(this,i,0)}}}function rr(i){if(W===clearTimeout)return clearTimeout(i);if((W===je||!W)&&clearTimeout)return W=clearTimeout,clearTimeout(i);try{return W(i)}catch{try{return W.call(null,i)}catch{return W.call(this,i)}}}var S=[],z=!1,L,de=-1;function ir(){!z||!L||(z=!1,L.length?S=L.concat(S):de=-1,S.length&&et())}function et(){if(!z){var i=He(ir);z=!0;for(var e=S.length;e;){for(L=S,S=[];++de<e;)L&&L[de].run();de=-1,e=S.length}L=null,z=!1,rr(i)}}function nr(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];S.push(new tt(i,e)),S.length===1&&!z&&He(et)}function tt(i,e){this.fun=i,this.array=e}tt.prototype.run=function(){this.fun.apply(null,this.array)};var sr="browser",or="browser",ar=!0,cr={},lr=[],ur="",hr={},fr={},dr={};function B(){}var pr=B,mr=B,gr=B,yr=B,Tr=B,Er=B,_r=B;function br(i){throw new Error("process.binding is not supported")}function Ar(){return"/"}function xr(i){throw new Error("process.chdir is not supported")}function wr(){return 0}var X=globalThis.performance||{},Ir=X.now||X.mozNow||X.msNow||X.oNow||X.webkitNow||function(){return new Date().getTime()};function kr(i){var e=Ir.call(X)*.001,t=Math.floor(e),r=Math.floor(e%1*1e9);return i&&(t=t-i[0],r=r-i[1],r<0&&(t--,r+=1e9)),[t,r]}var Pr=new Date;function Rr(){var i=new Date,e=i-Pr;return e/1e3}var h={nextTick:nr,title:sr,browser:ar,env:cr,argv:lr,version:ur,versions:hr,on:pr,addListener:mr,once:gr,off:yr,removeListener:Tr,removeAllListeners:Er,emit:_r,binding:br,cwd:Ar,chdir:xr,umask:wr,hrtime:kr,platform:or,release:fr,config:dr,uptime:Rr},Ze={};Object.keys(Ze).forEach(i=>{let e=i.split("."),t=h;for(let r=0;r<e.length;r++){let n=e[r];r===e.length-1?t[n]=Ze[i]:t=t[n]||(t[n]={})}});var P=[],I=[],Sr=typeof Uint8Array<"u"?Uint8Array:Array,Se=!1;function st(){Se=!0;for(var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,t=i.length;e<t;++e)P[e]=i[e],I[i.charCodeAt(e)]=e;I[45]=62,I[95]=63}function vr(i){Se||st();var e,t,r,n,s,o,l=i.length;if(l%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s=i[l-2]==="="?2:i[l-1]==="="?1:0,o=new Sr(l*3/4-s),r=s>0?l-4:l;var u=0;for(e=0,t=0;e<r;e+=4,t+=3)n=I[i.charCodeAt(e)]<<18|I[i.charCodeAt(e+1)]<<12|I[i.charCodeAt(e+2)]<<6|I[i.charCodeAt(e+3)],o[u++]=n>>16&255,o[u++]=n>>8&255,o[u++]=n&255;return s===2?(n=I[i.charCodeAt(e)]<<2|I[i.charCodeAt(e+1)]>>4,o[u++]=n&255):s===1&&(n=I[i.charCodeAt(e)]<<10|I[i.charCodeAt(e+1)]<<4|I[i.charCodeAt(e+2)]>>2,o[u++]=n>>8&255,o[u++]=n&255),o}function Dr(i){return P[i>>18&63]+P[i>>12&63]+P[i>>6&63]+P[i&63]}function Nr(i,e,t){for(var r,n=[],s=e;s<t;s+=3)r=(i[s]<<16)+(i[s+1]<<8)+i[s+2],n.push(Dr(r));return n.join("")}function rt(i){Se||st();for(var e,t=i.length,r=t%3,n="",s=[],o=16383,l=0,u=t-r;l<u;l+=o)s.push(Nr(i,l,l+o>u?u:l+o));return r===1?(e=i[t-1],n+=P[e>>2],n+=P[e<<4&63],n+="=="):r===2&&(e=(i[t-2]<<8)+i[t-1],n+=P[e>>10],n+=P[e>>4&63],n+=P[e<<2&63],n+="="),s.push(n),s.join("")}c.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:!0;function pe(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function v(i,e){if(pe()<e)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(i=new Uint8Array(e),i.__proto__=c.prototype):(i===null&&(i=new c(e)),i.length=e),i}function c(i,e,t){if(!c.TYPED_ARRAY_SUPPORT&&!(this instanceof c))return new c(i,e,t);if(typeof i=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return ve(this,i)}return ot(this,i,e,t)}c.poolSize=8192;c._augment=function(i){return i.__proto__=c.prototype,i};function ot(i,e,t,r){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?Wr(i,e,t,r):typeof e=="string"?Ur(i,e,t):Or(i,e)}c.from=function(i,e,t){return ot(null,i,e,t)};c.kMaxLength=pe();c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&c[Symbol.species]);function at(i){if(typeof i!="number")throw new TypeError('"size" argument must be a number');if(i<0)throw new RangeError('"size" argument must not be negative')}function Mr(i,e,t,r){return at(e),e<=0?v(i,e):t!==void 0?typeof r=="string"?v(i,e).fill(t,r):v(i,e).fill(t):v(i,e)}c.alloc=function(i,e,t){return Mr(null,i,e,t)};function ve(i,e){if(at(e),i=v(i,e<0?0:De(e)|0),!c.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)i[t]=0;return i}c.allocUnsafe=function(i){return ve(null,i)};c.allocUnsafeSlow=function(i){return ve(null,i)};function Ur(i,e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!c.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var r=ct(e,t)|0;i=v(i,r);var n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function Re(i,e){var t=e.length<0?0:De(e.length)|0;i=v(i,t);for(var r=0;r<t;r+=1)i[r]=e[r]&255;return i}function Wr(i,e,t,r){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(r||0))throw new RangeError("'length' is out of bounds");return t===void 0&&r===void 0?e=new Uint8Array(e):r===void 0?e=new Uint8Array(e,t):e=new Uint8Array(e,t,r),c.TYPED_ARRAY_SUPPORT?(i=e,i.__proto__=c.prototype):i=Re(i,e),i}function Or(i,e){if(R(e)){var t=De(e.length)|0;return i=v(i,t),i.length===0||e.copy(i,0,0,t),i}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||ti(e.length)?v(i,0):Re(i,e);if(e.type==="Buffer"&&Array.isArray(e.data))return Re(i,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function De(i){if(i>=pe())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+pe().toString(16)+" bytes");return i|0}c.isBuffer=ri;function R(i){return!!(i!=null&&i._isBuffer)}c.compare=function(e,t){if(!R(e)||!R(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,s=0,o=Math.min(r,n);s<o;++s)if(e[s]!==t[s]){r=e[s],n=t[s];break}return r<n?-1:n<r?1:0};c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return c.alloc(0);var r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=c.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var o=e[r];if(!R(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(n,s),s+=o.length}return n};function ct(i,e){if(R(i))return i.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(i)||i instanceof ArrayBuffer))return i.byteLength;typeof i!="string"&&(i=""+i);var t=i.length;if(t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":case void 0:return me(i).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return mt(i).length;default:if(r)return me(i).length;e=(""+e).toLowerCase(),r=!0}}c.byteLength=ct;function Cr(i,e,t){var r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(i||(i="utf8");;)switch(i){case"hex":return zr(this,e,t);case"utf8":case"utf-8":return ht(this,e,t);case"ascii":return $r(this,e,t);case"latin1":case"binary":return Xr(this,e,t);case"base64":return Yr(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Jr(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+i);i=(i+"").toLowerCase(),r=!0}}c.prototype._isBuffer=!0;function G(i,e,t){var r=i[e];i[e]=i[t],i[t]=r}c.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)G(this,t,t+1);return this};c.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)G(this,t,t+3),G(this,t+1,t+2);return this};c.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)G(this,t,t+7),G(this,t+1,t+6),G(this,t+2,t+5),G(this,t+3,t+4);return this};c.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?ht(this,0,e):Cr.apply(this,arguments)};c.prototype.equals=function(e){if(!R(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:c.compare(this,e)===0};c.prototype.compare=function(e,t,r,n,s){if(!R(e))throw new TypeError("Argument must be a Buffer");if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),n===void 0&&(n=0),s===void 0&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,s>>>=0,this===e)return 0;for(var o=s-n,l=r-t,u=Math.min(o,l),f=this.slice(n,s),d=e.slice(t,r),p=0;p<u;++p)if(f[p]!==d[p]){o=f[p],l=d[p];break}return o<l?-1:l<o?1:0};function lt(i,e,t,r,n){if(i.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=n?0:i.length-1),t<0&&(t=i.length+t),t>=i.length){if(n)return-1;t=i.length-1}else if(t<0)if(n)t=0;else return-1;if(typeof e=="string"&&(e=c.from(e,r)),R(e))return e.length===0?-1:it(i,e,t,r,n);if(typeof e=="number")return e=e&255,c.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(i,e,t):Uint8Array.prototype.lastIndexOf.call(i,e,t):it(i,[e],t,r,n);throw new TypeError("val must be string, number or Buffer")}function it(i,e,t,r,n){var s=1,o=i.length,l=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(i.length<2||e.length<2)return-1;s=2,o/=2,l/=2,t/=2}function u(x,$){return s===1?x[$]:x.readUInt16BE($*s)}var f;if(n){var d=-1;for(f=t;f<o;f++)if(u(i,f)===u(e,d===-1?0:f-d)){if(d===-1&&(d=f),f-d+1===l)return d*s}else d!==-1&&(f-=f-d),d=-1}else for(t+l>o&&(t=o-l),f=t;f>=0;f--){for(var p=!0,_=0;_<l;_++)if(u(i,f+_)!==u(e,_)){p=!1;break}if(p)return f}return-1}c.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};c.prototype.indexOf=function(e,t,r){return lt(this,e,t,r,!0)};c.prototype.lastIndexOf=function(e,t,r){return lt(this,e,t,r,!1)};function Fr(i,e,t,r){t=Number(t)||0;var n=i.length-t;r?(r=Number(r),r>n&&(r=n)):r=n;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var l=parseInt(e.substr(o*2,2),16);if(isNaN(l))return o;i[t+o]=l}return o}function Lr(i,e,t,r){return Te(me(e,i.length-t),i,t,r)}function ut(i,e,t,r){return Te(Hr(e),i,t,r)}function Br(i,e,t,r){return ut(i,e,t,r)}function Gr(i,e,t,r){return Te(mt(e),i,t,r)}function Vr(i,e,t,r){return Te(ei(e,i.length-t),i,t,r)}c.prototype.write=function(e,t,r,n){if(t===void 0)n="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")n=t,r=this.length,t=0;else if(isFinite(t))t=t|0,isFinite(r)?(r=r|0,n===void 0&&(n="utf8")):(n=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-t;if((r===void 0||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return Fr(this,e,t,r);case"utf8":case"utf-8":return Lr(this,e,t,r);case"ascii":return ut(this,e,t,r);case"latin1":case"binary":return Br(this,e,t,r);case"base64":return Gr(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Vr(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}};c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Yr(i,e,t){return e===0&&t===i.length?rt(i):rt(i.slice(e,t))}function ht(i,e,t){t=Math.min(i.length,t);for(var r=[],n=e;n<t;){var s=i[n],o=null,l=s>239?4:s>223?3:s>191?2:1;if(n+l<=t){var u,f,d,p;switch(l){case 1:s<128&&(o=s);break;case 2:u=i[n+1],(u&192)===128&&(p=(s&31)<<6|u&63,p>127&&(o=p));break;case 3:u=i[n+1],f=i[n+2],(u&192)===128&&(f&192)===128&&(p=(s&15)<<12|(u&63)<<6|f&63,p>2047&&(p<55296||p>57343)&&(o=p));break;case 4:u=i[n+1],f=i[n+2],d=i[n+3],(u&192)===128&&(f&192)===128&&(d&192)===128&&(p=(s&15)<<18|(u&63)<<12|(f&63)<<6|d&63,p>65535&&p<1114112&&(o=p))}}o===null?(o=65533,l=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),n+=l}return qr(r)}var nt=4096;function qr(i){var e=i.length;if(e<=nt)return String.fromCharCode.apply(String,i);for(var t="",r=0;r<e;)t+=String.fromCharCode.apply(String,i.slice(r,r+=nt));return t}function $r(i,e,t){var r="";t=Math.min(i.length,t);for(var n=e;n<t;++n)r+=String.fromCharCode(i[n]&127);return r}function Xr(i,e,t){var r="";t=Math.min(i.length,t);for(var n=e;n<t;++n)r+=String.fromCharCode(i[n]);return r}function zr(i,e,t){var r=i.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);for(var n="",s=e;s<t;++s)n+=jr(i[s]);return n}function Jr(i,e,t){for(var r=i.slice(e,t),n="",s=0;s<r.length;s+=2)n+=String.fromCharCode(r[s]+r[s+1]*256);return n}c.prototype.slice=function(e,t){var r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);var n;if(c.TYPED_ARRAY_SUPPORT)n=this.subarray(e,t),n.__proto__=c.prototype;else{var s=t-e;n=new c(s,void 0);for(var o=0;o<s;++o)n[o]=this[o+e]}return n};function E(i,e,t){if(i%1!==0||i<0)throw new RangeError("offset is not uint");if(i+e>t)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUIntLE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e],s=1,o=0;++o<t&&(s*=256);)n+=this[e+o]*s;return n};c.prototype.readUIntBE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e+--t],s=1;t>0&&(s*=256);)n+=this[e+--t]*s;return n};c.prototype.readUInt8=function(e,t){return t||E(e,1,this.length),this[e]};c.prototype.readUInt16LE=function(e,t){return t||E(e,2,this.length),this[e]|this[e+1]<<8};c.prototype.readUInt16BE=function(e,t){return t||E(e,2,this.length),this[e]<<8|this[e+1]};c.prototype.readUInt32LE=function(e,t){return t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};c.prototype.readUInt32BE=function(e,t){return t||E(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};c.prototype.readIntLE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e],s=1,o=0;++o<t&&(s*=256);)n+=this[e+o]*s;return s*=128,n>=s&&(n-=Math.pow(2,8*t)),n};c.prototype.readIntBE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=t,s=1,o=this[e+--n];n>0&&(s*=256);)o+=this[e+--n]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o};c.prototype.readInt8=function(e,t){return t||E(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};c.prototype.readInt16LE=function(e,t){t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};c.prototype.readInt16BE=function(e,t){t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};c.prototype.readInt32LE=function(e,t){return t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};c.prototype.readInt32BE=function(e,t){return t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};c.prototype.readFloatLE=function(e,t){return t||E(e,4,this.length),Ee(this,e,!0,23,4)};c.prototype.readFloatBE=function(e,t){return t||E(e,4,this.length),Ee(this,e,!1,23,4)};c.prototype.readDoubleLE=function(e,t){return t||E(e,8,this.length),Ee(this,e,!0,52,8)};c.prototype.readDoubleBE=function(e,t){return t||E(e,8,this.length),Ee(this,e,!1,52,8)};function A(i,e,t,r,n,s){if(!R(i))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<s)throw new RangeError('"value" argument is out of bounds');if(t+r>i.length)throw new RangeError("Index out of range")}c.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=t|0,r=r|0,!n){var s=Math.pow(2,8*r)-1;A(this,e,t,r,s,0)}var o=1,l=0;for(this[t]=e&255;++l<r&&(o*=256);)this[t+l]=e/o&255;return t+r};c.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t=t|0,r=r|0,!n){var s=Math.pow(2,8*r)-1;A(this,e,t,r,s,0)}var o=r-1,l=1;for(this[t+o]=e&255;--o>=0&&(l*=256);)this[t+o]=e/l&255;return t+r};c.prototype.writeUInt8=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function ge(i,e,t,r){e<0&&(e=65535+e+1);for(var n=0,s=Math.min(i.length-t,2);n<s;++n)i[t+n]=(e&255<<8*(r?n:1-n))>>>(r?n:1-n)*8}c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):ge(this,e,t,!0),t+2};c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):ge(this,e,t,!1),t+2};function ye(i,e,t,r){e<0&&(e=4294967295+e+1);for(var n=0,s=Math.min(i.length-t,4);n<s;++n)i[t+n]=e>>>(r?n:3-n)*8&255}c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):ye(this,e,t,!0),t+4};c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):ye(this,e,t,!1),t+4};c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=t|0,!n){var s=Math.pow(2,8*r-1);A(this,e,t,r,s-1,-s)}var o=0,l=1,u=0;for(this[t]=e&255;++o<r&&(l*=256);)e<0&&u===0&&this[t+o-1]!==0&&(u=1),this[t+o]=(e/l>>0)-u&255;return t+r};c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=t|0,!n){var s=Math.pow(2,8*r-1);A(this,e,t,r,s-1,-s)}var o=r-1,l=1,u=0;for(this[t+o]=e&255;--o>=0&&(l*=256);)e<0&&u===0&&this[t+o+1]!==0&&(u=1),this[t+o]=(e/l>>0)-u&255;return t+r};c.prototype.writeInt8=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1};c.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):ge(this,e,t,!0),t+2};c.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):ge(this,e,t,!1),t+2};c.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):ye(this,e,t,!0),t+4};c.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):ye(this,e,t,!1),t+4};function ft(i,e,t,r,n,s){if(t+r>i.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function dt(i,e,t,r,n){return n||ft(i,e,t,4,34028234663852886e22,-34028234663852886e22),yt(i,e,t,r,23,4),t+4}c.prototype.writeFloatLE=function(e,t,r){return dt(this,e,t,!0,r)};c.prototype.writeFloatBE=function(e,t,r){return dt(this,e,t,!1,r)};function pt(i,e,t,r,n){return n||ft(i,e,t,8,17976931348623157e292,-17976931348623157e292),yt(i,e,t,r,52,8),t+8}c.prototype.writeDoubleLE=function(e,t,r){return pt(this,e,t,!0,r)};c.prototype.writeDoubleBE=function(e,t,r){return pt(this,e,t,!1,r)};c.prototype.copy=function(e,t,r,n){if(r||(r=0),!n&&n!==0&&(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var s=n-r,o;if(this===e&&r<t&&t<n)for(o=s-1;o>=0;--o)e[o+t]=this[o+r];else if(s<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+s),t);return s};c.prototype.fill=function(e,t,r,n){if(typeof e=="string"){if(typeof t=="string"?(n=t,t=0,r=this.length):typeof r=="string"&&(n=r,r=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s)}if(n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!c.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else typeof e=="number"&&(e=e&255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);var o;if(typeof e=="number")for(o=t;o<r;++o)this[o]=e;else{var l=R(e)?e:me(new c(e,n).toString()),u=l.length;for(o=0;o<r-t;++o)this[o+t]=l[o%u]}return this};var Qr=/[^+\/0-9A-Za-z-_]/g;function Zr(i){if(i=Kr(i).replace(Qr,""),i.length<2)return"";for(;i.length%4!==0;)i=i+"=";return i}function Kr(i){return i.trim?i.trim():i.replace(/^\s+|\s+$/g,"")}function jr(i){return i<16?"0"+i.toString(16):i.toString(16)}function me(i,e){e=e||1/0;for(var t,r=i.length,n=null,s=[],o=0;o<r;++o){if(t=i.charCodeAt(o),t>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&s.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),n=t;continue}t=(n-55296<<10|t-56320)+65536}else n&&(e-=3)>-1&&s.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function Hr(i){for(var e=[],t=0;t<i.length;++t)e.push(i.charCodeAt(t)&255);return e}function ei(i,e){for(var t,r,n,s=[],o=0;o<i.length&&!((e-=2)<0);++o)t=i.charCodeAt(o),r=t>>8,n=t%256,s.push(n),s.push(r);return s}function mt(i){return vr(Zr(i))}function Te(i,e,t,r){for(var n=0;n<r&&!(n+t>=e.length||n>=i.length);++n)e[n+t]=i[n];return n}function ti(i){return i!==i}function ri(i){return i!=null&&(!!i._isBuffer||gt(i)||ii(i))}function gt(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function ii(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&gt(i.slice(0,0))}function Ee(i,e,t,r,n){var s,o,l=n*8-r-1,u=(1<<l)-1,f=u>>1,d=-7,p=t?n-1:0,_=t?-1:1,x=i[e+p];for(p+=_,s=x&(1<<-d)-1,x>>=-d,d+=l;d>0;s=s*256+i[e+p],p+=_,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=o*256+i[e+p],p+=_,d-=8);if(s===0)s=1-f;else{if(s===u)return o?NaN:(x?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-f}return(x?-1:1)*o*Math.pow(2,s-r)}function yt(i,e,t,r,n,s){var o,l,u,f=s*8-n-1,d=(1<<f)-1,p=d>>1,_=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,x=r?0:s-1,$=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+p>=1?e+=_/u:e+=_*Math.pow(2,1-p),e*u>=2&&(o++,u/=2),o+p>=d?(l=0,o=d):o+p>=1?(l=(e*u-1)*Math.pow(2,n),o=o+p):(l=e*Math.pow(2,p-1)*Math.pow(2,n),o=0));n>=8;i[t+x]=l&255,x+=$,l/=256,n-=8);for(o=o<<n|l,f+=n;f>0;i[t+x]=o&255,x+=$,o/=256,f-=8);i[t+x-$]|=y*128}var k=Object.create(null);k.open="0";k.close="1";k.ping="2";k.pong="3";k.message="4";k.upgrade="5";k.noop="6";var H=Object.create(null);Object.keys(k).forEach(i=>{H[k[i]]=i});var ee={type:"error",data:"parser error"};var _t=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",bt=typeof ArrayBuffer=="function",At=i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i&&i.buffer instanceof ArrayBuffer,te=({type:i,data:e},t,r)=>_t&&e instanceof Blob?t?r(e):Tt(e,r):bt&&(e instanceof ArrayBuffer||At(e))?t?r(e):Tt(new Blob([e]),r):r(k[i]+(e||"")),Tt=(i,e)=>{let t=new FileReader;return t.onload=function(){let r=t.result.split(",")[1];e("b"+(r||""))},t.readAsDataURL(i)};function Et(i){return i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}var Ne;function xt(i,e){if(_t&&i.data instanceof Blob)return i.data.arrayBuffer().then(Et).then(e);if(bt&&(i.data instanceof ArrayBuffer||At(i.data)))return e(Et(i.data));te(i,!1,t=>{Ne||(Ne=new TextEncoder),e(Ne.encode(t))})}var wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",re=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let i=0;i<wt.length;i++)re[wt.charCodeAt(i)]=i;var It=i=>{let e=i.length*.75,t=i.length,r,n=0,s,o,l,u;i[i.length-1]==="="&&(e--,i[i.length-2]==="="&&e--);let f=new ArrayBuffer(e),d=new Uint8Array(f);for(r=0;r<t;r+=4)s=re[i.charCodeAt(r)],o=re[i.charCodeAt(r+1)],l=re[i.charCodeAt(r+2)],u=re[i.charCodeAt(r+3)],d[n++]=s<<2|o>>4,d[n++]=(o&15)<<4|l>>2,d[n++]=(l&3)<<6|u&63;return f};var ni=typeof ArrayBuffer=="function",ie=(i,e)=>{if(typeof i!="string")return{type:"message",data:kt(i,e)};let t=i.charAt(0);return t==="b"?{type:"message",data:si(i.substring(1),e)}:H[t]?i.length>1?{type:H[t],data:i.substring(1)}:{type:H[t]}:ee},si=(i,e)=>{if(ni){let t=It(i);return kt(t,e)}else return{base64:!0,data:i}},kt=(i,e)=>{switch(e){case"blob":return i instanceof Blob?i:new Blob([i]);case"arraybuffer":default:return i instanceof ArrayBuffer?i:i.buffer}};var Pt="",Rt=(i,e)=>{let t=i.length,r=new Array(t),n=0;i.forEach((s,o)=>{te(s,!1,l=>{r[o]=l,++n===t&&e(r.join(Pt))})})},St=(i,e)=>{let t=i.split(Pt),r=[];for(let n=0;n<t.length;n++){let s=ie(t[n],e);if(r.push(s),s.type==="error")break}return r};function vt(){return new TransformStream({transform(i,e){xt(i,t=>{let r=t.length,n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,r)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(r))}i.data&&typeof i.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var Me;function _e(i){return i.reduce((e,t)=>e+t.length,0)}function be(i,e){if(i[0].length===e)return i.shift();let t=new Uint8Array(e),r=0;for(let n=0;n<e;n++)t[n]=i[0][r++],r===i[0].length&&(i.shift(),r=0);return i.length&&r<i[0].length&&(i[0]=i[0].slice(r)),t}function Dt(i,e){Me||(Me=new TextDecoder);let t=[],r=0,n=-1,s=!1;return new TransformStream({transform(o,l){for(t.push(o);;){if(r===0){if(_e(t)<1)break;let u=be(t,1);s=(u[0]&128)===128,n=u[0]&127,n<126?r=3:n===126?r=1:r=2}else if(r===1){if(_e(t)<2)break;let u=be(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),r=3}else if(r===2){if(_e(t)<8)break;let u=be(t,8),f=new DataView(u.buffer,u.byteOffset,u.length),d=f.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(ee);break}n=d*Math.pow(2,32)+f.getUint32(4),r=3}else{if(_e(t)<n)break;let u=be(t,n);l.enqueue(ie(s?u:Me.decode(u),e)),r=0}if(n===0||n>i){l.enqueue(ee);break}}}})}var Ue=4;function T(i){if(i)return oi(i)}function oi(i){for(var e in T.prototype)i[e]=T.prototype[e];return i}T.prototype.on=T.prototype.addEventListener=function(i,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+i]=this._callbacks["$"+i]||[]).push(e),this};T.prototype.once=function(i,e){function t(){this.off(i,t),e.apply(this,arguments)}return t.fn=e,this.on(i,t),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(i,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+i];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+i],this;for(var r,n=0;n<t.length;n++)if(r=t[n],r===e||r.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+i],this};T.prototype.emit=function(i){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+i],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(t){t=t.slice(0);for(var r=0,n=t.length;r<n;++r)t[r].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(i){return this._callbacks=this._callbacks||{},this._callbacks["$"+i]||[]};T.prototype.hasListeners=function(i){return!!this.listeners(i).length};var D=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),b=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Nt="arraybuffer";function Ae(i,...e){return e.reduce((t,r)=>(i.hasOwnProperty(r)&&(t[r]=i[r]),t),{})}var ai=b.setTimeout,ci=b.clearTimeout;function N(i,e){e.useNativeTimers?(i.setTimeoutFn=ai.bind(b),i.clearTimeoutFn=ci.bind(b)):(i.setTimeoutFn=b.setTimeout.bind(b),i.clearTimeoutFn=b.clearTimeout.bind(b))}var li=1.33;function Mt(i){return typeof i=="string"?ui(i):Math.ceil((i.byteLength||i.size)*li)}function ui(i){let e=0,t=0;for(let r=0,n=i.length;r<n;r++)e=i.charCodeAt(r),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(r++,t+=4);return t}function xe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ut(i){let e="";for(let t in i)i.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(i[t]));return e}function Wt(i){let e={},t=i.split("&");for(let r=0,n=t.length;r<n;r++){let s=t[r].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var we=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},M=class extends T{constructor(e){super(),this.writable=!1,N(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new we(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=ie(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Ut(e);return t.length?"?"+t:""}};var ne=class extends M{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};St(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Rt(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=xe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};var Ot=!1;try{Ot=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Ct=Ot;function hi(){}var We=class extends ne{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},O=class i extends T{constructor(e,t,r){super(),this.createRequest=e,N(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var e;let t=Ae(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&r.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var n;r.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=i.requestsCount++,i.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=hi,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete i.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};O.requestsCount=0;O.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ft);else if(typeof addEventListener=="function"){let i="onpagehide"in b?"pagehide":"unload";addEventListener(i,Ft,!1)}}function Ft(){for(let i in O.requests)O.requests.hasOwnProperty(i)&&O.requests[i].abort()}var fi=(function(){let i=Lt({xdomain:!1});return i&&i.responseType!==null})(),C=class extends We{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=fi&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new O(Lt,this.uri(),e)}};function Lt(i){let e=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ct))return new XMLHttpRequest}catch{}if(!e)try{return new b[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Bt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ce=class extends M{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Bt?{}:Ae(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;te(r,this.supportsBinary,s=>{try{this.doWrite(r,s)}catch{}n&&D(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=xe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Oe=b.WebSocket||b.MozWebSocket,F=class extends Ce{createSocket(e,t,r){return Bt?new Oe(e,t,r):t?new Oe(e,t):new Oe(e)}doWrite(e,t){this.ws.send(t)}};var J=class extends M{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Dt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=vt();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),s())}).catch(l=>{})};s();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;this._writer.write(r).then(()=>{n&&D(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};var Fe={websocket:F,webtransport:J,polling:C};var di=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,pi=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q(i){if(i.length>8e3)throw"URI too long";let e=i,t=i.indexOf("["),r=i.indexOf("]");t!=-1&&r!=-1&&(i=i.substring(0,t)+i.substring(t,r).replace(/:/g,";")+i.substring(r,i.length));let n=di.exec(i||""),s={},o=14;for(;o--;)s[pi[o]]=n[o]||"";return t!=-1&&r!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=mi(s,s.path),s.queryKey=gi(s,s.query),s}function mi(i,e){let t=/\/{2,9}/g,r=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function gi(i,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,n,s){n&&(t[n]=s)}),t}var Le=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ie=[];Le&&addEventListener("offline",()=>{Ie.forEach(i=>i())},!1);var V=class i extends T{constructor(e,t){if(super(),this.binaryType=Nt,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let r=Q(e);t.hostname=r.host,t.secure=r.protocol==="https"||r.protocol==="wss",t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=Q(t.host).host);N(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(r=>{let n=r.prototype.name;this.transports.push(n),this._transportsByName[n]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Wt(this.opts.query)),Le&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ie.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=Ue,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&i.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",i.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let n=this.writeBuffer[r].data;if(n&&(t+=Mt(n)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,D(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,n){if(typeof t=="function"&&(n=t,t=void 0),typeof r=="function"&&(n=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(i.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Le&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Ie.indexOf(this._offlineEventListener);r!==-1&&Ie.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};V.protocol=Ue;var ke=class extends V{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;V.priorWebsocketSuccess=!1;let n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;V.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){r||(r=!0,d(),t.close(),t=null)}let o=p=>{let _=new Error("probe error: "+p);_.transport=t.name,s(),this.emitReserved("upgradeError",_)};function l(){o("transport closed")}function u(){o("socket closed")}function f(p){t&&p.name!==t.name&&s()}let d=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};t.once("open",n),t.once("error",o),t.once("close",l),this.once("close",u),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},Z=class extends ke{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(n=>Fe[n]).filter(n=>!!n)),super(e,r)}};var eo=Z.protocol;function Gt(i,e="",t){let r=i;t=t||typeof location<"u"&&location,i==null&&(i=t.protocol+"//"+t.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=t.protocol+i:i=t.host+i),/^(https?|wss?):\/\//.test(i)||(typeof t<"u"?i=t.protocol+"//"+i:i="https://"+i),r=Q(i)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";let s=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(t&&t.port===r.port?"":":"+r.port),r}var $e={};tr($e,{Decoder:()=>Ye,Encoder:()=>Ve,PacketType:()=>m,protocol:()=>Xt});var Ti=typeof ArrayBuffer=="function",Ei=i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,Vt=Object.prototype.toString,_i=typeof Blob=="function"||typeof Blob<"u"&&Vt.call(Blob)==="[object BlobConstructor]",bi=typeof File=="function"||typeof File<"u"&&Vt.call(File)==="[object FileConstructor]";function oe(i){return Ti&&(i instanceof ArrayBuffer||Ei(i))||_i&&i instanceof Blob||bi&&i instanceof File}function se(i,e){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let t=0,r=i.length;t<r;t++)if(se(i[t]))return!0;return!1}if(oe(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return se(i.toJSON(),!0);for(let t in i)if(Object.prototype.hasOwnProperty.call(i,t)&&se(i[t]))return!0;return!1}function Yt(i){let e=[],t=i.data,r=i;return r.data=Be(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Be(i,e){if(!i)return i;if(oe(i)){let t={_placeholder:!0,num:e.length};return e.push(i),t}else if(Array.isArray(i)){let t=new Array(i.length);for(let r=0;r<i.length;r++)t[r]=Be(i[r],e);return t}else if(typeof i=="object"&&!(i instanceof Date)){let t={};for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=Be(i[r],e));return t}return i}function qt(i,e){return i.data=Ge(i.data,e),delete i.attachments,i}function Ge(i,e){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<e.length)return e[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let t=0;t<i.length;t++)i[t]=Ge(i[t],e);else if(typeof i=="object")for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(i[t]=Ge(i[t],e));return i}var Ai=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Xt=5,m;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(m||(m={}));var Ve=class{constructor(e){this.replacer=e}encode(e){return(e.type===m.EVENT||e.type===m.ACK)&&se(e)?this.encodeAsBinary({type:e.type===m.EVENT?m.BINARY_EVENT:m.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===m.BINARY_EVENT||e.type===m.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Yt(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}};function $t(i){return Object.prototype.toString.call(i)==="[object Object]"}var Ye=class i extends T{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let r=t.type===m.BINARY_EVENT;r||t.type===m.BINARY_ACK?(t.type=r?m.EVENT:m.ACK,this.reconstructor=new qe(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(oe(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(m[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===m.BINARY_EVENT||r.type===m.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let o=e.substring(s,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");r.attachments=Number(o)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););r.nsp=e.substring(s,t)}else r.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=t+1;for(;++t;){let o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}r.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(i.isPayloadValid(r.type,s))r.data=s;else throw new Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case m.CONNECT:return $t(t);case m.DISCONNECT:return t===void 0;case m.CONNECT_ERROR:return typeof t=="string"||$t(t);case m.EVENT:case m.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Ai.indexOf(t[0])===-1);case m.ACK:case m.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},qe=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=qt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function w(i,e,t){return i.on(e,t),function(){i.off(e,t)}}var xi=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),K=class extends T{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[w(e,"open",this.onopen.bind(this)),w(e,"packet",this.onpacket.bind(this)),w(e,"error",this.onerror.bind(this)),w(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,n,s;if(xi.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:m.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let d=this.ids++,p=t.pop();this._registerAckCallback(d,p),o.id=d}let l=(n=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!l||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var r;let n=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);t.call(this,new Error("operation has timed out"))},n),o=(...l)=>{this.io.clearTimeoutFn(s),t.apply(this,l)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,n)=>{let s=(o,l)=>o?n(o):r(l);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((n,...s)=>r!==this._queue[0]?void 0:(n!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(n)):(this._queue.shift(),t&&t(null,...s)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:m.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(r=>String(r.id)===e)){let r=this.acks[e];delete this.acks[e],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case m.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case m.EVENT:case m.BINARY_EVENT:this.onevent(e);break;case m.ACK:case m.BINARY_ACK:this.onack(e);break;case m.DISCONNECT:this.ondisconnect();break;case m.CONNECT_ERROR:this.destroy();let r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...n){r||(r=!0,t.packet({type:m.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:m.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function Y(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}Y.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*i);i=(Math.floor(e*10)&1)==0?i-t:i+t}return Math.min(i,this.max)|0};Y.prototype.reset=function(){this.attempts=0};Y.prototype.setMin=function(i){this.ms=i};Y.prototype.setMax=function(i){this.max=i};Y.prototype.setJitter=function(i){this.jitter=i};var j=class extends T{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,N(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Y({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||$e;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Z(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let n=w(t,"open",function(){r.onopen(),e&&e()}),s=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),e?e(l):this.maybeReconnectOnOpen()},o=w(t,"error",s);if(this._timeout!==!1){let l=this._timeout,u=this.setTimeoutFn(()=>{n(),s(new Error("timeout")),t.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(w(e,"ping",this.onping.bind(this)),w(e,"data",this.ondata.bind(this)),w(e,"error",this.onerror.bind(this)),w(e,"close",this.onclose.bind(this)),w(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){D(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new K(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var ae={};function ce(i,e){typeof i=="object"&&(e=i,i=void 0),e=e||{};let t=Gt(i,e.path||"/socket.io"),r=t.source,n=t.id,s=t.path,o=ae[n]&&s in ae[n].nsps,l=e.forceNew||e["force new connection"]||e.multiplex===!1||o,u;return l?u=new j(r,e):(ae[n]||(ae[n]=new j(r,e)),u=ae[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ce,{Manager:j,Socket:K,io:ce,connect:ce});import Ji from"axios";import{DEFAULT_ORDER_EXPIRATION_DAYS as Qi,ORDER_MSG_VERSION as Zi}from"@ultrade/shared/browser/constants";import{getRandomInt as Qe}from"@ultrade/shared/browser/common";import{getCancelOrderDataJsonBytes as Ki,makeLoginMsg as ji,makeTradingKeyMsg as jt,makeCreateOrderMsg as Hi}from"@ultrade/shared/browser/helpers/codex.helper";import{makeWithdrawMsg as en}from"@ultrade/shared/browser/helpers/withdraw.helper";import{TradingKeyType as tn}from"@ultrade/shared/browser/interfaces";import{PROVIDERS as q}from"@ultrade/shared/browser/interfaces";import{OrderStatus as fe}from"@ultrade/shared/browser/enums";import{makeDtwMsg as rn,makeTransferMsg as nn}from"@ultrade/shared/browser/helpers/codex";var le=class{constructor(e,t,r,n){this.onDisconnect=r;this.onConnectError=n;this.socket=null;this.socketPool={};this.websocketUrl=e,this.socketIOFactory=t,this.initializeSocket()}initializeSocket(){this.socket===null&&(this.socket=this.socketIOFactory(this.websocketUrl,{reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:9999,transports:["websocket"]}),this.onDisconnect&&this.socket.on("disconnect",()=>{this.onDisconnect(this.socket.id)}),this.onConnectError&&this.socket.on("connect_error",e=>{this.onConnectError(e)}))}getSocket(){return this.socket}subscribe(e,t){let r=Date.now();return this.socket===null&&this.initializeSocket(),this.socket.onAny((n,...s)=>{t(n,s)}),this.socket.io.on("reconnect",()=>{this.socket.emit("subscribe",e)}),this.socket.emit("subscribe",e),this.socketPool[r]=e,r}unsubscribe(e){let t=this.socketPool[e];t&&this.socket&&(this.socket.emit("unsubscribe",t),delete this.socketPool[e]),Object.keys(this.socketPool).length===0&&this.socket&&this.disconnect()}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null)}isConnected(){return this.socket!==null&&this.socket.connected}on(e,t){this.socket&&this.socket.on(e,t)}off(e,t){this.socket&&(t?this.socket.off(e,t):this.socket.off(e))}emit(e,...t){this.socket&&this.socket.emit(e,...t)}emitCurrentPair(e){this.emit("currentPair",e)}emitOrderFilter(e){this.emit("orderFilter",e)}onReconnect(e){return this.socket?(this.socket.io.off("reconnect"),this.socket.io.on("reconnect",e),()=>{this.socket&&this.socket.io.off("reconnect",e)}):()=>{}}offReconnect(e){this.socket&&(e?this.socket.io.off("reconnect",e):this.socket.io.off("reconnect"))}};import wi from"react-secure-storage";var Ii=new URL(window.location!==window.parent.location?document.referrer:document.location.href).host,zt=i=>`${i}_${Ii}`,ki=new Proxy(wi,{get(i,e,t){return typeof e=="string"&&typeof i[e]=="function"?function(...r){return typeof e=="string"&&["setItem","getItem","removeItem"].includes(e)&&(r[0]=zt(r[0])),i[e].apply(i,r)}:Reflect.get(i,e,t)}}),Xe=new Proxy(localStorage,{get(i,e,t){return typeof e=="string"&&typeof i[e]=="function"?function(...r){return typeof e=="string"&&["setItem","getItem","removeItem","key"].includes(e)&&(r[0]=zt(r[0])),i[e].apply(i,r)}:Reflect.get(i,e,t)}}),Pe=class{constructor(){this.keys={mainWallet:"main-wallet",tradingKey:"trading-key"};this.isBrowser=typeof window<"u",this.isBrowser||(this.clearMainWallet=()=>{},this.getMainWallet=()=>null,this.setMainWallet=()=>{})}setMainWallet(e){Xe.setItem(this.keys.mainWallet,JSON.stringify(e))}getMainWallet(){let e=Xe.getItem(this.keys.mainWallet);if(!e)return null;let t=JSON.parse(e),r=ki.getItem(`${this.keys.tradingKey}-${t.address}`);return r&&(r.expiredAt===0||Number(new Date(r.expiredAt))-Date.now()>1)&&(t.tradingKey=r.address),t}clearMainWallet(){Xe.removeItem(this.keys.mainWallet)}};var Pi=(t=>(t.YES="Y",t.NO="N",t))(Pi||{}),Ri=(f=>(f.MFT_AUDIO_LINK="mft.audioLink",f.MFT_TITLE="mft.title",f.VIEW_BASE_COIN_ICON_LINK="view.baseCoinIconLink",f.VIEW_BASE_COIN_MARKET_LINK="view.baseCoinMarketLink",f.VIEW_PRICE_COIN_ICON_LINK="view.priceCoinIconLink",f.VIEW_PRICE_COIN_MARKET_LINK="view.priceCoinMarketLink",f.MAKER_FEE="makerFee",f.TAKER_FEE="takerFee",f.MODE_PRE_SALE="mode.preSale",f))(Ri||{});var Si=(n=>(n[n.OPEN_ORDER=1]="OPEN_ORDER",n[n.CANCELLED=2]="CANCELLED",n[n.MATCHED=3]="MATCHED",n[n.SELF_MATCHED=4]="SELF_MATCHED",n))(Si||{}),vi=(s=>(s[s.Open=1]="Open",s[s.Canceled=2]="Canceled",s[s.Completed=3]="Completed",s[s.SelfMatch=4]="SelfMatch",s[s.Expired=5]="Expired",s))(vi||{}),Di=(n=>(n[n.Limit=0]="Limit",n[n.IOC=1]="IOC",n[n.POST=2]="POST",n[n.Market=3]="Market",n))(Di||{}),Ni=(r=>(r[r.created=1]="created",r[r.partially_filled=2]="partially_filled",r[r.removed=3]="removed",r))(Ni||{}),Mi=(a=>(a.ALGORAND="Algorand",a.SOLANA="Solana",a["5IRECHAIN_THUNDER_TESTNET"]="5ireChain Thunder Testnet",a.ACALA="Acala",a.ALFAJORES="Alfajores",a.APOTHEM_NETWORK="Apothem Network",a.ARBITRUM_GOERLI="Arbitrum Goerli",a.ARBITRUM_NOVA="Arbitrum Nova",a.ARBITRUM_ONE="Arbitrum",a.ARBITRUM_SEPOLIA="Arbitrum Sepolia",a.ASTAR="Astar",a.ASTAR_ZKEVM_TESTNET_ZKATANA="Astar zkEVM Testnet zKatana",a.AURORA="Aurora",a.AURORA_TESTNET="Aurora Testnet",a.AVALANCHE="Avalanche",a.AVALANCHE_FUJI="Avalanche Fuji",a.BAHAMUT="Bahamut",a.BASE="Base",a.BASE_GOERLI="Base Goerli",a.BASE_SEPOLIA="Base Sepolia",a.BEAR_NETWORK_CHAIN_MAINNET="Bear Network Chain Mainnet",a.BEAR_NETWORK_CHAIN_TESTNET="Bear Network Chain Testnet",a.BERACHAIN_ARTIO="Berachain Artio",a.BERESHEET_BEREEVM_TESTNET="Beresheet BereEVM Testnet",a.BINANCE_SMART_CHAIN_TESTNET="BNB Chain Testnet",a.BITTORRENT="BitTorrent",a.BITTORRENT_CHAIN_TESTNET="BitTorrent Chain Testnet",a.BLACKFORT_EXCHANGE_NETWORK="BlackFort Exchange Network",a.BLACKFORT_EXCHANGE_NETWORK_TESTNET="BlackFort Exchange Network Testnet",a.BLAST_SEPOLIA="Blast Sepolia",a.BNB_SMART_CHAIN="BNB Chain",a.BOBA_NETWORK="Boba Network",a.BRONOS="Bronos",a.BRONOS_TESTNET="Bronos Testnet",a.CANTO="Canto",a.CELO="Celo",a.CHILIZ_CHAIN="Chiliz Chain",a.CHILIZ_SPICY_TESTNET="Chiliz Spicy Testnet",a.CONFLUX_ESPACE="Conflux eSpace",a.CONFLUX_ESPACE_TESTNET="Conflux eSpace Testnet",a.CORE_DAO="Core Dao",a.COSTON="Coston",a.COSTON2="Coston2",a.CRONOS_MAINNET="Cronos Mainnet",a.CRONOS_TESTNET="Cronos Testnet",a.CROSSBELL="Crossbell",a.DEFICHAIN_EVM_MAINNET="DeFiChain EVM Mainnet",a.DEFICHAIN_EVM_TESTNET="DeFiChain EVM Testnet",a.DFK_CHAIN="DFK Chain",a.DOGECHAIN="Dogechain",a.EDGEWARE_EDGEEVM_MAINNET="Edgeware EdgeEVM Mainnet",a.EKTA="Ekta",a.EKTA_TESTNET="Ekta Testnet",a.EOS_EVM="EOS EVM",a.EOS_EVM_TESTNET="EOS EVM Testnet",a.ETHEREUM="Ethereum",a.ETHEREUM_CLASSIC="Ethereum Classic",a.EVMOS="Evmos",a.EVMOS_TESTNET="Evmos Testnet",a.FANTOM="Fantom",a.FANTOM_SONIC_OPEN_TESTNET="Fantom Sonic Open Testnet",a.FANTOM_TESTNET="Fantom Testnet",a.FIBO_CHAIN="Fibo Chain",a.FILECOIN_CALIBRATION="Filecoin Calibration",a.FILECOIN_HYPERSPACE="Filecoin Hyperspace",a.FILECOIN_MAINNET="Filecoin Mainnet",a.FLARE_MAINNET="Flare Mainnet",a.FOUNDRY="Foundry",a.FUSE="Fuse",a.FUSE_SPARKNET="Fuse Sparknet",a.GNOSIS="Gnosis",a.GNOSIS_CHIADO="Gnosis Chiado",a.GOERLI="Goerli",a.HAQQ_MAINNET="HAQQ Mainnet",a.HAQQ_TESTEDGE_2="HAQQ Testedge 2",a.HARDHAT="Hardhat",a.HARMONY_ONE="Harmony One",a.HEDERA_MAINNET="Hedera Mainnet",a.HEDERA_PREVIEWNET="Hedera Previewnet",a.HEDERA_TESTNET="Hedera Testnet",a.HOLESKY="Holesky",a.HORIZEN_GOBI_TESTNET="Horizen Gobi Testnet",a.IOTEX="IoTeX",a.IOTEX_TESTNET="IoTeX Testnet",a.JIBCHAIN_L1="JIBCHAIN L1",a.KARURA="Karura",a.KAVA_EVM="Kava EVM",a.KAVA_EVM_TESTNET="Kava EVM Testnet",a.KCC_MAINNET="KCC Mainnet",a.KLAYTN="Klaytn",a.KLAYTN_BAOBAB_TESTNET="Klaytn Baobab Testnet",a.KROMA="Kroma",a.KROMA_SEPOLIA="Kroma Sepolia",a.LIGHTLINK_PEGASUS_TESTNET="LightLink Pegasus Testnet",a.LIGHTLINK_PHOENIX="LightLink Phoenix",a.LINEA_GOERLI_TESTNET="Linea Goerli Testnet",a.LINEA_MAINNET="Linea Mainnet",a.LOCALHOST="Localhost",a.LUKSO="LUKSO",a.MANDALA_TC9="Mandala TC9",a.MANTA_PACIFIC_MAINNET="Manta Pacific Mainnet",a.MANTA_PACIFIC_TESTNET="Manta Pacific Testnet",a.MANTLE="Mantle",a.MANTLE_TESTNET="Mantle Testnet",a.METACHAIN_MAINNET="MetaChain Mainnet",a.METER="Meter",a.METER_TESTNET="Meter Testnet",a.METIS="Metis",a.METIS_GOERLI="Metis Goerli",a.MEVERSE_CHAIN_MAINNET="MEVerse Chain Mainnet",a.MEVERSE_CHAIN_TESTNET="MEVerse Chain Testnet",a.MODE_TESTNET="Mode Testnet",a.MOONBASE_ALPHA="Moonbase Alpha",a.MOONBEAM="Moonbeam",a.MOONBEAM_DEVELOPMENT_NODE="Moonbeam Development Node",a.MOONRIVER="Moonriver",a.NEON_EVM_DEVNET="Neon EVM DevNet",a.NEON_EVM_MAINNET="Neon EVM MainNet",a.NEXI="Nexi",a.NEXILIX_SMART_CHAIN="Nexilix Smart Chain",a.OASIS_SAPPHIRE="Oasis Sapphire",a.OASIS_SAPPHIRE_TESTNET="Oasis Sapphire Testnet",a.OASIS_TESTNET="Oasis Testnet",a.OASYS="Oasys",a.OKC="OKC",a.OORT_MAINNETDEV="OORT MainnetDev",a.OPBNB="opBNB",a.OPBNB_TESTNET="opBNB Testnet",a.OPTIMISM_GOERLI="Optimism Goerli",a.OP_MAINNET="Optimism",a.OP_SEPOLIA="Optimism Sepolia",a.PALM="Palm",a.PALM_TESTNET="Palm Testnet",a.PGN="PGN",a.PGN_="PGN ",a.PLINGA="Plinga",a.POLYGON="Polygon",a.POLYGON_AMOY="Polygon Amoy",a.POLYGON_MUMBAI="Polygon Mumbai",a.POLYGON_ZKEVM="Polygon zkEVM",a.POLYGON_ZKEVM_TESTNET="Polygon zkEVM Testnet",a.PULSECHAIN="PulseChain",a.PULSECHAIN_V4="PulseChain V4",a.Q_MAINNET="Q Mainnet",a.Q_TESTNET="Q Testnet",a.ROLLUX_MAINNET="Rollux Mainnet",a.ROLLUX_TESTNET="Rollux Testnet",a.RONIN="Ronin",a.ROOTSTOCK_MAINNET="Rootstock Mainnet",a.SAIGON_TESTNET="Saigon Testnet",a.SCROLL="Scroll",a.SCROLL_SEPOLIA="Scroll Sepolia",a.SCROLL_TESTNET="Scroll Testnet",a.SEPOLIA="Ethereum Sepolia",a.SHARDEUM_SPHINX="Shardeum Sphinx",a.SHIBARIUM="Shibarium",a.SHIMMER="Shimmer",a.SHIMMER_TESTNET="Shimmer Testnet",a["SKALE_|_BLOCK_BRAWLERS"]="SKALE | Block Brawlers",a["SKALE_|_CALYPSO_NFT_HUB"]="SKALE | Calypso NFT Hub",a["SKALE_|_CALYPSO_NFT_HUB_TESTNET"]="SKALE | Calypso NFT Hub Testnet",a["SKALE_|_CHAOS_TESTNET"]="SKALE | Chaos Testnet",a["SKALE_|_CRYPTOBLADES"]="SKALE | CryptoBlades",a["SKALE_|_CRYPTO_COLOSSEUM"]="SKALE | Crypto Colosseum",a["SKALE_|_EUROPA_LIQUIDITY_HUB"]="SKALE | Europa Liquidity Hub",a["SKALE_|_EUROPA_LIQUIDITY_HUB_TESTNET"]="SKALE | Europa Liquidity Hub Testnet",a["SKALE_|_EXORDE"]="SKALE | Exorde",a["SKALE_|_HUMAN_PROTOCOL"]="SKALE | Human Protocol",a["SKALE_|_NEBULA_GAMING_HUB"]="SKALE | Nebula Gaming Hub",a["SKALE_|_NEBULA_GAMING_HUB_TESTNET"]="SKALE | Nebula Gaming Hub Testnet",a["SKALE_|_RAZOR_NETWORK"]="SKALE | Razor Network",a["SKALE_|_TITAN_COMMUNITY_HUB"]="SKALE | Titan Community Hub",a["SKALE_|_TITAN_COMMUNITY_HUB_TESTNET"]="SKALE | Titan Community Hub Testnet",a.SONGBIRD_MAINNET="Songbird Mainnet",a.SYSCOIN_MAINNET="Syscoin Mainnet",a.SYSCOIN_TANENBAUM_TESTNET="Syscoin Tanenbaum Testnet",a["TAIKO_(ALPHA-3_TESTNET)"]="Taiko (Alpha-3 Testnet)",a["TAIKO_JOLNIR_(ALPHA-5_TESTNET)"]="Taiko Jolnir (Alpha-5 Testnet)",a["TAIKO_KATLA_(ALPHA-6_TESTNET)"]="Taiko Katla (Alpha-6 Testnet)",a.TARAXA_MAINNET="Taraxa Mainnet",a.TARAXA_TESTNET="Taraxa Testnet",a.TELOS="Telos",a.TENET="Tenet",a.VECHAIN="Vechain",a.WANCHAIN="Wanchain",a.WANCHAIN_TESTNET="Wanchain Testnet",a.WEMIX="WEMIX",a.WEMIX_TESTNET="WEMIX Testnet",a.X1_TESTNET="X1 Testnet",a.XINFIN_NETWORK="XinFin Network",a.ZETACHAIN_ATHENS_TESTNET="ZetaChain Athens Testnet",a.ZHEJIANG="Zhejiang",a.ZILLIQA="Zilliqa",a.ZILLIQA_TESTNET="Zilliqa Testnet",a.ZKFAIR_MAINNET="ZKFair Mainnet",a.ZKFAIR_TESTNET="ZKFair Testnet",a.ZKSYNC_ERA="zkSync Era",a.ZKSYNC_ERA_TESTNET="zkSync Era Testnet",a.ZKSYNC_SEPOLIA_TESTNET="zkSync Sepolia Testnet",a.ZORA="Zora",a.ZORA_GOERLI_TESTNET="Zora Goerli Testnet",a.ZORA_SEPOLIA="Zora Sepolia",a))(Mi||{}),Ui=(d=>(d.Pending="pending",d.Completed="completed",d.Failed="failed",d.Received="received",d.Success="success",d.Failure="failure",d.Dropped="dropped",d.Replaced="replaced",d.Stuck="stuck",d.Confirmed="confirmed",d))(Ui||{}),Wi=(s=>(s.USER_TO_TMC="user_to_tmc",s.TMC_TO_USER="tmc_to_user",s.RELAYER_TO_TMC="relayer_to_tmc",s.RELAYER_TO_CODEX="relayer_to_codex",s.RELAYER_TO_CIRCLE="relayer_to_circle",s))(Wi||{}),Oi=(r=>(r.D="deposit",r.W="withdraw",r.T="transfer",r))(Oi||{});var Ci=(n=>(n.COMPANY="COMPANY",n.TWITTER="TWITTER",n.DISCORD="DISCORD",n.TELEGRAM="TELEGRAM",n))(Ci||{});var Fi=(y=>(y[y.QUOTE=1]="QUOTE",y[y.LAST_PRICE=2]="LAST_PRICE",y[y.DEPTH=3]="DEPTH",y[y.LAST_CANDLESTICK=4]="LAST_CANDLESTICK",y[y.ORDERS=5]="ORDERS",y[y.TRADES=6]="TRADES",y[y.SYSTEM=7]="SYSTEM",y[y.WALLET_TRANSACTIONS=8]="WALLET_TRANSACTIONS",y[y.ALL_STAT=9]="ALL_STAT",y[y.CODEX_ASSETS=12]="CODEX_ASSETS",y[y.CODEX_BALANCES=10]="CODEX_BALANCES",y[y.LAST_LOOK=11]="LAST_LOOK",y[y.SETTINGS_UPDATE=13]="SETTINGS_UPDATE",y[y.NEW_NOTIFICATION=14]="NEW_NOTIFICATION",y[y.POINT_SYSTEM_SETTINGS_UPDATE=15]="POINT_SYSTEM_SETTINGS_UPDATE",y))(Fi||{}),ze=[5,8,10,11];var Li=(r=>(r.OFF="disable",r.ULTRADE="ultrade",r.ALL="all",r))(Li||{}),Bi=(g=>(g.ENABLED="company.enabled",g.APP_TITLE="company.appTitle",g.DOMAIN="company.domain",g.DIRECT_SETTLE="company.directSettlement",g.KYC="markets.kycTradeRequirementEnabled",g.GEOBLOCK="company.geoblock",g.LOGO="appearance.logo",g.THEMES="appearance.themes",g.NEW_TAB="appearance.newTab",g.TARGET="appearance.target",g.REPORT_BUTTONS="appearance.reportButtons",g.CUSTOM_MENU_ITEMS="appearance.customMenuItems",g.APPEARANCE_CHART_TYPE="appearance.chartType",g.APPEARANCE_CHART_INT="appearance.chartInt",g.AMM="product.amm",g.OBDEX="product.obdex",g.POINTS="product.pointSystem",g.AFFILIATE_DASHBOARD_THRESHOLD="product.affiliateDashboardThreshold",g.AFFILIATE_DEFAULT_FEE_SHARE="product.affiliateDefaultFeeShare",g.AFFILIATE_DASHBOARD_VISIBILITY="product.affiliateDashboardVisibility",g.AMM_FEE="company.ammFee",g.FEE_SHARE="company.feeShare",g.MIN_FEE="company.minFee",g.MAKER_FEE="company.makerFee",g.TAKER_FEE="company.takerFee",g.PINNED_PAIRS="markets.pinnedPairs",g.TWITTER_ENABLED="point-system.twitterEnabled",g.TWITTER_JOB_ENABLED="point-system.twitterJobEnabled",g.TWITTER_HASHTAGS="point-system.twitterHashtags",g.TWITTER_ACCOUNT_NAME="point-system.twitterAccountName",g.DISCORD_ENABLED="point-system.discordEnabled",g.TELEGRAM_ENABLED="point-system.telegramEnabled",g.TELEGRAM_GROUP_NAME="point-system.telegramGroupName",g.TELEGRAM_BOT_NAME="point-system.telegramBotName",g.GUIDE_LINK="point-system.guideLink",g))(Bi||{});var Gi=(r=>(r.DISABLED="disabled",r.ENABLED_FOR_ALL="enabled for all",r.ENABLED_FOR_AFFILIATES="enabled for affiliates",r))(Gi||{});import{decodeStateArray as Vi,getTxnParams as Yi}from"@ultrade/shared/browser/helpers/algo.helper";import ue from"algosdk";import qi from"axios";var he=class{constructor(e,t,r){this.client=e,this.authCredentials=t,this.indexerDomain=r}isAppOptedIn(e,t){return!!e?.find(r=>r.id===t)}isAssetOptedIn(e,t){return Object.keys(e).includes(t.toString())}async optInAsset(e,t){let r=await this.getTxnParams();return ue.makeAssetTransferTxnWithSuggestedParamsFromObject({suggestedParams:{...r},from:e,to:e,assetIndex:t,amount:0})}async makeAppCallTransaction(e,t,r,n,s){let o=[],l=[],u=[e];return ue.makeApplicationNoOpTxn(t,s||await this.getTxnParams(),r,n,o,l,u)}makeTransferTransaction(e,t,r,n,s){if(r<=0)return null;let o={suggestedParams:{...e},from:n,to:s,amount:r};return t===0?ue.makePaymentTxnWithSuggestedParamsFromObject(o):(o.assetIndex=t,ue.makeAssetTransferTxnWithSuggestedParamsFromObject(o))}get signer(){return this.authCredentials.signer}set signer(e){this.authCredentials.signer=e}async signAndSend(e){Array.isArray(e)||(e=[e]);let t=this.getCurrentAccount();if(t){let r=e.map(n=>n.signTxn(t.sk));return this.client.sendRawTransaction(r).do()}return this.authCredentials.signer.signAndSend(e)}async signAndSendData(e,t,r,n){let s=typeof e=="string"?e:JSON.stringify(e),o=typeof e=="string"?{message:s}:{...e},l=await t(s,n);return r({...o,signature:l})}async getTxnParams(){return await Yi(this.client)}getCurrentAccount(){return this.authCredentials.mnemonic?ue.mnemonicToSecretKey(this.authCredentials.mnemonic):null}async getAccountInfo(e){return this.client.accountInformation(e).do()}constructArgsForAppCall(...e){let t=[];return e.forEach(r=>{t.push(new Uint8Array(r.toBuffer?r.toBuffer():c.from(r.toString())))}),t}validateCredentials(){if(!this.authCredentials.mnemonic&&!this.authCredentials.signer)throw"You need specify mnemonic or signer to execute the method"}async getAppState(e){try{let t=await this.client.getApplicationByID(e).do();return Vi(t.params["global-state"])}catch(t){console.log(`Attempt to load app by id ${e}`),console.log(t.message)}}async getSuperAppId(e){return(await this.getAppState(e))?.UL_SUPERADMIN_APP||0}async getPairBalances(e,t){let{data:r}=await qi.get(`${this.indexerDomain}/v2/accounts/${t}?include-all=true`);if(r.account.hasOwnProperty("apps-local-state")){let n=r.account["apps-local-state"].find(l=>l.id===e&&l.deleted===!1);if(!n)return null;let s=n["key-value"].find(l=>l.key==="YWNjb3VudEluZm8="),o=c.from(s.value.bytes,"base64");return Jt(o)}}async calculateTransferAmount(e,t,r,n,s,o){let l=await this.getPairBalances(e,t),u=(r==="B"?l?.priceCoin_available:l?.baseCoin_available)??0;r==="B"&&(n=n/10**o*s);let f=Math.ceil(n-u);return f<0?0:f}};import Qt,{encodeAddress as $i}from"algosdk";var Xi={priceCoin_locked:{type:"uint"},priceCoin_available:{type:"uint"},baseCoin_locked:{type:"uint"},baseCoin_available:{type:"uint"},companyId:{type:"uint"},WLFeeShare:{type:"uint"},WLCustomFee:{type:"uint"},slotMap:{type:"uint"}},Jt=i=>{let e=new Map,t=0;for(let[r,n]of Object.entries(Xi)){if(t>=i.length)throw new Error("Array index out of bounds");let s;switch(n.type){case"address":s=$i(i.slice(t,t+32)),t+=32;break;case"bytes":s=i.slice(t,t+n.size),s=Qt.decodeUint64(s,"mixed"),t+=n.size;break;case"uint":s=Qt.decodeUint64(i.slice(t,t+8),"mixed"),t+=8;break;case"string":s=zi(i.slice(t,t+n.size)),t+=n.size;break}e.set(r,s)}return Object.fromEntries(e)},zi=i=>c.from(i).toString("utf-8");var Zt="By signing this message you are logging into your trading account and agreeing to all terms and conditions of the platform.";var Kt={mainnet:{algodNode:"https://mainnet-api.algonode.cloud",apiUrl:"https://mainnet-api.algonode.cloud",algodIndexer:"https://mainnet-idx.algonode.cloud"},testnet:{algodNode:"https://testnet-api.algonode.cloud",apiUrl:"https://testnet-apigw.ultradedev.net",algodIndexer:"https://testnet-idx.algonode.cloud"},local:{algodNode:"http://localhost:4001",apiUrl:"http://localhost:5001",algodIndexer:"http://localhost:8980"}},Je=["/market/balances","/market/order","/market/orders","/market/account/kyc/status","/market/account/kyc/init","/market/withdrawal-fee","/market/operation-details","/wallet/key","/wallet/transactions","/wallet/transfer","/wallet/withdraw","/wallet/whitelist","/wallet/withdrawal-wallets"];var Ht=class{constructor(e,t){this.axiosInterceptor=e=>{let t=l=>l.withWalletCredentials||(l.url?Je.some(u=>l.url.includes(u)):!1),r=l=>{let u=["/market/order"];return l.withWalletCredentials||(l.url?u.some(f=>l.url.includes(f)):!1)},n=l=>{let u=["/wallet/signin","/market/account/kyc/init","/notifications"];return l.url?u.some(f=>l.url.includes(f)):!1},s=l=>{let u=["/social/"];return l.url?u.some(f=>l.url.includes(f)):!1},o=l=>l.url?Je.some(u=>l.url.includes(u)):!1;return e.interceptors.request.use(l=>{if(this.wallet&&t(l)&&(l.headers["X-Wallet-Address"]=this.wallet.address,l.headers["X-Wallet-Token"]=this.wallet.token),this.wallet&&o(l)&&(l.headers.CompanyId=this.companyId),this.wallet&&r(l)){let u=this.wallet?.tradingKey;u&&(l.headers["X-Trading-Key"]=u)}return n(l)&&(l.headers.CompanyId=this.companyId),s(l)&&!l.headers.CompanyId&&(l.headers.CompanyId=this.isUltradeID?1:this.companyId),l},l=>Promise.reject(l)),e.interceptors.response.use(l=>l.data,async l=>(console.log("Request was failed",l),[401].includes(l?.response?.status)&&l.config&&t(l.config)&&(this.wallet=null,this.localStorageService.clearMainWallet()),Promise.reject(l))),e};let r=Kt[e.network];this.algodNode=r.algodNode,this.apiUrl=r.apiUrl,this.algodIndexer=r.algodIndexer,e.apiUrl!==void 0&&(this.apiUrl=e.apiUrl),e.companyId!==void 0&&(this.companyId=e.companyId),this.websocketUrl=e.websocketUrl,this.client=new he(e.algoSdkClient,t||{},this.algodIndexer),this._axios=this.axiosInterceptor(Ji.create({baseURL:this.apiUrl})),this.localStorageService=new Pe,this.wallet=this.localStorageService.getMainWallet(),this.isUltradeID=!1,this.socketManager=new le(this.websocketUrl,ce,n=>{console.log(`Socket ${n} disconnected at`,new Date)},n=>{console.log(`Socket connect_error due to ${n}`)}),console.log("SDK Wallet",this.wallet)}get useUltradeID(){return this.isUltradeID}set useUltradeID(e){this.isUltradeID=e}get isLogged(){return!!this.wallet?.token}get mainWallet(){return this.wallet}set mainWallet(e){this.wallet=e,e?this.localStorageService.setMainWallet(e):this.localStorageService.clearMainWallet()}setSigner(e){this.client.signer=e}subscribe(e,t){let r=e.streams.some(n=>ze.includes(n));return r&&!this.mainWallet?.token&&!this.mainWallet?.tradingKey?(e.streams=e.streams.filter(n=>!ze.includes(n)),this.socketManager.subscribe(e,t)):r?(e.options={...e.options,token:this.mainWallet?.token,tradingKey:this.mainWallet?.tradingKey},this.socketManager.subscribe(e,t)):this.socketManager.subscribe(e,t)}unsubscribe(e){this.socketManager.unsubscribe(e)}getPairList(e){let t=e?`&companyId=${e}`:"";return this._axios.get(`/market/markets?includeAllOrders=false${t}`)}getPair(e){return this._axios.get(`/market/market?symbol=${e}`)}getPrice(e){return this._axios.get(`/market/price?symbol=${e}`)}getDepth(e,t){return this._axios.get(`/market/depth?symbol=${e}&depth=${t}`)}getSymbols(e){return this._axios.get(`/market/symbols${e?"?mask="+e:""}`)}getLastTrades(e){return this._axios.get(`/market/last-trades?symbol=${e}`)}getHistory(e,t,r,n,s=500,o=1){return this._axios.get(`/market/history?symbol=${e}&interval=${t}&startTime=${r??""}&endTime=${n??""}&limit=${s}&page=${o}`)}getOrders(e,t,r=50,n,s){let o=t?t===1?fe.Open:[fe.Canceled,fe.Matched,fe.SelfMatched,fe.Expired].join(","):"",l=e?`&symbol=${e}`:"",u=o?`&status=${o}`:"",f=s?`&startTime=${s}`:"",d=n?`&endTime=${n}`:"";return this._axios.get(`/market/orders?limit=${r}${l}${u}${f}${d}`)}getOrderById(e){return this._axios.get(`/market/order/${e}`)}getSettings(){let e=new URL(window.location!==window.parent.location?document.referrer:document.location.href).host;return this._axios.get("/market/settings",{headers:{"wl-domain":e}})}getBalances(){return this._axios.get("/market/balances")}getChains(){return this._axios.get("/market/chains")}getCodexAssets(){return this._axios.get("/market/assets")}getCCTPAssets(){return this._axios.get("/market/cctp-assets")}getCCTPUnifiedAssets(){return this._axios.get("/market/cctp-unified-assets")}getWithdrawalFee(e,t){return this._axios.get(`/market/withdrawal-fee?assetAddress=${e}&chainId=${t}`)}getKycStatus(){return this._axios.get("/market/account/kyc/status")}getKycInitLink(e){return this._axios.post("/market/account/kyc/init",{embeddedAppUrl:e})}getDollarValues(e=[]){return this._axios.get(`/market/dollar-price?assetIds=${JSON.stringify(e)}`)}getTransactionDetalis(e){return this._axios.get(`/market/operation-details?operationId=${e}`)}getWalletTransactions(e,t,r=100){return this._axios.get(`/wallet/transactions?type=${e}&limit=${r}&page=${t}`,{withWalletCredentials:!0})}getTradingKeys(){return this._axios.get("/wallet/keys",{withWalletCredentials:!0})}getTransfers(e,t=100){return this._axios.get(`/wallet/transfers?limit=${t}&page=${e}`,{withWalletCredentials:!0})}getPendingTransactions(){return this._axios.get("/wallet/transactions/pending",{withWalletCredentials:!0})}getWhitelist(){return this._axios.get("/wallet/whitelist",{withWalletCredentials:!0})}async addWhitelist(e){e={...e,expiredDate:e.expiredDate&&Math.round(e.expiredDate/1e3)};let r=c.from(rn(e)).toString("hex");return await this.client.signAndSendData(r,this.client.signer.signMessage,({signature:n})=>this._axios.post("/wallet/whitelist",{message:r,signature:n}),"hex")}deleteWhitelist(e){let t={whitelistId:e};return this.client.signAndSendData(t,this.client.signer.signMessage,({signature:r})=>this._axios.delete("/wallet/whitelist",{data:{data:t,signature:r}}))}getAllWithdrawalWallets(){return this._axios.get("/wallet/withdrawal-wallets")}getWithdrawalWalletByAddress(e){return this._axios.get(`/wallet/withdrawal-wallets/${e}`)}createWithdrawalWallet(e){return this._axios.post("/wallet/withdrawal-wallets",e)}updateWithdrawalWallet(e){return this._axios.patch("/wallet/withdrawal-wallets",e)}deleteWithdrawalWallet(e){return this._axios.delete(`/wallet/withdrawal-wallets/${e}`)}getVersion(){return this._axios.get("/system/version")}getMaintenance(){return this._axios.get("/system/maintenance")}getNotifications(){return this._axios.get("/notifications",{withWalletCredentials:!0})}getNotificationsUnreadCount(){return this._axios.get("/notifications/count",{withWalletCredentials:!0})}readNotifications(e){return this._axios.put("/notifications",{notifications:e},{withWalletCredentials:!0})}getAffiliatesStatus(e){return this._axios.get(`/affiliates/${e}/dashboardStatus`,{withWalletCredentials:!0})}createAffiliate(e){return this._axios.post(`/affiliates/${e}`,{},{withWalletCredentials:!0})}getAffiliateProgress(e){return this._axios.get(`/affiliates/${e}/tradingVolumeProgress`,{withWalletCredentials:!0})}getAffiliateInfo(e,t){return this._axios.get(`/affiliates/${e}/dashboard?range=${t}`,{withWalletCredentials:!0})}async countAffiliateDepost(e){await this._axios.post(`/affiliates/${e}/deposit`,{},{withWalletCredentials:!0})}async countAffiliateClick(e){await this._axios.post("/affiliates/click",{referralToken:e},{withWalletCredentials:!0})}getSocialAccount(){return this._axios.get("/social/account",{withWalletCredentials:!0})}async addSocialEmail(e,t){await this._axios.put("/social/account/email",{email:e,embeddedAppUrl:t},{withWalletCredentials:!0})}async verifySocialEmail(e,t){await this._axios.put("/social/account/verifyEmail",{email:e,hash:t},{withWalletCredentials:!0})}getLeaderboards(){return this._axios.get("/social/leaderboard",{withWalletCredentials:!0})}getUnlocks(){return this._axios.get("/social/unlocks",{withWalletCredentials:!0})}getSocialSettings(){return this._axios.get("/social/settings",{withWalletCredentials:!0})}getSeason(e){return this._axios.get("/social/seasons/active",{withWalletCredentials:!0,headers:{CompanyId:e}})}getPastSeasons(){return this._axios.get("/social/seasons/history",{withWalletCredentials:!0})}addTelegram(e){return this._axios.post("/social/telegram/connect",e,{withWalletCredentials:!0})}async disconnectTelegram(e){await this._axios.put("/social/telegram/disconnect",e,{withWalletCredentials:!0})}async getDiscordConnectionUrl(e){let t=e?`?embeddedAppUrl=${encodeURIComponent(e)}`:"";return(await this._axios.get(`/social/discord/connect${t}`,{withWalletCredentials:!0})).url}async disconnectDiscord(){await this._axios.put("/social/discord/disconnect",{},{withWalletCredentials:!0})}async getTwitterConnectionUrl(e,t){let r=e?`?embeddedAppUrl=${encodeURIComponent(e)}`:"",n=t?`&scopes=${t}`:"";return(await this._axios.get(`/social/twitter/connect${r}${n}`,{withWalletCredentials:!0})).url}async disconnectTwitter(){await this._axios.put("/social/twitter/disconnect",{},{withWalletCredentials:!0})}getTweets(){return this._axios.get("/social/twitter/tweets",{withWalletCredentials:!0})}async actionWithTweet(e){await this._axios.post("/social/twitter/tweet/actions",e,{withWalletCredentials:!0})}getActions(){return this._axios.get("/social/actions",{withWalletCredentials:!0})}getActionHistory(){return this._axios.get("/social/actions/history",{withWalletCredentials:!0})}getAIStyles(){return this._axios.get("/social/twitter/tweets/styles",{withWalletCredentials:!0})}getAIComment(e,t){return this._axios.get(`/social/twitter/tweets/${t}/generateComment?styleId=${e}`,{withWalletCredentials:!0})}getTechnologyByProvider(e){switch(e){case q.PERA:return"ALGORAND";case q.METAMASK:return"EVM";case q.SOLFLARE:case q.COINBASE:case q.PHANTOM:case q.BACKPACK:case q.MOBILE:return"SOLANA";default:throw new Error("Not implemented")}}async login({address:e,provider:t,chain:r,referralToken:n,loginMessage:s}){let l=s||Zt,u={address:e,technology:this.getTechnologyByProvider(t)},f=c.from(ji(u,l)).toString("hex");return await this.client.signAndSendData(f,this.client.signer.signMessage,async({signature:d})=>{let p=await this._axios.put("/wallet/signin",{data:u,message:f,encoding:"hex",signature:d,referralToken:n});return this.mainWallet={address:e,provider:t,token:p,chain:r},p},"hex")}async addTradingKey(e){let r=c.from(jt(e,!0)).toString("hex"),{device:n,type:s}=e;return await this.client.signAndSendData(r,this.client.signer.signMessage,async({signature:o})=>{let l=await this._axios.post("/wallet/key",{data:{device:n,type:s},encoding:"hex",message:r,signature:o});return this.mainWallet&&l.type===tn.User&&(this.mainWallet.tradingKey=l.address),l},"hex")}async revokeTradingKey(e){let r=c.from(jt(e,!1)).toString("hex"),{device:n,type:s}=e;return await this.client.signAndSendData(r,this.client.signer.signMessage,async({signature:o})=>(await this._axios.delete("/wallet/key",{data:{data:{device:n,type:s},encoding:"hex",message:r,signature:o}}),this.mainWallet&&e.tkAddress===this.mainWallet.tradingKey&&(this.mainWallet.tradingKey=void 0),{signature:o}),"hex")}async withdraw(e,t){let n={...e,random:Qe(1,Number.MAX_SAFE_INTEGER)},s=c.from(en(n,t)).toString("hex");return await this.client.signAndSendData(s,this.client.signer.signMessage,({signature:o})=>this._axios.post("/wallet/withdraw",{encoding:"hex",message:s,signature:o,destinationAddress:n.recipient}),"hex")}async transfer(e){let r={...e,random:Qe(1,Number.MAX_SAFE_INTEGER)},n=c.from(nn(r)).toString("hex");return await this.client.signAndSendData(n,this.client.signer.signMessage,({signature:s})=>this._axios.post("/wallet/transfer",{message:n,signature:s}),"hex")}async createOrder(e){let t=Qi*24*60*60,r=Math.floor(Date.now()/1e3)+t,n={...e,version:Zi,expiredTime:r,random:Qe(1,Number.MAX_SAFE_INTEGER)};console.log("CreateOrderData",n);let s="hex",o=c.from(Hi(n)).toString(s);return await this.client.signAndSendData(o,this.client.signer.signMessageByToken,({signature:l})=>this._axios.post("/market/order",{encoding:s,message:o,signature:l}),s)}async cancelOrder(e){let t={orderId:e.orderId},r="hex",n=c.from(Ki(e)).toString(r);return await this.client.signAndSendData(n,this.client.signer.signMessageByToken,({signature:s})=>this._axios.delete("/market/order",{data:{data:t,message:n,signature:s}}),r)}async cancelMultipleOrders({orderIds:e,pairId:t}){let r={orderIds:e,pairId:t};return await this.client.signAndSendData(r,this.client.signer.signMessageByToken,({signature:n})=>this._axios.delete("/market/orders",{data:{data:r,signature:n}}))}async ping(){let e=await this._axios.get("/system/time");return Math.round(Date.now()-e.currentTime)}};export{Oi as ACTION_TYPE,Gi as AffDashboardVisibilitySettingEnum,Mi as BLOCKCHAINS,Ht as Client,Zt as DEFAULT_LOGIN_MESSAGE,Pi as DIRECT_SETTLE,Kt as NETWORK_CONFIGS,Si as ORDER_STATUS,Ui as OperationStatusEnum,vi as OrderStatus,Di as OrderTypeEnum,Ni as OrderUpdateStaus,Li as POINTS_SETTING,ze as PRIVATE_STREAMS,Ri as PairSettingsIds,Ci as SOCIAL_ACTION_SOURCE,Fi as STREAMS,Bi as SettingIds,le as SocketManager,Wi as TransactionType,Je as tokenizedUrls};
1
+ var er=Object.defineProperty;var tr=(i,e)=>{for(var t in e)er(i,t,{get:e[t],enumerable:!0})};function Ke(){throw new Error("setTimeout has not been defined")}function je(){throw new Error("clearTimeout has not been defined")}var U=Ke,W=je;typeof globalThis.setTimeout=="function"&&(U=setTimeout);typeof globalThis.clearTimeout=="function"&&(W=clearTimeout);function He(i){if(U===setTimeout)return setTimeout(i,0);if((U===Ke||!U)&&setTimeout)return U=setTimeout,setTimeout(i,0);try{return U(i,0)}catch{try{return U.call(null,i,0)}catch{return U.call(this,i,0)}}}function rr(i){if(W===clearTimeout)return clearTimeout(i);if((W===je||!W)&&clearTimeout)return W=clearTimeout,clearTimeout(i);try{return W(i)}catch{try{return W.call(null,i)}catch{return W.call(this,i)}}}var S=[],z=!1,L,de=-1;function ir(){!z||!L||(z=!1,L.length?S=L.concat(S):de=-1,S.length&&et())}function et(){if(!z){var i=He(ir);z=!0;for(var e=S.length;e;){for(L=S,S=[];++de<e;)L&&L[de].run();de=-1,e=S.length}L=null,z=!1,rr(i)}}function nr(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];S.push(new tt(i,e)),S.length===1&&!z&&He(et)}function tt(i,e){this.fun=i,this.array=e}tt.prototype.run=function(){this.fun.apply(null,this.array)};var sr="browser",or="browser",ar=!0,cr={},lr=[],ur="",hr={},fr={},dr={};function B(){}var pr=B,mr=B,gr=B,yr=B,Tr=B,Er=B,_r=B;function br(i){throw new Error("process.binding is not supported")}function Ar(){return"/"}function xr(i){throw new Error("process.chdir is not supported")}function wr(){return 0}var X=globalThis.performance||{},Ir=X.now||X.mozNow||X.msNow||X.oNow||X.webkitNow||function(){return new Date().getTime()};function kr(i){var e=Ir.call(X)*.001,t=Math.floor(e),r=Math.floor(e%1*1e9);return i&&(t=t-i[0],r=r-i[1],r<0&&(t--,r+=1e9)),[t,r]}var Pr=new Date;function Rr(){var i=new Date,e=i-Pr;return e/1e3}var h={nextTick:nr,title:sr,browser:ar,env:cr,argv:lr,version:ur,versions:hr,on:pr,addListener:mr,once:gr,off:yr,removeListener:Tr,removeAllListeners:Er,emit:_r,binding:br,cwd:Ar,chdir:xr,umask:wr,hrtime:kr,platform:or,release:fr,config:dr,uptime:Rr},Ze={};Object.keys(Ze).forEach(i=>{let e=i.split("."),t=h;for(let r=0;r<e.length;r++){let n=e[r];r===e.length-1?t[n]=Ze[i]:t=t[n]||(t[n]={})}});var P=[],I=[],Sr=typeof Uint8Array<"u"?Uint8Array:Array,Se=!1;function st(){Se=!0;for(var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,t=i.length;e<t;++e)P[e]=i[e],I[i.charCodeAt(e)]=e;I[45]=62,I[95]=63}function vr(i){Se||st();var e,t,r,n,s,o,l=i.length;if(l%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s=i[l-2]==="="?2:i[l-1]==="="?1:0,o=new Sr(l*3/4-s),r=s>0?l-4:l;var u=0;for(e=0,t=0;e<r;e+=4,t+=3)n=I[i.charCodeAt(e)]<<18|I[i.charCodeAt(e+1)]<<12|I[i.charCodeAt(e+2)]<<6|I[i.charCodeAt(e+3)],o[u++]=n>>16&255,o[u++]=n>>8&255,o[u++]=n&255;return s===2?(n=I[i.charCodeAt(e)]<<2|I[i.charCodeAt(e+1)]>>4,o[u++]=n&255):s===1&&(n=I[i.charCodeAt(e)]<<10|I[i.charCodeAt(e+1)]<<4|I[i.charCodeAt(e+2)]>>2,o[u++]=n>>8&255,o[u++]=n&255),o}function Dr(i){return P[i>>18&63]+P[i>>12&63]+P[i>>6&63]+P[i&63]}function Nr(i,e,t){for(var r,n=[],s=e;s<t;s+=3)r=(i[s]<<16)+(i[s+1]<<8)+i[s+2],n.push(Dr(r));return n.join("")}function rt(i){Se||st();for(var e,t=i.length,r=t%3,n="",s=[],o=16383,l=0,u=t-r;l<u;l+=o)s.push(Nr(i,l,l+o>u?u:l+o));return r===1?(e=i[t-1],n+=P[e>>2],n+=P[e<<4&63],n+="=="):r===2&&(e=(i[t-2]<<8)+i[t-1],n+=P[e>>10],n+=P[e>>4&63],n+=P[e<<2&63],n+="="),s.push(n),s.join("")}c.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:!0;function pe(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function v(i,e){if(pe()<e)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(i=new Uint8Array(e),i.__proto__=c.prototype):(i===null&&(i=new c(e)),i.length=e),i}function c(i,e,t){if(!c.TYPED_ARRAY_SUPPORT&&!(this instanceof c))return new c(i,e,t);if(typeof i=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return ve(this,i)}return ot(this,i,e,t)}c.poolSize=8192;c._augment=function(i){return i.__proto__=c.prototype,i};function ot(i,e,t,r){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?Wr(i,e,t,r):typeof e=="string"?Ur(i,e,t):Or(i,e)}c.from=function(i,e,t){return ot(null,i,e,t)};c.kMaxLength=pe();c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&c[Symbol.species]);function at(i){if(typeof i!="number")throw new TypeError('"size" argument must be a number');if(i<0)throw new RangeError('"size" argument must not be negative')}function Mr(i,e,t,r){return at(e),e<=0?v(i,e):t!==void 0?typeof r=="string"?v(i,e).fill(t,r):v(i,e).fill(t):v(i,e)}c.alloc=function(i,e,t){return Mr(null,i,e,t)};function ve(i,e){if(at(e),i=v(i,e<0?0:De(e)|0),!c.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)i[t]=0;return i}c.allocUnsafe=function(i){return ve(null,i)};c.allocUnsafeSlow=function(i){return ve(null,i)};function Ur(i,e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!c.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var r=ct(e,t)|0;i=v(i,r);var n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function Re(i,e){var t=e.length<0?0:De(e.length)|0;i=v(i,t);for(var r=0;r<t;r+=1)i[r]=e[r]&255;return i}function Wr(i,e,t,r){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(r||0))throw new RangeError("'length' is out of bounds");return t===void 0&&r===void 0?e=new Uint8Array(e):r===void 0?e=new Uint8Array(e,t):e=new Uint8Array(e,t,r),c.TYPED_ARRAY_SUPPORT?(i=e,i.__proto__=c.prototype):i=Re(i,e),i}function Or(i,e){if(R(e)){var t=De(e.length)|0;return i=v(i,t),i.length===0||e.copy(i,0,0,t),i}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||ti(e.length)?v(i,0):Re(i,e);if(e.type==="Buffer"&&Array.isArray(e.data))return Re(i,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function De(i){if(i>=pe())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+pe().toString(16)+" bytes");return i|0}c.isBuffer=ri;function R(i){return!!(i!=null&&i._isBuffer)}c.compare=function(e,t){if(!R(e)||!R(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,s=0,o=Math.min(r,n);s<o;++s)if(e[s]!==t[s]){r=e[s],n=t[s];break}return r<n?-1:n<r?1:0};c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return c.alloc(0);var r;if(t===void 0)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=c.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var o=e[r];if(!R(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(n,s),s+=o.length}return n};function ct(i,e){if(R(i))return i.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(i)||i instanceof ArrayBuffer))return i.byteLength;typeof i!="string"&&(i=""+i);var t=i.length;if(t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":case void 0:return me(i).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return mt(i).length;default:if(r)return me(i).length;e=(""+e).toLowerCase(),r=!0}}c.byteLength=ct;function Cr(i,e,t){var r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(i||(i="utf8");;)switch(i){case"hex":return zr(this,e,t);case"utf8":case"utf-8":return ht(this,e,t);case"ascii":return $r(this,e,t);case"latin1":case"binary":return Xr(this,e,t);case"base64":return Yr(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Jr(this,e,t);default:if(r)throw new TypeError("Unknown encoding: "+i);i=(i+"").toLowerCase(),r=!0}}c.prototype._isBuffer=!0;function G(i,e,t){var r=i[e];i[e]=i[t],i[t]=r}c.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)G(this,t,t+1);return this};c.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)G(this,t,t+3),G(this,t+1,t+2);return this};c.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)G(this,t,t+7),G(this,t+1,t+6),G(this,t+2,t+5),G(this,t+3,t+4);return this};c.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?ht(this,0,e):Cr.apply(this,arguments)};c.prototype.equals=function(e){if(!R(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:c.compare(this,e)===0};c.prototype.compare=function(e,t,r,n,s){if(!R(e))throw new TypeError("Argument must be a Buffer");if(t===void 0&&(t=0),r===void 0&&(r=e?e.length:0),n===void 0&&(n=0),s===void 0&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,s>>>=0,this===e)return 0;for(var o=s-n,l=r-t,u=Math.min(o,l),f=this.slice(n,s),d=e.slice(t,r),p=0;p<u;++p)if(f[p]!==d[p]){o=f[p],l=d[p];break}return o<l?-1:l<o?1:0};function lt(i,e,t,r,n){if(i.length===0)return-1;if(typeof t=="string"?(r=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=n?0:i.length-1),t<0&&(t=i.length+t),t>=i.length){if(n)return-1;t=i.length-1}else if(t<0)if(n)t=0;else return-1;if(typeof e=="string"&&(e=c.from(e,r)),R(e))return e.length===0?-1:it(i,e,t,r,n);if(typeof e=="number")return e=e&255,c.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(i,e,t):Uint8Array.prototype.lastIndexOf.call(i,e,t):it(i,[e],t,r,n);throw new TypeError("val must be string, number or Buffer")}function it(i,e,t,r,n){var s=1,o=i.length,l=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(i.length<2||e.length<2)return-1;s=2,o/=2,l/=2,t/=2}function u(x,$){return s===1?x[$]:x.readUInt16BE($*s)}var f;if(n){var d=-1;for(f=t;f<o;f++)if(u(i,f)===u(e,d===-1?0:f-d)){if(d===-1&&(d=f),f-d+1===l)return d*s}else d!==-1&&(f-=f-d),d=-1}else for(t+l>o&&(t=o-l),f=t;f>=0;f--){for(var p=!0,_=0;_<l;_++)if(u(i,f+_)!==u(e,_)){p=!1;break}if(p)return f}return-1}c.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1};c.prototype.indexOf=function(e,t,r){return lt(this,e,t,r,!0)};c.prototype.lastIndexOf=function(e,t,r){return lt(this,e,t,r,!1)};function Fr(i,e,t,r){t=Number(t)||0;var n=i.length-t;r?(r=Number(r),r>n&&(r=n)):r=n;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var l=parseInt(e.substr(o*2,2),16);if(isNaN(l))return o;i[t+o]=l}return o}function Lr(i,e,t,r){return Te(me(e,i.length-t),i,t,r)}function ut(i,e,t,r){return Te(Hr(e),i,t,r)}function Br(i,e,t,r){return ut(i,e,t,r)}function Gr(i,e,t,r){return Te(mt(e),i,t,r)}function Vr(i,e,t,r){return Te(ei(e,i.length-t),i,t,r)}c.prototype.write=function(e,t,r,n){if(t===void 0)n="utf8",r=this.length,t=0;else if(r===void 0&&typeof t=="string")n=t,r=this.length,t=0;else if(isFinite(t))t=t|0,isFinite(r)?(r=r|0,n===void 0&&(n="utf8")):(n=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-t;if((r===void 0||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return Fr(this,e,t,r);case"utf8":case"utf-8":return Lr(this,e,t,r);case"ascii":return ut(this,e,t,r);case"latin1":case"binary":return Br(this,e,t,r);case"base64":return Gr(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Vr(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}};c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Yr(i,e,t){return e===0&&t===i.length?rt(i):rt(i.slice(e,t))}function ht(i,e,t){t=Math.min(i.length,t);for(var r=[],n=e;n<t;){var s=i[n],o=null,l=s>239?4:s>223?3:s>191?2:1;if(n+l<=t){var u,f,d,p;switch(l){case 1:s<128&&(o=s);break;case 2:u=i[n+1],(u&192)===128&&(p=(s&31)<<6|u&63,p>127&&(o=p));break;case 3:u=i[n+1],f=i[n+2],(u&192)===128&&(f&192)===128&&(p=(s&15)<<12|(u&63)<<6|f&63,p>2047&&(p<55296||p>57343)&&(o=p));break;case 4:u=i[n+1],f=i[n+2],d=i[n+3],(u&192)===128&&(f&192)===128&&(d&192)===128&&(p=(s&15)<<18|(u&63)<<12|(f&63)<<6|d&63,p>65535&&p<1114112&&(o=p))}}o===null?(o=65533,l=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),n+=l}return qr(r)}var nt=4096;function qr(i){var e=i.length;if(e<=nt)return String.fromCharCode.apply(String,i);for(var t="",r=0;r<e;)t+=String.fromCharCode.apply(String,i.slice(r,r+=nt));return t}function $r(i,e,t){var r="";t=Math.min(i.length,t);for(var n=e;n<t;++n)r+=String.fromCharCode(i[n]&127);return r}function Xr(i,e,t){var r="";t=Math.min(i.length,t);for(var n=e;n<t;++n)r+=String.fromCharCode(i[n]);return r}function zr(i,e,t){var r=i.length;(!e||e<0)&&(e=0),(!t||t<0||t>r)&&(t=r);for(var n="",s=e;s<t;++s)n+=jr(i[s]);return n}function Jr(i,e,t){for(var r=i.slice(e,t),n="",s=0;s<r.length;s+=2)n+=String.fromCharCode(r[s]+r[s+1]*256);return n}c.prototype.slice=function(e,t){var r=this.length;e=~~e,t=t===void 0?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);var n;if(c.TYPED_ARRAY_SUPPORT)n=this.subarray(e,t),n.__proto__=c.prototype;else{var s=t-e;n=new c(s,void 0);for(var o=0;o<s;++o)n[o]=this[o+e]}return n};function E(i,e,t){if(i%1!==0||i<0)throw new RangeError("offset is not uint");if(i+e>t)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUIntLE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e],s=1,o=0;++o<t&&(s*=256);)n+=this[e+o]*s;return n};c.prototype.readUIntBE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e+--t],s=1;t>0&&(s*=256);)n+=this[e+--t]*s;return n};c.prototype.readUInt8=function(e,t){return t||E(e,1,this.length),this[e]};c.prototype.readUInt16LE=function(e,t){return t||E(e,2,this.length),this[e]|this[e+1]<<8};c.prototype.readUInt16BE=function(e,t){return t||E(e,2,this.length),this[e]<<8|this[e+1]};c.prototype.readUInt32LE=function(e,t){return t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};c.prototype.readUInt32BE=function(e,t){return t||E(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};c.prototype.readIntLE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=this[e],s=1,o=0;++o<t&&(s*=256);)n+=this[e+o]*s;return s*=128,n>=s&&(n-=Math.pow(2,8*t)),n};c.prototype.readIntBE=function(e,t,r){e=e|0,t=t|0,r||E(e,t,this.length);for(var n=t,s=1,o=this[e+--n];n>0&&(s*=256);)o+=this[e+--n]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o};c.prototype.readInt8=function(e,t){return t||E(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};c.prototype.readInt16LE=function(e,t){t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};c.prototype.readInt16BE=function(e,t){t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};c.prototype.readInt32LE=function(e,t){return t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};c.prototype.readInt32BE=function(e,t){return t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};c.prototype.readFloatLE=function(e,t){return t||E(e,4,this.length),Ee(this,e,!0,23,4)};c.prototype.readFloatBE=function(e,t){return t||E(e,4,this.length),Ee(this,e,!1,23,4)};c.prototype.readDoubleLE=function(e,t){return t||E(e,8,this.length),Ee(this,e,!0,52,8)};c.prototype.readDoubleBE=function(e,t){return t||E(e,8,this.length),Ee(this,e,!1,52,8)};function A(i,e,t,r,n,s){if(!R(i))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<s)throw new RangeError('"value" argument is out of bounds');if(t+r>i.length)throw new RangeError("Index out of range")}c.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=t|0,r=r|0,!n){var s=Math.pow(2,8*r)-1;A(this,e,t,r,s,0)}var o=1,l=0;for(this[t]=e&255;++l<r&&(o*=256);)this[t+l]=e/o&255;return t+r};c.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t=t|0,r=r|0,!n){var s=Math.pow(2,8*r)-1;A(this,e,t,r,s,0)}var o=r-1,l=1;for(this[t+o]=e&255;--o>=0&&(l*=256);)this[t+o]=e/l&255;return t+r};c.prototype.writeUInt8=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function ge(i,e,t,r){e<0&&(e=65535+e+1);for(var n=0,s=Math.min(i.length-t,2);n<s;++n)i[t+n]=(e&255<<8*(r?n:1-n))>>>(r?n:1-n)*8}c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):ge(this,e,t,!0),t+2};c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):ge(this,e,t,!1),t+2};function ye(i,e,t,r){e<0&&(e=4294967295+e+1);for(var n=0,s=Math.min(i.length-t,4);n<s;++n)i[t+n]=e>>>(r?n:3-n)*8&255}c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):ye(this,e,t,!0),t+4};c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):ye(this,e,t,!1),t+4};c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=t|0,!n){var s=Math.pow(2,8*r-1);A(this,e,t,r,s-1,-s)}var o=0,l=1,u=0;for(this[t]=e&255;++o<r&&(l*=256);)e<0&&u===0&&this[t+o-1]!==0&&(u=1),this[t+o]=(e/l>>0)-u&255;return t+r};c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=t|0,!n){var s=Math.pow(2,8*r-1);A(this,e,t,r,s-1,-s)}var o=r-1,l=1,u=0;for(this[t+o]=e&255;--o>=0&&(l*=256);)e<0&&u===0&&this[t+o+1]!==0&&(u=1),this[t+o]=(e/l>>0)-u&255;return t+r};c.prototype.writeInt8=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1};c.prototype.writeInt16LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):ge(this,e,t,!0),t+2};c.prototype.writeInt16BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):ge(this,e,t,!1),t+2};c.prototype.writeInt32LE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):ye(this,e,t,!0),t+4};c.prototype.writeInt32BE=function(e,t,r){return e=+e,t=t|0,r||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):ye(this,e,t,!1),t+4};function ft(i,e,t,r,n,s){if(t+r>i.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function dt(i,e,t,r,n){return n||ft(i,e,t,4,34028234663852886e22,-34028234663852886e22),yt(i,e,t,r,23,4),t+4}c.prototype.writeFloatLE=function(e,t,r){return dt(this,e,t,!0,r)};c.prototype.writeFloatBE=function(e,t,r){return dt(this,e,t,!1,r)};function pt(i,e,t,r,n){return n||ft(i,e,t,8,17976931348623157e292,-17976931348623157e292),yt(i,e,t,r,52,8),t+8}c.prototype.writeDoubleLE=function(e,t,r){return pt(this,e,t,!0,r)};c.prototype.writeDoubleBE=function(e,t,r){return pt(this,e,t,!1,r)};c.prototype.copy=function(e,t,r,n){if(r||(r=0),!n&&n!==0&&(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var s=n-r,o;if(this===e&&r<t&&t<n)for(o=s-1;o>=0;--o)e[o+t]=this[o+r];else if(s<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+s),t);return s};c.prototype.fill=function(e,t,r,n){if(typeof e=="string"){if(typeof t=="string"?(n=t,t=0,r=this.length):typeof r=="string"&&(n=r,r=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s)}if(n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!c.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else typeof e=="number"&&(e=e&255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t=t>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);var o;if(typeof e=="number")for(o=t;o<r;++o)this[o]=e;else{var l=R(e)?e:me(new c(e,n).toString()),u=l.length;for(o=0;o<r-t;++o)this[o+t]=l[o%u]}return this};var Qr=/[^+\/0-9A-Za-z-_]/g;function Zr(i){if(i=Kr(i).replace(Qr,""),i.length<2)return"";for(;i.length%4!==0;)i=i+"=";return i}function Kr(i){return i.trim?i.trim():i.replace(/^\s+|\s+$/g,"")}function jr(i){return i<16?"0"+i.toString(16):i.toString(16)}function me(i,e){e=e||1/0;for(var t,r=i.length,n=null,s=[],o=0;o<r;++o){if(t=i.charCodeAt(o),t>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===r){(e-=3)>-1&&s.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),n=t;continue}t=(n-55296<<10|t-56320)+65536}else n&&(e-=3)>-1&&s.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return s}function Hr(i){for(var e=[],t=0;t<i.length;++t)e.push(i.charCodeAt(t)&255);return e}function ei(i,e){for(var t,r,n,s=[],o=0;o<i.length&&!((e-=2)<0);++o)t=i.charCodeAt(o),r=t>>8,n=t%256,s.push(n),s.push(r);return s}function mt(i){return vr(Zr(i))}function Te(i,e,t,r){for(var n=0;n<r&&!(n+t>=e.length||n>=i.length);++n)e[n+t]=i[n];return n}function ti(i){return i!==i}function ri(i){return i!=null&&(!!i._isBuffer||gt(i)||ii(i))}function gt(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function ii(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&gt(i.slice(0,0))}function Ee(i,e,t,r,n){var s,o,l=n*8-r-1,u=(1<<l)-1,f=u>>1,d=-7,p=t?n-1:0,_=t?-1:1,x=i[e+p];for(p+=_,s=x&(1<<-d)-1,x>>=-d,d+=l;d>0;s=s*256+i[e+p],p+=_,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=o*256+i[e+p],p+=_,d-=8);if(s===0)s=1-f;else{if(s===u)return o?NaN:(x?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-f}return(x?-1:1)*o*Math.pow(2,s-r)}function yt(i,e,t,r,n,s){var o,l,u,f=s*8-n-1,d=(1<<f)-1,p=d>>1,_=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,x=r?0:s-1,$=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+p>=1?e+=_/u:e+=_*Math.pow(2,1-p),e*u>=2&&(o++,u/=2),o+p>=d?(l=0,o=d):o+p>=1?(l=(e*u-1)*Math.pow(2,n),o=o+p):(l=e*Math.pow(2,p-1)*Math.pow(2,n),o=0));n>=8;i[t+x]=l&255,x+=$,l/=256,n-=8);for(o=o<<n|l,f+=n;f>0;i[t+x]=o&255,x+=$,o/=256,f-=8);i[t+x-$]|=y*128}var k=Object.create(null);k.open="0";k.close="1";k.ping="2";k.pong="3";k.message="4";k.upgrade="5";k.noop="6";var H=Object.create(null);Object.keys(k).forEach(i=>{H[k[i]]=i});var ee={type:"error",data:"parser error"};var _t=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",bt=typeof ArrayBuffer=="function",At=i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i&&i.buffer instanceof ArrayBuffer,te=({type:i,data:e},t,r)=>_t&&e instanceof Blob?t?r(e):Tt(e,r):bt&&(e instanceof ArrayBuffer||At(e))?t?r(e):Tt(new Blob([e]),r):r(k[i]+(e||"")),Tt=(i,e)=>{let t=new FileReader;return t.onload=function(){let r=t.result.split(",")[1];e("b"+(r||""))},t.readAsDataURL(i)};function Et(i){return i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}var Ne;function xt(i,e){if(_t&&i.data instanceof Blob)return i.data.arrayBuffer().then(Et).then(e);if(bt&&(i.data instanceof ArrayBuffer||At(i.data)))return e(Et(i.data));te(i,!1,t=>{Ne||(Ne=new TextEncoder),e(Ne.encode(t))})}var wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",re=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let i=0;i<wt.length;i++)re[wt.charCodeAt(i)]=i;var It=i=>{let e=i.length*.75,t=i.length,r,n=0,s,o,l,u;i[i.length-1]==="="&&(e--,i[i.length-2]==="="&&e--);let f=new ArrayBuffer(e),d=new Uint8Array(f);for(r=0;r<t;r+=4)s=re[i.charCodeAt(r)],o=re[i.charCodeAt(r+1)],l=re[i.charCodeAt(r+2)],u=re[i.charCodeAt(r+3)],d[n++]=s<<2|o>>4,d[n++]=(o&15)<<4|l>>2,d[n++]=(l&3)<<6|u&63;return f};var ni=typeof ArrayBuffer=="function",ie=(i,e)=>{if(typeof i!="string")return{type:"message",data:kt(i,e)};let t=i.charAt(0);return t==="b"?{type:"message",data:si(i.substring(1),e)}:H[t]?i.length>1?{type:H[t],data:i.substring(1)}:{type:H[t]}:ee},si=(i,e)=>{if(ni){let t=It(i);return kt(t,e)}else return{base64:!0,data:i}},kt=(i,e)=>{switch(e){case"blob":return i instanceof Blob?i:new Blob([i]);case"arraybuffer":default:return i instanceof ArrayBuffer?i:i.buffer}};var Pt="",Rt=(i,e)=>{let t=i.length,r=new Array(t),n=0;i.forEach((s,o)=>{te(s,!1,l=>{r[o]=l,++n===t&&e(r.join(Pt))})})},St=(i,e)=>{let t=i.split(Pt),r=[];for(let n=0;n<t.length;n++){let s=ie(t[n],e);if(r.push(s),s.type==="error")break}return r};function vt(){return new TransformStream({transform(i,e){xt(i,t=>{let r=t.length,n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,r)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(r))}i.data&&typeof i.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var Me;function _e(i){return i.reduce((e,t)=>e+t.length,0)}function be(i,e){if(i[0].length===e)return i.shift();let t=new Uint8Array(e),r=0;for(let n=0;n<e;n++)t[n]=i[0][r++],r===i[0].length&&(i.shift(),r=0);return i.length&&r<i[0].length&&(i[0]=i[0].slice(r)),t}function Dt(i,e){Me||(Me=new TextDecoder);let t=[],r=0,n=-1,s=!1;return new TransformStream({transform(o,l){for(t.push(o);;){if(r===0){if(_e(t)<1)break;let u=be(t,1);s=(u[0]&128)===128,n=u[0]&127,n<126?r=3:n===126?r=1:r=2}else if(r===1){if(_e(t)<2)break;let u=be(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),r=3}else if(r===2){if(_e(t)<8)break;let u=be(t,8),f=new DataView(u.buffer,u.byteOffset,u.length),d=f.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(ee);break}n=d*Math.pow(2,32)+f.getUint32(4),r=3}else{if(_e(t)<n)break;let u=be(t,n);l.enqueue(ie(s?u:Me.decode(u),e)),r=0}if(n===0||n>i){l.enqueue(ee);break}}}})}var Ue=4;function T(i){if(i)return oi(i)}function oi(i){for(var e in T.prototype)i[e]=T.prototype[e];return i}T.prototype.on=T.prototype.addEventListener=function(i,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+i]=this._callbacks["$"+i]||[]).push(e),this};T.prototype.once=function(i,e){function t(){this.off(i,t),e.apply(this,arguments)}return t.fn=e,this.on(i,t),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(i,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+i];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+i],this;for(var r,n=0;n<t.length;n++)if(r=t[n],r===e||r.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+i],this};T.prototype.emit=function(i){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+i],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(t){t=t.slice(0);for(var r=0,n=t.length;r<n;++r)t[r].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(i){return this._callbacks=this._callbacks||{},this._callbacks["$"+i]||[]};T.prototype.hasListeners=function(i){return!!this.listeners(i).length};var D=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),b=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Nt="arraybuffer";function Ae(i,...e){return e.reduce((t,r)=>(i.hasOwnProperty(r)&&(t[r]=i[r]),t),{})}var ai=b.setTimeout,ci=b.clearTimeout;function N(i,e){e.useNativeTimers?(i.setTimeoutFn=ai.bind(b),i.clearTimeoutFn=ci.bind(b)):(i.setTimeoutFn=b.setTimeout.bind(b),i.clearTimeoutFn=b.clearTimeout.bind(b))}var li=1.33;function Mt(i){return typeof i=="string"?ui(i):Math.ceil((i.byteLength||i.size)*li)}function ui(i){let e=0,t=0;for(let r=0,n=i.length;r<n;r++)e=i.charCodeAt(r),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(r++,t+=4);return t}function xe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ut(i){let e="";for(let t in i)i.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(i[t]));return e}function Wt(i){let e={},t=i.split("&");for(let r=0,n=t.length;r<n;r++){let s=t[r].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}var we=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},M=class extends T{constructor(e){super(),this.writable=!1,N(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new we(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=ie(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Ut(e);return t.length?"?"+t:""}};var ne=class extends M{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};St(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Rt(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=xe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};var Ot=!1;try{Ot=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Ct=Ot;function hi(){}var We=class extends ne{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},O=class i extends T{constructor(e,t,r){super(),this.createRequest=e,N(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var e;let t=Ae(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&r.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var n;r.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=i.requestsCount++,i.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=hi,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete i.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};O.requestsCount=0;O.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ft);else if(typeof addEventListener=="function"){let i="onpagehide"in b?"pagehide":"unload";addEventListener(i,Ft,!1)}}function Ft(){for(let i in O.requests)O.requests.hasOwnProperty(i)&&O.requests[i].abort()}var fi=(function(){let i=Lt({xdomain:!1});return i&&i.responseType!==null})(),C=class extends We{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=fi&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new O(Lt,this.uri(),e)}};function Lt(i){let e=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ct))return new XMLHttpRequest}catch{}if(!e)try{return new b[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Bt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ce=class extends M{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Bt?{}:Ae(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;te(r,this.supportsBinary,s=>{try{this.doWrite(r,s)}catch{}n&&D(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=xe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Oe=b.WebSocket||b.MozWebSocket,F=class extends Ce{createSocket(e,t,r){return Bt?new Oe(e,t,r):t?new Oe(e,t):new Oe(e)}doWrite(e,t){this.ws.send(t)}};var J=class extends M{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Dt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=vt();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),s())}).catch(l=>{})};s();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],n=t===e.length-1;this._writer.write(r).then(()=>{n&&D(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};var Fe={websocket:F,webtransport:J,polling:C};var di=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,pi=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q(i){if(i.length>8e3)throw"URI too long";let e=i,t=i.indexOf("["),r=i.indexOf("]");t!=-1&&r!=-1&&(i=i.substring(0,t)+i.substring(t,r).replace(/:/g,";")+i.substring(r,i.length));let n=di.exec(i||""),s={},o=14;for(;o--;)s[pi[o]]=n[o]||"";return t!=-1&&r!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=mi(s,s.path),s.queryKey=gi(s,s.query),s}function mi(i,e){let t=/\/{2,9}/g,r=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function gi(i,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,n,s){n&&(t[n]=s)}),t}var Le=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ie=[];Le&&addEventListener("offline",()=>{Ie.forEach(i=>i())},!1);var V=class i extends T{constructor(e,t){if(super(),this.binaryType=Nt,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let r=Q(e);t.hostname=r.host,t.secure=r.protocol==="https"||r.protocol==="wss",t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=Q(t.host).host);N(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(r=>{let n=r.prototype.name;this.transports.push(n),this._transportsByName[n]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Wt(this.opts.query)),Le&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ie.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=Ue,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&i.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",i.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let n=this.writeBuffer[r].data;if(n&&(t+=Mt(n)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,D(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,n){if(typeof t=="function"&&(n=t,t=void 0),typeof r=="function"&&(n=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(i.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Le&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Ie.indexOf(this._offlineEventListener);r!==-1&&Ie.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};V.protocol=Ue;var ke=class extends V{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;V.priorWebsocketSuccess=!1;let n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;V.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){r||(r=!0,d(),t.close(),t=null)}let o=p=>{let _=new Error("probe error: "+p);_.transport=t.name,s(),this.emitReserved("upgradeError",_)};function l(){o("transport closed")}function u(){o("socket closed")}function f(p){t&&p.name!==t.name&&s()}let d=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};t.once("open",n),t.once("error",o),t.once("close",l),this.once("close",u),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},Z=class extends ke{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(n=>Fe[n]).filter(n=>!!n)),super(e,r)}};var eo=Z.protocol;function Gt(i,e="",t){let r=i;t=t||typeof location<"u"&&location,i==null&&(i=t.protocol+"//"+t.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=t.protocol+i:i=t.host+i),/^(https?|wss?):\/\//.test(i)||(typeof t<"u"?i=t.protocol+"//"+i:i="https://"+i),r=Q(i)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";let s=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(t&&t.port===r.port?"":":"+r.port),r}var $e={};tr($e,{Decoder:()=>Ye,Encoder:()=>Ve,PacketType:()=>m,protocol:()=>Xt});var Ti=typeof ArrayBuffer=="function",Ei=i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,Vt=Object.prototype.toString,_i=typeof Blob=="function"||typeof Blob<"u"&&Vt.call(Blob)==="[object BlobConstructor]",bi=typeof File=="function"||typeof File<"u"&&Vt.call(File)==="[object FileConstructor]";function oe(i){return Ti&&(i instanceof ArrayBuffer||Ei(i))||_i&&i instanceof Blob||bi&&i instanceof File}function se(i,e){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let t=0,r=i.length;t<r;t++)if(se(i[t]))return!0;return!1}if(oe(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return se(i.toJSON(),!0);for(let t in i)if(Object.prototype.hasOwnProperty.call(i,t)&&se(i[t]))return!0;return!1}function Yt(i){let e=[],t=i.data,r=i;return r.data=Be(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Be(i,e){if(!i)return i;if(oe(i)){let t={_placeholder:!0,num:e.length};return e.push(i),t}else if(Array.isArray(i)){let t=new Array(i.length);for(let r=0;r<i.length;r++)t[r]=Be(i[r],e);return t}else if(typeof i=="object"&&!(i instanceof Date)){let t={};for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=Be(i[r],e));return t}return i}function qt(i,e){return i.data=Ge(i.data,e),delete i.attachments,i}function Ge(i,e){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<e.length)return e[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let t=0;t<i.length;t++)i[t]=Ge(i[t],e);else if(typeof i=="object")for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(i[t]=Ge(i[t],e));return i}var Ai=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Xt=5,m;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(m||(m={}));var Ve=class{constructor(e){this.replacer=e}encode(e){return(e.type===m.EVENT||e.type===m.ACK)&&se(e)?this.encodeAsBinary({type:e.type===m.EVENT?m.BINARY_EVENT:m.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===m.BINARY_EVENT||e.type===m.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Yt(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}};function $t(i){return Object.prototype.toString.call(i)==="[object Object]"}var Ye=class i extends T{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let r=t.type===m.BINARY_EVENT;r||t.type===m.BINARY_ACK?(t.type=r?m.EVENT:m.ACK,this.reconstructor=new qe(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(oe(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(m[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===m.BINARY_EVENT||r.type===m.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let o=e.substring(s,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");r.attachments=Number(o)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););r.nsp=e.substring(s,t)}else r.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=t+1;for(;++t;){let o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}r.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(i.isPayloadValid(r.type,s))r.data=s;else throw new Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case m.CONNECT:return $t(t);case m.DISCONNECT:return t===void 0;case m.CONNECT_ERROR:return typeof t=="string"||$t(t);case m.EVENT:case m.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Ai.indexOf(t[0])===-1);case m.ACK:case m.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},qe=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=qt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function w(i,e,t){return i.on(e,t),function(){i.off(e,t)}}var xi=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),K=class extends T{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[w(e,"open",this.onopen.bind(this)),w(e,"packet",this.onpacket.bind(this)),w(e,"error",this.onerror.bind(this)),w(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,n,s;if(xi.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:m.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let d=this.ids++,p=t.pop();this._registerAckCallback(d,p),o.id=d}let l=(n=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!l||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var r;let n=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);t.call(this,new Error("operation has timed out"))},n),o=(...l)=>{this.io.clearTimeoutFn(s),t.apply(this,l)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,n)=>{let s=(o,l)=>o?n(o):r(l);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((n,...s)=>r!==this._queue[0]?void 0:(n!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(n)):(this._queue.shift(),t&&t(null,...s)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:m.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(r=>String(r.id)===e)){let r=this.acks[e];delete this.acks[e],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case m.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case m.EVENT:case m.BINARY_EVENT:this.onevent(e);break;case m.ACK:case m.BINARY_ACK:this.onack(e);break;case m.DISCONNECT:this.ondisconnect();break;case m.CONNECT_ERROR:this.destroy();let r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...n){r||(r=!0,t.packet({type:m.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:m.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function Y(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}Y.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*i);i=(Math.floor(e*10)&1)==0?i-t:i+t}return Math.min(i,this.max)|0};Y.prototype.reset=function(){this.attempts=0};Y.prototype.setMin=function(i){this.ms=i};Y.prototype.setMax=function(i){this.max=i};Y.prototype.setJitter=function(i){this.jitter=i};var j=class extends T{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,N(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Y({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||$e;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Z(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let n=w(t,"open",function(){r.onopen(),e&&e()}),s=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),e?e(l):this.maybeReconnectOnOpen()},o=w(t,"error",s);if(this._timeout!==!1){let l=this._timeout,u=this.setTimeoutFn(()=>{n(),s(new Error("timeout")),t.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(w(e,"ping",this.onping.bind(this)),w(e,"data",this.ondata.bind(this)),w(e,"error",this.onerror.bind(this)),w(e,"close",this.onclose.bind(this)),w(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){D(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new K(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var ae={};function ce(i,e){typeof i=="object"&&(e=i,i=void 0),e=e||{};let t=Gt(i,e.path||"/socket.io"),r=t.source,n=t.id,s=t.path,o=ae[n]&&s in ae[n].nsps,l=e.forceNew||e["force new connection"]||e.multiplex===!1||o,u;return l?u=new j(r,e):(ae[n]||(ae[n]=new j(r,e)),u=ae[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ce,{Manager:j,Socket:K,io:ce,connect:ce});import Ji from"axios";import{DEFAULT_ORDER_EXPIRATION_DAYS as Qi,ORDER_MSG_VERSION as Zi}from"@ultrade/shared/browser/constants";import{getRandomInt as Qe}from"@ultrade/shared/browser/common";import{getCancelOrderDataJsonBytes as Ki,makeLoginMsg as ji,makeTradingKeyMsg as jt,makeCreateOrderMsg as Hi}from"@ultrade/shared/browser/helpers/codex.helper";import{makeWithdrawMsg as en}from"@ultrade/shared/browser/helpers/withdraw.helper";import{TradingKeyType as tn}from"@ultrade/shared/browser/interfaces";import{PROVIDERS as q}from"@ultrade/shared/browser/interfaces";import{OrderStatus as fe}from"@ultrade/shared/browser/enums";import{makeDtwMsg as rn,makeTransferMsg as nn}from"@ultrade/shared/browser/helpers/codex";var le=class{constructor(e,t,r,n){this.onDisconnect=r;this.onConnectError=n;this.socket=null;this.socketPool={};this.websocketUrl=e,this.socketIOFactory=t,this.initializeSocket()}initializeSocket(){this.socket===null&&(this.socket=this.socketIOFactory(this.websocketUrl,{reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:9999,transports:["websocket"]}),this.onDisconnect&&this.socket.on("disconnect",()=>{this.onDisconnect(this.socket.id)}),this.onConnectError&&this.socket.on("connect_error",e=>{this.onConnectError(e)}))}getSocket(){return this.socket}subscribe(e,t){let r=Date.now();return this.socket===null&&this.initializeSocket(),this.socket.onAny((n,...s)=>{t(n,s)}),this.socket.io.on("reconnect",()=>{this.socket.emit("subscribe",e)}),this.socket.emit("subscribe",e),this.socketPool[r]=e,r}unsubscribe(e){let t=this.socketPool[e];t&&this.socket&&(this.socket.emit("unsubscribe",t),delete this.socketPool[e]),Object.keys(this.socketPool).length===0&&this.socket&&this.disconnect()}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null)}isConnected(){return this.socket!==null&&this.socket.connected}on(e,t){this.socket&&this.socket.on(e,t)}off(e,t){this.socket&&(t?this.socket.off(e,t):this.socket.off(e))}emit(e,...t){this.socket&&this.socket.emit(e,...t)}emitCurrentPair(e){this.emit("currentPair",e)}emitOrderFilter(e){this.emit("orderFilter",e)}onReconnect(e){return this.socket?(this.socket.io.off("reconnect"),this.socket.io.on("reconnect",e),()=>{this.socket&&this.socket.io.off("reconnect",e)}):()=>{}}offReconnect(e){this.socket&&(e?this.socket.io.off("reconnect",e):this.socket.io.off("reconnect"))}};import wi from"react-secure-storage";var Ii=new URL(window.location!==window.parent.location?document.referrer:document.location.href).host,zt=i=>`${i}_${Ii}`,ki=new Proxy(wi,{get(i,e,t){return typeof e=="string"&&typeof i[e]=="function"?function(...r){return typeof e=="string"&&["setItem","getItem","removeItem"].includes(e)&&(r[0]=zt(r[0])),i[e].apply(i,r)}:Reflect.get(i,e,t)}}),Xe=new Proxy(localStorage,{get(i,e,t){return typeof e=="string"&&typeof i[e]=="function"?function(...r){return typeof e=="string"&&["setItem","getItem","removeItem","key"].includes(e)&&(r[0]=zt(r[0])),i[e].apply(i,r)}:Reflect.get(i,e,t)}}),Pe=class{constructor(){this.keys={mainWallet:"main-wallet",tradingKey:"trading-key"};this.isBrowser=typeof window<"u",this.isBrowser||(this.clearMainWallet=()=>{},this.getMainWallet=()=>null,this.setMainWallet=()=>{})}setMainWallet(e){Xe.setItem(this.keys.mainWallet,JSON.stringify(e))}getMainWallet(){let e=Xe.getItem(this.keys.mainWallet);if(!e)return null;let t=JSON.parse(e),r=ki.getItem(`${this.keys.tradingKey}-${t.address}`);return r&&(r.expiredAt===0||Number(new Date(r.expiredAt))-Date.now()>1)&&(t.tradingKey=r.address),t}clearMainWallet(){Xe.removeItem(this.keys.mainWallet)}};var Pi=(t=>(t.YES="Y",t.NO="N",t))(Pi||{}),Ri=(f=>(f.MFT_AUDIO_LINK="mft.audioLink",f.MFT_TITLE="mft.title",f.VIEW_BASE_COIN_ICON_LINK="view.baseCoinIconLink",f.VIEW_BASE_COIN_MARKET_LINK="view.baseCoinMarketLink",f.VIEW_PRICE_COIN_ICON_LINK="view.priceCoinIconLink",f.VIEW_PRICE_COIN_MARKET_LINK="view.priceCoinMarketLink",f.MAKER_FEE="makerFee",f.TAKER_FEE="takerFee",f.MODE_PRE_SALE="mode.preSale",f))(Ri||{});var Si=(n=>(n[n.OPEN_ORDER=1]="OPEN_ORDER",n[n.CANCELLED=2]="CANCELLED",n[n.MATCHED=3]="MATCHED",n[n.SELF_MATCHED=4]="SELF_MATCHED",n))(Si||{}),vi=(s=>(s[s.Open=1]="Open",s[s.Canceled=2]="Canceled",s[s.Completed=3]="Completed",s[s.SelfMatch=4]="SelfMatch",s[s.Expired=5]="Expired",s))(vi||{}),Di=(n=>(n[n.Limit=0]="Limit",n[n.IOC=1]="IOC",n[n.POST=2]="POST",n[n.Market=3]="Market",n))(Di||{}),Ni=(r=>(r[r.created=1]="created",r[r.partially_filled=2]="partially_filled",r[r.removed=3]="removed",r))(Ni||{}),Mi=(a=>(a.ALGORAND="Algorand",a.SOLANA="Solana",a["5IRECHAIN_THUNDER_TESTNET"]="5ireChain Thunder Testnet",a.ACALA="Acala",a.ALFAJORES="Alfajores",a.APOTHEM_NETWORK="Apothem Network",a.ARBITRUM_GOERLI="Arbitrum Goerli",a.ARBITRUM_NOVA="Arbitrum Nova",a.ARBITRUM_ONE="Arbitrum",a.ARBITRUM_SEPOLIA="Arbitrum Sepolia",a.ASTAR="Astar",a.ASTAR_ZKEVM_TESTNET_ZKATANA="Astar zkEVM Testnet zKatana",a.AURORA="Aurora",a.AURORA_TESTNET="Aurora Testnet",a.AVALANCHE="Avalanche",a.AVALANCHE_FUJI="Avalanche Fuji",a.BAHAMUT="Bahamut",a.BASE="Base",a.BASE_GOERLI="Base Goerli",a.BASE_SEPOLIA="Base Sepolia",a.BEAR_NETWORK_CHAIN_MAINNET="Bear Network Chain Mainnet",a.BEAR_NETWORK_CHAIN_TESTNET="Bear Network Chain Testnet",a.BERACHAIN_ARTIO="Berachain Artio",a.BERESHEET_BEREEVM_TESTNET="Beresheet BereEVM Testnet",a.BINANCE_SMART_CHAIN_TESTNET="BNB Chain Testnet",a.BITTORRENT="BitTorrent",a.BITTORRENT_CHAIN_TESTNET="BitTorrent Chain Testnet",a.BLACKFORT_EXCHANGE_NETWORK="BlackFort Exchange Network",a.BLACKFORT_EXCHANGE_NETWORK_TESTNET="BlackFort Exchange Network Testnet",a.BLAST_SEPOLIA="Blast Sepolia",a.BNB_SMART_CHAIN="BNB Chain",a.BOBA_NETWORK="Boba Network",a.BRONOS="Bronos",a.BRONOS_TESTNET="Bronos Testnet",a.CANTO="Canto",a.CELO="Celo",a.CHILIZ_CHAIN="Chiliz Chain",a.CHILIZ_SPICY_TESTNET="Chiliz Spicy Testnet",a.CONFLUX_ESPACE="Conflux eSpace",a.CONFLUX_ESPACE_TESTNET="Conflux eSpace Testnet",a.CORE_DAO="Core Dao",a.COSTON="Coston",a.COSTON2="Coston2",a.CRONOS_MAINNET="Cronos Mainnet",a.CRONOS_TESTNET="Cronos Testnet",a.CROSSBELL="Crossbell",a.DEFICHAIN_EVM_MAINNET="DeFiChain EVM Mainnet",a.DEFICHAIN_EVM_TESTNET="DeFiChain EVM Testnet",a.DFK_CHAIN="DFK Chain",a.DOGECHAIN="Dogechain",a.EDGEWARE_EDGEEVM_MAINNET="Edgeware EdgeEVM Mainnet",a.EKTA="Ekta",a.EKTA_TESTNET="Ekta Testnet",a.EOS_EVM="EOS EVM",a.EOS_EVM_TESTNET="EOS EVM Testnet",a.ETHEREUM="Ethereum",a.ETHEREUM_CLASSIC="Ethereum Classic",a.EVMOS="Evmos",a.EVMOS_TESTNET="Evmos Testnet",a.FANTOM="Fantom",a.FANTOM_SONIC_OPEN_TESTNET="Fantom Sonic Open Testnet",a.FANTOM_TESTNET="Fantom Testnet",a.FIBO_CHAIN="Fibo Chain",a.FILECOIN_CALIBRATION="Filecoin Calibration",a.FILECOIN_HYPERSPACE="Filecoin Hyperspace",a.FILECOIN_MAINNET="Filecoin Mainnet",a.FLARE_MAINNET="Flare Mainnet",a.FOUNDRY="Foundry",a.FUSE="Fuse",a.FUSE_SPARKNET="Fuse Sparknet",a.GNOSIS="Gnosis",a.GNOSIS_CHIADO="Gnosis Chiado",a.GOERLI="Goerli",a.HAQQ_MAINNET="HAQQ Mainnet",a.HAQQ_TESTEDGE_2="HAQQ Testedge 2",a.HARDHAT="Hardhat",a.HARMONY_ONE="Harmony One",a.HEDERA_MAINNET="Hedera Mainnet",a.HEDERA_PREVIEWNET="Hedera Previewnet",a.HEDERA_TESTNET="Hedera Testnet",a.HOLESKY="Holesky",a.HORIZEN_GOBI_TESTNET="Horizen Gobi Testnet",a.IOTEX="IoTeX",a.IOTEX_TESTNET="IoTeX Testnet",a.JIBCHAIN_L1="JIBCHAIN L1",a.KARURA="Karura",a.KAVA_EVM="Kava EVM",a.KAVA_EVM_TESTNET="Kava EVM Testnet",a.KCC_MAINNET="KCC Mainnet",a.KLAYTN="Klaytn",a.KLAYTN_BAOBAB_TESTNET="Klaytn Baobab Testnet",a.KROMA="Kroma",a.KROMA_SEPOLIA="Kroma Sepolia",a.LIGHTLINK_PEGASUS_TESTNET="LightLink Pegasus Testnet",a.LIGHTLINK_PHOENIX="LightLink Phoenix",a.LINEA_GOERLI_TESTNET="Linea Goerli Testnet",a.LINEA_MAINNET="Linea Mainnet",a.LOCALHOST="Localhost",a.LUKSO="LUKSO",a.MANDALA_TC9="Mandala TC9",a.MANTA_PACIFIC_MAINNET="Manta Pacific Mainnet",a.MANTA_PACIFIC_TESTNET="Manta Pacific Testnet",a.MANTLE="Mantle",a.MANTLE_TESTNET="Mantle Testnet",a.METACHAIN_MAINNET="MetaChain Mainnet",a.METER="Meter",a.METER_TESTNET="Meter Testnet",a.METIS="Metis",a.METIS_GOERLI="Metis Goerli",a.MEVERSE_CHAIN_MAINNET="MEVerse Chain Mainnet",a.MEVERSE_CHAIN_TESTNET="MEVerse Chain Testnet",a.MODE_TESTNET="Mode Testnet",a.MOONBASE_ALPHA="Moonbase Alpha",a.MOONBEAM="Moonbeam",a.MOONBEAM_DEVELOPMENT_NODE="Moonbeam Development Node",a.MOONRIVER="Moonriver",a.NEON_EVM_DEVNET="Neon EVM DevNet",a.NEON_EVM_MAINNET="Neon EVM MainNet",a.NEXI="Nexi",a.NEXILIX_SMART_CHAIN="Nexilix Smart Chain",a.OASIS_SAPPHIRE="Oasis Sapphire",a.OASIS_SAPPHIRE_TESTNET="Oasis Sapphire Testnet",a.OASIS_TESTNET="Oasis Testnet",a.OASYS="Oasys",a.OKC="OKC",a.OORT_MAINNETDEV="OORT MainnetDev",a.OPBNB="opBNB",a.OPBNB_TESTNET="opBNB Testnet",a.OPTIMISM_GOERLI="Optimism Goerli",a.OP_MAINNET="Optimism",a.OP_SEPOLIA="Optimism Sepolia",a.PALM="Palm",a.PALM_TESTNET="Palm Testnet",a.PGN="PGN",a.PGN_="PGN ",a.PLINGA="Plinga",a.POLYGON="Polygon",a.POLYGON_AMOY="Polygon Amoy",a.POLYGON_MUMBAI="Polygon Mumbai",a.POLYGON_ZKEVM="Polygon zkEVM",a.POLYGON_ZKEVM_TESTNET="Polygon zkEVM Testnet",a.PULSECHAIN="PulseChain",a.PULSECHAIN_V4="PulseChain V4",a.Q_MAINNET="Q Mainnet",a.Q_TESTNET="Q Testnet",a.ROLLUX_MAINNET="Rollux Mainnet",a.ROLLUX_TESTNET="Rollux Testnet",a.RONIN="Ronin",a.ROOTSTOCK_MAINNET="Rootstock Mainnet",a.SAIGON_TESTNET="Saigon Testnet",a.SCROLL="Scroll",a.SCROLL_SEPOLIA="Scroll Sepolia",a.SCROLL_TESTNET="Scroll Testnet",a.SEPOLIA="Ethereum Sepolia",a.SHARDEUM_SPHINX="Shardeum Sphinx",a.SHIBARIUM="Shibarium",a.SHIMMER="Shimmer",a.SHIMMER_TESTNET="Shimmer Testnet",a["SKALE_|_BLOCK_BRAWLERS"]="SKALE | Block Brawlers",a["SKALE_|_CALYPSO_NFT_HUB"]="SKALE | Calypso NFT Hub",a["SKALE_|_CALYPSO_NFT_HUB_TESTNET"]="SKALE | Calypso NFT Hub Testnet",a["SKALE_|_CHAOS_TESTNET"]="SKALE | Chaos Testnet",a["SKALE_|_CRYPTOBLADES"]="SKALE | CryptoBlades",a["SKALE_|_CRYPTO_COLOSSEUM"]="SKALE | Crypto Colosseum",a["SKALE_|_EUROPA_LIQUIDITY_HUB"]="SKALE | Europa Liquidity Hub",a["SKALE_|_EUROPA_LIQUIDITY_HUB_TESTNET"]="SKALE | Europa Liquidity Hub Testnet",a["SKALE_|_EXORDE"]="SKALE | Exorde",a["SKALE_|_HUMAN_PROTOCOL"]="SKALE | Human Protocol",a["SKALE_|_NEBULA_GAMING_HUB"]="SKALE | Nebula Gaming Hub",a["SKALE_|_NEBULA_GAMING_HUB_TESTNET"]="SKALE | Nebula Gaming Hub Testnet",a["SKALE_|_RAZOR_NETWORK"]="SKALE | Razor Network",a["SKALE_|_TITAN_COMMUNITY_HUB"]="SKALE | Titan Community Hub",a["SKALE_|_TITAN_COMMUNITY_HUB_TESTNET"]="SKALE | Titan Community Hub Testnet",a.SONGBIRD_MAINNET="Songbird Mainnet",a.SYSCOIN_MAINNET="Syscoin Mainnet",a.SYSCOIN_TANENBAUM_TESTNET="Syscoin Tanenbaum Testnet",a["TAIKO_(ALPHA-3_TESTNET)"]="Taiko (Alpha-3 Testnet)",a["TAIKO_JOLNIR_(ALPHA-5_TESTNET)"]="Taiko Jolnir (Alpha-5 Testnet)",a["TAIKO_KATLA_(ALPHA-6_TESTNET)"]="Taiko Katla (Alpha-6 Testnet)",a.TARAXA_MAINNET="Taraxa Mainnet",a.TARAXA_TESTNET="Taraxa Testnet",a.TELOS="Telos",a.TENET="Tenet",a.VECHAIN="Vechain",a.WANCHAIN="Wanchain",a.WANCHAIN_TESTNET="Wanchain Testnet",a.WEMIX="WEMIX",a.WEMIX_TESTNET="WEMIX Testnet",a.X1_TESTNET="X1 Testnet",a.XINFIN_NETWORK="XinFin Network",a.ZETACHAIN_ATHENS_TESTNET="ZetaChain Athens Testnet",a.ZHEJIANG="Zhejiang",a.ZILLIQA="Zilliqa",a.ZILLIQA_TESTNET="Zilliqa Testnet",a.ZKFAIR_MAINNET="ZKFair Mainnet",a.ZKFAIR_TESTNET="ZKFair Testnet",a.ZKSYNC_ERA="zkSync Era",a.ZKSYNC_ERA_TESTNET="zkSync Era Testnet",a.ZKSYNC_SEPOLIA_TESTNET="zkSync Sepolia Testnet",a.ZORA="Zora",a.ZORA_GOERLI_TESTNET="Zora Goerli Testnet",a.ZORA_SEPOLIA="Zora Sepolia",a))(Mi||{}),Ui=(d=>(d.Pending="pending",d.Completed="completed",d.Failed="failed",d.Received="received",d.Success="success",d.Failure="failure",d.Dropped="dropped",d.Replaced="replaced",d.Stuck="stuck",d.Confirmed="confirmed",d))(Ui||{}),Wi=(s=>(s.USER_TO_TMC="user_to_tmc",s.TMC_TO_USER="tmc_to_user",s.RELAYER_TO_TMC="relayer_to_tmc",s.RELAYER_TO_CODEX="relayer_to_codex",s.RELAYER_TO_CIRCLE="relayer_to_circle",s))(Wi||{}),Oi=(r=>(r.D="deposit",r.W="withdraw",r.T="transfer",r))(Oi||{});var Ci=(n=>(n.COMPANY="COMPANY",n.TWITTER="TWITTER",n.DISCORD="DISCORD",n.TELEGRAM="TELEGRAM",n))(Ci||{});var Fi=(y=>(y[y.QUOTE=1]="QUOTE",y[y.LAST_PRICE=2]="LAST_PRICE",y[y.DEPTH=3]="DEPTH",y[y.LAST_CANDLESTICK=4]="LAST_CANDLESTICK",y[y.ORDERS=5]="ORDERS",y[y.TRADES=6]="TRADES",y[y.SYSTEM=7]="SYSTEM",y[y.WALLET_TRANSACTIONS=8]="WALLET_TRANSACTIONS",y[y.ALL_STAT=9]="ALL_STAT",y[y.CODEX_ASSETS=12]="CODEX_ASSETS",y[y.CODEX_BALANCES=10]="CODEX_BALANCES",y[y.LAST_LOOK=11]="LAST_LOOK",y[y.SETTINGS_UPDATE=13]="SETTINGS_UPDATE",y[y.NEW_NOTIFICATION=14]="NEW_NOTIFICATION",y[y.POINT_SYSTEM_SETTINGS_UPDATE=15]="POINT_SYSTEM_SETTINGS_UPDATE",y))(Fi||{}),ze=[5,8,10,11];var Li=(r=>(r.OFF="disable",r.ULTRADE="ultrade",r.ALL="all",r))(Li||{}),Bi=(g=>(g.ENABLED="company.enabled",g.APP_TITLE="company.appTitle",g.DOMAIN="company.domain",g.DIRECT_SETTLE="company.directSettlement",g.KYC="markets.kycTradeRequirementEnabled",g.GEOBLOCK="company.geoblock",g.LOGO="appearance.logo",g.THEMES="appearance.themes",g.NEW_TAB="appearance.newTab",g.TARGET="appearance.target",g.REPORT_BUTTONS="appearance.reportButtons",g.CUSTOM_MENU_ITEMS="appearance.customMenuItems",g.APPEARANCE_CHART_TYPE="appearance.chartType",g.APPEARANCE_CHART_INT="appearance.chartInt",g.AMM="product.amm",g.OBDEX="product.obdex",g.POINTS="product.pointSystem",g.AFFILIATE_DASHBOARD_THRESHOLD="product.affiliateDashboardThreshold",g.AFFILIATE_DEFAULT_FEE_SHARE="product.affiliateDefaultFeeShare",g.AFFILIATE_DASHBOARD_VISIBILITY="product.affiliateDashboardVisibility",g.AMM_FEE="company.ammFee",g.FEE_SHARE="company.feeShare",g.MIN_FEE="company.minFee",g.MAKER_FEE="company.makerFee",g.TAKER_FEE="company.takerFee",g.PINNED_PAIRS="markets.pinnedPairs",g.TWITTER_ENABLED="point-system.twitterEnabled",g.TWITTER_JOB_ENABLED="point-system.twitterJobEnabled",g.TWITTER_HASHTAGS="point-system.twitterHashtags",g.TWITTER_ACCOUNT_NAME="point-system.twitterAccountName",g.DISCORD_ENABLED="point-system.discordEnabled",g.TELEGRAM_ENABLED="point-system.telegramEnabled",g.TELEGRAM_GROUP_NAME="point-system.telegramGroupName",g.TELEGRAM_BOT_NAME="point-system.telegramBotName",g.GUIDE_LINK="point-system.guideLink",g))(Bi||{});var Gi=(r=>(r.DISABLED="disabled",r.ENABLED_FOR_ALL="enabled for all",r.ENABLED_FOR_AFFILIATES="enabled for affiliates",r))(Gi||{});import{decodeStateArray as Vi,getTxnParams as Yi}from"@ultrade/shared/browser/helpers/algo.helper";import ue from"algosdk";import qi from"axios";var he=class{constructor(e,t,r){this.client=e,this.authCredentials=t,this.indexerDomain=r}isAppOptedIn(e,t){return!!e?.find(r=>r.id===t)}isAssetOptedIn(e,t){return Object.keys(e).includes(t.toString())}async optInAsset(e,t){let r=await this.getTxnParams();return ue.makeAssetTransferTxnWithSuggestedParamsFromObject({suggestedParams:{...r},from:e,to:e,assetIndex:t,amount:0})}async makeAppCallTransaction(e,t,r,n,s){let o=[],l=[],u=[e];return ue.makeApplicationNoOpTxn(t,s||await this.getTxnParams(),r,n,o,l,u)}makeTransferTransaction(e,t,r,n,s){if(r<=0)return null;let o={suggestedParams:{...e},from:n,to:s,amount:r};return t===0?ue.makePaymentTxnWithSuggestedParamsFromObject(o):(o.assetIndex=t,ue.makeAssetTransferTxnWithSuggestedParamsFromObject(o))}get signer(){return this.authCredentials.signer}set signer(e){this.authCredentials.signer=e}async signAndSend(e){Array.isArray(e)||(e=[e]);let t=this.getCurrentAccount();if(t){let r=e.map(n=>n.signTxn(t.sk));return this.client.sendRawTransaction(r).do()}return this.authCredentials.signer.signAndSend(e)}async signAndSendData(e,t,r,n){let s=typeof e=="string"?e:JSON.stringify(e),o=typeof e=="string"?{message:s}:{...e},l=await t(s,n);return r({...o,signature:l})}async getTxnParams(){return await Yi(this.client)}getCurrentAccount(){return this.authCredentials.mnemonic?ue.mnemonicToSecretKey(this.authCredentials.mnemonic):null}async getAccountInfo(e){return this.client.accountInformation(e).do()}constructArgsForAppCall(...e){let t=[];return e.forEach(r=>{t.push(new Uint8Array(r.toBuffer?r.toBuffer():c.from(r.toString())))}),t}validateCredentials(){if(!this.authCredentials.mnemonic&&!this.authCredentials.signer)throw"You need specify mnemonic or signer to execute the method"}async getAppState(e){try{let t=await this.client.getApplicationByID(e).do();return Vi(t.params["global-state"])}catch(t){console.log(`Attempt to load app by id ${e}`),console.log(t.message)}}async getSuperAppId(e){return(await this.getAppState(e))?.UL_SUPERADMIN_APP||0}async getPairBalances(e,t){let{data:r}=await qi.get(`${this.indexerDomain}/v2/accounts/${t}?include-all=true`);if(r.account.hasOwnProperty("apps-local-state")){let n=r.account["apps-local-state"].find(l=>l.id===e&&l.deleted===!1);if(!n)return null;let s=n["key-value"].find(l=>l.key==="YWNjb3VudEluZm8="),o=c.from(s.value.bytes,"base64");return Jt(o)}}async calculateTransferAmount(e,t,r,n,s,o){let l=await this.getPairBalances(e,t),u=(r==="B"?l?.priceCoin_available:l?.baseCoin_available)??0;r==="B"&&(n=n/10**o*s);let f=Math.ceil(n-u);return f<0?0:f}};import Qt,{encodeAddress as $i}from"algosdk";var Xi={priceCoin_locked:{type:"uint"},priceCoin_available:{type:"uint"},baseCoin_locked:{type:"uint"},baseCoin_available:{type:"uint"},companyId:{type:"uint"},WLFeeShare:{type:"uint"},WLCustomFee:{type:"uint"},slotMap:{type:"uint"}},Jt=i=>{let e=new Map,t=0;for(let[r,n]of Object.entries(Xi)){if(t>=i.length)throw new Error("Array index out of bounds");let s;switch(n.type){case"address":s=$i(i.slice(t,t+32)),t+=32;break;case"bytes":s=i.slice(t,t+n.size),s=Qt.decodeUint64(s,"mixed"),t+=n.size;break;case"uint":s=Qt.decodeUint64(i.slice(t,t+8),"mixed"),t+=8;break;case"string":s=zi(i.slice(t,t+n.size)),t+=n.size;break}e.set(r,s)}return Object.fromEntries(e)},zi=i=>c.from(i).toString("utf-8");var Zt="By signing this message you are logging into your trading account and agreeing to all terms and conditions of the platform.";var Kt={mainnet:{algodNode:"https://mainnet-api.algonode.cloud",apiUrl:"https://mainnet-api.algonode.cloud",algodIndexer:"https://mainnet-idx.algonode.cloud"},testnet:{algodNode:"https://testnet-api.algonode.cloud",apiUrl:"https://testnet-apigw.ultradedev.net",algodIndexer:"https://testnet-idx.algonode.cloud"},local:{algodNode:"http://localhost:4001",apiUrl:"http://localhost:5001",algodIndexer:"http://localhost:8980"}},Je=["/market/balances","/market/order","/market/orders","/market/account/kyc/status","/market/account/kyc/init","/market/withdrawal-fee","/market/operation-details","/wallet/key","/wallet/transactions","/wallet/transfer","/wallet/withdraw","/wallet/whitelist","/wallet/withdrawal-wallets"];var Ht=class{constructor(e,t){this.axiosInterceptor=e=>{let t=l=>l.withWalletCredentials||(l.url?Je.some(u=>l.url.includes(u)):!1),r=l=>{let u=["/market/order"];return l.withWalletCredentials||(l.url?u.some(f=>l.url.includes(f)):!1)},n=l=>{let u=["/wallet/signin","/market/account/kyc/init","/notifications"];return l.url?u.some(f=>l.url.includes(f)):!1},s=l=>{let u=["/social/"];return l.url?u.some(f=>l.url.includes(f)):!1},o=l=>l.url?Je.some(u=>l.url.includes(u)):!1;return e.interceptors.request.use(l=>{if(this.wallet&&t(l)&&(l.headers["X-Wallet-Address"]=this.wallet.address,l.headers["X-Wallet-Token"]=this.wallet.token),this.wallet&&o(l)&&(l.headers.CompanyId=this.companyId),this.wallet&&r(l)){let u=this.wallet?.tradingKey;u&&(l.headers["X-Trading-Key"]=u)}return n(l)&&(l.headers.CompanyId=this.companyId),s(l)&&!l.headers.CompanyId&&(l.headers.CompanyId=this.isUltradeID?1:this.companyId),l},l=>Promise.reject(l)),e.interceptors.response.use(l=>l.data,async l=>(console.log("Request was failed",l),[401].includes(l?.response?.status)&&l.config&&t(l.config)&&(this.wallet=null,this.localStorageService.clearMainWallet()),Promise.reject(l))),e};let r=Kt[e.network];this.algodNode=r.algodNode,this.apiUrl=r.apiUrl,this.algodIndexer=r.algodIndexer,e.apiUrl!==void 0&&(this.apiUrl=e.apiUrl),e.companyId!==void 0&&(this.companyId=e.companyId),this.websocketUrl=e.websocketUrl,this.client=new he(e.algoSdkClient,t||{},this.algodIndexer),this._axios=this.axiosInterceptor(Ji.create({baseURL:this.apiUrl})),this.localStorageService=new Pe,this.wallet=this.localStorageService.getMainWallet(),this.isUltradeID=!1,this.socketManager=new le(this.websocketUrl,ce,n=>{console.log(`Socket ${n} disconnected at`,new Date)},n=>{console.log(`Socket connect_error due to ${n}`)}),console.log("SDK Wallet",this.wallet)}get useUltradeID(){return this.isUltradeID}set useUltradeID(e){this.isUltradeID=e}get isLogged(){return!!this.wallet?.token}get mainWallet(){return this.wallet}set mainWallet(e){this.wallet=e,e?this.localStorageService.setMainWallet(e):this.localStorageService.clearMainWallet()}setSigner(e){this.client.signer=e}subscribe(e,t){let r=e.streams.some(n=>ze.includes(n));return r&&!this.mainWallet?.token&&!this.mainWallet?.tradingKey?(e.streams=e.streams.filter(n=>!ze.includes(n)),this.socketManager.subscribe(e,t)):r?(e.options={...e.options,token:this.mainWallet?.token,tradingKey:this.mainWallet?.tradingKey},this.socketManager.subscribe(e,t)):this.socketManager.subscribe(e,t)}unsubscribe(e){this.socketManager.unsubscribe(e)}getPairList(e){let t=e?`&companyId=${e}`:"";return this._axios.get(`/market/markets?includeAllOrders=false${t}`)}getPair(e){return this._axios.get(`/market/market?symbol=${e}`)}getPrice(e){return this._axios.get(`/market/price?symbol=${e}`)}getDepth(e,t){return this._axios.get(`/market/depth?symbol=${e}&depth=${t}`)}getSymbols(e){return this._axios.get(`/market/symbols${e?"?mask="+e:""}`)}getLastTrades(e){return this._axios.get(`/market/last-trades?symbol=${e}`)}getHistory(e,t,r,n,s=500,o=1){return this._axios.get(`/market/history?symbol=${e}&interval=${t}&startTime=${r??""}&endTime=${n??""}&limit=${s}&page=${o}`)}getOrders(e,t,r=50,n,s){let o=t?t===1?fe.Open:[fe.Canceled,fe.Matched,fe.SelfMatched,fe.Expired].join(","):"",l=e?`&symbol=${e}`:"",u=o?`&status=${o}`:"",f=s?`&startTime=${s}`:"",d=n?`&endTime=${n}`:"";return this._axios.get(`/market/orders?limit=${r}${l}${u}${f}${d}`)}getOrderById(e){return this._axios.get(`/market/order/${e}`)}getSettings(){let e=new URL(window.location!==window.parent.location?document.referrer:document.location.href).host;return this._axios.get("/market/settings",{headers:{"wl-domain":e}})}getBalances(){return this._axios.get("/market/balances")}getChains(){return this._axios.get("/market/chains")}getCodexAssets(){return this._axios.get("/market/assets")}getCCTPAssets(){return this._axios.get("/market/cctp-assets")}getCCTPUnifiedAssets(){return this._axios.get("/market/cctp-unified-assets")}getWithdrawalFee(e,t){return this._axios.get(`/market/withdrawal-fee?assetAddress=${e}&chainId=${t}`)}getKycStatus(){return this._axios.get("/market/account/kyc/status")}getKycInitLink(e){return this._axios.post("/market/account/kyc/init",{embeddedAppUrl:e})}getDollarValues(e=[]){return this._axios.get(`/market/dollar-price?assetIds=${JSON.stringify(e)}`)}getTransactionDetalis(e){return this._axios.get(`/market/operation-details?operationId=${e}`)}getWalletTransactions(e,t,r=100){return this._axios.get(`/wallet/transactions?type=${e}&limit=${r}&page=${t}`,{withWalletCredentials:!0})}getTradingKeys(){return this._axios.get("/wallet/keys",{withWalletCredentials:!0})}getTransfers(e,t=100){return this._axios.get(`/wallet/transfers?limit=${t}&page=${e}`,{withWalletCredentials:!0})}getPendingTransactions(){return this._axios.get("/wallet/transactions/pending",{withWalletCredentials:!0})}getWhitelist(){return this._axios.get("/wallet/whitelist",{withWalletCredentials:!0})}async addWhitelist(e){e={...e,expiredDate:e.expiredDate&&Math.round(e.expiredDate/1e3)};let r=c.from(rn(e)).toString("hex");return await this.client.signAndSendData(r,this.client.signer.signMessage,({signature:n})=>this._axios.post("/wallet/whitelist",{message:r,signature:n}),"hex")}deleteWhitelist(e){let t={whitelistId:e};return this.client.signAndSendData(t,this.client.signer.signMessage,({signature:r})=>this._axios.delete("/wallet/whitelist",{data:{data:t,signature:r}}))}getAllWithdrawalWallets(){return this._axios.get("/wallet/withdrawal-wallets")}getWithdrawalWalletByAddress(e){return this._axios.get(`/wallet/withdrawal-wallets/${e}`)}createWithdrawalWallet(e){return this._axios.post("/wallet/withdrawal-wallets",e)}updateWithdrawalWallet(e){return this._axios.patch("/wallet/withdrawal-wallets",e)}deleteWithdrawalWallet(e){return this._axios.delete(`/wallet/withdrawal-wallets/${e}`)}getVersion(){return this._axios.get("/system/version")}getMaintenance(){return this._axios.get("/system/maintenance")}getNotifications(){return this._axios.get("/notifications",{withWalletCredentials:!0})}getNotificationsUnreadCount(){return this._axios.get("/notifications/count",{withWalletCredentials:!0})}readNotifications(e){return this._axios.put("/notifications",{notifications:e},{withWalletCredentials:!0})}getAffiliatesStatus(e){return this._axios.get(`/affiliates/${e}/dashboardStatus`,{withWalletCredentials:!0})}createAffiliate(e){return this._axios.post(`/affiliates/${e}`,{},{withWalletCredentials:!0})}getAffiliateProgress(e){return this._axios.get(`/affiliates/${e}/tradingVolumeProgress`,{withWalletCredentials:!0})}getAffiliateInfo(e,t){return this._axios.get(`/affiliates/${e}/dashboard?range=${t}`,{withWalletCredentials:!0})}async countAffiliateDepost(e){await this._axios.post(`/affiliates/${e}/deposit`,{},{withWalletCredentials:!0})}async countAffiliateClick(e){await this._axios.post("/affiliates/click",{referralToken:e},{withWalletCredentials:!0})}getSocialAccount(){return this._axios.get("/social/account",{withWalletCredentials:!0})}async addSocialEmail(e,t){await this._axios.put("/social/account/email",{email:e,embeddedAppUrl:t},{withWalletCredentials:!0})}async verifySocialEmail(e,t){await this._axios.put("/social/account/verifyEmail",{email:e,hash:t},{withWalletCredentials:!0})}getLeaderboards(){return this._axios.get("/social/leaderboard",{withWalletCredentials:!0})}getUnlocks(){return this._axios.get("/social/unlocks",{withWalletCredentials:!0})}getSocialSettings(){return this._axios.get("/social/settings",{withWalletCredentials:!0})}getSeason(e){return this._axios.get("/social/seasons/active",{withWalletCredentials:!0,headers:{CompanyId:e}})}getPastSeasons(){return this._axios.get("/social/seasons/history",{withWalletCredentials:!0})}addTelegram(e){return this._axios.post("/social/telegram/connect",e,{withWalletCredentials:!0})}async disconnectTelegram(e){await this._axios.put("/social/telegram/disconnect",e,{withWalletCredentials:!0})}async getDiscordConnectionUrl(e){let t=e?`?embeddedAppUrl=${encodeURIComponent(e)}`:"";return(await this._axios.get(`/social/discord/connect${t}`,{withWalletCredentials:!0})).url}async disconnectDiscord(){await this._axios.put("/social/discord/disconnect",{},{withWalletCredentials:!0})}async getTwitterConnectionUrl(e,t){let r=e?`?embeddedAppUrl=${encodeURIComponent(e)}`:"",n=t?`&scopes=${t}`:"";return(await this._axios.get(`/social/twitter/connect${r}${n}`,{withWalletCredentials:!0})).url}async disconnectTwitter(){await this._axios.put("/social/twitter/disconnect",{},{withWalletCredentials:!0})}getTweets(){return this._axios.get("/social/twitter/tweets",{withWalletCredentials:!0})}async actionWithTweet(e){await this._axios.post("/social/twitter/tweet/actions",e,{withWalletCredentials:!0})}getActions(){return this._axios.get("/social/actions",{withWalletCredentials:!0})}getActionHistory(){return this._axios.get("/social/actions/history",{withWalletCredentials:!0})}getAIStyles(){return this._axios.get("/social/twitter/tweets/styles",{withWalletCredentials:!0})}getAIComment(e,t){return this._axios.get(`/social/twitter/tweets/${t}/generateComment?styleId=${e}`,{withWalletCredentials:!0})}getTechnologyByProvider(e){switch(e){case q.PERA:return"ALGORAND";case q.METAMASK:return"EVM";case q.SOLFLARE:case q.COINBASE:case q.PHANTOM:case q.BACKPACK:case q.MOBILE:return"SOLANA";default:throw new Error("Not implemented")}}async login({address:e,provider:t,chain:r,referralToken:n,loginMessage:s}){let l=s||Zt,u={address:e,technology:this.getTechnologyByProvider(t)},f=c.from(ji(u,l)).toString("hex");return await this.client.signAndSendData(f,this.client.signer.signMessage,async({signature:d})=>{let p=await this._axios.put("/wallet/signin",{data:u,message:f,encoding:"hex",signature:d,referralToken:n});return this.mainWallet={address:e,provider:t,token:p,chain:r},p},"hex")}async addTradingKey(e){let r=c.from(jt(e,!0)).toString("hex"),{device:n,type:s}=e;return await this.client.signAndSendData(r,this.client.signer.signMessage,async({signature:o})=>{let l=await this._axios.post("/wallet/key",{data:{device:n,type:s},encoding:"hex",message:r,signature:o});return this.mainWallet&&l.type===tn.User&&(this.mainWallet.tradingKey=l.address),l},"hex")}async revokeTradingKey(e){let r=c.from(jt(e,!1)).toString("hex"),{device:n,type:s}=e;return await this.client.signAndSendData(r,this.client.signer.signMessage,async({signature:o})=>(await this._axios.delete("/wallet/key",{data:{data:{device:n,type:s},encoding:"hex",message:r,signature:o}}),this.mainWallet&&e.tkAddress===this.mainWallet.tradingKey&&(this.mainWallet.tradingKey=void 0),{signature:o}),"hex")}async withdraw(e,t){let n={...e,random:Qe(1,Number.MAX_SAFE_INTEGER)},s=c.from(en(n,t)).toString("hex");return await this.client.signAndSendData(s,this.client.signer.signMessage,({signature:o})=>this._axios.post("/wallet/withdraw",{encoding:"hex",message:s,signature:o,destinationAddress:n.recipient}),"hex")}async transfer(e){let r={...e,random:Qe(1,Number.MAX_SAFE_INTEGER)},n=c.from(nn(r)).toString("hex");return await this.client.signAndSendData(n,this.client.signer.signMessage,({signature:s})=>this._axios.post("/wallet/transfer",{message:n,signature:s}),"hex")}async createSpotOrder(e){let t=Qi*24*60*60,r=Math.floor(Date.now()/1e3)+t,n={...e,version:Zi,expiredTime:r,random:Qe(1,Number.MAX_SAFE_INTEGER)},s="hex",o=c.from(Hi(n)).toString(s);return await this.client.signAndSendData(o,this.client.signer.signMessageByToken,({signature:l})=>this._axios.post("/market/order",{encoding:s,message:o,signature:l}),s)}async cancelOrder(e){let t={orderId:e.orderId},r="hex",n=c.from(Ki(e)).toString(r);return await this.client.signAndSendData(n,this.client.signer.signMessageByToken,({signature:s})=>this._axios.delete("/market/order",{data:{data:t,message:n,signature:s}}),r)}async cancelMultipleOrders({orderIds:e,pairId:t}){let r={orderIds:e,pairId:t};return await this.client.signAndSendData(r,this.client.signer.signMessageByToken,({signature:n})=>this._axios.delete("/market/orders",{data:{data:r,signature:n}}))}async ping(){let e=await this._axios.get("/system/time");return Math.round(Date.now()-e.currentTime)}};export{Oi as ACTION_TYPE,Gi as AffDashboardVisibilitySettingEnum,Mi as BLOCKCHAINS,Ht as Client,Zt as DEFAULT_LOGIN_MESSAGE,Pi as DIRECT_SETTLE,Kt as NETWORK_CONFIGS,Si as ORDER_STATUS,Ui as OperationStatusEnum,vi as OrderStatus,Di as OrderTypeEnum,Ni as OrderUpdateStaus,Li as POINTS_SETTING,ze as PRIVATE_STREAMS,Ri as PairSettingsIds,Ci as SOCIAL_ACTION_SOURCE,Fi as STREAMS,Bi as SettingIds,le as SocketManager,Wi as TransactionType,Je as tokenizedUrls};
2
2
  /*! Bundled license information:
3
3
 
4
4
  @esbuild-plugins/node-globals-polyfill/Buffer.js:
@@ -184,7 +184,7 @@ interface IGetSymbolsItem {
184
184
  pairKey: string;
185
185
  }
186
186
  export type IGetSymbols = IGetSymbolsItem[];
187
- import { CreateOrderArgs, CancelOrderArgs } from "./index.ts";
187
+ import { CancelOrderArgs, CreateSpotOrderArgs } from "./index.ts";
188
188
  export interface ICancelOrderResponse {
189
189
  orderId: number;
190
190
  isCancelled: boolean;
@@ -222,7 +222,7 @@ export interface IMarketForClient {
222
222
  getKycStatus(): Promise<IGetKycStatus>;
223
223
  getKycInitLink(embeddedAppUrl: string | null): Promise<IGetKycInitLink>;
224
224
  getDollarValues(assetIds?: number[]): Promise<IGetDollarValues>;
225
- createOrder(order: CreateOrderArgs): Promise<IOrderDto>;
225
+ createSpotOrder(order: CreateSpotOrderArgs): Promise<IOrderDto>;
226
226
  cancelOrder(order: CancelOrderArgs): Promise<ICancelOrderResponse>;
227
227
  cancelMultipleOrders(data: {
228
228
  orderIds?: number[];
@@ -15,7 +15,7 @@ export interface CancelOrderArgs {
15
15
  priceCurrency: string;
16
16
  priceDecimal: number;
17
17
  }
18
- export interface CreateOrderArgs {
18
+ export interface CreateSpotOrderArgs {
19
19
  pairId: number;
20
20
  companyId: number;
21
21
  orderSide: OrderSide;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrade/ultrade-js-sdk",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "This package contains the original js/ts SDK.",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",