@0dotxyz/p0-ts-sdk 2.10.0-alpha.1 → 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(),
@@ -76555,6 +76699,23 @@ function getBalanceUsdValueWithPriceBias(params) {
76555
76699
  );
76556
76700
  return { assets: assetsValue, liabilities: liabilitiesValue };
76557
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
+ }
76558
76719
  function computeQuantity(balance, bank) {
76559
76720
  const assetsQuantity = getAssetQuantity(bank, balance.assetShares);
76560
76721
  const liabilitiesQuantity = getLiabilityQuantity(bank, balance.liabilityShares).plus(
@@ -76776,6 +76937,7 @@ function createEmptyBalance(bankPk) {
76776
76937
  const balance = {
76777
76938
  active: false,
76778
76939
  bankPk,
76940
+ tag: 0,
76779
76941
  assetShares: new BigNumber3(0),
76780
76942
  liabilityShares: new BigNumber3(0),
76781
76943
  premiumRate: new BigNumber3(0),
@@ -76790,6 +76952,18 @@ function getActiveBalances(balances) {
76790
76952
  function getBalance(bankAddress, balances) {
76791
76953
  return balances.filter((b) => b.active).find((b) => b.bankPk.equals(bankAddress)) ?? createEmptyBalance(bankAddress);
76792
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
+ }
76793
76967
  function computeAccountValue(marginfiAccount) {
76794
76968
  const { assets, liabilities } = computeHealthComponentsFromCache(
76795
76969
  marginfiAccount,
@@ -77055,6 +77229,7 @@ function computeProjectedActiveBalancesNoCpi({
77055
77229
  const projectedBalances = account.balances.map((b) => ({
77056
77230
  active: b.active,
77057
77231
  bankPk: b.bankPk,
77232
+ tag: b.tag,
77058
77233
  assetShares: new BigNumber3(b.assetShares),
77059
77234
  liabilityShares: new BigNumber3(b.liabilityShares),
77060
77235
  premiumRate: new BigNumber3(b.premiumRate),
@@ -77336,6 +77511,26 @@ var fetchMarginfiAccountData = async (program, marginfiAccountPk, banksMap, bank
77336
77511
  return { marginfiAccount };
77337
77512
  }
77338
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
+ };
77339
77534
  function randomDistinctIndices(count, maxExclusive) {
77340
77535
  const chosen = /* @__PURE__ */ new Set();
77341
77536
  while (chosen.size < count) {
@@ -77459,18 +77654,27 @@ function computeMaxBorrowForBank(params) {
77459
77654
  BigNumber3.min(healthMaxBorrow, borrowCapRemaining, availableLiquidity, rateLimitRemaining)
77460
77655
  );
77461
77656
  }
77462
- function computeOutflowRateLimitRemaining(bank, oraclePrice, groupRateLimiter, assetShareValueMultiplier) {
77657
+ function computeBankOutflowRateLimit(bank, assetShareValueMultiplier) {
77658
+ if (!bank.rateLimiter) return null;
77463
77659
  const nowSeconds = Date.now() / 1e3;
77464
- let remaining = new BigNumber3(Infinity);
77465
- let bankRemaining = computeBankRateLimitRemaining(bank, nowSeconds);
77466
- if (bankRemaining !== null) {
77467
- const limiterInBankMintUnits = bank.config.assetTag === 3 /* KAMINO */ || bank.config.assetTag === 2 /* STAKED */;
77468
- if (limiterInBankMintUnits && assetShareValueMultiplier?.gt(0)) {
77469
- bankRemaining = bankRemaining.times(assetShareValueMultiplier);
77470
- }
77471
- 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 };
77472
77672
  }
77473
- 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);
77474
77678
  if (groupRemainingUsd !== null) {
77475
77679
  const price = getPrice(oraclePrice, 1 /* None */, false);
77476
77680
  if (price.gt(0)) remaining = BigNumber3.min(remaining, groupRemainingUsd.div(price));
@@ -78335,6 +78539,26 @@ function isWholePosition(position, amount, mintDecimals) {
78335
78539
  const closePositionTokenAmount = computeClosePositionTokenAmount(position, mintDecimals);
78336
78540
  return amount >= closePositionTokenAmount;
78337
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
+ }
78338
78562
  var KAMINO_PROGRAM_ID = new PublicKey("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD");
78339
78563
  var FARMS_PROGRAM_ID2 = new PublicKey("FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr");
78340
78564
  function encodeU642(value) {
@@ -78347,11 +78571,6 @@ function encodeU8(value) {
78347
78571
  buf.writeUInt8(value, 0);
78348
78572
  return buf;
78349
78573
  }
78350
- function encodeU16(value) {
78351
- const buf = Buffer.alloc(2);
78352
- buf.writeUInt16LE(value, 0);
78353
- return buf;
78354
- }
78355
78574
  function encodeBool(value) {
78356
78575
  const buf = Buffer.alloc(1);
78357
78576
  buf.writeUInt8(value ? 1 : 0, 0);
@@ -78369,9 +78588,6 @@ function encodeOptionU8(value) {
78369
78588
  }
78370
78589
  return Buffer.concat([Buffer.from([1]), encodeU8(value)]);
78371
78590
  }
78372
- function encodePublicKey(pubkey) {
78373
- return Buffer.from(pubkey.toBytes());
78374
- }
78375
78591
  var DISCRIMINATORS = {
78376
78592
  MARGINFI_ACCOUNT_INITIALIZE: Buffer.from([43, 78, 61, 255, 148, 52, 249, 154]),
78377
78593
  KAMINO_DEPOSIT: Buffer.from([237, 8, 188, 187, 115, 99, 49, 85]),
@@ -78381,16 +78597,11 @@ var DISCRIMINATORS = {
78381
78597
  LENDING_ACCOUNT_WITHDRAW: Buffer.from([36, 72, 74, 19, 210, 210, 192, 192]),
78382
78598
  LENDING_ACCOUNT_BORROW: Buffer.from([4, 126, 116, 53, 48, 5, 212, 31]),
78383
78599
  LENDING_ACCOUNT_LIQUIDATE: Buffer.from([214, 169, 151, 213, 251, 167, 86, 219]),
78384
- LENDING_POOL_ADD_BANK: Buffer.from([215, 68, 72, 78, 208, 218, 103, 182]),
78385
- LENDING_POOL_CONFIGURE_BANK: Buffer.from([121, 173, 156, 40, 93, 148, 56, 237]),
78386
78600
  LENDING_ACCOUNT_START_FLASHLOAN: Buffer.from([14, 131, 33, 220, 81, 186, 180, 107]),
78387
78601
  LENDING_ACCOUNT_END_FLASHLOAN: Buffer.from([105, 124, 201, 106, 153, 2, 8, 156]),
78388
78602
  TRANSFER_TO_NEW_ACCOUNT: Buffer.from([28, 79, 129, 231, 169, 69, 69, 65]),
78389
- MARGINFI_GROUP_INITIALIZE: Buffer.from([255, 67, 67, 26, 94, 31, 34, 20]),
78390
78603
  MARGINFI_ACCOUNT_CLOSE: Buffer.from([186, 221, 93, 34, 50, 97, 194, 241]),
78391
78604
  LENDING_POOL_ADD_BANK_PERMISSIONLESS: Buffer.from([127, 187, 121, 34, 187, 167, 238, 102]),
78392
- LENDING_POOL_CONFIGURE_BANK_ORACLE: Buffer.from([209, 82, 255, 171, 124, 21, 71, 81]),
78393
- LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE: Buffer.from([134, 228, 127, 3, 117, 132, 85, 146]),
78394
78605
  LENDING_ACCOUNT_PULSE_HEALTH: Buffer.from([186, 52, 117, 97, 34, 74, 39, 253]),
78395
78606
  LENDING_ACCOUNT_SORT_BALANCES: Buffer.from([187, 194, 110, 84, 82, 170, 204, 9]),
78396
78607
  DRIFT_DEPOSIT: Buffer.from([252, 63, 250, 201, 98, 55, 130, 12]),
@@ -78784,103 +78995,6 @@ function makeAccountTransferToNewAccountIx2(programId, accounts) {
78784
78995
  data: DISCRIMINATORS.TRANSFER_TO_NEW_ACCOUNT
78785
78996
  });
78786
78997
  }
78787
- function makeGroupInitIx2(programId, accounts, args) {
78788
- const keys = [
78789
- { pubkey: accounts.marginfiGroup, isSigner: true, isWritable: true },
78790
- { pubkey: accounts.admin, isSigner: true, isWritable: true },
78791
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78792
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
78793
- ];
78794
- const data = Buffer.concat([
78795
- DISCRIMINATORS.MARGINFI_GROUP_INITIALIZE,
78796
- encodeBool(args?.isArenaGroup ?? false)
78797
- ]);
78798
- return new TransactionInstruction({
78799
- keys,
78800
- programId,
78801
- data
78802
- });
78803
- }
78804
- function makePoolConfigureBankIx2(programId, accounts, _args) {
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
- return new TransactionInstruction({
78811
- keys,
78812
- programId,
78813
- data: DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK
78814
- });
78815
- }
78816
- function makeLendingPoolConfigureBankOracleIx2(programId, accounts, args, remainingAccounts = []) {
78817
- const keys = [
78818
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78819
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78820
- { pubkey: accounts.bank, isSigner: false, isWritable: true }
78821
- ];
78822
- keys.push(...remainingAccounts);
78823
- const data = Buffer.concat([
78824
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE,
78825
- encodeU8(args.setup),
78826
- encodePublicKey(args.feedId)
78827
- ]);
78828
- return new TransactionInstruction({
78829
- keys,
78830
- programId,
78831
- data
78832
- });
78833
- }
78834
- function makeLendingPoolConfigureBankOracleScopeIx2(programId, accounts, args) {
78835
- const keys = [
78836
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78837
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78838
- { pubkey: accounts.bank, isSigner: false, isWritable: true },
78839
- { pubkey: args.oracle, isSigner: false, isWritable: false }
78840
- ];
78841
- const data = Buffer.concat([
78842
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE,
78843
- encodePublicKey(args.oracle),
78844
- encodeU16(args.entryIndex)
78845
- ]);
78846
- return new TransactionInstruction({
78847
- keys,
78848
- programId,
78849
- data
78850
- });
78851
- }
78852
- function makePoolAddBankIx2(programId, accounts, _args) {
78853
- const keys = [
78854
- { pubkey: accounts.marginfiGroup, isSigner: false, isWritable: true },
78855
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78856
- { pubkey: accounts.feePayer, isSigner: true, isWritable: true },
78857
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78858
- { pubkey: accounts.globalFeeWallet, isSigner: false, isWritable: true },
78859
- { pubkey: accounts.bankMint, isSigner: false, isWritable: false },
78860
- { pubkey: accounts.bank, isSigner: true, isWritable: true },
78861
- {
78862
- pubkey: accounts.liquidityVaultAuthority,
78863
- isSigner: false,
78864
- isWritable: false
78865
- },
78866
- { pubkey: accounts.liquidityVault, isSigner: false, isWritable: true },
78867
- {
78868
- pubkey: accounts.insuranceVaultAuthority,
78869
- isSigner: false,
78870
- isWritable: false
78871
- },
78872
- { pubkey: accounts.insuranceVault, isSigner: false, isWritable: true },
78873
- { pubkey: accounts.feeVaultAuthority, isSigner: false, isWritable: false },
78874
- { pubkey: accounts.feeVault, isSigner: false, isWritable: true },
78875
- { pubkey: accounts.tokenProgram, isSigner: false, isWritable: false },
78876
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
78877
- ];
78878
- return new TransactionInstruction({
78879
- keys,
78880
- programId,
78881
- data: DISCRIMINATORS.LENDING_POOL_ADD_BANK
78882
- });
78883
- }
78884
78998
  function makeDriftDepositIx2(programId, accounts, args) {
78885
78999
  const liquidityVaultAuthority = deriveBankLiquidityVaultAuthority(programId, accounts.bank)[0];
78886
79000
  const keys = [
@@ -79059,16 +79173,11 @@ var syncInstructions = {
79059
79173
  makeKaminoWithdrawIx: makeKaminoWithdrawIx2,
79060
79174
  makeBorrowIx: makeBorrowIx2,
79061
79175
  makeLendingAccountLiquidateIx: makeLendingAccountLiquidateIx2,
79062
- makePoolAddBankIx: makePoolAddBankIx2,
79063
- makePoolConfigureBankIx: makePoolConfigureBankIx2,
79064
79176
  makeBeginFlashLoanIx: makeBeginFlashLoanIx2,
79065
79177
  makeEndFlashLoanIx: makeEndFlashLoanIx2,
79066
79178
  makeAccountTransferToNewAccountIx: makeAccountTransferToNewAccountIx2,
79067
- makeGroupInitIx: makeGroupInitIx2,
79068
79179
  makeCloseAccountIx: makeCloseAccountIx2,
79069
79180
  makePoolAddPermissionlessStakedBankIx: makePoolAddPermissionlessStakedBankIx2,
79070
- makeLendingPoolConfigureBankOracleIx: makeLendingPoolConfigureBankOracleIx2,
79071
- makeLendingPoolConfigureBankOracleScopeIx: makeLendingPoolConfigureBankOracleScopeIx2,
79072
79181
  makePulseHealthIx: makePulseHealthIx2
79073
79182
  };
79074
79183
  var sync_instructions_default = syncInstructions;
@@ -79268,6 +79377,9 @@ async function makeDriftDepositIx3({
79268
79377
  }
79269
79378
  async function makeDriftDepositTx(params) {
79270
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
+ }
79271
79383
  if (!depositIxParams.bank.driftIntegrationAccounts) {
79272
79384
  throw new Error("Bank has no drift integration accounts");
79273
79385
  }
@@ -79275,13 +79387,17 @@ async function makeDriftDepositTx(params) {
79275
79387
  amount,
79276
79388
  ...depositIxParams
79277
79389
  });
79278
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79279
- 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
+ );
79280
79396
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79281
79397
  const depositTx = addTransactionMetadata(
79282
79398
  new VersionedTransaction(
79283
79399
  new TransactionMessage({
79284
- instructions: [...depositIxs.instructions, ...premiumIxs],
79400
+ instructions: instructions2,
79285
79401
  payerKey: params.authority,
79286
79402
  recentBlockhash: blockhash
79287
79403
  }).compileToV0Message(selectedLuts)
@@ -79387,6 +79503,9 @@ async function makeKaminoDepositIx3({
79387
79503
  }
79388
79504
  async function makeKaminoDepositTx(params) {
79389
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
+ }
79390
79509
  if (!depositIxParams.bank.kaminoIntegrationAccounts) {
79391
79510
  throw new Error("Bank has no kamino integration accounts");
79392
79511
  }
@@ -79411,13 +79530,17 @@ async function makeKaminoDepositTx(params) {
79411
79530
  amount,
79412
79531
  ...depositIxParams
79413
79532
  });
79414
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79415
- 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
+ );
79416
79539
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79417
79540
  const depositTx = addTransactionMetadata(
79418
79541
  new VersionedTransaction(
79419
79542
  new TransactionMessage({
79420
- instructions: [...refreshIxs, ...depositIxs.instructions, ...premiumIxs],
79543
+ instructions: instructions2,
79421
79544
  payerKey: params.authority,
79422
79545
  recentBlockhash: blockhash
79423
79546
  }).compileToV0Message(selectedLuts)
@@ -79494,10 +79617,17 @@ async function makeDepositIx3({
79494
79617
  }
79495
79618
  async function makeDepositTx(params) {
79496
79619
  const { luts, ...depositIxParams } = params;
79620
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79621
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79622
+ }
79497
79623
  const ixs = await makeDepositIx3(depositIxParams);
79498
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79499
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79500
- 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);
79501
79631
  tx.feePayer = params.authority;
79502
79632
  const solanaTx = addTransactionMetadata(tx, {
79503
79633
  type: "DEPOSIT" /* DEPOSIT */,
@@ -79573,6 +79703,9 @@ async function makeJuplendDepositIx2({
79573
79703
  }
79574
79704
  async function makeJuplendDepositTx(params) {
79575
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
+ }
79576
79709
  if (!depositIxParams.bank.jupLendIntegrationAccounts) {
79577
79710
  throw new Error("Bank has no JupLend integration accounts");
79578
79711
  }
@@ -79580,13 +79713,17 @@ async function makeJuplendDepositTx(params) {
79580
79713
  amount,
79581
79714
  ...depositIxParams
79582
79715
  });
79583
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79584
- 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
+ );
79585
79722
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79586
79723
  const depositTx = addTransactionMetadata(
79587
79724
  new VersionedTransaction(
79588
79725
  new TransactionMessage({
79589
- instructions: [...depositIxs.instructions, ...premiumIxs],
79726
+ instructions: instructions2,
79590
79727
  payerKey: params.authority,
79591
79728
  recentBlockhash: blockhash
79592
79729
  }).compileToV0Message(selectedLuts)
@@ -80858,9 +80995,13 @@ async function makeRepayTx(params) {
80858
80995
  const { luts, ...repayIxParams } = params;
80859
80996
  const ixs = await makeRepayIx3(repayIxParams);
80860
80997
  const closedBanks = params.repayAll ? [params.bank.address] : [];
80861
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, closedBanks) ? await makePremiumRefreshIxs(params.program, params, [], closedBanks) : [];
80862
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
80863
- 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);
80864
81005
  tx.feePayer = params.authority;
80865
81006
  const solanaTx = addTransactionMetadata(tx, {
80866
81007
  type: "REPAY" /* REPAY */,
@@ -80918,23 +81059,11 @@ async function makeRepayWithCollatTx(params) {
80918
81059
  return true;
80919
81060
  });
80920
81061
  setupIxs.push(...jupiterSetupInstructions);
80921
- const additionalTxs = [];
80922
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
80923
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
80924
- const txs = splitInstructionsToFitTransactions([], ixs, {
80925
- blockhash,
80926
- payerKey: marginfiAccount.authority,
80927
- luts: addressLookupTableAccounts ?? []
80928
- });
80929
- additionalTxs.push(
80930
- ...txs.map(
80931
- (tx) => addTransactionMetadata(tx, {
80932
- type: "CREATE_ATA" /* CREATE_ATA */,
80933
- addressLookupTables: addressLookupTableAccounts
80934
- })
80935
- )
80936
- );
80937
- }
81062
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
81063
+ blockhash,
81064
+ payerKey: marginfiAccount.authority,
81065
+ luts: addressLookupTableAccounts ?? []
81066
+ });
80938
81067
  const transactions = [...additionalTxs, flashloanTx];
80939
81068
  return {
80940
81069
  transactions,
@@ -81877,6 +82006,9 @@ async function makeAccountTransferToNewAccountTx({
81877
82006
  newAuthority,
81878
82007
  feePayer
81879
82008
  }) {
82009
+ if (marginfiAccount.accountFlags.includes(1 /* ACCOUNT_DISABLED */)) {
82010
+ throw TransactionBuildingError.accountDisabled(marginfiAccount.address.toBase58());
82011
+ }
81880
82012
  const feePayerKey = feePayer instanceof Keypair ? feePayer.publicKey : feePayer ?? marginfiAccount.authority;
81881
82013
  const [feeStateKey] = PublicKey.findProgramAddressSync(
81882
82014
  [Buffer.from("feestate", "utf-8")],
@@ -82068,13 +82200,21 @@ async function makePulseHealthIx3(program, marginfiAccount, banks, mandatoryBank
82068
82200
  return { instructions: [ix], keys: [] };
82069
82201
  }
82070
82202
  async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMetadataMap }, mandatoryBanks, excludedBanks) {
82071
- const refreshIxs = makeRefreshIntegrationBanksIxs(
82072
- marginfiAccount,
82073
- bankMap,
82074
- [],
82075
- bankMetadataMap,
82076
- mandatoryBanks
82077
- );
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
+ }
82078
82218
  const pulseIxs = await makePulseHealthIx3(
82079
82219
  program,
82080
82220
  marginfiAccount,
@@ -82082,13 +82222,38 @@ async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMe
82082
82222
  mandatoryBanks,
82083
82223
  excludedBanks
82084
82224
  );
82085
- 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;
82086
82250
  }
82087
82251
  function generateDummyAccount(group, authority, accountKey) {
82088
82252
  const dummyWrappedI80F48 = bigNumberToWrappedI80F48(new BigNumber3(0));
82089
82253
  const dummyBalances = Array(15).fill({
82090
82254
  active: false,
82091
82255
  bankPk: new PublicKey("11111111111111111111111111111111"),
82256
+ tag: 0,
82092
82257
  assetShares: dummyWrappedI80F48,
82093
82258
  liabilityShares: dummyWrappedI80F48,
82094
82259
  premiumRateSnapshot: 0,
@@ -82098,7 +82263,7 @@ function generateDummyAccount(group, authority, accountKey) {
82098
82263
  const rawAccount = {
82099
82264
  group,
82100
82265
  authority,
82101
- lendingAccount: { balances: dummyBalances },
82266
+ lendingAccount: { balances: dummyBalances, lastTagUsed: 0 },
82102
82267
  healthCache: {
82103
82268
  assetValue: {
82104
82269
  value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@@ -82120,14 +82285,15 @@ function generateDummyAccount(group, authority, accountKey) {
82120
82285
  mrgnErr: 0
82121
82286
  },
82122
82287
  emissionsDestinationAccount: new PublicKey("11111111111111111111111111111111"),
82123
- accountFlags: new BN8([0, 0, 0])
82288
+ accountFlags: new BN8([0, 0, 0]),
82289
+ activeOrders: 0
82124
82290
  };
82125
82291
  return parseMarginfiAccountRaw(accountKey, rawAccount);
82126
82292
  }
82127
82293
 
82128
82294
  // src/models/balance.ts
82129
82295
  var Balance = class _Balance {
82130
- constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate) {
82296
+ constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate, tag) {
82131
82297
  this.active = active;
82132
82298
  this.bankPk = bankPk;
82133
82299
  this.assetShares = assetShares;
@@ -82135,6 +82301,7 @@ var Balance = class _Balance {
82135
82301
  this.premiumRate = premiumRate;
82136
82302
  this.premiumOutstanding = premiumOutstanding;
82137
82303
  this.lastUpdate = lastUpdate;
82304
+ this.tag = tag;
82138
82305
  }
82139
82306
  static from(balanceRaw) {
82140
82307
  const props = parseBalanceRaw(balanceRaw);
@@ -82145,7 +82312,8 @@ var Balance = class _Balance {
82145
82312
  props.liabilityShares,
82146
82313
  props.premiumRate,
82147
82314
  props.premiumOutstanding,
82148
- props.lastUpdate
82315
+ props.lastUpdate,
82316
+ props.tag
82149
82317
  );
82150
82318
  }
82151
82319
  static fromBalanceType(balance) {
@@ -82156,7 +82324,8 @@ var Balance = class _Balance {
82156
82324
  balance.liabilityShares,
82157
82325
  balance.premiumRate,
82158
82326
  balance.premiumOutstanding,
82159
- balance.lastUpdate
82327
+ balance.lastUpdate,
82328
+ balance.tag
82160
82329
  );
82161
82330
  }
82162
82331
  static createEmpty(bankPk) {
@@ -82226,7 +82395,7 @@ var HealthCache = class _HealthCache {
82226
82395
 
82227
82396
  // src/models/account.ts
82228
82397
  var MarginfiAccount = class _MarginfiAccount {
82229
- constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache) {
82398
+ constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache, activeOrders = 0) {
82230
82399
  this.address = address;
82231
82400
  this.group = group;
82232
82401
  this.authority = authority;
@@ -82234,6 +82403,7 @@ var MarginfiAccount = class _MarginfiAccount {
82234
82403
  this.accountFlags = accountFlags;
82235
82404
  this.emissionsDestinationAccount = emissionsDestinationAccount;
82236
82405
  this.healthCache = healthCache;
82406
+ this.activeOrders = activeOrders;
82237
82407
  }
82238
82408
  /**
82239
82409
  * Fetches a marginfi account from on-chain data.
@@ -82258,7 +82428,8 @@ var MarginfiAccount = class _MarginfiAccount {
82258
82428
  account.balances.map((b) => Balance.fromBalanceType(b)),
82259
82429
  account.accountFlags,
82260
82430
  account.emissionsDestinationAccount,
82261
- account.healthCache
82431
+ account.healthCache,
82432
+ account.activeOrders
82262
82433
  );
82263
82434
  }
82264
82435
  /**
@@ -82278,7 +82449,8 @@ var MarginfiAccount = class _MarginfiAccount {
82278
82449
  props.balances.map((b) => Balance.fromBalanceType(b)),
82279
82450
  props.accountFlags,
82280
82451
  props.emissionsDestinationAccount,
82281
- HealthCache.fromHealthCacheType(props.healthCache)
82452
+ HealthCache.fromHealthCacheType(props.healthCache),
82453
+ props.activeOrders
82282
82454
  );
82283
82455
  }
82284
82456
  /**
@@ -83117,6 +83289,49 @@ var MarginfiAccount = class _MarginfiAccount {
83117
83289
  }
83118
83290
  });
83119
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
+ }
83120
83335
  /**
83121
83336
  * Creates a repay transaction.
83122
83337
  *
@@ -83275,7 +83490,8 @@ function projectAccountAfterFirstLeg(account, firstLegFlashloanTxs, program, ban
83275
83490
  projectedBalances.map((b) => Balance.fromBalanceType(b)),
83276
83491
  account.accountFlags,
83277
83492
  account.emissionsDestinationAccount,
83278
- account.healthCache
83493
+ account.healthCache,
83494
+ account.activeOrders
83279
83495
  );
83280
83496
  }
83281
83497
  function composeBundle(firstLegTxs, secondLegTxs, payer, blockhash, maxBundleTxs) {
@@ -83419,23 +83635,15 @@ async function makeSwapDebtTx(params) {
83419
83635
  return true;
83420
83636
  });
83421
83637
  setupIxs.push(...jupiterSetupInstructions);
83422
- const additionalTxs = [];
83423
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83424
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83425
- const txs = splitInstructionsToFitTransactions([], ixs, {
83638
+ const additionalTxs = makePreludeTxs(
83639
+ [...additionalIxs, ...setupIxs],
83640
+ refreshIntegrationIxs.instructions,
83641
+ {
83426
83642
  blockhash,
83427
83643
  payerKey: marginfiAccount.authority,
83428
83644
  luts: addressLookupTableAccounts ?? []
83429
- });
83430
- additionalTxs.push(
83431
- ...txs.map(
83432
- (tx) => addTransactionMetadata(tx, {
83433
- type: "CREATE_ATA" /* CREATE_ATA */,
83434
- addressLookupTables: addressLookupTableAccounts
83435
- })
83436
- )
83437
- );
83438
- }
83645
+ }
83646
+ );
83439
83647
  const transactions = [...additionalTxs, flashloanTx];
83440
83648
  return {
83441
83649
  transactions,
@@ -83719,12 +83927,18 @@ async function tryBridgedDebtSwap(params, bridgeOpts) {
83719
83927
  async function makeLoopTx(params) {
83720
83928
  const {
83721
83929
  marginfiAccount,
83930
+ bankMap,
83722
83931
  depositOpts,
83723
83932
  borrowOpts,
83724
83933
  addressLookupTableAccounts,
83725
83934
  connection,
83726
83935
  additionalIxs = []
83727
83936
  } = params;
83937
+ if (exceedsCostlyPositionLimit(marginfiAccount.balances, bankMap, depositOpts.depositBank)) {
83938
+ throw TransactionBuildingError.costlyPositionLimitExceeded(
83939
+ depositOpts.depositBank.address.toBase58()
83940
+ );
83941
+ }
83728
83942
  const blockhash = (await connection.getLatestBlockhash("confirmed")).blockhash;
83729
83943
  const setupIxs = await makeSetupIx({
83730
83944
  connection,
@@ -83764,28 +83978,20 @@ async function makeLoopTx(params) {
83764
83978
  return true;
83765
83979
  });
83766
83980
  setupIxs.push(...jupiterSetupInstructions);
83767
- const additionalTxs = [];
83768
83981
  if (depositOpts.depositBank.mint.equals(NATIVE_MINT) && depositOpts.inputDepositAmount) {
83769
83982
  setupIxs.push(
83770
83983
  ...makeWrapSolIxs(marginfiAccount.authority, new BigNumber(depositOpts.inputDepositAmount))
83771
83984
  );
83772
83985
  }
83773
- if (setupIxs.length > 0 || additionalIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83774
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83775
- const txs = splitInstructionsToFitTransactions([], ixs, {
83986
+ const additionalTxs = makePreludeTxs(
83987
+ [...additionalIxs, ...setupIxs],
83988
+ refreshIntegrationIxs.instructions,
83989
+ {
83776
83990
  blockhash,
83777
83991
  payerKey: marginfiAccount.authority,
83778
83992
  luts: addressLookupTableAccounts ?? []
83779
- });
83780
- additionalTxs.push(
83781
- ...txs.map(
83782
- (tx) => addTransactionMetadata(tx, {
83783
- type: "CREATE_ATA" /* CREATE_ATA */,
83784
- addressLookupTables: addressLookupTableAccounts
83785
- })
83786
- )
83787
- );
83788
- }
83993
+ }
83994
+ );
83789
83995
  const transactions = [...additionalTxs, flashloanTx];
83790
83996
  return {
83791
83997
  transactions,
@@ -84232,23 +84438,11 @@ async function makeSwapCollateralTx(params) {
84232
84438
  return true;
84233
84439
  });
84234
84440
  setupIxs.push(...jupiterSetupInstructions);
84235
- const additionalTxs = [];
84236
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
84237
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
84238
- const txs = splitInstructionsToFitTransactions([], ixs, {
84239
- blockhash,
84240
- payerKey: marginfiAccount.authority,
84241
- luts: addressLookupTableAccounts ?? []
84242
- });
84243
- additionalTxs.push(
84244
- ...txs.map(
84245
- (tx) => addTransactionMetadata(tx, {
84246
- type: "CREATE_ATA" /* CREATE_ATA */,
84247
- addressLookupTables: addressLookupTableAccounts
84248
- })
84249
- )
84250
- );
84251
- }
84441
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84442
+ blockhash,
84443
+ payerKey: marginfiAccount.authority,
84444
+ luts: addressLookupTableAccounts ?? []
84445
+ });
84252
84446
  const transactions = [...additionalTxs, flashloanTx];
84253
84447
  return {
84254
84448
  transactions,
@@ -84288,6 +84482,10 @@ async function buildSwapCollateralFlashloanTx({
84288
84482
  actualWithdrawAmount,
84289
84483
  withdrawBank.mintDecimals
84290
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
+ }
84291
84489
  const cuRequestIxs = [
84292
84490
  ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 }),
84293
84491
  ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 })
@@ -84679,6 +84877,8 @@ async function makeRollPtTx(params) {
84679
84877
  const {
84680
84878
  marginfiAccount,
84681
84879
  connection,
84880
+ bankMap,
84881
+ bankMetadataMap,
84682
84882
  withdrawOpts,
84683
84883
  depositOpts,
84684
84884
  rollOpts,
@@ -84713,33 +84913,29 @@ async function makeRollPtTx(params) {
84713
84913
  { mint: depositOpts.depositBank.mint, tokenProgram: depositOpts.tokenProgram }
84714
84914
  ]
84715
84915
  });
84916
+ const refreshIntegrationIxs = makeRefreshIntegrationBanksIxs(
84917
+ marginfiAccount,
84918
+ bankMap,
84919
+ [withdrawOpts.withdrawBank.address, depositOpts.depositBank.address],
84920
+ bankMetadataMap
84921
+ );
84716
84922
  const { flashloanTx, swapQuote } = await buildRollPtFlashloanTx({
84717
84923
  params,
84718
84924
  merge,
84719
84925
  clmm,
84720
84926
  blockhash
84721
84927
  });
84722
- const additionalTxs = [];
84723
- if (setupIxs.length > 0) {
84724
- const txs = splitInstructionsToFitTransactions([], setupIxs, {
84725
- blockhash,
84726
- payerKey: marginfiAccount.authority,
84727
- luts: addressLookupTableAccounts ?? []
84728
- });
84729
- additionalTxs.push(
84730
- ...txs.map(
84731
- (tx) => addTransactionMetadata(tx, {
84732
- type: "CREATE_ATA" /* CREATE_ATA */,
84733
- addressLookupTables: addressLookupTableAccounts
84734
- })
84735
- )
84736
- );
84737
- }
84928
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84929
+ blockhash,
84930
+ payerKey: marginfiAccount.authority,
84931
+ luts: addressLookupTableAccounts ?? []
84932
+ });
84738
84933
  const transactions = [...additionalTxs, flashloanTx];
84739
84934
  return {
84740
84935
  transactions,
84741
84936
  actionTxIndex: transactions.length - 1,
84742
- quoteResponse: swapQuote
84937
+ quoteResponse: swapQuote,
84938
+ mustBeAtomicBundle: refreshIntegrationIxs.instructions.length > 0
84743
84939
  };
84744
84940
  }
84745
84941
  async function buildRollPtFlashloanTx({
@@ -85089,6 +85285,13 @@ function classifyAndValidate(params) {
85089
85285
  );
85090
85286
  }
85091
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
+ }
85092
85295
  return positions;
85093
85296
  }
85094
85297
  function buildIntegrationRefreshIxs(args) {
@@ -85422,20 +85625,11 @@ async function makeTransferPositionsTx(params) {
85422
85625
  bankMap,
85423
85626
  bankMetadataMap
85424
85627
  });
85425
- const additionalTxs = [];
85426
- const preludeIxs = [...setupIxs, ...refreshIxs];
85427
- if (preludeIxs.length > 0) {
85428
- const txs = splitInstructionsToFitTransactions([], preludeIxs, {
85429
- blockhash,
85430
- payerKey: accountA.authority,
85431
- luts
85432
- });
85433
- additionalTxs.push(
85434
- ...txs.map(
85435
- (tx) => addTransactionMetadata(tx, { type: "CREATE_ATA" /* CREATE_ATA */, addressLookupTables: luts })
85436
- )
85437
- );
85438
- }
85628
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85629
+ blockhash,
85630
+ payerKey: accountA.authority,
85631
+ luts
85632
+ });
85439
85633
  const transactions = [...additionalTxs, flashloanTx];
85440
85634
  return {
85441
85635
  transactions,
@@ -85577,48 +85771,22 @@ async function makeBulkWithdrawTx(params) {
85577
85771
  type: "WITHDRAW" /* WITHDRAW */
85578
85772
  })
85579
85773
  );
85580
- const additionalTxs = [];
85581
85774
  const setupIxs = await makeSetupIx({
85582
85775
  connection,
85583
85776
  authority,
85584
85777
  tokens: setupTokens
85585
85778
  });
85586
- if (setupIxs.length > 0) {
85587
- const setupTxs = splitInstructionsToFitTransactions([], setupIxs, {
85588
- blockhash,
85589
- payerKey: authority,
85590
- luts: selectedLuts
85591
- });
85592
- additionalTxs.push(
85593
- ...setupTxs.map(
85594
- (tx) => addTransactionMetadata(tx, {
85595
- type: "CREATE_ATA" /* CREATE_ATA */,
85596
- addressLookupTables: selectedLuts
85597
- })
85598
- )
85599
- );
85600
- }
85601
85779
  const refreshIxs = makeRefreshIntegrationBanksIxs(
85602
85780
  marginfiAccount,
85603
85781
  bankMap,
85604
85782
  bankAddresses,
85605
85783
  bankMetadataMap
85606
85784
  ).instructions;
85607
- if (refreshIxs.length > 0) {
85608
- const refreshTxs = splitInstructionsToFitTransactions([], refreshIxs, {
85609
- blockhash,
85610
- payerKey: authority,
85611
- luts: selectedLuts
85612
- });
85613
- additionalTxs.push(
85614
- ...refreshTxs.map(
85615
- (tx) => addTransactionMetadata(tx, {
85616
- type: "CRANK" /* CRANK */,
85617
- addressLookupTables: selectedLuts
85618
- })
85619
- )
85620
- );
85621
- }
85785
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85786
+ blockhash,
85787
+ payerKey: authority,
85788
+ luts: selectedLuts
85789
+ });
85622
85790
  return {
85623
85791
  transactions: [...additionalTxs, ...withdrawTxs],
85624
85792
  actionTxIndex: additionalTxs.length,
@@ -85663,18 +85831,14 @@ async function makeBulkRepayTx(params) {
85663
85831
  });
85664
85832
  repayIxs.push(...repay.instructions);
85665
85833
  }
85666
- if (!params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses)) {
85667
- repayIxs.push(
85668
- ...await makePremiumRefreshIxs(
85669
- program,
85670
- { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85671
- [],
85672
- bankAddresses
85673
- )
85674
- );
85675
- }
85834
+ const premiumIxs = !params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses) ? await makePremiumRefreshIxs(
85835
+ program,
85836
+ { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85837
+ [],
85838
+ bankAddresses
85839
+ ) : [];
85676
85840
  const { blockhash } = await connection.getLatestBlockhash("confirmed");
85677
- const transactions = splitInstructionsToFitTransactions([], repayIxs, {
85841
+ const transactions = splitInstructionsToFitTransactions([], [...repayIxs, ...premiumIxs], {
85678
85842
  blockhash,
85679
85843
  payerKey: authority,
85680
85844
  luts,
@@ -85686,7 +85850,117 @@ async function makeBulkRepayTx(params) {
85686
85850
  type: "REPAY" /* REPAY */
85687
85851
  })
85688
85852
  );
85689
- 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 */);
85690
85964
  }
85691
85965
 
85692
85966
  // src/services/account/services/account-simulation.service.ts
@@ -86029,7 +86303,7 @@ function isGroupRateLimiterEnabled(rateLimiter) {
86029
86303
  if (!rateLimiter) return false;
86030
86304
  return rateLimiter.hourly.maxOutflow.gt(0) || rateLimiter.daily.maxOutflow.gt(0);
86031
86305
  }
86032
- async function makePoolConfigureBankIx3(program, bank, args) {
86306
+ async function makePoolConfigureBankIx2(program, bank, args) {
86033
86307
  const ix = await instructions_default3.makePoolConfigureBankIx(
86034
86308
  program,
86035
86309
  {
@@ -86042,6 +86316,17 @@ async function makePoolConfigureBankIx3(program, bank, args) {
86042
86316
  keys: []
86043
86317
  };
86044
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
+ }
86045
86330
  async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddress, feePayer, pythOracle) {
86046
86331
  const [settingsKey] = PublicKey.findProgramAddressSync(
86047
86332
  [Buffer.from("staked_settings", "utf-8"), group.toBuffer()],
@@ -86077,7 +86362,7 @@ async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddr
86077
86362
  keys: []
86078
86363
  };
86079
86364
  }
86080
- 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 = {}) {
86081
86366
  const rawBankConfig = serializeBankConfigOpt(bankConfig);
86082
86367
  const rawBankConfigCompact = {
86083
86368
  ...rawBankConfig,
@@ -87597,6 +87882,9 @@ function getKaminoCTokenMultiplier(reserve) {
87597
87882
  const [totalLiquidity, totalCollateral] = scaledSupplies(reserve);
87598
87883
  return totalCollateral.isZero() ? new BigNumber3(1) : new BigNumber3(totalLiquidity.dividedBy(totalCollateral).toString());
87599
87884
  }
87885
+ function withKaminoReserveEmergency(bank, reserve) {
87886
+ return { ...bank, kaminoEmergency: bank.kaminoEmergency || reserve.config.emergencyMode !== 0 };
87887
+ }
87600
87888
 
87601
87889
  // src/services/integration/integration.service.ts
87602
87890
  async function fetchBankIntegrationMetadata(options) {
@@ -87643,7 +87931,7 @@ async function fetchBankIntegrationMetadata(options) {
87643
87931
 
87644
87932
  // src/models/bank.ts
87645
87933
  var Bank = class _Bank {
87646
- 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) {
87647
87935
  this.address = address;
87648
87936
  this.mint = mint;
87649
87937
  this.mintDecimals = mintDecimals;
@@ -87676,6 +87964,7 @@ var Bank = class _Bank {
87676
87964
  this.premiumTag = premiumTag;
87677
87965
  this.premiumActive = premiumActive;
87678
87966
  this.premiumActivatedAt = premiumActivatedAt;
87967
+ this.kaminoEmergency = kaminoEmergency;
87679
87968
  this.rateLimiter = rateLimiter;
87680
87969
  this.kaminoIntegrationAccounts = kaminoIntegrationAccounts;
87681
87970
  this.driftIntegrationAccounts = driftIntegrationAccounts;
@@ -87751,6 +88040,7 @@ var Bank = class _Bank {
87751
88040
  bankType.premiumTag,
87752
88041
  bankType.premiumActive,
87753
88042
  bankType.premiumActivatedAt,
88043
+ bankType.kaminoEmergency,
87754
88044
  bankType.rateLimiter,
87755
88045
  bankType.kaminoIntegrationAccounts,
87756
88046
  bankType.driftIntegrationAccounts,
@@ -87797,6 +88087,7 @@ var Bank = class _Bank {
87797
88087
  props.premiumTag,
87798
88088
  props.premiumActive,
87799
88089
  props.premiumActivatedAt,
88090
+ props.kaminoEmergency,
87800
88091
  props.rateLimiter,
87801
88092
  props.kaminoIntegrationAccounts,
87802
88093
  props.driftIntegrationAccounts,
@@ -87992,7 +88283,7 @@ var MarginfiGroup = class _MarginfiGroup {
87992
88283
  // (TODO: move to Bank class)
87993
88284
  // ------------------------------------------------------------------------
87994
88285
  async makePoolConfigureBankIx(program, bank, args) {
87995
- return makePoolConfigureBankIx3(program, bank, args);
88286
+ return makePoolConfigureBankIx2(program, bank, args);
87996
88287
  }
87997
88288
  async makeAddPermissionlessStakedBankIx(program, voteAccountAddress, feePayer, pythOracle) {
87998
88289
  return makeAddPermissionlessStakedBankIx(
@@ -88004,7 +88295,7 @@ var MarginfiGroup = class _MarginfiGroup {
88004
88295
  );
88005
88296
  }
88006
88297
  async makePoolAddBankIx(program, bankPubkey, bankMint, bankConfig, feePayer) {
88007
- return makePoolAddBankIx3(
88298
+ return makePoolAddBankIx2(
88008
88299
  program,
88009
88300
  this.address,
88010
88301
  bankPubkey,
@@ -88575,6 +88866,75 @@ var MarginfiAccountWrapper = class {
88575
88866
  opts
88576
88867
  });
88577
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
+ }
88578
88938
  /**
88579
88939
  * Creates a repay transaction with auto-injected client data.
88580
88940
  *
@@ -89202,6 +89562,10 @@ var Project0Client = class _Project0Client {
89202
89562
  bank.address.toBase58(),
89203
89563
  getKaminoCTokenMultiplier(reserve)
89204
89564
  );
89565
+ bankMap.set(
89566
+ bank.address.toBase58(),
89567
+ Bank.fromBankType(withKaminoReserveEmergency(bank, reserve))
89568
+ );
89205
89569
  break;
89206
89570
  }
89207
89571
  case 4 /* DRIFT */: {
@@ -89294,6 +89658,6 @@ var EmodeSettings = class _EmodeSettings {
89294
89658
  }
89295
89659
  };
89296
89660
 
89297
- 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, 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, 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 };
89298
89662
  //# sourceMappingURL=index.js.map
89299
89663
  //# sourceMappingURL=index.js.map