@pyron-finance/pyron-client 2.5.2 → 2.6.0

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,68 +1,1255 @@
1
- const require_common = require('../common-DBVYOab7.cjs');
2
-
3
- exports.CustomNumberFormat = require_common.CustomNumberFormat;
4
- exports.NodeWallet = require_common.NodeWallet;
5
- exports.PriotitizationFeeLevels = require_common.PriotitizationFeeLevels;
6
- exports.TransactionArenaKeyMap = require_common.TransactionArenaKeyMap;
7
- exports.TransactionConfigMap = require_common.TransactionConfigMap;
8
- exports.TransactionType = require_common.TransactionType;
9
- exports.addTransactionMetadata = require_common.addTransactionMetadata;
10
- exports.aprToApy = require_common.aprToApy;
11
- exports.apyToApr = require_common.apyToApr;
12
- exports.bankExtendedMetadataOverrideSchema = require_common.bankExtendedMetadataOverrideSchema;
13
- exports.bigNumberToWrappedI80F48 = require_common.bigNumberToWrappedI80F48;
14
- exports.bpsToPercentile = require_common.bpsToPercentile;
15
- exports.calculateApyFromInterest = require_common.calculateApyFromInterest;
16
- exports.calculateInterestFromApy = require_common.calculateInterestFromApy;
17
- exports.ceil = require_common.ceil;
18
- exports.chunkedGetRawMultipleAccountInfoOrdered = require_common.chunkedGetRawMultipleAccountInfoOrdered;
19
- exports.chunkedGetRawMultipleAccountInfoOrderedWithNulls = require_common.chunkedGetRawMultipleAccountInfoOrderedWithNulls;
20
- exports.chunkedGetRawMultipleAccountInfos = require_common.chunkedGetRawMultipleAccountInfos;
21
- exports.chunks = require_common.chunks;
22
- exports.clampedNumeralFormatter = require_common.clampedNumeralFormatter;
23
- exports.compareInstructions = require_common.compareInstructions;
24
- exports.composeRemainingAccounts = require_common.composeRemainingAccounts;
25
- exports.decodeComputeBudgetInstruction = require_common.decodeComputeBudgetInstruction;
26
- exports.decodeInstruction = require_common.decodeInstruction;
27
- exports.decompileV0Transaction = require_common.decompileV0Transaction;
28
- exports.dynamicNumeralFormatter = require_common.dynamicNumeralFormatter;
29
- exports.fetchBanksExtendedMetadata = require_common.fetchBanksExtendedMetadata;
30
- exports.floor = require_common.floor;
31
- exports.getAccountKeys = require_common.getAccountKeys;
32
- exports.getCalculatedPrioritizationFeeByPercentile = require_common.getCalculatedPrioritizationFeeByPercentile;
33
- exports.getComputeBudgetUnits = require_common.getComputeBudgetUnits;
34
- exports.getMaxPrioritizationFeeByPercentile = require_common.getMaxPrioritizationFeeByPercentile;
35
- exports.getMeanPrioritizationFeeByPercentile = require_common.getMeanPrioritizationFeeByPercentile;
36
- exports.getMedianPrioritizationFeeByPercentile = require_common.getMedianPrioritizationFeeByPercentile;
37
- exports.getMinPrioritizationFeeByPercentile = require_common.getMinPrioritizationFeeByPercentile;
38
- exports.getRecentPrioritizationFeesByPercentile = require_common.getRecentPrioritizationFeesByPercentile;
39
- exports.getTxSize = require_common.getTxSize;
40
- exports.getValueInsensitive = require_common.getValueInsensitive;
41
- exports.groupedNumberFormatter = require_common.groupedNumberFormatter;
42
- exports.groupedNumberFormatterDyn = require_common.groupedNumberFormatterDyn;
43
- exports.isV0Tx = require_common.isV0Tx;
44
- exports.legacyTxToV0Tx = require_common.legacyTxToV0Tx;
45
- exports.median = require_common.median;
46
- exports.microLamportsToUi = require_common.microLamportsToUi;
47
- exports.nativeToUi = require_common.nativeToUi;
48
- exports.numeralFormatter = require_common.numeralFormatter;
49
- exports.parseBanksMetadataOverride = require_common.parseBanksMetadataOverride;
50
- exports.percentFormatter = require_common.percentFormatter;
51
- exports.percentFormatterDyn = require_common.percentFormatterDyn;
52
- exports.percentFormatterMod = require_common.percentFormatterMod;
53
- exports.replaceV0TxBlockhash = require_common.replaceV0TxBlockhash;
54
- exports.replaceV0TxInstructions = require_common.replaceV0TxInstructions;
55
- exports.setTimeoutPromise = require_common.setTimeoutPromise;
56
- exports.shortenAddress = require_common.shortenAddress;
57
- exports.sleep = require_common.sleep;
58
- exports.splitInstructionsToFitTransactions = require_common.splitInstructionsToFitTransactions;
59
- exports.toBigNumber = require_common.toBigNumber;
60
- exports.toNumber = require_common.toNumber;
61
- exports.tokenPriceFormatter = require_common.tokenPriceFormatter;
62
- exports.uiToMicroLamports = require_common.uiToMicroLamports;
63
- exports.uiToNative = require_common.uiToNative;
64
- exports.uiToNativeBigNumber = require_common.uiToNativeBigNumber;
65
- exports.updateV0Tx = require_common.updateV0Tx;
66
- exports.usdFormatter = require_common.usdFormatter;
67
- exports.usdFormatterDyn = require_common.usdFormatterDyn;
68
- exports.wrappedI80F48toBigNumber = require_common.wrappedI80F48toBigNumber;
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/common/index.ts
31
+ var common_exports = {};
32
+ __export(common_exports, {
33
+ CustomNumberFormat: () => CustomNumberFormat,
34
+ NodeWallet: () => NodeWallet,
35
+ PriotitizationFeeLevels: () => PriotitizationFeeLevels,
36
+ TransactionArenaKeyMap: () => TransactionArenaKeyMap,
37
+ TransactionConfigMap: () => TransactionConfigMap,
38
+ TransactionType: () => TransactionType,
39
+ addTransactionMetadata: () => addTransactionMetadata,
40
+ aprToApy: () => aprToApy,
41
+ apyToApr: () => apyToApr,
42
+ bankExtendedMetadataOverrideSchema: () => bankExtendedMetadataOverrideSchema,
43
+ bigNumberToWrappedI80F48: () => bigNumberToWrappedI80F48,
44
+ bpsToPercentile: () => bpsToPercentile,
45
+ calculateApyFromInterest: () => calculateApyFromInterest,
46
+ calculateInterestFromApy: () => calculateInterestFromApy,
47
+ ceil: () => ceil,
48
+ chunkedGetRawMultipleAccountInfoOrdered: () => chunkedGetRawMultipleAccountInfoOrdered,
49
+ chunkedGetRawMultipleAccountInfoOrderedWithNulls: () => chunkedGetRawMultipleAccountInfoOrderedWithNulls,
50
+ chunkedGetRawMultipleAccountInfos: () => chunkedGetRawMultipleAccountInfos,
51
+ chunks: () => chunks,
52
+ clampedNumeralFormatter: () => clampedNumeralFormatter,
53
+ compareInstructions: () => compareInstructions,
54
+ composeRemainingAccounts: () => composeRemainingAccounts,
55
+ decodeComputeBudgetInstruction: () => decodeComputeBudgetInstruction,
56
+ decodeInstruction: () => decodeInstruction,
57
+ decompileV0Transaction: () => decompileV0Transaction,
58
+ dynamicNumeralFormatter: () => dynamicNumeralFormatter,
59
+ fetchBanksExtendedMetadata: () => fetchBanksExtendedMetadata,
60
+ floor: () => floor,
61
+ getAccountKeys: () => getAccountKeys,
62
+ getCalculatedPrioritizationFeeByPercentile: () => getCalculatedPrioritizationFeeByPercentile,
63
+ getComputeBudgetUnits: () => getComputeBudgetUnits,
64
+ getMaxPrioritizationFeeByPercentile: () => getMaxPrioritizationFeeByPercentile,
65
+ getMeanPrioritizationFeeByPercentile: () => getMeanPrioritizationFeeByPercentile,
66
+ getMedianPrioritizationFeeByPercentile: () => getMedianPrioritizationFeeByPercentile,
67
+ getMinPrioritizationFeeByPercentile: () => getMinPrioritizationFeeByPercentile,
68
+ getRecentPrioritizationFeesByPercentile: () => getRecentPrioritizationFeesByPercentile,
69
+ getTxSize: () => getTxSize,
70
+ getValueInsensitive: () => getValueInsensitive,
71
+ groupedNumberFormatter: () => groupedNumberFormatter,
72
+ groupedNumberFormatterDyn: () => groupedNumberFormatterDyn,
73
+ isV0Tx: () => isV0Tx,
74
+ legacyTxToV0Tx: () => legacyTxToV0Tx,
75
+ median: () => median,
76
+ microLamportsToUi: () => microLamportsToUi,
77
+ nativeToUi: () => nativeToUi,
78
+ numeralFormatter: () => numeralFormatter,
79
+ parseBanksMetadataOverride: () => parseBanksMetadataOverride,
80
+ percentFormatter: () => percentFormatter,
81
+ percentFormatterDyn: () => percentFormatterDyn,
82
+ percentFormatterMod: () => percentFormatterMod,
83
+ replaceV0TxBlockhash: () => replaceV0TxBlockhash,
84
+ replaceV0TxInstructions: () => replaceV0TxInstructions,
85
+ setTimeoutPromise: () => setTimeoutPromise,
86
+ shortenAddress: () => shortenAddress,
87
+ sleep: () => sleep,
88
+ splitInstructionsToFitTransactions: () => splitInstructionsToFitTransactions,
89
+ toBigNumber: () => toBigNumber,
90
+ toNumber: () => toNumber,
91
+ tokenPriceFormatter: () => tokenPriceFormatter,
92
+ uiToMicroLamports: () => uiToMicroLamports,
93
+ uiToNative: () => uiToNative,
94
+ uiToNativeBigNumber: () => uiToNativeBigNumber,
95
+ updateV0Tx: () => updateV0Tx,
96
+ usdFormatter: () => usdFormatter,
97
+ usdFormatterDyn: () => usdFormatterDyn,
98
+ wrappedI80F48toBigNumber: () => wrappedI80F48toBigNumber
99
+ });
100
+ module.exports = __toCommonJS(common_exports);
101
+
102
+ // src/common/nodeWallet.ts
103
+ var NodeWallet = class {
104
+ /**
105
+ * @param payer Keypair of the associated payer
106
+ */
107
+ constructor(payer) {
108
+ this.payer = payer;
109
+ }
110
+ async signTransaction(tx) {
111
+ if ("version" in tx) {
112
+ tx.sign([this.payer]);
113
+ } else {
114
+ tx.partialSign(this.payer);
115
+ }
116
+ return tx;
117
+ }
118
+ async signAllTransactions(txs) {
119
+ return txs.map((tx) => {
120
+ if ("version" in tx) {
121
+ tx.sign([this.payer]);
122
+ return tx;
123
+ } else {
124
+ tx.partialSign(this.payer);
125
+ return tx;
126
+ }
127
+ });
128
+ }
129
+ get publicKey() {
130
+ return this.payer.publicKey;
131
+ }
132
+ };
133
+
134
+ // src/common/math.ts
135
+ function floor(value, decimals) {
136
+ return Math.floor(value * 10 ** decimals) / 10 ** decimals;
137
+ }
138
+ function ceil(value, decimals) {
139
+ return Math.ceil(value * 10 ** decimals) / 10 ** decimals;
140
+ }
141
+ function median(values) {
142
+ if (values.length === 0) {
143
+ throw new Error("Input array is empty");
144
+ }
145
+ const sortedValues = [...values].sort((a, b) => a - b);
146
+ const half = Math.floor(sortedValues.length / 2);
147
+ return sortedValues.length % 2 ? sortedValues[half] : (sortedValues[half - 1] + sortedValues[half]) / 2;
148
+ }
149
+
150
+ // src/common/misc.ts
151
+ var import_web3 = require("@solana/web3.js");
152
+ function getValueInsensitive(map, key) {
153
+ const lowerCaseLabel = key.toLowerCase();
154
+ for (const key2 in map) {
155
+ if (key2.toLowerCase() === lowerCaseLabel) {
156
+ return map[key2];
157
+ }
158
+ }
159
+ throw new Error(`Token metadata not found for ${key}`);
160
+ }
161
+ function sleep(ms) {
162
+ return new Promise((resolve) => setTimeout(resolve, ms));
163
+ }
164
+ function chunks(array, size) {
165
+ return Array.apply(0, new Array(Math.ceil(array.length / size))).map(
166
+ (_, index) => array.slice(index * size, (index + 1) * size)
167
+ );
168
+ }
169
+ function setTimeoutPromise(duration, message) {
170
+ return new Promise((_, reject) => setTimeout(() => reject(new Error(message)), duration));
171
+ }
172
+ async function chunkedGetRawMultipleAccountInfos(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
173
+ const accountInfoMap = /* @__PURE__ */ new Map();
174
+ let contextSlot = 0;
175
+ const batches = chunkArray(pks, batchChunkSize);
176
+ for (let i = 0; i < batches.length; i++) {
177
+ const batch = batches[i];
178
+ const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
179
+ methodName: "getMultipleAccounts",
180
+ args: connection._buildArgs([pubkeys], "confirmed", "base64")
181
+ }));
182
+ let accountInfos = [];
183
+ let retries = 0;
184
+ const maxRetries = 3;
185
+ while (retries < maxRetries && accountInfos.length === 0) {
186
+ try {
187
+ accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
188
+ contextSlot = Math.max(...batchResults.map((res) => res.result.context.slot));
189
+ const accounts = batchResults.reduce(
190
+ (acc, res) => {
191
+ acc.push(...res.result.value);
192
+ return acc;
193
+ },
194
+ []
195
+ );
196
+ return accounts;
197
+ });
198
+ } catch (_error) {
199
+ retries++;
200
+ }
201
+ }
202
+ if (accountInfos.length === 0) {
203
+ throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
204
+ }
205
+ accountInfos.forEach((item, index) => {
206
+ const publicKey = batch[index];
207
+ if (item) {
208
+ accountInfoMap.set(publicKey, {
209
+ ...item,
210
+ owner: new import_web3.PublicKey(item.owner),
211
+ data: Buffer.from(item.data[0], "base64")
212
+ });
213
+ }
214
+ });
215
+ }
216
+ return [contextSlot, accountInfoMap];
217
+ }
218
+ async function chunkedGetRawMultipleAccountInfoOrderedWithNulls(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
219
+ const allAccountInfos = [];
220
+ const batches = chunkArray(pks, batchChunkSize);
221
+ for (let i = 0; i < batches.length; i++) {
222
+ const batch = batches[i];
223
+ const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
224
+ methodName: "getMultipleAccounts",
225
+ args: connection._buildArgs([pubkeys], "confirmed", "base64")
226
+ }));
227
+ let accountInfos = [];
228
+ let retries = 0;
229
+ const maxRetries = 3;
230
+ while (retries < maxRetries && accountInfos.length === 0) {
231
+ try {
232
+ accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
233
+ const accounts = batchResults.reduce(
234
+ (acc, res) => {
235
+ acc.push(...res.result.value);
236
+ return acc;
237
+ },
238
+ []
239
+ );
240
+ return accounts;
241
+ });
242
+ } catch (_error) {
243
+ retries++;
244
+ }
245
+ }
246
+ if (accountInfos.length === 0) {
247
+ throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
248
+ }
249
+ accountInfos.forEach((item) => {
250
+ if (item) {
251
+ allAccountInfos.push({
252
+ ...item,
253
+ owner: new import_web3.PublicKey(item.owner),
254
+ data: Buffer.from(item.data[0], "base64")
255
+ });
256
+ } else {
257
+ allAccountInfos.push(null);
258
+ }
259
+ });
260
+ }
261
+ return allAccountInfos;
262
+ }
263
+ async function chunkedGetRawMultipleAccountInfoOrdered(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
264
+ const allAccountInfos = [];
265
+ const batches = chunkArray(pks, batchChunkSize);
266
+ for (let i = 0; i < batches.length; i++) {
267
+ const batch = batches[i];
268
+ const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
269
+ methodName: "getMultipleAccounts",
270
+ args: connection._buildArgs([pubkeys], "confirmed", "base64")
271
+ }));
272
+ let accountInfos = [];
273
+ let retries = 0;
274
+ const maxRetries = 3;
275
+ while (retries < maxRetries && accountInfos.length === 0) {
276
+ try {
277
+ accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
278
+ const accounts = batchResults.reduce(
279
+ (acc, res) => {
280
+ acc.push(...res.result.value);
281
+ return acc;
282
+ },
283
+ []
284
+ );
285
+ return accounts;
286
+ });
287
+ } catch (_error) {
288
+ retries++;
289
+ }
290
+ }
291
+ if (accountInfos.length === 0) {
292
+ throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
293
+ }
294
+ accountInfos.forEach((item) => {
295
+ if (item) {
296
+ allAccountInfos.push({
297
+ ...item,
298
+ owner: new import_web3.PublicKey(item.owner),
299
+ data: Buffer.from(item.data[0], "base64")
300
+ });
301
+ }
302
+ });
303
+ }
304
+ return allAccountInfos;
305
+ }
306
+ function chunkArray(array, chunkSize) {
307
+ const chunks2 = [];
308
+ for (let i = 0; i < array.length; i += chunkSize) {
309
+ chunks2.push(array.slice(i, i + chunkSize));
310
+ }
311
+ return chunks2;
312
+ }
313
+
314
+ // src/common/modules/transactions/transaction.types.ts
315
+ var import_web32 = require("@solana/web3.js");
316
+ var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
317
+ TransactionType2["DEPOSIT"] = "DEPOSIT";
318
+ TransactionType2["WITHDRAW"] = "WITHDRAW";
319
+ TransactionType2["REPAY"] = "REPAY";
320
+ TransactionType2["BORROW"] = "BORROW";
321
+ TransactionType2["FLASHLOAN"] = "FLASHLOAN";
322
+ TransactionType2["LOOP"] = "LOOP";
323
+ TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
324
+ TransactionType2["LONG"] = "LONG";
325
+ TransactionType2["SHORT"] = "SHORT";
326
+ TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
327
+ TransactionType2["CREATE_ATA"] = "CREATE_ATA";
328
+ TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
329
+ TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
330
+ TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
331
+ TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
332
+ TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
333
+ TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
334
+ TransactionType2["CRANK"] = "CRANK";
335
+ TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
336
+ TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
337
+ TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
338
+ TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
339
+ TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
340
+ TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
341
+ TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
342
+ TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
343
+ TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
344
+ TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
345
+ TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
346
+ TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
347
+ TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
348
+ TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
349
+ TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
350
+ return TransactionType2;
351
+ })(TransactionType || {});
352
+ var TransactionConfigMap = {
353
+ // BASE LENDING ACTIONS
354
+ ["DEPOSIT" /* DEPOSIT */]: {
355
+ label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
356
+ },
357
+ ["WITHDRAW" /* WITHDRAW */]: {
358
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
359
+ },
360
+ ["REPAY" /* REPAY */]: {
361
+ label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
362
+ },
363
+ ["BORROW" /* BORROW */]: {
364
+ label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
365
+ },
366
+ // FLASHLOANS
367
+ ["FLASHLOAN" /* FLASHLOAN */]: { label: () => "Executing Flashloan" },
368
+ ["LOOP" /* LOOP */]: {
369
+ label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
370
+ },
371
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: {
372
+ label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
373
+ },
374
+ ["LONG" /* LONG */]: {
375
+ label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
376
+ },
377
+ ["SHORT" /* SHORT */]: {
378
+ label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
379
+ },
380
+ // SWB
381
+ ["CRANK" /* CRANK */]: { label: () => "Updating latest prices" },
382
+ ["JUPITER_SWAP" /* JUPITER_SWAP */]: {
383
+ label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
384
+ },
385
+ // SETUP
386
+ ["CREATE_ACCOUNT" /* CREATE_ACCOUNT */]: { label: () => "Create lendr account" },
387
+ ["CREATE_ATA" /* CREATE_ATA */]: { label: () => "Configure token account" },
388
+ // ACCOUNT MANAGEMENT
389
+ ["CLOSE_ACCOUNT" /* CLOSE_ACCOUNT */]: { label: () => "Close lendr account" },
390
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: { label: () => "Close position" },
391
+ ["MOVE_POSITION_WITHDRAW" /* MOVE_POSITION_WITHDRAW */]: {
392
+ label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
393
+ },
394
+ ["MOVE_POSITION_DEPOSIT" /* MOVE_POSITION_DEPOSIT */]: {
395
+ label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
396
+ },
397
+ ["TRANSFER_AUTH" /* TRANSFER_AUTH */]: { label: () => "Authorize account transfer" },
398
+ // NATIVE STAKE ACTIONS
399
+ ["DEPOSIT_STAKE" /* DEPOSIT_STAKE */]: {
400
+ label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
401
+ },
402
+ ["WITHDRAW_STAKE" /* WITHDRAW_STAKE */]: {
403
+ label: () => "Authorize stake account"
404
+ },
405
+ ["INITIALIZE_STAKED_POOL" /* INITIALIZE_STAKED_POOL */]: { label: () => "Initialize stake pool" },
406
+ ["ADD_STAKED_BANK" /* ADD_STAKED_BANK */]: { label: () => "Create staked asset bank" },
407
+ ["MERGE_STAKE_ACCOUNTS" /* MERGE_STAKE_ACCOUNTS */]: { label: () => "Merge stake accounts" },
408
+ // LST (Liquid Staking Tokens)
409
+ ["STAKE_TO_STAKE" /* STAKE_TO_STAKE */]: { label: () => "Convert stake" },
410
+ ["MINT_LST_NATIVE" /* MINT_LST_NATIVE */]: { label: () => "Mint LST" },
411
+ ["SWAP_TO_SOL" /* SWAP_TO_SOL */]: {
412
+ label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
413
+ },
414
+ ["SOL_TO_LST" /* SOL_TO_LST */]: {
415
+ label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
416
+ },
417
+ ["UNSTAKE_LST" /* UNSTAKE_LST */]: { label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST" },
418
+ // EMISSIONS
419
+ ["WITHDRAW_EMISSIONS" /* WITHDRAW_EMISSIONS */]: { label: () => "Withdraw emissions" },
420
+ // LIQUIDATE
421
+ ["LIQUIDATE_ACCOUNT" /* LIQUIDATE_ACCOUNT */]: { label: () => "Liquidate account" },
422
+ // BANK and GROUPS
423
+ ["CREATE_PERM_BANK" /* CREATE_PERM_BANK */]: { label: () => "Create permissionless bank" },
424
+ ["CREATE_GROUP" /* CREATE_GROUP */]: { label: () => "Create lendr group" },
425
+ ["WITHDRAW_ALL" /* WITHDRAW_ALL */]: {
426
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
427
+ }
428
+ };
429
+ var TransactionArenaKeyMap = {
430
+ ["DEPOSIT" /* DEPOSIT */]: new import_web32.PublicKey("ArenaDeposit1111111111111111111111111111111"),
431
+ ["WITHDRAW" /* WITHDRAW */]: new import_web32.PublicKey("ArenaWithdraw111111111111111111111111111111"),
432
+ ["BORROW" /* BORROW */]: new import_web32.PublicKey("ArenaBorrow11111111111111111111111111111111"),
433
+ ["REPAY" /* REPAY */]: new import_web32.PublicKey("ArenaRepay111111111111111111111111111111111"),
434
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: new import_web32.PublicKey("ArenaRepayCo11at111111111111111111111111111"),
435
+ ["LONG" /* LONG */]: new import_web32.PublicKey("ArenaLong1111111111111111111111111111111111"),
436
+ ["SHORT" /* SHORT */]: new import_web32.PublicKey("ArenaShort111111111111111111111111111111111"),
437
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: new import_web32.PublicKey("ArenaC1ose111111111111111111111111111111111")
438
+ // Add more mappings if needed
439
+ };
440
+
441
+ // src/common/modules/transactions/transaction.utils.ts
442
+ var import_anchor = require("@coral-xyz/anchor");
443
+ var import_web36 = require("@solana/web3.js");
444
+
445
+ // src/constants/bank.ts
446
+ var PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED = Buffer.from("liquidity_vault_auth");
447
+ var PDA_BANK_INSURANCE_VAULT_AUTH_SEED = Buffer.from("insurance_vault_auth");
448
+ var PDA_BANK_FEE_VAULT_AUTH_SEED = Buffer.from("fee_vault_auth");
449
+ var PDA_BANK_LIQUIDITY_VAULT_SEED = Buffer.from("liquidity_vault");
450
+ var PDA_BANK_INSURANCE_VAULT_SEED = Buffer.from("insurance_vault");
451
+ var PDA_BANK_FEE_VAULT_SEED = Buffer.from("fee_vault");
452
+
453
+ // src/constants/defaults.ts
454
+ var DEFAULT_COMMITMENT = "processed";
455
+ var DEFAULT_SEND_OPTS = {
456
+ skipPreflight: false,
457
+ preflightCommitment: DEFAULT_COMMITMENT
458
+ };
459
+ var DEFAULT_CONFIRM_OPTS = {
460
+ commitment: DEFAULT_COMMITMENT,
461
+ ...DEFAULT_SEND_OPTS
462
+ };
463
+ var MAX_TX_SIZE = 1232;
464
+
465
+ // src/constants/flags.ts
466
+ var DISABLED_FLAG = 1 << 0;
467
+ var FLASHLOAN_ENABLED_FLAG = 1 << 2;
468
+ var TRANSFER_ACCOUNT_AUTHORITY_FLAG = 1 << 3;
469
+
470
+ // src/constants/misc.ts
471
+ var import_web33 = require("@solana/web3.js");
472
+ var import_bignumber = __toESM(require("bignumber.js"), 1);
473
+ var HOURS_PER_YEAR = 365.25 * 24;
474
+ var MAX_U64 = BigInt("18446744073709551615").toString();
475
+ var PYTH_PRICE_CONF_INTERVALS = new import_bignumber.default(2.12);
476
+ var SWB_PRICE_CONF_INTERVALS = new import_bignumber.default(1.96);
477
+ var MAX_CONFIDENCE_INTERVAL_RATIO = new import_bignumber.default(0.05);
478
+ var PYTH_PUSH_ORACLE_ID = new import_web33.PublicKey("pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT");
479
+ var GROUP_PK = new import_web33.PublicKey(process.env.LENDR_GROUP_PK ?? "4vDRNkXaeAcwJULZCQFFdNBM295sD8hSKQt3RaMwsRFc");
480
+ var PROGRAM_ID = new import_web33.PublicKey(process.env.LENDR_PROGRAM_ID ?? "89ZQeCPwkzSPJyTpktCKWNY6hBWMKuYt47R85Jo36yyh");
481
+ var DEFAULT_CLUSTER = process.env.LENDR_CLUSTER_OVERRIDE ?? "mainnet";
482
+
483
+ // src/constants/programs.ts
484
+ var import_web34 = require("@solana/web3.js");
485
+ var JUPITER_V6_PROGRAM = new import_web34.PublicKey("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");
486
+ var LENDR_PROGRAM = new import_web34.PublicKey("89ZQeCPwkzSPJyTpktCKWNY6hBWMKuYt47R85Jo36yyh");
487
+ var SINGLE_POOL_PROGRAM_ID = new import_web34.PublicKey("SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE");
488
+ var STAKE_PROGRAM_ID = new import_web34.PublicKey("Stake11111111111111111111111111111111111111");
489
+ var MPL_METADATA_PROGRAM_ID = new import_web34.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
490
+ var SYSTEM_PROGRAM_ID = new import_web34.PublicKey("11111111111111111111111111111111");
491
+ var SYSVAR_RENT_ID = new import_web34.PublicKey("SysvarRent111111111111111111111111111111111");
492
+ var SYSVAR_CLOCK_ID = new import_web34.PublicKey("SysvarC1ock11111111111111111111111111111111");
493
+ var SYSVAR_STAKE_HISTORY_ID = new import_web34.PublicKey("SysvarStakeHistory1111111111111111111111111");
494
+ var STAKE_CONFIG_ID = new import_web34.PublicKey("StakeConfig11111111111111111111111111111111");
495
+
496
+ // src/constants/tokens.ts
497
+ var import_web35 = require("@solana/web3.js");
498
+ var WSOL_MINT = new import_web35.PublicKey("So11111111111111111111111111111111111111112");
499
+ var WSOL_EXTENDED_METADATA = {
500
+ symbol: "wSOL",
501
+ name: "Wrapped SOL",
502
+ address: "D7zkaUgFUDkhQHExySRxokL3Fa1GFnnuiVDTs9yMrFHY",
503
+ logoURI: "https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/So11111111111111111111111111111111111111112/logo.png",
504
+ additionalMetadata: [],
505
+ uri: "",
506
+ mint: WSOL_MINT.toBase58()
507
+ };
508
+ var LST_MINT = new import_web35.PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
509
+ var USDC_MINT = new import_web35.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
510
+ var DUMMY_USDC_MINT = new import_web35.PublicKey("JAiSLhTCvAhGM4SojCYGoTPuqjw7KaCsopvRuNryzbML");
511
+
512
+ // src/common/modules/transactions/transaction.utils.ts
513
+ function isV0Tx(tx) {
514
+ return "message" in tx;
515
+ }
516
+ function getTxSize(tx) {
517
+ const isVersioned = isV0Tx(tx);
518
+ const numSigners = tx.signatures.length;
519
+ const numRequiredSignatures = isVersioned ? tx.message.header.numRequiredSignatures : 0;
520
+ const feePayerSize = isVersioned || tx.feePayer ? 0 : 32;
521
+ const signaturesSize = (numRequiredSignatures - numSigners) * 64 + 1;
522
+ try {
523
+ const baseTxSize = isVersioned ? tx.serialize().length : tx.serialize({ requireAllSignatures: false, verifySignatures: false }).length;
524
+ return baseTxSize + feePayerSize + signaturesSize;
525
+ } catch (_error) {
526
+ return 9999;
527
+ }
528
+ }
529
+ function getAccountKeys(tx, lookupTableAccounts) {
530
+ const isVersioned = isV0Tx(tx);
531
+ try {
532
+ if (isVersioned) {
533
+ const message = import_web36.TransactionMessage.decompile(tx.message, { addressLookupTableAccounts: lookupTableAccounts });
534
+ return message.compileToLegacyMessage().getAccountKeys().length;
535
+ } else {
536
+ return tx.compileMessage().getAccountKeys().length;
537
+ }
538
+ } catch (_error) {
539
+ return 9999;
540
+ }
541
+ }
542
+ function decodeInstruction(idl, encoded) {
543
+ const coder = new import_anchor.BorshInstructionCoder(idl);
544
+ return coder.decode(encoded, "base58");
545
+ }
546
+ function decompileV0Transaction(tx, lookupTableAccounts) {
547
+ return import_web36.TransactionMessage.decompile(tx.message, { addressLookupTableAccounts: lookupTableAccounts });
548
+ }
549
+ function legacyTxToV0Tx(transaction, opts) {
550
+ const feePayer = opts?.feePayer ?? transaction.feePayer;
551
+ const blockhash = opts?.blockhash ?? transaction.recentBlockhash;
552
+ const additionalIxs = opts?.additionalIxs ?? [];
553
+ const addressLookupTables = opts?.addressLookupTables ?? [];
554
+ if (!feePayer || !blockhash) {
555
+ throw new Error("Fee payer and blockhash are required");
556
+ }
557
+ const ixs = transaction.instructions;
558
+ const versionedMessage = new import_web36.TransactionMessage({
559
+ instructions: [...additionalIxs, ...ixs],
560
+ payerKey: feePayer,
561
+ recentBlockhash: blockhash
562
+ });
563
+ return new import_web36.VersionedTransaction(versionedMessage.compileToV0Message(addressLookupTables));
564
+ }
565
+ function updateV0Tx(transaction, opts) {
566
+ const additionalIxs = opts?.additionalIxs ?? [];
567
+ const addressLookupTables = opts?.addressLookupTables ?? [];
568
+ let instructions = [];
569
+ const message = decompileV0Transaction(transaction, addressLookupTables);
570
+ const feePayer = opts?.feePayer ?? message.payerKey;
571
+ const blockhash = opts?.blockhash ?? message.recentBlockhash;
572
+ if (additionalIxs.length > 0) {
573
+ instructions = replaceV0TxInstructions(additionalIxs, message.instructions, opts?.replaceOnly);
574
+ } else {
575
+ instructions = message.instructions;
576
+ }
577
+ const versionedMessage = new import_web36.TransactionMessage({
578
+ instructions,
579
+ payerKey: feePayer,
580
+ recentBlockhash: blockhash
581
+ });
582
+ return new import_web36.VersionedTransaction(versionedMessage.compileToV0Message(addressLookupTables));
583
+ }
584
+ function compareInstructions(ix1, ix2) {
585
+ const dataCompare = ix1.data.equals(ix2.data);
586
+ const programIdCompare = ix1.programId.equals(ix2.programId);
587
+ const keysCompare = ix1.keys.length === ix2.keys.length && ix1.keys.every((key, index) => {
588
+ const key2 = ix2.keys[index];
589
+ return key.pubkey.equals(key2.pubkey) && key.isSigner === key2.isSigner && key.isWritable === key2.isWritable;
590
+ });
591
+ return dataCompare && programIdCompare && keysCompare;
592
+ }
593
+ function replaceV0TxInstructions(additionalInstructions, instructions, replaceOnly) {
594
+ let updatedAdditionalIxs = additionalInstructions;
595
+ const updatedInstructions = instructions.map((ix) => {
596
+ const programId = ix.programId;
597
+ const additionalIxs = additionalInstructions.filter((a) => a.programId.equals(programId));
598
+ if (additionalIxs.length > 0) {
599
+ if (ix.programId.equals(import_web36.ComputeBudgetProgram.programId)) {
600
+ const decoded = decodeComputeBudgetInstruction(ix);
601
+ const updatedCuPriceIx = additionalIxs.find(
602
+ (a) => decodeComputeBudgetInstruction(a).instructionType === "SetComputeUnitPrice"
603
+ );
604
+ const updatedCuLimitIx = additionalIxs.find(
605
+ (a) => decodeComputeBudgetInstruction(a).instructionType === "SetComputeUnitLimit"
606
+ );
607
+ if (decoded.instructionType === "SetComputeUnitPrice" && updatedCuPriceIx) {
608
+ updatedAdditionalIxs = updatedAdditionalIxs.filter((a) => !compareInstructions(a, updatedCuPriceIx));
609
+ return updatedCuPriceIx;
610
+ }
611
+ if (decoded.instructionType === "SetComputeUnitLimit" && updatedCuLimitIx) {
612
+ updatedAdditionalIxs = updatedAdditionalIxs.filter((a) => !compareInstructions(a, updatedCuLimitIx));
613
+ return updatedCuLimitIx;
614
+ }
615
+ }
616
+ }
617
+ return ix;
618
+ });
619
+ return [...replaceOnly ? [] : updatedAdditionalIxs, ...updatedInstructions];
620
+ }
621
+ function replaceV0TxBlockhash(transaction, blockhash) {
622
+ const message = transaction.message;
623
+ message.recentBlockhash = blockhash;
624
+ return new import_web36.VersionedTransaction(message);
625
+ }
626
+ function addTransactionMetadata(transaction, options) {
627
+ return Object.assign(transaction, options);
628
+ }
629
+ function identifyComputeBudgetInstruction(data) {
630
+ const discriminator = data.readUInt8(0);
631
+ switch (discriminator) {
632
+ case 0:
633
+ return "RequestUnits";
634
+ case 1:
635
+ return "RequestHeapFrame";
636
+ case 2:
637
+ return "SetComputeUnitLimit";
638
+ case 3:
639
+ return "SetComputeUnitPrice";
640
+ case 4:
641
+ return "SetLoadedAccountsDataSizeLimit";
642
+ default:
643
+ throw new Error("Unknown ComputeBudget instruction discriminator.");
644
+ }
645
+ }
646
+ function decodeComputeBudgetInstruction(instruction) {
647
+ const data = Buffer.from(instruction.data || instruction);
648
+ const instructionType = identifyComputeBudgetInstruction(data);
649
+ switch (instructionType) {
650
+ case "RequestUnits": {
651
+ if (data.length !== 9) {
652
+ throw new Error("Invalid data length for RequestUnits");
653
+ }
654
+ const units = data.readUInt32LE(1);
655
+ const additionalFee = data.readUInt32LE(5);
656
+ return { instructionType, units, additionalFee };
657
+ }
658
+ case "RequestHeapFrame": {
659
+ if (data.length !== 5) {
660
+ throw new Error("Invalid data length for RequestHeapFrame");
661
+ }
662
+ const bytes = data.readUInt32LE(1);
663
+ return { instructionType, bytes };
664
+ }
665
+ case "SetComputeUnitLimit": {
666
+ if (data.length !== 5) {
667
+ throw new Error("Invalid data length for SetComputeUnitLimit");
668
+ }
669
+ const units = data.readUInt32LE(1);
670
+ return { instructionType, units };
671
+ }
672
+ case "SetComputeUnitPrice": {
673
+ if (data.length !== 9) {
674
+ throw new Error("Invalid data length for SetComputeUnitPrice");
675
+ }
676
+ const microLamports = data.readBigUInt64LE(1);
677
+ return { instructionType, microLamports: microLamports.toString() };
678
+ }
679
+ case "SetLoadedAccountsDataSizeLimit": {
680
+ if (data.length !== 5) {
681
+ throw new Error("Invalid data length for SetLoadedAccountsDataSizeLimit");
682
+ }
683
+ const accountDataSizeLimit = data.readUInt32LE(1);
684
+ return { instructionType, accountDataSizeLimit };
685
+ }
686
+ default:
687
+ throw new Error("Unknown ComputeBudget instruction type.");
688
+ }
689
+ }
690
+ var DEFAULT_COMPUTE_BUDGET_IX = 2e5;
691
+ function getComputeBudgetUnits(tx) {
692
+ let instructions = [];
693
+ if (isV0Tx(tx)) {
694
+ const addressLookupTableAccounts = tx.addressLookupTables ?? [];
695
+ const message = decompileV0Transaction(tx, addressLookupTableAccounts);
696
+ instructions = message.instructions;
697
+ } else {
698
+ instructions = tx.instructions;
699
+ }
700
+ const computeBudgetIxs = instructions.filter((ix) => ix.programId.equals(import_web36.ComputeBudgetProgram.programId));
701
+ if (computeBudgetIxs.length === 0) {
702
+ return Math.min(instructions.length * DEFAULT_COMPUTE_BUDGET_IX, 14e5);
703
+ }
704
+ const decoded = computeBudgetIxs.map((ix) => decodeComputeBudgetInstruction(ix));
705
+ const limit = decoded.find((ix) => ix.instructionType === "SetComputeUnitLimit");
706
+ return limit?.units ?? instructions.length * DEFAULT_COMPUTE_BUDGET_IX;
707
+ }
708
+ var uiToMicroLamports = (ui, limitCU = 14e5) => {
709
+ const priorityFeeMicroLamports = ui * import_web36.LAMPORTS_PER_SOL * 1e6;
710
+ return priorityFeeMicroLamports / limitCU;
711
+ };
712
+ var microLamportsToUi = (microLamports, limitCU = 14e5) => {
713
+ const priorityFeeMicroLamports = microLamports * limitCU;
714
+ const priorityFeeUi = priorityFeeMicroLamports / (import_web36.LAMPORTS_PER_SOL * 1e6);
715
+ return Math.trunc(priorityFeeUi * import_web36.LAMPORTS_PER_SOL) / import_web36.LAMPORTS_PER_SOL;
716
+ };
717
+ function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
718
+ const result = [];
719
+ let buffer = [];
720
+ function buildTx(mandatoryIxs2, extraIxs, opts2) {
721
+ const messageV0 = new import_web36.TransactionMessage({
722
+ payerKey: opts2.payerKey,
723
+ recentBlockhash: opts2.blockhash,
724
+ instructions: [...mandatoryIxs2, ...extraIxs]
725
+ }).compileToV0Message(opts2.luts);
726
+ return new import_web36.VersionedTransaction(messageV0);
727
+ }
728
+ for (const ix of ixs) {
729
+ const trial = buildTx(mandatoryIxs, [...buffer, ix], opts);
730
+ if (getTxSize(trial) <= MAX_TX_SIZE) {
731
+ buffer.push(ix);
732
+ } else {
733
+ if (buffer.length === 0) {
734
+ throw new Error("Single instruction too large to fit in a transaction");
735
+ }
736
+ const tx = buildTx(mandatoryIxs, buffer, opts);
737
+ result.push(tx);
738
+ buffer = [ix];
739
+ const solo = buildTx(mandatoryIxs, buffer, opts);
740
+ if (getTxSize(solo) > MAX_TX_SIZE) {
741
+ throw new Error("Single instruction too large to fit in a transaction");
742
+ }
743
+ }
744
+ }
745
+ if (buffer.length > 0) {
746
+ const tx = buildTx(mandatoryIxs, buffer, opts);
747
+ result.push(tx);
748
+ }
749
+ return result;
750
+ }
751
+
752
+ // src/common/priority.ts
753
+ var PriotitizationFeeLevels = /* @__PURE__ */ ((PriotitizationFeeLevels2) => {
754
+ PriotitizationFeeLevels2[PriotitizationFeeLevels2["LOW"] = 2500] = "LOW";
755
+ PriotitizationFeeLevels2[PriotitizationFeeLevels2["MEDIAN"] = 5e3] = "MEDIAN";
756
+ PriotitizationFeeLevels2[PriotitizationFeeLevels2["HIGH"] = 7500] = "HIGH";
757
+ PriotitizationFeeLevels2[PriotitizationFeeLevels2["MAX"] = 1e4] = "MAX";
758
+ return PriotitizationFeeLevels2;
759
+ })(PriotitizationFeeLevels || {});
760
+ var getCalculatedPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
761
+ const fees = await getRecentPrioritizationFeesByPercentile(connection, config, slotsToReturn);
762
+ const { min, max, sum } = fees.reduce(
763
+ (acc, fee) => ({
764
+ min: fee.prioritizationFee < acc.min.prioritizationFee ? fee : acc.min,
765
+ max: fee.prioritizationFee > acc.max.prioritizationFee ? fee : acc.max,
766
+ sum: acc.sum + fee.prioritizationFee
767
+ }),
768
+ { min: fees[0], max: fees[0], sum: 0 }
769
+ );
770
+ const mean = Math.ceil(sum / fees.length);
771
+ const sortedFees = [...fees].sort((a, b) => a.prioritizationFee - b.prioritizationFee);
772
+ const midIndex = Math.floor(fees.length / 2);
773
+ const median2 = fees.length % 2 === 0 ? Math.ceil((sortedFees[midIndex - 1].prioritizationFee + sortedFees[midIndex].prioritizationFee) / 2) : sortedFees[midIndex].prioritizationFee;
774
+ return {
775
+ min,
776
+ max,
777
+ mean,
778
+ median: median2
779
+ };
780
+ };
781
+ var getMinPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
782
+ const recentPrioritizationFees = await getRecentPrioritizationFeesByPercentile(connection, config, slotsToReturn);
783
+ const minPriorityFee = recentPrioritizationFees.reduce((min, current) => {
784
+ return current.prioritizationFee < min.prioritizationFee ? current : min;
785
+ });
786
+ return minPriorityFee.prioritizationFee;
787
+ };
788
+ var getMaxPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
789
+ const recentPrioritizationFees = await getRecentPrioritizationFeesByPercentile(connection, config, slotsToReturn);
790
+ const maxPriorityFee = recentPrioritizationFees.reduce((max, current) => {
791
+ return current.prioritizationFee > max.prioritizationFee ? current : max;
792
+ });
793
+ return maxPriorityFee.prioritizationFee;
794
+ };
795
+ var getMeanPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
796
+ const recentPrioritizationFees = await getRecentPrioritizationFeesByPercentile(connection, config, slotsToReturn);
797
+ const mean = Math.ceil(
798
+ recentPrioritizationFees.reduce((acc, fee) => acc + fee.prioritizationFee, 0) / recentPrioritizationFees.length
799
+ );
800
+ return mean;
801
+ };
802
+ var getMedianPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
803
+ const recentPrioritizationFees = await getRecentPrioritizationFeesByPercentile(connection, config, slotsToReturn);
804
+ recentPrioritizationFees.sort((a, b) => a.prioritizationFee - b.prioritizationFee);
805
+ const half = Math.floor(recentPrioritizationFees.length / 2);
806
+ if (recentPrioritizationFees.length % 2) {
807
+ return recentPrioritizationFees[half].prioritizationFee;
808
+ }
809
+ return Math.ceil(
810
+ (recentPrioritizationFees[half - 1].prioritizationFee + recentPrioritizationFees[half].prioritizationFee) / 2
811
+ );
812
+ };
813
+ var getRecentPrioritizationFeesFromRpc = async (config, rpcRequest) => {
814
+ const accounts = config?.lockedWritableAccounts?.map((key) => key.toBase58());
815
+ const args = accounts?.length ? [accounts] : [[]];
816
+ config.percentile && args.push({ percentile: config.percentile });
817
+ const response = await rpcRequest("getRecentPrioritizationFees", args);
818
+ return response;
819
+ };
820
+ var getRecentPrioritizationFeesByPercentile = async (connection, config, slotsToReturn) => {
821
+ const { fallback = true, lockedWritableAccounts = [] } = config || {};
822
+ const validSlotsToReturn = slotsToReturn && Number.isInteger(slotsToReturn) ? slotsToReturn : -1;
823
+ const promises = [];
824
+ let tritonRpcResponse;
825
+ let fallbackRpcResponse;
826
+ const rpcRequest = connection._rpcRequest;
827
+ promises.push(
828
+ getRecentPrioritizationFeesFromRpc(config, rpcRequest).then((result) => {
829
+ tritonRpcResponse = result;
830
+ })
831
+ );
832
+ if (fallback) {
833
+ promises.push(
834
+ getRecentPrioritizationFeesFromRpc({ lockedWritableAccounts }, rpcRequest).then((result) => {
835
+ fallbackRpcResponse = result;
836
+ })
837
+ );
838
+ }
839
+ await Promise.all(promises);
840
+ const tritonGRPFResponse = tritonRpcResponse;
841
+ const fallbackGRPFResponse = fallbackRpcResponse;
842
+ let recentPrioritizationFees = [];
843
+ if (tritonGRPFResponse?.result) {
844
+ recentPrioritizationFees = tritonGRPFResponse.result;
845
+ }
846
+ if (fallbackGRPFResponse?.result && !tritonGRPFResponse?.result) {
847
+ recentPrioritizationFees = fallbackGRPFResponse.result;
848
+ }
849
+ if (fallback && fallbackGRPFResponse.error) {
850
+ return fallbackGRPFResponse.error;
851
+ }
852
+ if (tritonGRPFResponse?.error) {
853
+ return tritonGRPFResponse.error;
854
+ }
855
+ recentPrioritizationFees.sort((a, b) => a.slot - b.slot);
856
+ if (validSlotsToReturn > 0) return recentPrioritizationFees.slice(0, validSlotsToReturn);
857
+ return recentPrioritizationFees;
858
+ };
859
+
860
+ // src/common/utils/accounting.utils.ts
861
+ var apyToApr = (apy, compoundingFrequency = HOURS_PER_YEAR) => ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;
862
+ var aprToApy = (apr, compoundingFrequency = HOURS_PER_YEAR, apyCap = 3) => Math.min((1 + apr / compoundingFrequency) ** compoundingFrequency - 1, apyCap);
863
+ function calculateInterestFromApy(principal, durationInYears, apy) {
864
+ return principal * apy * durationInYears;
865
+ }
866
+ function calculateApyFromInterest(principal, durationInYears, interest) {
867
+ return interest / (principal * durationInYears);
868
+ }
869
+
870
+ // src/common/utils/conversion.utils.ts
871
+ var import_bignumber2 = __toESM(require("bignumber.js"), 1);
872
+ var import_bn = __toESM(require("bn.js"), 1);
873
+ var import_decimal = require("decimal.js");
874
+ var I80F48_FRACTIONAL_BYTES = 6;
875
+ var I80F48_TOTAL_BYTES = 16;
876
+ var I80F48_DIVISOR = new import_decimal.Decimal(2).pow(8 * I80F48_FRACTIONAL_BYTES);
877
+ function wrappedI80F48toBigNumber(wrapped) {
878
+ const bytesLE = wrapped.value;
879
+ if (bytesLE.length !== I80F48_TOTAL_BYTES) {
880
+ throw new Error(`Expected a ${I80F48_TOTAL_BYTES}-byte buffer`);
881
+ }
882
+ let bytesBE = bytesLE.slice();
883
+ bytesBE.reverse();
884
+ let signChar = "";
885
+ const msb = bytesBE[0];
886
+ if (msb & 128) {
887
+ signChar = "-";
888
+ bytesBE = bytesBE.map((v) => ~v & 255);
889
+ }
890
+ const hex = `${signChar}0x${bytesBE.map((v) => v.toString(16).padStart(2, "0")).join("")}`;
891
+ const decoded = new import_decimal.Decimal(hex).dividedBy(I80F48_DIVISOR);
892
+ return new import_bignumber2.default(decoded.toString());
893
+ }
894
+ function bigNumberToWrappedI80F48(value) {
895
+ let decimalValue = new import_decimal.Decimal(value.toString());
896
+ const isNegative = decimalValue.isNegative();
897
+ decimalValue = decimalValue.times(I80F48_DIVISOR);
898
+ let wrappedValue = new import_bn.default(decimalValue.round().toFixed()).toArray();
899
+ if (wrappedValue.length < I80F48_TOTAL_BYTES) {
900
+ const padding = Array(I80F48_TOTAL_BYTES - wrappedValue.length).fill(0);
901
+ wrappedValue.unshift(...padding);
902
+ }
903
+ if (isNegative) {
904
+ wrappedValue[wrappedValue.length - 1] |= 128;
905
+ wrappedValue = wrappedValue.map((v) => ~v & 255);
906
+ }
907
+ wrappedValue.reverse();
908
+ return { value: wrappedValue };
909
+ }
910
+ function toNumber(amount) {
911
+ let amt;
912
+ if (typeof amount === "number") {
913
+ amt = amount;
914
+ } else if (typeof amount === "string") {
915
+ amt = Number(amount);
916
+ } else {
917
+ amt = amount.toNumber();
918
+ }
919
+ return amt;
920
+ }
921
+ function toBigNumber(amount) {
922
+ let amt;
923
+ if (amount instanceof import_bignumber2.default) {
924
+ amt = amount;
925
+ } else {
926
+ amt = new import_bignumber2.default(amount.toString());
927
+ }
928
+ return amt;
929
+ }
930
+ function uiToNative(amount, decimals) {
931
+ const amt = toBigNumber(amount);
932
+ return new import_bn.default(amt.times(10 ** decimals).toFixed(0, import_bignumber2.default.ROUND_FLOOR));
933
+ }
934
+ function uiToNativeBigNumber(amount, decimals) {
935
+ const amt = toBigNumber(amount);
936
+ return amt.times(10 ** decimals);
937
+ }
938
+ function nativeToUi(amount, decimals) {
939
+ const amt = toBigNumber(amount);
940
+ return amt.div(10 ** decimals).toNumber();
941
+ }
942
+ function shortenAddress(pubkey, chars = 4) {
943
+ const pubkeyStr = pubkey.toString();
944
+ return `${pubkeyStr.slice(0, chars)}...${pubkeyStr.slice(-chars)}`;
945
+ }
946
+ function bpsToPercentile(bps) {
947
+ return bps / 1e4;
948
+ }
949
+ var composeRemainingAccounts = (banksAndOracles) => {
950
+ banksAndOracles.sort((a, b) => {
951
+ const A = a[0].toBytes();
952
+ const B = b[0].toBytes();
953
+ for (let i = 0; i < 32; i++) {
954
+ if (A[i] !== B[i]) {
955
+ return B[i] - A[i];
956
+ }
957
+ }
958
+ return 0;
959
+ });
960
+ return banksAndOracles.flat();
961
+ };
962
+
963
+ // src/common/utils/formatters.utils.ts
964
+ var import_numeral = __toESM(require("numeral"), 1);
965
+ var CustomNumberFormat = class extends Intl.NumberFormat {
966
+ format(value) {
967
+ if (value === 0) {
968
+ return "-";
969
+ } else {
970
+ return super.format(value);
971
+ }
972
+ }
973
+ };
974
+ var groupedNumberFormatter = new CustomNumberFormat("en-US", {
975
+ useGrouping: true,
976
+ minimumFractionDigits: 0,
977
+ maximumFractionDigits: 2
978
+ });
979
+ var numeralFormatter = (value) => {
980
+ if (value < 0.01) {
981
+ return "0";
982
+ } else {
983
+ return (0, import_numeral.default)(value).format("0.00a");
984
+ }
985
+ };
986
+ var dynamicNumeralFormatter = (value, options = {}) => {
987
+ const {
988
+ minDisplay = 1e-5,
989
+ // Default minDisplay for backward compatibility
990
+ maxDisplay = 1e4,
991
+ // Default maxDisplay for backward compatibility
992
+ tokenPrice,
993
+ logging = false,
994
+ ignoreMinDisplay = false,
995
+ // New flag to control ignoring minDisplay
996
+ forceDecimals
997
+ } = options;
998
+ if (value === 0 || Number.isNaN(value)) return "0";
999
+ const absValue = Math.abs(value);
1000
+ if (logging) {
1001
+ console.log({
1002
+ value,
1003
+ minDisplay,
1004
+ maxDisplay,
1005
+ tokenPrice,
1006
+ ignoreMinDisplay,
1007
+ absValue
1008
+ });
1009
+ }
1010
+ if (!ignoreMinDisplay && absValue < minDisplay) {
1011
+ return `<${minDisplay}`;
1012
+ }
1013
+ if (absValue > maxDisplay) {
1014
+ return (0, import_numeral.default)(value).format(forceDecimals ? "0,0.00a" : "0,0.[00]a");
1015
+ }
1016
+ if (!ignoreMinDisplay && Math.abs(value) >= 0.01) {
1017
+ return (0, import_numeral.default)(value).format(forceDecimals && Math.abs(value) > 0.99 ? "0,0.00a" : "0,0.[0000]a");
1018
+ }
1019
+ if (ignoreMinDisplay) {
1020
+ const decimalPart = absValue - Math.floor(absValue);
1021
+ const decimalPlaces = decimalPart > 0 ? 3 : 0;
1022
+ if (absValue >= 1) {
1023
+ return value.toFixed(decimalPlaces).replace(/\.?0+$/, "");
1024
+ } else {
1025
+ const exponent = Math.floor(Math.log10(absValue));
1026
+ const significantDecimals = Math.max(3, 2 - exponent);
1027
+ return value.toFixed(significantDecimals).replace(/\.?0+$/, "");
1028
+ }
1029
+ }
1030
+ if (Math.abs(value) >= minDisplay) {
1031
+ const decimalPlaces = Math.max(0, Math.ceil(-Math.log10(minDisplay)));
1032
+ return (0, import_numeral.default)(value).format(`0,0.[${"0".repeat(decimalPlaces)}]`);
1033
+ }
1034
+ if (tokenPrice) {
1035
+ const smallestUnit = minDisplay / tokenPrice;
1036
+ const significantDecimals = Math.max(3, Math.ceil(-Math.log10(smallestUnit)));
1037
+ return value.toFixed(significantDecimals).replace(/\.?0+$/, "");
1038
+ }
1039
+ return "0";
1040
+ };
1041
+ var groupedNumberFormatterDyn = new Intl.NumberFormat("en-US", {
1042
+ useGrouping: true,
1043
+ minimumFractionDigits: 0,
1044
+ maximumFractionDigits: 2
1045
+ });
1046
+ var usdFormatter = new Intl.NumberFormat("en-US", {
1047
+ style: "currency",
1048
+ currency: "USD",
1049
+ minimumFractionDigits: 2,
1050
+ maximumFractionDigits: 2,
1051
+ signDisplay: "auto"
1052
+ });
1053
+ var usdFormatterDyn = new Intl.NumberFormat("en-US", {
1054
+ style: "currency",
1055
+ currency: "USD",
1056
+ minimumFractionDigits: 0,
1057
+ maximumFractionDigits: 2,
1058
+ signDisplay: "auto"
1059
+ });
1060
+ var percentFormatter = new Intl.NumberFormat("en-US", {
1061
+ style: "percent",
1062
+ minimumFractionDigits: 2,
1063
+ maximumFractionDigits: 2
1064
+ });
1065
+ var percentFormatterDyn = new Intl.NumberFormat("en-US", {
1066
+ style: "percent",
1067
+ minimumFractionDigits: 0,
1068
+ maximumFractionDigits: 2
1069
+ });
1070
+ var percentFormatterMod = (value, opts = { minFractionDigits: 2, maxFractionDigits: 2 }) => {
1071
+ const percentFormatter2 = new Intl.NumberFormat("en-US", {
1072
+ style: "percent",
1073
+ minimumFractionDigits: opts.minFractionDigits,
1074
+ maximumFractionDigits: opts.maxFractionDigits
1075
+ });
1076
+ if (value === 0) {
1077
+ return "0%";
1078
+ } else {
1079
+ return percentFormatter2.format(value);
1080
+ }
1081
+ };
1082
+ var clampedNumeralFormatter = (value) => {
1083
+ if (value === 0) {
1084
+ return "0";
1085
+ } else if (value < 0.01) {
1086
+ return "< 0.01";
1087
+ } else {
1088
+ return (0, import_numeral.default)(value).format("0.00a");
1089
+ }
1090
+ };
1091
+ var tokenPriceFormatter = (price, style = "currency") => {
1092
+ if (price === 0) {
1093
+ return 0;
1094
+ }
1095
+ const reformatNum = Number(price.toFixed(20));
1096
+ if (price === 0) {
1097
+ return 0;
1098
+ }
1099
+ if (reformatNum < 1e-8) {
1100
+ return price.toExponential(2);
1101
+ }
1102
+ const { minFractionDigits, maxFractionDigits } = reformatNum > 1 ? { minFractionDigits: 2, maxFractionDigits: 2 } : reformatNum > 1e-6 ? { minFractionDigits: 2, maxFractionDigits: 7 } : { minFractionDigits: 7, maxFractionDigits: 10 };
1103
+ const formatter = new Intl.NumberFormat("en-US", {
1104
+ style,
1105
+ currency: "USD",
1106
+ minimumFractionDigits: minFractionDigits,
1107
+ maximumFractionDigits: maxFractionDigits,
1108
+ signDisplay: "auto"
1109
+ });
1110
+ return formatter.format(price);
1111
+ };
1112
+
1113
+ // src/common/bank-metadata.ts
1114
+ var import_zod = require("zod");
1115
+ var bankExtendedMetadataOverrideSchema = import_zod.z.object({
1116
+ name: import_zod.z.string().optional(),
1117
+ symbol: import_zod.z.string().optional(),
1118
+ logoURI: import_zod.z.string().url().optional(),
1119
+ // TODO)) [later] remove these if not used anywhere
1120
+ address: import_zod.z.string().optional(),
1121
+ mint: import_zod.z.string().optional(),
1122
+ // TODO)) added in new IDL version
1123
+ validatorVoteAccount: import_zod.z.string().optional()
1124
+ });
1125
+ var parseBanksMetadataOverride = (data) => {
1126
+ return import_zod.z.record(import_zod.z.string(), bankExtendedMetadataOverrideSchema).parse(data);
1127
+ };
1128
+ var fetchBanksExtendedMetadata = async ({
1129
+ mintsWithOwner,
1130
+ metadataService,
1131
+ logger,
1132
+ overrideBanksMetadata
1133
+ }) => {
1134
+ const metas = await metadataService.forMints(mintsWithOwner.map(({ mint }) => mint));
1135
+ const results = await Promise.all(
1136
+ mintsWithOwner.map(async ({ mint }) => {
1137
+ const mintAddress = mint.toBase58();
1138
+ const tokenMeta = metas[mintAddress];
1139
+ if (!tokenMeta) {
1140
+ logger.warn({ mintStr: mintAddress }, "fetched metadata was null");
1141
+ if (!overrideBanksMetadata) {
1142
+ return null;
1143
+ }
1144
+ const overrideMetadata2 = Object.values(overrideBanksMetadata).find((m) => m?.mint === mintAddress);
1145
+ if (!overrideMetadata2) {
1146
+ return null;
1147
+ }
1148
+ const { name: name2, symbol: symbol2, logoURI } = overrideMetadata2;
1149
+ if (name2 && symbol2) {
1150
+ return {
1151
+ mint: mintAddress,
1152
+ name: name2,
1153
+ symbol: symbol2,
1154
+ logoURI,
1155
+ uri: "",
1156
+ additionalMetadata: []
1157
+ };
1158
+ }
1159
+ logger.warn(
1160
+ {
1161
+ overrideMetadata: overrideMetadata2,
1162
+ mint: mintAddress
1163
+ },
1164
+ "override metadata exists but is missing required fields: name, symbol, mint"
1165
+ );
1166
+ return null;
1167
+ }
1168
+ const { name, symbol, image, uri } = tokenMeta;
1169
+ const overrideMetadata = overrideBanksMetadata?.[symbol];
1170
+ return {
1171
+ mint: mintAddress,
1172
+ name: overrideMetadata?.name ?? name,
1173
+ symbol: overrideMetadata?.symbol ?? symbol,
1174
+ logoURI: overrideMetadata?.logoURI ?? image,
1175
+ uri: uri ?? "",
1176
+ additionalMetadata: []
1177
+ };
1178
+ })
1179
+ );
1180
+ const metadataMap = /* @__PURE__ */ new Map();
1181
+ for (const result of results) {
1182
+ if (!result) continue;
1183
+ metadataMap.set(result.mint, result);
1184
+ }
1185
+ return metadataMap;
1186
+ };
1187
+ // Annotate the CommonJS export names for ESM import in node:
1188
+ 0 && (module.exports = {
1189
+ CustomNumberFormat,
1190
+ NodeWallet,
1191
+ PriotitizationFeeLevels,
1192
+ TransactionArenaKeyMap,
1193
+ TransactionConfigMap,
1194
+ TransactionType,
1195
+ addTransactionMetadata,
1196
+ aprToApy,
1197
+ apyToApr,
1198
+ bankExtendedMetadataOverrideSchema,
1199
+ bigNumberToWrappedI80F48,
1200
+ bpsToPercentile,
1201
+ calculateApyFromInterest,
1202
+ calculateInterestFromApy,
1203
+ ceil,
1204
+ chunkedGetRawMultipleAccountInfoOrdered,
1205
+ chunkedGetRawMultipleAccountInfoOrderedWithNulls,
1206
+ chunkedGetRawMultipleAccountInfos,
1207
+ chunks,
1208
+ clampedNumeralFormatter,
1209
+ compareInstructions,
1210
+ composeRemainingAccounts,
1211
+ decodeComputeBudgetInstruction,
1212
+ decodeInstruction,
1213
+ decompileV0Transaction,
1214
+ dynamicNumeralFormatter,
1215
+ fetchBanksExtendedMetadata,
1216
+ floor,
1217
+ getAccountKeys,
1218
+ getCalculatedPrioritizationFeeByPercentile,
1219
+ getComputeBudgetUnits,
1220
+ getMaxPrioritizationFeeByPercentile,
1221
+ getMeanPrioritizationFeeByPercentile,
1222
+ getMedianPrioritizationFeeByPercentile,
1223
+ getMinPrioritizationFeeByPercentile,
1224
+ getRecentPrioritizationFeesByPercentile,
1225
+ getTxSize,
1226
+ getValueInsensitive,
1227
+ groupedNumberFormatter,
1228
+ groupedNumberFormatterDyn,
1229
+ isV0Tx,
1230
+ legacyTxToV0Tx,
1231
+ median,
1232
+ microLamportsToUi,
1233
+ nativeToUi,
1234
+ numeralFormatter,
1235
+ parseBanksMetadataOverride,
1236
+ percentFormatter,
1237
+ percentFormatterDyn,
1238
+ percentFormatterMod,
1239
+ replaceV0TxBlockhash,
1240
+ replaceV0TxInstructions,
1241
+ setTimeoutPromise,
1242
+ shortenAddress,
1243
+ sleep,
1244
+ splitInstructionsToFitTransactions,
1245
+ toBigNumber,
1246
+ toNumber,
1247
+ tokenPriceFormatter,
1248
+ uiToMicroLamports,
1249
+ uiToNative,
1250
+ uiToNativeBigNumber,
1251
+ updateV0Tx,
1252
+ usdFormatter,
1253
+ usdFormatterDyn,
1254
+ wrappedI80F48toBigNumber
1255
+ });