@triadxyz/triad-protocol 2.3.3-beta → 2.3.5-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,22 +1,884 @@
1
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
+ const web3_js_1 = require("@solana/web3.js");
6
16
  const anchor_1 = require("@coral-xyz/anchor");
17
+ const bn_js_1 = __importDefault(require("bn.js"));
7
18
  const idl_triad_protocol_json_1 = __importDefault(require("./types/idl_triad_protocol.json"));
8
- const trade_1 = __importDefault(require("./trade"));
19
+ const types_1 = require("./types");
20
+ const constants_1 = require("./utils/constants");
21
+ const helpers_1 = require("./utils/helpers");
22
+ const pda_1 = require("./utils/pda");
23
+ const sendVersionedTransaction_1 = __importDefault(require("./utils/sendVersionedTransaction"));
24
+ const swap_1 = require("./utils/swap");
9
25
  const stake_1 = __importDefault(require("./stake"));
10
26
  const poseidon_1 = __importDefault(require("./poseidon"));
11
27
  class TriadProtocolClient {
12
28
  constructor(connection, wallet) {
29
+ this.decimals = constants_1.TRD_DECIMALS; // We're using only TRD or USDC so we can use the same decimals 6
13
30
  this.provider = new anchor_1.AnchorProvider(connection, wallet, {
14
31
  commitment: 'confirmed'
15
32
  });
16
33
  this.program = new anchor_1.Program(idl_triad_protocol_json_1.default, this.provider);
17
- this.trade = new trade_1.default(this.program);
18
34
  this.stake = new stake_1.default(this.program);
19
35
  this.poseidon = new poseidon_1.default(this.program);
20
36
  }
37
+ /**
38
+ * Get All Pools
39
+ *
40
+ */
41
+ getAllPools() {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const pool = yield this.program.account.pool.all();
44
+ return pool.map(({ account, publicKey }) => (0, helpers_1.formatPool)(account, publicKey));
45
+ });
46
+ }
47
+ /**
48
+ * Get All Markets
49
+ *
50
+ */
51
+ getAllMarkets() {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ const marketV2 = yield this.program.account.marketV2.all();
54
+ return marketV2.map(({ account, publicKey }) => (0, helpers_1.formatMarket)(account, publicKey));
55
+ });
56
+ }
57
+ /**
58
+ * Get My User Trades from a user authority
59
+ * @param wallet - User wallet PublicKey
60
+ *
61
+ */
62
+ getMyUserTrades(wallet) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ const response = yield this.program.account.userTrade.all([
65
+ {
66
+ memcmp: {
67
+ offset: 8 + 1,
68
+ bytes: wallet.toBase58()
69
+ }
70
+ }
71
+ ]);
72
+ return response.map(({ account, publicKey }) => (0, helpers_1.formatUserTrade)(account, publicKey));
73
+ });
74
+ }
75
+ /**
76
+ * Get User Orders
77
+ * @param wallet - User wallet PublicKey
78
+ *
79
+ */
80
+ getUserOrders(wallet) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const myUserTrades = yield this.getMyUserTrades(wallet);
83
+ return myUserTrades.flatMap((userTrade) => userTrade.orders);
84
+ });
85
+ }
86
+ /**
87
+ * Get Pool By ID
88
+ * @param poolId - The ID of the pool
89
+ *
90
+ */
91
+ getPoolById(poolId) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ const poolPDA = (0, pda_1.getPoolPDA)(this.program.programId, poolId);
94
+ const response = yield this.program.account.pool.fetch(poolPDA);
95
+ return (0, helpers_1.formatPool)(response, poolPDA);
96
+ });
97
+ }
98
+ /**
99
+ * Get Market By ID
100
+ * @param marketId - The ID of the market
101
+ *
102
+ */
103
+ getMarketById(marketId) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ const marketPDA = (0, pda_1.getMarketPDA)(this.program.programId, marketId);
106
+ const response = yield this.program.account.marketV2.fetch(marketPDA);
107
+ return (0, helpers_1.formatMarket)(response, marketPDA);
108
+ });
109
+ }
110
+ /**
111
+ * Get Market By Address
112
+ * @param marketAddress - The address of the market
113
+ *
114
+ */
115
+ getMarketByAddress(marketAddress) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ const account = yield this.program.account.marketV2.fetch(marketAddress);
118
+ return (0, helpers_1.formatMarket)(account, marketAddress);
119
+ });
120
+ }
121
+ /**
122
+ * Get User Trade PDA
123
+ * @param wallet - User wallet PublicKey
124
+ * @param userNonce - The nonce of the user
125
+ *
126
+ */
127
+ getUserPDA(wallet, userNonce = 0) {
128
+ let userTradePDA = (0, pda_1.getUserTradePDA)(this.program.programId, wallet);
129
+ if (userNonce !== 0) {
130
+ const subUserTradePDA = (0, pda_1.getSubUserTradePDA)(this.program.programId, wallet, userNonce);
131
+ userTradePDA = (0, pda_1.getUserTradePDA)(this.program.programId, subUserTradePDA);
132
+ }
133
+ return userTradePDA;
134
+ }
135
+ /**
136
+ * Get User Trade
137
+ * @param wallet - User wallet PublicKey
138
+ * @param userNonce - The nonce of the user
139
+ *
140
+ */
141
+ getUserTrade(wallet, userNonce = 0) {
142
+ return __awaiter(this, void 0, void 0, function* () {
143
+ const userTradePDA = this.getUserPDA(wallet, userNonce);
144
+ return this.program.account.userTrade.fetch(userTradePDA);
145
+ });
146
+ }
147
+ /**
148
+ * Create Market
149
+ * @param args.marketId - new markert id - length + 1
150
+ * @param args.startTime - start time
151
+ * @param args.endTime - end time
152
+ * @param args.question - question (max 80 characters)
153
+ * @param args.liquidityAtStart - liquidity at start
154
+ * @param args.payoutFee - payout fee (to add affiliate system)
155
+ * @param args.currentMarketId - if fast market, we need check the pool parameters
156
+ *
157
+ * @param options - RPC options
158
+ *
159
+ */
160
+ createMarket({ marketId, startTime, endTime, question, feeBps, customer, payoutFee, mint, poolId }, options) {
161
+ return __awaiter(this, void 0, void 0, function* () {
162
+ if (question.length > 80) {
163
+ throw new Error('Question must be less than 80 characters');
164
+ }
165
+ const ixs = [];
166
+ let poolPDA = null;
167
+ if (poolId) {
168
+ poolPDA = (0, pda_1.getPoolPDA)(this.program.programId, poolId);
169
+ }
170
+ let userTrade = null;
171
+ try {
172
+ yield this.getUserTrade(this.program.provider.publicKey);
173
+ userTrade = (0, pda_1.getUserTradePDA)(this.program.programId, this.program.provider.publicKey);
174
+ }
175
+ catch (_a) { }
176
+ ixs.push(yield this.program.methods
177
+ .createMarket({
178
+ marketId: new bn_js_1.default(marketId),
179
+ question: (0, helpers_1.encodeString)(question, 80),
180
+ marketStart: new bn_js_1.default(startTime),
181
+ marketEnd: new bn_js_1.default(endTime),
182
+ feeBps,
183
+ payoutFee
184
+ })
185
+ .accounts({
186
+ signer: this.program.provider.publicKey,
187
+ mint,
188
+ tokenProgram: (0, helpers_1.getTokenProgram)(mint),
189
+ customer,
190
+ pool: poolPDA,
191
+ userTrade
192
+ })
193
+ .instruction());
194
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
195
+ });
196
+ }
197
+ /**
198
+ * Create Pool
199
+ * @param poolId - The ID of the pool
200
+ * @param question - The question of the pool
201
+ * @param markets - The markets of the pool
202
+ *
203
+ * @param options - RPC options
204
+ */
205
+ createPool({ poolId, question, markets, mint, customer, startTime, endTime, feeBps, payoutFee, isFast }, options) {
206
+ return __awaiter(this, void 0, void 0, function* () {
207
+ if (question.length > 80) {
208
+ throw new Error('Pool question must be less than 80 characters');
209
+ }
210
+ const ixs = [];
211
+ const poolPDA = (0, pda_1.getPoolPDA)(this.program.programId, poolId);
212
+ ixs.push(yield this.program.methods
213
+ .createPool({
214
+ poolId: new bn_js_1.default(poolId),
215
+ question: (0, helpers_1.encodeString)(question, 80),
216
+ isFast
217
+ })
218
+ .accounts({
219
+ signer: this.program.provider.publicKey
220
+ })
221
+ .instruction());
222
+ let userTrade = null;
223
+ try {
224
+ yield this.getUserTrade(this.program.provider.publicKey);
225
+ userTrade = (0, pda_1.getUserTradePDA)(this.program.programId, this.program.provider.publicKey);
226
+ }
227
+ catch (_a) { }
228
+ for (const market of markets) {
229
+ if (market.question.length > 80) {
230
+ throw new Error('Market question must be less than 80 characters');
231
+ }
232
+ ixs.push(yield this.program.methods
233
+ .createMarket({
234
+ marketId: new bn_js_1.default(market.marketId),
235
+ question: (0, helpers_1.encodeString)(market.question, 80),
236
+ marketStart: new bn_js_1.default(startTime),
237
+ marketEnd: new bn_js_1.default(endTime),
238
+ feeBps,
239
+ payoutFee
240
+ })
241
+ .accounts({
242
+ signer: this.program.provider.publicKey,
243
+ mint,
244
+ tokenProgram: (0, helpers_1.getTokenProgram)(mint),
245
+ pool: poolPDA,
246
+ customer,
247
+ userTrade
248
+ })
249
+ .instruction());
250
+ }
251
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
252
+ });
253
+ }
254
+ /**
255
+ * Open Order
256
+ * @param args.marketId - The ID of the Market
257
+ * @param args.amount - The amount of the Order
258
+ * @param args.direction - The direction of the Order
259
+ * @param args.mint - The mint of the Order
260
+ * @param args.token - The token to use for the Order
261
+ *
262
+ * @param options - RPC options
263
+ *
264
+ */
265
+ openOrder({ marketId, amount, direction, mint, token }, options) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ const ixs = [];
268
+ const addressLookupTableAccounts = [];
269
+ const { userTradePDA, ixs: userTradeIxs } = yield this.getUserTradeIxs();
270
+ if (userTradeIxs.length > 0) {
271
+ ixs.push(...userTradeIxs);
272
+ }
273
+ let amountInTRD = amount * Math.pow(10, constants_1.TRD_DECIMALS);
274
+ if (token !== constants_1.TRD_MINT.toBase58()) {
275
+ const { setupInstructions, swapIxs, addressLookupTableAccounts, trdAmount } = yield (0, swap_1.swap)({
276
+ connection: this.program.provider.connection,
277
+ wallet: this.program.provider.publicKey.toBase58(),
278
+ inToken: token,
279
+ amount
280
+ });
281
+ amountInTRD = trdAmount;
282
+ if (swapIxs.length === 0) {
283
+ return;
284
+ }
285
+ ixs.push(...setupInstructions);
286
+ ixs.push(...swapIxs);
287
+ addressLookupTableAccounts.push(...addressLookupTableAccounts);
288
+ }
289
+ ixs.push(yield this.program.methods
290
+ .openOrder({
291
+ amount: new bn_js_1.default(amountInTRD),
292
+ direction: direction
293
+ })
294
+ .accounts({
295
+ signer: this.program.provider.publicKey,
296
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
297
+ userTrade: userTradePDA,
298
+ mint
299
+ })
300
+ .instruction());
301
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options, addressLookupTableAccounts);
302
+ });
303
+ }
304
+ /**
305
+ * Close Order
306
+ * @param args.marketId - The ID of the Market
307
+ * @param args.orderId - The ID of the Order
308
+ * @param args.userNonce - The nonce of the user
309
+ *
310
+ * @param options - RPC options
311
+ *
312
+ */
313
+ closeOrder({ marketId, orderId, userNonce }, options) {
314
+ return __awaiter(this, void 0, void 0, function* () {
315
+ const ixs = [];
316
+ const userTrade = this.getUserPDA(this.program.provider.publicKey, userNonce);
317
+ ixs.push(yield this.program.methods
318
+ .closeOrder(new bn_js_1.default(orderId))
319
+ .accounts({
320
+ signer: this.program.provider.publicKey,
321
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
322
+ mint: constants_1.TRD_MINT,
323
+ userTrade
324
+ })
325
+ .instruction());
326
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
327
+ });
328
+ }
329
+ /**
330
+ * Resolve Market
331
+ * @param args.marketId - The ID of the Market
332
+ * @param args.winningDirection - The Winning Direction of the Market
333
+ *
334
+ * @param options - RPC options
335
+ *
336
+ */
337
+ resolveMarket({ marketId, poolId, winningDirection }, options) {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ const ixs = [];
340
+ let poolPDA = null;
341
+ if (poolId) {
342
+ poolPDA = (0, pda_1.getPoolPDA)(this.program.programId, poolId);
343
+ }
344
+ ixs.push(yield this.program.methods
345
+ .updateMarket({
346
+ winningDirection,
347
+ allowPayout: null,
348
+ marketEnd: null
349
+ })
350
+ .accounts({
351
+ signer: this.program.provider.publicKey,
352
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
353
+ pool: poolPDA
354
+ })
355
+ .instruction());
356
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
357
+ });
358
+ }
359
+ /**
360
+ * Collect Remaining Liquidity
361
+ * @param marketId - The ID of the market
362
+ *
363
+ * @param options - RPC options
364
+ *
365
+ */
366
+ collectRemainingLiquidity(marketId, options) {
367
+ return __awaiter(this, void 0, void 0, function* () {
368
+ const ixs = [];
369
+ const marketPDA = (0, pda_1.getMarketPDA)(this.program.programId, marketId);
370
+ const market = yield this.getMarketByAddress(marketPDA);
371
+ ixs.push(yield this.program.methods
372
+ .collectRemainingLiquidity()
373
+ .accounts({
374
+ signer: this.program.provider.publicKey,
375
+ market: marketPDA,
376
+ mint: market.mint
377
+ })
378
+ .instruction());
379
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
380
+ });
381
+ }
382
+ /**
383
+ * Payout Order
384
+ * @param args.marketId - The ID of the Market
385
+ * @param args.orderId - The ID of the Order to Payout
386
+ * @param args.userNonce - The nonce of the user
387
+ *
388
+ * @param options - RPC options
389
+ *
390
+ */
391
+ payoutOrder(orders, options) {
392
+ return __awaiter(this, void 0, void 0, function* () {
393
+ const ixs = [];
394
+ if (orders.length > 10) {
395
+ throw new Error('Max 10 orders per transaction');
396
+ }
397
+ for (const order of orders) {
398
+ ixs.push(yield this.program.methods
399
+ .payoutOrder(new bn_js_1.default(order.orderId))
400
+ .accounts({
401
+ signer: this.program.provider.publicKey,
402
+ userTrade: this.getUserPDA(this.program.provider.publicKey, order.userNonce),
403
+ market: (0, pda_1.getMarketPDA)(this.program.programId, order.marketId),
404
+ mint: order.mint,
405
+ tokenProgram: (0, helpers_1.getTokenProgram)(order.mint)
406
+ })
407
+ .instruction());
408
+ }
409
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
410
+ });
411
+ }
412
+ /**
413
+ * Allow Market to Payout
414
+ * @param marketId - The ID of the market
415
+ * @param poolId - The ID of the pool
416
+ *
417
+ * @param options - RPC options
418
+ *
419
+ */
420
+ allowMarketToPayout({ marketId, poolId }, options) {
421
+ return __awaiter(this, void 0, void 0, function* () {
422
+ const ixs = [];
423
+ let poolPDA = null;
424
+ if (poolId) {
425
+ poolPDA = (0, pda_1.getPoolPDA)(this.program.programId, poolId);
426
+ }
427
+ ixs.push(yield this.program.methods
428
+ .updateMarket({
429
+ winningDirection: null,
430
+ allowPayout: true,
431
+ marketEnd: null
432
+ })
433
+ .accounts({
434
+ signer: this.program.provider.publicKey,
435
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
436
+ pool: poolPDA
437
+ })
438
+ .instruction());
439
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
440
+ });
441
+ }
442
+ /**
443
+ * Create Sub User Trade
444
+ * @param user - User PublicKey the main user
445
+ *
446
+ * @param options - RPC options
447
+ *
448
+ */
449
+ createSubUserTrade(user, options) {
450
+ return __awaiter(this, void 0, void 0, function* () {
451
+ const ixs = [];
452
+ const userTrade = yield this.getUserTrade(user);
453
+ const subUserTradePDA = (0, pda_1.getSubUserTradePDA)(this.program.programId, user, userTrade.nonce + 1);
454
+ ixs.push(yield this.program.methods
455
+ .createSubUserTrade(subUserTradePDA)
456
+ .accounts({
457
+ signer: this.program.provider.publicKey
458
+ })
459
+ .instruction());
460
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
461
+ });
462
+ }
463
+ /**
464
+ * Update Market
465
+ * @param marketId - The ID of the market
466
+ * @param marketEnd - The end time of the market
467
+ *
468
+ * @param options - RPC options
469
+ *
470
+ */
471
+ updateMarket(marketId, marketEnd, options) {
472
+ return __awaiter(this, void 0, void 0, function* () {
473
+ const ixs = [];
474
+ ixs.push(yield this.program.methods
475
+ .updateMarket({
476
+ marketEnd: new bn_js_1.default(marketEnd),
477
+ winningDirection: null,
478
+ allowPayout: null
479
+ })
480
+ .accounts({
481
+ signer: this.program.provider.publicKey,
482
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
483
+ pool: null
484
+ })
485
+ .instruction());
486
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
487
+ });
488
+ }
489
+ /**
490
+ * Create Customer
491
+ * @param args.id - The ID of the customer
492
+ * @param args.name - The name of the customer
493
+ * @param args.authority - The authority of the customer
494
+ * @param args.feeRecipient - The fee recipient of the customer
495
+ *
496
+ * @param options - RPC options
497
+ *
498
+ */
499
+ createCustomer({ id, name, authority, feeRecipient }, options) {
500
+ return __awaiter(this, void 0, void 0, function* () {
501
+ const ixs = [];
502
+ ixs.push(yield this.program.methods
503
+ .createCustomer({ id, name, authority, feeRecipient })
504
+ .accounts({
505
+ signer: this.program.provider.publicKey
506
+ })
507
+ .instruction());
508
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
509
+ });
510
+ }
511
+ /**
512
+ * Get User Trade Nonce With Slots
513
+ * @param userTrades - User Trades
514
+ *
515
+ */
516
+ getUserTradeNonceWithSlots(userTrades) {
517
+ let nonce = null;
518
+ for (const userTrade of userTrades) {
519
+ if (nonce !== null) {
520
+ break;
521
+ }
522
+ userTrade.orders.forEach((order) => {
523
+ if (order.orderStatus !== types_1.OrderStatus.OPEN &&
524
+ order.orderStatus !== types_1.OrderStatus.WAITING) {
525
+ nonce = userTrade.isSubUser ? Number(userTrade.nonce) : 0;
526
+ }
527
+ });
528
+ }
529
+ if (nonce === null) {
530
+ throw new Error('No open orders found');
531
+ }
532
+ return this.getUserPDA(this.program.provider.publicKey, nonce);
533
+ }
534
+ /**
535
+ * Get User Trade Ixs
536
+ *
537
+ */
538
+ getUserTradeIxs() {
539
+ return __awaiter(this, void 0, void 0, function* () {
540
+ const ixs = [];
541
+ let myUserTrades = [];
542
+ myUserTrades = yield this.getMyUserTrades(this.program.provider.publicKey);
543
+ if (myUserTrades.length === 0) {
544
+ ixs.push(yield this.program.methods
545
+ .createUserTrade()
546
+ .accounts({
547
+ signer: this.program.provider.publicKey
548
+ })
549
+ .instruction());
550
+ return {
551
+ userTradePDA: this.getUserPDA(this.program.provider.publicKey),
552
+ ixs,
553
+ nonce: 0
554
+ };
555
+ }
556
+ try {
557
+ const userTradePDA = this.getUserTradeNonceWithSlots(myUserTrades);
558
+ return { userTradePDA, ixs };
559
+ }
560
+ catch (_a) {
561
+ const mainUserTrade = myUserTrades.find((trade) => !trade.isSubUser);
562
+ const subUserTradePDA = (0, pda_1.getSubUserTradePDA)(this.program.programId, this.program.provider.publicKey, Number(mainUserTrade.nonce) + 1);
563
+ ixs.push(yield this.program.methods
564
+ .createSubUserTrade(subUserTradePDA)
565
+ .accounts({
566
+ signer: this.program.provider.publicKey
567
+ })
568
+ .instruction());
569
+ return {
570
+ userTradePDA: (0, pda_1.getUserTradePDA)(this.program.programId, subUserTradePDA),
571
+ ixs
572
+ };
573
+ }
574
+ });
575
+ }
576
+ /**
577
+ * Place Bid Order
578
+ * @param args.marketId - The ID of the Market
579
+ * @param args.amount - The amount of the Order
580
+ * @param args.direction - The direction of the Order
581
+ * @param args.mint - The mint of the Order
582
+ * @param args.price - The price of the Order
583
+ *
584
+ * @param options - RPC options
585
+ */
586
+ placeBidOrder({ marketId, amount, direction, mint, price }, options) {
587
+ return __awaiter(this, void 0, void 0, function* () {
588
+ const ixs = [];
589
+ const { userTradePDA, ixs: userTradeIxs } = yield this.getUserTradeIxs();
590
+ if (userTradeIxs.length > 0) {
591
+ ixs.push(...userTradeIxs);
592
+ }
593
+ ixs.push(yield this.program.methods
594
+ .placeBidOrder({
595
+ amount: new bn_js_1.default(amount * Math.pow(10, this.decimals)),
596
+ price: new bn_js_1.default(price * Math.pow(10, this.decimals)),
597
+ orderDirection: direction
598
+ })
599
+ .accounts({
600
+ signer: this.program.provider.publicKey,
601
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
602
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
603
+ userTrade: userTradePDA,
604
+ mint,
605
+ tokenProgram: (0, helpers_1.getTokenProgram)(mint)
606
+ })
607
+ .instruction());
608
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
609
+ });
610
+ }
611
+ /**
612
+ * Place Ask Order
613
+ * @param args.marketId - The ID of the Market
614
+ * @param args.amount - The amount of the Order
615
+ * @param args.direction - The direction of the Order
616
+ * @param args.price - The price of the Order
617
+ * @param args.bidOrderId - The ID of the Bid Order
618
+ * @param args.bidNonce - The nonce of the Bid Order
619
+ *
620
+ * @param options - RPC options
621
+ *
622
+ */
623
+ placeAskOrder({ marketId, orders }, options) {
624
+ return __awaiter(this, void 0, void 0, function* () {
625
+ const ixs = [];
626
+ for (const order of orders) {
627
+ ixs.push(yield this.program.methods
628
+ .placeAskOrder({
629
+ shares: new bn_js_1.default(order.amount * Math.pow(10, this.decimals)),
630
+ price: new bn_js_1.default(order.price * Math.pow(10, this.decimals)),
631
+ bidOrderId: new bn_js_1.default(order.bidOrderId)
632
+ })
633
+ .accounts({
634
+ signer: this.program.provider.publicKey,
635
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
636
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
637
+ userTrade: this.getUserPDA(this.program.provider.publicKey, order.userNonce)
638
+ })
639
+ .instruction());
640
+ }
641
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
642
+ });
643
+ }
644
+ /**
645
+ * Cancel Bid Order
646
+ * @param args.marketId - The ID of the Market
647
+ * @param args.orderId - The ID of the Order
648
+ * @param args.userNonce - The nonce of the user
649
+ * @param args.direction - The direction of the Order
650
+ *
651
+ * @param options - RPC options
652
+ */
653
+ cancelBidOrder({ marketId, orderId, userNonce, mint, direction }, options) {
654
+ return __awaiter(this, void 0, void 0, function* () {
655
+ const ixs = [];
656
+ ixs.push(yield this.program.methods
657
+ .cancelBidOrder({
658
+ orderId: new bn_js_1.default(orderId),
659
+ orderDirection: direction
660
+ })
661
+ .accounts({
662
+ signer: this.program.provider.publicKey,
663
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
664
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
665
+ userTrade: this.getUserPDA(this.program.provider.publicKey, userNonce),
666
+ mint,
667
+ tokenProgram: (0, helpers_1.getTokenProgram)(mint)
668
+ })
669
+ .instruction());
670
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
671
+ });
672
+ }
673
+ /**
674
+ * Cancel Ask Order
675
+ * @param args.marketId - The ID of the Market
676
+ * @param args.orderId - The ID of the Order
677
+ * @param args.userNonce - The nonce of the user
678
+ * @param args.userNonceBidOrder - The nonce of the bid user
679
+ * @param args.direction - The direction of the Order
680
+ *
681
+ * @param options - RPC options
682
+ */
683
+ cancelAskOrder({ marketId, orderId, userNonce, direction }, options) {
684
+ return __awaiter(this, void 0, void 0, function* () {
685
+ const ixs = [];
686
+ ixs.push(yield this.program.methods
687
+ .cancelAskOrder({
688
+ orderId: new bn_js_1.default(orderId),
689
+ orderDirection: direction
690
+ })
691
+ .accounts({
692
+ signer: this.program.provider.publicKey,
693
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
694
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
695
+ userTrade: this.getUserPDA(this.program.provider.publicKey, userNonce)
696
+ })
697
+ .instruction());
698
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
699
+ });
700
+ }
701
+ /**
702
+ * Market Bid Order
703
+ * @param args.marketId - The ID of the Market
704
+ * @param args.amount - The amount of the Order
705
+ * @param args.direction - The direction of the Order
706
+ * @param args.mint - The mint of the Order
707
+ *
708
+ * @param options - RPC options
709
+ */
710
+ marketBidOrder({ marketId, amount, direction, mint, feeBps = 0 }, options) {
711
+ return __awaiter(this, void 0, void 0, function* () {
712
+ const marketPDA = (0, pda_1.getMarketPDA)(this.program.programId, marketId);
713
+ const ixs = [];
714
+ const { userTradePDA, ixs: userTradeIxs } = yield this.getUserTradeIxs();
715
+ const orderBook = yield this.getOrderBook(marketId);
716
+ let remainingUSDC = new bn_js_1.default(amount * Math.pow(10, this.decimals));
717
+ const orders = Object.keys(direction)[0] === 'hype'
718
+ ? orderBook.hype.ask
719
+ : orderBook.flop.ask;
720
+ const sortedOrders = orders.sort((a, b) => Number(a.price) - Number(b.price));
721
+ const tokenProgram = (0, helpers_1.getTokenProgram)(mint);
722
+ for (const order of sortedOrders) {
723
+ if (remainingUSDC.lte(new bn_js_1.default(0)))
724
+ break;
725
+ if (order.authority === this.program.provider.publicKey.toBase58()) {
726
+ continue;
727
+ }
728
+ const orderPrice = new bn_js_1.default(order.price);
729
+ const availableShares = new bn_js_1.default(order.totalShares).sub(new bn_js_1.default(order.filledShares));
730
+ let adjustedPrice = orderPrice;
731
+ if (feeBps > 0) {
732
+ const priceSpread = new bn_js_1.default(1000000).sub(orderPrice);
733
+ const fee = priceSpread
734
+ .mul(new bn_js_1.default(feeBps))
735
+ .div(new bn_js_1.default(10000))
736
+ .mul(orderPrice)
737
+ .div(new bn_js_1.default(1000000));
738
+ adjustedPrice = orderPrice.add(fee);
739
+ }
740
+ const maxSharesForPrice = remainingUSDC
741
+ .mul(new bn_js_1.default(Math.pow(10, this.decimals)))
742
+ .div(adjustedPrice);
743
+ const sharesToBuy = bn_js_1.default.min(maxSharesForPrice, availableShares);
744
+ if (sharesToBuy.lt(new bn_js_1.default(0)))
745
+ continue;
746
+ const usdcAmount = sharesToBuy
747
+ .mul(adjustedPrice)
748
+ .div(new bn_js_1.default(Math.pow(10, this.decimals)));
749
+ ixs.push(yield this.program.methods
750
+ .marketBidOrder({
751
+ amount: new bn_js_1.default(usdcAmount),
752
+ orderDirection: direction,
753
+ askOrderId: new bn_js_1.default(order.id)
754
+ })
755
+ .accounts({
756
+ signer: this.program.provider.publicKey,
757
+ market: marketPDA,
758
+ buyerTrade: userTradePDA,
759
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
760
+ mint,
761
+ tokenProgram,
762
+ sellerAuthority: new web3_js_1.PublicKey(order.authority),
763
+ sellerTrade: this.getUserPDA(new web3_js_1.PublicKey(order.authority), Number(order.userNonce)),
764
+ marketAta: (0, pda_1.getTokenATA)(marketPDA, mint, tokenProgram),
765
+ buyerAta: (0, pda_1.getTokenATA)(this.program.provider.publicKey, mint, tokenProgram)
766
+ })
767
+ .instruction());
768
+ remainingUSDC = remainingUSDC.sub(usdcAmount);
769
+ }
770
+ if (userTradeIxs.length > 0) {
771
+ ixs.unshift(...userTradeIxs);
772
+ }
773
+ if (ixs.length === 0) {
774
+ throw new Error('No matching orders found to fill the requested amount');
775
+ }
776
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
777
+ });
778
+ }
779
+ marketAskOrder({ marketId, shares, bidOrderId, direction, mint }, options) {
780
+ return __awaiter(this, void 0, void 0, function* () {
781
+ const marketPDA = (0, pda_1.getMarketPDA)(this.program.programId, marketId);
782
+ const ixs = [];
783
+ const { userTradePDA, ixs: userTradeIxs } = yield this.getUserTradeIxs();
784
+ const orderBook = yield this.getOrderBook(marketId);
785
+ let remainingShares = new bn_js_1.default(shares * Math.pow(10, this.decimals));
786
+ const orders = Object.keys(direction)[0] === 'hype'
787
+ ? orderBook.hype.bid
788
+ : orderBook.flop.bid;
789
+ const sortedOrders = orders.sort((a, b) => Number(b.price) - Number(a.price));
790
+ const tokenProgram = (0, helpers_1.getTokenProgram)(mint);
791
+ for (const order of sortedOrders) {
792
+ if (remainingShares.lte(new bn_js_1.default(0)))
793
+ break;
794
+ if (order.authority === this.program.provider.publicKey.toBase58()) {
795
+ continue;
796
+ }
797
+ const availableShares = new bn_js_1.default(order.totalShares).sub(new bn_js_1.default(order.filledShares));
798
+ const sharesToSell = bn_js_1.default.min(remainingShares, availableShares);
799
+ if (sharesToSell.lt(new bn_js_1.default(0)))
800
+ continue;
801
+ ixs.push(yield this.program.methods
802
+ .marketAskOrder({
803
+ shares: new bn_js_1.default(sharesToSell),
804
+ orderDirection: direction,
805
+ bidOrderId: new bn_js_1.default(bidOrderId)
806
+ })
807
+ .accounts({
808
+ signer: this.program.provider.publicKey,
809
+ market: marketPDA,
810
+ buyerTrade: this.getUserPDA(new web3_js_1.PublicKey(order.authority), Number(order.userNonce)),
811
+ orderBook: (0, pda_1.getOrderBookPDA)(this.program.programId, marketId),
812
+ mint,
813
+ tokenProgram,
814
+ marketAta: (0, pda_1.getTokenATA)(marketPDA, mint, tokenProgram),
815
+ sellerTrade: userTradePDA
816
+ })
817
+ .instruction());
818
+ }
819
+ if (userTradeIxs.length > 0) {
820
+ ixs.unshift(...userTradeIxs);
821
+ }
822
+ if (ixs.length === 0) {
823
+ throw new Error('No matching orders found to fill the requested amount');
824
+ }
825
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
826
+ });
827
+ }
828
+ /**
829
+ * Get Orders By Market ID
830
+ * @param marketId - The ID of the market
831
+ *
832
+ */
833
+ getOrderBook(marketId) {
834
+ return __awaiter(this, void 0, void 0, function* () {
835
+ const data = {
836
+ marketId: marketId,
837
+ rewardsAvailable: '0',
838
+ rewardsClaimed: '0',
839
+ spreadToReward: '0',
840
+ hype: { bid: [], ask: [] },
841
+ flop: { bid: [], ask: [] }
842
+ };
843
+ const orderBookPDA = (0, pda_1.getOrderBookPDA)(this.program.programId, marketId);
844
+ const orderBook = yield this.program.account.orderBook.fetch(orderBookPDA);
845
+ data.rewardsAvailable = orderBook.rewardsAvailable.toString();
846
+ data.rewardsClaimed = orderBook.rewardsClaimed.toString();
847
+ data.spreadToReward = orderBook.spreadToReward.toString();
848
+ const processOrders = (orders, side) => {
849
+ for (const order of orders) {
850
+ if ((0, helpers_1.getOrderSideFromNumber)(order.orderSide) === types_1.OrderSide.BID) {
851
+ data[side].bid.push((0, helpers_1.formatBookOrder)(order));
852
+ }
853
+ if ((0, helpers_1.getOrderSideFromNumber)(order.orderSide) === types_1.OrderSide.ASK) {
854
+ data[side].ask.push((0, helpers_1.formatBookOrder)(order));
855
+ }
856
+ }
857
+ };
858
+ processOrders(orderBook.hypeOrders, 'hype');
859
+ processOrders(orderBook.flopOrders, 'flop');
860
+ return data;
861
+ });
862
+ }
863
+ /**
864
+ * Collect Market Fee
865
+ * @param marketId - The ID of the market
866
+ *
867
+ * @param options - RPC options
868
+ */
869
+ collectMarketFee(marketId, options) {
870
+ return __awaiter(this, void 0, void 0, function* () {
871
+ const ixs = [];
872
+ ixs.push(yield this.program.methods
873
+ .collectMarketFee()
874
+ .accounts({
875
+ signer: this.program.provider.publicKey,
876
+ market: (0, pda_1.getMarketPDA)(this.program.programId, marketId),
877
+ mint: constants_1.TRD_MINT
878
+ })
879
+ .instruction());
880
+ return (0, sendVersionedTransaction_1.default)(this.program, ixs, options);
881
+ });
882
+ }
21
883
  }
22
884
  exports.default = TriadProtocolClient;