@0dotxyz/p0-ts-sdk 2.10.0-alpha.0 → 2.10.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.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { PublicKey, SolanaJSONRPCError, ComputeBudgetProgram, SystemProgram, TransactionMessage, VersionedTransaction, AddressLookupTableAccount, Transaction, TransactionInstruction, Keypair, StakeProgram, LAMPORTS_PER_SOL, StakeAuthorizationLayout, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RENT_PUBKEY, STAKE_CONFIG_ID as STAKE_CONFIG_ID$1 } from '@solana/web3.js';
2
2
  import { object, string, enums, array, assert } from 'superstruct';
3
3
  import BigNumber3, { BigNumber } from 'bignumber.js';
4
+ import { sha256 } from '@noble/hashes/sha2';
4
5
  import BN8, { BN } from 'bn.js';
5
6
  import Decimal3, { Decimal } from 'decimal.js';
6
7
  import { BorshAccountsCoder, BorshCoder, BorshInstructionCoder, AnchorProvider, Program } from '@coral-xyz/anchor';
@@ -81,6 +82,95 @@ function getConfig(environment = "production", overrides) {
81
82
  ...getProject0Config(environment, overrides)
82
83
  };
83
84
  }
85
+ var PYTH_PUSH_ORACLE_ID = new PublicKey("pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT");
86
+ var PYTH_SPONSORED_SHARD_ID = 0;
87
+ var MARGINFI_SPONSORED_SHARD_ID = 3301;
88
+ var DEFAULT_ORACLE_MAX_AGE = 60;
89
+ var ZERO_ORACLE_KEY = "DMhGWtLAKE5d56WdyHQxqeFncwUeqMEnuC2RvvZfbuur";
90
+ var PYTH_PRICE_CONF_INTERVALS = new BigNumber3(2.12);
91
+ var MAX_CONFIDENCE_INTERVAL_RATIO = new BigNumber3(0.05);
92
+ var DISABLED_FLAG = 1 << 0;
93
+ var FLASHLOAN_ENABLED_FLAG = 1 << 2;
94
+ var TRANSFER_ACCOUNT_AUTHORITY_FLAG = 1 << 3;
95
+ var STAKED_ORACLE_DISABLED_FLAG = 1 << 9;
96
+ var STAKED_ORACLE_USES_ONRAMP_FLAG = 1 << 10;
97
+ var PREMIUM_ACTIVE_FLAG = 1 << 13;
98
+ var KAMINO_MARKET_EMERGENCY_FLAG = 1 << 14;
99
+ var MAX_COSTLY_POSITIONS = 4;
100
+ var MARGINFI_PROGRAM = new PublicKey("MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA");
101
+ var MARGINFI_PROGRAM_STAGING = new PublicKey(
102
+ "stag8sTKds2h4KzjUw3zKTsxbqvT4XKHdaR9X9E6Rct"
103
+ );
104
+ var MARGINFI_PROGRAM_STAGING_ALT = new PublicKey(
105
+ "5UDghkpgW1HfYSrmEj2iAApHShqU44H6PKTAar9LL9bY"
106
+ );
107
+ var ADDRESS_LOOKUP_TABLE_FOR_GROUP = {
108
+ "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
109
+ new PublicKey("8dk6oxKXC4iMLMa8Q4AVtPJPkEfitZuHSB4JqUsLLV2R"),
110
+ new PublicKey("43xneYSZYLFkaksMcfBMJANibRiKsWgxkPbsrmcYjqF6"),
111
+ new PublicKey("67cS6yqmAy5D1QRJwAXcFv9GLvrMbe88GFGDJcntkL7C")
112
+ ],
113
+ // Main pool — general group
114
+ FCPfpHA69EbS8f9KKSreTRkXbzFpunsKuYf5qNmnJjpo: [
115
+ new PublicKey("9p1CwvXMYNEY9CqSwuWySVXsG37NGb36nua94ea5KsiQ")
116
+ ],
117
+ // staging
118
+ Diu1q9gniR1qR4Daaej3rcHd6949HMmxLGsnQ94Z3rLz: [
119
+ new PublicKey("5ggm1hB8yPF5dKWJ3W7n1txztDrU4zf2RQk3TLrFvvRn")
120
+ ]
121
+ // staging
122
+ };
123
+ var ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE = {
124
+ "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
125
+ new PublicKey("FhVyrX2gfHmxKHq8wWWBJB3ZvHZcAQ6UAcjWxUyfyXuE"),
126
+ new PublicKey("GYEJ3BcgwHfNSL2BAuDcth3KKKt9eiK14EHwLCjU9Eoo")
127
+ ]
128
+ // Main pool — native-stake group
129
+ };
130
+ var ADDRESS_LOOKUP_TABLE_FOR_SWAP = new PublicKey(
131
+ "5X5gDr8Bp9BpizTeZ3VJhxMw4z3q2rwoexJvwttmATs5"
132
+ );
133
+ var JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = 5;
134
+ var JUPITER_V6_PROGRAM = new PublicKey(
135
+ "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"
136
+ );
137
+ var SINGLE_POOL_PROGRAM_ID = new PublicKey(
138
+ "SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE"
139
+ );
140
+ var STAKE_PROGRAM_ID = new PublicKey(
141
+ "Stake11111111111111111111111111111111111111"
142
+ );
143
+ var MPL_METADATA_PROGRAM_ID = new PublicKey(
144
+ "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
145
+ );
146
+ var SYSTEM_PROGRAM_ID = new PublicKey("11111111111111111111111111111111");
147
+ var SYSVAR_RENT_ID = new PublicKey(
148
+ "SysvarRent111111111111111111111111111111111"
149
+ );
150
+ var SYSVAR_CLOCK_ID = new PublicKey(
151
+ "SysvarC1ock11111111111111111111111111111111"
152
+ );
153
+ var SYSVAR_STAKE_HISTORY_ID = new PublicKey(
154
+ "SysvarStakeHistory1111111111111111111111111"
155
+ );
156
+ var STAKE_CONFIG_ID = new PublicKey(
157
+ "StakeConfig11111111111111111111111111111111"
158
+ );
159
+
160
+ // src/constants/misc.consts.ts
161
+ var HOURS_PER_YEAR = 365.25 * 24;
162
+ var MAX_U64 = BigInt("18446744073709551615").toString();
163
+
164
+ // src/constants/transaction.consts.ts
165
+ var MAX_TX_SIZE = 1232;
166
+ var MAX_ACCOUNT_LOCKS = 64;
167
+ var BUNDLE_TX_SIZE = 81;
168
+ var PRIORITY_TX_SIZE = 44;
169
+ var WSOL_MINT = new PublicKey("So11111111111111111111111111111111111111112");
170
+ var LST_MINT = new PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
171
+ var USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
172
+ var USDT_MINT = new PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
173
+ var USDC_DECIMALS = 6;
84
174
 
85
175
  // src/errors/transaction-building.errors.ts
86
176
  var TransactionBuildingErrorCode = /* @__PURE__ */ ((TransactionBuildingErrorCode2) => {
@@ -96,6 +186,10 @@ var TransactionBuildingErrorCode = /* @__PURE__ */ ((TransactionBuildingErrorCod
96
186
  TransactionBuildingErrorCode2["TRANSFER_POSITIONS_UNSUPPORTED_BANK"] = "TRANSFER_POSITIONS_UNSUPPORTED_BANK";
97
187
  TransactionBuildingErrorCode2["TRANSFER_POSITIONS_UNSPLITTABLE"] = "TRANSFER_POSITIONS_UNSPLITTABLE";
98
188
  TransactionBuildingErrorCode2["BRIDGE_CONFLICT"] = "BRIDGE_CONFLICT";
189
+ TransactionBuildingErrorCode2["ORDER_INVALID_TRIGGER"] = "ORDER_INVALID_TRIGGER";
190
+ TransactionBuildingErrorCode2["ORDER_INVALID_SLIPPAGE"] = "ORDER_INVALID_SLIPPAGE";
191
+ TransactionBuildingErrorCode2["COSTLY_POSITION_LIMIT_EXCEEDED"] = "COSTLY_POSITION_LIMIT_EXCEEDED";
192
+ TransactionBuildingErrorCode2["ACCOUNT_DISABLED"] = "ACCOUNT_DISABLED";
99
193
  return TransactionBuildingErrorCode2;
100
194
  })(TransactionBuildingErrorCode || {});
101
195
  var TransactionBuildingError = class _TransactionBuildingError extends Error {
@@ -229,6 +323,49 @@ var TransactionBuildingError = class _TransactionBuildingError extends Error {
229
323
  { conflictingBanks, bridgeTokenSide }
230
324
  );
231
325
  }
326
+ /**
327
+ * The order trigger can't be placed: no threshold set, a threshold not above 0, or take-profit
328
+ * at or below stop-loss (the program rejects all three with `InvalidOrderTakeProfitOrStopLoss`).
329
+ */
330
+ static orderInvalidTrigger(reason, takeProfitUsd, stopLossUsd) {
331
+ return new _TransactionBuildingError(
332
+ "ORDER_INVALID_TRIGGER" /* ORDER_INVALID_TRIGGER */,
333
+ `Invalid order trigger: ${reason}`,
334
+ { reason, takeProfitUsd, stopLossUsd }
335
+ );
336
+ }
337
+ /**
338
+ * The action would open an integration (Kamino, Drift, Solend, JupLend) or staked position
339
+ * beyond the per-account limit on such positions.
340
+ */
341
+ static costlyPositionLimitExceeded(bankAddress) {
342
+ return new _TransactionBuildingError(
343
+ "COSTLY_POSITION_LIMIT_EXCEEDED" /* COSTLY_POSITION_LIMIT_EXCEEDED */,
344
+ `An account can hold at most ${MAX_COSTLY_POSITIONS} integration and staked positions`,
345
+ { bankAddress, limit: MAX_COSTLY_POSITIONS }
346
+ );
347
+ }
348
+ /**
349
+ * The order's max slippage is outside (0, cap]. The program accepts 0, but a keeper can't
350
+ * execute an order that allows no slippage, so the SDK rejects it.
351
+ */
352
+ static orderInvalidSlippage(maxSlippagePercent, maxAllowedPercent) {
353
+ return new _TransactionBuildingError(
354
+ "ORDER_INVALID_SLIPPAGE" /* ORDER_INVALID_SLIPPAGE */,
355
+ `Max slippage percent must be in (0, ${maxAllowedPercent}], got ${maxSlippagePercent}`,
356
+ { maxSlippagePercent, maxAllowedPercent }
357
+ );
358
+ }
359
+ /**
360
+ * The marginfi account is disabled (e.g. already transferred to a new account), so it can't act.
361
+ */
362
+ static accountDisabled(accountAddress) {
363
+ return new _TransactionBuildingError(
364
+ "ACCOUNT_DISABLED" /* ACCOUNT_DISABLED */,
365
+ `Account ${accountAddress} is disabled`,
366
+ { accountAddress }
367
+ );
368
+ }
232
369
  /**
233
370
  * Generic escape hatch for custom errors
234
371
  */
@@ -258,6 +395,7 @@ var PDA_BANK_FEE_STATE_SEED = Buffer.from("feestate");
258
395
  var PDA_BANK_EMISSIONS_AUTH_SEED = Buffer.from("emissions_auth_seed");
259
396
  var PDA_BANK_EMISSIONS_VAULT_SEED = Buffer.from("emissions_vault");
260
397
  var PDA_MARGINFI_ACCOUNT_SEED = Buffer.from("marginfi_account");
398
+ var PDA_ORDER_SEED = Buffer.from("order");
261
399
  var PDA_REBALANCE_FEE_POOL_SEED = Buffer.from("rebalance_fee_pool");
262
400
  function deriveBankLiquidityVaultAuthority(programId, bank) {
263
401
  return PublicKey.findProgramAddressSync(
@@ -323,99 +461,20 @@ function deriveMarginfiAccount(programId, group, authority, accountIndex, thirdP
323
461
  programId
324
462
  );
325
463
  }
464
+ function deriveOrderPda(programId, marginfiAccount, bankKeys) {
465
+ const sortedBankKeys = bankKeys.map((key) => key.toBuffer()).sort(Buffer.compare);
466
+ const bankKeysHash = Buffer.from(sha256(Buffer.concat(sortedBankKeys)));
467
+ return PublicKey.findProgramAddressSync(
468
+ [PDA_ORDER_SEED, marginfiAccount.toBuffer(), bankKeysHash],
469
+ programId
470
+ );
471
+ }
326
472
  function deriveRebalanceFeePool(programId, marginfiAccount) {
327
473
  return PublicKey.findProgramAddressSync(
328
474
  [PDA_REBALANCE_FEE_POOL_SEED, marginfiAccount.toBuffer()],
329
475
  programId
330
476
  );
331
477
  }
332
- var PYTH_PUSH_ORACLE_ID = new PublicKey("pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT");
333
- var PYTH_SPONSORED_SHARD_ID = 0;
334
- var MARGINFI_SPONSORED_SHARD_ID = 3301;
335
- var DEFAULT_ORACLE_MAX_AGE = 60;
336
- var ZERO_ORACLE_KEY = "DMhGWtLAKE5d56WdyHQxqeFncwUeqMEnuC2RvvZfbuur";
337
- var PYTH_PRICE_CONF_INTERVALS = new BigNumber3(2.12);
338
- var MAX_CONFIDENCE_INTERVAL_RATIO = new BigNumber3(0.05);
339
- var DISABLED_FLAG = 1 << 0;
340
- var FLASHLOAN_ENABLED_FLAG = 1 << 2;
341
- var TRANSFER_ACCOUNT_AUTHORITY_FLAG = 1 << 3;
342
- var STAKED_ORACLE_DISABLED_FLAG = 1 << 9;
343
- var STAKED_ORACLE_USES_ONRAMP_FLAG = 1 << 10;
344
- var PREMIUM_ACTIVE_FLAG = 1 << 13;
345
- var MARGINFI_PROGRAM = new PublicKey("MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA");
346
- var MARGINFI_PROGRAM_STAGING = new PublicKey(
347
- "stag8sTKds2h4KzjUw3zKTsxbqvT4XKHdaR9X9E6Rct"
348
- );
349
- var MARGINFI_PROGRAM_STAGING_ALT = new PublicKey(
350
- "5UDghkpgW1HfYSrmEj2iAApHShqU44H6PKTAar9LL9bY"
351
- );
352
- var ADDRESS_LOOKUP_TABLE_FOR_GROUP = {
353
- "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
354
- new PublicKey("8dk6oxKXC4iMLMa8Q4AVtPJPkEfitZuHSB4JqUsLLV2R"),
355
- new PublicKey("43xneYSZYLFkaksMcfBMJANibRiKsWgxkPbsrmcYjqF6"),
356
- new PublicKey("67cS6yqmAy5D1QRJwAXcFv9GLvrMbe88GFGDJcntkL7C")
357
- ],
358
- // Main pool — general group
359
- FCPfpHA69EbS8f9KKSreTRkXbzFpunsKuYf5qNmnJjpo: [
360
- new PublicKey("9p1CwvXMYNEY9CqSwuWySVXsG37NGb36nua94ea5KsiQ")
361
- ],
362
- // staging
363
- Diu1q9gniR1qR4Daaej3rcHd6949HMmxLGsnQ94Z3rLz: [
364
- new PublicKey("5ggm1hB8yPF5dKWJ3W7n1txztDrU4zf2RQk3TLrFvvRn")
365
- ]
366
- // staging
367
- };
368
- var ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE = {
369
- "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
370
- new PublicKey("FhVyrX2gfHmxKHq8wWWBJB3ZvHZcAQ6UAcjWxUyfyXuE"),
371
- new PublicKey("GYEJ3BcgwHfNSL2BAuDcth3KKKt9eiK14EHwLCjU9Eoo")
372
- ]
373
- // Main pool — native-stake group
374
- };
375
- var ADDRESS_LOOKUP_TABLE_FOR_SWAP = new PublicKey(
376
- "5X5gDr8Bp9BpizTeZ3VJhxMw4z3q2rwoexJvwttmATs5"
377
- );
378
- var JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = 5;
379
- var JUPITER_V6_PROGRAM = new PublicKey(
380
- "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"
381
- );
382
- var SINGLE_POOL_PROGRAM_ID = new PublicKey(
383
- "SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE"
384
- );
385
- var STAKE_PROGRAM_ID = new PublicKey(
386
- "Stake11111111111111111111111111111111111111"
387
- );
388
- var MPL_METADATA_PROGRAM_ID = new PublicKey(
389
- "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
390
- );
391
- var SYSTEM_PROGRAM_ID = new PublicKey("11111111111111111111111111111111");
392
- var SYSVAR_RENT_ID = new PublicKey(
393
- "SysvarRent111111111111111111111111111111111"
394
- );
395
- var SYSVAR_CLOCK_ID = new PublicKey(
396
- "SysvarC1ock11111111111111111111111111111111"
397
- );
398
- var SYSVAR_STAKE_HISTORY_ID = new PublicKey(
399
- "SysvarStakeHistory1111111111111111111111111"
400
- );
401
- var STAKE_CONFIG_ID = new PublicKey(
402
- "StakeConfig11111111111111111111111111111111"
403
- );
404
-
405
- // src/constants/misc.consts.ts
406
- var HOURS_PER_YEAR = 365.25 * 24;
407
- var MAX_U64 = BigInt("18446744073709551615").toString();
408
-
409
- // src/constants/transaction.consts.ts
410
- var MAX_TX_SIZE = 1232;
411
- var MAX_ACCOUNT_LOCKS = 64;
412
- var BUNDLE_TX_SIZE = 81;
413
- var PRIORITY_TX_SIZE = 44;
414
- var WSOL_MINT = new PublicKey("So11111111111111111111111111111111111111112");
415
- var LST_MINT = new PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
416
- var USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
417
- var USDT_MINT = new PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
418
- var USDC_DECIMALS = 6;
419
478
 
420
479
  // src/utils/accounting.utils.ts
421
480
  var apyToApr = (apy, compoundingFrequency = HOURS_PER_YEAR) => ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;
@@ -501,6 +560,17 @@ function shortenAddress(pubkey, chars = 4) {
501
560
  function bpsToPercentile(bps) {
502
561
  return bps / 1e4;
503
562
  }
563
+ var U32_MAX = 4294967295;
564
+ var MAX_ORDER_SLIPPAGE_PERCENT = 10;
565
+ function percentToMaxSlippageU32(percent) {
566
+ if (!(percent > 0) || percent > MAX_ORDER_SLIPPAGE_PERCENT) {
567
+ throw TransactionBuildingError.orderInvalidSlippage(percent, MAX_ORDER_SLIPPAGE_PERCENT);
568
+ }
569
+ return Math.floor(percent / 100 * U32_MAX);
570
+ }
571
+ function maxSlippageU32ToPercent(maxSlippage) {
572
+ return maxSlippage / U32_MAX * 100;
573
+ }
504
574
  var composeRemainingAccounts = (banksAndOracles) => {
505
575
  banksAndOracles.sort((a, b) => {
506
576
  const A = a[0].toBytes();
@@ -666,6 +736,155 @@ function makeBundleTipIx(feePayer, bundleTip = 1e5) {
666
736
  });
667
737
  return bundleTipInstruction;
668
738
  }
739
+ var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
740
+ TransactionType2["DEPOSIT"] = "DEPOSIT";
741
+ TransactionType2["WITHDRAW"] = "WITHDRAW";
742
+ TransactionType2["REPAY"] = "REPAY";
743
+ TransactionType2["BORROW"] = "BORROW";
744
+ TransactionType2["FLASHLOAN"] = "FLASHLOAN";
745
+ TransactionType2["LOOP"] = "LOOP";
746
+ TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
747
+ TransactionType2["LONG"] = "LONG";
748
+ TransactionType2["SHORT"] = "SHORT";
749
+ TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
750
+ TransactionType2["CREATE_ATA"] = "CREATE_ATA";
751
+ TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
752
+ TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
753
+ TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
754
+ TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
755
+ TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
756
+ TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
757
+ TransactionType2["CRANK"] = "CRANK";
758
+ TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
759
+ TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
760
+ TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
761
+ TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
762
+ TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
763
+ TransactionType2["VAULT_DEPOSIT"] = "VAULT_DEPOSIT";
764
+ TransactionType2["VAULT_WITHDRAW"] = "VAULT_WITHDRAW";
765
+ TransactionType2["VAULT_COMPLETE_WITHDRAWAL"] = "VAULT_COMPLETE_WITHDRAWAL";
766
+ TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
767
+ TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
768
+ TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
769
+ TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
770
+ TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
771
+ TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
772
+ TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
773
+ TransactionType2["PLACE_ORDER"] = "PLACE_ORDER";
774
+ TransactionType2["CLOSE_ORDER"] = "CLOSE_ORDER";
775
+ TransactionType2["UPDATE_ORDER"] = "UPDATE_ORDER";
776
+ TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
777
+ TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
778
+ TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
779
+ return TransactionType2;
780
+ })(TransactionType || {});
781
+ var TransactionConfigMap = {
782
+ // BASE LENDING ACTIONS
783
+ ["DEPOSIT" /* DEPOSIT */]: {
784
+ label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
785
+ },
786
+ ["WITHDRAW" /* WITHDRAW */]: {
787
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
788
+ },
789
+ ["REPAY" /* REPAY */]: {
790
+ label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
791
+ },
792
+ ["BORROW" /* BORROW */]: {
793
+ label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
794
+ },
795
+ // FLASHLOANS
796
+ ["FLASHLOAN" /* FLASHLOAN */]: { label: () => "Executing Flashloan" },
797
+ ["LOOP" /* LOOP */]: {
798
+ label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
799
+ },
800
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: {
801
+ label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
802
+ },
803
+ ["LONG" /* LONG */]: {
804
+ label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
805
+ },
806
+ ["SHORT" /* SHORT */]: {
807
+ label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
808
+ },
809
+ ["CRANK" /* CRANK */]: { label: () => "Updating latest prices" },
810
+ ["JUPITER_SWAP" /* JUPITER_SWAP */]: {
811
+ label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
812
+ },
813
+ // SETUP
814
+ ["CREATE_ACCOUNT" /* CREATE_ACCOUNT */]: { label: () => "Create marginfi account" },
815
+ ["CREATE_ATA" /* CREATE_ATA */]: { label: () => "Configure token account" },
816
+ // ACCOUNT MANAGEMENT
817
+ ["CLOSE_ACCOUNT" /* CLOSE_ACCOUNT */]: { label: () => "Close marginfi account" },
818
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: { label: () => "Close position" },
819
+ ["MOVE_POSITION_WITHDRAW" /* MOVE_POSITION_WITHDRAW */]: {
820
+ label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
821
+ },
822
+ ["MOVE_POSITION_DEPOSIT" /* MOVE_POSITION_DEPOSIT */]: {
823
+ label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
824
+ },
825
+ ["TRANSFER_AUTH" /* TRANSFER_AUTH */]: { label: () => "Authorize account transfer" },
826
+ // NATIVE STAKE ACTIONS
827
+ ["DEPOSIT_STAKE" /* DEPOSIT_STAKE */]: {
828
+ label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
829
+ },
830
+ ["WITHDRAW_STAKE" /* WITHDRAW_STAKE */]: {
831
+ label: () => "Authorize stake account"
832
+ },
833
+ ["INITIALIZE_STAKED_POOL" /* INITIALIZE_STAKED_POOL */]: { label: () => "Initialize stake pool" },
834
+ ["ADD_STAKED_BANK" /* ADD_STAKED_BANK */]: { label: () => "Create staked asset bank" },
835
+ ["MERGE_STAKE_ACCOUNTS" /* MERGE_STAKE_ACCOUNTS */]: { label: () => "Merge stake accounts" },
836
+ // GAMMA VAULT ACTIONS
837
+ ["VAULT_DEPOSIT" /* VAULT_DEPOSIT */]: {
838
+ label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token} into vault` : "Deposit into vault"
839
+ },
840
+ ["VAULT_WITHDRAW" /* VAULT_WITHDRAW */]: {
841
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token} from vault` : "Withdraw from vault"
842
+ },
843
+ ["VAULT_COMPLETE_WITHDRAWAL" /* VAULT_COMPLETE_WITHDRAWAL */]: {
844
+ label: () => "Claim vault withdrawal"
845
+ },
846
+ // LST (Liquid Staking Tokens)
847
+ ["STAKE_TO_STAKE" /* STAKE_TO_STAKE */]: { label: () => "Convert stake" },
848
+ ["MINT_LST_NATIVE" /* MINT_LST_NATIVE */]: { label: () => "Mint LST" },
849
+ ["SWAP_TO_SOL" /* SWAP_TO_SOL */]: {
850
+ label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
851
+ },
852
+ ["SOL_TO_LST" /* SOL_TO_LST */]: {
853
+ label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
854
+ },
855
+ ["UNSTAKE_LST" /* UNSTAKE_LST */]: {
856
+ label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST"
857
+ },
858
+ // EMISSIONS
859
+ ["WITHDRAW_EMISSIONS" /* WITHDRAW_EMISSIONS */]: { label: () => "Withdraw emissions" },
860
+ // LIQUIDATE
861
+ ["LIQUIDATE_ACCOUNT" /* LIQUIDATE_ACCOUNT */]: { label: () => "Liquidate account" },
862
+ // ORDERS (TP/SL)
863
+ ["PLACE_ORDER" /* PLACE_ORDER */]: {
864
+ label: ({ collateralToken, debtToken } = {}) => collateralToken && debtToken ? `Place TP/SL order on ${collateralToken}/${debtToken}` : "Place TP/SL order"
865
+ },
866
+ ["CLOSE_ORDER" /* CLOSE_ORDER */]: { label: () => "Close TP/SL order" },
867
+ ["UPDATE_ORDER" /* UPDATE_ORDER */]: {
868
+ label: ({ collateralToken, debtToken } = {}) => collateralToken && debtToken ? `Update TP/SL order on ${collateralToken}/${debtToken}` : "Update TP/SL order"
869
+ },
870
+ // BANK and GROUPS
871
+ ["CREATE_PERM_BANK" /* CREATE_PERM_BANK */]: { label: () => "Create permissionless bank" },
872
+ ["CREATE_GROUP" /* CREATE_GROUP */]: { label: () => "Create marginfi group" },
873
+ ["WITHDRAW_ALL" /* WITHDRAW_ALL */]: {
874
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
875
+ }
876
+ };
877
+ var TransactionArenaKeyMap = {
878
+ ["DEPOSIT" /* DEPOSIT */]: new PublicKey("ArenaDeposit1111111111111111111111111111111"),
879
+ ["WITHDRAW" /* WITHDRAW */]: new PublicKey("ArenaWithdraw111111111111111111111111111111"),
880
+ ["BORROW" /* BORROW */]: new PublicKey("ArenaBorrow11111111111111111111111111111111"),
881
+ ["REPAY" /* REPAY */]: new PublicKey("ArenaRepay111111111111111111111111111111111"),
882
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: new PublicKey("ArenaRepayCo11at111111111111111111111111111"),
883
+ ["LONG" /* LONG */]: new PublicKey("ArenaLong1111111111111111111111111111111111"),
884
+ ["SHORT" /* SHORT */]: new PublicKey("ArenaShort111111111111111111111111111111111"),
885
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: new PublicKey("ArenaC1ose111111111111111111111111111111111")
886
+ // Add more mappings if needed
887
+ };
669
888
  function decodeInstruction(idl, encoded) {
670
889
  const coder = new BorshInstructionCoder(idl);
671
890
  return coder.decode(encoded, "base58");
@@ -24942,10 +25161,24 @@ function countTxAccountLocks(tx) {
24942
25161
  );
24943
25162
  return message.staticAccountKeys.length + lookupKeys;
24944
25163
  }
25164
+ function fitsInOneTransaction(ixs, opts) {
25165
+ try {
25166
+ const tx = new VersionedTransaction(
25167
+ new TransactionMessage({
25168
+ payerKey: opts.payerKey,
25169
+ recentBlockhash: PublicKey.default.toBase58(),
25170
+ instructions: ixs
25171
+ }).compileToV0Message(opts.luts)
25172
+ );
25173
+ if (getTxSize(tx) > MAX_TX_SIZE - (opts.sizeMargin ?? 0)) return false;
25174
+ return opts.maxAccountLocks === void 0 || countTxAccountLocks(tx) <= opts.maxAccountLocks;
25175
+ } catch {
25176
+ return false;
25177
+ }
25178
+ }
24945
25179
  function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
24946
25180
  const result = [];
24947
25181
  let buffer = [];
24948
- const maxSize = MAX_TX_SIZE - (opts.sizeMargin ?? 0);
24949
25182
  function buildTx(extraIxs) {
24950
25183
  const messageV0 = new TransactionMessage({
24951
25184
  payerKey: opts.payerKey,
@@ -24955,16 +25188,7 @@ function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
24955
25188
  return new VersionedTransaction(messageV0);
24956
25189
  }
24957
25190
  function fits(extraIxs) {
24958
- try {
24959
- const tx = buildTx(extraIxs);
24960
- if (getTxSize(tx) > maxSize) return false;
24961
- if (opts.maxAccountLocks !== void 0 && countTxAccountLocks(tx) > opts.maxAccountLocks) {
24962
- return false;
24963
- }
24964
- return true;
24965
- } catch {
24966
- return false;
24967
- }
25191
+ return fitsInOneTransaction([...mandatoryIxs, ...extraIxs], opts);
24968
25192
  }
24969
25193
  for (const ix of ixs) {
24970
25194
  if (fits([...buffer, ix])) {
@@ -24985,6 +25209,15 @@ function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
24985
25209
  }
24986
25210
  return result;
24987
25211
  }
25212
+ function makePreludeTxs(setupIxs, refreshIxs, opts) {
25213
+ const build = (ixs, type) => splitInstructionsToFitTransactions([], ixs, opts).map(
25214
+ (tx) => addTransactionMetadata(tx, { type, addressLookupTables: opts.luts })
25215
+ );
25216
+ return [
25217
+ ...build(setupIxs, "CREATE_ATA" /* CREATE_ATA */),
25218
+ ...build(refreshIxs, "CRANK" /* CRANK */)
25219
+ ];
25220
+ }
24988
25221
  function addTransactionMetadata(transaction, options) {
24989
25222
  return Object.assign(transaction, options);
24990
25223
  }
@@ -25182,144 +25415,6 @@ function makeWrapSolIxs(walletAddress, amount) {
25182
25415
  }
25183
25416
  return ixs;
25184
25417
  }
25185
- var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
25186
- TransactionType2["DEPOSIT"] = "DEPOSIT";
25187
- TransactionType2["WITHDRAW"] = "WITHDRAW";
25188
- TransactionType2["REPAY"] = "REPAY";
25189
- TransactionType2["BORROW"] = "BORROW";
25190
- TransactionType2["FLASHLOAN"] = "FLASHLOAN";
25191
- TransactionType2["LOOP"] = "LOOP";
25192
- TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
25193
- TransactionType2["LONG"] = "LONG";
25194
- TransactionType2["SHORT"] = "SHORT";
25195
- TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
25196
- TransactionType2["CREATE_ATA"] = "CREATE_ATA";
25197
- TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
25198
- TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
25199
- TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
25200
- TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
25201
- TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
25202
- TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
25203
- TransactionType2["CRANK"] = "CRANK";
25204
- TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
25205
- TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
25206
- TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
25207
- TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
25208
- TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
25209
- TransactionType2["VAULT_DEPOSIT"] = "VAULT_DEPOSIT";
25210
- TransactionType2["VAULT_WITHDRAW"] = "VAULT_WITHDRAW";
25211
- TransactionType2["VAULT_COMPLETE_WITHDRAWAL"] = "VAULT_COMPLETE_WITHDRAWAL";
25212
- TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
25213
- TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
25214
- TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
25215
- TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
25216
- TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
25217
- TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
25218
- TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
25219
- TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
25220
- TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
25221
- TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
25222
- return TransactionType2;
25223
- })(TransactionType || {});
25224
- var TransactionConfigMap = {
25225
- // BASE LENDING ACTIONS
25226
- ["DEPOSIT" /* DEPOSIT */]: {
25227
- label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
25228
- },
25229
- ["WITHDRAW" /* WITHDRAW */]: {
25230
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
25231
- },
25232
- ["REPAY" /* REPAY */]: {
25233
- label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
25234
- },
25235
- ["BORROW" /* BORROW */]: {
25236
- label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
25237
- },
25238
- // FLASHLOANS
25239
- ["FLASHLOAN" /* FLASHLOAN */]: { label: () => "Executing Flashloan" },
25240
- ["LOOP" /* LOOP */]: {
25241
- label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
25242
- },
25243
- ["REPAY_COLLAT" /* REPAY_COLLAT */]: {
25244
- label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
25245
- },
25246
- ["LONG" /* LONG */]: {
25247
- label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
25248
- },
25249
- ["SHORT" /* SHORT */]: {
25250
- label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
25251
- },
25252
- ["CRANK" /* CRANK */]: { label: () => "Updating latest prices" },
25253
- ["JUPITER_SWAP" /* JUPITER_SWAP */]: {
25254
- label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
25255
- },
25256
- // SETUP
25257
- ["CREATE_ACCOUNT" /* CREATE_ACCOUNT */]: { label: () => "Create marginfi account" },
25258
- ["CREATE_ATA" /* CREATE_ATA */]: { label: () => "Configure token account" },
25259
- // ACCOUNT MANAGEMENT
25260
- ["CLOSE_ACCOUNT" /* CLOSE_ACCOUNT */]: { label: () => "Close marginfi account" },
25261
- ["CLOSE_POSITION" /* CLOSE_POSITION */]: { label: () => "Close position" },
25262
- ["MOVE_POSITION_WITHDRAW" /* MOVE_POSITION_WITHDRAW */]: {
25263
- label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
25264
- },
25265
- ["MOVE_POSITION_DEPOSIT" /* MOVE_POSITION_DEPOSIT */]: {
25266
- label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
25267
- },
25268
- ["TRANSFER_AUTH" /* TRANSFER_AUTH */]: { label: () => "Authorize account transfer" },
25269
- // NATIVE STAKE ACTIONS
25270
- ["DEPOSIT_STAKE" /* DEPOSIT_STAKE */]: {
25271
- label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
25272
- },
25273
- ["WITHDRAW_STAKE" /* WITHDRAW_STAKE */]: {
25274
- label: () => "Authorize stake account"
25275
- },
25276
- ["INITIALIZE_STAKED_POOL" /* INITIALIZE_STAKED_POOL */]: { label: () => "Initialize stake pool" },
25277
- ["ADD_STAKED_BANK" /* ADD_STAKED_BANK */]: { label: () => "Create staked asset bank" },
25278
- ["MERGE_STAKE_ACCOUNTS" /* MERGE_STAKE_ACCOUNTS */]: { label: () => "Merge stake accounts" },
25279
- // GAMMA VAULT ACTIONS
25280
- ["VAULT_DEPOSIT" /* VAULT_DEPOSIT */]: {
25281
- label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token} into vault` : "Deposit into vault"
25282
- },
25283
- ["VAULT_WITHDRAW" /* VAULT_WITHDRAW */]: {
25284
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token} from vault` : "Withdraw from vault"
25285
- },
25286
- ["VAULT_COMPLETE_WITHDRAWAL" /* VAULT_COMPLETE_WITHDRAWAL */]: {
25287
- label: () => "Claim vault withdrawal"
25288
- },
25289
- // LST (Liquid Staking Tokens)
25290
- ["STAKE_TO_STAKE" /* STAKE_TO_STAKE */]: { label: () => "Convert stake" },
25291
- ["MINT_LST_NATIVE" /* MINT_LST_NATIVE */]: { label: () => "Mint LST" },
25292
- ["SWAP_TO_SOL" /* SWAP_TO_SOL */]: {
25293
- label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
25294
- },
25295
- ["SOL_TO_LST" /* SOL_TO_LST */]: {
25296
- label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
25297
- },
25298
- ["UNSTAKE_LST" /* UNSTAKE_LST */]: {
25299
- label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST"
25300
- },
25301
- // EMISSIONS
25302
- ["WITHDRAW_EMISSIONS" /* WITHDRAW_EMISSIONS */]: { label: () => "Withdraw emissions" },
25303
- // LIQUIDATE
25304
- ["LIQUIDATE_ACCOUNT" /* LIQUIDATE_ACCOUNT */]: { label: () => "Liquidate account" },
25305
- // BANK and GROUPS
25306
- ["CREATE_PERM_BANK" /* CREATE_PERM_BANK */]: { label: () => "Create permissionless bank" },
25307
- ["CREATE_GROUP" /* CREATE_GROUP */]: { label: () => "Create marginfi group" },
25308
- ["WITHDRAW_ALL" /* WITHDRAW_ALL */]: {
25309
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
25310
- }
25311
- };
25312
- var TransactionArenaKeyMap = {
25313
- ["DEPOSIT" /* DEPOSIT */]: new PublicKey("ArenaDeposit1111111111111111111111111111111"),
25314
- ["WITHDRAW" /* WITHDRAW */]: new PublicKey("ArenaWithdraw111111111111111111111111111111"),
25315
- ["BORROW" /* BORROW */]: new PublicKey("ArenaBorrow11111111111111111111111111111111"),
25316
- ["REPAY" /* REPAY */]: new PublicKey("ArenaRepay111111111111111111111111111111111"),
25317
- ["REPAY_COLLAT" /* REPAY_COLLAT */]: new PublicKey("ArenaRepayCo11at111111111111111111111111111"),
25318
- ["LONG" /* LONG */]: new PublicKey("ArenaLong1111111111111111111111111111111111"),
25319
- ["SHORT" /* SHORT */]: new PublicKey("ArenaShort111111111111111111111111111111111"),
25320
- ["CLOSE_POSITION" /* CLOSE_POSITION */]: new PublicKey("ArenaC1ose111111111111111111111111111111111")
25321
- // Add more mappings if needed
25322
- };
25323
25418
  function serializeBankConfigOpt(bankConfigOpt) {
25324
25419
  const toWrappedI80F48 = (value) => value && bigNumberToWrappedI80F48(value);
25325
25420
  const toBN2 = (value) => value && new BN8(value.toString());
@@ -25567,6 +25662,7 @@ function toBankDto(bank) {
25567
25662
  premiumTag: bank.premiumTag,
25568
25663
  premiumActive: bank.premiumActive,
25569
25664
  premiumActivatedAt: bank.premiumActivatedAt,
25665
+ kaminoEmergency: bank.kaminoEmergency,
25570
25666
  rateLimiter: bank.rateLimiter ? toBankRateLimiterDto(bank.rateLimiter) : void 0,
25571
25667
  tokenSymbol: bank.tokenSymbol,
25572
25668
  feesDestinationAccount: bank.feesDestinationAccount?.toBase58(),
@@ -25947,6 +26043,7 @@ function parseBankRaw(address, accountParsed, bankMetadata) {
25947
26043
  premiumTag: accountParsed.premiumTag,
25948
26044
  premiumActive,
25949
26045
  premiumActivatedAt: accountParsed.premiumActivatedAt.toNumber(),
26046
+ kaminoEmergency: (flags & KAMINO_MARKET_EMERGENCY_FLAG) > 0,
25950
26047
  rateLimiter,
25951
26048
  tokenSymbol,
25952
26049
  kaminoIntegrationAccounts,
@@ -25992,6 +26089,7 @@ function dtoToBank(bankDto) {
25992
26089
  premiumTag: bankDto.premiumTag ?? 0,
25993
26090
  premiumActive: bankDto.premiumActive ?? false,
25994
26091
  premiumActivatedAt: bankDto.premiumActivatedAt ?? 0,
26092
+ kaminoEmergency: bankDto.kaminoEmergency ?? false,
25995
26093
  rateLimiter: bankDto.rateLimiter ? dtoToBankRateLimiter(bankDto.rateLimiter) : void 0,
25996
26094
  tokenSymbol: bankDto.tokenSymbol,
25997
26095
  feesDestinationAccount: bankDto.feesDestinationAccount ? new PublicKey(bankDto.feesDestinationAccount) : void 0,
@@ -26444,6 +26542,10 @@ var AccountFlags = /* @__PURE__ */ ((AccountFlags2) => {
26444
26542
  AccountFlags2[AccountFlags2["ACCOUNT_IN_FLASHLOAN"] = 2] = "ACCOUNT_IN_FLASHLOAN";
26445
26543
  AccountFlags2[AccountFlags2["ACCOUNT_FLAG_DEPRECATED"] = 4] = "ACCOUNT_FLAG_DEPRECATED";
26446
26544
  AccountFlags2[AccountFlags2["ACCOUNT_TRANSFER_AUTHORITY_ALLOWED"] = 8] = "ACCOUNT_TRANSFER_AUTHORITY_ALLOWED";
26545
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_RECEIVERSHIP"] = 16] = "ACCOUNT_IN_RECEIVERSHIP";
26546
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_DELEVERAGE"] = 32] = "ACCOUNT_IN_DELEVERAGE";
26547
+ AccountFlags2[AccountFlags2["ACCOUNT_FROZEN"] = 64] = "ACCOUNT_FROZEN";
26548
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_ORDER_EXECUTION"] = 128] = "ACCOUNT_IN_ORDER_EXECUTION";
26447
26549
  return AccountFlags2;
26448
26550
  })(AccountFlags || {});
26449
26551
  var MarginRequirementType = /* @__PURE__ */ ((MarginRequirementType5) => {
@@ -40606,6 +40708,7 @@ function kaminoReserveToDto(reserve) {
40606
40708
  protocolTakeRatePct: reserve.config.protocolTakeRatePct,
40607
40709
  hostFixedInterestRateBps: reserve.config.hostFixedInterestRateBps,
40608
40710
  interestRateBasis: reserve.config.interestRateBasis ?? 0 /* Legacy */,
40711
+ emergencyMode: reserve.config.emergencyMode,
40609
40712
  depositLimit: reserve.config.depositLimit.toString(),
40610
40713
  borrowLimit: reserve.config.borrowLimit.toString(),
40611
40714
  borrowRateCurve: {
@@ -47139,6 +47242,7 @@ function dtoToKaminoReserve(reserveDto) {
47139
47242
  protocolTakeRatePct: reserveDto.config.protocolTakeRatePct,
47140
47243
  hostFixedInterestRateBps: reserveDto.config.hostFixedInterestRateBps,
47141
47244
  interestRateBasis: reserveDto.config.interestRateBasis ?? 0 /* Legacy */,
47245
+ emergencyMode: reserveDto.config.emergencyMode ?? 0,
47142
47246
  depositLimit: new BN8(reserveDto.config.depositLimit),
47143
47247
  borrowLimit: new BN8(reserveDto.config.borrowLimit),
47144
47248
  borrowRateCurve: {
@@ -47439,34 +47543,27 @@ function makeRefreshKaminoBanksIxs(marginfiAccount, bankMap, newBanksPk, bankMet
47439
47543
  const kaminoBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 3 /* KAMINO */);
47440
47544
  if (kaminoBanks.length > 0) {
47441
47545
  const newBanksPkBase = newBanksPk.map((pk2) => pk2.toBase58());
47442
- const banksToRefreshObligations = kaminoBanks.filter(
47443
- (bank) => newBanksPkBase.includes(bank.address.toBase58())
47444
- );
47445
- const refreshReserveData = kaminoBanks.map((kaminoBank) => {
47446
- const bankMetadata = bankMetadataMap?.[kaminoBank.address.toBase58()];
47447
- if (!bankMetadata?.kaminoStates) return;
47448
- if (!kaminoBank.kaminoIntegrationAccounts) return;
47449
- const kaminoReserve = kaminoBank.kaminoIntegrationAccounts.kaminoReserve;
47450
- const lendingMarket = bankMetadata.kaminoStates.reserveState.lendingMarket;
47546
+ const refreshes = kaminoBanks.map((kaminoBank) => {
47547
+ const kaminoStates = bankMetadataMap[kaminoBank.address.toBase58()]?.kaminoStates;
47548
+ if (!kaminoStates || !kaminoBank.kaminoIntegrationAccounts) {
47549
+ throw TransactionBuildingError.kaminoReserveNotFound(
47550
+ kaminoBank.address.toBase58(),
47551
+ kaminoBank.mint.toBase58(),
47552
+ kaminoBank.tokenSymbol
47553
+ );
47554
+ }
47451
47555
  return {
47452
- reserve: kaminoReserve,
47453
- lendingMarket
47556
+ bank: kaminoBank.address.toBase58(),
47557
+ reserve: kaminoBank.kaminoIntegrationAccounts.kaminoReserve,
47558
+ obligation: kaminoBank.kaminoIntegrationAccounts.kaminoObligation,
47559
+ lendingMarket: kaminoStates.reserveState.lendingMarket
47454
47560
  };
47455
- }).filter((bank) => !!bank);
47456
- const reserveIx = makeRefreshReservesBatchIx(refreshReserveData);
47457
- ixs.push(reserveIx);
47458
- for (const kaminoBank of banksToRefreshObligations) {
47459
- const bankMetadata = bankMetadataMap?.[kaminoBank.address.toBase58()];
47460
- if (!bankMetadata?.kaminoStates) continue;
47461
- if (!kaminoBank.kaminoIntegrationAccounts) continue;
47462
- const kaminoReserve = kaminoBank.kaminoIntegrationAccounts.kaminoReserve;
47463
- const lendingMarket = bankMetadata.kaminoStates.reserveState.lendingMarket;
47464
- const obligationIx = makeRefreshObligationIx(
47465
- lendingMarket,
47466
- kaminoBank.kaminoIntegrationAccounts.kaminoObligation,
47467
- kaminoReserve
47468
- );
47469
- ixs.push(obligationIx);
47561
+ });
47562
+ ixs.push(makeRefreshReservesBatchIx(refreshes));
47563
+ for (const { bank, reserve, obligation, lendingMarket } of refreshes) {
47564
+ if (newBanksPkBase.includes(bank)) {
47565
+ ixs.push(makeRefreshObligationIx(lendingMarket, obligation, reserve));
47566
+ }
47470
47567
  }
47471
47568
  }
47472
47569
  return {
@@ -61998,15 +62095,17 @@ function makeUpdateDriftMarketIxs(marginfiAccount, bankMap, banksToExclude, bank
61998
62095
  const allActiveBanks = activeBanksPk.filter((pk2) => !banksToExcludeSet.has(pk2.toBase58())).map((pk2) => bankMap.get(pk2.toBase58()));
61999
62096
  const driftBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 4);
62000
62097
  if (driftBanks.length > 0) {
62001
- const refreshReserveData = driftBanks.map((driftBank) => {
62002
- const bankMetadata = bankMetadataMap?.[driftBank.address.toBase58()];
62003
- if (!bankMetadata?.driftStates) return;
62004
- const driftSpotMarket = bankMetadata.driftStates.spotMarketState;
62005
- return driftSpotMarket;
62006
- }).filter((bank) => !!bank);
62007
- const updateDriftMarketIxs = refreshReserveData.map(
62008
- (market) => makeUpdateSpotMarketIx({ spotMarket: market })
62009
- );
62098
+ const updateDriftMarketIxs = driftBanks.map((driftBank) => {
62099
+ const driftStates = bankMetadataMap[driftBank.address.toBase58()]?.driftStates;
62100
+ if (!driftStates) {
62101
+ throw TransactionBuildingError.driftStateNotFound(
62102
+ driftBank.address.toBase58(),
62103
+ driftBank.mint.toBase58(),
62104
+ driftBank.tokenSymbol
62105
+ );
62106
+ }
62107
+ return makeUpdateSpotMarketIx({ spotMarket: driftStates.spotMarketState });
62108
+ });
62010
62109
  ixs.push(...updateDriftMarketIxs);
62011
62110
  }
62012
62111
  return {
@@ -64295,12 +64394,16 @@ function makeUpdateJupLendRateIxs(marginfiAccount, bankMap, banksToExclude, bank
64295
64394
  const jupLendBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 6 /* JUPLEND */);
64296
64395
  if (jupLendBanks.length > 0) {
64297
64396
  const updateRateIxs = jupLendBanks.map((bank) => {
64298
- const bankMetadata = bankMetadataMap?.[bank.address.toBase58()];
64299
- if (!bankMetadata?.jupLendStates) return;
64300
- return makeUpdateJupLendRate({
64301
- lendingState: bankMetadata.jupLendStates.jupLendingState
64302
- });
64303
- }).filter((ix) => !!ix);
64397
+ const jupLendStates = bankMetadataMap[bank.address.toBase58()]?.jupLendStates;
64398
+ if (!jupLendStates) {
64399
+ throw TransactionBuildingError.jupLendStateNotFound(
64400
+ bank.address.toBase58(),
64401
+ bank.mint.toBase58(),
64402
+ bank.tokenSymbol
64403
+ );
64404
+ }
64405
+ return makeUpdateJupLendRate({ lendingState: jupLendStates.jupLendingState });
64406
+ });
64304
64407
  ixs.push(...updateRateIxs);
64305
64408
  }
64306
64409
  return {
@@ -74857,7 +74960,7 @@ function getAssetWeight(params) {
74857
74960
  if (bank.config.riskTier === "Isolated" /* Isolated */) {
74858
74961
  return new BigNumber3(0);
74859
74962
  }
74860
- if (marginRequirement === 0 /* Initial */ && bank.config.operationalState === "ReduceOnly" /* ReduceOnly */) {
74963
+ if (marginRequirement === 0 /* Initial */ && (bank.config.operationalState === "ReduceOnly" /* ReduceOnly */ || bank.kaminoEmergency)) {
74861
74964
  return new BigNumber3(0);
74862
74965
  }
74863
74966
  const assetWeightInit = BigNumber3.max(
@@ -75106,13 +75209,13 @@ function computeInterestRates(bank) {
75106
75209
  const borrowingRate = baseInterestRate.times(new BigNumber3(1).plus(rateFee)).plus(fixedFee);
75107
75210
  return { lendingRate, borrowingRate };
75108
75211
  }
75109
- var U32_MAX = 4294967295;
75212
+ var U32_MAX2 = 4294967295;
75110
75213
  function rateFromU32(rate) {
75111
- const ratio = new BigNumber3(rate).div(U32_MAX);
75214
+ const ratio = new BigNumber3(rate).div(U32_MAX2);
75112
75215
  return ratio.times(10);
75113
75216
  }
75114
75217
  function utilFromU32(util) {
75115
- return new BigNumber3(util).div(U32_MAX);
75218
+ return new BigNumber3(util).div(U32_MAX2);
75116
75219
  }
75117
75220
  function calculateRateBetweenPoints(startX, startY, endX, endY, targetX) {
75118
75221
  if (endX.lte(startX)) return startY;
@@ -75623,6 +75726,10 @@ function makePoolConfigureBankIx(mfiProgram, accounts, args) {
75623
75726
  bank
75624
75727
  }).accountsPartial(optionalAccounts).instruction();
75625
75728
  }
75729
+ function makePoolConfigureBankGovIx(mfiProgram, accounts, args) {
75730
+ const { bank, ...optionalAccounts } = accounts;
75731
+ return mfiProgram.methods.lendingPoolConfigureBankGov(args.bankConfigOpt).accounts({ bank }).accountsPartial(optionalAccounts).instruction();
75732
+ }
75626
75733
  function makeBeginFlashLoanIx(mfiProgram, accounts, args) {
75627
75734
  const { marginfiAccount, ...optionalAccounts } = accounts;
75628
75735
  return mfiProgram.methods.lendingAccountStartFlashloan(args.endIndex).accounts({
@@ -75666,7 +75773,9 @@ async function makeLendingPoolConfigureBankOracleIx(mfProgram, accounts, args, r
75666
75773
  }
75667
75774
  async function makeLendingPoolConfigureBankOracleScopeIx(mfProgram, accounts, args) {
75668
75775
  const { bank, ...optionalAccounts } = accounts;
75669
- return mfProgram.methods.lendingPoolConfigureBankOracleScope(args.oracle, args.entryIndex).accounts({ bank }).accountsPartial(optionalAccounts).remainingAccounts([{ pubkey: args.oracle, isSigner: false, isWritable: false }]).instruction();
75776
+ return mfProgram.methods.lendingPoolConfigureBankOracleScope(args.oracle, args.entryIndex).accounts({ bank }).accountsPartial(optionalAccounts).remainingAccounts(
75777
+ [args.oracle, args.integrationAccount].filter((pubkey) => pubkey !== void 0).map((pubkey) => ({ pubkey, isSigner: false, isWritable: false }))
75778
+ ).instruction();
75670
75779
  }
75671
75780
  async function makeLendingPoolSetOraclePriceIx(mfProgram, accounts, args, remainingAccounts = []) {
75672
75781
  const { bank, ...optionalAccounts } = accounts;
@@ -75722,6 +75831,22 @@ async function makePulseHealthIx(mfProgram, accounts, remainingAccounts = []) {
75722
75831
  group: accounts.group
75723
75832
  }).remainingAccounts(remainingAccounts).instruction();
75724
75833
  }
75834
+ async function makePlaceOrderIx(mfProgram, accounts, args, remainingAccounts = []) {
75835
+ const { marginfiAccount, feePayer, authority, order, globalFeeWallet, ...optionalAccounts } = accounts;
75836
+ return mfProgram.methods.marginfiAccountPlaceOrder(args.bankKeys, args.trigger).accounts({
75837
+ marginfiAccount,
75838
+ feePayer,
75839
+ order
75840
+ }).accountsPartial({ authority, globalFeeWallet, ...optionalAccounts }).remainingAccounts(remainingAccounts).instruction();
75841
+ }
75842
+ async function makeCloseOrderIx(mfProgram, accounts, remainingAccounts = []) {
75843
+ const { marginfiAccount, authority, order, feeRecipient, ...optionalAccounts } = accounts;
75844
+ return mfProgram.methods.marginfiAccountCloseOrder().accounts({
75845
+ authority,
75846
+ order,
75847
+ feeRecipient
75848
+ }).accountsPartial({ marginfiAccount, ...optionalAccounts }).remainingAccounts(remainingAccounts).instruction();
75849
+ }
75725
75850
  var instructions = {
75726
75851
  makeDepositIx,
75727
75852
  makeJuplendDepositIx,
@@ -75738,6 +75863,7 @@ var instructions = {
75738
75863
  makeLendingAccountLiquidateIx,
75739
75864
  makePoolAddBankIx,
75740
75865
  makePoolConfigureBankIx,
75866
+ makePoolConfigureBankGovIx,
75741
75867
  makeBeginFlashLoanIx,
75742
75868
  makeEndFlashLoanIx,
75743
75869
  makeAccountTransferToNewAccountIx,
@@ -75747,37 +75873,30 @@ var instructions = {
75747
75873
  makeLendingPoolConfigureBankOracleIx,
75748
75874
  makeLendingPoolConfigureBankOracleScopeIx,
75749
75875
  makeLendingPoolSetOraclePriceIx,
75750
- makePulseHealthIx
75876
+ makePulseHealthIx,
75877
+ makePlaceOrderIx,
75878
+ makeCloseOrderIx
75751
75879
  };
75752
75880
  var instructions_default3 = instructions;
75753
75881
 
75754
75882
  // src/services/bank/bank.service.ts
75755
- async function freezeBankConfigIx(program, bankAddress, bankConfigOpt) {
75756
- const bankConfigRaw = serializeBankConfigOpt(bankConfigOpt);
75757
- const ix = await instructions_default3.makePoolConfigureBankIx(
75883
+ async function freezeBankConfigIx(program, bankAddress) {
75884
+ const ix = await instructions_default3.makePoolConfigureBankGovIx(
75758
75885
  program,
75759
- {
75760
- bank: bankAddress
75761
- },
75886
+ { bank: bankAddress },
75762
75887
  {
75763
75888
  bankConfigOpt: {
75764
- ...bankConfigRaw,
75765
75889
  assetWeightInit: null,
75766
75890
  assetWeightMaint: null,
75767
75891
  liabilityWeightInit: null,
75768
75892
  liabilityWeightMaint: null,
75769
- depositLimit: null,
75770
- borrowLimit: null,
75893
+ operationalState: null,
75771
75894
  riskTier: null,
75772
75895
  assetTag: null,
75773
- totalAssetValueInitLimit: null,
75774
- interestRateConfig: null,
75775
- operationalState: null,
75776
- oracleMaxAge: null,
75777
- permissionlessBadDebtSettlement: null,
75778
- freezeSettings: true,
75779
75896
  oracleMaxConfidence: null,
75780
- tokenlessRepaymentsAllowed: null
75897
+ oracleMaxAge: null,
75898
+ tokenlessRepaymentsAllowed: null,
75899
+ freezeSettings: true
75781
75900
  }
75782
75901
  }
75783
75902
  );
@@ -75794,11 +75913,12 @@ async function addOracleToBanksIx({
75794
75913
  oracleAccounts,
75795
75914
  setup,
75796
75915
  groupAddress,
75797
- adminAddress
75916
+ governanceAdminAddress
75798
75917
  }) {
75799
- if (setup === "Scope" /* Scope */ || setup === "PTPyth" /* PTPyth */ || setup === "PTFixed" /* PTFixed */ || setup === "Fixed" /* Fixed */ || setup === "FixedKamino" /* FixedKamino */ || setup === "FixedDrift" /* FixedDrift */ || setup === "FixedJuplend" /* FixedJuplend */) {
75918
+ const isScope = setup === "Scope" /* Scope */ || setup === "ScopeKamino" /* ScopeKamino */ || setup === "ScopeJuplend" /* ScopeJuplend */;
75919
+ if (isScope || setup === "PTPyth" /* PTPyth */ || setup === "PTFixed" /* PTFixed */ || setup === "Fixed" /* Fixed */ || setup === "FixedKamino" /* FixedKamino */ || setup === "FixedDrift" /* FixedDrift */ || setup === "FixedJuplend" /* FixedJuplend */) {
75800
75920
  throw new Error(
75801
- `${setup} must be configured with ${setup === "Scope" /* Scope */ ? "configureScopeOracleIx" : "setOraclePriceIx"}`
75921
+ `${setup} must be configured with ${isScope ? "configureScopeOracleIx" : "setOraclePriceIx"}`
75802
75922
  );
75803
75923
  }
75804
75924
  const resolvedOracleAccounts = oracleAccounts ?? (oracleKey ? [oracleKey] : []);
@@ -75816,7 +75936,7 @@ async function addOracleToBanksIx({
75816
75936
  {
75817
75937
  bank: bankAddress,
75818
75938
  group: groupAddress,
75819
- admin: adminAddress
75939
+ governanceAdmin: governanceAdminAddress
75820
75940
  },
75821
75941
  {
75822
75942
  setup: serializeOracleSetupToIndex(setup),
@@ -75840,7 +75960,7 @@ async function setOraclePriceIx({
75840
75960
  setup,
75841
75961
  oracleAccounts = [],
75842
75962
  groupAddress,
75843
- adminAddress
75963
+ governanceAdminAddress
75844
75964
  }) {
75845
75965
  const expectedAccountCount = setup === "PTPyth" /* PTPyth */ ? 2 : setup === "PTFixed" /* PTFixed */ ? 1 : void 0;
75846
75966
  if (expectedAccountCount !== void 0 && oracleAccounts.length !== expectedAccountCount) {
@@ -75851,7 +75971,7 @@ async function setOraclePriceIx({
75851
75971
  {
75852
75972
  bank: bankAddress,
75853
75973
  group: groupAddress,
75854
- admin: adminAddress
75974
+ governanceAdmin: governanceAdminAddress
75855
75975
  },
75856
75976
  {
75857
75977
  price: bigNumberToWrappedI80F48(price),
@@ -75866,22 +75986,24 @@ async function setOraclePriceIx({
75866
75986
  }
75867
75987
  async function configureScopeOracleIx({
75868
75988
  program,
75869
- bankAddress,
75989
+ bank,
75870
75990
  oracle,
75871
75991
  entryIndex,
75872
75992
  groupAddress,
75873
- adminAddress
75993
+ governanceAdminAddress
75874
75994
  }) {
75875
75995
  const ix = await instructions_default3.makeLendingPoolConfigureBankOracleScopeIx(
75876
75996
  program,
75877
75997
  {
75878
- bank: bankAddress,
75998
+ bank: bank.address,
75879
75999
  group: groupAddress,
75880
- admin: adminAddress
76000
+ governanceAdmin: governanceAdminAddress
75881
76001
  },
75882
76002
  {
75883
76003
  oracle,
75884
- entryIndex
76004
+ entryIndex,
76005
+ // ScopeKamino / ScopeJuplend validate the Kamino reserve or JupLend lending account after the feed
76006
+ integrationAccount: bank.config.assetTag === 3 /* KAMINO */ || bank.config.assetTag === 6 /* JUPLEND */ ? bank.config.oracleKeys[1] : void 0
75885
76007
  }
75886
76008
  );
75887
76009
  return {
@@ -75913,9 +76035,25 @@ function decodeAccountRaw(encoded, idl) {
75913
76035
  const coder = new BorshCoder(idl);
75914
76036
  return coder.accounts.decode("marginfiAccount" /* MarginfiAccount */, encoded);
75915
76037
  }
76038
+ function parseOrderRaw(orderAddress, orderRaw) {
76039
+ let trigger = "stopLoss";
76040
+ if ("takeProfit" in orderRaw.trigger) trigger = "takeProfit";
76041
+ if ("both" in orderRaw.trigger) trigger = "both";
76042
+ return {
76043
+ address: orderAddress,
76044
+ marginfiAccount: orderRaw.marginfiAccount,
76045
+ trigger,
76046
+ stopLoss: trigger === "takeProfit" ? null : wrappedI80F48toBigNumber(orderRaw.stopLoss),
76047
+ takeProfit: trigger === "stopLoss" ? null : wrappedI80F48toBigNumber(orderRaw.takeProfit),
76048
+ tags: [orderRaw.tags[0], orderRaw.tags[1]],
76049
+ createdAt: orderRaw.createdAt.toNumber(),
76050
+ maxSlippagePercent: maxSlippageU32ToPercent(orderRaw.maxSlippage)
76051
+ };
76052
+ }
75916
76053
  function parseBalanceRaw(balanceRaw) {
75917
76054
  const active = typeof balanceRaw.active === "number" ? balanceRaw.active === 1 : balanceRaw.active;
75918
76055
  const bankPk = balanceRaw.bankPk;
76056
+ const tag = balanceRaw.tag;
75919
76057
  const assetShares = wrappedI80F48toBigNumber(balanceRaw.assetShares);
75920
76058
  const liabilityShares = wrappedI80F48toBigNumber(balanceRaw.liabilityShares);
75921
76059
  const premiumRate = rateFromU32(balanceRaw.premiumRateSnapshot);
@@ -75924,6 +76062,7 @@ function parseBalanceRaw(balanceRaw) {
75924
76062
  return {
75925
76063
  active,
75926
76064
  bankPk,
76065
+ tag,
75927
76066
  assetShares,
75928
76067
  liabilityShares,
75929
76068
  premiumRate,
@@ -75971,7 +76110,8 @@ function parseMarginfiAccountRaw(marginfiAccountPk, accountData) {
75971
76110
  balances,
75972
76111
  accountFlags,
75973
76112
  emissionsDestinationAccount,
75974
- healthCache
76113
+ healthCache,
76114
+ activeOrders: accountData.activeOrders
75975
76115
  };
75976
76116
  }
75977
76117
  function getActiveAccountFlags(flags) {
@@ -76027,13 +76167,15 @@ function dtoToMarginfiAccount(marginfiAccountDto) {
76027
76167
  balances: marginfiAccountDto.balances.map(dtoToBalance),
76028
76168
  accountFlags: marginfiAccountDto.accountFlags,
76029
76169
  emissionsDestinationAccount: new PublicKey(marginfiAccountDto.emissionsDestinationAccount),
76030
- healthCache: dtoToHealthCache(marginfiAccountDto.healthCache)
76170
+ healthCache: dtoToHealthCache(marginfiAccountDto.healthCache),
76171
+ activeOrders: marginfiAccountDto.activeOrders ?? 0
76031
76172
  };
76032
76173
  }
76033
76174
  function dtoToBalance(balanceDto) {
76034
76175
  return {
76035
76176
  active: balanceDto.active,
76036
76177
  bankPk: new PublicKey(balanceDto.bankPk),
76178
+ tag: balanceDto.tag ?? 0,
76037
76179
  assetShares: new BigNumber3(balanceDto.assetShares),
76038
76180
  liabilityShares: new BigNumber3(balanceDto.liabilityShares),
76039
76181
  premiumRate: new BigNumber3(balanceDto.premiumRate),
@@ -76066,13 +76208,15 @@ function marginfiAccountToDto(marginfiAccount) {
76066
76208
  balances: marginfiAccount.balances.map(balanceToDto),
76067
76209
  accountFlags: marginfiAccount.accountFlags,
76068
76210
  emissionsDestinationAccount: marginfiAccount.emissionsDestinationAccount.toBase58(),
76069
- healthCache: healthCacheToDto(marginfiAccount.healthCache)
76211
+ healthCache: healthCacheToDto(marginfiAccount.healthCache),
76212
+ activeOrders: marginfiAccount.activeOrders
76070
76213
  };
76071
76214
  }
76072
76215
  function balanceToDto(balance) {
76073
76216
  return {
76074
76217
  active: balance.active,
76075
76218
  bankPk: balance.bankPk.toBase58(),
76219
+ tag: balance.tag,
76076
76220
  assetShares: balance.assetShares.toString(),
76077
76221
  liabilityShares: balance.liabilityShares.toString(),
76078
76222
  premiumRate: balance.premiumRate.toString(),
@@ -76348,11 +76492,22 @@ function computePremiumRatesByBank(params) {
76348
76492
  const rates = /* @__PURE__ */ new Map();
76349
76493
  for (const [bankKey, bank] of params.banksMap) {
76350
76494
  if (bank.premiumActive) {
76351
- rates.set(bankKey, computePremiumRate(collateral, params.premiumEntries, bank.premiumTag));
76495
+ rates.set(
76496
+ bankKey,
76497
+ breakdownPremium(collateral, params.premiumEntries, bank.premiumTag).reduce(
76498
+ (rate, row) => rate.plus(row.contributionApr),
76499
+ new BigNumber(0)
76500
+ )
76501
+ );
76352
76502
  }
76353
76503
  }
76354
76504
  return rates;
76355
76505
  }
76506
+ function computePremiumBreakdown(params, liabilityBank) {
76507
+ const bank = params.banksMap.get(liabilityBank.toBase58());
76508
+ if (!bank?.premiumActive) return [];
76509
+ return breakdownPremium(computePremiumCollateral(params), params.premiumEntries, bank.premiumTag);
76510
+ }
76356
76511
  function computePremiumImpact(params) {
76357
76512
  const { activeBalances, banksMap, oraclePricesByBank, premiumEntries, actions } = params;
76358
76513
  const nowSeconds = Date.now() / 1e3;
@@ -76388,6 +76543,7 @@ function computePremiumImpact(params) {
76388
76543
  );
76389
76544
  const usd = collateral.get(bankKey)?.usd ?? new BigNumber(0);
76390
76545
  collateral.set(bankKey, {
76546
+ bank: action.bank,
76391
76547
  tag: bank.premiumTag,
76392
76548
  usd: action.type === "deposit" ? usd.plus(delta) : BigNumber.max(0, usd.minus(delta))
76393
76549
  });
@@ -76425,8 +76581,9 @@ function computePremiumImpact(params) {
76425
76581
  const liabilities = /* @__PURE__ */ new Map();
76426
76582
  const debtsAfter = [];
76427
76583
  for (const [bankKey, debt] of debts) {
76428
- const after = computePremiumRate(collateral, premiumEntries, debt.bank.premiumTag);
76429
- liabilities.set(bankKey, { before: debt.storedRate, after });
76584
+ const breakdown = breakdownPremium(collateral, premiumEntries, debt.bank.premiumTag);
76585
+ const after = breakdown.reduce((rate, row) => rate.plus(row.contributionApr), new BigNumber(0));
76586
+ liabilities.set(bankKey, { before: debt.storedRate, after, breakdown });
76430
76587
  debtsAfter.push({ ...debt, rate: after });
76431
76588
  }
76432
76589
  return {
@@ -76456,6 +76613,7 @@ function computePremiumCollateral({
76456
76613
  continue;
76457
76614
  }
76458
76615
  collateral.set(bankKey, {
76616
+ bank: balance.bankPk,
76459
76617
  tag: bank.premiumTag,
76460
76618
  usd: computeUsdValue({
76461
76619
  bank,
@@ -76469,17 +76627,15 @@ function computePremiumCollateral({
76469
76627
  }
76470
76628
  return collateral;
76471
76629
  }
76472
- function computePremiumRate(collateral, premiumEntries, liabilityTag) {
76473
- let totalUsd = new BigNumber(0);
76474
- let weightedUsd = new BigNumber(0);
76475
- for (const { tag, usd } of collateral.values()) {
76630
+ function breakdownPremium(collateral, premiumEntries, liabilityTag) {
76631
+ const counted = [...collateral.values()].filter(({ usd }) => usd.gt(0));
76632
+ const totalUsd = counted.reduce((sum, { usd }) => sum.plus(usd), new BigNumber(0));
76633
+ return counted.map(({ bank, tag, usd }) => {
76476
76634
  const pairRate = premiumEntries.find(
76477
76635
  (entry) => entry.collateralTag === tag && entry.liabilityTag === liabilityTag
76478
- )?.rate;
76479
- totalUsd = totalUsd.plus(usd);
76480
- if (pairRate) weightedUsd = weightedUsd.plus(usd.times(pairRate));
76481
- }
76482
- return totalUsd.gt(0) ? weightedUsd.div(totalUsd) : new BigNumber(0);
76636
+ )?.rate ?? new BigNumber(0);
76637
+ return { bank, tag, usd, pairRate, contributionApr: usd.times(pairRate).div(totalUsd) };
76638
+ });
76483
76639
  }
76484
76640
  function sumAnnualPremiumUsd(debts, oraclePricesByBank) {
76485
76641
  return debts.reduce((sum, { bank, principal, rate }) => {
@@ -76543,6 +76699,23 @@ function getBalanceUsdValueWithPriceBias(params) {
76543
76699
  );
76544
76700
  return { assets: assetsValue, liabilities: liabilitiesValue };
76545
76701
  }
76702
+ function computeOrderPairNetValue(params) {
76703
+ const { collateral, debt } = params;
76704
+ const { assets: collateralUsd } = getBalanceUsdValueWithPriceBias({
76705
+ balance: collateral.balance,
76706
+ bank: collateral.bank,
76707
+ oraclePrice: collateral.oraclePrice,
76708
+ marginRequirement: 2 /* Equity */,
76709
+ assetShareValueMultiplier: collateral.assetShareValueMultiplier
76710
+ });
76711
+ const { liabilities: debtUsd } = getBalanceUsdValueWithPriceBias({
76712
+ balance: debt.balance,
76713
+ bank: debt.bank,
76714
+ oraclePrice: debt.oraclePrice,
76715
+ marginRequirement: 2 /* Equity */
76716
+ });
76717
+ return { collateralUsd, debtUsd, netUsd: collateralUsd.minus(debtUsd) };
76718
+ }
76546
76719
  function computeQuantity(balance, bank) {
76547
76720
  const assetsQuantity = getAssetQuantity(bank, balance.assetShares);
76548
76721
  const liabilitiesQuantity = getLiabilityQuantity(bank, balance.liabilityShares).plus(
@@ -76764,6 +76937,7 @@ function createEmptyBalance(bankPk) {
76764
76937
  const balance = {
76765
76938
  active: false,
76766
76939
  bankPk,
76940
+ tag: 0,
76767
76941
  assetShares: new BigNumber3(0),
76768
76942
  liabilityShares: new BigNumber3(0),
76769
76943
  premiumRate: new BigNumber3(0),
@@ -76778,6 +76952,18 @@ function getActiveBalances(balances) {
76778
76952
  function getBalance(bankAddress, balances) {
76779
76953
  return balances.filter((b) => b.active).find((b) => b.bankPk.equals(bankAddress)) ?? createEmptyBalance(bankAddress);
76780
76954
  }
76955
+ var EMPTY_BALANCE_THRESHOLD = 1;
76956
+ function resolveOrderLegs(marginfiAccount, order) {
76957
+ const taggedBalances = marginfiAccount.balances.filter(
76958
+ (balance) => balance.active && balance.tag !== 0 && order.tags.includes(balance.tag)
76959
+ );
76960
+ return {
76961
+ collateralBank: taggedBalances.find(
76962
+ (balance) => balance.liabilityShares.lt(EMPTY_BALANCE_THRESHOLD) && balance.assetShares.gte(EMPTY_BALANCE_THRESHOLD)
76963
+ )?.bankPk ?? null,
76964
+ debtBank: taggedBalances.find((balance) => balance.liabilityShares.gte(EMPTY_BALANCE_THRESHOLD))?.bankPk ?? null
76965
+ };
76966
+ }
76781
76967
  function computeAccountValue(marginfiAccount) {
76782
76968
  const { assets, liabilities } = computeHealthComponentsFromCache(
76783
76969
  marginfiAccount,
@@ -77043,6 +77229,7 @@ function computeProjectedActiveBalancesNoCpi({
77043
77229
  const projectedBalances = account.balances.map((b) => ({
77044
77230
  active: b.active,
77045
77231
  bankPk: b.bankPk,
77232
+ tag: b.tag,
77046
77233
  assetShares: new BigNumber3(b.assetShares),
77047
77234
  liabilityShares: new BigNumber3(b.liabilityShares),
77048
77235
  premiumRate: new BigNumber3(b.premiumRate),
@@ -77324,6 +77511,26 @@ var fetchMarginfiAccountData = async (program, marginfiAccountPk, banksMap, bank
77324
77511
  return { marginfiAccount };
77325
77512
  }
77326
77513
  };
77514
+ var fetchOrdersForAccount = async (program, marginfiAccount) => {
77515
+ const orders = await program.account.order.all([
77516
+ {
77517
+ memcmp: {
77518
+ bytes: marginfiAccount.toBase58(),
77519
+ offset: 8
77520
+ // first field after the discriminator
77521
+ }
77522
+ }
77523
+ ]);
77524
+ return orders.map(({ publicKey: publicKey5, account }) => parseOrderRaw(publicKey5, account));
77525
+ };
77526
+ var fetchOrderFees = async (program) => {
77527
+ const [feeStateAddress] = deriveFeeState(program.programId);
77528
+ const feeState = await program.account.feeState.fetch(feeStateAddress);
77529
+ return {
77530
+ placementFeeLamports: feeState.orderInitFlatSolFee,
77531
+ executionMaxFee: wrappedI80F48toBigNumber(feeState.orderExecutionMaxFee)
77532
+ };
77533
+ };
77327
77534
  function randomDistinctIndices(count, maxExclusive) {
77328
77535
  const chosen = /* @__PURE__ */ new Set();
77329
77536
  while (chosen.size < count) {
@@ -77447,18 +77654,27 @@ function computeMaxBorrowForBank(params) {
77447
77654
  BigNumber3.min(healthMaxBorrow, borrowCapRemaining, availableLiquidity, rateLimitRemaining)
77448
77655
  );
77449
77656
  }
77450
- function computeOutflowRateLimitRemaining(bank, oraclePrice, groupRateLimiter, assetShareValueMultiplier) {
77657
+ function computeBankOutflowRateLimit(bank, assetShareValueMultiplier) {
77658
+ if (!bank.rateLimiter) return null;
77451
77659
  const nowSeconds = Date.now() / 1e3;
77452
- let remaining = new BigNumber3(Infinity);
77453
- let bankRemaining = computeBankRateLimitRemaining(bank, nowSeconds);
77454
- if (bankRemaining !== null) {
77455
- const limiterInBankMintUnits = bank.config.assetTag === 3 /* KAMINO */ || bank.config.assetTag === 2 /* STAKED */;
77456
- if (limiterInBankMintUnits && assetShareValueMultiplier?.gt(0)) {
77457
- bankRemaining = bankRemaining.times(assetShareValueMultiplier);
77458
- }
77459
- remaining = BigNumber3.min(remaining, bankRemaining);
77660
+ const limiterToUnderlying = bank.config.assetTag === 2 /* STAKED */ && assetShareValueMultiplier?.gt(0) ? assetShareValueMultiplier : new BigNumber3(1);
77661
+ let tightest = null;
77662
+ for (const window of ["hourly", "daily"]) {
77663
+ const remainingNative = computeRateLimitWindowRemainingCapacity(
77664
+ bank.rateLimiter[window],
77665
+ nowSeconds
77666
+ );
77667
+ if (!remainingNative) continue;
77668
+ const remaining = BigNumber3.max(0, nativeToUi(remainingNative, bank.mintDecimals)).times(
77669
+ limiterToUnderlying
77670
+ );
77671
+ if (!tightest || remaining.lt(tightest.remaining)) tightest = { window, remaining };
77460
77672
  }
77461
- const groupRemainingUsd = computeGroupRateLimitRemainingUsd(groupRateLimiter, nowSeconds);
77673
+ return tightest;
77674
+ }
77675
+ function computeOutflowRateLimitRemaining(bank, oraclePrice, groupRateLimiter, assetShareValueMultiplier) {
77676
+ let remaining = computeBankOutflowRateLimit(bank, assetShareValueMultiplier)?.remaining ?? new BigNumber3(Infinity);
77677
+ const groupRemainingUsd = computeGroupRateLimitRemainingUsd(groupRateLimiter);
77462
77678
  if (groupRemainingUsd !== null) {
77463
77679
  const price = getPrice(oraclePrice, 1 /* None */, false);
77464
77680
  if (price.gt(0)) remaining = BigNumber3.min(remaining, groupRemainingUsd.div(price));
@@ -78323,6 +78539,26 @@ function isWholePosition(position, amount, mintDecimals) {
78323
78539
  const closePositionTokenAmount = computeClosePositionTokenAmount(position, mintDecimals);
78324
78540
  return amount >= closePositionTokenAmount;
78325
78541
  }
78542
+ function isCostlyBank(bank) {
78543
+ return [
78544
+ 3 /* KAMINO */,
78545
+ 4 /* DRIFT */,
78546
+ 5 /* SOLEND */,
78547
+ 6 /* JUPLEND */,
78548
+ 2 /* STAKED */
78549
+ ].includes(bank.config.assetTag);
78550
+ }
78551
+ function exceedsCostlyPositionLimit(balances, bankMap, bank) {
78552
+ const active = balances.filter((balance) => balance.active);
78553
+ if (!isCostlyBank(bank) || active.some((balance) => balance.bankPk.equals(bank.address))) {
78554
+ return false;
78555
+ }
78556
+ const held = active.filter((balance) => {
78557
+ const heldBank = bankMap.get(balance.bankPk.toBase58());
78558
+ return heldBank !== void 0 && isCostlyBank(heldBank);
78559
+ }).length;
78560
+ return held >= MAX_COSTLY_POSITIONS;
78561
+ }
78326
78562
  var KAMINO_PROGRAM_ID = new PublicKey("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD");
78327
78563
  var FARMS_PROGRAM_ID2 = new PublicKey("FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr");
78328
78564
  function encodeU642(value) {
@@ -78335,11 +78571,6 @@ function encodeU8(value) {
78335
78571
  buf.writeUInt8(value, 0);
78336
78572
  return buf;
78337
78573
  }
78338
- function encodeU16(value) {
78339
- const buf = Buffer.alloc(2);
78340
- buf.writeUInt16LE(value, 0);
78341
- return buf;
78342
- }
78343
78574
  function encodeBool(value) {
78344
78575
  const buf = Buffer.alloc(1);
78345
78576
  buf.writeUInt8(value ? 1 : 0, 0);
@@ -78357,9 +78588,6 @@ function encodeOptionU8(value) {
78357
78588
  }
78358
78589
  return Buffer.concat([Buffer.from([1]), encodeU8(value)]);
78359
78590
  }
78360
- function encodePublicKey(pubkey) {
78361
- return Buffer.from(pubkey.toBytes());
78362
- }
78363
78591
  var DISCRIMINATORS = {
78364
78592
  MARGINFI_ACCOUNT_INITIALIZE: Buffer.from([43, 78, 61, 255, 148, 52, 249, 154]),
78365
78593
  KAMINO_DEPOSIT: Buffer.from([237, 8, 188, 187, 115, 99, 49, 85]),
@@ -78369,16 +78597,11 @@ var DISCRIMINATORS = {
78369
78597
  LENDING_ACCOUNT_WITHDRAW: Buffer.from([36, 72, 74, 19, 210, 210, 192, 192]),
78370
78598
  LENDING_ACCOUNT_BORROW: Buffer.from([4, 126, 116, 53, 48, 5, 212, 31]),
78371
78599
  LENDING_ACCOUNT_LIQUIDATE: Buffer.from([214, 169, 151, 213, 251, 167, 86, 219]),
78372
- LENDING_POOL_ADD_BANK: Buffer.from([215, 68, 72, 78, 208, 218, 103, 182]),
78373
- LENDING_POOL_CONFIGURE_BANK: Buffer.from([121, 173, 156, 40, 93, 148, 56, 237]),
78374
78600
  LENDING_ACCOUNT_START_FLASHLOAN: Buffer.from([14, 131, 33, 220, 81, 186, 180, 107]),
78375
78601
  LENDING_ACCOUNT_END_FLASHLOAN: Buffer.from([105, 124, 201, 106, 153, 2, 8, 156]),
78376
78602
  TRANSFER_TO_NEW_ACCOUNT: Buffer.from([28, 79, 129, 231, 169, 69, 69, 65]),
78377
- MARGINFI_GROUP_INITIALIZE: Buffer.from([255, 67, 67, 26, 94, 31, 34, 20]),
78378
78603
  MARGINFI_ACCOUNT_CLOSE: Buffer.from([186, 221, 93, 34, 50, 97, 194, 241]),
78379
78604
  LENDING_POOL_ADD_BANK_PERMISSIONLESS: Buffer.from([127, 187, 121, 34, 187, 167, 238, 102]),
78380
- LENDING_POOL_CONFIGURE_BANK_ORACLE: Buffer.from([209, 82, 255, 171, 124, 21, 71, 81]),
78381
- LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE: Buffer.from([134, 228, 127, 3, 117, 132, 85, 146]),
78382
78605
  LENDING_ACCOUNT_PULSE_HEALTH: Buffer.from([186, 52, 117, 97, 34, 74, 39, 253]),
78383
78606
  LENDING_ACCOUNT_SORT_BALANCES: Buffer.from([187, 194, 110, 84, 82, 170, 204, 9]),
78384
78607
  DRIFT_DEPOSIT: Buffer.from([252, 63, 250, 201, 98, 55, 130, 12]),
@@ -78772,103 +78995,6 @@ function makeAccountTransferToNewAccountIx2(programId, accounts) {
78772
78995
  data: DISCRIMINATORS.TRANSFER_TO_NEW_ACCOUNT
78773
78996
  });
78774
78997
  }
78775
- function makeGroupInitIx2(programId, accounts, args) {
78776
- const keys = [
78777
- { pubkey: accounts.marginfiGroup, isSigner: true, isWritable: true },
78778
- { pubkey: accounts.admin, isSigner: true, isWritable: true },
78779
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78780
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
78781
- ];
78782
- const data = Buffer.concat([
78783
- DISCRIMINATORS.MARGINFI_GROUP_INITIALIZE,
78784
- encodeBool(args?.isArenaGroup ?? false)
78785
- ]);
78786
- return new TransactionInstruction({
78787
- keys,
78788
- programId,
78789
- data
78790
- });
78791
- }
78792
- function makePoolConfigureBankIx2(programId, accounts, _args) {
78793
- const keys = [
78794
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78795
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78796
- { pubkey: accounts.bank, isSigner: false, isWritable: true }
78797
- ];
78798
- return new TransactionInstruction({
78799
- keys,
78800
- programId,
78801
- data: DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK
78802
- });
78803
- }
78804
- function makeLendingPoolConfigureBankOracleIx2(programId, accounts, args, remainingAccounts = []) {
78805
- const keys = [
78806
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78807
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78808
- { pubkey: accounts.bank, isSigner: false, isWritable: true }
78809
- ];
78810
- keys.push(...remainingAccounts);
78811
- const data = Buffer.concat([
78812
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE,
78813
- encodeU8(args.setup),
78814
- encodePublicKey(args.feedId)
78815
- ]);
78816
- return new TransactionInstruction({
78817
- keys,
78818
- programId,
78819
- data
78820
- });
78821
- }
78822
- function makeLendingPoolConfigureBankOracleScopeIx2(programId, accounts, args) {
78823
- const keys = [
78824
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78825
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78826
- { pubkey: accounts.bank, isSigner: false, isWritable: true },
78827
- { pubkey: args.oracle, isSigner: false, isWritable: false }
78828
- ];
78829
- const data = Buffer.concat([
78830
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE,
78831
- encodePublicKey(args.oracle),
78832
- encodeU16(args.entryIndex)
78833
- ]);
78834
- return new TransactionInstruction({
78835
- keys,
78836
- programId,
78837
- data
78838
- });
78839
- }
78840
- function makePoolAddBankIx2(programId, accounts, _args) {
78841
- const keys = [
78842
- { pubkey: accounts.marginfiGroup, isSigner: false, isWritable: true },
78843
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78844
- { pubkey: accounts.feePayer, isSigner: true, isWritable: true },
78845
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78846
- { pubkey: accounts.globalFeeWallet, isSigner: false, isWritable: true },
78847
- { pubkey: accounts.bankMint, isSigner: false, isWritable: false },
78848
- { pubkey: accounts.bank, isSigner: true, isWritable: true },
78849
- {
78850
- pubkey: accounts.liquidityVaultAuthority,
78851
- isSigner: false,
78852
- isWritable: false
78853
- },
78854
- { pubkey: accounts.liquidityVault, isSigner: false, isWritable: true },
78855
- {
78856
- pubkey: accounts.insuranceVaultAuthority,
78857
- isSigner: false,
78858
- isWritable: false
78859
- },
78860
- { pubkey: accounts.insuranceVault, isSigner: false, isWritable: true },
78861
- { pubkey: accounts.feeVaultAuthority, isSigner: false, isWritable: false },
78862
- { pubkey: accounts.feeVault, isSigner: false, isWritable: true },
78863
- { pubkey: accounts.tokenProgram, isSigner: false, isWritable: false },
78864
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
78865
- ];
78866
- return new TransactionInstruction({
78867
- keys,
78868
- programId,
78869
- data: DISCRIMINATORS.LENDING_POOL_ADD_BANK
78870
- });
78871
- }
78872
78998
  function makeDriftDepositIx2(programId, accounts, args) {
78873
78999
  const liquidityVaultAuthority = deriveBankLiquidityVaultAuthority(programId, accounts.bank)[0];
78874
79000
  const keys = [
@@ -79047,16 +79173,11 @@ var syncInstructions = {
79047
79173
  makeKaminoWithdrawIx: makeKaminoWithdrawIx2,
79048
79174
  makeBorrowIx: makeBorrowIx2,
79049
79175
  makeLendingAccountLiquidateIx: makeLendingAccountLiquidateIx2,
79050
- makePoolAddBankIx: makePoolAddBankIx2,
79051
- makePoolConfigureBankIx: makePoolConfigureBankIx2,
79052
79176
  makeBeginFlashLoanIx: makeBeginFlashLoanIx2,
79053
79177
  makeEndFlashLoanIx: makeEndFlashLoanIx2,
79054
79178
  makeAccountTransferToNewAccountIx: makeAccountTransferToNewAccountIx2,
79055
- makeGroupInitIx: makeGroupInitIx2,
79056
79179
  makeCloseAccountIx: makeCloseAccountIx2,
79057
79180
  makePoolAddPermissionlessStakedBankIx: makePoolAddPermissionlessStakedBankIx2,
79058
- makeLendingPoolConfigureBankOracleIx: makeLendingPoolConfigureBankOracleIx2,
79059
- makeLendingPoolConfigureBankOracleScopeIx: makeLendingPoolConfigureBankOracleScopeIx2,
79060
79181
  makePulseHealthIx: makePulseHealthIx2
79061
79182
  };
79062
79183
  var sync_instructions_default = syncInstructions;
@@ -79256,6 +79377,9 @@ async function makeDriftDepositIx3({
79256
79377
  }
79257
79378
  async function makeDriftDepositTx(params) {
79258
79379
  const { luts, connection, amount, ...depositIxParams } = params;
79380
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79381
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79382
+ }
79259
79383
  if (!depositIxParams.bank.driftIntegrationAccounts) {
79260
79384
  throw new Error("Bank has no drift integration accounts");
79261
79385
  }
@@ -79263,13 +79387,17 @@ async function makeDriftDepositTx(params) {
79263
79387
  amount,
79264
79388
  ...depositIxParams
79265
79389
  });
79266
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79267
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79390
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79391
+ params,
79392
+ depositIxs.instructions,
79393
+ [params.bank.address],
79394
+ []
79395
+ );
79268
79396
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79269
79397
  const depositTx = addTransactionMetadata(
79270
79398
  new VersionedTransaction(
79271
79399
  new TransactionMessage({
79272
- instructions: [...depositIxs.instructions, ...premiumIxs],
79400
+ instructions: instructions2,
79273
79401
  payerKey: params.authority,
79274
79402
  recentBlockhash: blockhash
79275
79403
  }).compileToV0Message(selectedLuts)
@@ -79375,6 +79503,9 @@ async function makeKaminoDepositIx3({
79375
79503
  }
79376
79504
  async function makeKaminoDepositTx(params) {
79377
79505
  const { luts, connection, amount, ...depositIxParams } = params;
79506
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79507
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79508
+ }
79378
79509
  if (!depositIxParams.bank.kaminoIntegrationAccounts) {
79379
79510
  throw new Error("Bank has no kamino integration accounts");
79380
79511
  }
@@ -79399,13 +79530,17 @@ async function makeKaminoDepositTx(params) {
79399
79530
  amount,
79400
79531
  ...depositIxParams
79401
79532
  });
79402
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79403
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79533
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79534
+ params,
79535
+ [...refreshIxs, ...depositIxs.instructions],
79536
+ [params.bank.address],
79537
+ []
79538
+ );
79404
79539
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79405
79540
  const depositTx = addTransactionMetadata(
79406
79541
  new VersionedTransaction(
79407
79542
  new TransactionMessage({
79408
- instructions: [...refreshIxs, ...depositIxs.instructions, ...premiumIxs],
79543
+ instructions: instructions2,
79409
79544
  payerKey: params.authority,
79410
79545
  recentBlockhash: blockhash
79411
79546
  }).compileToV0Message(selectedLuts)
@@ -79482,10 +79617,17 @@ async function makeDepositIx3({
79482
79617
  }
79483
79618
  async function makeDepositTx(params) {
79484
79619
  const { luts, ...depositIxParams } = params;
79620
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79621
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79622
+ }
79485
79623
  const ixs = await makeDepositIx3(depositIxParams);
79486
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79487
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79488
- const tx = new Transaction().add(...ixs.instructions, ...premiumIxs);
79624
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79625
+ params,
79626
+ ixs.instructions,
79627
+ [params.bank.address],
79628
+ []
79629
+ );
79630
+ const tx = new Transaction().add(...instructions2);
79489
79631
  tx.feePayer = params.authority;
79490
79632
  const solanaTx = addTransactionMetadata(tx, {
79491
79633
  type: "DEPOSIT" /* DEPOSIT */,
@@ -79561,6 +79703,9 @@ async function makeJuplendDepositIx2({
79561
79703
  }
79562
79704
  async function makeJuplendDepositTx(params) {
79563
79705
  const { luts, connection, amount, ...depositIxParams } = params;
79706
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79707
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79708
+ }
79564
79709
  if (!depositIxParams.bank.jupLendIntegrationAccounts) {
79565
79710
  throw new Error("Bank has no JupLend integration accounts");
79566
79711
  }
@@ -79568,13 +79713,17 @@ async function makeJuplendDepositTx(params) {
79568
79713
  amount,
79569
79714
  ...depositIxParams
79570
79715
  });
79571
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79572
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79716
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79717
+ params,
79718
+ depositIxs.instructions,
79719
+ [params.bank.address],
79720
+ []
79721
+ );
79573
79722
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79574
79723
  const depositTx = addTransactionMetadata(
79575
79724
  new VersionedTransaction(
79576
79725
  new TransactionMessage({
79577
- instructions: [...depositIxs.instructions, ...premiumIxs],
79726
+ instructions: instructions2,
79578
79727
  payerKey: params.authority,
79579
79728
  recentBlockhash: blockhash
79580
79729
  }).compileToV0Message(selectedLuts)
@@ -80846,9 +80995,13 @@ async function makeRepayTx(params) {
80846
80995
  const { luts, ...repayIxParams } = params;
80847
80996
  const ixs = await makeRepayIx3(repayIxParams);
80848
80997
  const closedBanks = params.repayAll ? [params.bank.address] : [];
80849
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, closedBanks) ? await makePremiumRefreshIxs(params.program, params, [], closedBanks) : [];
80850
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
80851
- const tx = new Transaction().add(...ixs.instructions, ...premiumIxs);
80998
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
80999
+ params,
81000
+ ixs.instructions,
81001
+ [],
81002
+ closedBanks
81003
+ );
81004
+ const tx = new Transaction().add(...instructions2);
80852
81005
  tx.feePayer = params.authority;
80853
81006
  const solanaTx = addTransactionMetadata(tx, {
80854
81007
  type: "REPAY" /* REPAY */,
@@ -80906,23 +81059,11 @@ async function makeRepayWithCollatTx(params) {
80906
81059
  return true;
80907
81060
  });
80908
81061
  setupIxs.push(...jupiterSetupInstructions);
80909
- const additionalTxs = [];
80910
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
80911
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
80912
- const txs = splitInstructionsToFitTransactions([], ixs, {
80913
- blockhash,
80914
- payerKey: marginfiAccount.authority,
80915
- luts: addressLookupTableAccounts ?? []
80916
- });
80917
- additionalTxs.push(
80918
- ...txs.map(
80919
- (tx) => addTransactionMetadata(tx, {
80920
- type: "CREATE_ATA" /* CREATE_ATA */,
80921
- addressLookupTables: addressLookupTableAccounts
80922
- })
80923
- )
80924
- );
80925
- }
81062
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
81063
+ blockhash,
81064
+ payerKey: marginfiAccount.authority,
81065
+ luts: addressLookupTableAccounts ?? []
81066
+ });
80926
81067
  const transactions = [...additionalTxs, flashloanTx];
80927
81068
  return {
80928
81069
  transactions,
@@ -81865,6 +82006,9 @@ async function makeAccountTransferToNewAccountTx({
81865
82006
  newAuthority,
81866
82007
  feePayer
81867
82008
  }) {
82009
+ if (marginfiAccount.accountFlags.includes(1 /* ACCOUNT_DISABLED */)) {
82010
+ throw TransactionBuildingError.accountDisabled(marginfiAccount.address.toBase58());
82011
+ }
81868
82012
  const feePayerKey = feePayer instanceof Keypair ? feePayer.publicKey : feePayer ?? marginfiAccount.authority;
81869
82013
  const [feeStateKey] = PublicKey.findProgramAddressSync(
81870
82014
  [Buffer.from("feestate", "utf-8")],
@@ -82056,13 +82200,21 @@ async function makePulseHealthIx3(program, marginfiAccount, banks, mandatoryBank
82056
82200
  return { instructions: [ix], keys: [] };
82057
82201
  }
82058
82202
  async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMetadataMap }, mandatoryBanks, excludedBanks) {
82059
- const refreshIxs = makeRefreshIntegrationBanksIxs(
82060
- marginfiAccount,
82061
- bankMap,
82062
- [],
82063
- bankMetadataMap,
82064
- mandatoryBanks
82065
- );
82203
+ let refreshIxs;
82204
+ try {
82205
+ refreshIxs = makeRefreshIntegrationBanksIxs(
82206
+ marginfiAccount,
82207
+ bankMap,
82208
+ [],
82209
+ bankMetadataMap,
82210
+ mandatoryBanks
82211
+ ).instructions;
82212
+ } catch (error) {
82213
+ if (error instanceof TransactionBuildingError && (error.code === "KAMINO_RESERVE_NOT_FOUND" /* KAMINO_RESERVE_NOT_FOUND */ || error.code === "DRIFT_STATE_NOT_FOUND" /* DRIFT_STATE_NOT_FOUND */ || error.code === "JUPLEND_STATE_NOT_FOUND" /* JUPLEND_STATE_NOT_FOUND */)) {
82214
+ return [];
82215
+ }
82216
+ throw error;
82217
+ }
82066
82218
  const pulseIxs = await makePulseHealthIx3(
82067
82219
  program,
82068
82220
  marginfiAccount,
@@ -82070,13 +82222,38 @@ async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMe
82070
82222
  mandatoryBanks,
82071
82223
  excludedBanks
82072
82224
  );
82073
- return [...refreshIxs.instructions, ...pulseIxs.instructions];
82225
+ return [...refreshIxs, ...pulseIxs.instructions];
82226
+ }
82227
+ async function appendPremiumRefresh(params, actionIxs, mandatoryBanks, excludedBanks) {
82228
+ const { marginfiAccount, bankMap, bank, luts } = params;
82229
+ const actionOnly = { instructions: actionIxs, luts: selectLutsForBanks(luts, [bank]) };
82230
+ if (params.opts?.skipPremiumRefresh || !needsPremiumRefresh(marginfiAccount, bankMap, excludedBanks)) {
82231
+ return actionOnly;
82232
+ }
82233
+ const premiumIxs = await makePremiumRefreshIxs(
82234
+ params.program,
82235
+ params,
82236
+ mandatoryBanks,
82237
+ excludedBanks
82238
+ );
82239
+ const withPremium = {
82240
+ instructions: [...actionIxs, ...premiumIxs],
82241
+ luts: selectLutsForAccountAction(luts, bank, marginfiAccount.balances, bankMap)
82242
+ };
82243
+ const fits = premiumIxs.length > 0 && fitsInOneTransaction(withPremium.instructions, {
82244
+ payerKey: params.authority,
82245
+ luts: withPremium.luts,
82246
+ sizeMargin: PRIORITY_TX_SIZE + BUNDLE_TX_SIZE,
82247
+ maxAccountLocks: MAX_ACCOUNT_LOCKS - 3
82248
+ });
82249
+ return fits ? withPremium : actionOnly;
82074
82250
  }
82075
82251
  function generateDummyAccount(group, authority, accountKey) {
82076
82252
  const dummyWrappedI80F48 = bigNumberToWrappedI80F48(new BigNumber3(0));
82077
82253
  const dummyBalances = Array(15).fill({
82078
82254
  active: false,
82079
82255
  bankPk: new PublicKey("11111111111111111111111111111111"),
82256
+ tag: 0,
82080
82257
  assetShares: dummyWrappedI80F48,
82081
82258
  liabilityShares: dummyWrappedI80F48,
82082
82259
  premiumRateSnapshot: 0,
@@ -82086,7 +82263,7 @@ function generateDummyAccount(group, authority, accountKey) {
82086
82263
  const rawAccount = {
82087
82264
  group,
82088
82265
  authority,
82089
- lendingAccount: { balances: dummyBalances },
82266
+ lendingAccount: { balances: dummyBalances, lastTagUsed: 0 },
82090
82267
  healthCache: {
82091
82268
  assetValue: {
82092
82269
  value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@@ -82108,14 +82285,15 @@ function generateDummyAccount(group, authority, accountKey) {
82108
82285
  mrgnErr: 0
82109
82286
  },
82110
82287
  emissionsDestinationAccount: new PublicKey("11111111111111111111111111111111"),
82111
- accountFlags: new BN8([0, 0, 0])
82288
+ accountFlags: new BN8([0, 0, 0]),
82289
+ activeOrders: 0
82112
82290
  };
82113
82291
  return parseMarginfiAccountRaw(accountKey, rawAccount);
82114
82292
  }
82115
82293
 
82116
82294
  // src/models/balance.ts
82117
82295
  var Balance = class _Balance {
82118
- constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate) {
82296
+ constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate, tag) {
82119
82297
  this.active = active;
82120
82298
  this.bankPk = bankPk;
82121
82299
  this.assetShares = assetShares;
@@ -82123,6 +82301,7 @@ var Balance = class _Balance {
82123
82301
  this.premiumRate = premiumRate;
82124
82302
  this.premiumOutstanding = premiumOutstanding;
82125
82303
  this.lastUpdate = lastUpdate;
82304
+ this.tag = tag;
82126
82305
  }
82127
82306
  static from(balanceRaw) {
82128
82307
  const props = parseBalanceRaw(balanceRaw);
@@ -82133,7 +82312,8 @@ var Balance = class _Balance {
82133
82312
  props.liabilityShares,
82134
82313
  props.premiumRate,
82135
82314
  props.premiumOutstanding,
82136
- props.lastUpdate
82315
+ props.lastUpdate,
82316
+ props.tag
82137
82317
  );
82138
82318
  }
82139
82319
  static fromBalanceType(balance) {
@@ -82144,7 +82324,8 @@ var Balance = class _Balance {
82144
82324
  balance.liabilityShares,
82145
82325
  balance.premiumRate,
82146
82326
  balance.premiumOutstanding,
82147
- balance.lastUpdate
82327
+ balance.lastUpdate,
82328
+ balance.tag
82148
82329
  );
82149
82330
  }
82150
82331
  static createEmpty(bankPk) {
@@ -82214,7 +82395,7 @@ var HealthCache = class _HealthCache {
82214
82395
 
82215
82396
  // src/models/account.ts
82216
82397
  var MarginfiAccount = class _MarginfiAccount {
82217
- constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache) {
82398
+ constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache, activeOrders = 0) {
82218
82399
  this.address = address;
82219
82400
  this.group = group;
82220
82401
  this.authority = authority;
@@ -82222,6 +82403,7 @@ var MarginfiAccount = class _MarginfiAccount {
82222
82403
  this.accountFlags = accountFlags;
82223
82404
  this.emissionsDestinationAccount = emissionsDestinationAccount;
82224
82405
  this.healthCache = healthCache;
82406
+ this.activeOrders = activeOrders;
82225
82407
  }
82226
82408
  /**
82227
82409
  * Fetches a marginfi account from on-chain data.
@@ -82246,7 +82428,8 @@ var MarginfiAccount = class _MarginfiAccount {
82246
82428
  account.balances.map((b) => Balance.fromBalanceType(b)),
82247
82429
  account.accountFlags,
82248
82430
  account.emissionsDestinationAccount,
82249
- account.healthCache
82431
+ account.healthCache,
82432
+ account.activeOrders
82250
82433
  );
82251
82434
  }
82252
82435
  /**
@@ -82266,7 +82449,8 @@ var MarginfiAccount = class _MarginfiAccount {
82266
82449
  props.balances.map((b) => Balance.fromBalanceType(b)),
82267
82450
  props.accountFlags,
82268
82451
  props.emissionsDestinationAccount,
82269
- HealthCache.fromHealthCacheType(props.healthCache)
82452
+ HealthCache.fromHealthCacheType(props.healthCache),
82453
+ props.activeOrders
82270
82454
  );
82271
82455
  }
82272
82456
  /**
@@ -83105,6 +83289,49 @@ var MarginfiAccount = class _MarginfiAccount {
83105
83289
  }
83106
83290
  });
83107
83291
  }
83292
+ // ----------------------------------------------------------------------------
83293
+ // Orders (take-profit / stop-loss)
83294
+ // ----------------------------------------------------------------------------
83295
+ /**
83296
+ * Creates a place-order instruction for this marginfi account.
83297
+ *
83298
+ * @see {@link makePlaceOrderIx} for detailed implementation
83299
+ */
83300
+ async makePlaceOrderIx(params) {
83301
+ return makePlaceOrderIx2({ ...params, marginfiAccount: this });
83302
+ }
83303
+ /**
83304
+ * Creates a transaction placing a take-profit / stop-loss order on a collateral/debt pair.
83305
+ *
83306
+ * @see {@link makePlaceOrderTx} for detailed implementation
83307
+ */
83308
+ async makePlaceOrderTx(params) {
83309
+ return makePlaceOrderTx({ ...params, marginfiAccount: this });
83310
+ }
83311
+ /**
83312
+ * Creates a close-order instruction for this marginfi account.
83313
+ *
83314
+ * @see {@link makeCloseOrderIx} for detailed implementation
83315
+ */
83316
+ async makeCloseOrderIx(params) {
83317
+ return makeCloseOrderIx2({ ...params, marginfiAccount: this });
83318
+ }
83319
+ /**
83320
+ * Creates a transaction closing an existing order.
83321
+ *
83322
+ * @see {@link makeCloseOrderTx} for detailed implementation
83323
+ */
83324
+ async makeCloseOrderTx(params) {
83325
+ return makeCloseOrderTx({ ...params, marginfiAccount: this });
83326
+ }
83327
+ /**
83328
+ * Creates a transaction replacing the pair's existing order with new thresholds.
83329
+ *
83330
+ * @see {@link makeUpdateOrderTx} for detailed implementation
83331
+ */
83332
+ async makeUpdateOrderTx(params) {
83333
+ return makeUpdateOrderTx({ ...params, marginfiAccount: this });
83334
+ }
83108
83335
  /**
83109
83336
  * Creates a repay transaction.
83110
83337
  *
@@ -83263,7 +83490,8 @@ function projectAccountAfterFirstLeg(account, firstLegFlashloanTxs, program, ban
83263
83490
  projectedBalances.map((b) => Balance.fromBalanceType(b)),
83264
83491
  account.accountFlags,
83265
83492
  account.emissionsDestinationAccount,
83266
- account.healthCache
83493
+ account.healthCache,
83494
+ account.activeOrders
83267
83495
  );
83268
83496
  }
83269
83497
  function composeBundle(firstLegTxs, secondLegTxs, payer, blockhash, maxBundleTxs) {
@@ -83407,23 +83635,15 @@ async function makeSwapDebtTx(params) {
83407
83635
  return true;
83408
83636
  });
83409
83637
  setupIxs.push(...jupiterSetupInstructions);
83410
- const additionalTxs = [];
83411
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83412
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83413
- const txs = splitInstructionsToFitTransactions([], ixs, {
83638
+ const additionalTxs = makePreludeTxs(
83639
+ [...additionalIxs, ...setupIxs],
83640
+ refreshIntegrationIxs.instructions,
83641
+ {
83414
83642
  blockhash,
83415
83643
  payerKey: marginfiAccount.authority,
83416
83644
  luts: addressLookupTableAccounts ?? []
83417
- });
83418
- additionalTxs.push(
83419
- ...txs.map(
83420
- (tx) => addTransactionMetadata(tx, {
83421
- type: "CREATE_ATA" /* CREATE_ATA */,
83422
- addressLookupTables: addressLookupTableAccounts
83423
- })
83424
- )
83425
- );
83426
- }
83645
+ }
83646
+ );
83427
83647
  const transactions = [...additionalTxs, flashloanTx];
83428
83648
  return {
83429
83649
  transactions,
@@ -83707,12 +83927,18 @@ async function tryBridgedDebtSwap(params, bridgeOpts) {
83707
83927
  async function makeLoopTx(params) {
83708
83928
  const {
83709
83929
  marginfiAccount,
83930
+ bankMap,
83710
83931
  depositOpts,
83711
83932
  borrowOpts,
83712
83933
  addressLookupTableAccounts,
83713
83934
  connection,
83714
83935
  additionalIxs = []
83715
83936
  } = params;
83937
+ if (exceedsCostlyPositionLimit(marginfiAccount.balances, bankMap, depositOpts.depositBank)) {
83938
+ throw TransactionBuildingError.costlyPositionLimitExceeded(
83939
+ depositOpts.depositBank.address.toBase58()
83940
+ );
83941
+ }
83716
83942
  const blockhash = (await connection.getLatestBlockhash("confirmed")).blockhash;
83717
83943
  const setupIxs = await makeSetupIx({
83718
83944
  connection,
@@ -83752,28 +83978,20 @@ async function makeLoopTx(params) {
83752
83978
  return true;
83753
83979
  });
83754
83980
  setupIxs.push(...jupiterSetupInstructions);
83755
- const additionalTxs = [];
83756
83981
  if (depositOpts.depositBank.mint.equals(NATIVE_MINT) && depositOpts.inputDepositAmount) {
83757
83982
  setupIxs.push(
83758
83983
  ...makeWrapSolIxs(marginfiAccount.authority, new BigNumber(depositOpts.inputDepositAmount))
83759
83984
  );
83760
83985
  }
83761
- if (setupIxs.length > 0 || additionalIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83762
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83763
- const txs = splitInstructionsToFitTransactions([], ixs, {
83986
+ const additionalTxs = makePreludeTxs(
83987
+ [...additionalIxs, ...setupIxs],
83988
+ refreshIntegrationIxs.instructions,
83989
+ {
83764
83990
  blockhash,
83765
83991
  payerKey: marginfiAccount.authority,
83766
83992
  luts: addressLookupTableAccounts ?? []
83767
- });
83768
- additionalTxs.push(
83769
- ...txs.map(
83770
- (tx) => addTransactionMetadata(tx, {
83771
- type: "CREATE_ATA" /* CREATE_ATA */,
83772
- addressLookupTables: addressLookupTableAccounts
83773
- })
83774
- )
83775
- );
83776
- }
83993
+ }
83994
+ );
83777
83995
  const transactions = [...additionalTxs, flashloanTx];
83778
83996
  return {
83779
83997
  transactions,
@@ -84220,23 +84438,11 @@ async function makeSwapCollateralTx(params) {
84220
84438
  return true;
84221
84439
  });
84222
84440
  setupIxs.push(...jupiterSetupInstructions);
84223
- const additionalTxs = [];
84224
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
84225
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
84226
- const txs = splitInstructionsToFitTransactions([], ixs, {
84227
- blockhash,
84228
- payerKey: marginfiAccount.authority,
84229
- luts: addressLookupTableAccounts ?? []
84230
- });
84231
- additionalTxs.push(
84232
- ...txs.map(
84233
- (tx) => addTransactionMetadata(tx, {
84234
- type: "CREATE_ATA" /* CREATE_ATA */,
84235
- addressLookupTables: addressLookupTableAccounts
84236
- })
84237
- )
84238
- );
84239
- }
84441
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84442
+ blockhash,
84443
+ payerKey: marginfiAccount.authority,
84444
+ luts: addressLookupTableAccounts ?? []
84445
+ });
84240
84446
  const transactions = [...additionalTxs, flashloanTx];
84241
84447
  return {
84242
84448
  transactions,
@@ -84276,6 +84482,10 @@ async function buildSwapCollateralFlashloanTx({
84276
84482
  actualWithdrawAmount,
84277
84483
  withdrawBank.mintDecimals
84278
84484
  );
84485
+ const balancesAtDeposit = isFullWithdraw ? marginfiAccount.balances.filter((balance) => !balance.bankPk.equals(withdrawBank.address)) : marginfiAccount.balances;
84486
+ if (exceedsCostlyPositionLimit(balancesAtDeposit, bankMap, depositBank)) {
84487
+ throw TransactionBuildingError.costlyPositionLimitExceeded(depositBank.address.toBase58());
84488
+ }
84279
84489
  const cuRequestIxs = [
84280
84490
  ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 }),
84281
84491
  ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 })
@@ -84667,6 +84877,8 @@ async function makeRollPtTx(params) {
84667
84877
  const {
84668
84878
  marginfiAccount,
84669
84879
  connection,
84880
+ bankMap,
84881
+ bankMetadataMap,
84670
84882
  withdrawOpts,
84671
84883
  depositOpts,
84672
84884
  rollOpts,
@@ -84701,33 +84913,29 @@ async function makeRollPtTx(params) {
84701
84913
  { mint: depositOpts.depositBank.mint, tokenProgram: depositOpts.tokenProgram }
84702
84914
  ]
84703
84915
  });
84916
+ const refreshIntegrationIxs = makeRefreshIntegrationBanksIxs(
84917
+ marginfiAccount,
84918
+ bankMap,
84919
+ [withdrawOpts.withdrawBank.address, depositOpts.depositBank.address],
84920
+ bankMetadataMap
84921
+ );
84704
84922
  const { flashloanTx, swapQuote } = await buildRollPtFlashloanTx({
84705
84923
  params,
84706
84924
  merge,
84707
84925
  clmm,
84708
84926
  blockhash
84709
84927
  });
84710
- const additionalTxs = [];
84711
- if (setupIxs.length > 0) {
84712
- const txs = splitInstructionsToFitTransactions([], setupIxs, {
84713
- blockhash,
84714
- payerKey: marginfiAccount.authority,
84715
- luts: addressLookupTableAccounts ?? []
84716
- });
84717
- additionalTxs.push(
84718
- ...txs.map(
84719
- (tx) => addTransactionMetadata(tx, {
84720
- type: "CREATE_ATA" /* CREATE_ATA */,
84721
- addressLookupTables: addressLookupTableAccounts
84722
- })
84723
- )
84724
- );
84725
- }
84928
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84929
+ blockhash,
84930
+ payerKey: marginfiAccount.authority,
84931
+ luts: addressLookupTableAccounts ?? []
84932
+ });
84726
84933
  const transactions = [...additionalTxs, flashloanTx];
84727
84934
  return {
84728
84935
  transactions,
84729
84936
  actionTxIndex: transactions.length - 1,
84730
- quoteResponse: swapQuote
84937
+ quoteResponse: swapQuote,
84938
+ mustBeAtomicBundle: refreshIntegrationIxs.instructions.length > 0
84731
84939
  };
84732
84940
  }
84733
84941
  async function buildRollPtFlashloanTx({
@@ -85077,6 +85285,13 @@ function classifyAndValidate(params) {
85077
85285
  );
85078
85286
  }
85079
85287
  }
85288
+ const costlyCountB = destPreexistingBanksOf(accountB, bankMap).filter(isCostlyBank).length + positions.filter((p) => p.side === "collateral" && isCostlyBank(p.bank)).length;
85289
+ if (costlyCountB > MAX_COSTLY_POSITIONS) {
85290
+ throw TransactionBuildingError.transferPositionsInvalidSelection(
85291
+ `destination account cannot hold ${costlyCountB} integration and staked positions (max ${MAX_COSTLY_POSITIONS})`,
85292
+ positions.map((p) => p.bankAddress.toBase58())
85293
+ );
85294
+ }
85080
85295
  return positions;
85081
85296
  }
85082
85297
  function buildIntegrationRefreshIxs(args) {
@@ -85410,20 +85625,11 @@ async function makeTransferPositionsTx(params) {
85410
85625
  bankMap,
85411
85626
  bankMetadataMap
85412
85627
  });
85413
- const additionalTxs = [];
85414
- const preludeIxs = [...setupIxs, ...refreshIxs];
85415
- if (preludeIxs.length > 0) {
85416
- const txs = splitInstructionsToFitTransactions([], preludeIxs, {
85417
- blockhash,
85418
- payerKey: accountA.authority,
85419
- luts
85420
- });
85421
- additionalTxs.push(
85422
- ...txs.map(
85423
- (tx) => addTransactionMetadata(tx, { type: "CREATE_ATA" /* CREATE_ATA */, addressLookupTables: luts })
85424
- )
85425
- );
85426
- }
85628
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85629
+ blockhash,
85630
+ payerKey: accountA.authority,
85631
+ luts
85632
+ });
85427
85633
  const transactions = [...additionalTxs, flashloanTx];
85428
85634
  return {
85429
85635
  transactions,
@@ -85565,48 +85771,22 @@ async function makeBulkWithdrawTx(params) {
85565
85771
  type: "WITHDRAW" /* WITHDRAW */
85566
85772
  })
85567
85773
  );
85568
- const additionalTxs = [];
85569
85774
  const setupIxs = await makeSetupIx({
85570
85775
  connection,
85571
85776
  authority,
85572
85777
  tokens: setupTokens
85573
85778
  });
85574
- if (setupIxs.length > 0) {
85575
- const setupTxs = splitInstructionsToFitTransactions([], setupIxs, {
85576
- blockhash,
85577
- payerKey: authority,
85578
- luts: selectedLuts
85579
- });
85580
- additionalTxs.push(
85581
- ...setupTxs.map(
85582
- (tx) => addTransactionMetadata(tx, {
85583
- type: "CREATE_ATA" /* CREATE_ATA */,
85584
- addressLookupTables: selectedLuts
85585
- })
85586
- )
85587
- );
85588
- }
85589
85779
  const refreshIxs = makeRefreshIntegrationBanksIxs(
85590
85780
  marginfiAccount,
85591
85781
  bankMap,
85592
85782
  bankAddresses,
85593
85783
  bankMetadataMap
85594
85784
  ).instructions;
85595
- if (refreshIxs.length > 0) {
85596
- const refreshTxs = splitInstructionsToFitTransactions([], refreshIxs, {
85597
- blockhash,
85598
- payerKey: authority,
85599
- luts: selectedLuts
85600
- });
85601
- additionalTxs.push(
85602
- ...refreshTxs.map(
85603
- (tx) => addTransactionMetadata(tx, {
85604
- type: "CRANK" /* CRANK */,
85605
- addressLookupTables: selectedLuts
85606
- })
85607
- )
85608
- );
85609
- }
85785
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85786
+ blockhash,
85787
+ payerKey: authority,
85788
+ luts: selectedLuts
85789
+ });
85610
85790
  return {
85611
85791
  transactions: [...additionalTxs, ...withdrawTxs],
85612
85792
  actionTxIndex: additionalTxs.length,
@@ -85651,18 +85831,14 @@ async function makeBulkRepayTx(params) {
85651
85831
  });
85652
85832
  repayIxs.push(...repay.instructions);
85653
85833
  }
85654
- if (!params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses)) {
85655
- repayIxs.push(
85656
- ...await makePremiumRefreshIxs(
85657
- program,
85658
- { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85659
- [],
85660
- bankAddresses
85661
- )
85662
- );
85663
- }
85834
+ const premiumIxs = !params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses) ? await makePremiumRefreshIxs(
85835
+ program,
85836
+ { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85837
+ [],
85838
+ bankAddresses
85839
+ ) : [];
85664
85840
  const { blockhash } = await connection.getLatestBlockhash("confirmed");
85665
- const transactions = splitInstructionsToFitTransactions([], repayIxs, {
85841
+ const transactions = splitInstructionsToFitTransactions([], [...repayIxs, ...premiumIxs], {
85666
85842
  blockhash,
85667
85843
  payerKey: authority,
85668
85844
  luts,
@@ -85674,7 +85850,117 @@ async function makeBulkRepayTx(params) {
85674
85850
  type: "REPAY" /* REPAY */
85675
85851
  })
85676
85852
  );
85677
- return { transactions, actionTxIndex: 0, mustBeAtomicBundle: false };
85853
+ return {
85854
+ transactions,
85855
+ actionTxIndex: 0,
85856
+ // Venue refreshes only count in the pulse's slot, and the pulse must follow every repay
85857
+ mustBeAtomicBundle: premiumIxs.length > 0 && transactions.length > 1
85858
+ };
85859
+ }
85860
+ function buildOrderTrigger(params) {
85861
+ const { stopLossUsd, takeProfitUsd } = params;
85862
+ const maxSlippage = percentToMaxSlippageU32(params.maxSlippagePercent);
85863
+ const invalidTrigger = (reason) => TransactionBuildingError.orderInvalidTrigger(
85864
+ reason,
85865
+ takeProfitUsd?.toString(),
85866
+ stopLossUsd?.toString()
85867
+ );
85868
+ if (stopLossUsd && !stopLossUsd.gt(0)) {
85869
+ throw invalidTrigger(`stop-loss threshold (${stopLossUsd}) must be above 0`);
85870
+ }
85871
+ if (takeProfitUsd && !takeProfitUsd.gt(0)) {
85872
+ throw invalidTrigger(`take-profit threshold (${takeProfitUsd}) must be above 0`);
85873
+ }
85874
+ if (stopLossUsd && takeProfitUsd) {
85875
+ if (takeProfitUsd.lte(stopLossUsd)) {
85876
+ throw invalidTrigger(
85877
+ `take-profit threshold (${takeProfitUsd}) must be above stop-loss threshold (${stopLossUsd})`
85878
+ );
85879
+ }
85880
+ return {
85881
+ both: {
85882
+ stopLoss: bigNumberToWrappedI80F48(stopLossUsd),
85883
+ takeProfit: bigNumberToWrappedI80F48(takeProfitUsd),
85884
+ maxSlippage
85885
+ }
85886
+ };
85887
+ }
85888
+ if (stopLossUsd) {
85889
+ return { stopLoss: { threshold: bigNumberToWrappedI80F48(stopLossUsd), maxSlippage } };
85890
+ }
85891
+ if (takeProfitUsd) {
85892
+ return { takeProfit: { threshold: bigNumberToWrappedI80F48(takeProfitUsd), maxSlippage } };
85893
+ }
85894
+ throw invalidTrigger("an order needs a stop-loss threshold, a take-profit threshold, or both");
85895
+ }
85896
+ async function makePlaceOrderIx2(params) {
85897
+ const { program, marginfiAccount, collateralBank, debtBank, trigger, feePayer } = params;
85898
+ const [order] = deriveOrderPda(program.programId, marginfiAccount.address, [
85899
+ collateralBank,
85900
+ debtBank
85901
+ ]);
85902
+ const globalFeeWallet = params.globalFeeWallet ?? (await program.account.feeState.fetch(deriveFeeState(program.programId)[0])).globalFeeWallet;
85903
+ const placeOrderIx = await instructions_default3.makePlaceOrderIx(
85904
+ program,
85905
+ {
85906
+ marginfiAccount: marginfiAccount.address,
85907
+ feePayer: feePayer ?? marginfiAccount.authority,
85908
+ authority: marginfiAccount.authority,
85909
+ order,
85910
+ globalFeeWallet,
85911
+ group: marginfiAccount.group
85912
+ },
85913
+ { bankKeys: [collateralBank, debtBank], trigger: buildOrderTrigger(trigger) }
85914
+ );
85915
+ return { instructions: [placeOrderIx], keys: [] };
85916
+ }
85917
+ async function makeCloseOrderIx2(params) {
85918
+ const { program, marginfiAccount, order, feeRecipient } = params;
85919
+ const closeOrderIx = await instructions_default3.makeCloseOrderIx(program, {
85920
+ marginfiAccount: marginfiAccount.address,
85921
+ authority: marginfiAccount.authority,
85922
+ order,
85923
+ feeRecipient: feeRecipient ?? marginfiAccount.authority,
85924
+ group: marginfiAccount.group
85925
+ });
85926
+ return { instructions: [closeOrderIx], keys: [] };
85927
+ }
85928
+ async function compileOrderTx(params, payerKey, ixs, type) {
85929
+ const blockhash = params.blockhash ?? (await params.connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
85930
+ return addTransactionMetadata(
85931
+ new VersionedTransaction(
85932
+ new TransactionMessage({
85933
+ instructions: ixs.flatMap((ix) => ix.instructions),
85934
+ payerKey,
85935
+ recentBlockhash: blockhash
85936
+ }).compileToV0Message(params.luts)
85937
+ ),
85938
+ { type, signers: ixs.flatMap((ix) => ix.keys), addressLookupTables: params.luts }
85939
+ );
85940
+ }
85941
+ async function makePlaceOrderTx(params) {
85942
+ const placeIxs = await makePlaceOrderIx2(params);
85943
+ const payerKey = params.feePayer ?? params.marginfiAccount.authority;
85944
+ return compileOrderTx(params, payerKey, [placeIxs], "PLACE_ORDER" /* PLACE_ORDER */);
85945
+ }
85946
+ async function makeCloseOrderTx(params) {
85947
+ const closeIxs = await makeCloseOrderIx2(params);
85948
+ return compileOrderTx(
85949
+ params,
85950
+ params.marginfiAccount.authority,
85951
+ [closeIxs],
85952
+ "CLOSE_ORDER" /* CLOSE_ORDER */
85953
+ );
85954
+ }
85955
+ async function makeUpdateOrderTx(params) {
85956
+ const [order] = deriveOrderPda(params.program.programId, params.marginfiAccount.address, [
85957
+ params.collateralBank,
85958
+ params.debtBank
85959
+ ]);
85960
+ const closeIxs = await makeCloseOrderIx2({ ...params, order, feeRecipient: params.feePayer });
85961
+ const placeIxs = await makePlaceOrderIx2(params);
85962
+ const payerKey = params.feePayer ?? params.marginfiAccount.authority;
85963
+ return compileOrderTx(params, payerKey, [closeIxs, placeIxs], "UPDATE_ORDER" /* UPDATE_ORDER */);
85678
85964
  }
85679
85965
 
85680
85966
  // src/services/account/services/account-simulation.service.ts
@@ -86017,7 +86303,7 @@ function isGroupRateLimiterEnabled(rateLimiter) {
86017
86303
  if (!rateLimiter) return false;
86018
86304
  return rateLimiter.hourly.maxOutflow.gt(0) || rateLimiter.daily.maxOutflow.gt(0);
86019
86305
  }
86020
- async function makePoolConfigureBankIx3(program, bank, args) {
86306
+ async function makePoolConfigureBankIx2(program, bank, args) {
86021
86307
  const ix = await instructions_default3.makePoolConfigureBankIx(
86022
86308
  program,
86023
86309
  {
@@ -86030,6 +86316,17 @@ async function makePoolConfigureBankIx3(program, bank, args) {
86030
86316
  keys: []
86031
86317
  };
86032
86318
  }
86319
+ async function makePoolConfigureBankGovIx2(program, bank, args) {
86320
+ const ix = await instructions_default3.makePoolConfigureBankGovIx(
86321
+ program,
86322
+ { bank },
86323
+ { bankConfigOpt: args }
86324
+ );
86325
+ return {
86326
+ instructions: [ix],
86327
+ keys: []
86328
+ };
86329
+ }
86033
86330
  async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddress, feePayer, pythOracle) {
86034
86331
  const [settingsKey] = PublicKey.findProgramAddressSync(
86035
86332
  [Buffer.from("staked_settings", "utf-8"), group.toBuffer()],
@@ -86065,7 +86362,7 @@ async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddr
86065
86362
  keys: []
86066
86363
  };
86067
86364
  }
86068
- async function makePoolAddBankIx3(program, group, bank, feePayer, bankMint, bankConfig, tokenProgram = TOKEN_PROGRAM_ID, overrideOpt = {}) {
86365
+ async function makePoolAddBankIx2(program, group, bank, feePayer, bankMint, bankConfig, tokenProgram = TOKEN_PROGRAM_ID, overrideOpt = {}) {
86069
86366
  const rawBankConfig = serializeBankConfigOpt(bankConfig);
86070
86367
  const rawBankConfigCompact = {
86071
86368
  ...rawBankConfig,
@@ -87585,6 +87882,9 @@ function getKaminoCTokenMultiplier(reserve) {
87585
87882
  const [totalLiquidity, totalCollateral] = scaledSupplies(reserve);
87586
87883
  return totalCollateral.isZero() ? new BigNumber3(1) : new BigNumber3(totalLiquidity.dividedBy(totalCollateral).toString());
87587
87884
  }
87885
+ function withKaminoReserveEmergency(bank, reserve) {
87886
+ return { ...bank, kaminoEmergency: bank.kaminoEmergency || reserve.config.emergencyMode !== 0 };
87887
+ }
87588
87888
 
87589
87889
  // src/services/integration/integration.service.ts
87590
87890
  async function fetchBankIntegrationMetadata(options) {
@@ -87631,7 +87931,7 @@ async function fetchBankIntegrationMetadata(options) {
87631
87931
 
87632
87932
  // src/models/bank.ts
87633
87933
  var Bank = class _Bank {
87634
- constructor(address, mint, mintDecimals, group, assetShareValue, liabilityShareValue, liquidityVault, liquidityVaultBump, liquidityVaultAuthorityBump, insuranceVault, insuranceVaultBump, insuranceVaultAuthorityBump, collectedInsuranceFeesOutstanding, feeVault, feeVaultBump, feeVaultAuthorityBump, collectedGroupFeesOutstanding, lastUpdate, config, totalAssetShares, totalLiabilityShares, emissionsActiveBorrowing, emissionsActiveLending, emissionsRate, emissionsMint, emissionsRemaining, collectedProgramFeesOutstanding, oracleKey, emode, premiumTag, premiumActive, premiumActivatedAt, rateLimiter, kaminoIntegrationAccounts, driftIntegrationAccounts, solendIntegrationAccounts, jupLendIntegrationAccounts, feesDestinationAccount, lendingPositionCount, borrowingPositionCount, tokenSymbol) {
87934
+ constructor(address, mint, mintDecimals, group, assetShareValue, liabilityShareValue, liquidityVault, liquidityVaultBump, liquidityVaultAuthorityBump, insuranceVault, insuranceVaultBump, insuranceVaultAuthorityBump, collectedInsuranceFeesOutstanding, feeVault, feeVaultBump, feeVaultAuthorityBump, collectedGroupFeesOutstanding, lastUpdate, config, totalAssetShares, totalLiabilityShares, emissionsActiveBorrowing, emissionsActiveLending, emissionsRate, emissionsMint, emissionsRemaining, collectedProgramFeesOutstanding, oracleKey, emode, premiumTag, premiumActive, premiumActivatedAt, kaminoEmergency, rateLimiter, kaminoIntegrationAccounts, driftIntegrationAccounts, solendIntegrationAccounts, jupLendIntegrationAccounts, feesDestinationAccount, lendingPositionCount, borrowingPositionCount, tokenSymbol) {
87635
87935
  this.address = address;
87636
87936
  this.mint = mint;
87637
87937
  this.mintDecimals = mintDecimals;
@@ -87664,6 +87964,7 @@ var Bank = class _Bank {
87664
87964
  this.premiumTag = premiumTag;
87665
87965
  this.premiumActive = premiumActive;
87666
87966
  this.premiumActivatedAt = premiumActivatedAt;
87967
+ this.kaminoEmergency = kaminoEmergency;
87667
87968
  this.rateLimiter = rateLimiter;
87668
87969
  this.kaminoIntegrationAccounts = kaminoIntegrationAccounts;
87669
87970
  this.driftIntegrationAccounts = driftIntegrationAccounts;
@@ -87739,6 +88040,7 @@ var Bank = class _Bank {
87739
88040
  bankType.premiumTag,
87740
88041
  bankType.premiumActive,
87741
88042
  bankType.premiumActivatedAt,
88043
+ bankType.kaminoEmergency,
87742
88044
  bankType.rateLimiter,
87743
88045
  bankType.kaminoIntegrationAccounts,
87744
88046
  bankType.driftIntegrationAccounts,
@@ -87785,6 +88087,7 @@ var Bank = class _Bank {
87785
88087
  props.premiumTag,
87786
88088
  props.premiumActive,
87787
88089
  props.premiumActivatedAt,
88090
+ props.kaminoEmergency,
87788
88091
  props.rateLimiter,
87789
88092
  props.kaminoIntegrationAccounts,
87790
88093
  props.driftIntegrationAccounts,
@@ -87958,7 +88261,7 @@ var MarginfiGroup = class _MarginfiGroup {
87958
88261
  // ----------------------------------------------------------------------------
87959
88262
  static fromAccountParsed(address, accountData) {
87960
88263
  const rateLimiter = accountData.rateLimiter ? parseBankRateLimiterRaw(accountData.rateLimiter) : void 0;
87961
- const premiumEntries = (accountData.premiumEntries ?? []).slice(0, accountData.premiumSettings?.entryCount ?? 0).map((entry) => ({ ...entry, rate: rateFromU32(entry.rate) }));
88264
+ const premiumEntries = accountData.premiumEntries.slice(0, accountData.premiumSettings.entryCount).map((entry) => ({ ...entry, rate: rateFromU32(entry.rate) }));
87962
88265
  return new _MarginfiGroup(accountData.admin, address, rateLimiter, premiumEntries);
87963
88266
  }
87964
88267
  static fromBuffer(address, rawData, idl) {
@@ -87980,7 +88283,7 @@ var MarginfiGroup = class _MarginfiGroup {
87980
88283
  // (TODO: move to Bank class)
87981
88284
  // ------------------------------------------------------------------------
87982
88285
  async makePoolConfigureBankIx(program, bank, args) {
87983
- return makePoolConfigureBankIx3(program, bank, args);
88286
+ return makePoolConfigureBankIx2(program, bank, args);
87984
88287
  }
87985
88288
  async makeAddPermissionlessStakedBankIx(program, voteAccountAddress, feePayer, pythOracle) {
87986
88289
  return makeAddPermissionlessStakedBankIx(
@@ -87992,7 +88295,7 @@ var MarginfiGroup = class _MarginfiGroup {
87992
88295
  );
87993
88296
  }
87994
88297
  async makePoolAddBankIx(program, bankPubkey, bankMint, bankConfig, feePayer) {
87995
- return makePoolAddBankIx3(
88298
+ return makePoolAddBankIx2(
87996
88299
  program,
87997
88300
  this.address,
87998
88301
  bankPubkey,
@@ -88563,6 +88866,75 @@ var MarginfiAccountWrapper = class {
88563
88866
  opts
88564
88867
  });
88565
88868
  }
88869
+ // ----------------------------------------------------------------------------
88870
+ // Orders (take-profit / stop-loss)
88871
+ // ----------------------------------------------------------------------------
88872
+ /**
88873
+ * Creates a place-order instruction, for composing into a larger transaction.
88874
+ *
88875
+ * @param collateralBank - Bank of the asset-side balance
88876
+ * @param debtBank - Bank of the liability-side balance
88877
+ * @param trigger - USD pair-equity thresholds and max slippage
88878
+ */
88879
+ async makePlaceOrderIx(collateralBank, debtBank, trigger) {
88880
+ return this.account.makePlaceOrderIx({
88881
+ program: this.client.program,
88882
+ collateralBank,
88883
+ debtBank,
88884
+ trigger
88885
+ });
88886
+ }
88887
+ /**
88888
+ * Creates a close-order instruction, for composing into a larger transaction.
88889
+ *
88890
+ * @param order - The order PDA (from `fetchOrdersForAccount` or `deriveOrderPda`)
88891
+ */
88892
+ async makeCloseOrderIx(order) {
88893
+ return this.account.makeCloseOrderIx({ program: this.client.program, order });
88894
+ }
88895
+ /**
88896
+ * Creates a transaction placing a take-profit / stop-loss order on a collateral/debt pair.
88897
+ *
88898
+ * @param collateralBank - Bank of the asset-side balance
88899
+ * @param debtBank - Bank of the liability-side balance
88900
+ * @param trigger - USD pair-equity thresholds and max slippage
88901
+ */
88902
+ async makePlaceOrderTx(collateralBank, debtBank, trigger) {
88903
+ return this.account.makePlaceOrderTx({
88904
+ program: this.client.program,
88905
+ collateralBank,
88906
+ debtBank,
88907
+ trigger,
88908
+ luts: this.client.addressLookupTables,
88909
+ connection: this.client.program.provider.connection
88910
+ });
88911
+ }
88912
+ /**
88913
+ * Creates a transaction replacing the pair's existing order with new thresholds.
88914
+ */
88915
+ async makeUpdateOrderTx(collateralBank, debtBank, trigger) {
88916
+ return this.account.makeUpdateOrderTx({
88917
+ program: this.client.program,
88918
+ collateralBank,
88919
+ debtBank,
88920
+ trigger,
88921
+ luts: this.client.addressLookupTables,
88922
+ connection: this.client.program.provider.connection
88923
+ });
88924
+ }
88925
+ /**
88926
+ * Creates a transaction closing an existing order.
88927
+ *
88928
+ * @param order - The order PDA (from `fetchOrdersForAccount` or `deriveOrderPda`)
88929
+ */
88930
+ async makeCloseOrderTx(order) {
88931
+ return this.account.makeCloseOrderTx({
88932
+ program: this.client.program,
88933
+ order,
88934
+ luts: this.client.addressLookupTables,
88935
+ connection: this.client.program.provider.connection
88936
+ });
88937
+ }
88566
88938
  /**
88567
88939
  * Creates a repay transaction with auto-injected client data.
88568
88940
  *
@@ -88732,6 +89104,13 @@ var MarginfiAccountWrapper = class {
88732
89104
  getPremiumRatesByBank() {
88733
89105
  return computePremiumRatesByBank(this.premiumRateParams());
88734
89106
  }
89107
+ /**
89108
+ * Per-collateral breakdown of the premium rate `liabilityBank` would charge this account.
89109
+ * See {@link computePremiumBreakdown}.
89110
+ */
89111
+ getPremiumBreakdown(liabilityBank) {
89112
+ return computePremiumBreakdown(this.premiumRateParams(), liabilityBank);
89113
+ }
88735
89114
  /**
88736
89115
  * How `actions` would change this account's premium rates and yearly premium.
88737
89116
  * See {@link computePremiumImpact}.
@@ -89183,6 +89562,10 @@ var Project0Client = class _Project0Client {
89183
89562
  bank.address.toBase58(),
89184
89563
  getKaminoCTokenMultiplier(reserve)
89185
89564
  );
89565
+ bankMap.set(
89566
+ bank.address.toBase58(),
89567
+ Bank.fromBankType(withKaminoReserveEmergency(bank, reserve))
89568
+ );
89186
89569
  break;
89187
89570
  }
89188
89571
  case 4 /* DRIFT */: {
@@ -89275,6 +89658,6 @@ var EmodeSettings = class _EmodeSettings {
89275
89658
  }
89276
89659
  };
89277
89660
 
89278
- export { ADDRESS_LOOKUP_TABLE_FOR_GROUP, ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE, ADDRESS_LOOKUP_TABLE_FOR_SWAP, AccountFlags, AccountType, AssetTag, BUNDLE_TX_SIZE, Balance, Bank, BankConfig, BankConfigFlag, BankVaultType, DEFAULT_BRIDGE_MINTS, DEFAULT_ORACLE_MAX_AGE, DEFAULT_REPAY_ALL_EXTRA_BUFFER_BPS, DISABLED_FLAG, EMPTY_HEALTH_CACHE, EXECUTION_HEADROOM_SECONDS, EmodeEntryFlags, EmodeFlags, EmodeImpactStatus, EmodeSettings, EmodeTag, FLASHLOAN_ENABLED_FLAG, HOURS_PER_YEAR, HealthCache, HealthCacheFlags, HealthCacheSimulationError, HealthCacheStatus, JUPITER_V6_PROGRAM, JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX, LST_MINT, MARGINFI_IDL, MARGINFI_PROGRAM, MARGINFI_PROGRAM_STAGING, MARGINFI_PROGRAM_STAGING_ALT, MARGINFI_SPONSORED_SHARD_ID, MAX_ACCOUNT_LOCKS, MAX_CONFIDENCE_INTERVAL_RATIO, MAX_TX_SIZE, MAX_U64, MPL_METADATA_PROGRAM_ID, MarginRequirementType, MarginfiAccount, MarginfiAccountWrapper, MarginfiGroup, OperationalState, OracleSetup, PDA_BANK_EMISSIONS_AUTH_SEED, PDA_BANK_EMISSIONS_VAULT_SEED, PDA_BANK_FEE_STATE_SEED, PDA_BANK_FEE_VAULT_AUTH_SEED, PDA_BANK_FEE_VAULT_SEED, PDA_BANK_INSURANCE_VAULT_AUTH_SEED, PDA_BANK_INSURANCE_VAULT_SEED, PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED, PDA_BANK_LIQUIDITY_VAULT_SEED, PDA_MARGINFI_ACCOUNT_SEED, PDA_REBALANCE_FEE_POOL_SEED, PREMIUM_ACTIVE_FLAG, PRIORITY_TX_SIZE, PYTH_PRICE_CONF_INTERVALS, PYTH_PUSH_ORACLE_ID, PYTH_SPONSORED_SHARD_ID, PriceBias, Project0Client, RiskTier, SECONDS_PER_YEAR, SINGLE_POOL_PROGRAM_ID, STAKED_ORACLE_DISABLED_FLAG, STAKED_ORACLE_USES_ONRAMP_FLAG, STAKE_CONFIG_ID, STAKE_PROGRAM_ID, SWAP_ADAPTERS, SYSTEM_PROGRAM_ID, SYSVAR_CLOCK_ID, SYSVAR_RENT_ID, SYSVAR_STAKE_HISTORY_ID, SwapProvider, TRANSFER_ACCOUNT_AUTHORITY_FLAG, TransactionArenaKeyMap, TransactionBuildingError, TransactionBuildingErrorCode, TransactionConfigMap, TransactionType, U64_MAX2 as U64_MAX, USDC_DECIMALS, USDC_MINT, USDT_MINT, VENUE_AVAILABLE_LIQUIDITY_BUFFER, WSOL_MINT, ZERO_ORACLE_KEY, accountConflictsWithBridgeBank, accountFlagToBN, addOracleToBanksIx, addTransactionMetadata, adjustPriceComponent, aprToApy, apyToApr, balanceToDto, bankConfigRawToDto, bankConfigToBankConfigRaw, bankMetadataMapToDto, bankMetadataToDto, bankRateLimiterRawToDto, bankRawToDto, bigNumberToWrappedI80F48, bpsToPercentile, buildCollateralLegIxs, calculateApyFromInterest, calculateInterestFromApy, capConfidenceInterval, categorizePythBanks, checkJupiterFeeAccount, checkTitanFeeAccount, chunkedGetRawMultipleAccountInfoOrdered, chunkedGetRawMultipleAccountInfoOrderedWithNulls, chunkedGetRawMultipleAccountInfos, classifyAndValidate, compileFlashloanPrecheck, composeBridgedSwap, composeRemainingAccounts, computeAccountValue, computeAccrualProjectionSeconds, computeActiveEmodePairs, computeAssetHealthComponent, computeAssetUsdValue, computeBalancePremium, computeBalanceUsdValue, computeBankAvailableLiquidity, computeBankBorrowApy, computeBankBorrowCapRemaining, computeBankDepositCapRemaining, computeBankMetrics, computeBankPoolSize, computeBankProjectedAvailableLiquidity, computeBankRateLimitRemaining, computeBankSupplyApy, computeBankTotalBorrows, computeBankTotalBorrowsUsd, computeBankTotalDeposits, computeBankTotalDepositsUsd, computeBaseInterestRate, computeBorrowEstimateForRepay, computeClosePositionTokenAmount, computeEmodeImpacts, computeFlashLoanNonSwapBudget, computeFlashloanSwapConstraints, computeFreeCollateralFromBalances, computeFreeCollateralFromCache, computeGroupRateLimitRemainingUsd, computeHealthAccountMetas, computeHealthCacheStatus, computeHealthCheckAccounts, computeHealthComponentsFromBalances, computeHealthComponentsFromCache, computeInterestRates, computeLiabilityHealthComponent, computeLiabilityUsdValue, computeLiquidationPriceForBank, computeLoopingParams, computeLowestEmodeWeights, computeMaxBorrowForBank, computeMaxDepositForBank, computeMaxLeverage, computeMaxWithdrawForBank, computeNetApy, computeOracleMultiplier, computeOracleMultipliers, computePremiumImpact, computePremiumRatesByBank, computeProjectedActiveBalancesNoCpi, computeProjectedActiveBanksNoCpi, computePtMultiplier, computeQuantity, computeQuantityUi, computeRateLimitWindowRemainingCapacity, computeRateLimiterRemainingCapacity, computeRemainingCapacity, computeStakedBankMultipliers, computeTvl, computeUsdValue, computeUtilizationRate, computeV0TxSize, computeVenueAvailableLiquidity, configureScopeOracleIx, convertVoteAccCoeffsToBankCoeffs, createActiveEmodePairFromPairs, createEmptyBalance, decodeAccountRaw, decodeBankRaw, decodeInstruction, decodeMultiplierAccount, decompileV0Transaction, deriveBankEmissionsAuth, deriveBankEmissionsVault, deriveBankFeeVault, deriveBankFeeVaultAuthority, deriveBankInsuranceVault, deriveBankInsuranceVaultAuthority, deriveBankLiquidityVault, deriveBankLiquidityVaultAuthority, deriveFeeState, deriveMarginfiAccount, deriveRebalanceFeePool, deserializeInstruction, deserializeLut, deserializeSwapEngineRequest, deserializeSwapEngineResult, dtoToBalance, dtoToBank, dtoToBankConfig, dtoToBankConfigRaw, dtoToBankMetadata, dtoToBankMetadataMap, dtoToBankRateLimiter, dtoToBankRateLimiterRaw, dtoToBankRaw, dtoToEmodeSettings, dtoToEmodeSettingsRaw, dtoToGroup, dtoToHealthCache, dtoToInterestRateConfig, dtoToMarginfiAccount, dtoToOraclePrice, dtoToValidatorStakeGroup, emodeSettingsRawToDto, extractPythOracleKeys, fetchBank, fetchBankIntegrationMetadata, fetchGammaLpVault, fetchGammaWithdrawReceipt, fetchMarginfiAccountActiveBalancesForBank, fetchMarginfiAccountAddresses, fetchMarginfiAccountAddressesHoldingBank, fetchMarginfiAccountData, fetchMultipleBanks, fetchMultiplierAccountStates, fetchMultiplierAccountStatesFromAPI, fetchNativeStakeAccounts, fetchOracleData, fetchOracleMultipliers, fetchOracleMultipliersFromAPI, fetchOracleMultipliersFromChain, fetchProgramForMints, fetchPythOracleData, fetchPythOraclePricesFromAPI, fetchPythOraclePricesFromChain, fetchScopeOracleData, fetchScopeOraclePricesFromAPI, fetchScopeOraclePricesFromChain, fetchStakeAccount, fetchStakePoolActiveStates, fetchStakePoolMev, findRandomAvailableAccountIndex, freezeBankConfigIx, generateDummyAccount, getAccountKeys, getActiveAccountFlags, getActiveBalances, getActiveEmodeEntryFlags, getActiveEmodeFlags, getActiveHealthCacheFlags, getAssetQuantity, getAssetShares, getAssetWeight, getBalance, getBalanceUsdValueWithPriceBias, getBankVaultAuthority, getBankVaultSeeds, getBirdeyeFallbackPricesByFeedId, getBirdeyePricesForMints, getConfig, getDriftCTokenMultiplier, getDriftMetadata, getDriftStatesDto, getEffectiveDepositLimit, getEmodePairs, getExactOutEstimate, getFallbackPricesByFeedId, getFallbackPricesForMints, getHealthCacheStatusDescription, getHealthSimulationTransactions, getJupLendFTokenMultiplier, getJupLendMetadata, getJupLendStatesDto, getJupiterReferralFeeAccount, getJupiterSwapIxsForFlashloan, getKaminoCTokenMultiplier, getKaminoMetadata, getKaminoStatesDto, getLiabilityQuantity, getLiabilityShares, getLiabilityWeight, getOracleMultiplierBankInput, getOracleSourceFromBank, getOracleSourceFromOracleSetup, getOracleSourceNameFromKey, getPrice, getPriceWithConfidence, getStakedBankMetadataMap, getSwapAdapter, getSwapIxsForFlashloan, getTitanExactOutEstimate, getTitanSwapIxsForFlashloan, getTotalAccountKeys, getTotalAssetQuantity, getTotalLiabilityQuantity, getTxSize, getValidatorVoteAccountByBank, getWritableAccountKeys, groupToDto, hasAccountFlag, hasEmodeEntryFlag, hasEmodeFlag, hasHealthCacheFlag, healthCacheToDto, isBorrowLimitActive, isBridgeConflictError, isDecomposableSwapError, isDepositIx, isDepositLimitActive, isFlashloan, isGroupRateLimiterEnabled, isStandardBorrowable, isStandardDepositable, isV0Tx, isWeightedPrice, isWholePosition, makeAccountTransferToNewAccountTx, makeAddPermissionlessStakedBankIx, makeBeginFlashLoanIx3 as makeBeginFlashLoanIx, makeBorrowIx3 as makeBorrowIx, makeBorrowTx, makeBridgedLoopTx, makeBridgedSwapCollateralTx, makeBridgedSwapDebtTx, makeBulkRepayTx, makeBulkWithdrawTx, makeBundleTipIx, makeCloseMarginfiAccountIx, makeCloseMarginfiAccountTx, makeCreateAccountIxWithProjection, makeCreateAccountTxWithProjection, makeCreateMarginfiAccountIx, makeCreateMarginfiAccountTx, makeDepositIx3 as makeDepositIx, makeDepositTx, makeDriftDepositIx3 as makeDriftDepositIx, makeDriftDepositTx, makeDriftWithdrawIx3 as makeDriftWithdrawIx, makeDriftWithdrawTx, makeEndFlashLoanIx3 as makeEndFlashLoanIx, makeFlashLoanTx, makeJuplendDepositIx2 as makeJuplendDepositIx, makeJuplendDepositTx, makeJuplendWithdrawIx2 as makeJuplendWithdrawIx, makeJuplendWithdrawTx, makeKaminoDepositIx3 as makeKaminoDepositIx, makeKaminoDepositTx, makeKaminoWithdrawIx3 as makeKaminoWithdrawIx, makeKaminoWithdrawTx, makeLoopTx, makeMergeStakeAccountsTx, makeMintStakedLstIx, makeMintStakedLstTx, makePoolAddBankIx3 as makePoolAddBankIx, makePoolConfigureBankIx3 as makePoolConfigureBankIx, makePremiumRefreshIxs, makePriorityFeeIx, makePriorityFeeMicroIx, makePulseHealthIx3 as makePulseHealthIx, makeRedeemStakedLstIx, makeRedeemStakedLstTx, makeRefreshIntegrationBanksIxs, makeRefreshKaminoBanksIxs, makeRepayIx3 as makeRepayIx, makeRepayTx, makeRepayWithCollatTx, makeRollPtTx, makeSetupIx, makeSwapCollateralTx, makeSwapDebtTx, makeTransferPositionsTx, makeTxPriorityIx, makeUnwrapSolIx, makeUpdateDriftMarketIxs, makeUpdateJupLendRateIxs, makeVaultCompleteWithdrawalIx, makeVaultCompleteWithdrawalTx, makeVaultDepositIx, makeVaultDepositTx, makeVaultDepositWithSwapTx, makeVaultWithdrawIx, makeVaultWithdrawTx, makeVersionedTransaction, makeWithdrawIx3 as makeWithdrawIx, makeWithdrawTx, makeWrapSolIxs, mapJupiterQuoteToSwapQuoteResult, mapPythBanksToOraclePrices, marginfiAccountToDto, mergeBridgeQuotes, mergeBridgeQuotesDebt, mergeBridgeQuotesLoop, nativeToUi, needsPremiumRefresh, oraclePriceToDto, parseBalanceRaw, parseBankConfigRaw, parseBankRateLimiterRaw, parseBankRaw, parseEmodeSettingsRaw, parseEmodeTag, parseHealthCacheRaw, parseMarginfiAccountRaw, parseOperationalState, parseOracleSetup, parseOraclePriceData as parsePriceInfo, parseRiskTier, parseRpcPythPriceData, patchDepositAmount, rateFromU32, requireBank, requireTokenProgram, resolveAmount, resolveBridgeCandidateBanks, resolvePinnedSwapRoute, resolveTokenProgramForMint, resolveVaultTokenProgram, runSwapEngine, selectLutsForAccountAction, selectLutsForBanks, selectSwapBridges, serializeBankConfigOpt, serializeInstruction, serializeInterestRateConfig, serializeLut, serializeOperationalState, serializeOracleSetup, serializeOracleSetupToIndex, serializeRiskTier, serializeSwapEngineRequest, serializeSwapEngineResult, setOraclePriceIx, sharedBridgeLegContext, shortenAddress, simulateAccountHealthCache, simulateAccountHealthCacheWithFallback, simulateBundle, splitInstructionsToFitTransactions, swapEngineProvidersFromOpts, swapEngineQuoteFieldsFromOpts, toBankConfigDto, toBankDto, toBankRateLimiterDto, toBigNumber, toEmodeSettingsDto, toInterestRateConfigDto, toJupiterConfig, toNumber, tryBridgeCandidates, uiToNative, uiToNativeBigNumber, validatorStakeGroupToDto, wrappedI80F48toBigNumber };
89661
+ export { ADDRESS_LOOKUP_TABLE_FOR_GROUP, ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE, ADDRESS_LOOKUP_TABLE_FOR_SWAP, AccountFlags, AccountType, AssetTag, BUNDLE_TX_SIZE, Balance, Bank, BankConfig, BankConfigFlag, BankVaultType, DEFAULT_BRIDGE_MINTS, DEFAULT_ORACLE_MAX_AGE, DEFAULT_REPAY_ALL_EXTRA_BUFFER_BPS, DISABLED_FLAG, EMPTY_HEALTH_CACHE, EXECUTION_HEADROOM_SECONDS, EmodeEntryFlags, EmodeFlags, EmodeImpactStatus, EmodeSettings, EmodeTag, FLASHLOAN_ENABLED_FLAG, HOURS_PER_YEAR, HealthCache, HealthCacheFlags, HealthCacheSimulationError, HealthCacheStatus, JUPITER_V6_PROGRAM, JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX, KAMINO_MARKET_EMERGENCY_FLAG, LST_MINT, MARGINFI_IDL, MARGINFI_PROGRAM, MARGINFI_PROGRAM_STAGING, MARGINFI_PROGRAM_STAGING_ALT, MARGINFI_SPONSORED_SHARD_ID, MAX_ACCOUNT_LOCKS, MAX_CONFIDENCE_INTERVAL_RATIO, MAX_COSTLY_POSITIONS, MAX_TX_SIZE, MAX_U64, MPL_METADATA_PROGRAM_ID, MarginRequirementType, MarginfiAccount, MarginfiAccountWrapper, MarginfiGroup, OperationalState, OracleSetup, PDA_BANK_EMISSIONS_AUTH_SEED, PDA_BANK_EMISSIONS_VAULT_SEED, PDA_BANK_FEE_STATE_SEED, PDA_BANK_FEE_VAULT_AUTH_SEED, PDA_BANK_FEE_VAULT_SEED, PDA_BANK_INSURANCE_VAULT_AUTH_SEED, PDA_BANK_INSURANCE_VAULT_SEED, PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED, PDA_BANK_LIQUIDITY_VAULT_SEED, PDA_MARGINFI_ACCOUNT_SEED, PDA_ORDER_SEED, PDA_REBALANCE_FEE_POOL_SEED, PREMIUM_ACTIVE_FLAG, PRIORITY_TX_SIZE, PYTH_PRICE_CONF_INTERVALS, PYTH_PUSH_ORACLE_ID, PYTH_SPONSORED_SHARD_ID, PriceBias, Project0Client, RiskTier, SECONDS_PER_YEAR, SINGLE_POOL_PROGRAM_ID, STAKED_ORACLE_DISABLED_FLAG, STAKED_ORACLE_USES_ONRAMP_FLAG, STAKE_CONFIG_ID, STAKE_PROGRAM_ID, SWAP_ADAPTERS, SYSTEM_PROGRAM_ID, SYSVAR_CLOCK_ID, SYSVAR_RENT_ID, SYSVAR_STAKE_HISTORY_ID, SwapProvider, TRANSFER_ACCOUNT_AUTHORITY_FLAG, TransactionArenaKeyMap, TransactionBuildingError, TransactionBuildingErrorCode, TransactionConfigMap, TransactionType, U64_MAX2 as U64_MAX, USDC_DECIMALS, USDC_MINT, USDT_MINT, VENUE_AVAILABLE_LIQUIDITY_BUFFER, WSOL_MINT, ZERO_ORACLE_KEY, accountConflictsWithBridgeBank, accountFlagToBN, addOracleToBanksIx, addTransactionMetadata, adjustPriceComponent, appendPremiumRefresh, aprToApy, apyToApr, balanceToDto, bankConfigRawToDto, bankConfigToBankConfigRaw, bankMetadataMapToDto, bankMetadataToDto, bankRateLimiterRawToDto, bankRawToDto, bigNumberToWrappedI80F48, bpsToPercentile, buildCollateralLegIxs, buildOrderTrigger, calculateApyFromInterest, calculateInterestFromApy, capConfidenceInterval, categorizePythBanks, checkJupiterFeeAccount, checkTitanFeeAccount, chunkedGetRawMultipleAccountInfoOrdered, chunkedGetRawMultipleAccountInfoOrderedWithNulls, chunkedGetRawMultipleAccountInfos, classifyAndValidate, compileFlashloanPrecheck, composeBridgedSwap, composeRemainingAccounts, computeAccountValue, computeAccrualProjectionSeconds, computeActiveEmodePairs, computeAssetHealthComponent, computeAssetUsdValue, computeBalancePremium, computeBalanceUsdValue, computeBankAvailableLiquidity, computeBankBorrowApy, computeBankBorrowCapRemaining, computeBankDepositCapRemaining, computeBankMetrics, computeBankOutflowRateLimit, computeBankPoolSize, computeBankProjectedAvailableLiquidity, computeBankRateLimitRemaining, computeBankSupplyApy, computeBankTotalBorrows, computeBankTotalBorrowsUsd, computeBankTotalDeposits, computeBankTotalDepositsUsd, computeBaseInterestRate, computeBorrowEstimateForRepay, computeClosePositionTokenAmount, computeEmodeImpacts, computeFlashLoanNonSwapBudget, computeFlashloanSwapConstraints, computeFreeCollateralFromBalances, computeFreeCollateralFromCache, computeGroupRateLimitRemainingUsd, computeHealthAccountMetas, computeHealthCacheStatus, computeHealthCheckAccounts, computeHealthComponentsFromBalances, computeHealthComponentsFromCache, computeInterestRates, computeLiabilityHealthComponent, computeLiabilityUsdValue, computeLiquidationPriceForBank, computeLoopingParams, computeLowestEmodeWeights, computeMaxBorrowForBank, computeMaxDepositForBank, computeMaxLeverage, computeMaxWithdrawForBank, computeNetApy, computeOracleMultiplier, computeOracleMultipliers, computeOrderPairNetValue, computePremiumBreakdown, computePremiumImpact, computePremiumRatesByBank, computeProjectedActiveBalancesNoCpi, computeProjectedActiveBanksNoCpi, computePtMultiplier, computeQuantity, computeQuantityUi, computeRateLimitWindowRemainingCapacity, computeRateLimiterRemainingCapacity, computeRemainingCapacity, computeStakedBankMultipliers, computeTvl, computeUsdValue, computeUtilizationRate, computeV0TxSize, computeVenueAvailableLiquidity, configureScopeOracleIx, convertVoteAccCoeffsToBankCoeffs, createActiveEmodePairFromPairs, createEmptyBalance, decodeAccountRaw, decodeBankRaw, decodeInstruction, decodeMultiplierAccount, decompileV0Transaction, deriveBankEmissionsAuth, deriveBankEmissionsVault, deriveBankFeeVault, deriveBankFeeVaultAuthority, deriveBankInsuranceVault, deriveBankInsuranceVaultAuthority, deriveBankLiquidityVault, deriveBankLiquidityVaultAuthority, deriveFeeState, deriveMarginfiAccount, deriveOrderPda, deriveRebalanceFeePool, deserializeInstruction, deserializeLut, deserializeSwapEngineRequest, deserializeSwapEngineResult, dtoToBalance, dtoToBank, dtoToBankConfig, dtoToBankConfigRaw, dtoToBankMetadata, dtoToBankMetadataMap, dtoToBankRateLimiter, dtoToBankRateLimiterRaw, dtoToBankRaw, dtoToEmodeSettings, dtoToEmodeSettingsRaw, dtoToGroup, dtoToHealthCache, dtoToInterestRateConfig, dtoToMarginfiAccount, dtoToOraclePrice, dtoToValidatorStakeGroup, emodeSettingsRawToDto, exceedsCostlyPositionLimit, extractPythOracleKeys, fetchBank, fetchBankIntegrationMetadata, fetchGammaLpVault, fetchGammaWithdrawReceipt, fetchMarginfiAccountActiveBalancesForBank, fetchMarginfiAccountAddresses, fetchMarginfiAccountAddressesHoldingBank, fetchMarginfiAccountData, fetchMultipleBanks, fetchMultiplierAccountStates, fetchMultiplierAccountStatesFromAPI, fetchNativeStakeAccounts, fetchOracleData, fetchOracleMultipliers, fetchOracleMultipliersFromAPI, fetchOracleMultipliersFromChain, fetchOrderFees, fetchOrdersForAccount, fetchProgramForMints, fetchPythOracleData, fetchPythOraclePricesFromAPI, fetchPythOraclePricesFromChain, fetchScopeOracleData, fetchScopeOraclePricesFromAPI, fetchScopeOraclePricesFromChain, fetchStakeAccount, fetchStakePoolActiveStates, fetchStakePoolMev, findRandomAvailableAccountIndex, fitsInOneTransaction, freezeBankConfigIx, generateDummyAccount, getAccountKeys, getActiveAccountFlags, getActiveBalances, getActiveEmodeEntryFlags, getActiveEmodeFlags, getActiveHealthCacheFlags, getAssetQuantity, getAssetShares, getAssetWeight, getBalance, getBalanceUsdValueWithPriceBias, getBankVaultAuthority, getBankVaultSeeds, getBirdeyeFallbackPricesByFeedId, getBirdeyePricesForMints, getConfig, getDriftCTokenMultiplier, getDriftMetadata, getDriftStatesDto, getEffectiveDepositLimit, getEmodePairs, getExactOutEstimate, getFallbackPricesByFeedId, getFallbackPricesForMints, getHealthCacheStatusDescription, getHealthSimulationTransactions, getJupLendFTokenMultiplier, getJupLendMetadata, getJupLendStatesDto, getJupiterReferralFeeAccount, getJupiterSwapIxsForFlashloan, getKaminoCTokenMultiplier, getKaminoMetadata, getKaminoStatesDto, getLiabilityQuantity, getLiabilityShares, getLiabilityWeight, getOracleMultiplierBankInput, getOracleSourceFromBank, getOracleSourceFromOracleSetup, getOracleSourceNameFromKey, getPrice, getPriceWithConfidence, getStakedBankMetadataMap, getSwapAdapter, getSwapIxsForFlashloan, getTitanExactOutEstimate, getTitanSwapIxsForFlashloan, getTotalAccountKeys, getTotalAssetQuantity, getTotalLiabilityQuantity, getTxSize, getValidatorVoteAccountByBank, getWritableAccountKeys, groupToDto, hasAccountFlag, hasEmodeEntryFlag, hasEmodeFlag, hasHealthCacheFlag, healthCacheToDto, isBorrowLimitActive, isBridgeConflictError, isCostlyBank, isDecomposableSwapError, isDepositIx, isDepositLimitActive, isFlashloan, isGroupRateLimiterEnabled, isStandardBorrowable, isStandardDepositable, isV0Tx, isWeightedPrice, isWholePosition, makeAccountTransferToNewAccountTx, makeAddPermissionlessStakedBankIx, makeBeginFlashLoanIx3 as makeBeginFlashLoanIx, makeBorrowIx3 as makeBorrowIx, makeBorrowTx, makeBridgedLoopTx, makeBridgedSwapCollateralTx, makeBridgedSwapDebtTx, makeBulkRepayTx, makeBulkWithdrawTx, makeBundleTipIx, makeCloseMarginfiAccountIx, makeCloseMarginfiAccountTx, makeCloseOrderIx2 as makeCloseOrderIx, makeCloseOrderTx, makeCreateAccountIxWithProjection, makeCreateAccountTxWithProjection, makeCreateMarginfiAccountIx, makeCreateMarginfiAccountTx, makeDepositIx3 as makeDepositIx, makeDepositTx, makeDriftDepositIx3 as makeDriftDepositIx, makeDriftDepositTx, makeDriftWithdrawIx3 as makeDriftWithdrawIx, makeDriftWithdrawTx, makeEndFlashLoanIx3 as makeEndFlashLoanIx, makeFlashLoanTx, makeJuplendDepositIx2 as makeJuplendDepositIx, makeJuplendDepositTx, makeJuplendWithdrawIx2 as makeJuplendWithdrawIx, makeJuplendWithdrawTx, makeKaminoDepositIx3 as makeKaminoDepositIx, makeKaminoDepositTx, makeKaminoWithdrawIx3 as makeKaminoWithdrawIx, makeKaminoWithdrawTx, makeLoopTx, makeMergeStakeAccountsTx, makeMintStakedLstIx, makeMintStakedLstTx, makePlaceOrderIx2 as makePlaceOrderIx, makePlaceOrderTx, makePoolAddBankIx2 as makePoolAddBankIx, makePoolConfigureBankGovIx2 as makePoolConfigureBankGovIx, makePoolConfigureBankIx2 as makePoolConfigureBankIx, makePreludeTxs, makePremiumRefreshIxs, makePriorityFeeIx, makePriorityFeeMicroIx, makePulseHealthIx3 as makePulseHealthIx, makeRedeemStakedLstIx, makeRedeemStakedLstTx, makeRefreshIntegrationBanksIxs, makeRefreshKaminoBanksIxs, makeRepayIx3 as makeRepayIx, makeRepayTx, makeRepayWithCollatTx, makeRollPtTx, makeSetupIx, makeSwapCollateralTx, makeSwapDebtTx, makeTransferPositionsTx, makeTxPriorityIx, makeUnwrapSolIx, makeUpdateDriftMarketIxs, makeUpdateJupLendRateIxs, makeUpdateOrderTx, makeVaultCompleteWithdrawalIx, makeVaultCompleteWithdrawalTx, makeVaultDepositIx, makeVaultDepositTx, makeVaultDepositWithSwapTx, makeVaultWithdrawIx, makeVaultWithdrawTx, makeVersionedTransaction, makeWithdrawIx3 as makeWithdrawIx, makeWithdrawTx, makeWrapSolIxs, mapJupiterQuoteToSwapQuoteResult, mapPythBanksToOraclePrices, marginfiAccountToDto, maxSlippageU32ToPercent, mergeBridgeQuotes, mergeBridgeQuotesDebt, mergeBridgeQuotesLoop, nativeToUi, needsPremiumRefresh, oraclePriceToDto, parseBalanceRaw, parseBankConfigRaw, parseBankRateLimiterRaw, parseBankRaw, parseEmodeSettingsRaw, parseEmodeTag, parseHealthCacheRaw, parseMarginfiAccountRaw, parseOperationalState, parseOracleSetup, parseOrderRaw, parseOraclePriceData as parsePriceInfo, parseRiskTier, parseRpcPythPriceData, patchDepositAmount, percentToMaxSlippageU32, rateFromU32, requireBank, requireTokenProgram, resolveAmount, resolveBridgeCandidateBanks, resolveOrderLegs, resolvePinnedSwapRoute, resolveTokenProgramForMint, resolveVaultTokenProgram, runSwapEngine, selectLutsForAccountAction, selectLutsForBanks, selectSwapBridges, serializeBankConfigOpt, serializeInstruction, serializeInterestRateConfig, serializeLut, serializeOperationalState, serializeOracleSetup, serializeOracleSetupToIndex, serializeRiskTier, serializeSwapEngineRequest, serializeSwapEngineResult, setOraclePriceIx, sharedBridgeLegContext, shortenAddress, simulateAccountHealthCache, simulateAccountHealthCacheWithFallback, simulateBundle, splitInstructionsToFitTransactions, swapEngineProvidersFromOpts, swapEngineQuoteFieldsFromOpts, toBankConfigDto, toBankDto, toBankRateLimiterDto, toBigNumber, toEmodeSettingsDto, toInterestRateConfigDto, toJupiterConfig, toNumber, tryBridgeCandidates, uiToNative, uiToNativeBigNumber, validatorStakeGroupToDto, withKaminoReserveEmergency, wrappedI80F48toBigNumber };
89279
89662
  //# sourceMappingURL=index.js.map
89280
89663
  //# sourceMappingURL=index.js.map