@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,624 @@
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.RebalanceHandler = exports.KeeperMonitor = void 0;
13
+ const web3_js_1 = require("@solana/web3.js");
14
+ const _1 = require(".");
15
+ const rebalanceIntent_1 = require("./states/intents/rebalanceIntent");
16
+ const constants_1 = require("./constants");
17
+ class KeeperMonitor {
18
+ constructor(params) {
19
+ var _a, _b;
20
+ this.delay = (ms) => __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, ms)); });
21
+ this.params = {
22
+ wallet: params.wallet,
23
+ connection: params.connection,
24
+ symmetryCore: new _1.SymmetryCore({
25
+ connection: params.connection,
26
+ network: params.network,
27
+ priorityFee: (_a = params.priorityFee) !== null && _a !== void 0 ? _a : constants_1.PRIORITY_FEE,
28
+ }),
29
+ network: params.network,
30
+ jupiterApiKey: params.jupiterApiKey,
31
+ maxAllowedAccounts: params.maxAllowedAccounts,
32
+ simulateTransactions: (_b = params.simulateTransactions) !== null && _b !== void 0 ? _b : false,
33
+ };
34
+ //@ts-ignore
35
+ this.globalConfig = {};
36
+ this.intents = new Map();
37
+ this.rebalanceIntents = new Map();
38
+ this.baskets = new Map();
39
+ }
40
+ update() {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ var _a;
43
+ let baskets;
44
+ try {
45
+ baskets = yield this.params.symmetryCore.fetchAllBaskets();
46
+ }
47
+ catch (e) {
48
+ console.log("Error fetching baskets:", e);
49
+ }
50
+ if (baskets) {
51
+ for (let basket of baskets)
52
+ this.baskets.set(basket.ownAddress.toBase58(), basket);
53
+ }
54
+ let intents;
55
+ try {
56
+ intents = yield this.params.symmetryCore.fetchAllIntents();
57
+ }
58
+ catch (e) {
59
+ console.log("Error fetching intents:", e);
60
+ }
61
+ if (intents) {
62
+ for (let intent of intents) {
63
+ let oldInstance = this.intents.get(intent.ownAddress.toBase58());
64
+ this.intents.set(intent.ownAddress.toBase58(), intent);
65
+ let isMonitored = oldInstance ? true : false;
66
+ if (!isMonitored) {
67
+ console.log("New Intent:", intent.ownAddress.toBase58());
68
+ this.monitorIntent(intent.ownAddress.toBase58());
69
+ }
70
+ }
71
+ for (let intent of this.intents.values()) {
72
+ if (!intents.find(i => i.ownAddress.equals(intent.ownAddress))) {
73
+ this.intents.delete(intent.ownAddress.toBase58());
74
+ console.log("Intent deleted:", intent.ownAddress.toBase58());
75
+ }
76
+ }
77
+ }
78
+ let rebalanceIntents;
79
+ try {
80
+ rebalanceIntents = yield this.params.symmetryCore.fetchAllRebalanceIntents();
81
+ }
82
+ catch (e) {
83
+ console.log("Error fetching rebalance intents:", e);
84
+ }
85
+ if (rebalanceIntents) {
86
+ for (let rebalanceIntent of rebalanceIntents) {
87
+ let oldInstance = this.rebalanceIntents.get(rebalanceIntent.formatted_data.pubkey);
88
+ this.rebalanceIntents.set(rebalanceIntent.formatted_data.pubkey, rebalanceIntent);
89
+ let isMonitored = oldInstance && (oldInstance.formatted_data.current_action != "deposit_tokens" &&
90
+ oldInstance.formatted_data.current_action != "not_active");
91
+ let shouldMonitor = rebalanceIntent && (rebalanceIntent.formatted_data.current_action != "deposit_tokens" &&
92
+ rebalanceIntent.formatted_data.current_action != "not_active");
93
+ if (!isMonitored && shouldMonitor) {
94
+ console.log("New Rebalance Intent:", rebalanceIntent.formatted_data.pubkey);
95
+ this.monitorRebalanceIntent(rebalanceIntent.formatted_data.pubkey);
96
+ }
97
+ }
98
+ for (let rebalanceIntent of this.rebalanceIntents.values()) {
99
+ if (!rebalanceIntents.find(i => i.formatted_data.pubkey == rebalanceIntent.formatted_data.pubkey)) {
100
+ this.rebalanceIntents.delete(rebalanceIntent.formatted_data.pubkey);
101
+ console.log("Rebalance Intent deleted:", rebalanceIntent.formatted_data.pubkey);
102
+ }
103
+ }
104
+ }
105
+ console.log("Baskets: ", (_a = this.baskets) === null || _a === void 0 ? void 0 : _a.size, " Intents: ", this.intents.size, " Rebalance intents: ", this.rebalanceIntents.size);
106
+ });
107
+ }
108
+ run(runTime) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ console.log("Starting keeper monitor", this.params.wallet.publicKey.toBase58());
111
+ if (!runTime)
112
+ runTime = 10 * 60;
113
+ if (runTime < 60)
114
+ runTime = 60;
115
+ let startTime = Date.now() / 1000;
116
+ while (true) {
117
+ let now = Date.now() / 1000;
118
+ if (now + 45 > startTime + runTime)
119
+ break;
120
+ yield this.update();
121
+ yield this.delay(Math.min(30 * 1000, Math.max(0, startTime + runTime - now - 45 + 0.2) * 1000));
122
+ }
123
+ this.baskets = new Map();
124
+ this.intents = new Map();
125
+ this.rebalanceIntents = new Map();
126
+ yield this.delay(45 * 1000);
127
+ });
128
+ }
129
+ monitorIntent(pubkey) {
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ let nextCheckTime = 0;
132
+ let numTries = 0;
133
+ while (true) {
134
+ let intent = this.intents.get(pubkey);
135
+ if (!intent)
136
+ break;
137
+ let now = Date.now() / 1000;
138
+ if (now < nextCheckTime) {
139
+ yield this.delay(Math.min(30 * 1000, Math.max(0, nextCheckTime - now + 0.2) * 1000));
140
+ continue;
141
+ }
142
+ nextCheckTime = now + 35;
143
+ if (intent.formatted.activation_timestamp > now) {
144
+ nextCheckTime = intent.formatted.activation_timestamp;
145
+ continue;
146
+ }
147
+ if (now < intent.formatted.expiration_timestamp && numTries >= 2) {
148
+ nextCheckTime = intent.formatted.expiration_timestamp;
149
+ continue;
150
+ }
151
+ if (now < intent.formatted.expiration_timestamp) {
152
+ numTries += 1;
153
+ try {
154
+ let tx = yield this.params.symmetryCore.executeBasketIntentTx({
155
+ keeper: this.params.wallet.publicKey.toBase58(),
156
+ intent: intent.ownAddress.toBase58(),
157
+ });
158
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
159
+ console.log("Execute Basket Intent - ", pubkey, " : ", res);
160
+ nextCheckTime = now + 60;
161
+ }
162
+ catch (_a) { }
163
+ continue;
164
+ }
165
+ numTries = Math.max(2, numTries);
166
+ if (numTries >= 4)
167
+ break;
168
+ numTries += 1;
169
+ try {
170
+ let tx = yield this.params.symmetryCore.cancelBasketIntentTx({
171
+ keeper: this.params.wallet.publicKey.toBase58(),
172
+ intent: intent.ownAddress.toBase58(),
173
+ });
174
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
175
+ console.log("Cancel Basket Intent - ", pubkey, " : ", res);
176
+ nextCheckTime = now + 60;
177
+ }
178
+ catch (e) {
179
+ if (numTries == 4) {
180
+ console.log("Stop monitoring - ", pubkey, " : ", e);
181
+ }
182
+ }
183
+ continue;
184
+ }
185
+ });
186
+ }
187
+ monitorRebalanceIntent(pubkey) {
188
+ return __awaiter(this, void 0, void 0, function* () {
189
+ var _a, _b, _c, _d, _e;
190
+ let nextCheckTime = 0;
191
+ let numTriesUpdatePrices = 0;
192
+ let numTriesMint = 0;
193
+ let numTriesRedeemTokens = 0;
194
+ let numTriesClaimBounty = 0;
195
+ let lastJupQuotesUpdate = 0;
196
+ let jupQuotes = [];
197
+ while (true) {
198
+ let uiIntent = this.rebalanceIntents.get(pubkey);
199
+ if (!uiIntent)
200
+ break;
201
+ let intent = uiIntent.formatted_data;
202
+ let chainData = uiIntent.chain_data;
203
+ let now = Date.now() / 1000;
204
+ if (now < nextCheckTime) {
205
+ yield this.delay(Math.min(30 * 1000, Math.max(0, nextCheckTime - now + 0.2) * 1000));
206
+ continue;
207
+ }
208
+ nextCheckTime = now + 35;
209
+ if (intent.current_action == "not_active")
210
+ continue;
211
+ if (intent.current_action == "deposit_tokens")
212
+ continue;
213
+ if (intent.current_action == "update_prices" && intent.last_action_timestamp > now) {
214
+ nextCheckTime = intent.last_action_timestamp;
215
+ continue;
216
+ }
217
+ if (intent.current_action == "update_prices") {
218
+ if (numTriesUpdatePrices >= 5)
219
+ break;
220
+ numTriesUpdatePrices += 1;
221
+ try {
222
+ let tx = yield this.params.symmetryCore.updateTokenPricesTx({
223
+ keeper: this.params.wallet.publicKey.toBase58(),
224
+ basket: intent.basket,
225
+ rebalance_intent: intent.pubkey,
226
+ });
227
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
228
+ console.log("Update Prices - ", pubkey, " : ", res);
229
+ }
230
+ catch (e) {
231
+ if (numTriesUpdatePrices == 5) {
232
+ console.log("Stop monitoring - ", pubkey, " : ", e);
233
+ }
234
+ }
235
+ nextCheckTime += 60;
236
+ continue;
237
+ }
238
+ if (intent.auctions[2].end_time > now) {
239
+ let basket = this.baskets.get(intent.basket);
240
+ if (!basket)
241
+ continue;
242
+ let pairs = (0, rebalanceIntent_1.getSwapPairs)(chainData, basket);
243
+ if (Date.now() / 1000 > lastJupQuotesUpdate + 60) {
244
+ lastJupQuotesUpdate = Date.now() / 1000;
245
+ jupQuotes = [];
246
+ for (let pair of pairs) {
247
+ if (pair.value < 0.005)
248
+ continue;
249
+ if (this.params.network == "mainnet")
250
+ try {
251
+ let res = yield (0, _1.getJupTokenLedgerAndSwapInstructions)({
252
+ keeper: this.params.wallet.publicKey,
253
+ basketMintIn: new web3_js_1.PublicKey(pair.inMint),
254
+ basketMintOut: new web3_js_1.PublicKey(pair.outMint),
255
+ basketAmountIn: pair.inAmount,
256
+ basketAmountOut: pair.outAmount,
257
+ swapMode: "ioc",
258
+ apiKey: this.params.jupiterApiKey,
259
+ maxJupAccounts: this.params.maxAllowedAccounts,
260
+ });
261
+ jupQuotes.push(Object.assign(Object.assign({}, res), { inMint: pair.inMint, outMint: pair.outMint }));
262
+ console.log("Fetch new Jup Quote:", pair.inMint, pair.outMint);
263
+ console.log(pair, "Jup Quote:", parseFloat((_b = (_a = res.quoteResponse) === null || _a === void 0 ? void 0 : _a.outAmount) !== null && _b !== void 0 ? _b : 0), "Requested In:", pair.inAmount);
264
+ }
265
+ catch (_f) { }
266
+ }
267
+ }
268
+ for (let index = 0; index < pairs.length; index++)
269
+ try {
270
+ let pair = pairs[index];
271
+ let jupIndex = jupQuotes.findIndex(q => q && q.inMint == pair.inMint && q.outMint == pair.outMint);
272
+ let quote = jupIndex >= 0 ? jupQuotes[jupIndex] : undefined;
273
+ if (!quote && this.params.network == "mainnet")
274
+ continue;
275
+ if (pair.value < 0.005)
276
+ continue;
277
+ let tokenLedgerInstruction = quote === null || quote === void 0 ? void 0 : quote.tokenLedgerInstruction;
278
+ let swapInstruction = quote === null || quote === void 0 ? void 0 : quote.swapInstruction;
279
+ let addressLookupTableAddresses = (_c = quote === null || quote === void 0 ? void 0 : quote.addressLookupTableAddresses) !== null && _c !== void 0 ? _c : [];
280
+ let quoteResponse = quote === null || quote === void 0 ? void 0 : quote.quoteResponse;
281
+ if (this.params.network == "mainnet" && !quoteResponse)
282
+ continue;
283
+ console.log(pair, "Jup Quote:", parseFloat((_d = quoteResponse === null || quoteResponse === void 0 ? void 0 : quoteResponse.outAmount) !== null && _d !== void 0 ? _d : 0), "Requested In:", pair.inAmount);
284
+ let quoteResponseAmount = parseFloat((_e = quoteResponse === null || quoteResponse === void 0 ? void 0 : quoteResponse.outAmount) !== null && _e !== void 0 ? _e : 0);
285
+ if (this.params.network == "mainnet" && quoteResponseAmount * 1.005 <= pair.inAmount)
286
+ continue;
287
+ try {
288
+ let tx = yield this.params.symmetryCore.flashSwapTx({
289
+ keeper: this.params.wallet.publicKey.toBase58(),
290
+ basket: basket.ownAddress.toBase58(),
291
+ rebalance_intent: intent.pubkey,
292
+ mint_in: pair.inMint,
293
+ mint_out: pair.outMint,
294
+ amount_in: pair.inAmount,
295
+ amount_out: pair.outAmount,
296
+ mode: 2,
297
+ jup_token_ledger_ix: tokenLedgerInstruction,
298
+ jup_swap_ix: swapInstruction,
299
+ jup_address_lookup_table_addresses: addressLookupTableAddresses,
300
+ });
301
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
302
+ console.log("Flash Swap - ", pubkey, " : ", res);
303
+ jupQuotes = jupQuotes.filter(q => q && (q.inMint != pair.inMint || q.outMint != pair.outMint));
304
+ }
305
+ catch (_g) { }
306
+ }
307
+ catch (_h) { }
308
+ nextCheckTime = (Date.now() / 1000) + 8;
309
+ continue;
310
+ }
311
+ if (intent.rebalance_type == "deposit") {
312
+ if (numTriesMint >= 3)
313
+ break;
314
+ lastJupQuotesUpdate = 0;
315
+ numTriesMint += 1;
316
+ try {
317
+ let tx = yield this.params.symmetryCore.mintTx({
318
+ keeper: this.params.wallet.publicKey.toBase58(),
319
+ rebalance_intent: intent.pubkey,
320
+ });
321
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
322
+ console.log("Mint - ", pubkey, " : ", res);
323
+ }
324
+ catch (e) {
325
+ if (numTriesMint == 3) {
326
+ console.log("Stop monitoring - ", pubkey, " : ", e);
327
+ }
328
+ }
329
+ continue;
330
+ }
331
+ let hasTokens = intent.tokens.find(token => token.amount > 0);
332
+ if (hasTokens && intent.rebalance_type == "withdraw") {
333
+ if (numTriesRedeemTokens >= 3)
334
+ break;
335
+ numTriesRedeemTokens += 1;
336
+ try {
337
+ let tx = yield this.params.symmetryCore.redeemTokensTx({
338
+ keeper: this.params.wallet.publicKey.toBase58(),
339
+ rebalance_intent: intent.pubkey,
340
+ });
341
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
342
+ console.log("Redeem Tokens:", res);
343
+ }
344
+ catch (e) {
345
+ if (numTriesRedeemTokens == 3) {
346
+ console.log("Stop monitoring - ", pubkey, " : ", e);
347
+ }
348
+ }
349
+ continue;
350
+ }
351
+ if (numTriesClaimBounty >= 3)
352
+ break;
353
+ numTriesClaimBounty += 1;
354
+ try {
355
+ let tx = yield this.params.symmetryCore.claimBountyTx({
356
+ keeper: this.params.wallet.publicKey.toBase58(),
357
+ rebalance_intent: intent.pubkey,
358
+ });
359
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
360
+ console.log("Claim Bounty - ", pubkey, " : ", res);
361
+ nextCheckTime = now + 60;
362
+ }
363
+ catch (e) {
364
+ if (numTriesClaimBounty == 3) {
365
+ console.log("Stop monitoring - ", pubkey, " : ", e);
366
+ }
367
+ }
368
+ continue;
369
+ }
370
+ });
371
+ }
372
+ }
373
+ exports.KeeperMonitor = KeeperMonitor;
374
+ class RebalanceHandler {
375
+ constructor(params) {
376
+ var _a, _b;
377
+ this.delay = (ms) => __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, ms)); });
378
+ this.params = {
379
+ wallet: params.wallet,
380
+ connection: params.connection,
381
+ symmetryCore: new _1.SymmetryCore({
382
+ connection: params.connection,
383
+ network: params.network,
384
+ priorityFee: (_a = params.priorityFee) !== null && _a !== void 0 ? _a : constants_1.PRIORITY_FEE,
385
+ }),
386
+ network: params.network,
387
+ jupiterApiKey: params.jupiterApiKey,
388
+ maxAllowedAccounts: params.maxAllowedAccounts,
389
+ simulateTransactions: (_b = params.simulateTransactions) !== null && _b !== void 0 ? _b : false,
390
+ };
391
+ this.intent = params.intent;
392
+ this.basket = params.basket;
393
+ }
394
+ refresh() {
395
+ return __awaiter(this, void 0, void 0, function* () {
396
+ this.intent = yield this.params.symmetryCore.fetchRebalanceIntent(this.intent.formatted_data.pubkey);
397
+ this.basket = yield this.params.symmetryCore.fetchBasket(this.intent.formatted_data.basket);
398
+ });
399
+ }
400
+ static run(params) {
401
+ return __awaiter(this, void 0, void 0, function* () {
402
+ var _a;
403
+ let symmetryCore = new _1.SymmetryCore({
404
+ connection: params.connection,
405
+ network: params.network,
406
+ priorityFee: (_a = params.priorityFee) !== null && _a !== void 0 ? _a : constants_1.PRIORITY_FEE,
407
+ });
408
+ let intent = yield symmetryCore.fetchRebalanceIntent(params.intentPubkey.toBase58());
409
+ let basket = yield symmetryCore.fetchBasket(intent.formatted_data.basket);
410
+ let handler = new RebalanceHandler({
411
+ intent, basket,
412
+ wallet: params.wallet,
413
+ connection: params.connection,
414
+ network: params.network,
415
+ jupiterApiKey: params.jupiterApiKey,
416
+ maxAllowedAccounts: params.maxAllowedAccounts,
417
+ simulateTransactions: params.simulateTransactions,
418
+ });
419
+ handler.execute();
420
+ for (let i = 0; i < 20; i++) {
421
+ yield handler.delay(15 * 1000);
422
+ try {
423
+ yield handler.refresh();
424
+ }
425
+ catch (e) {
426
+ handler.intent = undefined;
427
+ break;
428
+ }
429
+ }
430
+ });
431
+ }
432
+ execute() {
433
+ return __awaiter(this, void 0, void 0, function* () {
434
+ var _a, _b;
435
+ console.log("Starting rebalance handler for intent:", this.intent.formatted_data.pubkey);
436
+ let nextCheckTime = 0;
437
+ let numTriesUpdatePrices = 0;
438
+ let numTriesMint = 0;
439
+ let numTriesRedeemTokens = 0;
440
+ let numTriesClaimBounty = 0;
441
+ let rebalancePairs = [];
442
+ let lastJupQuotesUpdate = 0;
443
+ let jupQuotes = [];
444
+ while (true) {
445
+ if (!this.intent)
446
+ break;
447
+ let intent = this.intent.formatted_data;
448
+ let chainData = this.intent.chain_data;
449
+ let now = Date.now() / 1000;
450
+ if (now < nextCheckTime) {
451
+ yield this.delay(Math.min(30 * 1000, Math.max(0, nextCheckTime - now + 0.2) * 1000));
452
+ continue;
453
+ }
454
+ nextCheckTime = now + 5;
455
+ if (intent.current_action == "not_active") {
456
+ console.log("Intent not active, stopping");
457
+ break;
458
+ }
459
+ if (intent.current_action == "deposit_tokens") {
460
+ console.log("Waiting for deposit...");
461
+ continue;
462
+ }
463
+ if (intent.current_action == "update_prices" && intent.last_action_timestamp > now) {
464
+ nextCheckTime = intent.last_action_timestamp;
465
+ continue;
466
+ }
467
+ if (intent.current_action == "update_prices") {
468
+ if (numTriesUpdatePrices >= 5) {
469
+ console.log("Max retries for update_prices");
470
+ break;
471
+ }
472
+ numTriesUpdatePrices += 1;
473
+ try {
474
+ let tx = yield this.params.symmetryCore.updateTokenPricesTx({
475
+ keeper: this.params.wallet.publicKey.toBase58(),
476
+ basket: intent.basket,
477
+ rebalance_intent: intent.pubkey,
478
+ });
479
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
480
+ console.log("Update Prices:", res);
481
+ }
482
+ catch (e) {
483
+ if (numTriesUpdatePrices == 5) {
484
+ console.log("Stop - update prices failed:", e);
485
+ }
486
+ }
487
+ continue;
488
+ }
489
+ if (intent.auctions[2].end_time > now) {
490
+ rebalancePairs = (0, rebalanceIntent_1.getSwapPairs)(chainData, this.basket);
491
+ if (Date.now() / 1000 > lastJupQuotesUpdate + 60) {
492
+ let usedValue = new Map();
493
+ jupQuotes = [];
494
+ for (let pair of rebalancePairs) {
495
+ let inValue = (_a = usedValue.get(pair.inMint)) !== null && _a !== void 0 ? _a : 0;
496
+ let outValue = (_b = usedValue.get(pair.outMint)) !== null && _b !== void 0 ? _b : 0;
497
+ let swapValue = Math.min(pair.value - inValue, pair.value - outValue);
498
+ if (swapValue < 0.005) {
499
+ jupQuotes.push(undefined);
500
+ continue;
501
+ }
502
+ usedValue.set(pair.inMint, inValue + swapValue);
503
+ usedValue.set(pair.outMint, outValue + swapValue);
504
+ let res = undefined;
505
+ if (this.params.network == "mainnet")
506
+ try {
507
+ res = Object.assign(Object.assign({}, (yield (0, _1.getJupTokenLedgerAndSwapInstructions)({
508
+ keeper: this.params.wallet.publicKey,
509
+ basketMintIn: new web3_js_1.PublicKey(pair.inMint),
510
+ basketMintOut: new web3_js_1.PublicKey(pair.outMint),
511
+ basketAmountIn: pair.inAmount,
512
+ basketAmountOut: pair.outAmount,
513
+ swapMode: "ioc",
514
+ apiKey: this.params.jupiterApiKey,
515
+ maxJupAccounts: this.params.maxAllowedAccounts,
516
+ }))), { inMint: pair.inMint, outMint: pair.outMint });
517
+ }
518
+ catch (_c) { }
519
+ ;
520
+ jupQuotes.push(res);
521
+ }
522
+ }
523
+ for (let index = 0; index < rebalancePairs.length; index++)
524
+ try {
525
+ let pair = rebalancePairs[index];
526
+ let quote = jupQuotes.find(q => q && q.inMint == pair.inMint && q.outMint == pair.outMint);
527
+ if (!quote)
528
+ continue;
529
+ if (pair.value < 0.005)
530
+ continue;
531
+ let { tokenLedgerInstruction, swapInstruction, addressLookupTableAddresses, quoteResponse } = quote;
532
+ if (!quoteResponse)
533
+ continue;
534
+ console.log(pair, "Jup Quote:", parseFloat(quoteResponse.outAmount), "Requested In:", pair.inAmount);
535
+ if (parseFloat(quoteResponse.outAmount) <= pair.inAmount && this.params.network == "mainnet")
536
+ continue;
537
+ try {
538
+ let tx = yield this.params.symmetryCore.flashSwapTx({
539
+ keeper: this.params.wallet.publicKey.toBase58(),
540
+ basket: this.basket.ownAddress.toBase58(),
541
+ rebalance_intent: intent.pubkey,
542
+ mint_in: pair.inMint,
543
+ mint_out: pair.outMint,
544
+ amount_in: pair.inAmount,
545
+ amount_out: pair.outAmount,
546
+ mode: 2,
547
+ jup_token_ledger_ix: tokenLedgerInstruction,
548
+ jup_swap_ix: swapInstruction,
549
+ jup_address_lookup_table_addresses: addressLookupTableAddresses,
550
+ });
551
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
552
+ console.log("Flash Swap:", res);
553
+ rebalancePairs = rebalancePairs.splice(index, 1);
554
+ index -= 1;
555
+ }
556
+ catch (_d) { }
557
+ }
558
+ catch (_e) { }
559
+ nextCheckTime = (Date.now() / 1000) + 10;
560
+ continue;
561
+ }
562
+ if (intent.rebalance_type == "deposit") {
563
+ if (numTriesMint >= 3)
564
+ break;
565
+ lastJupQuotesUpdate = 0;
566
+ numTriesMint += 1;
567
+ try {
568
+ let tx = yield this.params.symmetryCore.mintTx({
569
+ keeper: this.params.wallet.publicKey.toBase58(),
570
+ rebalance_intent: intent.pubkey,
571
+ });
572
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
573
+ console.log("Mint -", res);
574
+ }
575
+ catch (e) {
576
+ if (numTriesMint == 3) {
577
+ console.log("Stop monitoring -", e);
578
+ }
579
+ }
580
+ continue;
581
+ }
582
+ let hasTokens = intent.tokens.find(token => token.amount > 0);
583
+ if (hasTokens && intent.rebalance_type == "withdraw") {
584
+ if (numTriesRedeemTokens >= 3)
585
+ break;
586
+ numTriesRedeemTokens += 1;
587
+ try {
588
+ let tx = yield this.params.symmetryCore.redeemTokensTx({
589
+ keeper: this.params.wallet.publicKey.toBase58(),
590
+ rebalance_intent: intent.pubkey,
591
+ });
592
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
593
+ console.log("Redeem Tokens -", res);
594
+ }
595
+ catch (e) {
596
+ if (numTriesRedeemTokens == 3) {
597
+ console.log("Stop monitoring -", e);
598
+ }
599
+ }
600
+ continue;
601
+ }
602
+ if (numTriesClaimBounty >= 3)
603
+ break;
604
+ numTriesClaimBounty += 1;
605
+ try {
606
+ let tx = yield this.params.symmetryCore.claimBountyTx({
607
+ keeper: this.params.wallet.publicKey.toBase58(),
608
+ rebalance_intent: intent.pubkey,
609
+ });
610
+ let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
611
+ console.log("Claim Bounty -", res);
612
+ nextCheckTime = now + 60;
613
+ }
614
+ catch (e) {
615
+ if (numTriesClaimBounty == 3) {
616
+ console.log("Stop monitoring -", e);
617
+ }
618
+ }
619
+ continue;
620
+ }
621
+ });
622
+ }
623
+ }
624
+ exports.RebalanceHandler = RebalanceHandler;