@deriverse/kit 1.0.38 → 1.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/auto_buffer.d.ts +0 -2
  2. package/dist/auto_data.d.ts +0 -2
  3. package/dist/constants.d.ts +12 -0
  4. package/dist/constants.js +26 -0
  5. package/dist/engine/account-helpers.d.ts +59 -0
  6. package/dist/engine/account-helpers.js +177 -0
  7. package/dist/engine/account-helpers.test.d.ts +1 -0
  8. package/dist/engine/account-helpers.test.js +199 -0
  9. package/dist/engine/client-queries.d.ts +36 -0
  10. package/dist/engine/client-queries.js +498 -0
  11. package/dist/engine/client-queries.test.d.ts +1 -0
  12. package/dist/engine/client-queries.test.js +341 -0
  13. package/dist/engine/context-builders.d.ts +16 -0
  14. package/dist/engine/context-builders.js +158 -0
  15. package/dist/engine/context-builders.test.d.ts +1 -0
  16. package/dist/engine/context-builders.test.js +156 -0
  17. package/dist/engine/index.d.ts +101 -0
  18. package/dist/engine/index.js +745 -0
  19. package/dist/engine/index.test.d.ts +1 -0
  20. package/dist/engine/index.test.js +663 -0
  21. package/dist/engine/logs-decoder.d.ts +18 -0
  22. package/dist/engine/logs-decoder.js +414 -0
  23. package/dist/engine/logs-decoder.test.d.ts +1 -0
  24. package/dist/engine/logs-decoder.test.js +836 -0
  25. package/dist/engine/perp-instructions.d.ts +68 -0
  26. package/dist/engine/perp-instructions.js +478 -0
  27. package/dist/engine/perp-instructions.test.d.ts +1 -0
  28. package/dist/engine/perp-instructions.test.js +296 -0
  29. package/dist/engine/spot-instructions.d.ts +52 -0
  30. package/dist/engine/spot-instructions.js +376 -0
  31. package/dist/engine/spot-instructions.test.d.ts +1 -0
  32. package/dist/engine/spot-instructions.test.js +221 -0
  33. package/dist/engine/utils.d.ts +23 -0
  34. package/dist/engine/utils.js +329 -0
  35. package/dist/engine/utils.test.d.ts +1 -0
  36. package/dist/engine/utils.test.js +120 -0
  37. package/dist/index.d.ts +6 -247
  38. package/dist/index.js +14 -2925
  39. package/dist/instruction_models.d.ts +0 -2
  40. package/dist/instruction_models.js +39 -40
  41. package/dist/logs_models.d.ts +0 -2
  42. package/dist/types/engine-args.d.ts +32 -0
  43. package/dist/types/engine-args.js +2 -0
  44. package/dist/types/enums.d.ts +43 -0
  45. package/dist/{types.js → types/enums.js} +3 -5
  46. package/dist/types/index.d.ts +8 -0
  47. package/dist/types/index.js +38 -0
  48. package/dist/types/log-message.d.ts +2 -0
  49. package/dist/types/log-message.js +2 -0
  50. package/dist/types/responses.d.ts +248 -0
  51. package/dist/types/responses.js +2 -0
  52. package/dist/types/schemas.d.ts +165 -0
  53. package/dist/types/schemas.js +254 -0
  54. package/dist/types/schemas.test.d.ts +1 -0
  55. package/dist/types/schemas.test.js +94 -0
  56. package/dist/utils.d.ts +0 -0
  57. package/dist/utils.js +1 -0
  58. package/package.json +26 -6
  59. package/dist/types.d.ts +0 -565
package/dist/index.js CHANGED
@@ -13,2931 +13,20 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
13
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
16
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.Engine = exports.getPerpPriceStep = exports.getSpotPriceStep = void 0;
27
- const kit_1 = require("@solana/kit");
28
- const system_1 = require("@solana-program/system");
29
- const bs58_1 = require("bs58");
30
- const buffer_1 = require("buffer");
31
- const types_1 = require("./types");
32
- const structure_models_1 = require("./structure_models");
33
- const instruction_models_1 = require("./instruction_models");
34
- const base64_arraybuffer_1 = require("base64-arraybuffer");
35
- const logs_models_1 = require("./logs_models");
17
+ exports.AccountType = exports.getPerpPriceStep = exports.getSpotPriceStep = exports.MARKET_DEPTH = exports.PROGRAM_ID = exports.VERSION = exports.Engine = void 0;
18
+ var engine_1 = require("./engine");
19
+ Object.defineProperty(exports, "Engine", { enumerable: true, get: function () { return engine_1.Engine; } });
36
20
  __exportStar(require("./types"), exports);
21
+ var constants_1 = require("./constants");
22
+ Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return constants_1.VERSION; } });
23
+ Object.defineProperty(exports, "PROGRAM_ID", { enumerable: true, get: function () { return constants_1.PROGRAM_ID; } });
24
+ Object.defineProperty(exports, "MARKET_DEPTH", { enumerable: true, get: function () { return constants_1.MARKET_DEPTH; } });
25
+ var utils_1 = require("./engine/utils");
26
+ Object.defineProperty(exports, "getSpotPriceStep", { enumerable: true, get: function () { return utils_1.getSpotPriceStep; } });
27
+ Object.defineProperty(exports, "getPerpPriceStep", { enumerable: true, get: function () { return utils_1.getPerpPriceStep; } });
28
+ __exportStar(require("./structure_models"), exports);
29
+ var types_1 = require("./types");
30
+ Object.defineProperty(exports, "AccountType", { enumerable: true, get: function () { return types_1.AccountType; } });
37
31
  __exportStar(require("./logs_models"), exports);
38
- const ADDRESS_LOOKUP_TABLE_PROGRAM_ID = (0, kit_1.address)("AddressLookupTab1e1111111111111111111111111");
39
- const SYSTEM_PROGRAM_ID = (0, kit_1.address)("11111111111111111111111111111111");
40
- const TOKEN_PROGRAM_ID = (0, kit_1.address)('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
41
- const TOKEN_2022_PROGRAM_ID = (0, kit_1.address)('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
42
- const ASSOCIATED_TOKEN_PROGRAM_ID = (0, kit_1.address)('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
43
- let dec = 1000000000;
44
- let lpDec = 10000;
45
- const nullOrder = 0xFFFF;
46
- /**
47
- * Get price step between orderbook lines depending on curent price
48
- * @param price Current market price
49
- * @returns Price step
50
- */
51
- function getSpotPriceStep(price) {
52
- if (price <= 0.00001) {
53
- return 0.000000001;
54
- }
55
- else if (price <= 0.00002) {
56
- return 0.000000002;
57
- }
58
- else if (price <= 0.00005) {
59
- return 0.000000005;
60
- }
61
- else if (price <= 0.0001) {
62
- return 0.00000001;
63
- }
64
- else if (price <= 0.0002) {
65
- return 0.00000002;
66
- }
67
- else if (price <= 0.0005) {
68
- return 0.00000005;
69
- }
70
- else if (price <= 0.001) {
71
- return 0.0000001;
72
- }
73
- else if (price <= 0.002) {
74
- return 0.0000002;
75
- }
76
- else if (price <= 0.005) {
77
- return 0.0000005;
78
- }
79
- else if (price <= 0.01) {
80
- return 0.000001;
81
- }
82
- else if (price <= 0.02) {
83
- return 0.000002;
84
- }
85
- else if (price <= 0.05) {
86
- return 0.000005;
87
- }
88
- else if (price <= 0.1) {
89
- return 0.00001;
90
- }
91
- else if (price <= 0.2) {
92
- return 0.00002;
93
- }
94
- else if (price <= 0.5) {
95
- return 0.00005;
96
- }
97
- else if (price <= 1) {
98
- return 0.0001;
99
- }
100
- else if (price <= 2) {
101
- return 0.0002;
102
- }
103
- else if (price <= 5) {
104
- return 0.0005;
105
- }
106
- else if (price <= 10) {
107
- return 0.001;
108
- }
109
- else if (price <= 20) {
110
- return 0.002;
111
- }
112
- else if (price <= 50) {
113
- return 0.005;
114
- }
115
- else if (price <= 100) {
116
- return 0.01;
117
- }
118
- else if (price <= 200) {
119
- return 0.02;
120
- }
121
- else if (price <= 500) {
122
- return 0.05;
123
- }
124
- else if (price <= 1000) {
125
- return 0.1;
126
- }
127
- else if (price <= 2000) {
128
- return 0.2;
129
- }
130
- else if (price <= 5000) {
131
- return 0.5;
132
- }
133
- else if (price <= 10000) {
134
- return 1;
135
- }
136
- else if (price <= 20000) {
137
- return 2;
138
- }
139
- else if (price <= 50000) {
140
- return 5;
141
- }
142
- else if (price <= 100000) {
143
- return 10;
144
- }
145
- else if (price <= 200000) {
146
- return 20;
147
- }
148
- else if (price <= 500000) {
149
- return 50;
150
- }
151
- else if (price <= 1000000) {
152
- return 100;
153
- }
154
- else if (price <= 2000000) {
155
- return 200;
156
- }
157
- else if (price <= 5000000) {
158
- return 500;
159
- }
160
- else {
161
- return 1000;
162
- }
163
- }
164
- exports.getSpotPriceStep = getSpotPriceStep;
165
- /**
166
- * Get price step between orderbook lines depending on curent price
167
- * @param price Current market price
168
- * @returns Price step
169
- */
170
- function getPerpPriceStep(price) {
171
- if (price <= 0.00005) {
172
- return 0.000000001;
173
- }
174
- else if (price <= 0.0001) {
175
- return 0.000000002;
176
- }
177
- else if (price <= 0.0002) {
178
- return 0.000000005;
179
- }
180
- else if (price <= 0.0005) {
181
- return 0.00000001;
182
- }
183
- else if (price <= 0.001) {
184
- return 0.00000002;
185
- }
186
- else if (price <= 0.002) {
187
- return 0.00000005;
188
- }
189
- else if (price <= 0.005) {
190
- return 0.0000001;
191
- }
192
- else if (price <= 0.01) {
193
- return 0.0000002;
194
- }
195
- else if (price <= 0.02) {
196
- return 0.0000005;
197
- }
198
- else if (price <= 0.05) {
199
- return 0.000001;
200
- }
201
- else if (price <= 0.1) {
202
- return 0.000002;
203
- }
204
- else if (price <= 0.2) {
205
- return 0.000005;
206
- }
207
- else if (price <= 0.5) {
208
- return 0.00001;
209
- }
210
- else if (price <= 1) {
211
- return 0.00002;
212
- }
213
- else if (price <= 2) {
214
- return 0.00005;
215
- }
216
- else if (price <= 5) {
217
- return 0.0001;
218
- }
219
- else if (price <= 10) {
220
- return 0.0002;
221
- }
222
- else if (price <= 20) {
223
- return 0.0005;
224
- }
225
- else if (price <= 50) {
226
- return 0.001;
227
- }
228
- else if (price <= 100) {
229
- return 0.002;
230
- }
231
- else if (price <= 200) {
232
- return 0.005;
233
- }
234
- else if (price <= 500) {
235
- return 0.01;
236
- }
237
- else if (price <= 1000) {
238
- return 0.02;
239
- }
240
- else if (price <= 2000) {
241
- return 0.05;
242
- }
243
- else if (price <= 5000) {
244
- return 0.1;
245
- }
246
- else if (price <= 10000) {
247
- return 0.2;
248
- }
249
- else if (price <= 20000) {
250
- return 0.5;
251
- }
252
- else if (price <= 50000) {
253
- return 1;
254
- }
255
- else if (price <= 100000) {
256
- return 2;
257
- }
258
- else if (price <= 200000) {
259
- return 5;
260
- }
261
- else if (price <= 500000) {
262
- return 10;
263
- }
264
- else if (price <= 1000000) {
265
- return 20;
266
- }
267
- else if (price <= 2000000) {
268
- return 50;
269
- }
270
- else if (price <= 5000000) {
271
- return 100;
272
- }
273
- else if (price <= 10000000) {
274
- return 200;
275
- }
276
- else if (price <= 20000000) {
277
- return 500;
278
- }
279
- else {
280
- return 1000;
281
- }
282
- }
283
- exports.getPerpPriceStep = getPerpPriceStep;
284
- function perpSeatReserve(activeUsers) {
285
- return 250000 * activeUsers / (25000 - activeUsers);
286
- }
287
- function findAssociatedTokenAddress(owner, tokenProgramId, mint) {
288
- return __awaiter(this, void 0, void 0, function* () {
289
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
290
- programAddress: ASSOCIATED_TOKEN_PROGRAM_ID,
291
- seeds: [
292
- (0, kit_1.getAddressEncoder)().encode(owner),
293
- (0, kit_1.getAddressEncoder)().encode(tokenProgramId),
294
- (0, kit_1.getAddressEncoder)().encode(mint),
295
- ]
296
- }))[0];
297
- return address;
298
- });
299
- }
300
- function getMultipleSpotOrders(data, firstEntry, clientId) {
301
- let orders = [];
302
- let entry = firstEntry;
303
- while (entry != nullOrder) {
304
- const offset = entry * 64 + structure_models_1.SpotTradeAccountHeaderModel.LENGTH;
305
- const order = structure_models_1.OrderModel.fromBuffer(data, offset);
306
- if (order.origClientId != clientId) {
307
- break;
308
- }
309
- orders.push(order);
310
- entry = order.clNext;
311
- }
312
- return orders;
313
- }
314
- function getMultiplePerpOrders(data, firstEntry, clientId) {
315
- let orders = [];
316
- let entry = firstEntry;
317
- while (entry != nullOrder) {
318
- const offset = entry * 64 + structure_models_1.PerpTradeAccountHeaderModel.LENGTH;
319
- const order = structure_models_1.OrderModel.fromBuffer(data, offset);
320
- if (order.origClientId != clientId) {
321
- break;
322
- }
323
- orders.push(order);
324
- entry = order.clNext;
325
- }
326
- return orders;
327
- }
328
- function getLookupTableAddress(authority, slot) {
329
- return __awaiter(this, void 0, void 0, function* () {
330
- let buf = buffer_1.Buffer.alloc(8);
331
- buf.writeBigInt64LE(BigInt(slot), 0);
332
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
333
- programAddress: ADDRESS_LOOKUP_TABLE_PROGRAM_ID,
334
- seeds: [(0, kit_1.getAddressEncoder)().encode(authority), buf]
335
- }))[0];
336
- return address;
337
- });
338
- }
339
- /**
340
- * Main class to operate with Deriverse
341
- * @property {number} originalClientId Deriverse main client ID
342
- * @property {AddressLookupTableAccount} lut Root address lookup table account
343
- * @property {AddressLookupTableAccount} clientLut Client address lookup table account
344
- * @property {Map<number, Token>} tokens Tokens data
345
- * @property {Map<number, Instrument>} instruments Instruments data
346
- */
347
- class Engine {
348
- /**
349
- * @param rpc @solana/kit rpc
350
- */
351
- constructor(rpc, args) {
352
- this.rpc = rpc;
353
- if (args == undefined || args.programId == null || args.programId == undefined) {
354
- this.programId = types_1.PROGRAM_ID;
355
- }
356
- else {
357
- this.programId = args.programId;
358
- }
359
- if (args == undefined || args.version == null || args.version == undefined) {
360
- this.version = types_1.VERSION;
361
- }
362
- else {
363
- this.version = args.version;
364
- }
365
- if (args == undefined || args.commitment == null || args.commitment == undefined) {
366
- this.commitment = 'confirmed';
367
- }
368
- else {
369
- this.commitment = args.commitment;
370
- }
371
- if (args == undefined || args.uiNumbers == null || args.uiNumbers == undefined) {
372
- this.uiNumbers = true;
373
- }
374
- else {
375
- this.uiNumbers = args.uiNumbers;
376
- }
377
- if (!this.uiNumbers) {
378
- dec = 1;
379
- lpDec = 1;
380
- }
381
- }
382
- logsDecode(data) {
383
- let assetTokenDec = 1;
384
- let crncyTokenDec = 1;
385
- let logs = [];
386
- for (var log of data) {
387
- if (log.startsWith("Program returned error") || log.startsWith(`Program logged: "Error`)) {
388
- return [];
389
- }
390
- if (!log.startsWith("Program data: ")) {
391
- continue;
392
- }
393
- const buffer = buffer_1.Buffer.from((0, base64_arraybuffer_1.decode)(log.substring(14)));
394
- switch (buffer[0]) {
395
- case logs_models_1.LogType.deposit: {
396
- if (buffer.length == logs_models_1.DepositReportModel.LENGTH) {
397
- let report = logs_models_1.DepositReportModel.fromBuffer(buffer);
398
- if (this.uiNumbers) {
399
- crncyTokenDec = this.tokenDec(report.tokenId);
400
- report.amount /= crncyTokenDec;
401
- }
402
- logs.push(report);
403
- }
404
- break;
405
- }
406
- case logs_models_1.LogType.withdraw: {
407
- if (buffer.length == logs_models_1.WithdrawReportModel.LENGTH) {
408
- let report = logs_models_1.WithdrawReportModel.fromBuffer(buffer);
409
- if (this.uiNumbers) {
410
- crncyTokenDec = this.tokenDec(report.tokenId);
411
- report.amount /= crncyTokenDec;
412
- }
413
- logs.push(report);
414
- }
415
- break;
416
- }
417
- case logs_models_1.LogType.perpDeposit: {
418
- if (buffer.length == logs_models_1.PerpDepositReportModel.LENGTH) {
419
- let report = logs_models_1.PerpDepositReportModel.fromBuffer(buffer);
420
- if (this.uiNumbers) {
421
- const instrInfo = this.instruments.get(report.instrId);
422
- if (instrInfo) {
423
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
424
- report.amount /= crncyTokenDec;
425
- }
426
- }
427
- logs.push(report);
428
- }
429
- break;
430
- }
431
- case logs_models_1.LogType.buyMarketSeat: {
432
- if (buffer.length == logs_models_1.BuyMarketSeatReportModel.LENGTH) {
433
- let report = logs_models_1.BuyMarketSeatReportModel.fromBuffer(buffer);
434
- if (this.uiNumbers) {
435
- const instrInfo = this.instruments.get(report.instrId);
436
- if (instrInfo) {
437
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
438
- report.amount /= crncyTokenDec;
439
- report.seatPrice /= crncyTokenDec;
440
- }
441
- }
442
- logs.push(report);
443
- }
444
- break;
445
- }
446
- case logs_models_1.LogType.sellMarketSeat: {
447
- if (buffer.length == logs_models_1.SellMarketSeatReportModel.LENGTH) {
448
- let report = logs_models_1.SellMarketSeatReportModel.fromBuffer(buffer);
449
- if (this.uiNumbers) {
450
- const instrInfo = this.instruments.get(report.instrId);
451
- if (instrInfo) {
452
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
453
- report.seatPrice /= crncyTokenDec;
454
- }
455
- }
456
- logs.push(report);
457
- }
458
- break;
459
- }
460
- case logs_models_1.LogType.perpWithdraw: {
461
- if (buffer.length == logs_models_1.PerpWithdrawReportModel.LENGTH) {
462
- let report = logs_models_1.PerpWithdrawReportModel.fromBuffer(buffer);
463
- if (this.uiNumbers) {
464
- const instrInfo = this.instruments.get(report.instrId);
465
- if (instrInfo) {
466
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
467
- report.amount /= crncyTokenDec;
468
- }
469
- }
470
- logs.push(report);
471
- }
472
- break;
473
- }
474
- case logs_models_1.LogType.feesDeposit: {
475
- if (buffer.length == logs_models_1.FeesDepositReportModel.LENGTH) {
476
- let report = logs_models_1.FeesDepositReportModel.fromBuffer(buffer);
477
- if (this.uiNumbers) {
478
- crncyTokenDec = this.tokenDec(report.tokenId);
479
- report.amount /= crncyTokenDec;
480
- }
481
- logs.push(report);
482
- }
483
- break;
484
- }
485
- case logs_models_1.LogType.feesWithdraw: {
486
- if (buffer.length == logs_models_1.FeesWithdrawReportModel.LENGTH) {
487
- let report = logs_models_1.FeesWithdrawReportModel.fromBuffer(buffer);
488
- if (this.uiNumbers) {
489
- crncyTokenDec = this.tokenDec(report.tokenId);
490
- report.amount /= crncyTokenDec;
491
- }
492
- logs.push(report);
493
- }
494
- break;
495
- }
496
- case logs_models_1.LogType.spotLpTrade: {
497
- if (buffer.length == logs_models_1.SpotlpTradeReportModel.LENGTH) {
498
- let report = logs_models_1.SpotlpTradeReportModel.fromBuffer(buffer);
499
- if (this.uiNumbers) {
500
- const instrInfo = this.instruments.get(report.instrId);
501
- if (instrInfo) {
502
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
503
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
504
- report.qty /= lpDec;
505
- report.tokens /= assetTokenDec;
506
- report.crncy /= crncyTokenDec;
507
- }
508
- }
509
- logs.push(report);
510
- }
511
- break;
512
- }
513
- case logs_models_1.LogType.moveSpot: {
514
- if (buffer.length == logs_models_1.MoveSpotAvailFundsReportModel.LENGTH) {
515
- let report = logs_models_1.MoveSpotAvailFundsReportModel.fromBuffer(buffer);
516
- if (this.uiNumbers) {
517
- const instrInfo = this.instruments.get(report.instrId);
518
- if (instrInfo) {
519
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
520
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
521
- report.qty /= assetTokenDec;
522
- report.crncy /= crncyTokenDec;
523
- }
524
- }
525
- logs.push(report);
526
- }
527
- break;
528
- }
529
- case logs_models_1.LogType.earnings: {
530
- if (buffer.length == logs_models_1.EarningsReportModel.LENGTH) {
531
- let report = logs_models_1.EarningsReportModel.fromBuffer(buffer);
532
- if (this.uiNumbers) {
533
- crncyTokenDec = this.tokenDec(report.tokenId);
534
- report.amount /= crncyTokenDec;
535
- }
536
- logs.push(report);
537
- }
538
- break;
539
- }
540
- case logs_models_1.LogType.drvsAirdrop: {
541
- if (buffer.length == logs_models_1.DrvsAirdropReportModel.LENGTH) {
542
- let report = logs_models_1.DrvsAirdropReportModel.fromBuffer(buffer);
543
- if (this.uiNumbers) {
544
- crncyTokenDec = this.tokenDec(0);
545
- report.amount /= crncyTokenDec;
546
- }
547
- logs.push(report);
548
- }
549
- break;
550
- }
551
- case logs_models_1.LogType.spotPlaceOrder: {
552
- if (buffer.length == logs_models_1.SpotPlaceOrderReportModel.LENGTH) {
553
- let report = logs_models_1.SpotPlaceOrderReportModel.fromBuffer(buffer);
554
- if (this.uiNumbers) {
555
- const instrInfo = this.instruments.get(report.instrId);
556
- if (instrInfo) {
557
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
558
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
559
- report.qty /= assetTokenDec;
560
- }
561
- report.price /= dec;
562
- }
563
- logs.push(report);
564
- }
565
- break;
566
- }
567
- case logs_models_1.LogType.spotFillOrder: {
568
- if (buffer.length == logs_models_1.SpotFillOrderReportModel.LENGTH) {
569
- let report = logs_models_1.SpotFillOrderReportModel.fromBuffer(buffer);
570
- if (this.uiNumbers) {
571
- report.qty /= assetTokenDec;
572
- report.crncy /= crncyTokenDec;
573
- report.rebates /= crncyTokenDec;
574
- report.price /= dec;
575
- }
576
- logs.push(report);
577
- }
578
- break;
579
- }
580
- case logs_models_1.LogType.spotNewOrder: {
581
- if (buffer.length == logs_models_1.SpotNewOrderReportModel.LENGTH) {
582
- let report = logs_models_1.SpotNewOrderReportModel.fromBuffer(buffer);
583
- if (this.uiNumbers) {
584
- report.qty /= assetTokenDec;
585
- report.crncy /= crncyTokenDec;
586
- }
587
- logs.push(report);
588
- }
589
- break;
590
- }
591
- case logs_models_1.LogType.spotOrderCancel: {
592
- if (buffer.length == logs_models_1.SpotOrderCancelReportModel.LENGTH) {
593
- let report = logs_models_1.SpotOrderCancelReportModel.fromBuffer(buffer);
594
- if (this.uiNumbers) {
595
- const instrInfo = this.instruments.get(report.instrId);
596
- if (instrInfo) {
597
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
598
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
599
- report.qty /= assetTokenDec;
600
- report.crncy /= crncyTokenDec;
601
- }
602
- }
603
- logs.push(report);
604
- }
605
- break;
606
- }
607
- case logs_models_1.LogType.spotOrderRevoke: {
608
- if (buffer.length == logs_models_1.SpotOrderRevokeReportModel.LENGTH) {
609
- let report = logs_models_1.SpotOrderRevokeReportModel.fromBuffer(buffer);
610
- if (this.uiNumbers) {
611
- report.qty /= assetTokenDec;
612
- report.crncy /= crncyTokenDec;
613
- }
614
- logs.push(report);
615
- }
616
- break;
617
- }
618
- case logs_models_1.LogType.spotFees: {
619
- if (buffer.length == logs_models_1.SpotFeesReportModel.LENGTH) {
620
- let report = logs_models_1.SpotFeesReportModel.fromBuffer(buffer);
621
- if (this.uiNumbers) {
622
- report.fees /= crncyTokenDec;
623
- report.refPayment /= crncyTokenDec;
624
- }
625
- logs.push(report);
626
- }
627
- break;
628
- }
629
- case logs_models_1.LogType.spotPlaceMassCancel: {
630
- if (buffer.length == logs_models_1.SpotPlaceMassCancelReportModel.LENGTH) {
631
- let report = logs_models_1.SpotPlaceMassCancelReportModel.fromBuffer(buffer);
632
- if (this.uiNumbers) {
633
- const instrInfo = this.instruments.get(report.instrId);
634
- if (instrInfo) {
635
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
636
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
637
- }
638
- }
639
- logs.push(report);
640
- }
641
- break;
642
- }
643
- case logs_models_1.LogType.spotMassCancel: {
644
- if (buffer.length == logs_models_1.SpotMassCancelReportModel.LENGTH) {
645
- let report = logs_models_1.SpotMassCancelReportModel.fromBuffer(buffer);
646
- if (this.uiNumbers) {
647
- report.qty /= assetTokenDec;
648
- report.crncy /= crncyTokenDec;
649
- }
650
- logs.push(report);
651
- }
652
- break;
653
- }
654
- case logs_models_1.LogType.perpPlaceOrder: {
655
- if (buffer.length == logs_models_1.PerpPlaceOrderReportModel.LENGTH) {
656
- let report = logs_models_1.PerpPlaceOrderReportModel.fromBuffer(buffer);
657
- if (this.uiNumbers) {
658
- const instrInfo = this.instruments.get(report.instrId);
659
- if (instrInfo) {
660
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
661
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
662
- report.perps /= assetTokenDec;
663
- }
664
- report.price /= dec;
665
- }
666
- logs.push(report);
667
- }
668
- break;
669
- }
670
- case logs_models_1.LogType.perpFillOrder: {
671
- if (buffer.length == logs_models_1.PerpFillOrderReportModel.LENGTH) {
672
- let report = logs_models_1.PerpFillOrderReportModel.fromBuffer(buffer);
673
- if (this.uiNumbers) {
674
- report.perps /= assetTokenDec;
675
- report.crncy /= crncyTokenDec;
676
- report.rebates /= crncyTokenDec;
677
- report.price /= dec;
678
- }
679
- logs.push(report);
680
- }
681
- break;
682
- }
683
- case logs_models_1.LogType.perpNewOrder: {
684
- if (buffer.length == logs_models_1.PerpNewOrderReportModel.LENGTH) {
685
- let report = logs_models_1.PerpNewOrderReportModel.fromBuffer(buffer);
686
- if (this.uiNumbers) {
687
- report.perps /= assetTokenDec;
688
- report.crncy /= crncyTokenDec;
689
- }
690
- logs.push(report);
691
- }
692
- break;
693
- }
694
- case logs_models_1.LogType.perpOrderCancel: {
695
- if (buffer.length == logs_models_1.PerpOrderCancelReportModel.LENGTH) {
696
- let report = logs_models_1.PerpOrderCancelReportModel.fromBuffer(buffer);
697
- if (this.uiNumbers) {
698
- const instrInfo = this.instruments.get(report.instrId);
699
- if (instrInfo) {
700
- assetTokenDec = this.tokenDec(instrInfo.header.assetTokenId);
701
- crncyTokenDec = this.tokenDec(instrInfo.header.crncyTokenId);
702
- report.perps /= assetTokenDec;
703
- report.crncy /= crncyTokenDec;
704
- }
705
- }
706
- logs.push(report);
707
- }
708
- break;
709
- }
710
- case logs_models_1.LogType.perpOrderRevoke: {
711
- if (buffer.length == logs_models_1.PerpOrderRevokeReportModel.LENGTH) {
712
- let report = logs_models_1.PerpOrderRevokeReportModel.fromBuffer(buffer);
713
- if (this.uiNumbers) {
714
- report.perps /= assetTokenDec;
715
- report.crncy /= crncyTokenDec;
716
- }
717
- logs.push(report);
718
- }
719
- break;
720
- }
721
- case logs_models_1.LogType.perpFees: {
722
- if (buffer.length == logs_models_1.PerpFeesReportModel.LENGTH) {
723
- let report = logs_models_1.PerpFeesReportModel.fromBuffer(buffer);
724
- if (this.uiNumbers) {
725
- report.fees /= crncyTokenDec;
726
- report.refPayment /= crncyTokenDec;
727
- }
728
- logs.push(report);
729
- }
730
- break;
731
- }
732
- case logs_models_1.LogType.perpPlaceMassCancel: {
733
- if (buffer.length == logs_models_1.PerpPlaceMassCancelReportModel.LENGTH) {
734
- let report = logs_models_1.PerpPlaceMassCancelReportModel.fromBuffer(buffer);
735
- logs.push(report);
736
- }
737
- break;
738
- }
739
- case logs_models_1.LogType.perpMassCancel: {
740
- if (buffer.length == logs_models_1.PerpMassCancelReportModel.LENGTH) {
741
- let report = logs_models_1.PerpMassCancelReportModel.fromBuffer(buffer);
742
- if (this.uiNumbers) {
743
- report.perps /= assetTokenDec;
744
- report.crncy /= crncyTokenDec;
745
- }
746
- logs.push(report);
747
- }
748
- break;
749
- }
750
- case logs_models_1.LogType.perpFunding: {
751
- if (buffer.length == logs_models_1.PerpFundingReportModel.LENGTH) {
752
- let report = logs_models_1.PerpFundingReportModel.fromBuffer(buffer);
753
- if (this.uiNumbers) {
754
- report.funding /= crncyTokenDec;
755
- }
756
- logs.push(report);
757
- }
758
- break;
759
- }
760
- case logs_models_1.LogType.perpSocLoss: {
761
- if (buffer.length == logs_models_1.PerpSocLossReportModel.LENGTH) {
762
- let report = logs_models_1.PerpSocLossReportModel.fromBuffer(buffer);
763
- if (this.uiNumbers) {
764
- report.socLoss /= crncyTokenDec;
765
- }
766
- logs.push(report);
767
- }
768
- break;
769
- }
770
- case logs_models_1.LogType.perpChangeLeverage: {
771
- if (buffer.length == logs_models_1.PerpChangeLeverageReportModel.LENGTH) {
772
- let report = logs_models_1.PerpChangeLeverageReportModel.fromBuffer(buffer);
773
- logs.push(report);
774
- }
775
- break;
776
- }
777
- }
778
- }
779
- return logs;
780
- }
781
- findAccountsByTag(tag, dataSlice) {
782
- return __awaiter(this, void 0, void 0, function* () {
783
- let tagBuf = buffer_1.Buffer.alloc(8);
784
- tagBuf.writeUInt32LE(tag, 0);
785
- tagBuf.writeUInt32LE(this.version, 4);
786
- let accounts = yield this.rpc.getProgramAccounts(this.programId, {
787
- encoding: 'base64',
788
- dataSlice: dataSlice,
789
- filters: [
790
- {
791
- memcmp: {
792
- offset: BigInt(0),
793
- encoding: 'base58',
794
- bytes: (0, bs58_1.encode)(tagBuf),
795
- },
796
- },
797
- ],
798
- }).send();
799
- return accounts;
800
- });
801
- }
802
- /**
803
- * After creation you have to initialize Engine
804
- */
805
- initialize() {
806
- return __awaiter(this, void 0, void 0, function* () {
807
- try {
808
- this.drvsAuthority = (yield (0, kit_1.getProgramDerivedAddress)({ programAddress: this.programId, seeds: ["ndxnt"] }))[0];
809
- this.rootAccount = yield this.getAccountByTag(types_1.AccountType.ROOT);
810
- this.communityAccount = yield this.getAccountByTag(types_1.AccountType.COMMUNITY);
811
- const infos = yield this.rpc.getMultipleAccounts([this.rootAccount, this.communityAccount], {
812
- commitment: this.commitment,
813
- encoding: 'base64'
814
- }).send();
815
- if (infos.value == null) {
816
- throw new Error("Initialization failed: getMultipleAccountsInfo");
817
- }
818
- this.rootStateModel = structure_models_1.RootStateModel.fromBuffer(infos.value[0].data);
819
- this.tokens = new Map();
820
- this.instruments = new Map();
821
- this.privateMode = (this.rootStateModel.mask & 1) != 0;
822
- const tokenAccounts = yield this.findAccountsByTag(types_1.AccountType.TOKEN);
823
- tokenAccounts.forEach((t) => {
824
- let tokenStateModel = structure_models_1.TokenStateModel.fromBuffer(t.account.data);
825
- this.tokens.set(tokenStateModel.id, tokenStateModel);
826
- });
827
- const instrAccounts = yield this.findAccountsByTag(types_1.AccountType.INSTR, { offset: 8, length: 16 });
828
- instrAccounts.forEach((response) => {
829
- const buffer = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(response.account.data[0]));
830
- let instrAccountHeaderModel = new structure_models_1.InstrAccountHeaderModel();
831
- instrAccountHeaderModel.instrId = buffer.readUint32LE(0);
832
- instrAccountHeaderModel.assetTokenId = buffer.readUint32LE(4);
833
- instrAccountHeaderModel.crncyTokenId = buffer.readUint32LE(8);
834
- instrAccountHeaderModel.mask = buffer.readUint32LE(12);
835
- this.instruments.set(instrAccountHeaderModel.instrId, {
836
- address: response.pubkey,
837
- header: instrAccountHeaderModel,
838
- spotBids: [],
839
- spotAsks: [],
840
- perpBids: [],
841
- perpAsks: [],
842
- });
843
- });
844
- this.updateCommunityFromBuffer(infos.value[1].data);
845
- return true;
846
- }
847
- catch (err) {
848
- console.log("Initialization failed:", err);
849
- return false;
850
- }
851
- });
852
- }
853
- addToken(tokenAccount) {
854
- return __awaiter(this, void 0, void 0, function* () {
855
- const info = yield this.rpc.getAccountInfo(tokenAccount, { commitment: this.commitment, encoding: 'base64' }).send();
856
- if (info.value == null) {
857
- throw new Error("Add Token Failed: getAccountInfo");
858
- }
859
- const tokenStateModel = structure_models_1.TokenStateModel.fromBuffer(info.value.data);
860
- if (tokenStateModel.id > this.rootStateModel.tokensCount ||
861
- tokenStateModel.tag != types_1.AccountType.TOKEN ||
862
- tokenStateModel.version != this.version) {
863
- throw new Error("Invalid Token Account");
864
- }
865
- this.tokens.set(tokenStateModel.id, tokenStateModel);
866
- });
867
- }
868
- addInstr(instrAccount) {
869
- return __awaiter(this, void 0, void 0, function* () {
870
- const info = yield this.rpc.getAccountInfo(instrAccount, { commitment: this.commitment, encoding: 'base64' }).send();
871
- if (info.value == null) {
872
- throw new Error("Add Instrument Failed: getAccountInfo");
873
- }
874
- const instrAccountHeaderModel = structure_models_1.InstrAccountHeaderModel.fromBuffer(info.value.data);
875
- if (instrAccountHeaderModel.instrId > this.rootStateModel.instrCount ||
876
- instrAccountHeaderModel.tag != types_1.AccountType.INSTR ||
877
- instrAccountHeaderModel.version != this.version) {
878
- throw new Error("Invalid Instrument Account");
879
- }
880
- this.instruments.set(instrAccountHeaderModel.instrId, {
881
- address: instrAccount,
882
- header: instrAccountHeaderModel,
883
- spotBids: [],
884
- spotAsks: [],
885
- perpBids: [],
886
- perpAsks: [],
887
- });
888
- });
889
- }
890
- updateCommunityFromBuffer(data) {
891
- let baseCrncyRecords = new Map();
892
- let communityAccountHeaderModel = structure_models_1.CommunityAccountHeaderModel.fromBuffer(data);
893
- const drvsDec = this.tokenDec(0);
894
- communityAccountHeaderModel.prevVotingSupply /= drvsDec;
895
- communityAccountHeaderModel.votingSupply /= drvsDec;
896
- communityAccountHeaderModel.drvsTokens /= drvsDec;
897
- for (var i = 0; i < communityAccountHeaderModel.count; ++i) {
898
- let record = structure_models_1.BaseCrncyRecordModel.fromBuffer(data, structure_models_1.CommunityAccountHeaderModel.LENGTH + i * structure_models_1.BaseCrncyRecordModel.LENGTH);
899
- record.funds /= this.tokenDec(record.crncyTokenId);
900
- baseCrncyRecords.set(record.crncyTokenId, record);
901
- }
902
- this.community = {
903
- header: communityAccountHeaderModel,
904
- data: baseCrncyRecords
905
- };
906
- }
907
- updateCommunity() {
908
- return __awaiter(this, void 0, void 0, function* () {
909
- const info = yield this.rpc.getAccountInfo(this.communityAccount, { commitment: this.commitment, encoding: 'base64' }).send();
910
- if (info.value == null) {
911
- throw new Error("Community Account: GetAccountInfo Failed");
912
- }
913
- this.updateCommunityFromBuffer(info.value.data);
914
- });
915
- }
916
- updateRootFromBuffer(data) {
917
- this.rootStateModel = structure_models_1.RootStateModel.fromBuffer(data);
918
- }
919
- updateRoot() {
920
- return __awaiter(this, void 0, void 0, function* () {
921
- const info = yield this.rpc.getAccountInfo(this.rootAccount, { commitment: this.commitment, encoding: 'base64' }).send();
922
- if (info.value == null) {
923
- throw new Error("Root Account: GetAccountInfo Failed");
924
- }
925
- this.updateRootFromBuffer(info.value.data);
926
- });
927
- }
928
- getInstrAccountByTag(args) {
929
- return __awaiter(this, void 0, void 0, function* () {
930
- let buf = buffer_1.Buffer.alloc(16);
931
- buf.writeInt32LE(this.version, 0);
932
- buf.writeInt32LE(args.tag, 4);
933
- buf.writeInt32LE(args.assetTokenId, 8);
934
- buf.writeInt32LE(args.crncyTokenId, 12);
935
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
936
- programAddress: this.programId,
937
- seeds: [buf, (0, kit_1.getAddressEncoder)().encode(this.drvsAuthority)]
938
- }))[0];
939
- return address;
940
- });
941
- }
942
- getAccountByTag(tag) {
943
- return __awaiter(this, void 0, void 0, function* () {
944
- let buf = buffer_1.Buffer.alloc(8);
945
- buf.writeInt32LE(this.version, 0);
946
- buf.writeInt32LE(tag, 4);
947
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
948
- programAddress: this.programId,
949
- seeds: [buf, (0, kit_1.getAddressEncoder)().encode(this.drvsAuthority)]
950
- }))[0];
951
- return address;
952
- });
953
- }
954
- getSpotContext(instrAccountHeaderModel) {
955
- return __awaiter(this, void 0, void 0, function* () {
956
- return [
957
- {
958
- address: yield this.getInstrAccountByTag({
959
- assetTokenId: instrAccountHeaderModel.assetTokenId,
960
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
961
- tag: types_1.AccountType.INSTR
962
- }),
963
- role: kit_1.AccountRole.WRITABLE
964
- },
965
- {
966
- address: yield this.getInstrAccountByTag({
967
- assetTokenId: instrAccountHeaderModel.assetTokenId,
968
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
969
- tag: types_1.AccountType.SPOT_BIDS_TREE
970
- }),
971
- role: kit_1.AccountRole.WRITABLE
972
- },
973
- {
974
- address: yield this.getInstrAccountByTag({
975
- assetTokenId: instrAccountHeaderModel.assetTokenId,
976
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
977
- tag: types_1.AccountType.SPOT_ASKS_TREE
978
- }),
979
- role: kit_1.AccountRole.WRITABLE
980
- },
981
- {
982
- address: yield this.getInstrAccountByTag({
983
- assetTokenId: instrAccountHeaderModel.assetTokenId,
984
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
985
- tag: types_1.AccountType.SPOT_BID_ORDERS
986
- }),
987
- role: kit_1.AccountRole.WRITABLE
988
- },
989
- {
990
- address: yield this.getInstrAccountByTag({
991
- assetTokenId: instrAccountHeaderModel.assetTokenId,
992
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
993
- tag: types_1.AccountType.SPOT_ASK_ORDERS
994
- }),
995
- role: kit_1.AccountRole.WRITABLE
996
- },
997
- {
998
- address: yield this.getInstrAccountByTag({
999
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1000
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1001
- tag: types_1.AccountType.SPOT_LINES
1002
- }),
1003
- role: kit_1.AccountRole.WRITABLE
1004
- },
1005
- {
1006
- address: instrAccountHeaderModel.mapsAddress,
1007
- role: kit_1.AccountRole.WRITABLE
1008
- },
1009
- {
1010
- address: yield this.getInstrAccountByTag({
1011
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1012
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1013
- tag: types_1.AccountType.SPOT_CLIENT_INFOS
1014
- }),
1015
- role: kit_1.AccountRole.WRITABLE
1016
- },
1017
- {
1018
- address: yield this.getInstrAccountByTag({
1019
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1020
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1021
- tag: types_1.AccountType.SPOT_CLIENT_INFOS2
1022
- }),
1023
- role: kit_1.AccountRole.WRITABLE
1024
- },
1025
- ];
1026
- });
1027
- }
1028
- getPerpContext(instrAccountHeaderModel) {
1029
- return __awaiter(this, void 0, void 0, function* () {
1030
- return [
1031
- {
1032
- address: yield this.getInstrAccountByTag({
1033
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1034
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1035
- tag: types_1.AccountType.INSTR
1036
- }),
1037
- role: kit_1.AccountRole.WRITABLE
1038
- },
1039
- {
1040
- address: yield this.getInstrAccountByTag({
1041
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1042
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1043
- tag: types_1.AccountType.PERP_BIDS_TREE
1044
- }),
1045
- role: kit_1.AccountRole.WRITABLE
1046
- },
1047
- {
1048
- address: yield this.getInstrAccountByTag({
1049
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1050
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1051
- tag: types_1.AccountType.PERP_ASKS_TREE
1052
- }),
1053
- role: kit_1.AccountRole.WRITABLE
1054
- },
1055
- {
1056
- address: yield this.getInstrAccountByTag({
1057
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1058
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1059
- tag: types_1.AccountType.PERP_BID_ORDERS
1060
- }),
1061
- role: kit_1.AccountRole.WRITABLE
1062
- },
1063
- {
1064
- address: yield this.getInstrAccountByTag({
1065
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1066
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1067
- tag: types_1.AccountType.PERP_ASK_ORDERS
1068
- }),
1069
- role: kit_1.AccountRole.WRITABLE
1070
- },
1071
- {
1072
- address: yield this.getInstrAccountByTag({
1073
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1074
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1075
- tag: types_1.AccountType.PERP_LINES
1076
- }),
1077
- role: kit_1.AccountRole.WRITABLE
1078
- },
1079
- {
1080
- address: instrAccountHeaderModel.perpMapsAddress,
1081
- role: kit_1.AccountRole.WRITABLE
1082
- },
1083
- {
1084
- address: yield this.getInstrAccountByTag({
1085
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1086
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1087
- tag: types_1.AccountType.PERP_CLIENT_INFOS
1088
- }),
1089
- role: kit_1.AccountRole.WRITABLE
1090
- },
1091
- {
1092
- address: yield this.getInstrAccountByTag({
1093
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1094
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1095
- tag: types_1.AccountType.PERP_CLIENT_INFOS2
1096
- }),
1097
- role: kit_1.AccountRole.WRITABLE
1098
- },
1099
- {
1100
- address: yield this.getInstrAccountByTag({
1101
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1102
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1103
- tag: types_1.AccountType.PERP_CLIENT_INFOS3
1104
- }),
1105
- role: kit_1.AccountRole.WRITABLE
1106
- },
1107
- {
1108
- address: yield this.getInstrAccountByTag({
1109
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1110
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1111
- tag: types_1.AccountType.PERP_CLIENT_INFOS4
1112
- }),
1113
- role: kit_1.AccountRole.WRITABLE
1114
- },
1115
- {
1116
- address: yield this.getInstrAccountByTag({
1117
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1118
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1119
- tag: types_1.AccountType.PERP_CLIENT_INFOS5
1120
- }),
1121
- role: kit_1.AccountRole.WRITABLE
1122
- },
1123
- {
1124
- address: yield this.getInstrAccountByTag({
1125
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1126
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1127
- tag: types_1.AccountType.PERP_LONG_PX_TREE
1128
- }),
1129
- role: kit_1.AccountRole.WRITABLE
1130
- },
1131
- {
1132
- address: yield this.getInstrAccountByTag({
1133
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1134
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1135
- tag: types_1.AccountType.PERP_SHORT_PX_TREE
1136
- }),
1137
- role: kit_1.AccountRole.WRITABLE
1138
- },
1139
- {
1140
- address: yield this.getInstrAccountByTag({
1141
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1142
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1143
- tag: types_1.AccountType.PERP_REBALANCE_TIME_TREE
1144
- }),
1145
- role: kit_1.AccountRole.WRITABLE
1146
- },
1147
- ];
1148
- });
1149
- }
1150
- getSpotCandles(instrAccountHeaderModel) {
1151
- return __awaiter(this, void 0, void 0, function* () {
1152
- return [
1153
- {
1154
- address: yield this.getInstrAccountByTag({
1155
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1156
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1157
- tag: types_1.AccountType.SPOT_1M_CANDLES
1158
- }),
1159
- role: kit_1.AccountRole.WRITABLE
1160
- },
1161
- {
1162
- address: yield this.getInstrAccountByTag({
1163
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1164
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1165
- tag: types_1.AccountType.SPOT_15M_CANDLES
1166
- }),
1167
- role: kit_1.AccountRole.WRITABLE
1168
- },
1169
- {
1170
- address: yield this.getInstrAccountByTag({
1171
- assetTokenId: instrAccountHeaderModel.assetTokenId,
1172
- crncyTokenId: instrAccountHeaderModel.crncyTokenId,
1173
- tag: types_1.AccountType.SPOT_DAY_CANDLES
1174
- }),
1175
- role: kit_1.AccountRole.WRITABLE
1176
- },
1177
- ];
1178
- });
1179
- }
1180
- getTokenAccount(mint) {
1181
- return __awaiter(this, void 0, void 0, function* () {
1182
- let buf = buffer_1.Buffer.from((0, kit_1.getAddressEncoder)().encode(mint).buffer);
1183
- buf.writeInt32LE(this.version, 28);
1184
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
1185
- programAddress: this.programId,
1186
- seeds: [buf, (0, kit_1.getAddressEncoder)().encode(this.drvsAuthority)]
1187
- }))[0];
1188
- return address;
1189
- });
1190
- }
1191
- /**
1192
- * Get Token ID from mint public key if this token registered on Deriverse
1193
- * @param mint Public key
1194
- * @returns Token ID
1195
- */
1196
- getTokenId(mint) {
1197
- return __awaiter(this, void 0, void 0, function* () {
1198
- const tokenAddress = yield this.getTokenAccount(mint);
1199
- let info = yield this.rpc.getAccountInfo(tokenAddress, { commitment: this.commitment, encoding: 'base64', dataSlice: { offset: structure_models_1.TokenStateModel.OFFSET_ID, length: 4 } }).send();
1200
- if (!info.value) {
1201
- return null;
1202
- }
1203
- else {
1204
- const data = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(info.value.data[0]));
1205
- return data.readUInt32LE(0);
1206
- }
1207
- });
1208
- }
1209
- /**
1210
- * Get intrument ID if this instrument registered on Deriverse
1211
- * @param args Base crncy Token ID and asset token ID
1212
- * @returns Instrument ID
1213
- */
1214
- getInstrId(args) {
1215
- return __awaiter(this, void 0, void 0, function* () {
1216
- let buf = buffer_1.Buffer.alloc(16);
1217
- buf.writeInt32LE(this.version, 0);
1218
- buf.writeInt32LE(types_1.AccountType.INSTR, 4);
1219
- buf.writeInt32LE(args.assetTokenId, 8);
1220
- buf.writeInt32LE(args.crncyTokenId, 12);
1221
- const instrAddress = yield this.getInstrAccountByTag({
1222
- assetTokenId: args.assetTokenId,
1223
- crncyTokenId: args.crncyTokenId,
1224
- tag: types_1.AccountType.INSTR
1225
- });
1226
- let info = yield this.rpc.getAccountInfo(instrAddress, { commitment: this.commitment, encoding: 'base64', dataSlice: { offset: structure_models_1.InstrAccountHeaderModel.OFFSET_INSTR_ID, length: 4 } }).send();
1227
- if (info.value == null) {
1228
- return null;
1229
- }
1230
- else {
1231
- const data = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(info.value.data[0]));
1232
- return data.readUInt32LE(0);
1233
- }
1234
- });
1235
- }
1236
- /**
1237
- * Assignes client public key to Engine
1238
- * @param signer Client public key
1239
- */
1240
- setSigner(signer) {
1241
- return __awaiter(this, void 0, void 0, function* () {
1242
- this.signer = signer;
1243
- let buf = buffer_1.Buffer.alloc(8);
1244
- buf.writeUint32LE(this.version, 0);
1245
- buf.writeUint32LE(types_1.AccountType.CLIENT_PRIMARY, 4);
1246
- const clientPrimaryAccount = yield this.findClientPrimaryAccount(signer);
1247
- let exists = false;
1248
- try {
1249
- const info = yield this.rpc.getAccountInfo(clientPrimaryAccount, {
1250
- commitment: this.commitment,
1251
- encoding: 'base64'
1252
- }).send();
1253
- if (info.value) {
1254
- const clientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(info.value.data);
1255
- if (clientPrimaryAccountHeaderModel.walletAddress == signer) {
1256
- this.clientPrimaryAccount = clientPrimaryAccount;
1257
- this.clientCommunityAccount = yield this.findClientCommunityAccount(signer);
1258
- this.originalClientId = clientPrimaryAccountHeaderModel.id;
1259
- this.clientLutAddress = clientPrimaryAccountHeaderModel.lutAddress;
1260
- let date = Math.floor((new Date()).valueOf() / 1000);
1261
- if (date < clientPrimaryAccountHeaderModel.refProgramExpiration) {
1262
- this.refClientPrimaryAccount = clientPrimaryAccountHeaderModel.refAddress;
1263
- let refInfo = yield this.rpc.getAccountInfo(this.refClientPrimaryAccount, {
1264
- commitment: this.commitment,
1265
- encoding: 'base64'
1266
- }).send();
1267
- const refClientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(refInfo.value.data);
1268
- this.refClientCommunityAccount =
1269
- yield this.findClientCommunityAccount(refClientPrimaryAccountHeaderModel.walletAddress);
1270
- }
1271
- exists = true;
1272
- }
1273
- }
1274
- }
1275
- catch (err) {
1276
- console.log(err);
1277
- throw new Error("Wallet connection failed");
1278
- }
1279
- if (!exists) {
1280
- this.clientPrimaryAccount = null;
1281
- this.originalClientId = null;
1282
- }
1283
- });
1284
- }
1285
- findClientPrimaryAccount(wallet) {
1286
- return __awaiter(this, void 0, void 0, function* () {
1287
- let tagBuf = buffer_1.Buffer.alloc(8);
1288
- tagBuf.writeUint32LE(this.version, 0);
1289
- tagBuf.writeUint32LE(types_1.AccountType.CLIENT_PRIMARY, 4);
1290
- let source = (wallet == null || wallet == undefined) ? this.signer : wallet;
1291
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
1292
- programAddress: this.programId,
1293
- seeds: [tagBuf, (0, kit_1.getAddressEncoder)().encode(source)]
1294
- }))[0];
1295
- return address;
1296
- });
1297
- }
1298
- findClientCommunityAccount(wallet) {
1299
- return __awaiter(this, void 0, void 0, function* () {
1300
- let tagBuf = buffer_1.Buffer.alloc(8);
1301
- tagBuf.writeUint32LE(this.version, 0);
1302
- tagBuf.writeUint32LE(types_1.AccountType.CLIENT_COMMUNITY, 4);
1303
- let source = (wallet == null || wallet == undefined) ? this.signer : wallet;
1304
- const address = (yield (0, kit_1.getProgramDerivedAddress)({
1305
- programAddress: this.programId,
1306
- seeds: [tagBuf, (0, kit_1.getAddressEncoder)().encode(source)]
1307
- }))[0];
1308
- return address;
1309
- });
1310
- }
1311
- checkClient() {
1312
- return __awaiter(this, void 0, void 0, function* () {
1313
- if (this.signer == null) {
1314
- throw new Error("Wallet not connected");
1315
- }
1316
- if (this.clientPrimaryAccount != null) {
1317
- return true;
1318
- }
1319
- const clientPrimaryAccount = yield this.findClientPrimaryAccount();
1320
- try {
1321
- const info = yield this.rpc.getAccountInfo(clientPrimaryAccount, {
1322
- commitment: this.commitment,
1323
- encoding: 'base64'
1324
- }).send();
1325
- if (info.value == null) {
1326
- return false;
1327
- }
1328
- const clientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(info.value.data);
1329
- this.clientPrimaryAccount = clientPrimaryAccount;
1330
- this.clientCommunityAccount = yield this.findClientCommunityAccount();
1331
- this.originalClientId = clientPrimaryAccountHeaderModel.id;
1332
- return true;
1333
- }
1334
- catch (err) {
1335
- console.log(err);
1336
- return false;
1337
- }
1338
- });
1339
- }
1340
- /**
1341
- * Unpack client accounts
1342
- * @returns All client data that are in client accounts
1343
- */
1344
- getClientData() {
1345
- return __awaiter(this, void 0, void 0, function* () {
1346
- if (!(yield this.checkClient())) {
1347
- throw new Error("Client account not found");
1348
- }
1349
- const infos = yield this.rpc.getMultipleAccounts([this.clientPrimaryAccount, this.clientCommunityAccount], {
1350
- commitment: this.commitment,
1351
- encoding: 'base64'
1352
- }).send();
1353
- if (infos.value == null) {
1354
- throw new Error("GetClientData: GetAccountInfo failed");
1355
- }
1356
- const clientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(infos.value[0].data);
1357
- let clientCommunityAccountHeaderModel = structure_models_1.ClientCommunityAccountHeaderModel.fromBuffer(infos.value[1].data);
1358
- const primaryData = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(infos.value[0].data[0]));
1359
- let tokens = new Map();
1360
- let lp = new Map();
1361
- let spot = new Map();
1362
- let perp = new Map();
1363
- for (var i = 0; i < clientPrimaryAccountHeaderModel.assetsCount; ++i) {
1364
- const offset = structure_models_1.ClientPrimaryAccountHeaderModel.LENGTH + i * 16;
1365
- const assetInfo = primaryData.readUint32LE(offset);
1366
- const tag = assetInfo >> 28;
1367
- const id = assetInfo & 0xFFFFFFF;
1368
- if (tag == 1) {
1369
- tokens.set(id, {
1370
- tokenId: id,
1371
- amount: Number(primaryData.readBigInt64LE(offset + 8)) / this.tokenDec(id)
1372
- });
1373
- }
1374
- else if (tag == 2) {
1375
- lp.set(id, {
1376
- instrId: id,
1377
- amount: Number(primaryData.readBigInt64LE(offset + 8)) / lpDec
1378
- });
1379
- }
1380
- else if (tag == 3) {
1381
- const clientId = primaryData.readUint32LE(offset + 4);
1382
- const slot = primaryData.readUint32LE(offset + 8);
1383
- spot.set(id, {
1384
- instrId: id,
1385
- clientId: clientId,
1386
- slot: slot
1387
- });
1388
- }
1389
- else if (tag == 4) {
1390
- const clientId = primaryData.readUint32LE(offset + 4);
1391
- const slot = primaryData.readUint32LE(offset + 8);
1392
- perp.set(id, {
1393
- instrId: id,
1394
- clientId: clientId,
1395
- slot: slot
1396
- });
1397
- }
1398
- }
1399
- let clientCommunityRecords = new Map();
1400
- for (var i = 0; i < clientCommunityAccountHeaderModel.count; ++i) {
1401
- const offset = structure_models_1.ClientCommunityAccountHeaderModel.LENGTH + structure_models_1.ClientCommunityRecordModel.LENGTH * i;
1402
- let clientCommunityRecordModel = structure_models_1.ClientCommunityRecordModel.fromBuffer(infos.value[1].data, offset);
1403
- const crncyDec = this.tokenDec(clientCommunityRecordModel.crncyTokenId);
1404
- clientCommunityRecordModel.dividendsValue /= crncyDec;
1405
- clientCommunityRecordModel.feesPrepayment /= crncyDec;
1406
- clientCommunityRecordModel.refPayments /= crncyDec;
1407
- clientCommunityRecords.set(clientCommunityRecordModel.crncyTokenId, clientCommunityRecordModel);
1408
- }
1409
- const drvsDec = this.tokenDec(0);
1410
- clientCommunityAccountHeaderModel.drvsTokens /= drvsDec;
1411
- clientCommunityAccountHeaderModel.currentVotingTokens /= drvsDec;
1412
- clientCommunityAccountHeaderModel.lastVotingTokens /= drvsDec;
1413
- return {
1414
- clientId: clientPrimaryAccountHeaderModel.id,
1415
- mask: clientPrimaryAccountHeaderModel.mask,
1416
- points: clientPrimaryAccountHeaderModel.points,
1417
- slot: clientPrimaryAccountHeaderModel.slot,
1418
- spotTrades: clientPrimaryAccountHeaderModel.spotTrades,
1419
- lpTrades: clientPrimaryAccountHeaderModel.lpTrades,
1420
- perpTrades: clientPrimaryAccountHeaderModel.perpTrades,
1421
- tokens: tokens,
1422
- lp: lp,
1423
- spot: spot,
1424
- perp: perp,
1425
- refProgram: {
1426
- address: clientPrimaryAccountHeaderModel.refAddress,
1427
- expiration: clientPrimaryAccountHeaderModel.refProgramExpiration,
1428
- clientId: clientPrimaryAccountHeaderModel.refClientId,
1429
- disount: clientPrimaryAccountHeaderModel.refProgramDiscount,
1430
- ratio: clientPrimaryAccountHeaderModel.refProgramRatio,
1431
- },
1432
- community: {
1433
- header: clientCommunityAccountHeaderModel,
1434
- data: clientCommunityRecords
1435
- },
1436
- refLinks: [
1437
- {
1438
- id: clientPrimaryAccountHeaderModel.firstRefLinkId,
1439
- expiration: clientPrimaryAccountHeaderModel.firstRefLinkExpiration,
1440
- discount: clientPrimaryAccountHeaderModel.firstRefLinkDiscount,
1441
- ratio: clientPrimaryAccountHeaderModel.firstRefLinkRatio
1442
- },
1443
- {
1444
- id: clientPrimaryAccountHeaderModel.secondRefLinkId,
1445
- expiration: clientPrimaryAccountHeaderModel.secondRefLinkExpiration,
1446
- discount: clientPrimaryAccountHeaderModel.secondRefLinkDiscount,
1447
- ratio: clientPrimaryAccountHeaderModel.secondRefLinkRatio
1448
- }
1449
- ],
1450
- };
1451
- });
1452
- }
1453
- tokenDec(tokenId) {
1454
- if (this.uiNumbers) {
1455
- const token = this.tokens.get(tokenId);
1456
- if (token) {
1457
- return Math.pow(10, token.mask & 0xFF);
1458
- }
1459
- else {
1460
- return 1;
1461
- }
1462
- }
1463
- else {
1464
- return 1;
1465
- }
1466
- }
1467
- /**
1468
- * Get general information about open orders in particular instrument (spot)
1469
- * @param args Contains data from getClientData function
1470
- * @returns General information about open orders (spot)
1471
- */
1472
- getClientSpotOrdersInfo(args) {
1473
- return __awaiter(this, void 0, void 0, function* () {
1474
- const instr = this.instruments.get(args.instrId);
1475
- if (instr == undefined) {
1476
- throw new Error("Invalid Instrument ID");
1477
- }
1478
- const clientInfosAccount = yield this.getInstrAccountByTag({
1479
- assetTokenId: instr.header.assetTokenId,
1480
- crncyTokenId: instr.header.crncyTokenId,
1481
- tag: types_1.AccountType.SPOT_CLIENT_INFOS
1482
- });
1483
- const clientInfos2Account = yield this.getInstrAccountByTag({
1484
- assetTokenId: instr.header.assetTokenId,
1485
- crncyTokenId: instr.header.crncyTokenId,
1486
- tag: types_1.AccountType.SPOT_CLIENT_INFOS2
1487
- });
1488
- const infos = yield this.rpc.getMultipleAccounts([clientInfosAccount, clientInfos2Account], {
1489
- commitment: this.commitment,
1490
- encoding: 'base64',
1491
- dataSlice: {
1492
- offset: structure_models_1.SpotTradeAccountHeaderModel.LENGTH + 32 * args.clientId,
1493
- length: 32
1494
- }
1495
- }).send();
1496
- if (infos.value[0] == null || infos.value[1] == null) {
1497
- throw new Error("Orders Info Not Found");
1498
- }
1499
- const data = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(infos.value[0].data[0]));
1500
- const data1 = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(infos.value[1].data[0]));
1501
- return {
1502
- contextSlot: Number(infos.context.slot),
1503
- bidSlot: data1.readUint32LE(structure_models_1.SpotClientInfo2Model.OFFSET_BID_SLOT),
1504
- askSlot: data1.readUint32LE(structure_models_1.SpotClientInfo2Model.OFFSET_ASK_SLOT),
1505
- bidsEntry: data.readUint16LE(structure_models_1.SpotClientInfoModel.OFFSET_BIDS_ENTRY),
1506
- bidsCount: data.readUint16LE(structure_models_1.SpotClientInfoModel.OFFSET_BIDS_ENTRY + 2),
1507
- asksEntry: data.readUint16LE(structure_models_1.SpotClientInfoModel.OFFSET_ASKS_ENTRY),
1508
- asksCount: data.readUint16LE(structure_models_1.SpotClientInfoModel.OFFSET_ASKS_ENTRY + 2),
1509
- tempAssetTokens: Number(data.readBigInt64LE(structure_models_1.SpotClientInfoModel.OFFSET_AVAIL_ASSET_TOKENS)) /
1510
- this.tokenDec(instr.header.assetTokenId),
1511
- tempCrncyTokens: Number(data.readBigInt64LE(structure_models_1.SpotClientInfoModel.OFFSET_AVAIL_CRNCY_TOKENS)) /
1512
- this.tokenDec(instr.header.crncyTokenId),
1513
- inOrdersAssetTokens: Number(data1.readBigInt64LE(structure_models_1.SpotClientInfo2Model.OFFSET_IN_ORDERS_ASSET_TOKENS)) /
1514
- this.tokenDec(instr.header.assetTokenId),
1515
- inOrdersCrncyTokens: Number(data1.readBigInt64LE(structure_models_1.SpotClientInfo2Model.OFFSET_IN_ORDERS_CRNCY_TOKENS)) /
1516
- this.tokenDec(instr.header.crncyTokenId),
1517
- };
1518
- });
1519
- }
1520
- /**
1521
- * Get general information about open orders in particular instrument (perp)
1522
- * @param args Contains data from getClientData function
1523
- * @returns General information about open orders (perp)
1524
- */
1525
- getClientPerpOrdersInfo(args) {
1526
- return __awaiter(this, void 0, void 0, function* () {
1527
- const instr = this.instruments.get(args.instrId);
1528
- if (instr == undefined) {
1529
- throw new Error("Invalid Instrument ID");
1530
- }
1531
- const clientInfosAccount = yield this.getInstrAccountByTag({
1532
- assetTokenId: instr.header.assetTokenId,
1533
- crncyTokenId: instr.header.crncyTokenId,
1534
- tag: types_1.AccountType.PERP_CLIENT_INFOS
1535
- });
1536
- const clientInfos2Account = yield this.getInstrAccountByTag({
1537
- assetTokenId: instr.header.assetTokenId,
1538
- crncyTokenId: instr.header.crncyTokenId,
1539
- tag: types_1.AccountType.PERP_CLIENT_INFOS2
1540
- });
1541
- const clientInfos3Account = yield this.getInstrAccountByTag({
1542
- assetTokenId: instr.header.assetTokenId,
1543
- crncyTokenId: instr.header.crncyTokenId,
1544
- tag: types_1.AccountType.PERP_CLIENT_INFOS3
1545
- });
1546
- const clientInfos4Account = yield this.getInstrAccountByTag({
1547
- assetTokenId: instr.header.assetTokenId,
1548
- crncyTokenId: instr.header.crncyTokenId,
1549
- tag: types_1.AccountType.PERP_CLIENT_INFOS4
1550
- });
1551
- const clientInfos5Account = yield this.getInstrAccountByTag({
1552
- assetTokenId: instr.header.assetTokenId,
1553
- crncyTokenId: instr.header.crncyTokenId,
1554
- tag: types_1.AccountType.PERP_CLIENT_INFOS5
1555
- });
1556
- const infos = yield this.rpc.getMultipleAccounts([clientInfosAccount, clientInfos2Account, clientInfos3Account, clientInfos4Account, clientInfos5Account], {
1557
- commitment: this.commitment,
1558
- encoding: 'base64',
1559
- dataSlice: {
1560
- offset: structure_models_1.SpotTradeAccountHeaderModel.LENGTH + 32 * args.clientId,
1561
- length: 32
1562
- }
1563
- }).send();
1564
- if (infos.value[0] == null || infos.value[1] == null || infos.value[2] == null ||
1565
- infos.value[3] == null || infos.value[4] == null) {
1566
- throw new Error("Orders Info Not Found");
1567
- }
1568
- const clientInfoModel = structure_models_1.PerpClientInfoModel.fromBuffer(infos.value[0].data);
1569
- const clientInfo2Model = structure_models_1.PerpClientInfo2Model.fromBuffer(infos.value[1].data);
1570
- const clientInfo3Model = structure_models_1.PerpClientInfo3Model.fromBuffer(infos.value[2].data);
1571
- const clientInfo4Model = structure_models_1.PerpClientInfo4Model.fromBuffer(infos.value[3].data);
1572
- const clientInfo5Model = structure_models_1.PerpClientInfo5Model.fromBuffer(infos.value[4].data);
1573
- return {
1574
- contextSlot: Number(infos.context.slot),
1575
- bidSlot: clientInfo2Model.bidSlot,
1576
- askSlot: clientInfo2Model.askSlot,
1577
- bidsEntry: clientInfo3Model.bidsEntry & 0xFFFF,
1578
- bidsCount: clientInfo3Model.bidsEntry >> 16,
1579
- asksEntry: clientInfo3Model.asksEntry & 0xFFFF,
1580
- asksCount: clientInfo3Model.asksEntry >> 16,
1581
- perps: clientInfoModel.perps,
1582
- funds: clientInfoModel.funds,
1583
- inOrdersPerps: clientInfoModel.inOrdersPerps,
1584
- inOrdersFunds: clientInfoModel.inOrdersFunds,
1585
- fees: clientInfo3Model.fees,
1586
- rebates: clientInfo3Model.rebates,
1587
- result: clientInfo2Model.result,
1588
- cost: clientInfo2Model.cost,
1589
- mask: clientInfo2Model.mask,
1590
- socLossFunds: clientInfo4Model.socLossFunds,
1591
- fundingFunds: clientInfo5Model.fundingFunds,
1592
- lossCoverage: clientInfo4Model.lossCoverage
1593
- };
1594
- });
1595
- }
1596
- /**
1597
- * Get list of open orders (spot) in particular instrument
1598
- * @param args Contains data from getClientSpotOrdersInfo
1599
- * @returns List of open orders
1600
- */
1601
- getClientSpotOrders(args) {
1602
- return __awaiter(this, void 0, void 0, function* () {
1603
- const instr = this.instruments.get(args.instrId);
1604
- const bidOrdersAccount = yield this.getInstrAccountByTag({
1605
- assetTokenId: instr.header.assetTokenId,
1606
- crncyTokenId: instr.header.crncyTokenId,
1607
- tag: types_1.AccountType.SPOT_BID_ORDERS
1608
- });
1609
- const askOrdersAccount = yield this.getInstrAccountByTag({
1610
- assetTokenId: instr.header.assetTokenId,
1611
- crncyTokenId: instr.header.crncyTokenId,
1612
- tag: types_1.AccountType.SPOT_ASK_ORDERS
1613
- });
1614
- const assetTokenDec = this.tokenDec(instr.header.assetTokenId);
1615
- const crncyTokenDec = this.tokenDec(instr.header.crncyTokenId);
1616
- if (args.bidsCount > 1 && args.asksCount > 1) {
1617
- let infos = yield this.rpc.getMultipleAccounts([bidOrdersAccount, askOrdersAccount], { commitment: this.commitment, encoding: 'base64' }).send();
1618
- let bids = getMultipleSpotOrders(infos.value[0].data, args.bidsEntry, this.originalClientId);
1619
- for (let i = 0; i < bids.length; ++i) {
1620
- bids[i].qty /= assetTokenDec;
1621
- bids[i].sum /= crncyTokenDec;
1622
- }
1623
- let asks = getMultipleSpotOrders(infos.value[1].data, args.asksEntry, this.originalClientId);
1624
- for (let i = 0; i < asks.length; ++i) {
1625
- asks[i].qty /= assetTokenDec;
1626
- asks[i].sum /= crncyTokenDec;
1627
- }
1628
- return {
1629
- contextSlot: Number(infos.context.slot),
1630
- bids: bids,
1631
- asks: asks
1632
- };
1633
- }
1634
- let bids = [];
1635
- let asks = [];
1636
- let bidContextSlot = 0;
1637
- let askContextSlot = 0;
1638
- if (args.bidsCount > 1) {
1639
- let info = yield this.rpc.getAccountInfo(bidOrdersAccount, {
1640
- commitment: this.commitment,
1641
- encoding: 'base64'
1642
- }).send();
1643
- bidContextSlot = Number(info.context.slot);
1644
- bids = getMultipleSpotOrders(info.value.data, args.bidsEntry, this.originalClientId);
1645
- }
1646
- else if (args.bidsCount == 1) {
1647
- let info = yield this.rpc.getAccountInfo(bidOrdersAccount, {
1648
- commitment: this.commitment,
1649
- encoding: 'base64',
1650
- dataSlice: {
1651
- offset: args.bidsEntry * 64 + structure_models_1.SpotTradeAccountHeaderModel.LENGTH,
1652
- length: 64
1653
- }
1654
- }).send();
1655
- const order = structure_models_1.OrderModel.fromBuffer(info.value.data);
1656
- if (order.origClientId == this.originalClientId) {
1657
- bids = [order];
1658
- }
1659
- bidContextSlot = Number(info.context.slot);
1660
- }
1661
- if (args.asksCount > 1) {
1662
- let info = yield this.rpc.getAccountInfo(askOrdersAccount, {
1663
- commitment: this.commitment,
1664
- encoding: 'base64'
1665
- }).send();
1666
- askContextSlot = Number(info.context.slot);
1667
- asks = getMultipleSpotOrders(info.value.data, args.bidsEntry, this.originalClientId);
1668
- }
1669
- else if (args.asksCount == 1) {
1670
- let info = yield this.rpc.getAccountInfo(askOrdersAccount, {
1671
- commitment: this.commitment,
1672
- encoding: 'base64',
1673
- dataSlice: {
1674
- offset: args.asksEntry * 64 + structure_models_1.SpotTradeAccountHeaderModel.LENGTH,
1675
- length: 64
1676
- }
1677
- }).send();
1678
- const order = structure_models_1.OrderModel.fromBuffer(info.value.data);
1679
- if (order.origClientId == this.originalClientId) {
1680
- asks = [order];
1681
- }
1682
- askContextSlot = Number(info.context.slot);
1683
- }
1684
- for (let i = 0; i < bids.length; ++i) {
1685
- bids[i].qty /= assetTokenDec;
1686
- bids[i].sum /= crncyTokenDec;
1687
- }
1688
- for (let i = 0; i < asks.length; ++i) {
1689
- asks[i].qty /= assetTokenDec;
1690
- asks[i].sum /= crncyTokenDec;
1691
- }
1692
- let contextSlot = 0;
1693
- if (bidContextSlot > 0 || askContextSlot > 0) {
1694
- if (bidContextSlot == 0) {
1695
- contextSlot = askContextSlot;
1696
- }
1697
- else if (askContextSlot == 0) {
1698
- contextSlot = bidContextSlot;
1699
- }
1700
- else {
1701
- contextSlot = Math.min(bidContextSlot, askContextSlot);
1702
- }
1703
- }
1704
- return {
1705
- contextSlot: contextSlot,
1706
- bids: bids,
1707
- asks: asks
1708
- };
1709
- });
1710
- }
1711
- /**
1712
- * Get list of open orders (perp) in particular instrument
1713
- * @param args Contains data from getClientSpotOrdersInfo
1714
- * @returns List of open orders
1715
- */
1716
- getClientPerpOrders(args) {
1717
- return __awaiter(this, void 0, void 0, function* () {
1718
- const instr = this.instruments.get(args.instrId);
1719
- const bidOrdersAccount = yield this.getInstrAccountByTag({
1720
- assetTokenId: instr.header.assetTokenId,
1721
- crncyTokenId: instr.header.crncyTokenId,
1722
- tag: types_1.AccountType.PERP_BID_ORDERS
1723
- });
1724
- const askOrdersAccount = yield this.getInstrAccountByTag({
1725
- assetTokenId: instr.header.assetTokenId,
1726
- crncyTokenId: instr.header.crncyTokenId,
1727
- tag: types_1.AccountType.PERP_ASK_ORDERS
1728
- });
1729
- const assetTokenDec = this.tokenDec(instr.header.assetTokenId);
1730
- const crncyTokenDec = this.tokenDec(instr.header.crncyTokenId);
1731
- if (args.bidsCount > 1 && args.asksCount > 1) {
1732
- let infos = yield this.rpc.getMultipleAccounts([bidOrdersAccount, askOrdersAccount], { commitment: this.commitment, encoding: 'base64' }).send();
1733
- let bids = getMultiplePerpOrders(infos.value[0].data, args.bidsEntry, this.originalClientId);
1734
- for (let i = 0; i < bids.length; ++i) {
1735
- bids[i].qty /= assetTokenDec;
1736
- bids[i].sum /= crncyTokenDec;
1737
- }
1738
- let asks = getMultiplePerpOrders(infos.value[1].data, args.asksEntry, this.originalClientId);
1739
- for (let i = 0; i < asks.length; ++i) {
1740
- asks[i].qty /= assetTokenDec;
1741
- asks[i].sum /= crncyTokenDec;
1742
- }
1743
- return {
1744
- contextSlot: Number(infos.context.slot),
1745
- bids: bids,
1746
- asks: asks
1747
- };
1748
- }
1749
- let bids = [];
1750
- let asks = [];
1751
- let bidContextSlot = 0;
1752
- let askContextSlot = 0;
1753
- if (args.bidsCount > 1) {
1754
- let info = yield this.rpc.getAccountInfo(bidOrdersAccount, { commitment: this.commitment, encoding: 'base64' }).send();
1755
- bidContextSlot = Number(info.context.slot);
1756
- bids = getMultiplePerpOrders(info.value.data, args.bidsEntry, this.originalClientId);
1757
- }
1758
- else if (args.bidsCount == 1) {
1759
- let info = yield this.rpc.getAccountInfo(bidOrdersAccount, {
1760
- commitment: this.commitment,
1761
- encoding: 'base64',
1762
- dataSlice: {
1763
- offset: args.bidsEntry * 64 + structure_models_1.PerpTradeAccountHeaderModel.LENGTH,
1764
- length: 64
1765
- }
1766
- }).send();
1767
- const order = structure_models_1.OrderModel.fromBuffer(info.value.data);
1768
- if (order.origClientId == this.originalClientId) {
1769
- bids = [order];
1770
- }
1771
- bidContextSlot = Number(info.context.slot);
1772
- }
1773
- if (args.asksCount > 1) {
1774
- let info = yield this.rpc.getAccountInfo(askOrdersAccount, { commitment: this.commitment, encoding: 'base64' }).send();
1775
- askContextSlot = Number(info.context.slot);
1776
- asks = getMultiplePerpOrders(info.value.data, args.bidsEntry, this.originalClientId);
1777
- }
1778
- else if (args.asksCount == 1) {
1779
- let info = yield this.rpc.getAccountInfo(askOrdersAccount, {
1780
- commitment: this.commitment,
1781
- encoding: 'base64',
1782
- dataSlice: {
1783
- offset: args.asksEntry * 64 + structure_models_1.PerpTradeAccountHeaderModel.LENGTH,
1784
- length: 64
1785
- }
1786
- }).send();
1787
- const order = structure_models_1.OrderModel.fromBuffer(info.value.data);
1788
- if (order.origClientId == this.originalClientId) {
1789
- asks = [order];
1790
- }
1791
- askContextSlot = Number(info.context.slot);
1792
- }
1793
- for (let i = 0; i < bids.length; ++i) {
1794
- bids[i].qty /= assetTokenDec;
1795
- bids[i].sum /= crncyTokenDec;
1796
- }
1797
- for (let i = 0; i < asks.length; ++i) {
1798
- asks[i].qty /= assetTokenDec;
1799
- asks[i].sum /= crncyTokenDec;
1800
- }
1801
- let contextSlot = 0;
1802
- if (bidContextSlot > 0 || askContextSlot > 0) {
1803
- if (bidContextSlot == 0) {
1804
- contextSlot = askContextSlot;
1805
- }
1806
- else if (askContextSlot == 0) {
1807
- contextSlot = bidContextSlot;
1808
- }
1809
- else {
1810
- contextSlot = Math.min(bidContextSlot, askContextSlot);
1811
- }
1812
- }
1813
- return {
1814
- contextSlot: contextSlot,
1815
- bids: bids,
1816
- asks: asks
1817
- };
1818
- });
1819
- }
1820
- /**
1821
- * Unpack market data to Engine fields, you can use this function to subscribe to Solana account
1822
- * @param buf Engine Instrument Dynamic Account data
1823
- */
1824
- updateInstrDataFromBuffer(data) {
1825
- return __awaiter(this, void 0, void 0, function* () {
1826
- let header = structure_models_1.InstrAccountHeaderModel.fromBuffer(data);
1827
- header.ps /= lpDec;
1828
- const assetTokenDec = this.tokenDec(header.assetTokenId);
1829
- const crncyTokenDec = this.tokenDec(header.crncyTokenId);
1830
- header.assetTokens /= assetTokenDec;
1831
- header.crncyTokens /= crncyTokenDec;
1832
- header.protocolFees /= crncyTokenDec;
1833
- header.lastAssetTokens /= assetTokenDec;
1834
- header.lastCrncyTokens /= crncyTokenDec;
1835
- header.dayAssetTokens /= assetTokenDec;
1836
- header.dayCrncyTokens /= crncyTokenDec;
1837
- header.prevDayAssetTokens /= assetTokenDec;
1838
- header.prevDayCrncyTokens /= crncyTokenDec;
1839
- header.perpLastTradeAssetTokens /= assetTokenDec;
1840
- header.perpLastTradeCrncyTokens /= crncyTokenDec;
1841
- header.perpDayAssetTokens /= assetTokenDec;
1842
- header.perpDayCrncyTokens /= crncyTokenDec;
1843
- header.fixingAssetTokens /= assetTokenDec;
1844
- header.fixingCrncyTokens /= crncyTokenDec;
1845
- header.perpFundingFunds /= crncyTokenDec;
1846
- header.perpInsuranceFund /= crncyTokenDec;
1847
- header.perpOpenInt /= assetTokenDec;
1848
- header.perpSocLossFunds /= crncyTokenDec;
1849
- header.perpPrevDayAssetTokens /= assetTokenDec;
1850
- header.perpPrevDayCrncyTokens /= crncyTokenDec;
1851
- header.bestBid /= dec;
1852
- header.bestAsk /= dec;
1853
- header.dayHigh /= dec;
1854
- header.dayLow /= dec;
1855
- header.perpBestBid /= dec;
1856
- header.perpBestAsk /= dec;
1857
- header.perpDayHigh /= dec;
1858
- header.perpDayLow /= dec;
1859
- header.lastPx /= dec;
1860
- header.perpUnderlyingPx /= dec;
1861
- header.lastClose /= dec;
1862
- header.fixingPx /= dec;
1863
- header.perpLastClose /= dec;
1864
- header.perpLastPx /= dec;
1865
- header.perpLongSpotPriceForWithdrowal /= dec;
1866
- header.perpShortSpotPriceForWithdrowal /= dec;
1867
- header.poolFees /= crncyTokenDec;
1868
- let spotBids = [];
1869
- let spotAsks = [];
1870
- let perpBids = [];
1871
- let perpAsks = [];
1872
- for (var i = 0; i < types_1.MARKET_DEPTH; ++i) {
1873
- const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16;
1874
- let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
1875
- if (line.px == 0) {
1876
- break;
1877
- }
1878
- line.px /= dec;
1879
- line.qty /= assetTokenDec;
1880
- spotBids.push(line);
1881
- }
1882
- for (var i = 0; i < types_1.MARKET_DEPTH; ++i) {
1883
- const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * types_1.MARKET_DEPTH;
1884
- let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
1885
- if (line.px == 0) {
1886
- break;
1887
- }
1888
- line.px /= dec;
1889
- line.qty /= assetTokenDec;
1890
- spotAsks.push(line);
1891
- }
1892
- for (var i = 0; i < types_1.MARKET_DEPTH; ++i) {
1893
- const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * types_1.MARKET_DEPTH * 2;
1894
- let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
1895
- if (line.px == 0) {
1896
- break;
1897
- }
1898
- line.px /= dec;
1899
- line.qty /= assetTokenDec;
1900
- perpBids.push(line);
1901
- }
1902
- for (var i = 0; i < types_1.MARKET_DEPTH; ++i) {
1903
- const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * types_1.MARKET_DEPTH * 3;
1904
- let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
1905
- if (line.px == 0) {
1906
- break;
1907
- }
1908
- line.px /= dec;
1909
- line.qty /= assetTokenDec;
1910
- perpAsks.push(line);
1911
- }
1912
- let pattern = buffer_1.Buffer.alloc(16);
1913
- pattern.writeInt32LE(this.version, 0);
1914
- pattern.writeInt32LE(types_1.AccountType.INSTR, 4);
1915
- pattern.writeInt32LE(header.assetTokenId, 8);
1916
- pattern.writeInt32LE(header.crncyTokenId, 12);
1917
- const instrAddress = (yield (0, kit_1.getProgramDerivedAddress)({
1918
- programAddress: this.programId,
1919
- seeds: [pattern, (0, kit_1.getAddressEncoder)().encode(this.drvsAuthority)]
1920
- }))[0];
1921
- this.instruments.set(header.instrId, {
1922
- address: instrAddress,
1923
- header: header,
1924
- spotBids: spotBids,
1925
- spotAsks: spotAsks,
1926
- perpBids: perpBids,
1927
- perpAsks: perpAsks
1928
- });
1929
- });
1930
- }
1931
- /**
1932
- * Get AddressLookupTableAccount to compile Versioned Transaction with this instrument (spot + derivatives)
1933
- * @param args Instrument ID
1934
- * @returns AddressLookupTableAccount for instrument
1935
- */
1936
- instrLut(args) {
1937
- return this.instruments.get(args.instrId).header.lutAddress;
1938
- }
1939
- /**
1940
- * Update market data on Engine fields
1941
- * @param args Instrument ID
1942
- */
1943
- updateInstrData(args) {
1944
- return __awaiter(this, void 0, void 0, function* () {
1945
- const instr = this.instruments.get(args.instrId);
1946
- let instrAccount = yield this.getInstrAccountByTag({
1947
- assetTokenId: instr.header.assetTokenId,
1948
- crncyTokenId: instr.header.crncyTokenId,
1949
- tag: types_1.AccountType.INSTR
1950
- });
1951
- const info = yield this.rpc.getAccountInfo(instrAccount, { commitment: this.commitment, encoding: 'base64' }).send();
1952
- yield this.updateInstrDataFromBuffer(info.value.data);
1953
- });
1954
- }
1955
- /**
1956
- * Build instruction to deposit SPL tokens
1957
- * @param args Order data
1958
- * @returns Transaction instruction
1959
- */
1960
- depositInstruction(args) {
1961
- return __awaiter(this, void 0, void 0, function* () {
1962
- var _a;
1963
- const exists = yield this.checkClient();
1964
- if (this.signer == null) {
1965
- throw new Error("Wallet is not connected");
1966
- }
1967
- const amount = (_a = args.amount) !== null && _a !== void 0 ? _a : 0;
1968
- const allFunds = args.all_funds ? 1 : 0;
1969
- const token = this.tokens.get(args.tokenId);
1970
- const tokenProgramId = (token.mask & 0x80000000) != 0 ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
1971
- const clientTokenAccount = yield findAssociatedTokenAddress(this.signer, tokenProgramId, token.address);
1972
- let keys = [
1973
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
1974
- { address: clientTokenAccount, role: kit_1.AccountRole.WRITABLE },
1975
- { address: token.programAddress, role: kit_1.AccountRole.WRITABLE },
1976
- { address: token.address, role: kit_1.AccountRole.READONLY },
1977
- { address: this.rootAccount, role: exists ? kit_1.AccountRole.READONLY : kit_1.AccountRole.WRITABLE },
1978
- { address: yield this.getTokenAccount(token.address), role: kit_1.AccountRole.READONLY },
1979
- { address: yield this.findClientPrimaryAccount(), role: kit_1.AccountRole.WRITABLE },
1980
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
1981
- { address: tokenProgramId, role: kit_1.AccountRole.READONLY },
1982
- ];
1983
- if (this.privateMode) {
1984
- keys.push({ address: yield this.getAccountByTag(types_1.AccountType.PRIVATE_CLIENTS), role: kit_1.AccountRole.WRITABLE });
1985
- }
1986
- if (exists) {
1987
- if (args.tokenId == 0) {
1988
- keys.push({ address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.WRITABLE });
1989
- keys.push({ address: this.clientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
1990
- }
1991
- return {
1992
- accounts: keys,
1993
- programAddress: this.programId,
1994
- data: (0, instruction_models_1.depositData)(7, 0, allFunds, args.tokenId, amount * this.tokenDec(args.tokenId), 0, 0)
1995
- };
1996
- }
1997
- else {
1998
- const slot = Number((yield this.rpc.getSlot().send())) - 1;
1999
- const lutAddress = yield getLookupTableAddress(this.signer, slot);
2000
- const clientCommunityAccount = yield this.findClientCommunityAccount();
2001
- keys.push({ address: clientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2002
- keys.push({ address: lutAddress, role: kit_1.AccountRole.WRITABLE });
2003
- keys.push({ address: ADDRESS_LOOKUP_TABLE_PROGRAM_ID, role: kit_1.AccountRole.WRITABLE });
2004
- if (args.tokenId == 0) {
2005
- keys.push({ address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.WRITABLE });
2006
- keys.push({ address: clientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2007
- }
2008
- let refId;
2009
- if (args.refId != null && args.refId != undefined) {
2010
- refId = args.refId;
2011
- if (args.refWallet == null || args.refWallet == undefined) {
2012
- throw new Error("Ref Wallet Not Found");
2013
- }
2014
- keys.push({ address: yield this.findClientPrimaryAccount(args.refWallet), role: kit_1.AccountRole.WRITABLE });
2015
- keys.push({ address: yield this.findClientCommunityAccount(args.refWallet), role: kit_1.AccountRole.WRITABLE });
2016
- }
2017
- else {
2018
- refId = 0;
2019
- }
2020
- return {
2021
- accounts: keys,
2022
- programAddress: this.programId,
2023
- data: (0, instruction_models_1.depositData)(7, 0, allFunds, args.tokenId, amount * this.tokenDec(args.tokenId), slot, refId)
2024
- };
2025
- }
2026
- });
2027
- }
2028
- /**
2029
- * Build instruction to withdraw SPL tokens
2030
- * @param args Order data
2031
- * @returns Transaction instruction
2032
- */
2033
- withdrawInstruction(args) {
2034
- return __awaiter(this, void 0, void 0, function* () {
2035
- if (!(yield this.checkClient())) {
2036
- throw new Error("Client account not found");
2037
- }
2038
- const token = this.tokens.get(args.tokenId);
2039
- const tokenProgramId = (token.mask & 0x80000000) != 0 ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
2040
- const clientTokenAccount = yield findAssociatedTokenAddress(this.signer, tokenProgramId, token.address);
2041
- let keys = [
2042
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2043
- { address: clientTokenAccount, role: kit_1.AccountRole.WRITABLE },
2044
- { address: token.programAddress, role: kit_1.AccountRole.WRITABLE },
2045
- { address: token.address, role: kit_1.AccountRole.READONLY },
2046
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2047
- { address: yield this.getTokenAccount(token.address), role: kit_1.AccountRole.READONLY },
2048
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2049
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2050
- { address: tokenProgramId, role: kit_1.AccountRole.READONLY },
2051
- { address: this.drvsAuthority, role: kit_1.AccountRole.READONLY },
2052
- { address: ASSOCIATED_TOKEN_PROGRAM_ID, role: kit_1.AccountRole.WRITABLE },
2053
- ];
2054
- if (args.spot != undefined) {
2055
- for (var i = 0; i < args.spot.length; ++i) {
2056
- const instr = this.instruments.get(args.spot[i].instrId);
2057
- if (instr.header.assetTokenId == args.tokenId || instr.header.crncyTokenId == args.tokenId) {
2058
- keys.push({ address: instr.header.mapsAddress, role: kit_1.AccountRole.READONLY });
2059
- keys.push({
2060
- address: yield this.getInstrAccountByTag({
2061
- assetTokenId: instr.header.assetTokenId,
2062
- crncyTokenId: instr.header.crncyTokenId,
2063
- tag: types_1.AccountType.SPOT_CLIENT_INFOS
2064
- }),
2065
- role: kit_1.AccountRole.READONLY
2066
- });
2067
- }
2068
- }
2069
- }
2070
- if (args.tokenId == 0) {
2071
- keys.push({ address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.WRITABLE });
2072
- keys.push({ address: yield this.clientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2073
- }
2074
- return {
2075
- accounts: keys,
2076
- programAddress: this.programId,
2077
- data: (0, instruction_models_1.withdrawData)(8, args.tokenId, args.amount * this.tokenDec(args.tokenId))
2078
- };
2079
- });
2080
- }
2081
- /**
2082
- * Build instruction to trade spot LP tokens in particular instrument
2083
- * @param args Order data
2084
- * @returns Trabsaction instruction
2085
- */
2086
- spotLpInstruction(args) {
2087
- return __awaiter(this, void 0, void 0, function* () {
2088
- if (!(yield this.checkClient())) {
2089
- throw new Error("Client account not found");
2090
- }
2091
- yield this.updateInstrData({ instrId: args.instrId });
2092
- let instr = this.instruments.get(args.instrId);
2093
- let keys = [
2094
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2095
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2096
- {
2097
- address: yield this.getInstrAccountByTag({
2098
- assetTokenId: instr.header.assetTokenId,
2099
- crncyTokenId: instr.header.crncyTokenId,
2100
- tag: types_1.AccountType.INSTR
2101
- }),
2102
- role: kit_1.AccountRole.WRITABLE
2103
- },
2104
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2105
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2106
- ];
2107
- if (instr.header.assetTokenId == 0) {
2108
- keys.push({ address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.WRITABLE });
2109
- keys.push({ address: this.clientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2110
- }
2111
- const minPrice = (args.minPrice == undefined || args.minPrice == null) ? 0 : args.minPrice;
2112
- const maxPrice = (args.maxPrice == undefined || args.maxPrice == null) ? 0 : args.maxPrice;
2113
- return {
2114
- accounts: keys,
2115
- programAddress: this.programId,
2116
- data: (0, instruction_models_1.spotLpData)(14, args.side, args.instrId, Math.round(args.amount * lpDec), minPrice * 1000000000, maxPrice * 1000000000),
2117
- };
2118
- });
2119
- }
2120
- /**
2121
- * Build instruction to add new spot order in particular instrument
2122
- * @param args Order data
2123
- * @returns Transaction instruction
2124
- */
2125
- newSpotOrderInstruction(args) {
2126
- return __awaiter(this, void 0, void 0, function* () {
2127
- if (!(yield this.checkClient())) {
2128
- throw new Error("Client account not found");
2129
- }
2130
- let instr = this.instruments.get(args.instrId);
2131
- if (instr.header.mapsAddress == undefined) {
2132
- yield this.updateInstrData({ instrId: args.instrId });
2133
- instr = this.instruments.get(args.instrId);
2134
- }
2135
- let buf = (0, instruction_models_1.newSpotOrderData)(12, args.ioc == null || args.ioc == undefined ? 0 : args.ioc, args.orderType == null || args.orderType == undefined ? 0 : args.orderType, args.side, args.instrId, Math.round(args.price * 1000000000), Math.round(args.qty * this.tokenDec(instr.header.assetTokenId)), args.edgePrice == null || args.edgePrice == undefined ? 0 : args.edgePrice * 1000000000);
2136
- let keys = [
2137
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2138
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2139
- { address: yield this.findClientPrimaryAccount(), role: kit_1.AccountRole.WRITABLE },
2140
- { address: yield this.findClientCommunityAccount(), role: kit_1.AccountRole.WRITABLE },
2141
- ...yield this.getSpotContext(instr.header),
2142
- ...yield this.getSpotCandles(instr.header),
2143
- {
2144
- address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY),
2145
- role: instr.header.assetTokenId == 0 ? kit_1.AccountRole.WRITABLE : kit_1.AccountRole.READONLY
2146
- },
2147
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2148
- ];
2149
- if (this.refClientPrimaryAccount != null && this.refClientPrimaryAccount != undefined) {
2150
- keys.push({ address: this.refClientPrimaryAccount, role: kit_1.AccountRole.WRITABLE });
2151
- keys.push({ address: this.refClientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2152
- }
2153
- return {
2154
- accounts: keys, programAddress: this.programId, data: buf
2155
- };
2156
- });
2157
- }
2158
- /**
2159
- * Build instruction to spot quotes replacement in particular instrument
2160
- * @param args Order data
2161
- * @returns Transaction instruction
2162
- */
2163
- spotQuotesReplaceInstruction(args) {
2164
- return __awaiter(this, void 0, void 0, function* () {
2165
- if (!(yield this.checkClient())) {
2166
- throw new Error("Client account not found");
2167
- }
2168
- let instr = this.instruments.get(args.instrId);
2169
- if (instr.header.mapsAddress == undefined) {
2170
- yield this.updateInstrData({ instrId: args.instrId });
2171
- instr = this.instruments.get(args.instrId);
2172
- }
2173
- let assetTokenDecFactor = this.tokenDec(instr.header.assetTokenId);
2174
- let buf = (0, instruction_models_1.spotQuotesReplaceData)(34, args.instrId, Math.round(args.newBidPrice * 1000000000), Math.round(args.newBidQty * assetTokenDecFactor), args.bidOrderIdToCancel, Math.round(args.newAskPrice * 1000000000), Math.round(args.newAskQty * assetTokenDecFactor), args.askOrderIdToCancel);
2175
- let keys = [
2176
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2177
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2178
- { address: yield this.findClientPrimaryAccount(), role: kit_1.AccountRole.WRITABLE },
2179
- { address: yield this.findClientCommunityAccount(), role: kit_1.AccountRole.WRITABLE },
2180
- ...yield this.getSpotContext(instr.header),
2181
- ...yield this.getSpotCandles(instr.header),
2182
- {
2183
- address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY),
2184
- role: instr.header.assetTokenId == 0 ? kit_1.AccountRole.WRITABLE : kit_1.AccountRole.READONLY
2185
- },
2186
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2187
- ];
2188
- if (this.refClientPrimaryAccount != null && this.refClientPrimaryAccount != undefined) {
2189
- keys.push({ address: this.refClientPrimaryAccount, role: kit_1.AccountRole.WRITABLE });
2190
- keys.push({ address: this.refClientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2191
- }
2192
- return {
2193
- accounts: keys, programAddress: this.programId, data: buf
2194
- };
2195
- });
2196
- }
2197
- /**
2198
- * Build instruction to cancel spot order in particular instrument
2199
- * @param args Order data
2200
- * @returns Transaction instruction
2201
- */
2202
- spotOrderCancelInstruction(args) {
2203
- return __awaiter(this, void 0, void 0, function* () {
2204
- if (!(yield this.checkClient())) {
2205
- throw new Error("Client account not found");
2206
- }
2207
- let instr = this.instruments.get(args.instrId);
2208
- if (instr.header.mapsAddress == undefined) {
2209
- yield this.updateInstrData({ instrId: args.instrId });
2210
- instr = this.instruments.get(args.instrId);
2211
- }
2212
- const drvs = instr.header.assetTokenId == 0;
2213
- let keys = [
2214
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2215
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2216
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2217
- ...yield this.getSpotContext(instr.header),
2218
- {
2219
- address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY),
2220
- role: drvs ? kit_1.AccountRole.WRITABLE : kit_1.AccountRole.READONLY
2221
- },
2222
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2223
- ];
2224
- if (drvs) {
2225
- keys.push({ address: yield this.findClientCommunityAccount(), role: kit_1.AccountRole.WRITABLE });
2226
- }
2227
- return {
2228
- accounts: keys,
2229
- programAddress: this.programId,
2230
- data: (0, instruction_models_1.spotOrderCancelData)(13, args.side, args.instrId, args.orderId),
2231
- };
2232
- });
2233
- }
2234
- /**
2235
- * Build instruction for spot mass cancel in particular instrument
2236
- * @param args Order data
2237
- * @returns Transaction instruction
2238
- */
2239
- spotMassCancelInstruction(args) {
2240
- return __awaiter(this, void 0, void 0, function* () {
2241
- if (!(yield this.checkClient())) {
2242
- throw new Error("Client account not found");
2243
- }
2244
- let instr = this.instruments.get(args.instrId);
2245
- if (instr.header.mapsAddress == undefined) {
2246
- yield this.updateInstrData({ instrId: args.instrId });
2247
- instr = this.instruments.get(args.instrId);
2248
- }
2249
- const drvs = instr.header.assetTokenId == 0;
2250
- let keys = [
2251
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2252
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2253
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2254
- ...yield this.getSpotContext(instr.header),
2255
- {
2256
- address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY),
2257
- role: drvs ? kit_1.AccountRole.WRITABLE : kit_1.AccountRole.READONLY
2258
- },
2259
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2260
- ];
2261
- if (drvs) {
2262
- keys.push({ address: yield this.findClientCommunityAccount(), role: kit_1.AccountRole.WRITABLE });
2263
- }
2264
- return {
2265
- accounts: keys,
2266
- programAddress: this.programId,
2267
- data: (0, instruction_models_1.spotMassCancelData)(15, args.instrId),
2268
- };
2269
- });
2270
- }
2271
- /**
2272
- * Build upgrade to PERP instructions
2273
- * @param args Order data
2274
- * @returns Transaction instruction
2275
- */
2276
- upgradeToPerpInstructions(args) {
2277
- return __awaiter(this, void 0, void 0, function* () {
2278
- if (this.signer == null) {
2279
- throw new Error("Wallet is not connected");
2280
- }
2281
- let instr = this.instruments.get(args.instrId);
2282
- if (instr == null) {
2283
- throw new Error("Invalid Instr ID");
2284
- }
2285
- yield this.updateInstrData({
2286
- instrId: args.instrId
2287
- });
2288
- instr = this.instruments.get(args.instrId);
2289
- if ((instr.header.mask & types_1.InstrMask.READY_TO_PERP_UPGRADE) == 0) {
2290
- throw new Error("Impossible to upgrade");
2291
- }
2292
- if ((instr.header.mask & types_1.InstrMask.PERP) != 0) {
2293
- throw new Error("Instr already upgraded");
2294
- }
2295
- const perpMapsAccountSeed = this.version.toString() + "_" +
2296
- types_1.AccountType.PERP_MAPS.toString() + "_" +
2297
- instr.header.assetTokenId.toString() + "_" +
2298
- instr.header.crncyTokenId.toString();
2299
- const perpMapsAccount = yield (0, kit_1.createAddressWithSeed)({
2300
- baseAddress: this.signer,
2301
- programAddress: this.programId,
2302
- seed: perpMapsAccountSeed
2303
- });
2304
- const perpMapsAccountSize = 168576;
2305
- const perpMapsAccountLamports = yield this.rpc.getMinimumBalanceForRentExemption(BigInt(perpMapsAccountSize)).send();
2306
- const createMapsAccountIx = (0, system_1.getCreateAccountWithSeedInstruction)({
2307
- payer: this.signer,
2308
- baseAccount: this.signer,
2309
- base: this.signer,
2310
- newAccount: perpMapsAccount,
2311
- seed: perpMapsAccountSeed,
2312
- space: perpMapsAccountSize,
2313
- programAddress: this.programId,
2314
- amount: perpMapsAccountLamports,
2315
- });
2316
- let keys = [
2317
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2318
- { address: this.rootAccount, role: kit_1.AccountRole.WRITABLE },
2319
- {
2320
- address: yield this.getInstrAccountByTag({
2321
- assetTokenId: instr.header.assetTokenId,
2322
- crncyTokenId: instr.header.crncyTokenId,
2323
- tag: types_1.AccountType.INSTR
2324
- }), role: kit_1.AccountRole.WRITABLE
2325
- },
2326
- { address: instr.header.lutAddress, role: kit_1.AccountRole.WRITABLE },
2327
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2328
- { address: ADDRESS_LOOKUP_TABLE_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2329
- { address: this.drvsAuthority, role: kit_1.AccountRole.READONLY },
2330
- {
2331
- address: yield this.getInstrAccountByTag({
2332
- assetTokenId: instr.header.assetTokenId,
2333
- crncyTokenId: instr.header.crncyTokenId,
2334
- tag: types_1.AccountType.PERP_BIDS_TREE
2335
- }), role: kit_1.AccountRole.WRITABLE
2336
- },
2337
- {
2338
- address: yield this.getInstrAccountByTag({
2339
- assetTokenId: instr.header.assetTokenId,
2340
- crncyTokenId: instr.header.crncyTokenId,
2341
- tag: types_1.AccountType.PERP_ASKS_TREE
2342
- }), role: kit_1.AccountRole.WRITABLE
2343
- },
2344
- {
2345
- address: yield this.getInstrAccountByTag({
2346
- assetTokenId: instr.header.assetTokenId,
2347
- crncyTokenId: instr.header.crncyTokenId,
2348
- tag: types_1.AccountType.PERP_BID_ORDERS
2349
- }), role: kit_1.AccountRole.WRITABLE
2350
- },
2351
- {
2352
- address: yield this.getInstrAccountByTag({
2353
- assetTokenId: instr.header.assetTokenId,
2354
- crncyTokenId: instr.header.crncyTokenId,
2355
- tag: types_1.AccountType.PERP_ASK_ORDERS
2356
- }), role: kit_1.AccountRole.WRITABLE
2357
- },
2358
- {
2359
- address: yield this.getInstrAccountByTag({
2360
- assetTokenId: instr.header.assetTokenId,
2361
- crncyTokenId: instr.header.crncyTokenId,
2362
- tag: types_1.AccountType.PERP_LINES
2363
- }), role: kit_1.AccountRole.WRITABLE
2364
- },
2365
- {
2366
- address: perpMapsAccount, role: kit_1.AccountRole.WRITABLE
2367
- },
2368
- {
2369
- address: yield this.getInstrAccountByTag({
2370
- assetTokenId: instr.header.assetTokenId,
2371
- crncyTokenId: instr.header.crncyTokenId,
2372
- tag: types_1.AccountType.PERP_CLIENT_INFOS
2373
- }), role: kit_1.AccountRole.WRITABLE
2374
- },
2375
- {
2376
- address: yield this.getInstrAccountByTag({
2377
- assetTokenId: instr.header.assetTokenId,
2378
- crncyTokenId: instr.header.crncyTokenId,
2379
- tag: types_1.AccountType.PERP_CLIENT_INFOS2
2380
- }), role: kit_1.AccountRole.WRITABLE
2381
- },
2382
- {
2383
- address: yield this.getInstrAccountByTag({
2384
- assetTokenId: instr.header.assetTokenId,
2385
- crncyTokenId: instr.header.crncyTokenId,
2386
- tag: types_1.AccountType.PERP_CLIENT_INFOS3
2387
- }), role: kit_1.AccountRole.WRITABLE
2388
- },
2389
- {
2390
- address: yield this.getInstrAccountByTag({
2391
- assetTokenId: instr.header.assetTokenId,
2392
- crncyTokenId: instr.header.crncyTokenId,
2393
- tag: types_1.AccountType.PERP_CLIENT_INFOS4
2394
- }), role: kit_1.AccountRole.WRITABLE
2395
- },
2396
- {
2397
- address: yield this.getInstrAccountByTag({
2398
- assetTokenId: instr.header.assetTokenId,
2399
- crncyTokenId: instr.header.crncyTokenId,
2400
- tag: types_1.AccountType.PERP_CLIENT_INFOS5
2401
- }), role: kit_1.AccountRole.WRITABLE
2402
- },
2403
- {
2404
- address: yield this.getInstrAccountByTag({
2405
- assetTokenId: instr.header.assetTokenId,
2406
- crncyTokenId: instr.header.crncyTokenId,
2407
- tag: types_1.AccountType.PERP_LONG_PX_TREE
2408
- }), role: kit_1.AccountRole.WRITABLE
2409
- },
2410
- {
2411
- address: yield this.getInstrAccountByTag({
2412
- assetTokenId: instr.header.assetTokenId,
2413
- crncyTokenId: instr.header.crncyTokenId,
2414
- tag: types_1.AccountType.PERP_SHORT_PX_TREE
2415
- }), role: kit_1.AccountRole.WRITABLE
2416
- },
2417
- {
2418
- address: yield this.getInstrAccountByTag({
2419
- assetTokenId: instr.header.assetTokenId,
2420
- crncyTokenId: instr.header.crncyTokenId,
2421
- tag: types_1.AccountType.PERP_REBALANCE_TIME_TREE
2422
- }), role: kit_1.AccountRole.WRITABLE
2423
- },
2424
- ];
2425
- const upgradeIx = {
2426
- accounts: keys,
2427
- programAddress: this.programId,
2428
- data: (0, instruction_models_1.upgradeToPerpData)(10, args.instrId)
2429
- };
2430
- return [createMapsAccountIx, upgradeIx];
2431
- });
2432
- }
2433
- /**
2434
- * Build instruction for perp deposit in particular instrument
2435
- * @param args Order data
2436
- * @returns Transaction instruction
2437
- */
2438
- perpDepositInstruction(args) {
2439
- return __awaiter(this, void 0, void 0, function* () {
2440
- if (!(yield this.checkClient())) {
2441
- throw new Error("Client account not found");
2442
- }
2443
- let instr = this.instruments.get(args.instrId);
2444
- if (instr.header.perpMapsAddress == undefined) {
2445
- yield this.updateInstrData({ instrId: args.instrId });
2446
- instr = this.instruments.get(args.instrId);
2447
- }
2448
- let keys = [
2449
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2450
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2451
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2452
- ...yield this.getPerpContext(instr.header),
2453
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2454
- ];
2455
- return {
2456
- accounts: keys,
2457
- programAddress: this.programId,
2458
- data: (0, instruction_models_1.perpDepositData)(11, args.instrId, args.amount * this.tokenDec(instr.header.crncyTokenId)),
2459
- };
2460
- });
2461
- }
2462
- /**
2463
- * Build instruction for perp buy seat in particular instrument
2464
- * @param args Order data
2465
- * @returns Transaction instruction
2466
- */
2467
- perpBuySeatInstruction(args) {
2468
- return __awaiter(this, void 0, void 0, function* () {
2469
- if (!(yield this.checkClient())) {
2470
- throw new Error("Client account not found");
2471
- }
2472
- yield this.updateInstrData({ instrId: args.instrId });
2473
- let instr = this.instruments.get(args.instrId);
2474
- let keys = [
2475
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2476
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2477
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2478
- ...yield this.getPerpContext(instr.header),
2479
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2480
- ];
2481
- const splippage = (args.slippage == undefined || args.slippage == null) ? 0 : args.slippage;
2482
- const slippagePrice = (perpSeatReserve(instr.header.perpClientsCount + 1) -
2483
- perpSeatReserve(instr.header.perpClientsCount)) * (1 + splippage);
2484
- const crncyDec = this.tokenDec(instr.header.crncyTokenId);
2485
- return {
2486
- accounts: keys,
2487
- programAddress: this.programId,
2488
- data: (0, instruction_models_1.buyMarketSeatData)(47, args.instrId, slippagePrice * crncyDec, args.amount * crncyDec),
2489
- };
2490
- });
2491
- }
2492
- perpSellSeatInstruction(args) {
2493
- return __awaiter(this, void 0, void 0, function* () {
2494
- if (!(yield this.checkClient())) {
2495
- throw new Error("Client account not found");
2496
- }
2497
- yield this.updateInstrData({ instrId: args.instrId });
2498
- let instr = this.instruments.get(args.instrId);
2499
- let keys = [
2500
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2501
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2502
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2503
- ...yield this.getPerpContext(instr.header),
2504
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2505
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2506
- ];
2507
- const splippage = (args.slippage == undefined || args.slippage == null) ? 0 : args.slippage;
2508
- const slippagePrice = (perpSeatReserve(instr.header.perpClientsCount + 1) -
2509
- perpSeatReserve(instr.header.perpClientsCount)) / (1 + splippage);
2510
- const crncyDec = this.tokenDec(instr.header.crncyTokenId);
2511
- return {
2512
- accounts: keys,
2513
- programAddress: this.programId,
2514
- data: (0, instruction_models_1.sellMarketSeatData)(48, slippagePrice * crncyDec, args.instrId),
2515
- };
2516
- });
2517
- }
2518
- /**
2519
- * Build instruction for new perp order in particular instrument
2520
- * @param args Order data
2521
- * @returns Transaction instruction
2522
- */
2523
- newPerpOrderInstruction(args) {
2524
- return __awaiter(this, void 0, void 0, function* () {
2525
- if (!(yield this.checkClient())) {
2526
- throw new Error("Client account not found");
2527
- }
2528
- let instr = this.instruments.get(args.instrId);
2529
- if (instr.header.perpMapsAddress == undefined) {
2530
- yield this.updateInstrData({ instrId: args.instrId });
2531
- instr = this.instruments.get(args.instrId);
2532
- }
2533
- let keys = [
2534
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2535
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2536
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2537
- { address: this.clientCommunityAccount, role: kit_1.AccountRole.WRITABLE },
2538
- ...yield this.getPerpContext(instr.header),
2539
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2540
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2541
- ];
2542
- if (this.refClientPrimaryAccount != null && this.refClientPrimaryAccount != undefined) {
2543
- keys.push({ address: this.refClientPrimaryAccount, role: kit_1.AccountRole.WRITABLE });
2544
- keys.push({ address: this.refClientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2545
- }
2546
- return {
2547
- accounts: keys,
2548
- programAddress: this.programId,
2549
- data: (0, instruction_models_1.newPerpOrderData)(19, args.ioc == null || args.ioc == undefined ? 0 : args.ioc, args.leverage == null || args.leverage == undefined ? 0 : args.leverage, args.orderType == null || args.orderType == undefined ? 0 : args.orderType, args.side, args.instrId, args.price * 1000000000, args.qty * this.tokenDec(instr.header.assetTokenId), args.edgePrice == null || args.edgePrice == undefined ? 0 : args.edgePrice * 1000000000),
2550
- };
2551
- });
2552
- }
2553
- /**
2554
- * Build instruction for perp quotes replace in particular instrument
2555
- * @param args Order data
2556
- * @returns Transaction instruction
2557
- */
2558
- perpQuotesReplaceInstruction(args) {
2559
- return __awaiter(this, void 0, void 0, function* () {
2560
- if (!(yield this.checkClient())) {
2561
- throw new Error("Client account not found");
2562
- }
2563
- let instr = this.instruments.get(args.instrId);
2564
- if (instr.header.perpMapsAddress == undefined) {
2565
- yield this.updateInstrData({ instrId: args.instrId });
2566
- instr = this.instruments.get(args.instrId);
2567
- }
2568
- let assetTokenDecFactor = this.tokenDec(instr.header.assetTokenId);
2569
- let buf = (0, instruction_models_1.perpQuotesReplaceData)(42, args.instrId, Math.round(args.newBidPrice * 1000000000), Math.round(args.newBidQty * assetTokenDecFactor), args.bidOrderIdToCancel, Math.round(args.newAskPrice * 1000000000), Math.round(args.newAskQty * assetTokenDecFactor), args.askOrderIdToCancel);
2570
- let keys = [
2571
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2572
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2573
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2574
- { address: this.clientCommunityAccount, role: kit_1.AccountRole.WRITABLE },
2575
- ...yield this.getPerpContext(instr.header),
2576
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2577
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2578
- ];
2579
- if (this.refClientPrimaryAccount != null && this.refClientPrimaryAccount != undefined) {
2580
- keys.push({ address: this.refClientPrimaryAccount, role: kit_1.AccountRole.WRITABLE });
2581
- keys.push({ address: this.refClientCommunityAccount, role: kit_1.AccountRole.WRITABLE });
2582
- }
2583
- return {
2584
- accounts: keys,
2585
- programAddress: this.programId,
2586
- data: buf,
2587
- };
2588
- });
2589
- }
2590
- /**
2591
- * Build instruction for perp order cancel in particular instrument
2592
- * @param args Order data
2593
- * @returns Transaction instruction
2594
- */
2595
- perpOrderCancelInstruction(args) {
2596
- return __awaiter(this, void 0, void 0, function* () {
2597
- if (!(yield this.checkClient())) {
2598
- throw new Error("Client account not found");
2599
- }
2600
- let instr = this.instruments.get(args.instrId);
2601
- if (instr.header.perpMapsAddress == undefined) {
2602
- yield this.updateInstrData({ instrId: args.instrId });
2603
- instr = this.instruments.get(args.instrId);
2604
- }
2605
- let keys = [
2606
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2607
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2608
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2609
- ...yield this.getPerpContext(instr.header),
2610
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2611
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2612
- ];
2613
- return {
2614
- accounts: keys,
2615
- programAddress: this.programId,
2616
- data: (0, instruction_models_1.perpOrderCancelData)(30, args.side, args.instrId, args.orderId),
2617
- };
2618
- });
2619
- }
2620
- /**
2621
- * Build instruction for perp mass cancel in particular instrument
2622
- * @param args Order data
2623
- * @returns Transaction instruction
2624
- */
2625
- perpMassCancelInstruction(args) {
2626
- return __awaiter(this, void 0, void 0, function* () {
2627
- if (!(yield this.checkClient())) {
2628
- throw new Error("Client account not found");
2629
- }
2630
- let instr = this.instruments.get(args.instrId);
2631
- if (instr.header.perpMapsAddress == undefined) {
2632
- yield this.updateInstrData({ instrId: args.instrId });
2633
- instr = this.instruments.get(args.instrId);
2634
- }
2635
- let keys = [
2636
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2637
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2638
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2639
- ...yield this.getPerpContext(instr.header),
2640
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2641
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2642
- ];
2643
- return {
2644
- accounts: keys,
2645
- programAddress: this.programId,
2646
- data: (0, instruction_models_1.perpMassCancelData)(36, args.instrId),
2647
- };
2648
- });
2649
- }
2650
- /**
2651
- * Build instruction for new referral link
2652
- * @returns Transaction instruction
2653
- */
2654
- newRefLinkInstruction() {
2655
- return __awaiter(this, void 0, void 0, function* () {
2656
- if (!(yield this.checkClient())) {
2657
- throw new Error("Client account not found");
2658
- }
2659
- let buf = buffer_1.Buffer.alloc(1);
2660
- buf.writeUInt8(45, 0);
2661
- let keys = [
2662
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2663
- { address: this.rootAccount, role: kit_1.AccountRole.WRITABLE },
2664
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2665
- ];
2666
- return {
2667
- accounts: keys,
2668
- programAddress: this.programId,
2669
- data: buf,
2670
- };
2671
- });
2672
- }
2673
- /**
2674
- * Build instruction for change leverage in particular instrument
2675
- * @param args Transaction data
2676
- * @returns Transaction instruction
2677
- */
2678
- perpChangeLeverageInstruction(args) {
2679
- return __awaiter(this, void 0, void 0, function* () {
2680
- if (!(yield this.checkClient())) {
2681
- throw new Error("Client account not found");
2682
- }
2683
- let instr = this.instruments.get(args.instrId);
2684
- if (instr.header.perpMapsAddress == undefined) {
2685
- yield this.updateInstrData({ instrId: args.instrId });
2686
- instr = this.instruments.get(args.instrId);
2687
- }
2688
- let keys = [
2689
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2690
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2691
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2692
- ...yield this.getPerpContext(instr.header),
2693
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2694
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2695
- ];
2696
- return {
2697
- accounts: keys,
2698
- programAddress: this.programId,
2699
- data: (0, instruction_models_1.perpChangeLeverageData)(37, args.instrId, args.leverage),
2700
- };
2701
- });
2702
- }
2703
- /**
2704
- * Build instruction for statistics reset in particular instrument
2705
- * @param args Transaction data
2706
- * @returns Transaction instruction
2707
- */
2708
- perpStatisticsResetInstruction(args) {
2709
- return __awaiter(this, void 0, void 0, function* () {
2710
- if (!(yield this.checkClient())) {
2711
- throw new Error("Client account not found");
2712
- }
2713
- let instr = this.instruments.get(args.instrId);
2714
- if (instr.header.perpMapsAddress == undefined) {
2715
- yield this.updateInstrData({ instrId: args.instrId });
2716
- instr = this.instruments.get(args.instrId);
2717
- }
2718
- let keys = [
2719
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2720
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2721
- { address: this.clientPrimaryAccount, role: kit_1.AccountRole.WRITABLE },
2722
- ...yield this.getPerpContext(instr.header),
2723
- { address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY), role: kit_1.AccountRole.READONLY },
2724
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2725
- ];
2726
- return {
2727
- accounts: keys,
2728
- programAddress: this.programId,
2729
- data: (0, instruction_models_1.perpStatisticsResetData)(46, args.instrId),
2730
- };
2731
- });
2732
- }
2733
- /**
2734
- * Build new instrument instructions
2735
- * @param args New instrument data
2736
- * @returns Transaction instruction
2737
- */
2738
- newInstrumentInstructions(args) {
2739
- return __awaiter(this, void 0, void 0, function* () {
2740
- if (this.signer == null) {
2741
- throw new Error("Wallet is not connected");
2742
- }
2743
- if (args.initialPrice <= 0) {
2744
- throw new Error("Invalid initial price");
2745
- }
2746
- const assetInfo = yield this.rpc.getAccountInfo(args.assetMint).send();
2747
- if (!assetInfo.value) {
2748
- throw new Error("Asset mint not found");
2749
- }
2750
- const tokenProgramId = assetInfo.value.owner == TOKEN_2022_PROGRAM_ID ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
2751
- const crncyTokenId = yield this.getTokenId(args.crncyMint);
2752
- const id = yield this.getTokenId(args.assetMint);
2753
- const newAssetToken = id == null;
2754
- const assetTokenId = newAssetToken ? this.rootStateModel.tokensCount : id;
2755
- if (!crncyTokenId) {
2756
- throw new Error("Currency mint not found");
2757
- }
2758
- const mapsAccountSeed = this.version.toString() + "_" +
2759
- types_1.AccountType.SPOT_MAPS.toString() + "_" +
2760
- assetTokenId.toString() + "_" +
2761
- crncyTokenId.toString();
2762
- const mapsAccount = yield (0, kit_1.createAddressWithSeed)({
2763
- baseAddress: this.signer,
2764
- programAddress: this.programId,
2765
- seed: mapsAccountSeed
2766
- });
2767
- const mapsAccountSize = 42184;
2768
- const mapsAccountLamports = yield this.rpc.getMinimumBalanceForRentExemption(BigInt(mapsAccountSize)).send();
2769
- const createMapsAccountIx = (0, system_1.getCreateAccountWithSeedInstruction)({
2770
- payer: this.signer,
2771
- baseAccount: this.signer,
2772
- base: this.signer,
2773
- newAccount: mapsAccount,
2774
- seed: mapsAccountSeed,
2775
- space: mapsAccountSize,
2776
- programAddress: this.programId,
2777
- amount: mapsAccountLamports,
2778
- });
2779
- const slot = Number((yield this.rpc.getSlot().send())) - 1;
2780
- const lutAddress = yield getLookupTableAddress(this.drvsAuthority, slot);
2781
- let keys = [
2782
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2783
- { address: this.rootAccount, role: kit_1.AccountRole.WRITABLE },
2784
- { address: yield this.getTokenAccount(args.assetMint), role: newAssetToken ? kit_1.AccountRole.WRITABLE : kit_1.AccountRole.READONLY },
2785
- { address: yield this.getTokenAccount(args.crncyMint), role: kit_1.AccountRole.READONLY },
2786
- { address: newAssetToken ? args.newProgramAccountAddress : this.tokens.get(assetTokenId).programAddress, role: newAssetToken ? kit_1.AccountRole.WRITABLE_SIGNER : kit_1.AccountRole.READONLY },
2787
- { address: args.assetMint, role: kit_1.AccountRole.READONLY },
2788
- { address: lutAddress, role: kit_1.AccountRole.WRITABLE },
2789
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2790
- { address: tokenProgramId, role: kit_1.AccountRole.READONLY },
2791
- { address: ADDRESS_LOOKUP_TABLE_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2792
- { address: this.drvsAuthority, role: kit_1.AccountRole.READONLY },
2793
- {
2794
- address: yield this.getInstrAccountByTag({
2795
- assetTokenId: assetTokenId,
2796
- crncyTokenId: crncyTokenId,
2797
- tag: types_1.AccountType.INSTR
2798
- }), role: kit_1.AccountRole.WRITABLE
2799
- },
2800
- {
2801
- address: yield this.getInstrAccountByTag({
2802
- assetTokenId: assetTokenId,
2803
- crncyTokenId: crncyTokenId,
2804
- tag: types_1.AccountType.SPOT_BIDS_TREE
2805
- }), role: kit_1.AccountRole.WRITABLE
2806
- },
2807
- {
2808
- address: yield this.getInstrAccountByTag({
2809
- assetTokenId: assetTokenId,
2810
- crncyTokenId: crncyTokenId,
2811
- tag: types_1.AccountType.SPOT_ASKS_TREE
2812
- }), role: kit_1.AccountRole.WRITABLE
2813
- },
2814
- {
2815
- address: yield this.getInstrAccountByTag({
2816
- assetTokenId: assetTokenId,
2817
- crncyTokenId: crncyTokenId,
2818
- tag: types_1.AccountType.SPOT_BID_ORDERS
2819
- }), role: kit_1.AccountRole.WRITABLE
2820
- },
2821
- {
2822
- address: yield this.getInstrAccountByTag({
2823
- assetTokenId: assetTokenId,
2824
- crncyTokenId: crncyTokenId,
2825
- tag: types_1.AccountType.SPOT_ASK_ORDERS
2826
- }), role: kit_1.AccountRole.WRITABLE
2827
- },
2828
- {
2829
- address: yield this.getInstrAccountByTag({
2830
- assetTokenId: assetTokenId,
2831
- crncyTokenId: crncyTokenId,
2832
- tag: types_1.AccountType.SPOT_LINES
2833
- }), role: kit_1.AccountRole.WRITABLE
2834
- },
2835
- {
2836
- address: mapsAccount, role: kit_1.AccountRole.WRITABLE
2837
- },
2838
- {
2839
- address: yield this.getInstrAccountByTag({
2840
- assetTokenId: assetTokenId,
2841
- crncyTokenId: crncyTokenId,
2842
- tag: types_1.AccountType.SPOT_CLIENT_INFOS
2843
- }), role: kit_1.AccountRole.WRITABLE
2844
- },
2845
- {
2846
- address: yield this.getInstrAccountByTag({
2847
- assetTokenId: assetTokenId,
2848
- crncyTokenId: crncyTokenId,
2849
- tag: types_1.AccountType.SPOT_CLIENT_INFOS2
2850
- }), role: kit_1.AccountRole.WRITABLE
2851
- },
2852
- {
2853
- address: yield this.getInstrAccountByTag({
2854
- assetTokenId: assetTokenId,
2855
- crncyTokenId: crncyTokenId,
2856
- tag: types_1.AccountType.SPOT_1M_CANDLES
2857
- }), role: kit_1.AccountRole.WRITABLE
2858
- },
2859
- {
2860
- address: yield this.getInstrAccountByTag({
2861
- assetTokenId: assetTokenId,
2862
- crncyTokenId: crncyTokenId,
2863
- tag: types_1.AccountType.SPOT_15M_CANDLES
2864
- }), role: kit_1.AccountRole.WRITABLE
2865
- },
2866
- {
2867
- address: yield this.getInstrAccountByTag({
2868
- assetTokenId: assetTokenId,
2869
- crncyTokenId: crncyTokenId,
2870
- tag: types_1.AccountType.SPOT_DAY_CANDLES
2871
- }), role: kit_1.AccountRole.WRITABLE
2872
- },
2873
- ];
2874
- const newInstrIx = {
2875
- accounts: keys,
2876
- programAddress: this.programId,
2877
- data: (0, instruction_models_1.newInstrumentData)(9, crncyTokenId, slot, args.initialPrice * 1000000000)
2878
- };
2879
- return [createMapsAccountIx, newInstrIx];
2880
- });
2881
- }
2882
- /**
2883
- * Build instruction for durect swap
2884
- * @param args Order data
2885
- * @returns Transaction instruction
2886
- */
2887
- swapInstruction(args) {
2888
- return __awaiter(this, void 0, void 0, function* () {
2889
- if (!(yield this.checkClient())) {
2890
- throw new Error("Client account not found");
2891
- }
2892
- const assetTokenId = yield this.getTokenId(args.assetMint);
2893
- const crncyTokenId = yield this.getTokenId(args.crncyMint);
2894
- const assetTokenAccount = this.tokens.get(assetTokenId);
2895
- const crncyTokenAccount = this.tokens.get(crncyTokenId);
2896
- const assetTokenProgramId = (assetTokenAccount.mask & 0x80000000) == 0 ?
2897
- TOKEN_PROGRAM_ID : TOKEN_2022_PROGRAM_ID;
2898
- const crncyTokenProgramId = (crncyTokenAccount.mask & 0x80000000) == 0 ?
2899
- TOKEN_PROGRAM_ID : TOKEN_2022_PROGRAM_ID;
2900
- let instrId = yield this.getInstrId({
2901
- assetTokenId: assetTokenId,
2902
- crncyTokenId: crncyTokenId
2903
- });
2904
- const clientAssetTokenAccount = yield findAssociatedTokenAddress(this.signer, assetTokenProgramId, args.assetMint);
2905
- const clientCrncyTokenAccount = yield findAssociatedTokenAddress(this.signer, crncyTokenProgramId, args.crncyMint);
2906
- let instr = this.instruments.get(instrId);
2907
- if (instr.header.mapsAddress == undefined) {
2908
- yield this.updateInstrData({ instrId: instrId });
2909
- instr = this.instruments.get(instrId);
2910
- }
2911
- let buf = (0, instruction_models_1.swapData)(26, args.crncyInput ? 1 : 0, instrId, Math.round(args.limitPrice * 1000000000), Math.round(args.amount *
2912
- (args.crncyInput ?
2913
- this.tokenDec(instr.header.crncyTokenId) :
2914
- this.tokenDec(instr.header.assetTokenId))));
2915
- let keys = [
2916
- { address: this.signer, role: kit_1.AccountRole.READONLY_SIGNER },
2917
- { address: this.rootAccount, role: kit_1.AccountRole.READONLY },
2918
- ...yield this.getSpotContext(instr.header),
2919
- ...yield this.getSpotCandles(instr.header),
2920
- {
2921
- address: yield this.getAccountByTag(types_1.AccountType.COMMUNITY),
2922
- role: kit_1.AccountRole.READONLY
2923
- },
2924
- { address: SYSTEM_PROGRAM_ID, role: kit_1.AccountRole.READONLY },
2925
- { address: assetTokenProgramId, role: kit_1.AccountRole.READONLY },
2926
- { address: crncyTokenProgramId, role: kit_1.AccountRole.READONLY },
2927
- { address: assetTokenAccount.programAddress, role: kit_1.AccountRole.WRITABLE },
2928
- { address: crncyTokenAccount.programAddress, role: kit_1.AccountRole.WRITABLE },
2929
- { address: args.assetMint, role: kit_1.AccountRole.READONLY },
2930
- { address: args.crncyMint, role: kit_1.AccountRole.READONLY },
2931
- { address: yield this.getTokenAccount(args.assetMint), role: kit_1.AccountRole.READONLY },
2932
- { address: yield this.getTokenAccount(args.crncyMint), role: kit_1.AccountRole.READONLY },
2933
- { address: clientAssetTokenAccount, role: kit_1.AccountRole.WRITABLE },
2934
- { address: clientCrncyTokenAccount, role: kit_1.AccountRole.WRITABLE },
2935
- { address: this.drvsAuthority, role: kit_1.AccountRole.READONLY },
2936
- ];
2937
- return {
2938
- accounts: keys, programAddress: this.programId, data: buf
2939
- };
2940
- });
2941
- }
2942
- }
2943
- exports.Engine = Engine;
32
+ __exportStar(require("./instruction_models"), exports);