@symmetry-hq/sdk 1.0.1

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 (121) hide show
  1. package/dist/src/constants.d.ts +23 -0
  2. package/dist/src/constants.js +38 -0
  3. package/dist/src/index.d.ts +804 -0
  4. package/dist/src/index.js +2097 -0
  5. package/dist/src/instructions/automation/auction.d.ts +6 -0
  6. package/dist/src/instructions/automation/auction.js +40 -0
  7. package/dist/src/instructions/automation/claimBounty.d.ts +12 -0
  8. package/dist/src/instructions/automation/claimBounty.js +44 -0
  9. package/dist/src/instructions/automation/flashSwap.d.ts +21 -0
  10. package/dist/src/instructions/automation/flashSwap.js +74 -0
  11. package/dist/src/instructions/automation/priceUpdate.d.ts +19 -0
  12. package/dist/src/instructions/automation/priceUpdate.js +89 -0
  13. package/dist/src/instructions/automation/rebalanceIntent.d.ts +32 -0
  14. package/dist/src/instructions/automation/rebalanceIntent.js +117 -0
  15. package/dist/src/instructions/automation/rebalanceSwap.d.ts +11 -0
  16. package/dist/src/instructions/automation/rebalanceSwap.js +42 -0
  17. package/dist/src/instructions/management/addBounty.d.ts +7 -0
  18. package/dist/src/instructions/management/addBounty.js +41 -0
  19. package/dist/src/instructions/management/admin.d.ts +9 -0
  20. package/dist/src/instructions/management/admin.js +53 -0
  21. package/dist/src/instructions/management/claimFees.d.ts +15 -0
  22. package/dist/src/instructions/management/claimFees.js +95 -0
  23. package/dist/src/instructions/management/createBasket.d.ts +21 -0
  24. package/dist/src/instructions/management/createBasket.js +98 -0
  25. package/dist/src/instructions/management/edit.d.ts +51 -0
  26. package/dist/src/instructions/management/edit.js +477 -0
  27. package/dist/src/instructions/management/luts.d.ts +30 -0
  28. package/dist/src/instructions/management/luts.js +99 -0
  29. package/dist/src/instructions/pda.d.ts +25 -0
  30. package/dist/src/instructions/pda.js +128 -0
  31. package/dist/src/instructions/user/deposit.d.ts +20 -0
  32. package/dist/src/instructions/user/deposit.js +100 -0
  33. package/dist/src/instructions/user/withdraw.d.ts +8 -0
  34. package/dist/src/instructions/user/withdraw.js +36 -0
  35. package/dist/src/jup.d.ts +49 -0
  36. package/dist/src/jup.js +80 -0
  37. package/dist/src/keeperMonitor.d.ts +52 -0
  38. package/dist/src/keeperMonitor.js +624 -0
  39. package/dist/src/layouts/basket.d.ts +191 -0
  40. package/dist/src/layouts/basket.js +51 -0
  41. package/dist/src/layouts/config.d.ts +281 -0
  42. package/dist/src/layouts/config.js +237 -0
  43. package/dist/src/layouts/fraction.d.ts +20 -0
  44. package/dist/src/layouts/fraction.js +164 -0
  45. package/dist/src/layouts/intents/bounty.d.ts +18 -0
  46. package/dist/src/layouts/intents/bounty.js +19 -0
  47. package/dist/src/layouts/intents/intent.d.ts +209 -0
  48. package/dist/src/layouts/intents/intent.js +97 -0
  49. package/dist/src/layouts/intents/rebalanceIntent.d.ts +212 -0
  50. package/dist/src/layouts/intents/rebalanceIntent.js +94 -0
  51. package/dist/src/layouts/lookupTable.d.ts +7 -0
  52. package/dist/src/layouts/lookupTable.js +10 -0
  53. package/dist/src/layouts/oracle.d.ts +63 -0
  54. package/dist/src/layouts/oracle.js +96 -0
  55. package/dist/src/states/basket.d.ts +14 -0
  56. package/dist/src/states/basket.js +479 -0
  57. package/dist/src/states/config.d.ts +3 -0
  58. package/dist/src/states/config.js +71 -0
  59. package/dist/src/states/intents/intent.d.ts +10 -0
  60. package/dist/src/states/intents/intent.js +316 -0
  61. package/dist/src/states/intents/rebalanceIntent.d.ts +42 -0
  62. package/dist/src/states/intents/rebalanceIntent.js +680 -0
  63. package/dist/src/states/oracles/constants.d.ts +9 -0
  64. package/dist/src/states/oracles/constants.js +15 -0
  65. package/dist/src/states/oracles/oracle.d.ts +24 -0
  66. package/dist/src/states/oracles/oracle.js +168 -0
  67. package/dist/src/states/oracles/pythOracle.d.ts +132 -0
  68. package/dist/src/states/oracles/pythOracle.js +609 -0
  69. package/dist/src/states/oracles/raydiumClmmOracle.d.ts +184 -0
  70. package/dist/src/states/oracles/raydiumClmmOracle.js +843 -0
  71. package/dist/src/states/oracles/raydiumCpmmOracle.d.ts +120 -0
  72. package/dist/src/states/oracles/raydiumCpmmOracle.js +540 -0
  73. package/dist/src/states/oracles/switchboardOracle.d.ts +0 -0
  74. package/dist/src/states/oracles/switchboardOracle.js +1 -0
  75. package/dist/src/states/withdrawBasketFees.d.ts +10 -0
  76. package/dist/src/states/withdrawBasketFees.js +154 -0
  77. package/dist/src/txUtils.d.ts +65 -0
  78. package/dist/src/txUtils.js +306 -0
  79. package/dist/test.d.ts +1 -0
  80. package/dist/test.js +561 -0
  81. package/package.json +31 -0
  82. package/src/constants.ts +40 -0
  83. package/src/index.ts +2431 -0
  84. package/src/instructions/automation/auction.ts +55 -0
  85. package/src/instructions/automation/claimBounty.ts +69 -0
  86. package/src/instructions/automation/flashSwap.ts +104 -0
  87. package/src/instructions/automation/priceUpdate.ts +117 -0
  88. package/src/instructions/automation/rebalanceIntent.ts +181 -0
  89. package/src/instructions/management/addBounty.ts +55 -0
  90. package/src/instructions/management/admin.ts +72 -0
  91. package/src/instructions/management/claimFees.ts +129 -0
  92. package/src/instructions/management/createBasket.ts +138 -0
  93. package/src/instructions/management/edit.ts +602 -0
  94. package/src/instructions/management/luts.ts +157 -0
  95. package/src/instructions/pda.ts +151 -0
  96. package/src/instructions/user/deposit.ts +143 -0
  97. package/src/instructions/user/withdraw.ts +53 -0
  98. package/src/jup.ts +113 -0
  99. package/src/keeperMonitor.ts +585 -0
  100. package/src/layouts/basket.ts +233 -0
  101. package/src/layouts/config.ts +576 -0
  102. package/src/layouts/fraction.ts +164 -0
  103. package/src/layouts/intents/bounty.ts +35 -0
  104. package/src/layouts/intents/intent.ts +324 -0
  105. package/src/layouts/intents/rebalanceIntent.ts +306 -0
  106. package/src/layouts/lookupTable.ts +14 -0
  107. package/src/layouts/oracle.ts +157 -0
  108. package/src/states/basket.ts +527 -0
  109. package/src/states/config.ts +62 -0
  110. package/src/states/intents/intent.ts +311 -0
  111. package/src/states/intents/rebalanceIntent.ts +751 -0
  112. package/src/states/oracles/constants.ts +13 -0
  113. package/src/states/oracles/oracle.ts +212 -0
  114. package/src/states/oracles/pythOracle.ts +874 -0
  115. package/src/states/oracles/raydiumClmmOracle.ts +1193 -0
  116. package/src/states/oracles/raydiumCpmmOracle.ts +784 -0
  117. package/src/states/oracles/switchboardOracle.ts +0 -0
  118. package/src/states/withdrawBasketFees.ts +160 -0
  119. package/src/txUtils.ts +424 -0
  120. package/test.ts +609 -0
  121. package/tsconfig.json +101 -0
@@ -0,0 +1,680 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.computeRebalanceIntentBountyAmount = computeRebalanceIntentBountyAmount;
16
+ exports.formatRebalanceIntent = formatRebalanceIntent;
17
+ exports.fetchRebalanceIntent = fetchRebalanceIntent;
18
+ exports.fetchRebalanceIntentsMultiple = fetchRebalanceIntentsMultiple;
19
+ exports.fetchRebalanceIntents = fetchRebalanceIntents;
20
+ exports.getSwapPairs = getSwapPairs;
21
+ const web3_js_1 = require("@solana/web3.js");
22
+ const rebalanceIntent_1 = require("../../layouts/intents/rebalanceIntent");
23
+ const constants_1 = require("../../constants");
24
+ const fraction_1 = require("../../layouts/fraction");
25
+ const txUtils_1 = require("../../txUtils");
26
+ const bn_js_1 = __importDefault(require("bn.js"));
27
+ const basket_1 = require("../basket");
28
+ function computeRebalanceIntentBountyAmount(rebalance_type, num_tokens, bounty_bond, bounty_per_task, bounty_per_price_update_task_max) {
29
+ let num_tasks = 0;
30
+ num_tasks += 1; // FinishPriceUpdates;
31
+ num_tasks += 1; // CancelRebalance;
32
+ if (rebalance_type == rebalanceIntent_1.RebalanceType.Deposit) {
33
+ num_tasks += 1; // MintBasket;
34
+ }
35
+ if (rebalance_type == rebalanceIntent_1.RebalanceType.Deposit || rebalance_type == rebalanceIntent_1.RebalanceType.Withdraw) {
36
+ num_tasks += num_tokens; // TokenSettlement;
37
+ }
38
+ else {
39
+ num_tasks += 1; // AuctionCreation;
40
+ }
41
+ let claim_bounty_tasks = (num_tasks + constants_1.MAX_TRANSFER_TOKENS - 1) / constants_1.MAX_TRANSFER_TOKENS;
42
+ let price_update_tasks = num_tokens;
43
+ let tasks = num_tasks + claim_bounty_tasks;
44
+ let bounty_total = bounty_per_price_update_task_max * price_update_tasks +
45
+ bounty_per_task * tasks +
46
+ bounty_bond;
47
+ return bounty_total;
48
+ }
49
+ function formatRebalanceIntent(rebalanceIntent, basket) {
50
+ var _a, _b, _c, _d;
51
+ let numTokens = constants_1.MAX_SUPPORTED_TOKENS_PER_BASKET;
52
+ while (numTokens > 0 && rebalanceIntent.tokens[numTokens - 1].mint.equals(web3_js_1.PublicKey.default))
53
+ numTokens--;
54
+ rebalanceIntent.tokens = rebalanceIntent.tokens.slice(0, numTokens);
55
+ rebalanceIntent.priceUpdateTasks = rebalanceIntent.priceUpdateTasks.slice(0, numTokens);
56
+ rebalanceIntent.tokenSettlementTasks = rebalanceIntent.tokenSettlementTasks.slice(0, numTokens);
57
+ let priceUpdateTasks = [];
58
+ for (let i = 0; i < numTokens; i++) {
59
+ priceUpdateTasks.push({
60
+ completed_by: rebalanceIntent.priceUpdateTasks[i].completedBy.toBase58(),
61
+ completed_bounty: parseInt(rebalanceIntent.priceUpdateTasks[i].completedBounty.toString()),
62
+ completed_time: parseInt(rebalanceIntent.priceUpdateTasks[i].completedTime.toString()),
63
+ });
64
+ }
65
+ let tokenSettlementTasks = [];
66
+ for (let i = 0; i < numTokens; i++) {
67
+ tokenSettlementTasks.push({
68
+ completed_by: rebalanceIntent.tokenSettlementTasks[i].completedBy.toBase58(),
69
+ completed_bounty: parseInt(rebalanceIntent.tokenSettlementTasks[i].completedBounty.toString()),
70
+ completed_time: parseInt(rebalanceIntent.tokenSettlementTasks[i].completedTime.toString()),
71
+ });
72
+ }
73
+ let placeholderTask = {
74
+ completed_by: rebalanceIntent.placeholderTask.completedBy.toBase58(),
75
+ completed_bounty: parseInt(rebalanceIntent.placeholderTask.completedBounty.toString()),
76
+ completed_time: parseInt(rebalanceIntent.placeholderTask.completedTime.toString()),
77
+ };
78
+ let finishPriceUpdateTask = {
79
+ completed_by: rebalanceIntent.finishPriceUpdateTask.completedBy.toBase58(),
80
+ completed_bounty: parseInt(rebalanceIntent.finishPriceUpdateTask.completedBounty.toString()),
81
+ completed_time: parseInt(rebalanceIntent.finishPriceUpdateTask.completedTime.toString()),
82
+ };
83
+ let auctionCreationTask = {
84
+ completed_by: rebalanceIntent.auctionCreationTask.completedBy.toBase58(),
85
+ completed_bounty: parseInt(rebalanceIntent.auctionCreationTask.completedBounty.toString()),
86
+ completed_time: parseInt(rebalanceIntent.auctionCreationTask.completedTime.toString()),
87
+ };
88
+ let mintBasketTask = {
89
+ completed_by: rebalanceIntent.mintBasketTask.completedBy.toBase58(),
90
+ completed_bounty: parseInt(rebalanceIntent.mintBasketTask.completedBounty.toString()),
91
+ completed_time: parseInt(rebalanceIntent.mintBasketTask.completedTime.toString()),
92
+ };
93
+ let cancelRebalanceTask = {
94
+ completed_by: rebalanceIntent.cancelRebalanceTask.completedBy.toBase58(),
95
+ completed_bounty: parseInt(rebalanceIntent.cancelRebalanceTask.completedBounty.toString()),
96
+ completed_time: parseInt(rebalanceIntent.cancelRebalanceTask.completedTime.toString()),
97
+ };
98
+ let tasks = [
99
+ placeholderTask,
100
+ finishPriceUpdateTask,
101
+ auctionCreationTask,
102
+ mintBasketTask,
103
+ cancelRebalanceTask,
104
+ ...tokenSettlementTasks,
105
+ ...priceUpdateTasks,
106
+ ];
107
+ let depositData = {
108
+ tokens: rebalanceIntent.tokens.map(token => ({
109
+ mint: token.mint.toBase58(),
110
+ amount: parseInt(token.amount.toString()),
111
+ })),
112
+ };
113
+ let priceUpdatesData = {
114
+ tokens: rebalanceIntent.priceUpdateTasks.map((task, index) => ({
115
+ mint: rebalanceIntent.tokens[index].mint.toBase58(),
116
+ updated: parseInt(task.completedTime.toString()) > 0 ? true : false,
117
+ price: (0, fraction_1.fractionToDecimal)(rebalanceIntent.tokens[index].price.price).toNumber(),
118
+ conf: (0, fraction_1.fractionToDecimal)(rebalanceIntent.tokens[index].price.conf).toNumber(),
119
+ expiration: parseInt(task.completedTime.toString()) + 60,
120
+ update_time: parseInt(task.completedTime.toString()),
121
+ })),
122
+ };
123
+ let auctionData = {
124
+ auction_stages: rebalanceIntent.auctions.map(auction => ({
125
+ start_time: parseInt(auction.startTime.toString()),
126
+ end_time: parseInt(auction.endTime.toString()),
127
+ })),
128
+ tokens: rebalanceIntent.tokens.map(token => ({
129
+ mint: token.mint.toBase58(),
130
+ amount: parseInt(token.amount.toString()),
131
+ target_amount: parseInt(token.targetAmount.toString()),
132
+ price: (0, fraction_1.fractionToDecimal)(token.price.price).toNumber(),
133
+ conf: (0, fraction_1.fractionToDecimal)(token.price.conf).toNumber(),
134
+ })),
135
+ };
136
+ let mintData = {
137
+ mintAmount: 0,
138
+ mintValue: 0,
139
+ fees: {
140
+ host: 0,
141
+ creator: 0,
142
+ managers: 0,
143
+ symmetry: 0,
144
+ basket: 0,
145
+ },
146
+ tokens: auctionData.tokens.map(token => ({
147
+ mint: token.mint,
148
+ contribution_amount: 0,
149
+ remaining_amount: 0,
150
+ })),
151
+ };
152
+ if (basket) {
153
+ let minRatio = 1;
154
+ for (let i = 0; i < basket.composition.length; i++) {
155
+ if (basket.composition[i].amount == 0)
156
+ continue;
157
+ let ratio = auctionData.tokens[i].amount / basket.composition[i].amount;
158
+ minRatio = Math.min(minRatio, ratio);
159
+ }
160
+ let mintValue = 0;
161
+ let remainingValue = 0;
162
+ let mintAmount = Math.floor(basket.supply_outstanding * minRatio);
163
+ for (let i = 0; i < basket.composition.length; i++) {
164
+ let contributionAmount = Math.floor(basket.composition[i].amount * minRatio);
165
+ contributionAmount = Math.min(contributionAmount, auctionData.tokens[i].amount);
166
+ mintData.tokens[i].contribution_amount = contributionAmount;
167
+ mintData.tokens[i].remaining_amount = auctionData.tokens[i].amount - contributionAmount;
168
+ mintValue += contributionAmount * auctionData.tokens[i].price;
169
+ remainingValue += (auctionData.tokens[i].amount - contributionAmount) * auctionData.tokens[i].price;
170
+ }
171
+ mintData.mintValue = mintValue;
172
+ mintData.mintAmount = mintAmount;
173
+ mintData.fees.host = Math.floor(mintValue * rebalanceIntent.basketFeeSettings.hostDepositFeeBps / constants_1.HUNDRED_PERCENT_BPS);
174
+ mintData.fees.creator = Math.floor(mintValue * rebalanceIntent.basketFeeSettings.creatorDepositFeeBps / constants_1.HUNDRED_PERCENT_BPS);
175
+ mintData.fees.managers = Math.floor(mintValue * rebalanceIntent.basketFeeSettings.managersDepositFeeBps / constants_1.HUNDRED_PERCENT_BPS);
176
+ mintData.fees.basket = Math.floor(mintValue * rebalanceIntent.basketFeeSettings.basketDepositFeeBps / constants_1.HUNDRED_PERCENT_BPS);
177
+ mintData.fees.symmetry = Math.floor(mintValue * 10 / constants_1.HUNDRED_PERCENT_BPS);
178
+ mintData.mintAmount -= mintData.fees.host + mintData.fees.creator + mintData.fees.managers + mintData.fees.symmetry + mintData.fees.basket;
179
+ }
180
+ let redeemData = {
181
+ tokens: rebalanceIntent.tokens.map(token => ({
182
+ mint: token.mint.toBase58(),
183
+ amount: parseInt(token.amount.toString()),
184
+ })).filter(token => token.amount > 0),
185
+ };
186
+ let bountyData = {
187
+ bounty_mint: rebalanceIntent.bounty.bountyMint.toBase58(),
188
+ keepers: [],
189
+ unused_bounty: {
190
+ pubkey: rebalanceIntent.bounty.bountyDepositor.toBase58(),
191
+ bounty_amount: parseInt(rebalanceIntent.bounty.bountyLeft.toString()),
192
+ },
193
+ rent: {
194
+ pubkey: rebalanceIntent.rentPayer.toBase58(),
195
+ sol_amount: (_a = rebalanceIntent.solBalance) !== null && _a !== void 0 ? _a : 0,
196
+ },
197
+ };
198
+ for (let i = 0; i < tasks.length; i++) {
199
+ if (tasks[i].completed_bounty > 0) {
200
+ let indexOf = bountyData.keepers.findIndex(keeper => keeper.pubkey == tasks[i].completed_by);
201
+ if (indexOf == -1) {
202
+ bountyData.keepers.push({
203
+ pubkey: tasks[i].completed_by,
204
+ bounty_amount: tasks[i].completed_bounty,
205
+ });
206
+ bountyData.unused_bounty.bounty_amount -= tasks[i].completed_bounty;
207
+ }
208
+ else {
209
+ bountyData.keepers[indexOf].bounty_amount += tasks[i].completed_bounty;
210
+ }
211
+ }
212
+ }
213
+ let formatted = {
214
+ pubkey: rebalanceIntent.ownAddress.toBase58(),
215
+ sol_balance: (_b = rebalanceIntent.solBalance) !== null && _b !== void 0 ? _b : 0,
216
+ basket: rebalanceIntent.basket.toBase58(),
217
+ owner: rebalanceIntent.owner.toBase58(),
218
+ rent_payer: rebalanceIntent.rentPayer.toBase58(),
219
+ rebalance_type: (_c = rebalanceIntent_1.REBALANCE_TYPE_STRINGS.get(rebalanceIntent.rebalanceType)) !== null && _c !== void 0 ? _c : "basket_custom",
220
+ current_action: (_d = rebalanceIntent_1.REBALANCE_ACTION_STRINGS.get(rebalanceIntent.currentAction)) !== null && _d !== void 0 ? _d : "not_active",
221
+ withdraw_params_burn_amount: parseInt(rebalanceIntent.withdrawParamsBurnAmount.toString()),
222
+ withdraw_params_amount_wo_fees: parseInt(rebalanceIntent.withdrawParamsAmountWoFees.toString()),
223
+ withdraw_params_keep_tokens_bitmask: rebalanceIntent.withdrawParamsKeepTokensBitmask,
224
+ withdraw_params_keep_all_tokens: rebalanceIntent.withdrawParamsKeepAllTokens == 1 ? true : false,
225
+ basket_fee_settings: {
226
+ host_deposit_fee_bps: rebalanceIntent.basketFeeSettings.hostDepositFeeBps,
227
+ host_withdraw_fee_bps: rebalanceIntent.basketFeeSettings.hostWithdrawFeeBps,
228
+ host_management_fee_bps: rebalanceIntent.basketFeeSettings.hostManagementFeeBps,
229
+ host_performance_fee_bps: rebalanceIntent.basketFeeSettings.hostPerformanceFeeBps,
230
+ creator_deposit_fee_bps: rebalanceIntent.basketFeeSettings.creatorDepositFeeBps,
231
+ creator_withdraw_fee_bps: rebalanceIntent.basketFeeSettings.creatorWithdrawFeeBps,
232
+ creator_management_fee_bps: rebalanceIntent.basketFeeSettings.creatorManagementFeeBps,
233
+ creator_performance_fee_bps: rebalanceIntent.basketFeeSettings.creatorPerformanceFeeBps,
234
+ managers_deposit_fee_bps: rebalanceIntent.basketFeeSettings.managersDepositFeeBps,
235
+ managers_withdraw_fee_bps: rebalanceIntent.basketFeeSettings.managersWithdrawFeeBps,
236
+ managers_management_fee_bps: rebalanceIntent.basketFeeSettings.managersManagementFeeBps,
237
+ managers_performance_fee_bps: rebalanceIntent.basketFeeSettings.managersPerformanceFeeBps,
238
+ basket_deposit_fee_bps: rebalanceIntent.basketFeeSettings.basketDepositFeeBps,
239
+ basket_withdraw_fee_bps: rebalanceIntent.basketFeeSettings.basketWithdrawFeeBps,
240
+ modification_delay: parseInt(rebalanceIntent.basketFeeSettings.modificationDelay.toString()),
241
+ updated_at: 0,
242
+ },
243
+ execution_start_time: parseInt(rebalanceIntent.executionStartTime.toString()),
244
+ rebalance_threshold_slippage_bps: rebalanceIntent.rebalanceThresholdSlippageBps,
245
+ per_trade_rebalance_threshold_slippage_bps: rebalanceIntent.perTradeRebalanceThresholdSlippageBps,
246
+ initial_tvl: (0, fraction_1.fractionToDecimal)(rebalanceIntent.initialTvl).toNumber(),
247
+ auction_update_timestamp: parseInt(rebalanceIntent.auctionUpdateTimestamp.toString()),
248
+ auctions: rebalanceIntent.auctions.map(auction => ({
249
+ start_time: parseInt(auction.startTime.toString()),
250
+ end_time: parseInt(auction.endTime.toString()),
251
+ })),
252
+ tokens: rebalanceIntent.tokens.map(token => ({
253
+ mint: token.mint.toBase58(),
254
+ amount: parseInt(token.amount.toString()),
255
+ target_amount: parseInt(token.targetAmount.toString()),
256
+ price: {
257
+ price: (0, fraction_1.fractionToDecimal)(token.price.price).toNumber(),
258
+ conf: (0, fraction_1.fractionToDecimal)(token.price.conf).toNumber(),
259
+ update_time: parseInt(token.price.updateTime.toString()),
260
+ },
261
+ keep_token: token.keepToken == 1 ? true : false,
262
+ })),
263
+ last_action_timestamp: parseInt(rebalanceIntent.lastActionTimestamp.toString()),
264
+ bounty: {
265
+ bounty_depositor: rebalanceIntent.bounty.bountyDepositor.toBase58(),
266
+ bounty_mint: rebalanceIntent.bounty.bountyMint.toBase58(),
267
+ bounty_per_price_update_task: {
268
+ min_bounty: parseInt(rebalanceIntent.bounty.bountyPerPriceUpdateTask.minBounty.toString()),
269
+ max_bounty: parseInt(rebalanceIntent.bounty.bountyPerPriceUpdateTask.maxBounty.toString()),
270
+ min_bounty_until: parseInt(rebalanceIntent.bounty.bountyPerPriceUpdateTask.minBountyUntil.toString()),
271
+ max_bounty_after: parseInt(rebalanceIntent.bounty.bountyPerPriceUpdateTask.maxBountyAfter.toString()),
272
+ },
273
+ bounty_per_task: {
274
+ min_bounty: parseInt(rebalanceIntent.bounty.bountyPerTask.minBounty.toString()),
275
+ max_bounty: parseInt(rebalanceIntent.bounty.bountyPerTask.maxBounty.toString()),
276
+ min_bounty_until: parseInt(rebalanceIntent.bounty.bountyPerTask.minBountyUntil.toString()),
277
+ max_bounty_after: parseInt(rebalanceIntent.bounty.bountyPerTask.maxBountyAfter.toString()),
278
+ },
279
+ bounty_total: parseInt(rebalanceIntent.bounty.bountyTotal.toString()),
280
+ bounty_left: parseInt(rebalanceIntent.bounty.bountyLeft.toString()),
281
+ },
282
+ bounty_adjustment_amount: parseInt(rebalanceIntent.bountyAdjustmentAmount.toString()),
283
+ placeholder_task: placeholderTask,
284
+ price_update_tasks: priceUpdateTasks,
285
+ finish_price_update_task: finishPriceUpdateTask,
286
+ auction_creation_task: auctionCreationTask,
287
+ mint_basket_task: mintBasketTask,
288
+ cancel_rebalance_task: cancelRebalanceTask,
289
+ token_settlement_tasks: tokenSettlementTasks,
290
+ };
291
+ let uiRebalanceIntent = {
292
+ rebalance_type: formatted.mint_basket_task.completed_time > 0 ? "deposit" : formatted.rebalance_type,
293
+ formatted_data: formatted,
294
+ chain_data: rebalanceIntent,
295
+ deposit_data: null,
296
+ price_updates_data: null,
297
+ auction_data: null,
298
+ mint_data: null,
299
+ redeem_data: null,
300
+ claim_bounty_data: null,
301
+ };
302
+ if (formatted.current_action == "deposit_tokens") {
303
+ uiRebalanceIntent.deposit_data = depositData;
304
+ }
305
+ if (formatted.current_action == "update_prices") {
306
+ uiRebalanceIntent.price_updates_data = priceUpdatesData;
307
+ }
308
+ if (formatted.current_action == "auction") {
309
+ let now = Math.floor(Date.now() / 1000);
310
+ if (now <= auctionData.auction_stages[2].end_time) {
311
+ uiRebalanceIntent.auction_data = auctionData;
312
+ }
313
+ else {
314
+ if (formatted.rebalance_type == "deposit") {
315
+ uiRebalanceIntent.mint_data = mintData;
316
+ }
317
+ else if (formatted.rebalance_type == "withdraw" && redeemData.tokens.length > 0) {
318
+ uiRebalanceIntent.redeem_data = redeemData;
319
+ }
320
+ else {
321
+ uiRebalanceIntent.claim_bounty_data = bountyData;
322
+ }
323
+ }
324
+ }
325
+ return uiRebalanceIntent;
326
+ }
327
+ function fetchRebalanceIntent(connection, rebalanceIntentAddress) {
328
+ return __awaiter(this, void 0, void 0, function* () {
329
+ var _a;
330
+ const rebalanceIntentAi = yield connection.getAccountInfo(rebalanceIntentAddress);
331
+ if (!rebalanceIntentAi)
332
+ throw new Error("Rebalance intent not found");
333
+ let rebalanceIntent = rebalanceIntent_1.RebalanceIntentLayout.decode(rebalanceIntentAi.data.slice(8));
334
+ rebalanceIntent.ownAddress = rebalanceIntentAddress;
335
+ rebalanceIntent.solBalance = (_a = rebalanceIntentAi.lamports) !== null && _a !== void 0 ? _a : 0;
336
+ let basket = (yield (0, basket_1.fetchBasket)(connection, rebalanceIntent.basket)).formatted;
337
+ return formatRebalanceIntent(rebalanceIntent, basket);
338
+ });
339
+ }
340
+ function fetchRebalanceIntentsMultiple(connection, rebalanceIntentAddresses) {
341
+ return __awaiter(this, void 0, void 0, function* () {
342
+ let multipleAccountsInfo = yield (0, txUtils_1.getMultipleAccountsInfoBatched)(connection, rebalanceIntentAddresses);
343
+ let rebalanceIntents = rebalanceIntentAddresses.map(address => {
344
+ var _a;
345
+ let ai = multipleAccountsInfo.get(address.toBase58());
346
+ if (!ai)
347
+ return null;
348
+ return Object.assign(Object.assign({}, rebalanceIntent_1.RebalanceIntentLayout.decode(ai.data.slice(8))), { ownAddress: address, solBalance: (_a = ai.lamports) !== null && _a !== void 0 ? _a : 0 });
349
+ }).filter(rebalanceIntent => rebalanceIntent !== null);
350
+ let formattedRebalanceIntents = rebalanceIntents.map(rebalanceIntent => formatRebalanceIntent(rebalanceIntent));
351
+ let rebalanceIntentsMap = new Map();
352
+ for (let rebalanceIntent of formattedRebalanceIntents)
353
+ rebalanceIntentsMap.set(rebalanceIntent.formatted_data.pubkey, rebalanceIntent);
354
+ return rebalanceIntentsMap;
355
+ });
356
+ }
357
+ function fetchRebalanceIntents(connection, filter) {
358
+ return __awaiter(this, void 0, void 0, function* () {
359
+ let accountFilters = [
360
+ { dataSize: 8 + rebalanceIntent_1.RebalanceIntentLayout.getSpan() },
361
+ ];
362
+ if ((filter === null || filter === void 0 ? void 0 : filter.type) === "basket") {
363
+ accountFilters.push({ memcmp: {
364
+ offset: 8,
365
+ bytes: filter.pubkey
366
+ } });
367
+ }
368
+ else if ((filter === null || filter === void 0 ? void 0 : filter.type) === "owner") {
369
+ accountFilters.push({ memcmp: {
370
+ offset: 8 + 32,
371
+ bytes: filter.pubkey
372
+ } });
373
+ }
374
+ const accounts = yield connection
375
+ .getProgramAccounts(constants_1.BASKETS_V3_PROGRAM_ID, {
376
+ commitment: "confirmed",
377
+ filters: accountFilters,
378
+ encoding: 'base64'
379
+ });
380
+ let basket;
381
+ if (filter && filter.type === "basket") {
382
+ basket = (yield (0, basket_1.fetchBasket)(connection, new web3_js_1.PublicKey(filter.pubkey))).formatted;
383
+ }
384
+ let rebalanceIntents = accounts.map(account => {
385
+ var _a;
386
+ let rebalanceIntent = rebalanceIntent_1.RebalanceIntentLayout.decode(account.account.data.slice(8));
387
+ rebalanceIntent.ownAddress = account.pubkey;
388
+ rebalanceIntent.solBalance = (_a = account.account.lamports) !== null && _a !== void 0 ? _a : 0;
389
+ return formatRebalanceIntent(rebalanceIntent, basket);
390
+ });
391
+ return rebalanceIntents;
392
+ });
393
+ }
394
+ class RebalanceIntentRustClass {
395
+ constructor(rebalanceIntent) {
396
+ this.self = rebalanceIntent;
397
+ }
398
+ findTokenIndex(mint) {
399
+ for (let i = 0; i < this.self.priceUpdateTasks.length; i++)
400
+ if (this.self.tokens[i].mint.equals(mint))
401
+ return i;
402
+ return undefined;
403
+ }
404
+ getSelfTvl() {
405
+ let selfTvl = { high: new bn_js_1.default(0), low: new bn_js_1.default(0) };
406
+ for (let i = 0; i < this.self.priceUpdateTasks.length; i++) {
407
+ if (this.self.priceUpdateTasks[i].completedTime.isZero()) {
408
+ continue;
409
+ }
410
+ const tokenAuction = this.self.tokens[i];
411
+ const tokenPrice = tokenAuction.price; // contains .price (mid)
412
+ if (!tokenPrice || !tokenAuction.amount)
413
+ continue;
414
+ // price * amount
415
+ const tokenValue = (0, fraction_1.fractionMul)(tokenPrice.price, { high: new bn_js_1.default(tokenAuction.amount), low: new bn_js_1.default(0) });
416
+ selfTvl = (0, fraction_1.fractionAdd)(selfTvl, tokenValue);
417
+ }
418
+ return selfTvl;
419
+ }
420
+ getBasketTvlAndWeightSum(basket) {
421
+ let basketTvl = { high: new bn_js_1.default(0), low: new bn_js_1.default(0) };
422
+ let weightSum = 0;
423
+ for (let i = 0; i < basket.numTokens; i++) {
424
+ const basketToken = basket.composition[i];
425
+ weightSum += basketToken.weight;
426
+ if (basketToken.amount.isZero()) {
427
+ continue;
428
+ }
429
+ const tokenIndex = this.findTokenIndex(basketToken.mint);
430
+ if (tokenIndex === undefined)
431
+ throw new Error("TokenNotFound");
432
+ if (this.self.priceUpdateTasks[tokenIndex].completedTime.isZero())
433
+ throw new Error("PriceUpdateNotCompleted");
434
+ const tokenPrice = this.self.tokens[tokenIndex].price;
435
+ // price * amount
436
+ const tokenValue = (0, fraction_1.fractionMul)(tokenPrice.price, { high: new bn_js_1.default(basketToken.amount), low: new bn_js_1.default(0) });
437
+ basketTvl = (0, fraction_1.fractionAdd)(basketTvl, tokenValue);
438
+ }
439
+ return { basketTvl, weightSum };
440
+ }
441
+ getPriceChange(price, timeSinceAuctionStart, auctionDuration) {
442
+ // price_change = conf * 2 * time_since_auction_start / auction_duration
443
+ if (auctionDuration.isZero()) {
444
+ throw new Error("AuctionNotLive");
445
+ }
446
+ // conf * 2
447
+ const confTimes2 = (0, fraction_1.fractionMul)(price.conf, { high: new bn_js_1.default(2), low: new bn_js_1.default(0) });
448
+ // conf * 2 * time_since_auction_start
449
+ const confTimes2TimesTime = (0, fraction_1.fractionMul)(confTimes2, { high: new bn_js_1.default(timeSinceAuctionStart), low: new bn_js_1.default(0) });
450
+ // (conf * 2 * time_since_auction_start) / auction_duration
451
+ const auctionDurationFraction = { high: new bn_js_1.default(auctionDuration), low: new bn_js_1.default(0) };
452
+ return (0, fraction_1.fractionDiv)(confTimes2TimesTime, auctionDurationFraction);
453
+ }
454
+ getSellPrice(price, timeSinceAuctionStart, auctionDuration) {
455
+ // sell_price = high() - get_price_change()
456
+ // high() = price + conf
457
+ const high = (0, fraction_1.fractionAdd)(price.price, price.conf);
458
+ const priceChange = this.getPriceChange(price, timeSinceAuctionStart, auctionDuration);
459
+ return (0, fraction_1.fractionSub)(high, priceChange);
460
+ }
461
+ getBuyPrice(price, timeSinceAuctionStart, auctionDuration) {
462
+ // buy_price = low() + get_price_change()
463
+ // low() = price - conf
464
+ const low = (0, fraction_1.fractionSub)(price.price, price.conf);
465
+ const priceChange = this.getPriceChange(price, timeSinceAuctionStart, auctionDuration);
466
+ return (0, fraction_1.fractionAdd)(low, priceChange);
467
+ }
468
+ getExchangeRate(outToken, inToken, timeSinceAuctionStart, auctionDuration) {
469
+ const outAmount = outToken.amount;
470
+ const outTargetAmount = outToken.targetAmount;
471
+ const inAmount = inToken.amount;
472
+ const inTargetAmount = inToken.targetAmount;
473
+ if (outAmount.lte(outTargetAmount))
474
+ throw new Error("InvalidSwap");
475
+ if (inAmount.gte(inTargetAmount))
476
+ throw new Error("InvalidSwap");
477
+ const maxAmountToSell = outAmount.sub(outTargetAmount);
478
+ const maxAmountToBuy = inTargetAmount.sub(inAmount);
479
+ const sellRate = this.getSellPrice(outToken.price, timeSinceAuctionStart, auctionDuration);
480
+ const buyRate = this.getBuyPrice(inToken.price, timeSinceAuctionStart, auctionDuration);
481
+ // sellValue = sellRate * maxAmountToSell
482
+ const sellValue = (0, fraction_1.fractionMul)(sellRate, { high: new bn_js_1.default(maxAmountToSell), low: new bn_js_1.default(0) });
483
+ // buyValue = buyRate * maxAmountToBuy
484
+ const buyValue = (0, fraction_1.fractionMul)(buyRate, { high: new bn_js_1.default(maxAmountToBuy), low: new bn_js_1.default(0) });
485
+ let sellSideLimits;
486
+ if ((0, fraction_1.fractionLte)(sellValue, buyValue)) {
487
+ sellSideLimits = true;
488
+ }
489
+ else if (!outTargetAmount.isZero()) {
490
+ sellSideLimits = false;
491
+ }
492
+ else {
493
+ // adjustedSellValue = sellValue * (HUNDRED_PERCENT_BPS - 100) / HUNDRED_PERCENT_BPS
494
+ const adjustmentFactor = (0, fraction_1.fractionDiv)({ high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS - 100), low: new bn_js_1.default(0) }, { high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS), low: new bn_js_1.default(0) });
495
+ const adjustedSellValue = (0, fraction_1.fractionMul)(sellValue, adjustmentFactor);
496
+ sellSideLimits = (0, fraction_1.fractionLte)(adjustedSellValue, buyValue);
497
+ }
498
+ if (sellSideLimits) {
499
+ // amountToBuy = sellValue / buyRate (rounded up)
500
+ const amountToBuy = (0, fraction_1.fractionRoundUp)((0, fraction_1.fractionDiv)(sellValue, buyRate));
501
+ return {
502
+ amountToSell: maxAmountToSell,
503
+ amountToBuy: amountToBuy,
504
+ exchangeValue: sellValue,
505
+ };
506
+ }
507
+ else {
508
+ // amountToSell = buyValue / sellRate (rounded down)
509
+ const amountToSell = (0, fraction_1.fractionRoundDown)((0, fraction_1.fractionDiv)(buyValue, sellRate));
510
+ return {
511
+ amountToSell: amountToSell,
512
+ amountToBuy: maxAmountToBuy,
513
+ exchangeValue: buyValue,
514
+ };
515
+ }
516
+ }
517
+ getSwapAmounts(inTokenIndex, outTokenIndex, timeSinceAuctionStart, auctionDuration) {
518
+ if (inTokenIndex === outTokenIndex)
519
+ throw new Error("InvalidSwap");
520
+ if (this.self.priceUpdateTasks[inTokenIndex].completedTime.isZero())
521
+ throw new Error("PriceUpdateNotCompleted");
522
+ if (this.self.priceUpdateTasks[outTokenIndex].completedTime.isZero())
523
+ throw new Error("PriceUpdateNotCompleted");
524
+ const inToken = this.self.tokens[inTokenIndex];
525
+ const outToken = this.self.tokens[outTokenIndex];
526
+ const exchangeRate = this.getExchangeRate(outToken, inToken, timeSinceAuctionStart, auctionDuration);
527
+ let basketBuys = exchangeRate.amountToBuy;
528
+ let basketSells = exchangeRate.amountToSell;
529
+ // inValue = inTokenPrice * basketBuys
530
+ const inValue = (0, fraction_1.fractionMul)(inToken.price.price, { high: new bn_js_1.default(basketBuys), low: new bn_js_1.default(0) });
531
+ // outValue = outTokenPrice * basketSells
532
+ const outValue = (0, fraction_1.fractionMul)(outToken.price.price, { high: new bn_js_1.default(basketSells), low: new bn_js_1.default(0) });
533
+ // slippageFactor = (HUNDRED_PERCENT_BPS - bps) / HUNDRED_PERCENT_BPS
534
+ const slippageFactor = (0, fraction_1.fractionDiv)({ high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS - this.self.perTradeRebalanceThresholdSlippageBps), low: new bn_js_1.default(0) }, { high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS), low: new bn_js_1.default(0) });
535
+ // Check: inValue < outValue * slippageFactor
536
+ const outValueWithSlippage = (0, fraction_1.fractionMul)(outValue, slippageFactor);
537
+ if ((0, fraction_1.fractionLt)(inValue, outValueWithSlippage)) {
538
+ throw new Error("RebalanceSlippageExceeded");
539
+ }
540
+ const selfTvl = this.getSelfTvl();
541
+ // minSelfTvl = initialTvl * (HUNDRED_PERCENT_BPS - rebalanceThresholdSlippageBps) / HUNDRED_PERCENT_BPS
542
+ const tvlSlippageFactor = (0, fraction_1.fractionDiv)({ high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS - this.self.rebalanceThresholdSlippageBps), low: new bn_js_1.default(0) }, { high: new bn_js_1.default(constants_1.HUNDRED_PERCENT_BPS), low: new bn_js_1.default(0) });
543
+ const minSelfTvl = (0, fraction_1.fractionMul)(this.self.initialTvl, tvlSlippageFactor);
544
+ if ((0, fraction_1.fractionLt)(selfTvl, minSelfTvl)) {
545
+ throw new Error("RebalanceSlippageExceeded");
546
+ }
547
+ return exchangeRate;
548
+ }
549
+ updateTargetAmounts(basket) {
550
+ this.self.auctionUpdateTimestamp = new bn_js_1.default(Math.floor(Date.now() / 1000));
551
+ const selfTvl = this.getSelfTvl();
552
+ const { basketTvl, weightSum } = this.getBasketTvlAndWeightSum(basket);
553
+ for (let tokenIndex = 0; tokenIndex < this.self.priceUpdateTasks.length; tokenIndex++) {
554
+ if (this.self.tokens[tokenIndex].mint.equals(web3_js_1.PublicKey.default)) {
555
+ continue;
556
+ }
557
+ if (this.self.priceUpdateTasks[tokenIndex].completedTime.isZero()) {
558
+ continue;
559
+ }
560
+ const auctionToken = this.self.tokens[tokenIndex];
561
+ const auctionTokenPrice = auctionToken.price;
562
+ const tokenPrice = auctionTokenPrice.price;
563
+ if (this.self.rebalanceType === rebalanceIntent_1.RebalanceType.Withdraw) {
564
+ this.self.tokens[tokenIndex].targetAmount = new bn_js_1.default(0);
565
+ if (auctionToken.keepToken === 1) {
566
+ // targetAmount = selfTvl / tokenPrice (rounded down) * 2
567
+ const targetAmount = (0, fraction_1.fractionRoundDown)((0, fraction_1.fractionDiv)(selfTvl, tokenPrice));
568
+ this.self.tokens[tokenIndex].targetAmount = targetAmount.mul(new bn_js_1.default(2));
569
+ }
570
+ continue;
571
+ }
572
+ // Find token index in basket composition
573
+ let tokenIndexInBasket = undefined;
574
+ for (let i = 0; i < basket.numTokens; i++) {
575
+ if (basket.composition[i].mint.equals(this.self.tokens[tokenIndex].mint)) {
576
+ tokenIndexInBasket = i;
577
+ break;
578
+ }
579
+ }
580
+ if (tokenIndexInBasket === undefined) {
581
+ this.self.tokens[tokenIndex].targetAmount = new bn_js_1.default(0);
582
+ continue;
583
+ }
584
+ const basketToken = basket.composition[tokenIndexInBasket];
585
+ if (this.self.rebalanceType === rebalanceIntent_1.RebalanceType.Deposit && basket.supplyOutstanding.gt(new bn_js_1.default(0))) {
586
+ // targetAmount = (basketToken.amount * selfTvl) / basketTvl (rounded down)
587
+ const basketTokenAmountFraction = { high: new bn_js_1.default(basketToken.amount), low: new bn_js_1.default(0) };
588
+ const numerator = (0, fraction_1.fractionMul)(basketTokenAmountFraction, selfTvl);
589
+ const targetAmount = (0, fraction_1.fractionRoundDown)((0, fraction_1.fractionDiv)(numerator, basketTvl));
590
+ this.self.tokens[tokenIndex].targetAmount = targetAmount;
591
+ }
592
+ if (this.self.rebalanceType === rebalanceIntent_1.RebalanceType.Deposit && basket.supplyOutstanding.isZero()) {
593
+ // targetValue = selfTvl * weight / weightSum
594
+ // targetAmount = targetValue / tokenPrice (rounded down)
595
+ const targetValue = (0, fraction_1.fractionDiv)((0, fraction_1.fractionMul)(selfTvl, { high: new bn_js_1.default(basketToken.weight), low: new bn_js_1.default(0) }), { high: new bn_js_1.default(weightSum), low: new bn_js_1.default(0) });
596
+ const targetAmount = (0, fraction_1.fractionRoundDown)((0, fraction_1.fractionDiv)(targetValue, tokenPrice));
597
+ this.self.tokens[tokenIndex].targetAmount = targetAmount;
598
+ }
599
+ if (this.self.rebalanceType === rebalanceIntent_1.RebalanceType.Basket || this.self.rebalanceType === rebalanceIntent_1.RebalanceType.BasketCustom) {
600
+ // targetValue = basketTvl * weight / weightSum
601
+ // targetAmount = targetValue / tokenPrice (rounded down)
602
+ const targetValue = (0, fraction_1.fractionDiv)((0, fraction_1.fractionMul)(basketTvl, { high: new bn_js_1.default(basketToken.weight), low: new bn_js_1.default(0) }), { high: new bn_js_1.default(weightSum), low: new bn_js_1.default(0) });
603
+ let targetAmount = (0, fraction_1.fractionRoundDown)((0, fraction_1.fractionDiv)(targetValue, tokenPrice));
604
+ if (this.self.bounty.bountyMint.equals(auctionToken.mint)) {
605
+ targetAmount = targetAmount.add(this.self.bountyAdjustmentAmount);
606
+ }
607
+ this.self.tokens[tokenIndex].targetAmount = targetAmount;
608
+ }
609
+ }
610
+ }
611
+ }
612
+ /**
613
+ * Returns all valid swap pairs available during the rebalance auction phase.
614
+ *
615
+ * **Swap direction (basket perspective):**
616
+ * - `inMint` / `inAmount`: what the basket is supposed to **receive**.
617
+ * - `outMint` / `outAmount`: what the basket wants to **swap** (give away).
618
+ * So each pair describes an **outMint → inMint** swap. When generating swap
619
+ * transactions, use this direction: swap `outMint` → `inMint` (sell outAmount of
620
+ * outMint, receive inAmount of inMint).
621
+ *
622
+ * Only runs when the rebalance is in Auction action and the current time falls
623
+ * within one of the three auction windows. For the active auction, target amounts
624
+ * are refreshed if they haven't been updated since the auction started.
625
+ *
626
+ * Iterates over completed price-update tokens to compute exchange rates via
627
+ * getSwapAmounts (using time-since-start and auction duration). Pairs with
628
+ * positive in/out amounts are collected and sorted by value descending
629
+ * (highest value first).
630
+ *
631
+ * @param rebalanceIntent - The rebalance intent state
632
+ * @param basket - The basket (used to update target amounts when needed)
633
+ * @returns Array of swap pairs, or empty array when not in auction or outside auction windows
634
+ */
635
+ function getSwapPairs(rebalanceIntent, basket) {
636
+ let rebalanceIntentRustClass = new RebalanceIntentRustClass(rebalanceIntent);
637
+ if (rebalanceIntentRustClass.self.currentAction !== rebalanceIntent_1.RebalanceAction.Auction)
638
+ return [];
639
+ const timestamp = new bn_js_1.default(Math.floor(Date.now() / 1000));
640
+ let currentAuction;
641
+ if (rebalanceIntentRustClass.self.auctions[0].startTime.lte(timestamp) && timestamp.lt(rebalanceIntentRustClass.self.auctions[0].endTime))
642
+ currentAuction = rebalanceIntentRustClass.self.auctions[0];
643
+ else if (rebalanceIntentRustClass.self.auctions[1].startTime.lte(timestamp) && timestamp.lt(rebalanceIntentRustClass.self.auctions[1].endTime))
644
+ currentAuction = rebalanceIntentRustClass.self.auctions[1];
645
+ else if (rebalanceIntentRustClass.self.auctions[2].startTime.lte(timestamp) && timestamp.lt(rebalanceIntentRustClass.self.auctions[2].endTime))
646
+ currentAuction = rebalanceIntentRustClass.self.auctions[2];
647
+ else
648
+ return [];
649
+ let start_time = currentAuction.startTime;
650
+ if (rebalanceIntentRustClass.self.auctionUpdateTimestamp.lt(start_time))
651
+ rebalanceIntentRustClass.updateTargetAmounts(basket);
652
+ let timeSinceAuctionStart = timestamp.sub(currentAuction.startTime);
653
+ let auctionDuration = currentAuction.endTime.sub(currentAuction.startTime);
654
+ let allPairs = [];
655
+ for (let inTokenIndex = 0; inTokenIndex < rebalanceIntentRustClass.self.priceUpdateTasks.length; inTokenIndex++) {
656
+ if (rebalanceIntentRustClass.self.priceUpdateTasks[inTokenIndex].completedTime.isZero())
657
+ continue;
658
+ for (let outTokenIndex = 0; outTokenIndex < rebalanceIntentRustClass.self.priceUpdateTasks.length; outTokenIndex++) {
659
+ if (inTokenIndex === outTokenIndex)
660
+ continue;
661
+ if (rebalanceIntentRustClass.self.priceUpdateTasks[outTokenIndex].completedTime.isZero())
662
+ continue;
663
+ try {
664
+ let exchangeRate = rebalanceIntentRustClass.getSwapAmounts(inTokenIndex, outTokenIndex, timeSinceAuctionStart, auctionDuration);
665
+ if (parseInt(exchangeRate.amountToBuy.toString()) > 0 && parseInt(exchangeRate.amountToSell.toString()) > 0) {
666
+ allPairs.push({
667
+ inMint: rebalanceIntentRustClass.self.tokens[inTokenIndex].mint.toBase58(),
668
+ outMint: rebalanceIntentRustClass.self.tokens[outTokenIndex].mint.toBase58(),
669
+ inAmount: parseInt(exchangeRate.amountToBuy.toString()),
670
+ outAmount: parseInt(exchangeRate.amountToSell.toString()),
671
+ value: (0, fraction_1.fractionToDecimal)(exchangeRate.exchangeValue).toNumber(),
672
+ });
673
+ }
674
+ }
675
+ catch (_a) { }
676
+ }
677
+ }
678
+ allPairs.sort((a, b) => b.value - a.value);
679
+ return allPairs;
680
+ }