@symmetry-hq/temp-v3-sdk 0.0.61 → 0.0.63

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.
@@ -1,7 +1,7 @@
1
1
  import { PublicKey } from '@solana/web3.js';
2
2
  import Decimal from 'decimal.js';
3
3
  export declare const COMPUTE_UNITS = 1000000;
4
- export declare const PRIORITY_FEE = 100000;
4
+ export declare const PRIORITY_FEE = 25000;
5
5
  export declare const BASKETS_V3_PROGRAM_ID: PublicKey;
6
6
  export declare const METADATA_PROGRAM_ID: PublicKey;
7
7
  export declare const ADDRESS_LOOKUP_TABLE_PROGRAM_ID: PublicKey;
@@ -7,7 +7,7 @@ exports.UPDATE_TOKEN_PRICES_MAX_ACCOUNTS = exports.LUT_EXTEND_BATCH_SIZE = expor
7
7
  const web3_js_1 = require("@solana/web3.js");
8
8
  const decimal_js_1 = __importDefault(require("decimal.js"));
9
9
  exports.COMPUTE_UNITS = 1000000;
10
- exports.PRIORITY_FEE = 100000;
10
+ exports.PRIORITY_FEE = 25000;
11
11
  exports.BASKETS_V3_PROGRAM_ID = new web3_js_1.PublicKey("BASKT7aKd8n7ibpUbwLP3Wiyxyi3yoiXsxBk4Hpumate");
12
12
  exports.METADATA_PROGRAM_ID = new web3_js_1.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
13
13
  exports.ADDRESS_LOOKUP_TABLE_PROGRAM_ID = new web3_js_1.PublicKey("AddressLookupTab1e1111111111111111111111111");
@@ -17,7 +17,7 @@ export declare class SymmetryCore {
17
17
  * @param params {connection: Connection, network: "devnet" | "mainnet", priorityFee?: number} - The parameters for the SDK.
18
18
  * @param params.connection - The connection to the Solana network.
19
19
  * @param params.network - The network to use (devnet or mainnet).
20
- * @param params.priorityFee - Optional. Compute unit price in micro-lamports. Defaults to PRIORITY_FEE (10_000).
20
+ * @param params.priorityFee - Optional. Compute unit price in micro-lamports. Defaults to PRIORITY_FEE (25_000).
21
21
  */
22
22
  constructor(params: {
23
23
  connection: Connection;
@@ -796,4 +796,4 @@ export { FormattedRebalanceType, FormattedRebalanceAction, FormattedOraclePrice,
796
796
  export { FormattedCreatorSettings, FormattedManagersSettings, FormattedFeeSettings, FormattedScheduleSettings, FormattedAutomationSettings, FormattedLpSettings, FormattedMetadataSettings, FormattedDepositsSettings, FormattedForceRebalanceSettings, FormattedCustomRebalanceSettings, FormattedAddTokenSettings, FormattedUpdateWeightsSettings, FormattedMakeDirectSwapSettings, FormattedAccumulatedFees, FormattedLookupTables, FormattedAsset, FormattedOracleSettings, FormattedOracleAggregator, FormattedOracle, FormattedOracleType, FormattedBasket, };
797
797
  export { EditCreatorSettings, EditManagerSettings, EditFeeSettings, EditScheduleSettings, EditAutomationSettings, EditLpSettings, EditMetadataSettings, EditDepositsSettings, EditForceRebalanceSettings, EditCustomRebalanceSettings, EditAddTokenSettings, EditUpdateWeightsSettings, EditMakeDirectSwapSettings, AddOrEditTokenInput, OracleInput, UpdateWeightsInput, MakeDirectSwapInput, Settings, TaskContext, TaskType, };
798
798
  export { getJupTokenLedgerAndSwapInstructions, };
799
- export { KeeperMonitor } from './keeperMonitor';
799
+ export { KeeperMonitor, RebalanceHandler, } from './keeperMonitor';
package/dist/src/index.js CHANGED
@@ -12,7 +12,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.KeeperMonitor = exports.getJupTokenLedgerAndSwapInstructions = exports.TaskType = exports.SymmetryCore = void 0;
15
+ exports.RebalanceHandler = exports.KeeperMonitor = exports.getJupTokenLedgerAndSwapInstructions = exports.TaskType = exports.SymmetryCore = void 0;
16
16
  const decimal_js_1 = __importDefault(require("decimal.js"));
17
17
  const bn_js_1 = __importDefault(require("bn.js"));
18
18
  const spl_token_1 = require("@solana/spl-token");
@@ -51,7 +51,7 @@ class SymmetryCore {
51
51
  * @param params {connection: Connection, network: "devnet" | "mainnet", priorityFee?: number} - The parameters for the SDK.
52
52
  * @param params.connection - The connection to the Solana network.
53
53
  * @param params.network - The network to use (devnet or mainnet).
54
- * @param params.priorityFee - Optional. Compute unit price in micro-lamports. Defaults to PRIORITY_FEE (10_000).
54
+ * @param params.priorityFee - Optional. Compute unit price in micro-lamports. Defaults to PRIORITY_FEE (25_000).
55
55
  */
56
56
  constructor(params) {
57
57
  var _a;
@@ -772,10 +772,10 @@ class SymmetryCore {
772
772
  basket: basket.ownAddress,
773
773
  rebalanceIntent: undefined,
774
774
  intent: intent,
775
- mintIn: new web3_js_1.PublicKey(editData.make_direct_swap.from_token_mint),
776
- mintOut: new web3_js_1.PublicKey(editData.make_direct_swap.to_token_mint),
777
- amountIn: new bn_js_1.default(editData.make_direct_swap.amount_from),
778
- amountOut: new bn_js_1.default(editData.make_direct_swap.amount_to),
775
+ mintIn: new web3_js_1.PublicKey(editData.from_token_mint),
776
+ mintOut: new web3_js_1.PublicKey(editData.to_token_mint),
777
+ amountIn: new bn_js_1.default(editData.amount_from),
778
+ amountOut: new bn_js_1.default(editData.amount_to),
779
779
  mode: undefined,
780
780
  };
781
781
  let ixWithdraw = (0, flashSwap_1.flashWithdrawIx)(flashParams);
@@ -2087,3 +2087,4 @@ class SymmetryCore {
2087
2087
  exports.SymmetryCore = SymmetryCore;
2088
2088
  var keeperMonitor_1 = require("./keeperMonitor");
2089
2089
  Object.defineProperty(exports, "KeeperMonitor", { enumerable: true, get: function () { return keeperMonitor_1.KeeperMonitor; } });
2090
+ Object.defineProperty(exports, "RebalanceHandler", { enumerable: true, get: function () { return keeperMonitor_1.RebalanceHandler; } });
@@ -338,7 +338,7 @@ function createEditBasketIntentIx(params) {
338
338
  });
339
339
  break;
340
340
  case intent_1.TaskType.UpdateWeights: { // 15 - 202
341
- const updateWeightsData = editData.update_weights;
341
+ const updateWeightsData = editData;
342
342
  const weights = updateWeightsData.token_weights.slice(0, constants_1.MAX_SUPPORTED_TOKENS_PER_BASKET);
343
343
  while (weights.length < constants_1.MAX_SUPPORTED_TOKENS_PER_BASKET)
344
344
  weights.push({ mint: '', weight_bps: 0 });
@@ -353,7 +353,7 @@ function createEditBasketIntentIx(params) {
353
353
  break;
354
354
  }
355
355
  case intent_1.TaskType.MakeDirectSwap: // 16 - 203
356
- let makeDirectSwapData = editData.make_direct_swap;
356
+ let makeDirectSwapData = editData;
357
357
  let makeDirectSwap = {
358
358
  fromTokenMint: new web3_js_1.PublicKey(makeDirectSwapData.from_token_mint),
359
359
  toTokenMint: new web3_js_1.PublicKey(makeDirectSwapData.to_token_mint),
@@ -1,5 +1,6 @@
1
- import { Connection } from "@solana/web3.js";
1
+ import { Connection, PublicKey } from "@solana/web3.js";
2
2
  import { Wallet } from "./txUtils";
3
+ import { Basket, UIRebalanceIntent } from ".";
3
4
  export declare class KeeperMonitor {
4
5
  private params;
5
6
  private intents;
@@ -20,3 +21,32 @@ export declare class KeeperMonitor {
20
21
  monitorIntent(pubkey: string): Promise<void>;
21
22
  monitorRebalanceIntent(pubkey: string): Promise<void>;
22
23
  }
24
+ export declare class RebalanceHandler {
25
+ private params;
26
+ private intent;
27
+ private basket;
28
+ constructor(params: {
29
+ intent: UIRebalanceIntent;
30
+ basket: Basket;
31
+ wallet: Wallet;
32
+ connection: Connection;
33
+ network: "devnet" | "mainnet";
34
+ jupiterApiKey: string;
35
+ maxAllowedAccounts: number;
36
+ priorityFee?: number;
37
+ simulateTransactions?: boolean;
38
+ });
39
+ delay: (ms: number) => Promise<unknown>;
40
+ refresh(): Promise<void>;
41
+ static run(params: {
42
+ intentPubkey: PublicKey;
43
+ wallet: Wallet;
44
+ connection: Connection;
45
+ network: "devnet" | "mainnet";
46
+ jupiterApiKey: string;
47
+ maxAllowedAccounts: number;
48
+ priorityFee?: number;
49
+ simulateTransactions?: boolean;
50
+ }): Promise<void>;
51
+ private execute;
52
+ }
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.KeeperMonitor = void 0;
12
+ exports.RebalanceHandler = exports.KeeperMonitor = void 0;
13
13
  const web3_js_1 = require("@solana/web3.js");
14
14
  const _1 = require(".");
15
15
  const rebalanceIntent_1 = require("./states/intents/rebalanceIntent");
@@ -156,7 +156,7 @@ class KeeperMonitor {
156
156
  intent: intent.ownAddress.toBase58(),
157
157
  });
158
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);
159
+ console.log("Execute Basket Intent -", pubkey, " : ", res);
160
160
  nextCheckTime = now + 60;
161
161
  }
162
162
  catch (_a) { }
@@ -172,12 +172,12 @@ class KeeperMonitor {
172
172
  intent: intent.ownAddress.toBase58(),
173
173
  });
174
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);
175
+ console.log("Cancel Basket Intent -", pubkey, " : ", res);
176
176
  nextCheckTime = now + 60;
177
177
  }
178
178
  catch (e) {
179
179
  if (numTries == 4) {
180
- console.log("Stop monitoring - ", pubkey, " : ", e);
180
+ console.log("Stop monitoring -", pubkey, " : ", e);
181
181
  }
182
182
  }
183
183
  continue;
@@ -186,12 +186,14 @@ class KeeperMonitor {
186
186
  }
187
187
  monitorRebalanceIntent(pubkey) {
188
188
  return __awaiter(this, void 0, void 0, function* () {
189
- var _a, _b;
189
+ var _a, _b, _c, _d, _e;
190
190
  let nextCheckTime = 0;
191
191
  let numTriesUpdatePrices = 0;
192
192
  let numTriesMint = 0;
193
193
  let numTriesRedeemTokens = 0;
194
194
  let numTriesClaimBounty = 0;
195
+ let lastJupQuotesUpdate = 0;
196
+ let jupQuotes = [];
195
197
  while (true) {
196
198
  let uiIntent = this.rebalanceIntents.get(pubkey);
197
199
  if (!uiIntent)
@@ -213,7 +215,7 @@ class KeeperMonitor {
213
215
  continue;
214
216
  }
215
217
  if (intent.current_action == "update_prices") {
216
- if (numTriesUpdatePrices >= 3)
218
+ if (numTriesUpdatePrices >= 5)
217
219
  break;
218
220
  numTriesUpdatePrices += 1;
219
221
  try {
@@ -226,86 +228,90 @@ class KeeperMonitor {
226
228
  console.log("Update Prices - ", pubkey, " : ", res);
227
229
  }
228
230
  catch (e) {
229
- if (numTriesUpdatePrices == 3) {
231
+ if (numTriesUpdatePrices == 4) {
230
232
  console.log("Stop monitoring - ", pubkey, " : ", e);
231
233
  }
232
234
  }
235
+ nextCheckTime += 60;
233
236
  continue;
234
237
  }
235
238
  if (intent.auctions[2].end_time > now) {
236
239
  let basket = this.baskets.get(intent.basket);
237
240
  if (!basket)
238
241
  continue;
239
- let auction0StartTime = intent.auctions[0].start_time;
240
- let auction0EndTime = intent.auctions[0].end_time;
241
- let auction0MidTime = auction0StartTime + (auction0EndTime - auction0StartTime) / 2;
242
- let auction1StartTime = intent.auctions[1].start_time;
243
- let auction1EndTime = intent.auctions[1].end_time;
244
- let auction1MidTime = auction1StartTime + (auction1EndTime - auction1StartTime) / 2;
245
- let auction2StartTime = intent.auctions[2].start_time;
246
- let auction2EndTime = intent.auctions[2].end_time;
247
- let auction2MidTime = auction2StartTime + (auction2EndTime - auction2StartTime) / 2;
248
- if (now < auction0MidTime + 30) {
249
- nextCheckTime = auction0MidTime + 30;
250
- continue;
251
- }
252
- if (now >= auction0EndTime) {
253
- if (now < auction1MidTime + 10) {
254
- nextCheckTime = auction1MidTime + 10;
255
- continue;
256
- }
257
- if (now >= auction1EndTime)
258
- if (now < auction2MidTime + 5) {
259
- nextCheckTime = auction2MidTime + 5;
260
- continue;
261
- }
262
- }
263
242
  let pairs = (0, rebalanceIntent_1.getSwapPairs)(chainData, basket);
264
- for (let pair of pairs)
265
- try {
243
+ if (Date.now() / 1000 > lastJupQuotesUpdate + 60) {
244
+ lastJupQuotesUpdate = Date.now() / 1000;
245
+ jupQuotes = [];
246
+ for (let pair of pairs) {
266
247
  if (pair.value < 0.005)
267
248
  continue;
268
- yield this.delay(1000);
269
- let { tokenLedgerInstruction, swapInstruction, addressLookupTableAddresses, quoteResponse } = this.params.network == "mainnet" ?
270
- yield (0, _1.getJupTokenLedgerAndSwapInstructions)({
271
- keeper: this.params.wallet.publicKey,
272
- basketMintIn: new web3_js_1.PublicKey(pair.inMint),
273
- basketMintOut: new web3_js_1.PublicKey(pair.outMint),
274
- basketAmountIn: pair.inAmount,
275
- basketAmountOut: pair.outAmount,
276
- swapMode: "ioc",
277
- apiKey: this.params.jupiterApiKey,
278
- maxJupAccounts: this.params.maxAllowedAccounts,
279
- }) : { tokenLedgerInstruction: undefined, swapInstruction: undefined, addressLookupTableAddresses: [], quoteResponse: undefined };
280
- console.log(pair, "Jup Quote:", parseFloat((_a = quoteResponse === null || quoteResponse === void 0 ? void 0 : quoteResponse.outAmount) !== null && _a !== void 0 ? _a : 0), "Requested In:", pair.inAmount);
281
- if (this.params.network == "devnet" || parseFloat((_b = quoteResponse === null || quoteResponse === void 0 ? void 0 : quoteResponse.outAmount) !== null && _b !== void 0 ? _b : 0) > pair.inAmount) {
249
+ if (this.params.network == "mainnet")
282
250
  try {
283
- let tx = yield this.params.symmetryCore.flashSwapTx({
284
- keeper: this.params.wallet.publicKey.toBase58(),
285
- basket: basket.ownAddress.toBase58(),
286
- rebalance_intent: intent.pubkey,
287
- mint_in: pair.inMint,
288
- mint_out: pair.outMint,
289
- amount_in: pair.inAmount,
290
- amount_out: pair.outAmount,
291
- mode: 2,
292
- jup_token_ledger_ix: tokenLedgerInstruction,
293
- jup_swap_ix: swapInstruction,
294
- jup_address_lookup_table_addresses: addressLookupTableAddresses,
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,
295
260
  });
296
- let res = yield this.params.symmetryCore.signAndSendTxPayloadBatchSequence({ txPayloadBatchSequence: tx, wallet: this.params.wallet, simulateTransactions: this.params.simulateTransactions });
297
- console.log("Flash Swap - ", pubkey, " : ", res);
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);
298
264
  }
299
- catch (_c) { }
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));
300
304
  }
305
+ catch (_g) { }
301
306
  }
302
- catch (_d) { }
307
+ catch (_h) { }
303
308
  nextCheckTime = (Date.now() / 1000) + 8;
304
309
  continue;
305
310
  }
306
311
  if (intent.rebalance_type == "deposit") {
307
312
  if (numTriesMint >= 3)
308
313
  break;
314
+ lastJupQuotesUpdate = 0;
309
315
  numTriesMint += 1;
310
316
  try {
311
317
  let tx = yield this.params.symmetryCore.mintTx({
@@ -365,3 +371,254 @@ class KeeperMonitor {
365
371
  }
366
372
  }
367
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 >= 3) {
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 == 3) {
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;
@@ -0,0 +1,32 @@
1
+ import { Connection, PublicKey } from "@solana/web3.js";
2
+ import { Wallet } from "./txUtils";
3
+ import { Basket, UIRebalanceIntent } from ".";
4
+ export declare class RebalanceHandler {
5
+ private params;
6
+ private intent;
7
+ private basket;
8
+ constructor(params: {
9
+ intent: UIRebalanceIntent;
10
+ basket: Basket;
11
+ wallet: Wallet;
12
+ connection: Connection;
13
+ network: "devnet" | "mainnet";
14
+ jupiterApiKey: string;
15
+ maxAllowedAccounts: number;
16
+ priorityFee?: number;
17
+ simulateTransactions?: boolean;
18
+ });
19
+ delay: (ms: number) => Promise<unknown>;
20
+ refresh(): Promise<void>;
21
+ static run(params: {
22
+ intentPubkey: PublicKey;
23
+ wallet: Wallet;
24
+ connection: Connection;
25
+ network: "devnet" | "mainnet";
26
+ jupiterApiKey: string;
27
+ maxAllowedAccounts: number;
28
+ priorityFee?: number;
29
+ simulateTransactions?: boolean;
30
+ }): Promise<void>;
31
+ private execute;
32
+ }