@deriverse/kit 1.0.39 → 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 -2923
  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
@@ -0,0 +1,745 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Engine = void 0;
13
+ const kit_1 = require("@solana/kit");
14
+ const buffer_1 = require("buffer");
15
+ const types_1 = require("../types");
16
+ const enums_1 = require("../types/enums");
17
+ const constants_1 = require("../constants");
18
+ const structure_models_1 = require("../structure_models");
19
+ const logs_decoder_1 = require("./logs-decoder");
20
+ const account_helpers_1 = require("./account-helpers");
21
+ const context_builders_1 = require("./context-builders");
22
+ const utils_1 = require("./utils");
23
+ const client_queries_1 = require("./client-queries");
24
+ const spot_instructions_1 = require("./spot-instructions");
25
+ const perp_instructions_1 = require("./perp-instructions");
26
+ /**
27
+ * Main class to operate with Deriverse
28
+ * @property {number} originalClientId Deriverse main client ID
29
+ * @property {AddressLookupTableAccount} lut Root address lookup table account
30
+ * @property {AddressLookupTableAccount} clientLut Client address lookup table account
31
+ * @property {Map<number, Token>} tokens Tokens data
32
+ * @property {Map<number, Instrument>} instruments Instruments data
33
+ */
34
+ class Engine {
35
+ /**
36
+ * @param rpc @solana/kit rpc
37
+ */
38
+ constructor(rpc, args) {
39
+ var _a, _b, _c, _d;
40
+ this.originalClientId = null;
41
+ this.clientLutAddress = null;
42
+ this.privateMode = false;
43
+ this.signer = null;
44
+ this.clientPrimaryAccount = null;
45
+ this.clientCommunityAccount = null;
46
+ this.refClientPrimaryAccount = null;
47
+ this.refClientCommunityAccount = null;
48
+ if (args)
49
+ types_1.EngineArgsSchema.parse(args);
50
+ this.rpc = rpc;
51
+ this.programId = (_a = args === null || args === void 0 ? void 0 : args.programId) !== null && _a !== void 0 ? _a : constants_1.PROGRAM_ID;
52
+ this.version = (_b = args === null || args === void 0 ? void 0 : args.version) !== null && _b !== void 0 ? _b : constants_1.VERSION;
53
+ this.commitment = (_c = args === null || args === void 0 ? void 0 : args.commitment) !== null && _c !== void 0 ? _c : 'confirmed';
54
+ this.uiNumbers = (_d = args === null || args === void 0 ? void 0 : args.uiNumbers) !== null && _d !== void 0 ? _d : true;
55
+ (0, constants_1.setDecimals)(this.uiNumbers);
56
+ }
57
+ // ============================================
58
+ // CONTEXT HELPERS (internal)
59
+ // ============================================
60
+ getAccountHelperContext() {
61
+ return {
62
+ rpc: this.rpc,
63
+ programId: this.programId,
64
+ version: this.version,
65
+ commitment: this.commitment,
66
+ drvsAuthority: this.drvsAuthority,
67
+ };
68
+ }
69
+ getSpotInstructionContext() {
70
+ if (this.signer === null) {
71
+ throw new Error('Wallet is not connected');
72
+ }
73
+ if (this.clientPrimaryAccount === null) {
74
+ throw new Error('Client primary account not found');
75
+ }
76
+ if (this.clientCommunityAccount === null) {
77
+ throw new Error('Client community account not found');
78
+ }
79
+ return Object.assign(Object.assign({}, this.getAccountHelperContext()), { instruments: this.instruments, tokens: this.tokens, uiNumbers: this.uiNumbers, signer: this.signer, rootAccount: this.rootAccount, clientPrimaryAccount: this.clientPrimaryAccount, clientCommunityAccount: this.clientCommunityAccount, refClientPrimaryAccount: this.refClientPrimaryAccount, refClientCommunityAccount: this.refClientCommunityAccount, privateMode: this.privateMode });
80
+ }
81
+ getPerpInstructionContext() {
82
+ return Object.assign(Object.assign({}, this.getSpotInstructionContext()), { rootStateModel: this.rootStateModel });
83
+ }
84
+ getClientQueryContext() {
85
+ return Object.assign(Object.assign({}, this.getAccountHelperContext()), { instruments: this.instruments, tokens: this.tokens, uiNumbers: this.uiNumbers, clientPrimaryAccount: this.clientPrimaryAccount, clientCommunityAccount: this.clientCommunityAccount, originalClientId: this.originalClientId });
86
+ }
87
+ requireClient() {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ if (!(yield this.checkClient())) {
90
+ throw new Error('Client account not found');
91
+ }
92
+ });
93
+ }
94
+ requireInstrument(instrId) {
95
+ const instr = this.instruments.get(instrId);
96
+ if (instr === undefined) {
97
+ throw new Error('Instrument not found');
98
+ }
99
+ return instr;
100
+ }
101
+ getSpotInstrumentWithUpdate(instrId) {
102
+ return __awaiter(this, void 0, void 0, function* () {
103
+ let instr = this.instruments.get(instrId);
104
+ if ((instr === null || instr === void 0 ? void 0 : instr.header.mapsAddress) == undefined) {
105
+ yield this.updateInstrData({ instrId });
106
+ instr = this.requireInstrument(instrId);
107
+ }
108
+ return instr;
109
+ });
110
+ }
111
+ getPerpInstrumentWithUpdate(instrId) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ let instr = this.instruments.get(instrId);
114
+ if ((instr === null || instr === void 0 ? void 0 : instr.header.perpMapsAddress) == undefined) {
115
+ yield this.updateInstrData({ instrId });
116
+ instr = this.requireInstrument(instrId);
117
+ }
118
+ return instr;
119
+ });
120
+ }
121
+ checkClient() {
122
+ return __awaiter(this, void 0, void 0, function* () {
123
+ if (this.signer === null) {
124
+ throw new Error('Wallet not connected');
125
+ }
126
+ if (this.clientPrimaryAccount != null) {
127
+ return true;
128
+ }
129
+ const clientPrimaryAccount = yield (0, account_helpers_1.findClientPrimaryAccount)({ programId: this.programId, version: this.version }, this.signer);
130
+ try {
131
+ const info = yield this.rpc
132
+ .getAccountInfo(clientPrimaryAccount, { commitment: this.commitment, encoding: 'base64' })
133
+ .send();
134
+ if (info.value == null) {
135
+ return false;
136
+ }
137
+ const clientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(info.value.data);
138
+ this.clientPrimaryAccount = clientPrimaryAccount;
139
+ this.clientCommunityAccount = yield (0, account_helpers_1.findClientCommunityAccount)({ programId: this.programId, version: this.version }, this.signer);
140
+ this.originalClientId = clientPrimaryAccountHeaderModel.id;
141
+ return true;
142
+ }
143
+ catch (err) {
144
+ console.error(err);
145
+ return false;
146
+ }
147
+ });
148
+ }
149
+ // ============================================
150
+ // LOGS DECODING
151
+ // ============================================
152
+ logsDecode(data) {
153
+ return (0, logs_decoder_1.decodeTransactionLogs)(data, {
154
+ instruments: this.instruments,
155
+ tokens: this.tokens,
156
+ uiNumbers: this.uiNumbers,
157
+ });
158
+ }
159
+ // ============================================
160
+ // INITIALIZATION METHODS
161
+ // ============================================
162
+ initialize() {
163
+ return __awaiter(this, void 0, void 0, function* () {
164
+ try {
165
+ this.drvsAuthority = (yield (0, kit_1.getProgramDerivedAddress)({ programAddress: this.programId, seeds: ['ndxnt'] }))[0];
166
+ const ctx = this.getAccountHelperContext();
167
+ this.rootAccount = yield (0, account_helpers_1.getAccountByTag)(ctx, enums_1.AccountType.ROOT);
168
+ this.communityAccount = yield (0, account_helpers_1.getAccountByTag)(ctx, enums_1.AccountType.COMMUNITY);
169
+ const infos = yield this.rpc
170
+ .getMultipleAccounts([this.rootAccount, this.communityAccount], {
171
+ commitment: this.commitment,
172
+ encoding: 'base64',
173
+ })
174
+ .send();
175
+ if (infos.value == null || infos.value[0] == null || infos.value[1] == null) {
176
+ throw new Error('Initialization failed: getMultipleAccountsInfo');
177
+ }
178
+ this.rootStateModel = structure_models_1.RootStateModel.fromBuffer(infos.value[0].data);
179
+ this.tokens = new Map();
180
+ this.instruments = new Map();
181
+ this.privateMode = (this.rootStateModel.mask & 1) != 0;
182
+ const tokenAccounts = yield (0, account_helpers_1.findAccountsByTag)(ctx, enums_1.AccountType.TOKEN);
183
+ tokenAccounts.forEach((t) => {
184
+ let tokenStateModel = structure_models_1.TokenStateModel.fromBuffer(t.account.data);
185
+ this.tokens.set(tokenStateModel.id, tokenStateModel);
186
+ });
187
+ const instrAccounts = yield (0, account_helpers_1.findAccountsByTag)(ctx, enums_1.AccountType.INSTR, {
188
+ offset: 8,
189
+ length: 16,
190
+ });
191
+ instrAccounts.forEach((response) => {
192
+ const buffer = buffer_1.Buffer.from((0, kit_1.getBase64Encoder)().encode(response.account.data[0]));
193
+ let instrAccountHeaderModel = new structure_models_1.InstrAccountHeaderModel();
194
+ instrAccountHeaderModel.instrId = buffer.readUint32LE(0);
195
+ instrAccountHeaderModel.assetTokenId = buffer.readUint32LE(4);
196
+ instrAccountHeaderModel.crncyTokenId = buffer.readUint32LE(8);
197
+ instrAccountHeaderModel.mask = buffer.readUint32LE(12);
198
+ this.instruments.set(instrAccountHeaderModel.instrId, {
199
+ address: response.pubkey,
200
+ header: instrAccountHeaderModel,
201
+ spotBids: [],
202
+ spotAsks: [],
203
+ perpBids: [],
204
+ perpAsks: [],
205
+ });
206
+ });
207
+ this.updateCommunityFromBuffer(infos.value[1].data);
208
+ return true;
209
+ }
210
+ catch (err) {
211
+ console.error('Initialization failed:', err);
212
+ return false;
213
+ }
214
+ });
215
+ }
216
+ addToken(tokenAccount) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ const info = yield this.rpc
219
+ .getAccountInfo(tokenAccount, { commitment: this.commitment, encoding: 'base64' })
220
+ .send();
221
+ if (info.value == null) {
222
+ throw new Error('Add Token Failed: getAccountInfo');
223
+ }
224
+ const tokenStateModel = structure_models_1.TokenStateModel.fromBuffer(info.value.data);
225
+ if (tokenStateModel.id > this.rootStateModel.tokensCount ||
226
+ tokenStateModel.tag != enums_1.AccountType.TOKEN ||
227
+ tokenStateModel.version != this.version) {
228
+ throw new Error('Invalid Token Account');
229
+ }
230
+ this.tokens.set(tokenStateModel.id, tokenStateModel);
231
+ });
232
+ }
233
+ addInstr(instrAccount) {
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ const info = yield this.rpc
236
+ .getAccountInfo(instrAccount, { commitment: this.commitment, encoding: 'base64' })
237
+ .send();
238
+ if (info.value == null) {
239
+ throw new Error('Add Instrument Failed: getAccountInfo');
240
+ }
241
+ const instrAccountHeaderModel = structure_models_1.InstrAccountHeaderModel.fromBuffer(info.value.data);
242
+ if (instrAccountHeaderModel.instrId > this.rootStateModel.instrCount ||
243
+ instrAccountHeaderModel.tag != enums_1.AccountType.INSTR ||
244
+ instrAccountHeaderModel.version != this.version) {
245
+ throw new Error('Invalid Instrument Account');
246
+ }
247
+ this.instruments.set(instrAccountHeaderModel.instrId, {
248
+ address: instrAccount,
249
+ header: instrAccountHeaderModel,
250
+ spotBids: [],
251
+ spotAsks: [],
252
+ perpBids: [],
253
+ perpAsks: [],
254
+ });
255
+ });
256
+ }
257
+ setSigner(signer) {
258
+ return __awaiter(this, void 0, void 0, function* () {
259
+ this.signer = signer;
260
+ const clientPrimaryAccount = yield (0, account_helpers_1.findClientPrimaryAccount)({ programId: this.programId, version: this.version }, signer);
261
+ let exists = false;
262
+ try {
263
+ const info = yield this.rpc
264
+ .getAccountInfo(clientPrimaryAccount, { commitment: this.commitment, encoding: 'base64' })
265
+ .send();
266
+ if (info.value) {
267
+ const clientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(info.value.data);
268
+ if (clientPrimaryAccountHeaderModel.walletAddress == signer) {
269
+ this.clientPrimaryAccount = clientPrimaryAccount;
270
+ this.clientCommunityAccount = yield (0, account_helpers_1.findClientCommunityAccount)({ programId: this.programId, version: this.version }, signer);
271
+ this.originalClientId = clientPrimaryAccountHeaderModel.id;
272
+ this.clientLutAddress = clientPrimaryAccountHeaderModel.lutAddress;
273
+ let date = Math.floor(new Date().valueOf() / 1000);
274
+ if (date < clientPrimaryAccountHeaderModel.refProgramExpiration) {
275
+ this.refClientPrimaryAccount = clientPrimaryAccountHeaderModel.refAddress;
276
+ if (!this.refClientPrimaryAccount)
277
+ throw new Error('Ref client account address not found');
278
+ let refInfo = yield this.rpc
279
+ .getAccountInfo(this.refClientPrimaryAccount, {
280
+ commitment: this.commitment,
281
+ encoding: 'base64',
282
+ })
283
+ .send();
284
+ if (refInfo.value == null)
285
+ throw new Error('Ref client account not found');
286
+ const refClientPrimaryAccountHeaderModel = structure_models_1.ClientPrimaryAccountHeaderModel.fromBuffer(refInfo.value.data);
287
+ this.refClientCommunityAccount = yield (0, account_helpers_1.findClientCommunityAccount)({ programId: this.programId, version: this.version }, refClientPrimaryAccountHeaderModel.walletAddress);
288
+ }
289
+ exists = true;
290
+ }
291
+ }
292
+ }
293
+ catch (err) {
294
+ console.error(err);
295
+ throw new Error('Wallet connection failed');
296
+ }
297
+ if (!exists) {
298
+ this.clientPrimaryAccount = null;
299
+ this.originalClientId = null;
300
+ }
301
+ });
302
+ }
303
+ // ============================================
304
+ // ACCOUNT & STATE UPDATE METHODS
305
+ // ============================================
306
+ updateCommunityFromBuffer(data) {
307
+ let baseCrncyRecords = new Map();
308
+ let communityAccountHeaderModel = structure_models_1.CommunityAccountHeaderModel.fromBuffer(data);
309
+ const drvsDec = (0, utils_1.tokenDec)(this.tokens, 0, this.uiNumbers);
310
+ communityAccountHeaderModel.prevVotingSupply /= drvsDec;
311
+ communityAccountHeaderModel.votingSupply /= drvsDec;
312
+ communityAccountHeaderModel.drvsTokens /= drvsDec;
313
+ for (let i = 0; i < communityAccountHeaderModel.count; ++i) {
314
+ let record = structure_models_1.BaseCrncyRecordModel.fromBuffer(data, structure_models_1.CommunityAccountHeaderModel.LENGTH + i * structure_models_1.BaseCrncyRecordModel.LENGTH);
315
+ record.funds /= (0, utils_1.tokenDec)(this.tokens, record.crncyTokenId, this.uiNumbers);
316
+ baseCrncyRecords.set(record.crncyTokenId, record);
317
+ }
318
+ this.community = {
319
+ header: communityAccountHeaderModel,
320
+ data: baseCrncyRecords,
321
+ };
322
+ }
323
+ updateCommunity() {
324
+ return __awaiter(this, void 0, void 0, function* () {
325
+ const info = yield this.rpc
326
+ .getAccountInfo(this.communityAccount, { commitment: this.commitment, encoding: 'base64' })
327
+ .send();
328
+ if (info.value == null) {
329
+ throw new Error('Community Account: GetAccountInfo Failed');
330
+ }
331
+ this.updateCommunityFromBuffer(info.value.data);
332
+ });
333
+ }
334
+ updateRootFromBuffer(data) {
335
+ this.rootStateModel = structure_models_1.RootStateModel.fromBuffer(data);
336
+ }
337
+ updateRoot() {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ const info = yield this.rpc
340
+ .getAccountInfo(this.rootAccount, { commitment: this.commitment, encoding: 'base64' })
341
+ .send();
342
+ if (info.value == null) {
343
+ throw new Error('Root Account: GetAccountInfo Failed');
344
+ }
345
+ this.updateRootFromBuffer(info.value.data);
346
+ });
347
+ }
348
+ getInstrAccountByTag(args) {
349
+ return __awaiter(this, void 0, void 0, function* () {
350
+ return (0, account_helpers_1.getInstrAccountByTag)(this.getAccountHelperContext(), args);
351
+ });
352
+ }
353
+ getAccountByTag(tag) {
354
+ return __awaiter(this, void 0, void 0, function* () {
355
+ return (0, account_helpers_1.getAccountByTag)(this.getAccountHelperContext(), tag);
356
+ });
357
+ }
358
+ getTokenAccount(mint) {
359
+ return __awaiter(this, void 0, void 0, function* () {
360
+ return (0, account_helpers_1.getTokenAccount)(this.getAccountHelperContext(), mint);
361
+ });
362
+ }
363
+ getTokenId(mint) {
364
+ return __awaiter(this, void 0, void 0, function* () {
365
+ return (0, account_helpers_1.getTokenId)(this.getAccountHelperContext(), mint);
366
+ });
367
+ }
368
+ getInstrId(args) {
369
+ return __awaiter(this, void 0, void 0, function* () {
370
+ return (0, account_helpers_1.getInstrId)(this.getAccountHelperContext(), args);
371
+ });
372
+ }
373
+ instrLut(args) {
374
+ return this.requireInstrument(args.instrId).header.lutAddress;
375
+ }
376
+ updateInstrData(args) {
377
+ return __awaiter(this, void 0, void 0, function* () {
378
+ const instr = this.instruments.get(args.instrId);
379
+ if (!instr) {
380
+ throw new Error('Instrument not found!');
381
+ }
382
+ const ctx = this.getAccountHelperContext();
383
+ let instrAccount = yield (0, account_helpers_1.getInstrAccountByTag)(ctx, {
384
+ assetTokenId: instr.header.assetTokenId,
385
+ crncyTokenId: instr.header.crncyTokenId,
386
+ tag: enums_1.AccountType.INSTR,
387
+ });
388
+ const info = yield this.rpc
389
+ .getAccountInfo(instrAccount, { commitment: this.commitment, encoding: 'base64' })
390
+ .send();
391
+ if (info.value == null) {
392
+ throw new Error('updateInstrData: getAccountInfo failed');
393
+ }
394
+ yield this.updateInstrDataFromBuffer(info.value.data);
395
+ });
396
+ }
397
+ updateInstrDataFromBuffer(data) {
398
+ return __awaiter(this, void 0, void 0, function* () {
399
+ let header = structure_models_1.InstrAccountHeaderModel.fromBuffer(data);
400
+ header.ps /= constants_1.lpDec;
401
+ const assetTokenDec = (0, utils_1.tokenDec)(this.tokens, header.assetTokenId, this.uiNumbers);
402
+ const crncyTokenDec = (0, utils_1.tokenDec)(this.tokens, header.crncyTokenId, this.uiNumbers);
403
+ header.assetTokens /= assetTokenDec;
404
+ header.crncyTokens /= crncyTokenDec;
405
+ header.protocolFees /= crncyTokenDec;
406
+ header.lastAssetTokens /= assetTokenDec;
407
+ header.lastCrncyTokens /= crncyTokenDec;
408
+ header.dayAssetTokens /= assetTokenDec;
409
+ header.dayCrncyTokens /= crncyTokenDec;
410
+ header.prevDayAssetTokens /= assetTokenDec;
411
+ header.prevDayCrncyTokens /= crncyTokenDec;
412
+ header.perpLastTradeAssetTokens /= assetTokenDec;
413
+ header.perpLastTradeCrncyTokens /= crncyTokenDec;
414
+ header.perpDayAssetTokens /= assetTokenDec;
415
+ header.perpDayCrncyTokens /= crncyTokenDec;
416
+ header.fixingAssetTokens /= assetTokenDec;
417
+ header.fixingCrncyTokens /= crncyTokenDec;
418
+ header.perpFundingFunds /= crncyTokenDec;
419
+ header.perpInsuranceFund /= crncyTokenDec;
420
+ header.perpOpenInt /= assetTokenDec;
421
+ header.perpSocLossFunds /= crncyTokenDec;
422
+ header.perpPrevDayAssetTokens /= assetTokenDec;
423
+ header.perpPrevDayCrncyTokens /= crncyTokenDec;
424
+ header.bestBid /= constants_1.dec;
425
+ header.bestAsk /= constants_1.dec;
426
+ header.dayHigh /= constants_1.dec;
427
+ header.dayLow /= constants_1.dec;
428
+ header.perpBestBid /= constants_1.dec;
429
+ header.perpBestAsk /= constants_1.dec;
430
+ header.perpDayHigh /= constants_1.dec;
431
+ header.perpDayLow /= constants_1.dec;
432
+ header.lastPx /= constants_1.dec;
433
+ header.perpUnderlyingPx /= constants_1.dec;
434
+ header.lastClose /= constants_1.dec;
435
+ header.fixingPx /= constants_1.dec;
436
+ header.perpLastClose /= constants_1.dec;
437
+ header.perpLastPx /= constants_1.dec;
438
+ header.perpLongSpotPriceForWithdrowal /= constants_1.dec;
439
+ header.perpShortSpotPriceForWithdrowal /= constants_1.dec;
440
+ header.poolFees /= crncyTokenDec;
441
+ let spotBids = [];
442
+ let spotAsks = [];
443
+ let perpBids = [];
444
+ let perpAsks = [];
445
+ for (let i = 0; i < constants_1.MARKET_DEPTH; ++i) {
446
+ const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16;
447
+ let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
448
+ if (line.px == 0) {
449
+ break;
450
+ }
451
+ line.px /= constants_1.dec;
452
+ line.qty /= assetTokenDec;
453
+ spotBids.push(line);
454
+ }
455
+ for (let i = 0; i < constants_1.MARKET_DEPTH; ++i) {
456
+ const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * constants_1.MARKET_DEPTH;
457
+ let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
458
+ if (line.px == 0) {
459
+ break;
460
+ }
461
+ line.px /= constants_1.dec;
462
+ line.qty /= assetTokenDec;
463
+ spotAsks.push(line);
464
+ }
465
+ for (let i = 0; i < constants_1.MARKET_DEPTH; ++i) {
466
+ const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * constants_1.MARKET_DEPTH * 2;
467
+ let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
468
+ if (line.px == 0) {
469
+ break;
470
+ }
471
+ line.px /= constants_1.dec;
472
+ line.qty /= assetTokenDec;
473
+ perpBids.push(line);
474
+ }
475
+ for (let i = 0; i < constants_1.MARKET_DEPTH; ++i) {
476
+ const offset = structure_models_1.InstrAccountHeaderModel.LENGTH + i * 16 + 16 * constants_1.MARKET_DEPTH * 3;
477
+ let line = structure_models_1.LineQuotesModel.fromBuffer(data, offset);
478
+ if (line.px == 0) {
479
+ break;
480
+ }
481
+ line.px /= constants_1.dec;
482
+ line.qty /= assetTokenDec;
483
+ perpAsks.push(line);
484
+ }
485
+ let pattern = buffer_1.Buffer.alloc(16);
486
+ pattern.writeInt32LE(this.version, 0);
487
+ pattern.writeInt32LE(enums_1.AccountType.INSTR, 4);
488
+ pattern.writeInt32LE(header.assetTokenId, 8);
489
+ pattern.writeInt32LE(header.crncyTokenId, 12);
490
+ const instrAddress = (yield (0, kit_1.getProgramDerivedAddress)({
491
+ programAddress: this.programId,
492
+ seeds: [pattern, (0, kit_1.getAddressEncoder)().encode(this.drvsAuthority)],
493
+ }))[0];
494
+ this.instruments.set(header.instrId, {
495
+ address: instrAddress,
496
+ header: header,
497
+ spotBids: spotBids,
498
+ spotAsks: spotAsks,
499
+ perpBids: perpBids,
500
+ perpAsks: perpAsks,
501
+ });
502
+ });
503
+ }
504
+ // ============================================
505
+ // CONTEXT BUILDER METHODS
506
+ // ============================================
507
+ getSpotContext(instrAccountHeaderModel) {
508
+ return __awaiter(this, void 0, void 0, function* () {
509
+ return (0, context_builders_1.getSpotContext)(this.getAccountHelperContext(), instrAccountHeaderModel);
510
+ });
511
+ }
512
+ getPerpContext(instrAccountHeaderModel) {
513
+ return __awaiter(this, void 0, void 0, function* () {
514
+ return (0, context_builders_1.getPerpContext)(this.getAccountHelperContext(), instrAccountHeaderModel);
515
+ });
516
+ }
517
+ getSpotCandles(instrAccountHeaderModel) {
518
+ return __awaiter(this, void 0, void 0, function* () {
519
+ return (0, context_builders_1.getSpotCandles)(this.getAccountHelperContext(), instrAccountHeaderModel);
520
+ });
521
+ }
522
+ // ============================================
523
+ // CLIENT DATA QUERY METHODS
524
+ // ============================================
525
+ getClientData() {
526
+ return __awaiter(this, void 0, void 0, function* () {
527
+ yield this.requireClient();
528
+ return (0, client_queries_1.getClientData)(this.getClientQueryContext());
529
+ });
530
+ }
531
+ getClientSpotOrdersInfo(args) {
532
+ return __awaiter(this, void 0, void 0, function* () {
533
+ types_1.GetClientSpotOrdersInfoArgsSchema.parse(args);
534
+ return (0, client_queries_1.getClientSpotOrdersInfo)(this.getClientQueryContext(), args);
535
+ });
536
+ }
537
+ getClientPerpOrdersInfo(args) {
538
+ return __awaiter(this, void 0, void 0, function* () {
539
+ types_1.GetClientPerpOrdersInfoArgsSchema.parse(args);
540
+ return (0, client_queries_1.getClientPerpOrdersInfo)(this.getClientQueryContext(), args);
541
+ });
542
+ }
543
+ getClientSpotOrders(args) {
544
+ return __awaiter(this, void 0, void 0, function* () {
545
+ types_1.GetClientSpotOrdersArgsSchema.parse(args);
546
+ return (0, client_queries_1.getClientSpotOrders)(this.getClientQueryContext(), args);
547
+ });
548
+ }
549
+ getClientPerpOrders(args) {
550
+ return __awaiter(this, void 0, void 0, function* () {
551
+ types_1.GetClientPerpOrdersArgsSchema.parse(args);
552
+ return (0, client_queries_1.getClientPerpOrders)(this.getClientQueryContext(), args);
553
+ });
554
+ }
555
+ // ============================================
556
+ // DEPOSIT & WITHDRAW INSTRUCTIONS
557
+ // ============================================
558
+ depositInstruction(args) {
559
+ return __awaiter(this, void 0, void 0, function* () {
560
+ types_1.DepositArgsSchema.parse(args);
561
+ const exists = yield this.checkClient();
562
+ return (0, spot_instructions_1.buildDepositInstruction)(this.getSpotInstructionContext(), args, exists, () => this.rpc.getSlot().send());
563
+ });
564
+ }
565
+ withdrawInstruction(args) {
566
+ return __awaiter(this, void 0, void 0, function* () {
567
+ types_1.WithdrawArgsSchema.parse(args);
568
+ yield this.requireClient();
569
+ return (0, spot_instructions_1.buildWithdrawInstruction)(this.getSpotInstructionContext(), args);
570
+ });
571
+ }
572
+ // ============================================
573
+ // SPOT TRADING INSTRUCTIONS
574
+ // ============================================
575
+ spotLpInstruction(args) {
576
+ return __awaiter(this, void 0, void 0, function* () {
577
+ types_1.SpotLpArgsSchema.parse(args);
578
+ yield this.requireClient();
579
+ yield this.updateInstrData({ instrId: args.instrId });
580
+ const instr = this.requireInstrument(args.instrId);
581
+ return (0, spot_instructions_1.buildSpotLpInstruction)(this.getSpotInstructionContext(), args, instr);
582
+ });
583
+ }
584
+ newSpotOrderInstruction(args) {
585
+ return __awaiter(this, void 0, void 0, function* () {
586
+ types_1.NewSpotOrderArgsSchema.parse(args);
587
+ yield this.requireClient();
588
+ const instr = yield this.getSpotInstrumentWithUpdate(args.instrId);
589
+ return (0, spot_instructions_1.buildNewSpotOrderInstruction)(this.getSpotInstructionContext(), args, instr);
590
+ });
591
+ }
592
+ spotQuotesReplaceInstruction(args) {
593
+ return __awaiter(this, void 0, void 0, function* () {
594
+ types_1.SpotQuotesReplaceArgsSchema.parse(args);
595
+ yield this.requireClient();
596
+ const instr = yield this.getSpotInstrumentWithUpdate(args.instrId);
597
+ return (0, spot_instructions_1.buildSpotQuotesReplaceInstruction)(this.getSpotInstructionContext(), args, instr);
598
+ });
599
+ }
600
+ spotOrderCancelInstruction(args) {
601
+ return __awaiter(this, void 0, void 0, function* () {
602
+ types_1.SpotOrderCancelArgsSchema.parse(args);
603
+ yield this.requireClient();
604
+ const instr = yield this.getSpotInstrumentWithUpdate(args.instrId);
605
+ return (0, spot_instructions_1.buildSpotOrderCancelInstruction)(this.getSpotInstructionContext(), args, instr);
606
+ });
607
+ }
608
+ spotMassCancelInstruction(args) {
609
+ return __awaiter(this, void 0, void 0, function* () {
610
+ types_1.SpotMassCancelArgsSchema.parse(args);
611
+ yield this.requireClient();
612
+ const instr = yield this.getSpotInstrumentWithUpdate(args.instrId);
613
+ return (0, spot_instructions_1.buildSpotMassCancelInstruction)(this.getSpotInstructionContext(), args, instr);
614
+ });
615
+ }
616
+ swapInstruction(args) {
617
+ return __awaiter(this, void 0, void 0, function* () {
618
+ types_1.SwapArgsSchema.parse(args);
619
+ const assetTokenId = yield this.getTokenId(args.assetMint);
620
+ const crncyTokenId = yield this.getTokenId(args.crncyMint);
621
+ if (assetTokenId === null) {
622
+ throw new Error('Asset token not found!');
623
+ }
624
+ if (crncyTokenId === null) {
625
+ throw new Error('Crncy token not found!');
626
+ }
627
+ const instrId = yield this.getInstrId({ assetTokenId, crncyTokenId });
628
+ if (instrId === null) {
629
+ throw new Error('Instruction not found!');
630
+ }
631
+ const instr = yield this.getSpotInstrumentWithUpdate(instrId);
632
+ return (0, spot_instructions_1.buildSwapInstruction)(this.getSpotInstructionContext(), args, instr);
633
+ });
634
+ }
635
+ // ============================================
636
+ // PERP TRADING INSTRUCTIONS
637
+ // ============================================
638
+ upgradeToPerpInstructions(args) {
639
+ return __awaiter(this, void 0, void 0, function* () {
640
+ types_1.InstrIdSchema.parse(args);
641
+ if (this.signer == null) {
642
+ throw new Error('Wallet is not connected');
643
+ }
644
+ if (this.instruments.get(args.instrId) == null) {
645
+ throw new Error('Invalid Instr ID');
646
+ }
647
+ yield this.updateInstrData({ instrId: args.instrId });
648
+ const instr = this.requireInstrument(args.instrId);
649
+ return (0, perp_instructions_1.buildUpgradeToPerpInstructions)(this.getPerpInstructionContext(), args, instr, (size) => this.rpc.getMinimumBalanceForRentExemption(size).send());
650
+ });
651
+ }
652
+ perpDepositInstruction(args) {
653
+ return __awaiter(this, void 0, void 0, function* () {
654
+ types_1.PerpDepositArgsSchema.parse(args);
655
+ yield this.requireClient();
656
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
657
+ return (0, perp_instructions_1.buildPerpDepositInstruction)(this.getPerpInstructionContext(), args, instr);
658
+ });
659
+ }
660
+ perpBuySeatInstruction(args) {
661
+ return __awaiter(this, void 0, void 0, function* () {
662
+ types_1.PerpBuySeatArgsSchema.parse(args);
663
+ yield this.requireClient();
664
+ yield this.updateInstrData({ instrId: args.instrId });
665
+ const instr = this.requireInstrument(args.instrId);
666
+ return (0, perp_instructions_1.buildPerpBuySeatInstruction)(this.getPerpInstructionContext(), args, instr);
667
+ });
668
+ }
669
+ perpSellSeatInstruction(args) {
670
+ return __awaiter(this, void 0, void 0, function* () {
671
+ types_1.PerpSellSeatArgsSchema.parse(args);
672
+ yield this.requireClient();
673
+ yield this.updateInstrData({ instrId: args.instrId });
674
+ const instr = this.requireInstrument(args.instrId);
675
+ return (0, perp_instructions_1.buildPerpSellSeatInstruction)(this.getPerpInstructionContext(), args, instr);
676
+ });
677
+ }
678
+ newPerpOrderInstruction(args) {
679
+ return __awaiter(this, void 0, void 0, function* () {
680
+ types_1.NewPerpOrderArgsSchema.parse(args);
681
+ yield this.requireClient();
682
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
683
+ return (0, perp_instructions_1.buildNewPerpOrderInstruction)(this.getPerpInstructionContext(), args, instr);
684
+ });
685
+ }
686
+ perpQuotesReplaceInstruction(args) {
687
+ return __awaiter(this, void 0, void 0, function* () {
688
+ types_1.PerpQuotesReplaceArgsSchema.parse(args);
689
+ yield this.requireClient();
690
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
691
+ return (0, perp_instructions_1.buildPerpQuotesReplaceInstruction)(this.getPerpInstructionContext(), args, instr);
692
+ });
693
+ }
694
+ perpOrderCancelInstruction(args) {
695
+ return __awaiter(this, void 0, void 0, function* () {
696
+ types_1.PerpOrderCancelArgsSchema.parse(args);
697
+ yield this.requireClient();
698
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
699
+ return (0, perp_instructions_1.buildPerpOrderCancelInstruction)(this.getPerpInstructionContext(), args, instr);
700
+ });
701
+ }
702
+ perpMassCancelInstruction(args) {
703
+ return __awaiter(this, void 0, void 0, function* () {
704
+ types_1.PerpMassCancelArgsSchema.parse(args);
705
+ yield this.requireClient();
706
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
707
+ return (0, perp_instructions_1.buildPerpMassCancelInstruction)(this.getPerpInstructionContext(), args, instr);
708
+ });
709
+ }
710
+ newRefLinkInstruction() {
711
+ return __awaiter(this, void 0, void 0, function* () {
712
+ yield this.requireClient();
713
+ return (0, perp_instructions_1.buildNewRefLinkInstruction)(this.getPerpInstructionContext());
714
+ });
715
+ }
716
+ perpChangeLeverageInstruction(args) {
717
+ return __awaiter(this, void 0, void 0, function* () {
718
+ types_1.PerpChangeLeverageArgsSchema.parse(args);
719
+ yield this.requireClient();
720
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
721
+ return (0, perp_instructions_1.buildPerpChangeLeverageInstruction)(this.getPerpInstructionContext(), args, instr);
722
+ });
723
+ }
724
+ perpStatisticsResetInstruction(args) {
725
+ return __awaiter(this, void 0, void 0, function* () {
726
+ types_1.PerpStatisticsResetArgsSchema.parse(args);
727
+ yield this.requireClient();
728
+ const instr = yield this.getPerpInstrumentWithUpdate(args.instrId);
729
+ return (0, perp_instructions_1.buildPerpStatisticsResetInstruction)(this.getPerpInstructionContext(), args, instr);
730
+ });
731
+ }
732
+ // ============================================
733
+ // NEW INSTRUMENT INSTRUCTIONS
734
+ // ============================================
735
+ newInstrumentInstructions(args) {
736
+ return __awaiter(this, void 0, void 0, function* () {
737
+ types_1.NewInstrumentArgsSchema.parse(args);
738
+ if (this.signer == null) {
739
+ throw new Error('Wallet is not connected');
740
+ }
741
+ return (0, perp_instructions_1.buildNewInstrumentInstructions)(this.getPerpInstructionContext(), args, () => this.rpc.getSlot().send(), (address) => this.rpc.getAccountInfo(address).send(), (size) => this.rpc.getMinimumBalanceForRentExemption(size).send());
742
+ });
743
+ }
744
+ }
745
+ exports.Engine = Engine;