@ultrade/ultrade-js-sdk 0.2.6 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,25 @@
1
- "use strict";
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ "use strict";
3
+ /******/ var __webpack_modules__ = ({
4
+
5
+ /***/ 10:
6
+ /***/ ((module) => {
7
+
8
+ module.exports = require("@ultrade/shared/common/index");
9
+
10
+ /***/ }),
11
+
12
+ /***/ 65:
13
+ /***/ ((module) => {
14
+
15
+ module.exports = require("@ultrade/shared/helpers/algo.helper");
16
+
17
+ /***/ }),
18
+
19
+ /***/ 156:
20
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
21
+
22
+
2
23
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
24
  if (k2 === undefined) k2 = k;
4
25
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -13,7 +34,1186 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
34
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
35
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
36
  };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./amm"), exports);
18
- __exportStar(require("./constants"), exports);
19
- __exportStar(require("./types"), exports);
37
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
38
+ exports.SocketManager = void 0;
39
+ __exportStar(__webpack_require__(985), exports);
40
+ var sockets_1 = __webpack_require__(382);
41
+ Object.defineProperty(exports, "SocketManager", ({ enumerable: true, get: function () { return sockets_1.SocketManager; } }));
42
+
43
+
44
+ /***/ }),
45
+
46
+ /***/ 185:
47
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
48
+
49
+
50
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
51
+ if (k2 === undefined) k2 = k;
52
+ var desc = Object.getOwnPropertyDescriptor(m, k);
53
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
54
+ desc = { enumerable: true, get: function() { return m[k]; } };
55
+ }
56
+ Object.defineProperty(o, k2, desc);
57
+ }) : (function(o, m, k, k2) {
58
+ if (k2 === undefined) k2 = k;
59
+ o[k2] = m[k];
60
+ }));
61
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
62
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
63
+ }) : function(o, v) {
64
+ o["default"] = v;
65
+ });
66
+ var __importStar = (this && this.__importStar) || (function () {
67
+ var ownKeys = function(o) {
68
+ ownKeys = Object.getOwnPropertyNames || function (o) {
69
+ var ar = [];
70
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
71
+ return ar;
72
+ };
73
+ return ownKeys(o);
74
+ };
75
+ return function (mod) {
76
+ if (mod && mod.__esModule) return mod;
77
+ var result = {};
78
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
79
+ __setModuleDefault(result, mod);
80
+ return result;
81
+ };
82
+ })();
83
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
84
+ exports.decodeString = exports.unpackData = void 0;
85
+ const algosdk_1 = __importStar(__webpack_require__(241));
86
+ const format = {
87
+ priceCoin_locked: {
88
+ type: 'uint',
89
+ },
90
+ priceCoin_available: {
91
+ type: 'uint',
92
+ },
93
+ baseCoin_locked: {
94
+ type: 'uint',
95
+ },
96
+ baseCoin_available: {
97
+ type: 'uint',
98
+ },
99
+ companyId: {
100
+ type: 'uint',
101
+ },
102
+ WLFeeShare: {
103
+ type: 'uint',
104
+ },
105
+ WLCustomFee: {
106
+ type: 'uint',
107
+ },
108
+ slotMap: {
109
+ type: 'uint',
110
+ },
111
+ };
112
+ const unpackData = (data) => {
113
+ const result = new Map();
114
+ let index = 0;
115
+ for (const [name, type] of Object.entries(format)) {
116
+ if (index >= data.length) {
117
+ throw new Error('Array index out of bounds');
118
+ }
119
+ let value;
120
+ switch (type.type) {
121
+ case 'address':
122
+ value = (0, algosdk_1.encodeAddress)(data.slice(index, index + 32));
123
+ index += 32;
124
+ break;
125
+ case 'bytes':
126
+ value = data.slice(index, index + type.size);
127
+ value = algosdk_1.default.decodeUint64(value, 'mixed');
128
+ index += type.size;
129
+ break;
130
+ case 'uint':
131
+ value = algosdk_1.default.decodeUint64(data.slice(index, index + 8), 'mixed');
132
+ index += 8;
133
+ break;
134
+ case 'string':
135
+ value = (0, exports.decodeString)(data.slice(index, index + type.size));
136
+ index += type.size;
137
+ break;
138
+ }
139
+ result.set(name, value);
140
+ }
141
+ return Object.fromEntries(result);
142
+ };
143
+ exports.unpackData = unpackData;
144
+ const decodeString = (value) => {
145
+ return Buffer.from(value).toString('utf-8');
146
+ };
147
+ exports.decodeString = decodeString;
148
+
149
+
150
+ /***/ }),
151
+
152
+ /***/ 186:
153
+ /***/ ((module) => {
154
+
155
+ module.exports = require("@ultrade/shared/enums");
156
+
157
+ /***/ }),
158
+
159
+ /***/ 193:
160
+ /***/ ((module) => {
161
+
162
+ module.exports = require("@ultrade/shared/constants");
163
+
164
+ /***/ }),
165
+
166
+ /***/ 230:
167
+ /***/ ((module) => {
168
+
169
+ module.exports = require("@ultrade/shared/helpers/codex/index");
170
+
171
+ /***/ }),
172
+
173
+ /***/ 241:
174
+ /***/ ((module) => {
175
+
176
+ module.exports = require("algosdk");
177
+
178
+ /***/ }),
179
+
180
+ /***/ 287:
181
+ /***/ ((module) => {
182
+
183
+ module.exports = require("react-secure-storage");
184
+
185
+ /***/ }),
186
+
187
+ /***/ 382:
188
+ /***/ ((__unused_webpack_module, exports) => {
189
+
190
+
191
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
192
+ exports.SocketManager = void 0;
193
+ class SocketManager {
194
+ onDisconnect;
195
+ onConnectError;
196
+ socket = null;
197
+ socketPool = {};
198
+ websocketUrl;
199
+ socketIOFactory;
200
+ constructor(url, socketIOFactory, onDisconnect, onConnectError) {
201
+ this.onDisconnect = onDisconnect;
202
+ this.onConnectError = onConnectError;
203
+ this.websocketUrl = url;
204
+ this.socketIOFactory = socketIOFactory;
205
+ this.initializeSocket();
206
+ }
207
+ initializeSocket() {
208
+ if (this.socket === null) {
209
+ this.socket = this.socketIOFactory(this.websocketUrl, {
210
+ reconnection: true,
211
+ reconnectionDelay: 1000,
212
+ reconnectionAttempts: 9999,
213
+ transports: ['websocket'],
214
+ });
215
+ if (this.onDisconnect) {
216
+ this.socket.on('disconnect', () => {
217
+ this.onDisconnect(this.socket.id);
218
+ });
219
+ }
220
+ if (this.onConnectError) {
221
+ this.socket.on('connect_error', (err) => {
222
+ this.onConnectError(err);
223
+ });
224
+ }
225
+ }
226
+ }
227
+ getSocket() {
228
+ return this.socket;
229
+ }
230
+ subscribe(subscribeOptions, callback) {
231
+ const handlerId = Date.now();
232
+ if (this.socket === null) {
233
+ this.initializeSocket();
234
+ }
235
+ this.socket.onAny((event, ...args) => {
236
+ callback(event, args);
237
+ });
238
+ this.socket.io.on('reconnect', () => {
239
+ this.socket.emit('subscribe', subscribeOptions);
240
+ });
241
+ this.socket.emit('subscribe', subscribeOptions);
242
+ this.socketPool[handlerId] = subscribeOptions;
243
+ return handlerId;
244
+ }
245
+ unsubscribe(handlerId) {
246
+ const options = this.socketPool[handlerId];
247
+ if (options && this.socket) {
248
+ this.socket.emit('unsubscribe', options);
249
+ delete this.socketPool[handlerId];
250
+ }
251
+ if (Object.keys(this.socketPool).length === 0 && this.socket) {
252
+ this.disconnect();
253
+ }
254
+ }
255
+ disconnect() {
256
+ if (this.socket) {
257
+ this.socket.disconnect();
258
+ this.socket = null;
259
+ }
260
+ }
261
+ isConnected() {
262
+ return this.socket !== null && this.socket.connected;
263
+ }
264
+ on(event, handler) {
265
+ if (this.socket) {
266
+ this.socket.on(event, handler);
267
+ }
268
+ }
269
+ off(event, handler) {
270
+ if (this.socket) {
271
+ if (handler) {
272
+ this.socket.off(event, handler);
273
+ }
274
+ else {
275
+ this.socket.off(event);
276
+ }
277
+ }
278
+ }
279
+ emit(event, ...args) {
280
+ if (this.socket) {
281
+ this.socket.emit(event, ...args);
282
+ }
283
+ }
284
+ emitCurrentPair(data) {
285
+ this.emit('currentPair', data);
286
+ }
287
+ emitOrderFilter(data) {
288
+ this.emit('orderFilter', data);
289
+ }
290
+ onReconnect(handler) {
291
+ if (this.socket) {
292
+ this.socket.io.off('reconnect');
293
+ this.socket.io.on('reconnect', handler);
294
+ return () => {
295
+ if (this.socket) {
296
+ this.socket.io.off('reconnect', handler);
297
+ }
298
+ };
299
+ }
300
+ return () => { };
301
+ }
302
+ offReconnect(handler) {
303
+ if (this.socket) {
304
+ if (handler) {
305
+ this.socket.io.off('reconnect', handler);
306
+ }
307
+ else {
308
+ this.socket.io.off('reconnect');
309
+ }
310
+ }
311
+ }
312
+ }
313
+ exports.SocketManager = SocketManager;
314
+
315
+
316
+ /***/ }),
317
+
318
+ /***/ 524:
319
+ /***/ ((module) => {
320
+
321
+ module.exports = require("@ultrade/shared/interfaces");
322
+
323
+ /***/ }),
324
+
325
+ /***/ 566:
326
+ /***/ ((module) => {
327
+
328
+ module.exports = require("@ultrade/shared/helpers/withdraw.helper");
329
+
330
+ /***/ }),
331
+
332
+ /***/ 610:
333
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
334
+
335
+
336
+ var __importDefault = (this && this.__importDefault) || function (mod) {
337
+ return (mod && mod.__esModule) ? mod : { "default": mod };
338
+ };
339
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
340
+ exports.LocalStorageService = void 0;
341
+ const react_secure_storage_1 = __importDefault(__webpack_require__(287));
342
+ const host = new URL((window.location !== window.parent.location) ? document.referrer : document.location.href).host;
343
+ const addHostPostfix = (key) => `${key}_${host}`;
344
+ const secureLocalStorageProxy = new Proxy(react_secure_storage_1.default, {
345
+ get(target, prop, receiver) {
346
+ if (typeof prop === 'string' && typeof target[prop] === 'function') {
347
+ return function (...args) {
348
+ if (typeof prop === 'string' && ['setItem', 'getItem', 'removeItem'].includes(prop)) {
349
+ args[0] = addHostPostfix(args[0]);
350
+ }
351
+ return target[prop].apply(target, args);
352
+ };
353
+ }
354
+ return Reflect.get(target, prop, receiver);
355
+ }
356
+ });
357
+ const localStorageProxy = new Proxy(localStorage, {
358
+ get(target, prop, receiver) {
359
+ if (typeof prop === 'string' && typeof target[prop] === 'function') {
360
+ return function (...args) {
361
+ if (typeof prop === 'string' && ['setItem', 'getItem', 'removeItem', 'key'].includes(prop)) {
362
+ args[0] = addHostPostfix(args[0]);
363
+ }
364
+ return target[prop].apply(target, args);
365
+ };
366
+ }
367
+ return Reflect.get(target, prop, receiver);
368
+ }
369
+ });
370
+ class LocalStorageService {
371
+ isBrowser;
372
+ keys = {
373
+ mainWallet: 'main-wallet',
374
+ tradingKey: 'trading-key'
375
+ };
376
+ constructor() {
377
+ this.isBrowser = typeof window !== 'undefined';
378
+ if (!this.isBrowser) {
379
+ this.clearMainWallet = () => { };
380
+ this.getMainWallet = () => null;
381
+ this.setMainWallet = () => { };
382
+ }
383
+ }
384
+ setMainWallet(mainWallet) {
385
+ localStorageProxy.setItem(this.keys.mainWallet, JSON.stringify(mainWallet));
386
+ }
387
+ getMainWallet() {
388
+ const mainWalletStr = localStorageProxy.getItem(this.keys.mainWallet);
389
+ if (!mainWalletStr) {
390
+ return null;
391
+ }
392
+ const mainWallet = JSON.parse(mainWalletStr);
393
+ const tradingKey = secureLocalStorageProxy.getItem(`${this.keys.tradingKey}-${mainWallet.address}`);
394
+ // @ts-ignore
395
+ if (tradingKey && (tradingKey.expiredAt === 0 || Number(new Date(tradingKey.expiredAt)) - Date.now() > 1)) {
396
+ // @ts-ignore
397
+ mainWallet.tradingKey = tradingKey.address;
398
+ }
399
+ return mainWallet;
400
+ }
401
+ clearMainWallet() {
402
+ localStorageProxy.removeItem(this.keys.mainWallet);
403
+ }
404
+ }
405
+ exports.LocalStorageService = LocalStorageService;
406
+
407
+
408
+ /***/ }),
409
+
410
+ /***/ 726:
411
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
412
+
413
+
414
+ var __importDefault = (this && this.__importDefault) || function (mod) {
415
+ return (mod && mod.__esModule) ? mod : { "default": mod };
416
+ };
417
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
418
+ exports.AlgodService = void 0;
419
+ const algo_helper_1 = __webpack_require__(65);
420
+ const algosdk_1 = __importDefault(__webpack_require__(241));
421
+ const axios_1 = __importDefault(__webpack_require__(938));
422
+ const utils_1 = __webpack_require__(185);
423
+ class AlgodService {
424
+ client;
425
+ authCredentials;
426
+ indexerDomain;
427
+ constructor(algodClient, credentials, indexerDomain) {
428
+ this.client = algodClient;
429
+ this.authCredentials = credentials;
430
+ this.indexerDomain = indexerDomain;
431
+ }
432
+ isAppOptedIn(appLocalState, appId) {
433
+ return !!appLocalState?.find((app) => app.id === appId);
434
+ }
435
+ isAssetOptedIn(balances, assetId) {
436
+ return Object.keys(balances).includes(assetId.toString());
437
+ }
438
+ async optInAsset(userAddress, assetIndex) {
439
+ const params = await this.getTxnParams();
440
+ const response = algosdk_1.default.makeAssetTransferTxnWithSuggestedParamsFromObject({
441
+ suggestedParams: {
442
+ ...params,
443
+ },
444
+ from: userAddress,
445
+ to: userAddress,
446
+ assetIndex: assetIndex,
447
+ amount: 0,
448
+ });
449
+ return response;
450
+ }
451
+ async makeAppCallTransaction(assetIndex, senderAddress, appId, args, params) {
452
+ const accounts = [];
453
+ const foreignApps = [];
454
+ const foreignAssets = [assetIndex];
455
+ const txn = algosdk_1.default.makeApplicationNoOpTxn(senderAddress, params || await this.getTxnParams(), appId, args, accounts, foreignApps, foreignAssets);
456
+ return txn;
457
+ }
458
+ makeTransferTransaction(params, assetIndex, transferAmount, senderAddress, appAddress) {
459
+ if (transferAmount <= 0)
460
+ return null;
461
+ const txn_params = {
462
+ suggestedParams: {
463
+ ...params,
464
+ },
465
+ from: senderAddress,
466
+ to: appAddress,
467
+ amount: transferAmount,
468
+ };
469
+ if (assetIndex === 0) {
470
+ return algosdk_1.default.makePaymentTxnWithSuggestedParamsFromObject(txn_params);
471
+ }
472
+ txn_params.assetIndex = assetIndex;
473
+ return algosdk_1.default.makeAssetTransferTxnWithSuggestedParamsFromObject(
474
+ // @ts-ignore
475
+ txn_params);
476
+ }
477
+ get signer() {
478
+ return this.authCredentials.signer;
479
+ }
480
+ set signer(value) {
481
+ this.authCredentials.signer = value;
482
+ }
483
+ async signAndSend(txnGroup) {
484
+ if (!Array.isArray(txnGroup))
485
+ txnGroup = [txnGroup];
486
+ const recoveredAccount = this.getCurrentAccount();
487
+ if (recoveredAccount) {
488
+ const signedTxns = txnGroup.map((txn) => txn.signTxn(recoveredAccount.sk));
489
+ return this.client.sendRawTransaction(signedTxns).do();
490
+ }
491
+ return this.authCredentials.signer.signAndSend(txnGroup);
492
+ }
493
+ async signAndSendData(data, signMessage, sendAction, encoding) {
494
+ const message = typeof data === "string" ? data : JSON.stringify(data);
495
+ const payload = typeof data === "string" ? { message } : { ...data };
496
+ const signature = await signMessage(message, encoding);
497
+ return sendAction({
498
+ ...payload,
499
+ signature: signature
500
+ });
501
+ }
502
+ async getTxnParams() {
503
+ return await (0, algo_helper_1.getTxnParams)(this.client);
504
+ }
505
+ getCurrentAccount() {
506
+ if (!this.authCredentials.mnemonic)
507
+ return null;
508
+ return algosdk_1.default.mnemonicToSecretKey(this.authCredentials.mnemonic);
509
+ }
510
+ async getAccountInfo(address) {
511
+ return this.client.accountInformation(address).do();
512
+ }
513
+ constructArgsForAppCall(...args) {
514
+ const appArgs = [];
515
+ args.forEach((elem) => {
516
+ appArgs.push(new Uint8Array(elem.toBuffer ? elem.toBuffer() : Buffer.from(elem.toString())));
517
+ });
518
+ return appArgs;
519
+ }
520
+ validateCredentials() {
521
+ if (!this.authCredentials.mnemonic && !this.authCredentials.signer) {
522
+ throw 'You need specify mnemonic or signer to execute the method';
523
+ }
524
+ }
525
+ async getAppState(appId) {
526
+ try {
527
+ const app = await this.client.getApplicationByID(appId).do();
528
+ const globalState = (0, algo_helper_1.decodeStateArray)(app['params']['global-state']);
529
+ return globalState;
530
+ }
531
+ catch (error) {
532
+ console.log(`Attempt to load app by id ${appId}`);
533
+ console.log(error.message);
534
+ }
535
+ }
536
+ async getSuperAppId(appId) {
537
+ const state = await this.getAppState(appId);
538
+ return state?.['UL_SUPERADMIN_APP'] || 0;
539
+ }
540
+ async getPairBalances(appId, address) {
541
+ const { data } = await axios_1.default.get(`${this.indexerDomain}/v2/accounts/${address}?include-all=true`);
542
+ if (data.account.hasOwnProperty('apps-local-state')) {
543
+ const state = data.account['apps-local-state'].find((el) => el.id === appId && el.deleted === false);
544
+ if (!state) {
545
+ return null;
546
+ }
547
+ const key = state['key-value'].find((el) => el.key === 'YWNjb3VudEluZm8=');
548
+ const uintArray = Buffer.from(key.value.bytes, 'base64');
549
+ return (0, utils_1.unpackData)(uintArray);
550
+ }
551
+ }
552
+ async calculateTransferAmount(appId, address, side, quantity, price, decimal) {
553
+ const pairBalances = await this.getPairBalances(appId, address);
554
+ const availableBalance = (side === 'B'
555
+ ? pairBalances?.priceCoin_available
556
+ : pairBalances?.baseCoin_available) ?? 0;
557
+ if (side === 'B') {
558
+ quantity = (quantity / 10 ** decimal) * price;
559
+ }
560
+ const transferAmount = Math.ceil(quantity - availableBalance);
561
+ if (transferAmount < 0) {
562
+ return 0;
563
+ }
564
+ return transferAmount;
565
+ }
566
+ }
567
+ exports.AlgodService = AlgodService;
568
+
569
+
570
+ /***/ }),
571
+
572
+ /***/ 734:
573
+ /***/ ((__unused_webpack_module, exports) => {
574
+
575
+
576
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
577
+ exports.SOCIAL_ACTION_SOURCE = exports.PRIVATE_STREAMS = exports.STREAMS = exports.ORDER_STATUS = exports.DIRECT_SETTLE = void 0;
578
+ var DIRECT_SETTLE;
579
+ (function (DIRECT_SETTLE) {
580
+ DIRECT_SETTLE["YES"] = "Y";
581
+ DIRECT_SETTLE["NO"] = "N";
582
+ })(DIRECT_SETTLE || (exports.DIRECT_SETTLE = DIRECT_SETTLE = {}));
583
+ var ORDER_STATUS;
584
+ (function (ORDER_STATUS) {
585
+ ORDER_STATUS[ORDER_STATUS["OPEN_ORDER"] = 1] = "OPEN_ORDER";
586
+ ORDER_STATUS[ORDER_STATUS["CANCELLED"] = 2] = "CANCELLED";
587
+ ORDER_STATUS[ORDER_STATUS["MATCHED"] = 3] = "MATCHED";
588
+ ORDER_STATUS[ORDER_STATUS["SELF_MATCHED"] = 4] = "SELF_MATCHED";
589
+ })(ORDER_STATUS || (exports.ORDER_STATUS = ORDER_STATUS = {}));
590
+ var STREAMS;
591
+ (function (STREAMS) {
592
+ STREAMS[STREAMS["QUOTE"] = 1] = "QUOTE";
593
+ STREAMS[STREAMS["LAST_PRICE"] = 2] = "LAST_PRICE";
594
+ STREAMS[STREAMS["DEPTH"] = 3] = "DEPTH";
595
+ STREAMS[STREAMS["LAST_CANDLESTICK"] = 4] = "LAST_CANDLESTICK";
596
+ STREAMS[STREAMS["ORDERS"] = 5] = "ORDERS";
597
+ STREAMS[STREAMS["TRADES"] = 6] = "TRADES";
598
+ STREAMS[STREAMS["SYSTEM"] = 7] = "SYSTEM";
599
+ STREAMS[STREAMS["WALLET_TRANSACTIONS"] = 8] = "WALLET_TRANSACTIONS";
600
+ STREAMS[STREAMS["ALL_STAT"] = 9] = "ALL_STAT";
601
+ STREAMS[STREAMS["CODEX_ASSETS"] = 12] = "CODEX_ASSETS";
602
+ STREAMS[STREAMS["CODEX_BALANCES"] = 10] = "CODEX_BALANCES";
603
+ STREAMS[STREAMS["LAST_LOOK"] = 11] = "LAST_LOOK";
604
+ STREAMS[STREAMS["SETTINGS_UPDATE"] = 13] = "SETTINGS_UPDATE";
605
+ STREAMS[STREAMS["NEW_NOTIFICATION"] = 14] = "NEW_NOTIFICATION";
606
+ STREAMS[STREAMS["POINT_SYSTEM_SETTINGS_UPDATE"] = 15] = "POINT_SYSTEM_SETTINGS_UPDATE";
607
+ })(STREAMS || (exports.STREAMS = STREAMS = {}));
608
+ exports.PRIVATE_STREAMS = [
609
+ STREAMS.ORDERS,
610
+ STREAMS.WALLET_TRANSACTIONS,
611
+ STREAMS.CODEX_BALANCES,
612
+ STREAMS.LAST_LOOK,
613
+ ];
614
+ var SOCIAL_ACTION_SOURCE;
615
+ (function (SOCIAL_ACTION_SOURCE) {
616
+ SOCIAL_ACTION_SOURCE["COMPANY"] = "COMPANY";
617
+ SOCIAL_ACTION_SOURCE["TWITTER"] = "TWITTER";
618
+ SOCIAL_ACTION_SOURCE["DISCORD"] = "DISCORD";
619
+ SOCIAL_ACTION_SOURCE["TELEGRAM"] = "TELEGRAM";
620
+ })(SOCIAL_ACTION_SOURCE || (exports.SOCIAL_ACTION_SOURCE = SOCIAL_ACTION_SOURCE = {}));
621
+
622
+
623
+ /***/ }),
624
+
625
+ /***/ 845:
626
+ /***/ ((module) => {
627
+
628
+ module.exports = require("@ultrade/shared/helpers/codex.helper");
629
+
630
+ /***/ }),
631
+
632
+ /***/ 938:
633
+ /***/ ((module) => {
634
+
635
+ module.exports = require("axios");
636
+
637
+ /***/ }),
638
+
639
+ /***/ 985:
640
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
641
+
642
+
643
+ // @ts-nocheck
644
+ var __importDefault = (this && this.__importDefault) || function (mod) {
645
+ return (mod && mod.__esModule) ? mod : { "default": mod };
646
+ };
647
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
648
+ exports.Client = void 0;
649
+ const axios_1 = __importDefault(__webpack_require__(938));
650
+ const constants_1 = __webpack_require__(193);
651
+ const index_1 = __webpack_require__(10);
652
+ const codex_helper_1 = __webpack_require__(845);
653
+ const withdraw_helper_1 = __webpack_require__(566);
654
+ const sockets_1 = __webpack_require__(382);
655
+ const algodService_1 = __webpack_require__(726);
656
+ const enums_1 = __webpack_require__(734);
657
+ const localStorage_1 = __webpack_require__(610);
658
+ const interfaces_1 = __webpack_require__(524);
659
+ const interfaces_2 = __webpack_require__(524);
660
+ const enums_2 = __webpack_require__(186);
661
+ const index_2 = __webpack_require__(230);
662
+ const DEFAULT_LOGIN_MESSAGE = `By signing this message you are logging into your trading account and agreeing to all terms and conditions of the platform.`;
663
+ class Client {
664
+ client;
665
+ algodNode;
666
+ algodIndexer;
667
+ apiUrl;
668
+ companyId;
669
+ websocketUrl;
670
+ wallet;
671
+ _axios;
672
+ localStorageService;
673
+ isUltradeID;
674
+ socketManager;
675
+ constructor(options, authCredentials) {
676
+ if (options.network === "mainnet") {
677
+ this.algodNode = 'https://mainnet-api.algonode.cloud';
678
+ this.apiUrl = 'https://mainnet-api.algonode.cloud';
679
+ this.algodIndexer = 'https://mainnet-idx.algonode.cloud';
680
+ }
681
+ else if (options.network === "testnet") {
682
+ this.apiUrl = "https://testnet-apigw.ultradedev.net";
683
+ this.algodNode = 'https://testnet-api.algonode.cloud';
684
+ this.algodIndexer = 'https://testnet-idx.algonode.cloud';
685
+ }
686
+ else {
687
+ this.apiUrl = "http://localhost:5001";
688
+ this.algodNode = 'http://localhost:4001';
689
+ this.algodIndexer = 'http://localhost:8980';
690
+ }
691
+ if (options.apiUrl !== undefined) {
692
+ this.apiUrl = options.apiUrl;
693
+ }
694
+ if (options.companyId !== undefined) {
695
+ this.companyId = options.companyId;
696
+ }
697
+ this.websocketUrl = options.websocketUrl;
698
+ this.client = new algodService_1.AlgodService(options.algoSdkClient, authCredentials || {}, this.algodIndexer);
699
+ this._axios = this.axiosInterceptor(axios_1.default.create({
700
+ baseURL: this.apiUrl,
701
+ }));
702
+ this.localStorageService = new localStorage_1.LocalStorageService();
703
+ this.wallet = this.localStorageService.getMainWallet();
704
+ this.isUltradeID = false;
705
+ this.socketManager = new sockets_1.SocketManager(this.websocketUrl, options.socketIO, (socketId) => {
706
+ console.log(`Socket ${socketId} disconnected at`, new Date());
707
+ }, (err) => {
708
+ console.log(`Socket connect_error due to ${err}`);
709
+ });
710
+ console.log('SDK Wallet', this.wallet);
711
+ }
712
+ axiosInterceptor = (axios) => {
713
+ const tokenizedUrls = [
714
+ '/market/balances',
715
+ '/market/order',
716
+ '/market/orders',
717
+ '/market/account/kyc/status',
718
+ '/market/account/kyc/init',
719
+ '/market/withdrawal-fee',
720
+ '/market/operation-details',
721
+ '/wallet/key',
722
+ '/wallet/transactions',
723
+ '/wallet/transfer',
724
+ '/wallet/withdraw',
725
+ '/wallet/whitelist',
726
+ '/wallet/withdrawal-wallets',
727
+ ];
728
+ const tokenRequired = (config) => {
729
+ return config.withWalletCredentials || tokenizedUrls.some(value => config.url.includes(value));
730
+ };
731
+ const tradingKeyRequired = (config) => {
732
+ const urls = [
733
+ '/market/order',
734
+ // '/wallet/transfer',
735
+ ];
736
+ return config.withWalletCredentials || urls.some(value => config.url.includes(value));
737
+ };
738
+ const companyIdRequired = (config) => {
739
+ const urls = [
740
+ '/wallet/signin',
741
+ '/market/account/kyc/init',
742
+ '/notifications'
743
+ ];
744
+ return urls.some(value => config.url.includes(value));
745
+ };
746
+ const isSocialRequest = (config) => {
747
+ const urls = [
748
+ '/social/',
749
+ ];
750
+ return urls.some(value => config.url.includes(value));
751
+ };
752
+ const ifCollectStatistic = (config) => {
753
+ return tokenizedUrls.some(value => config.url.includes(value));
754
+ };
755
+ axios.interceptors.request.use((config) => {
756
+ if (this.wallet && tokenRequired(config)) {
757
+ config.headers['X-Wallet-Address'] = this.wallet.address;
758
+ config.headers['X-Wallet-Token'] = this.wallet.token;
759
+ }
760
+ if (this.wallet && ifCollectStatistic(config)) {
761
+ config.headers['CompanyId'] = this.companyId;
762
+ }
763
+ if (this.wallet && tradingKeyRequired(config)) {
764
+ const tradingKey = this.wallet?.tradingKey;
765
+ if (tradingKey) {
766
+ config.headers['X-Trading-Key'] = tradingKey;
767
+ }
768
+ }
769
+ if (companyIdRequired(config)) {
770
+ config.headers['CompanyId'] = this.companyId;
771
+ }
772
+ if (isSocialRequest(config) && !config.headers.CompanyId) {
773
+ config.headers['CompanyId'] = this.isUltradeID ? 1 : this.companyId;
774
+ }
775
+ return config;
776
+ }, (error) => Promise.reject(error));
777
+ //Add a response interceptor
778
+ axios.interceptors.response.use((response) => {
779
+ return response.data;
780
+ }, async (error) => {
781
+ console.log('Request was failed', error);
782
+ const invalidToken = [401].includes(error?.response?.status);
783
+ if (invalidToken && tokenRequired(error.config)) {
784
+ this.wallet = null;
785
+ this.localStorageService.clearMainWallet();
786
+ }
787
+ return Promise.reject(error);
788
+ });
789
+ return axios;
790
+ };
791
+ // TODO: rework emit logic in SDK UL-1257
792
+ // public setState(args: AppSocketState) {
793
+ // return ws.emitPair(args);
794
+ // }
795
+ // public setFilter(args: AppSocketState) {
796
+ // return ws.emitFilter(args);
797
+ // }
798
+ get useUltradeID() {
799
+ return this.isUltradeID;
800
+ }
801
+ set useUltradeID(isUltrade) {
802
+ this.isUltradeID = isUltrade;
803
+ }
804
+ get isLogged() {
805
+ return !!this.wallet?.token;
806
+ }
807
+ get mainWallet() {
808
+ return this.wallet;
809
+ }
810
+ set mainWallet(wallet) {
811
+ this.wallet = wallet;
812
+ if (!wallet) {
813
+ this.localStorageService.clearMainWallet();
814
+ }
815
+ else {
816
+ this.localStorageService.setMainWallet(wallet);
817
+ }
818
+ }
819
+ setSigner(signer) {
820
+ this.client.signer = signer;
821
+ }
822
+ subscribe(subscribeOptions, callback) {
823
+ const requiresAuth = subscribeOptions.streams.some(stream => enums_1.PRIVATE_STREAMS.includes(stream));
824
+ if (requiresAuth && !this.mainWallet?.token && !this.mainWallet?.tradingKey) {
825
+ subscribeOptions.streams = subscribeOptions.streams.filter(stream => !enums_1.PRIVATE_STREAMS.includes(stream));
826
+ return this.socketManager.subscribe(subscribeOptions, callback);
827
+ }
828
+ if (requiresAuth) {
829
+ subscribeOptions.options = {
830
+ ...subscribeOptions.options,
831
+ token: this.mainWallet?.token,
832
+ tradingKey: this.mainWallet?.tradingKey
833
+ };
834
+ return this.socketManager.subscribe(subscribeOptions, callback);
835
+ }
836
+ return this.socketManager.subscribe(subscribeOptions, callback);
837
+ }
838
+ unsubscribe(handlerId) {
839
+ this.socketManager.unsubscribe(handlerId);
840
+ }
841
+ getPairList(companyId) {
842
+ const query = companyId ? `&companyId=${companyId}` : "";
843
+ return this._axios.get(`/market/markets?includeAllOrders=false${query}`);
844
+ }
845
+ getExchangeInfo(symbol) {
846
+ return this._axios.get(`/market/market?symbol=${symbol}`);
847
+ }
848
+ getPrice(symbol) {
849
+ return this._axios.get(`/market/price?symbol=${symbol}`);
850
+ }
851
+ getDepth(symbol, depth) {
852
+ return this._axios.get(`/market/depth?symbol=${symbol}&depth=${depth}`);
853
+ }
854
+ getSymbols(mask) {
855
+ return this._axios.get(`/market/symbols${mask ? '?mask=' + mask : ''}`);
856
+ }
857
+ getLastTrades(symbol) {
858
+ return this._axios.get(`/market/last-trades?symbol=${symbol}`);
859
+ }
860
+ getHistory(symbol, interval, startTime, endTime, limit = 500, page = 1) {
861
+ return this._axios.get(`/market/history?symbol=${symbol}&interval=${interval}&startTime=${startTime ?? ""}&endTime=${endTime ?? ""}&limit=${limit}&page=${page}`);
862
+ }
863
+ getOrders(symbol, status, limit = 50, endTime, startTime) {
864
+ const statusStr = !status
865
+ ? ""
866
+ : (status === 1)
867
+ ? enums_2.OrderStatus.Open
868
+ : [enums_2.OrderStatus.Canceled, enums_2.OrderStatus.Matched, enums_2.OrderStatus.SelfMatched, enums_2.OrderStatus.Expired].join(',');
869
+ const symbolQuery = symbol ? `&symbol=${symbol}` : "";
870
+ const statusQuery = statusStr ? `&status=${statusStr}` : "";
871
+ const startTimeQuery = startTime ? `&startTime=${startTime}` : "";
872
+ const endTimeQuery = endTime ? `&endTime=${endTime}` : "";
873
+ return this._axios.get(`/market/orders?limit=${limit}${symbolQuery}${statusQuery}${startTimeQuery}${endTimeQuery}`);
874
+ }
875
+ getOrderById(orderId) {
876
+ return this._axios.get(`/market/order/${orderId}`);
877
+ }
878
+ getSettings() {
879
+ const domain = new URL((window.location !== window.parent.location) ? document.referrer : document.location.href).host;
880
+ return this._axios.get(`/market/settings`, { headers: { "wl-domain": domain } });
881
+ }
882
+ getBalances() {
883
+ return this._axios.get(`/market/balances`);
884
+ }
885
+ getChains() {
886
+ return this._axios.get(`/market/chains`);
887
+ }
888
+ getCodexAssets() {
889
+ return this._axios.get(`/market/assets`);
890
+ }
891
+ getCCTPAssets() {
892
+ return this._axios.get(`/market/cctp-assets`);
893
+ }
894
+ getCCTPUnifiedAssets() {
895
+ return this._axios.get(`/market/cctp-unified-assets`);
896
+ }
897
+ getWithdrawalFee(assetAddress, chainId) {
898
+ return this._axios.get(`/market/withdrawal-fee?assetAddress=${assetAddress}&chainId=${chainId}`);
899
+ }
900
+ getKycStatus() {
901
+ return this._axios.get(`/market/account/kyc/status`);
902
+ }
903
+ getKycInitLink(embeddedAppUrl) {
904
+ return this._axios.post(`/market/account/kyc/init`, { embeddedAppUrl });
905
+ }
906
+ getDollarValues(assetIds = []) {
907
+ return this._axios.get(`/market/dollar-price?assetIds=${JSON.stringify(assetIds)}`);
908
+ }
909
+ getTransactionDetalis(transactionId) {
910
+ return this._axios.get(`/market/operation-details?operationId=${transactionId}`);
911
+ }
912
+ //#region Wallet
913
+ getWalletTransactions(type, page, limit = 100) {
914
+ return this._axios.get(`/wallet/transactions?type=${type}&limit=${limit}&page=${page}`, { withWalletCredentials: true });
915
+ }
916
+ getTradingKeys() {
917
+ return this._axios.get(`/wallet/keys`, { withWalletCredentials: true });
918
+ }
919
+ getTransfers(page, limit = 100) {
920
+ return this._axios.get(`/wallet/transfers?limit=${limit}&page=${page}`, { withWalletCredentials: true });
921
+ }
922
+ getPendingTransactions() {
923
+ return this._axios.get(`/wallet/transactions/pending`, { withWalletCredentials: true });
924
+ }
925
+ getWhitelist() {
926
+ return this._axios.get(`/wallet/whitelist`, { withWalletCredentials: true });
927
+ }
928
+ addWhitelist(data) {
929
+ const encoding = 'hex';
930
+ data = {
931
+ ...data,
932
+ expiredDate: data.expiredDate && Math.round(data.expiredDate / 1000)
933
+ };
934
+ const message = Buffer.from((0, index_2.makeDtwMsg)(data)).toString(encoding);
935
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.post(`/wallet/whitelist`, { message, signature }), encoding);
936
+ }
937
+ deleteWhitelist(whitelistId) {
938
+ const data = { whitelistId };
939
+ return this.client.signAndSendData(data, this.client.signer.signMessage, ({ signature }) => this._axios.delete(`/wallet/whitelist`, {
940
+ data: { data, signature }
941
+ }));
942
+ }
943
+ getAllWithdrawalWallets() {
944
+ return this._axios.get(`/wallet/withdrawal-wallets`);
945
+ }
946
+ getWithdrawalWalletByAddress(address) {
947
+ return this._axios.get(`/wallet/withdrawal-wallets/${address}`);
948
+ }
949
+ createWithdrawalWallet(body) {
950
+ return this._axios.post(`/wallet/withdrawal-wallets`, body);
951
+ }
952
+ updateWithdrawalWallet(params) {
953
+ return this._axios.patch(`/wallet/withdrawal-wallets`, params);
954
+ }
955
+ deleteWithdrawalWallet(address) {
956
+ return this._axios.delete(`/wallet/withdrawal-wallets/${address}`);
957
+ }
958
+ //#endregion Wallet
959
+ //#region System
960
+ getVersion() {
961
+ return this._axios.get(`/system/version`);
962
+ }
963
+ getMaintenance() {
964
+ return this._axios.get(`/system/maintenance`);
965
+ }
966
+ getNotifications() {
967
+ return this._axios.get(`/notifications`, { withWalletCredentials: true });
968
+ }
969
+ getNotificationsUnreadCount() {
970
+ return this._axios.get(`/notifications/count`, { withWalletCredentials: true });
971
+ }
972
+ readNotifications(notifications) {
973
+ return this._axios.put(`/notifications`, { notifications }, { withWalletCredentials: true });
974
+ }
975
+ //#endregion System
976
+ //#region Affiliates
977
+ getAffiliatesStatus(companyId) {
978
+ return this._axios.get(`/affiliates/${companyId}/dashboardStatus`, { withWalletCredentials: true });
979
+ }
980
+ createAffiliate(companyId) {
981
+ return this._axios.post(`/affiliates/${companyId}`, {}, { withWalletCredentials: true });
982
+ }
983
+ getAffiliateProgress(companyId) {
984
+ return this._axios.get(`/affiliates/${companyId}/tradingVolumeProgress`, { withWalletCredentials: true });
985
+ }
986
+ getAffiliateInfo(companyId, range) {
987
+ return this._axios.get(`/affiliates/${companyId}/dashboard?range=${range}`, { withWalletCredentials: true });
988
+ }
989
+ countAffiliateDepost(companyId) {
990
+ return this._axios.post(`/affiliates/${companyId}/deposit `, {}, { withWalletCredentials: true });
991
+ }
992
+ countAffiliateClick(referralToken) {
993
+ return this._axios.post(`/affiliates/click`, { referralToken }, { withWalletCredentials: true });
994
+ }
995
+ //#endregion Affiliates
996
+ //#region Social
997
+ getSocialAccount() {
998
+ return this._axios.get(`/social/account`, { withWalletCredentials: true });
999
+ }
1000
+ addSocialEmail(email, embeddedAppUrl) {
1001
+ return this._axios.put(`/social/account/email`, { email, embeddedAppUrl }, { withWalletCredentials: true });
1002
+ }
1003
+ verifySocialEmail(email, hash) {
1004
+ return this._axios.put(`/social/account/verifyEmail`, { email, hash }, { withWalletCredentials: true });
1005
+ }
1006
+ getLeaderboards() {
1007
+ return this._axios.get(`/social/leaderboard`, { withWalletCredentials: true });
1008
+ }
1009
+ getUnlocks() {
1010
+ return this._axios.get(`/social/unlocks`, { withWalletCredentials: true });
1011
+ }
1012
+ getSocialSettings() {
1013
+ return this._axios.get(`/social/settings`, { withWalletCredentials: true });
1014
+ }
1015
+ getSeason(ultradeId) {
1016
+ return this._axios.get(`/social/seasons/active`, {
1017
+ withWalletCredentials: true,
1018
+ headers: { "CompanyId": ultradeId }
1019
+ });
1020
+ }
1021
+ getPastSeasons() {
1022
+ return this._axios.get(`/social/seasons/history`, { withWalletCredentials: true });
1023
+ }
1024
+ //#region Telegram
1025
+ addTelegram(data) {
1026
+ return this._axios.post(`/social/telegram/connect`, data, { withWalletCredentials: true });
1027
+ }
1028
+ disconnectTelegram(data) {
1029
+ return this._axios.put(`/social/telegram/disconnect`, data, { withWalletCredentials: true });
1030
+ }
1031
+ //#endregion Telegram
1032
+ //#region Discord
1033
+ getDiscordConnectionUrl(url) {
1034
+ const query = url ? `?embeddedAppUrl=${encodeURIComponent(url)}` : "";
1035
+ return this._axios.get(`/social/discord/connect${query}`, { withWalletCredentials: true })
1036
+ .then(({ url }) => url);
1037
+ }
1038
+ disconnectDiscord() {
1039
+ return this._axios.put(`/social/discord/disconnect`, {}, { withWalletCredentials: true });
1040
+ }
1041
+ //#endregion Discord
1042
+ //#region Twitter
1043
+ getTwitterConnectionUrl(appUrl, permissions) {
1044
+ const queryURL = appUrl ? `?embeddedAppUrl=${encodeURIComponent(appUrl)}` : "";
1045
+ const queryPermissions = permissions ? `&scopes=${permissions}` : "";
1046
+ return this._axios.get(`/social/twitter/connect${queryURL}${queryPermissions}`, { withWalletCredentials: true })
1047
+ .then(({ url }) => url);
1048
+ }
1049
+ disconnectTwitter() {
1050
+ return this._axios.put(`/social/twitter/disconnect`, {}, { withWalletCredentials: true });
1051
+ }
1052
+ getTweets() {
1053
+ return this._axios.get(`/social/twitter/tweets`, { withWalletCredentials: true });
1054
+ }
1055
+ actionWithTweet(data) {
1056
+ return this._axios.post(`/social/twitter/tweet/actions`, data, { withWalletCredentials: true });
1057
+ }
1058
+ async getActions() {
1059
+ return this._axios.get(`/social/actions`, { withWalletCredentials: true });
1060
+ }
1061
+ async getActionHistory() {
1062
+ return this._axios.get(`/social/actions/history`, { withWalletCredentials: true });
1063
+ }
1064
+ getAIStyles() {
1065
+ return this._axios.get(`/social/twitter/tweets/styles`, { withWalletCredentials: true });
1066
+ }
1067
+ getAIComment(styleId, tweetId) {
1068
+ return this._axios.get(`/social/twitter/tweets/${tweetId}/generateComment?styleId=${styleId}`, { withWalletCredentials: true });
1069
+ }
1070
+ //#endregion Twitter
1071
+ //#endregion Social
1072
+ getTechnologyByProvider(provider) {
1073
+ switch (provider) {
1074
+ case interfaces_2.PROVIDERS.PERA:
1075
+ return "ALGORAND";
1076
+ case interfaces_2.PROVIDERS.METAMASK:
1077
+ return "EVM";
1078
+ case interfaces_2.PROVIDERS.SOLFLARE:
1079
+ case interfaces_2.PROVIDERS.COINBASE:
1080
+ case interfaces_2.PROVIDERS.PHANTOM:
1081
+ case interfaces_2.PROVIDERS.BACKPACK:
1082
+ case interfaces_2.PROVIDERS.MOBILE:
1083
+ return "SOLANA";
1084
+ default: throw new Error("Not implemented");
1085
+ }
1086
+ }
1087
+ login({ address, provider, chain, referralToken, loginMessage }) {
1088
+ const encoding = 'hex';
1089
+ const signingMessage = loginMessage || DEFAULT_LOGIN_MESSAGE;
1090
+ const data = {
1091
+ address,
1092
+ technology: this.getTechnologyByProvider(provider),
1093
+ };
1094
+ const message = Buffer.from((0, codex_helper_1.makeLoginMsg)(data, signingMessage)).toString(encoding);
1095
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.put(`/wallet/signin`, { data, message, encoding, signature, referralToken })
1096
+ .then((token) => {
1097
+ this.mainWallet = { address, provider, token, chain };
1098
+ return token;
1099
+ }), encoding);
1100
+ }
1101
+ addTradingKey(data) {
1102
+ const encoding = 'hex';
1103
+ const message = Buffer.from((0, codex_helper_1.makeTradingKeyMsg)(data, true)).toString(encoding);
1104
+ const { device, type } = data;
1105
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.post(`/wallet/key`, {
1106
+ data: { device, type }, encoding, message, signature
1107
+ })
1108
+ .then((tradingKey) => {
1109
+ if (this.mainWallet && tradingKey.type === interfaces_1.TradingKeyType.User) {
1110
+ this.mainWallet.tradingKey = tradingKey.address;
1111
+ }
1112
+ return tradingKey;
1113
+ }), encoding);
1114
+ }
1115
+ revokeTradingKey(data) {
1116
+ const encoding = 'hex';
1117
+ const message = Buffer.from((0, codex_helper_1.makeTradingKeyMsg)(data, false)).toString(encoding);
1118
+ const { device, type } = data;
1119
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.delete(`/wallet/key`, {
1120
+ data: { data: { device, type }, encoding, message, signature }
1121
+ })
1122
+ .then(() => {
1123
+ if (this.mainWallet && data.tkAddress === this.mainWallet.tradingKey) {
1124
+ this.mainWallet.tradingKey = undefined;
1125
+ }
1126
+ }), encoding);
1127
+ }
1128
+ withdraw(withdrawData, prettyMsg) {
1129
+ const encoding = 'hex';
1130
+ const data = {
1131
+ ...withdrawData,
1132
+ random: (0, index_1.getRandomInt)(1, Number.MAX_SAFE_INTEGER),
1133
+ };
1134
+ const message = Buffer.from((0, withdraw_helper_1.makeWithdrawMsg)(data, prettyMsg)).toString(encoding);
1135
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.post(`/wallet/withdraw`, { encoding, message, signature, destinationAddress: data.recipient }), encoding);
1136
+ }
1137
+ transfer(transferData) {
1138
+ const encoding = 'hex';
1139
+ const data = {
1140
+ ...transferData,
1141
+ random: (0, index_1.getRandomInt)(1, Number.MAX_SAFE_INTEGER),
1142
+ };
1143
+ const message = Buffer.from((0, index_2.makeTransferMsg)(data)).toString(encoding);
1144
+ return this.client.signAndSendData(message, this.client.signer.signMessage, ({ signature }) => this._axios.post(`/wallet/transfer`, { message, signature }), encoding);
1145
+ }
1146
+ async createOrder(order) {
1147
+ const _daysInSec = constants_1.DEFAULT_ORDER_EXPIRATION_DAYS * 24 * 60 * 60;
1148
+ const expiredTime = Math.floor(Date.now() / 1000) + _daysInSec;
1149
+ const data = {
1150
+ ...order,
1151
+ version: constants_1.ORDER_MSG_VERSION,
1152
+ expiredTime,
1153
+ random: (0, index_1.getRandomInt)(1, Number.MAX_SAFE_INTEGER),
1154
+ };
1155
+ console.log('CreateOrderData', data);
1156
+ const encoding = 'hex';
1157
+ const message = Buffer.from((0, codex_helper_1.makeCreateOrderMsg)(data)).toString(encoding);
1158
+ return await this.client.signAndSendData(message, this.client.signer.signMessageByToken, ({ signature }) => this._axios.post(`/market/order`, { encoding, message, signature }), encoding);
1159
+ }
1160
+ async cancelOrder(order) {
1161
+ const data = { orderId: order.orderId };
1162
+ const encoding = 'hex';
1163
+ const message = Buffer.from((0, codex_helper_1.getCancelOrderDataJsonBytes)(order)).toString(encoding);
1164
+ return this.client.signAndSendData(message, this.client.signer.signMessageByToken, ({ signature }) => this._axios.delete(`/market/order`, {
1165
+ data: { data, message, signature }
1166
+ }), encoding);
1167
+ }
1168
+ async cancelMultipleOrders({ orderIds, pairId }) {
1169
+ const data = { orderIds, pairId };
1170
+ return this.client.signAndSendData(data, this.client.signer.signMessageByToken, ({ signature }) => this._axios.delete(`/market/orders`, {
1171
+ data: { data, signature }
1172
+ }));
1173
+ }
1174
+ async ping() {
1175
+ const data = this._axios.get(`/system/time`);
1176
+ return Math.round(Date.now() - data.currentTime);
1177
+ }
1178
+ }
1179
+ exports.Client = Client;
1180
+
1181
+
1182
+ /***/ })
1183
+
1184
+ /******/ });
1185
+ /************************************************************************/
1186
+ /******/ // The module cache
1187
+ /******/ var __webpack_module_cache__ = {};
1188
+ /******/
1189
+ /******/ // The require function
1190
+ /******/ function __webpack_require__(moduleId) {
1191
+ /******/ // Check if module is in cache
1192
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
1193
+ /******/ if (cachedModule !== undefined) {
1194
+ /******/ return cachedModule.exports;
1195
+ /******/ }
1196
+ /******/ // Create a new module (and put it into the cache)
1197
+ /******/ var module = __webpack_module_cache__[moduleId] = {
1198
+ /******/ // no module.id needed
1199
+ /******/ // no module.loaded needed
1200
+ /******/ exports: {}
1201
+ /******/ };
1202
+ /******/
1203
+ /******/ // Execute the module function
1204
+ /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
1205
+ /******/
1206
+ /******/ // Return the exports of the module
1207
+ /******/ return module.exports;
1208
+ /******/ }
1209
+ /******/
1210
+ /************************************************************************/
1211
+ /******/
1212
+ /******/ // startup
1213
+ /******/ // Load entry module and return exports
1214
+ /******/ // This entry module is referenced by other modules so it can't be inlined
1215
+ /******/ var __webpack_exports__ = __webpack_require__(156);
1216
+ /******/ module.exports = __webpack_exports__;
1217
+ /******/
1218
+ /******/ })()
1219
+ ;