@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.cjs CHANGED
@@ -3,6 +3,7 @@
3
3
  var web3_js = require('@solana/web3.js');
4
4
  var superstruct = require('superstruct');
5
5
  var BigNumber3 = require('bignumber.js');
6
+ var sha2 = require('@noble/hashes/sha2');
6
7
  var BN8 = require('bn.js');
7
8
  var Decimal3 = require('decimal.js');
8
9
  var anchor = require('@coral-xyz/anchor');
@@ -109,6 +110,95 @@ function getConfig(environment = "production", overrides) {
109
110
  ...getProject0Config(environment, overrides)
110
111
  };
111
112
  }
113
+ var PYTH_PUSH_ORACLE_ID = new web3_js.PublicKey("pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT");
114
+ var PYTH_SPONSORED_SHARD_ID = 0;
115
+ var MARGINFI_SPONSORED_SHARD_ID = 3301;
116
+ var DEFAULT_ORACLE_MAX_AGE = 60;
117
+ var ZERO_ORACLE_KEY = "DMhGWtLAKE5d56WdyHQxqeFncwUeqMEnuC2RvvZfbuur";
118
+ var PYTH_PRICE_CONF_INTERVALS = new BigNumber3__default.default(2.12);
119
+ var MAX_CONFIDENCE_INTERVAL_RATIO = new BigNumber3__default.default(0.05);
120
+ var DISABLED_FLAG = 1 << 0;
121
+ var FLASHLOAN_ENABLED_FLAG = 1 << 2;
122
+ var TRANSFER_ACCOUNT_AUTHORITY_FLAG = 1 << 3;
123
+ var STAKED_ORACLE_DISABLED_FLAG = 1 << 9;
124
+ var STAKED_ORACLE_USES_ONRAMP_FLAG = 1 << 10;
125
+ var PREMIUM_ACTIVE_FLAG = 1 << 13;
126
+ var KAMINO_MARKET_EMERGENCY_FLAG = 1 << 14;
127
+ var MAX_COSTLY_POSITIONS = 4;
128
+ var MARGINFI_PROGRAM = new web3_js.PublicKey("MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA");
129
+ var MARGINFI_PROGRAM_STAGING = new web3_js.PublicKey(
130
+ "stag8sTKds2h4KzjUw3zKTsxbqvT4XKHdaR9X9E6Rct"
131
+ );
132
+ var MARGINFI_PROGRAM_STAGING_ALT = new web3_js.PublicKey(
133
+ "5UDghkpgW1HfYSrmEj2iAApHShqU44H6PKTAar9LL9bY"
134
+ );
135
+ var ADDRESS_LOOKUP_TABLE_FOR_GROUP = {
136
+ "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
137
+ new web3_js.PublicKey("8dk6oxKXC4iMLMa8Q4AVtPJPkEfitZuHSB4JqUsLLV2R"),
138
+ new web3_js.PublicKey("43xneYSZYLFkaksMcfBMJANibRiKsWgxkPbsrmcYjqF6"),
139
+ new web3_js.PublicKey("67cS6yqmAy5D1QRJwAXcFv9GLvrMbe88GFGDJcntkL7C")
140
+ ],
141
+ // Main pool — general group
142
+ FCPfpHA69EbS8f9KKSreTRkXbzFpunsKuYf5qNmnJjpo: [
143
+ new web3_js.PublicKey("9p1CwvXMYNEY9CqSwuWySVXsG37NGb36nua94ea5KsiQ")
144
+ ],
145
+ // staging
146
+ Diu1q9gniR1qR4Daaej3rcHd6949HMmxLGsnQ94Z3rLz: [
147
+ new web3_js.PublicKey("5ggm1hB8yPF5dKWJ3W7n1txztDrU4zf2RQk3TLrFvvRn")
148
+ ]
149
+ // staging
150
+ };
151
+ var ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE = {
152
+ "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
153
+ new web3_js.PublicKey("FhVyrX2gfHmxKHq8wWWBJB3ZvHZcAQ6UAcjWxUyfyXuE"),
154
+ new web3_js.PublicKey("GYEJ3BcgwHfNSL2BAuDcth3KKKt9eiK14EHwLCjU9Eoo")
155
+ ]
156
+ // Main pool — native-stake group
157
+ };
158
+ var ADDRESS_LOOKUP_TABLE_FOR_SWAP = new web3_js.PublicKey(
159
+ "5X5gDr8Bp9BpizTeZ3VJhxMw4z3q2rwoexJvwttmATs5"
160
+ );
161
+ var JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = 5;
162
+ var JUPITER_V6_PROGRAM = new web3_js.PublicKey(
163
+ "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"
164
+ );
165
+ var SINGLE_POOL_PROGRAM_ID = new web3_js.PublicKey(
166
+ "SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE"
167
+ );
168
+ var STAKE_PROGRAM_ID = new web3_js.PublicKey(
169
+ "Stake11111111111111111111111111111111111111"
170
+ );
171
+ var MPL_METADATA_PROGRAM_ID = new web3_js.PublicKey(
172
+ "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
173
+ );
174
+ var SYSTEM_PROGRAM_ID = new web3_js.PublicKey("11111111111111111111111111111111");
175
+ var SYSVAR_RENT_ID = new web3_js.PublicKey(
176
+ "SysvarRent111111111111111111111111111111111"
177
+ );
178
+ var SYSVAR_CLOCK_ID = new web3_js.PublicKey(
179
+ "SysvarC1ock11111111111111111111111111111111"
180
+ );
181
+ var SYSVAR_STAKE_HISTORY_ID = new web3_js.PublicKey(
182
+ "SysvarStakeHistory1111111111111111111111111"
183
+ );
184
+ var STAKE_CONFIG_ID = new web3_js.PublicKey(
185
+ "StakeConfig11111111111111111111111111111111"
186
+ );
187
+
188
+ // src/constants/misc.consts.ts
189
+ var HOURS_PER_YEAR = 365.25 * 24;
190
+ var MAX_U64 = BigInt("18446744073709551615").toString();
191
+
192
+ // src/constants/transaction.consts.ts
193
+ var MAX_TX_SIZE = 1232;
194
+ var MAX_ACCOUNT_LOCKS = 64;
195
+ var BUNDLE_TX_SIZE = 81;
196
+ var PRIORITY_TX_SIZE = 44;
197
+ var WSOL_MINT = new web3_js.PublicKey("So11111111111111111111111111111111111111112");
198
+ var LST_MINT = new web3_js.PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
199
+ var USDC_MINT = new web3_js.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
200
+ var USDT_MINT = new web3_js.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
201
+ var USDC_DECIMALS = 6;
112
202
 
113
203
  // src/errors/transaction-building.errors.ts
114
204
  var TransactionBuildingErrorCode = /* @__PURE__ */ ((TransactionBuildingErrorCode2) => {
@@ -124,6 +214,10 @@ var TransactionBuildingErrorCode = /* @__PURE__ */ ((TransactionBuildingErrorCod
124
214
  TransactionBuildingErrorCode2["TRANSFER_POSITIONS_UNSUPPORTED_BANK"] = "TRANSFER_POSITIONS_UNSUPPORTED_BANK";
125
215
  TransactionBuildingErrorCode2["TRANSFER_POSITIONS_UNSPLITTABLE"] = "TRANSFER_POSITIONS_UNSPLITTABLE";
126
216
  TransactionBuildingErrorCode2["BRIDGE_CONFLICT"] = "BRIDGE_CONFLICT";
217
+ TransactionBuildingErrorCode2["ORDER_INVALID_TRIGGER"] = "ORDER_INVALID_TRIGGER";
218
+ TransactionBuildingErrorCode2["ORDER_INVALID_SLIPPAGE"] = "ORDER_INVALID_SLIPPAGE";
219
+ TransactionBuildingErrorCode2["COSTLY_POSITION_LIMIT_EXCEEDED"] = "COSTLY_POSITION_LIMIT_EXCEEDED";
220
+ TransactionBuildingErrorCode2["ACCOUNT_DISABLED"] = "ACCOUNT_DISABLED";
127
221
  return TransactionBuildingErrorCode2;
128
222
  })(TransactionBuildingErrorCode || {});
129
223
  var TransactionBuildingError = class _TransactionBuildingError extends Error {
@@ -257,6 +351,49 @@ var TransactionBuildingError = class _TransactionBuildingError extends Error {
257
351
  { conflictingBanks, bridgeTokenSide }
258
352
  );
259
353
  }
354
+ /**
355
+ * The order trigger can't be placed: no threshold set, a threshold not above 0, or take-profit
356
+ * at or below stop-loss (the program rejects all three with `InvalidOrderTakeProfitOrStopLoss`).
357
+ */
358
+ static orderInvalidTrigger(reason, takeProfitUsd, stopLossUsd) {
359
+ return new _TransactionBuildingError(
360
+ "ORDER_INVALID_TRIGGER" /* ORDER_INVALID_TRIGGER */,
361
+ `Invalid order trigger: ${reason}`,
362
+ { reason, takeProfitUsd, stopLossUsd }
363
+ );
364
+ }
365
+ /**
366
+ * The action would open an integration (Kamino, Drift, Solend, JupLend) or staked position
367
+ * beyond the per-account limit on such positions.
368
+ */
369
+ static costlyPositionLimitExceeded(bankAddress) {
370
+ return new _TransactionBuildingError(
371
+ "COSTLY_POSITION_LIMIT_EXCEEDED" /* COSTLY_POSITION_LIMIT_EXCEEDED */,
372
+ `An account can hold at most ${MAX_COSTLY_POSITIONS} integration and staked positions`,
373
+ { bankAddress, limit: MAX_COSTLY_POSITIONS }
374
+ );
375
+ }
376
+ /**
377
+ * The order's max slippage is outside (0, cap]. The program accepts 0, but a keeper can't
378
+ * execute an order that allows no slippage, so the SDK rejects it.
379
+ */
380
+ static orderInvalidSlippage(maxSlippagePercent, maxAllowedPercent) {
381
+ return new _TransactionBuildingError(
382
+ "ORDER_INVALID_SLIPPAGE" /* ORDER_INVALID_SLIPPAGE */,
383
+ `Max slippage percent must be in (0, ${maxAllowedPercent}], got ${maxSlippagePercent}`,
384
+ { maxSlippagePercent, maxAllowedPercent }
385
+ );
386
+ }
387
+ /**
388
+ * The marginfi account is disabled (e.g. already transferred to a new account), so it can't act.
389
+ */
390
+ static accountDisabled(accountAddress) {
391
+ return new _TransactionBuildingError(
392
+ "ACCOUNT_DISABLED" /* ACCOUNT_DISABLED */,
393
+ `Account ${accountAddress} is disabled`,
394
+ { accountAddress }
395
+ );
396
+ }
260
397
  /**
261
398
  * Generic escape hatch for custom errors
262
399
  */
@@ -286,6 +423,7 @@ var PDA_BANK_FEE_STATE_SEED = Buffer.from("feestate");
286
423
  var PDA_BANK_EMISSIONS_AUTH_SEED = Buffer.from("emissions_auth_seed");
287
424
  var PDA_BANK_EMISSIONS_VAULT_SEED = Buffer.from("emissions_vault");
288
425
  var PDA_MARGINFI_ACCOUNT_SEED = Buffer.from("marginfi_account");
426
+ var PDA_ORDER_SEED = Buffer.from("order");
289
427
  var PDA_REBALANCE_FEE_POOL_SEED = Buffer.from("rebalance_fee_pool");
290
428
  function deriveBankLiquidityVaultAuthority(programId, bank) {
291
429
  return web3_js.PublicKey.findProgramAddressSync(
@@ -351,99 +489,20 @@ function deriveMarginfiAccount(programId, group, authority, accountIndex, thirdP
351
489
  programId
352
490
  );
353
491
  }
492
+ function deriveOrderPda(programId, marginfiAccount, bankKeys) {
493
+ const sortedBankKeys = bankKeys.map((key) => key.toBuffer()).sort(Buffer.compare);
494
+ const bankKeysHash = Buffer.from(sha2.sha256(Buffer.concat(sortedBankKeys)));
495
+ return web3_js.PublicKey.findProgramAddressSync(
496
+ [PDA_ORDER_SEED, marginfiAccount.toBuffer(), bankKeysHash],
497
+ programId
498
+ );
499
+ }
354
500
  function deriveRebalanceFeePool(programId, marginfiAccount) {
355
501
  return web3_js.PublicKey.findProgramAddressSync(
356
502
  [PDA_REBALANCE_FEE_POOL_SEED, marginfiAccount.toBuffer()],
357
503
  programId
358
504
  );
359
505
  }
360
- var PYTH_PUSH_ORACLE_ID = new web3_js.PublicKey("pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT");
361
- var PYTH_SPONSORED_SHARD_ID = 0;
362
- var MARGINFI_SPONSORED_SHARD_ID = 3301;
363
- var DEFAULT_ORACLE_MAX_AGE = 60;
364
- var ZERO_ORACLE_KEY = "DMhGWtLAKE5d56WdyHQxqeFncwUeqMEnuC2RvvZfbuur";
365
- var PYTH_PRICE_CONF_INTERVALS = new BigNumber3__default.default(2.12);
366
- var MAX_CONFIDENCE_INTERVAL_RATIO = new BigNumber3__default.default(0.05);
367
- var DISABLED_FLAG = 1 << 0;
368
- var FLASHLOAN_ENABLED_FLAG = 1 << 2;
369
- var TRANSFER_ACCOUNT_AUTHORITY_FLAG = 1 << 3;
370
- var STAKED_ORACLE_DISABLED_FLAG = 1 << 9;
371
- var STAKED_ORACLE_USES_ONRAMP_FLAG = 1 << 10;
372
- var PREMIUM_ACTIVE_FLAG = 1 << 13;
373
- var MARGINFI_PROGRAM = new web3_js.PublicKey("MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA");
374
- var MARGINFI_PROGRAM_STAGING = new web3_js.PublicKey(
375
- "stag8sTKds2h4KzjUw3zKTsxbqvT4XKHdaR9X9E6Rct"
376
- );
377
- var MARGINFI_PROGRAM_STAGING_ALT = new web3_js.PublicKey(
378
- "5UDghkpgW1HfYSrmEj2iAApHShqU44H6PKTAar9LL9bY"
379
- );
380
- var ADDRESS_LOOKUP_TABLE_FOR_GROUP = {
381
- "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
382
- new web3_js.PublicKey("8dk6oxKXC4iMLMa8Q4AVtPJPkEfitZuHSB4JqUsLLV2R"),
383
- new web3_js.PublicKey("43xneYSZYLFkaksMcfBMJANibRiKsWgxkPbsrmcYjqF6"),
384
- new web3_js.PublicKey("67cS6yqmAy5D1QRJwAXcFv9GLvrMbe88GFGDJcntkL7C")
385
- ],
386
- // Main pool — general group
387
- FCPfpHA69EbS8f9KKSreTRkXbzFpunsKuYf5qNmnJjpo: [
388
- new web3_js.PublicKey("9p1CwvXMYNEY9CqSwuWySVXsG37NGb36nua94ea5KsiQ")
389
- ],
390
- // staging
391
- Diu1q9gniR1qR4Daaej3rcHd6949HMmxLGsnQ94Z3rLz: [
392
- new web3_js.PublicKey("5ggm1hB8yPF5dKWJ3W7n1txztDrU4zf2RQk3TLrFvvRn")
393
- ]
394
- // staging
395
- };
396
- var ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE = {
397
- "4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8": [
398
- new web3_js.PublicKey("FhVyrX2gfHmxKHq8wWWBJB3ZvHZcAQ6UAcjWxUyfyXuE"),
399
- new web3_js.PublicKey("GYEJ3BcgwHfNSL2BAuDcth3KKKt9eiK14EHwLCjU9Eoo")
400
- ]
401
- // Main pool — native-stake group
402
- };
403
- var ADDRESS_LOOKUP_TABLE_FOR_SWAP = new web3_js.PublicKey(
404
- "5X5gDr8Bp9BpizTeZ3VJhxMw4z3q2rwoexJvwttmATs5"
405
- );
406
- var JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = 5;
407
- var JUPITER_V6_PROGRAM = new web3_js.PublicKey(
408
- "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"
409
- );
410
- var SINGLE_POOL_PROGRAM_ID = new web3_js.PublicKey(
411
- "SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE"
412
- );
413
- var STAKE_PROGRAM_ID = new web3_js.PublicKey(
414
- "Stake11111111111111111111111111111111111111"
415
- );
416
- var MPL_METADATA_PROGRAM_ID = new web3_js.PublicKey(
417
- "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
418
- );
419
- var SYSTEM_PROGRAM_ID = new web3_js.PublicKey("11111111111111111111111111111111");
420
- var SYSVAR_RENT_ID = new web3_js.PublicKey(
421
- "SysvarRent111111111111111111111111111111111"
422
- );
423
- var SYSVAR_CLOCK_ID = new web3_js.PublicKey(
424
- "SysvarC1ock11111111111111111111111111111111"
425
- );
426
- var SYSVAR_STAKE_HISTORY_ID = new web3_js.PublicKey(
427
- "SysvarStakeHistory1111111111111111111111111"
428
- );
429
- var STAKE_CONFIG_ID = new web3_js.PublicKey(
430
- "StakeConfig11111111111111111111111111111111"
431
- );
432
-
433
- // src/constants/misc.consts.ts
434
- var HOURS_PER_YEAR = 365.25 * 24;
435
- var MAX_U64 = BigInt("18446744073709551615").toString();
436
-
437
- // src/constants/transaction.consts.ts
438
- var MAX_TX_SIZE = 1232;
439
- var MAX_ACCOUNT_LOCKS = 64;
440
- var BUNDLE_TX_SIZE = 81;
441
- var PRIORITY_TX_SIZE = 44;
442
- var WSOL_MINT = new web3_js.PublicKey("So11111111111111111111111111111111111111112");
443
- var LST_MINT = new web3_js.PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
444
- var USDC_MINT = new web3_js.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
445
- var USDT_MINT = new web3_js.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
446
- var USDC_DECIMALS = 6;
447
506
 
448
507
  // src/utils/accounting.utils.ts
449
508
  var apyToApr = (apy, compoundingFrequency = HOURS_PER_YEAR) => ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;
@@ -529,6 +588,17 @@ function shortenAddress(pubkey, chars = 4) {
529
588
  function bpsToPercentile(bps) {
530
589
  return bps / 1e4;
531
590
  }
591
+ var U32_MAX = 4294967295;
592
+ var MAX_ORDER_SLIPPAGE_PERCENT = 10;
593
+ function percentToMaxSlippageU32(percent) {
594
+ if (!(percent > 0) || percent > MAX_ORDER_SLIPPAGE_PERCENT) {
595
+ throw TransactionBuildingError.orderInvalidSlippage(percent, MAX_ORDER_SLIPPAGE_PERCENT);
596
+ }
597
+ return Math.floor(percent / 100 * U32_MAX);
598
+ }
599
+ function maxSlippageU32ToPercent(maxSlippage) {
600
+ return maxSlippage / U32_MAX * 100;
601
+ }
532
602
  var composeRemainingAccounts = (banksAndOracles) => {
533
603
  banksAndOracles.sort((a, b) => {
534
604
  const A = a[0].toBytes();
@@ -694,6 +764,155 @@ function makeBundleTipIx(feePayer, bundleTip = 1e5) {
694
764
  });
695
765
  return bundleTipInstruction;
696
766
  }
767
+ var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
768
+ TransactionType2["DEPOSIT"] = "DEPOSIT";
769
+ TransactionType2["WITHDRAW"] = "WITHDRAW";
770
+ TransactionType2["REPAY"] = "REPAY";
771
+ TransactionType2["BORROW"] = "BORROW";
772
+ TransactionType2["FLASHLOAN"] = "FLASHLOAN";
773
+ TransactionType2["LOOP"] = "LOOP";
774
+ TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
775
+ TransactionType2["LONG"] = "LONG";
776
+ TransactionType2["SHORT"] = "SHORT";
777
+ TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
778
+ TransactionType2["CREATE_ATA"] = "CREATE_ATA";
779
+ TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
780
+ TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
781
+ TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
782
+ TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
783
+ TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
784
+ TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
785
+ TransactionType2["CRANK"] = "CRANK";
786
+ TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
787
+ TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
788
+ TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
789
+ TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
790
+ TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
791
+ TransactionType2["VAULT_DEPOSIT"] = "VAULT_DEPOSIT";
792
+ TransactionType2["VAULT_WITHDRAW"] = "VAULT_WITHDRAW";
793
+ TransactionType2["VAULT_COMPLETE_WITHDRAWAL"] = "VAULT_COMPLETE_WITHDRAWAL";
794
+ TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
795
+ TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
796
+ TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
797
+ TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
798
+ TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
799
+ TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
800
+ TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
801
+ TransactionType2["PLACE_ORDER"] = "PLACE_ORDER";
802
+ TransactionType2["CLOSE_ORDER"] = "CLOSE_ORDER";
803
+ TransactionType2["UPDATE_ORDER"] = "UPDATE_ORDER";
804
+ TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
805
+ TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
806
+ TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
807
+ return TransactionType2;
808
+ })(TransactionType || {});
809
+ var TransactionConfigMap = {
810
+ // BASE LENDING ACTIONS
811
+ ["DEPOSIT" /* DEPOSIT */]: {
812
+ label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
813
+ },
814
+ ["WITHDRAW" /* WITHDRAW */]: {
815
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
816
+ },
817
+ ["REPAY" /* REPAY */]: {
818
+ label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
819
+ },
820
+ ["BORROW" /* BORROW */]: {
821
+ label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
822
+ },
823
+ // FLASHLOANS
824
+ ["FLASHLOAN" /* FLASHLOAN */]: { label: () => "Executing Flashloan" },
825
+ ["LOOP" /* LOOP */]: {
826
+ label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
827
+ },
828
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: {
829
+ label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
830
+ },
831
+ ["LONG" /* LONG */]: {
832
+ label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
833
+ },
834
+ ["SHORT" /* SHORT */]: {
835
+ label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
836
+ },
837
+ ["CRANK" /* CRANK */]: { label: () => "Updating latest prices" },
838
+ ["JUPITER_SWAP" /* JUPITER_SWAP */]: {
839
+ label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
840
+ },
841
+ // SETUP
842
+ ["CREATE_ACCOUNT" /* CREATE_ACCOUNT */]: { label: () => "Create marginfi account" },
843
+ ["CREATE_ATA" /* CREATE_ATA */]: { label: () => "Configure token account" },
844
+ // ACCOUNT MANAGEMENT
845
+ ["CLOSE_ACCOUNT" /* CLOSE_ACCOUNT */]: { label: () => "Close marginfi account" },
846
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: { label: () => "Close position" },
847
+ ["MOVE_POSITION_WITHDRAW" /* MOVE_POSITION_WITHDRAW */]: {
848
+ label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
849
+ },
850
+ ["MOVE_POSITION_DEPOSIT" /* MOVE_POSITION_DEPOSIT */]: {
851
+ label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
852
+ },
853
+ ["TRANSFER_AUTH" /* TRANSFER_AUTH */]: { label: () => "Authorize account transfer" },
854
+ // NATIVE STAKE ACTIONS
855
+ ["DEPOSIT_STAKE" /* DEPOSIT_STAKE */]: {
856
+ label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
857
+ },
858
+ ["WITHDRAW_STAKE" /* WITHDRAW_STAKE */]: {
859
+ label: () => "Authorize stake account"
860
+ },
861
+ ["INITIALIZE_STAKED_POOL" /* INITIALIZE_STAKED_POOL */]: { label: () => "Initialize stake pool" },
862
+ ["ADD_STAKED_BANK" /* ADD_STAKED_BANK */]: { label: () => "Create staked asset bank" },
863
+ ["MERGE_STAKE_ACCOUNTS" /* MERGE_STAKE_ACCOUNTS */]: { label: () => "Merge stake accounts" },
864
+ // GAMMA VAULT ACTIONS
865
+ ["VAULT_DEPOSIT" /* VAULT_DEPOSIT */]: {
866
+ label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token} into vault` : "Deposit into vault"
867
+ },
868
+ ["VAULT_WITHDRAW" /* VAULT_WITHDRAW */]: {
869
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token} from vault` : "Withdraw from vault"
870
+ },
871
+ ["VAULT_COMPLETE_WITHDRAWAL" /* VAULT_COMPLETE_WITHDRAWAL */]: {
872
+ label: () => "Claim vault withdrawal"
873
+ },
874
+ // LST (Liquid Staking Tokens)
875
+ ["STAKE_TO_STAKE" /* STAKE_TO_STAKE */]: { label: () => "Convert stake" },
876
+ ["MINT_LST_NATIVE" /* MINT_LST_NATIVE */]: { label: () => "Mint LST" },
877
+ ["SWAP_TO_SOL" /* SWAP_TO_SOL */]: {
878
+ label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
879
+ },
880
+ ["SOL_TO_LST" /* SOL_TO_LST */]: {
881
+ label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
882
+ },
883
+ ["UNSTAKE_LST" /* UNSTAKE_LST */]: {
884
+ label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST"
885
+ },
886
+ // EMISSIONS
887
+ ["WITHDRAW_EMISSIONS" /* WITHDRAW_EMISSIONS */]: { label: () => "Withdraw emissions" },
888
+ // LIQUIDATE
889
+ ["LIQUIDATE_ACCOUNT" /* LIQUIDATE_ACCOUNT */]: { label: () => "Liquidate account" },
890
+ // ORDERS (TP/SL)
891
+ ["PLACE_ORDER" /* PLACE_ORDER */]: {
892
+ label: ({ collateralToken, debtToken } = {}) => collateralToken && debtToken ? `Place TP/SL order on ${collateralToken}/${debtToken}` : "Place TP/SL order"
893
+ },
894
+ ["CLOSE_ORDER" /* CLOSE_ORDER */]: { label: () => "Close TP/SL order" },
895
+ ["UPDATE_ORDER" /* UPDATE_ORDER */]: {
896
+ label: ({ collateralToken, debtToken } = {}) => collateralToken && debtToken ? `Update TP/SL order on ${collateralToken}/${debtToken}` : "Update TP/SL order"
897
+ },
898
+ // BANK and GROUPS
899
+ ["CREATE_PERM_BANK" /* CREATE_PERM_BANK */]: { label: () => "Create permissionless bank" },
900
+ ["CREATE_GROUP" /* CREATE_GROUP */]: { label: () => "Create marginfi group" },
901
+ ["WITHDRAW_ALL" /* WITHDRAW_ALL */]: {
902
+ label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
903
+ }
904
+ };
905
+ var TransactionArenaKeyMap = {
906
+ ["DEPOSIT" /* DEPOSIT */]: new web3_js.PublicKey("ArenaDeposit1111111111111111111111111111111"),
907
+ ["WITHDRAW" /* WITHDRAW */]: new web3_js.PublicKey("ArenaWithdraw111111111111111111111111111111"),
908
+ ["BORROW" /* BORROW */]: new web3_js.PublicKey("ArenaBorrow11111111111111111111111111111111"),
909
+ ["REPAY" /* REPAY */]: new web3_js.PublicKey("ArenaRepay111111111111111111111111111111111"),
910
+ ["REPAY_COLLAT" /* REPAY_COLLAT */]: new web3_js.PublicKey("ArenaRepayCo11at111111111111111111111111111"),
911
+ ["LONG" /* LONG */]: new web3_js.PublicKey("ArenaLong1111111111111111111111111111111111"),
912
+ ["SHORT" /* SHORT */]: new web3_js.PublicKey("ArenaShort111111111111111111111111111111111"),
913
+ ["CLOSE_POSITION" /* CLOSE_POSITION */]: new web3_js.PublicKey("ArenaC1ose111111111111111111111111111111111")
914
+ // Add more mappings if needed
915
+ };
697
916
  function decodeInstruction(idl, encoded) {
698
917
  const coder = new anchor.BorshInstructionCoder(idl);
699
918
  return coder.decode(encoded, "base58");
@@ -24970,10 +25189,24 @@ function countTxAccountLocks(tx) {
24970
25189
  );
24971
25190
  return message.staticAccountKeys.length + lookupKeys;
24972
25191
  }
25192
+ function fitsInOneTransaction(ixs, opts) {
25193
+ try {
25194
+ const tx = new web3_js.VersionedTransaction(
25195
+ new web3_js.TransactionMessage({
25196
+ payerKey: opts.payerKey,
25197
+ recentBlockhash: web3_js.PublicKey.default.toBase58(),
25198
+ instructions: ixs
25199
+ }).compileToV0Message(opts.luts)
25200
+ );
25201
+ if (getTxSize(tx) > MAX_TX_SIZE - (opts.sizeMargin ?? 0)) return false;
25202
+ return opts.maxAccountLocks === void 0 || countTxAccountLocks(tx) <= opts.maxAccountLocks;
25203
+ } catch {
25204
+ return false;
25205
+ }
25206
+ }
24973
25207
  function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
24974
25208
  const result = [];
24975
25209
  let buffer = [];
24976
- const maxSize = MAX_TX_SIZE - (opts.sizeMargin ?? 0);
24977
25210
  function buildTx(extraIxs) {
24978
25211
  const messageV0 = new web3_js.TransactionMessage({
24979
25212
  payerKey: opts.payerKey,
@@ -24983,16 +25216,7 @@ function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
24983
25216
  return new web3_js.VersionedTransaction(messageV0);
24984
25217
  }
24985
25218
  function fits(extraIxs) {
24986
- try {
24987
- const tx = buildTx(extraIxs);
24988
- if (getTxSize(tx) > maxSize) return false;
24989
- if (opts.maxAccountLocks !== void 0 && countTxAccountLocks(tx) > opts.maxAccountLocks) {
24990
- return false;
24991
- }
24992
- return true;
24993
- } catch {
24994
- return false;
24995
- }
25219
+ return fitsInOneTransaction([...mandatoryIxs, ...extraIxs], opts);
24996
25220
  }
24997
25221
  for (const ix of ixs) {
24998
25222
  if (fits([...buffer, ix])) {
@@ -25013,6 +25237,15 @@ function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
25013
25237
  }
25014
25238
  return result;
25015
25239
  }
25240
+ function makePreludeTxs(setupIxs, refreshIxs, opts) {
25241
+ const build = (ixs, type) => splitInstructionsToFitTransactions([], ixs, opts).map(
25242
+ (tx) => addTransactionMetadata(tx, { type, addressLookupTables: opts.luts })
25243
+ );
25244
+ return [
25245
+ ...build(setupIxs, "CREATE_ATA" /* CREATE_ATA */),
25246
+ ...build(refreshIxs, "CRANK" /* CRANK */)
25247
+ ];
25248
+ }
25016
25249
  function addTransactionMetadata(transaction, options) {
25017
25250
  return Object.assign(transaction, options);
25018
25251
  }
@@ -25210,144 +25443,6 @@ function makeWrapSolIxs(walletAddress, amount) {
25210
25443
  }
25211
25444
  return ixs;
25212
25445
  }
25213
- var TransactionType = /* @__PURE__ */ ((TransactionType2) => {
25214
- TransactionType2["DEPOSIT"] = "DEPOSIT";
25215
- TransactionType2["WITHDRAW"] = "WITHDRAW";
25216
- TransactionType2["REPAY"] = "REPAY";
25217
- TransactionType2["BORROW"] = "BORROW";
25218
- TransactionType2["FLASHLOAN"] = "FLASHLOAN";
25219
- TransactionType2["LOOP"] = "LOOP";
25220
- TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
25221
- TransactionType2["LONG"] = "LONG";
25222
- TransactionType2["SHORT"] = "SHORT";
25223
- TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
25224
- TransactionType2["CREATE_ATA"] = "CREATE_ATA";
25225
- TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
25226
- TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
25227
- TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
25228
- TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
25229
- TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
25230
- TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
25231
- TransactionType2["CRANK"] = "CRANK";
25232
- TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
25233
- TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
25234
- TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
25235
- TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
25236
- TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
25237
- TransactionType2["VAULT_DEPOSIT"] = "VAULT_DEPOSIT";
25238
- TransactionType2["VAULT_WITHDRAW"] = "VAULT_WITHDRAW";
25239
- TransactionType2["VAULT_COMPLETE_WITHDRAWAL"] = "VAULT_COMPLETE_WITHDRAWAL";
25240
- TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
25241
- TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
25242
- TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
25243
- TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
25244
- TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
25245
- TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
25246
- TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
25247
- TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
25248
- TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
25249
- TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
25250
- return TransactionType2;
25251
- })(TransactionType || {});
25252
- var TransactionConfigMap = {
25253
- // BASE LENDING ACTIONS
25254
- ["DEPOSIT" /* DEPOSIT */]: {
25255
- label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
25256
- },
25257
- ["WITHDRAW" /* WITHDRAW */]: {
25258
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
25259
- },
25260
- ["REPAY" /* REPAY */]: {
25261
- label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
25262
- },
25263
- ["BORROW" /* BORROW */]: {
25264
- label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
25265
- },
25266
- // FLASHLOANS
25267
- ["FLASHLOAN" /* FLASHLOAN */]: { label: () => "Executing Flashloan" },
25268
- ["LOOP" /* LOOP */]: {
25269
- label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
25270
- },
25271
- ["REPAY_COLLAT" /* REPAY_COLLAT */]: {
25272
- label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
25273
- },
25274
- ["LONG" /* LONG */]: {
25275
- label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
25276
- },
25277
- ["SHORT" /* SHORT */]: {
25278
- label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
25279
- },
25280
- ["CRANK" /* CRANK */]: { label: () => "Updating latest prices" },
25281
- ["JUPITER_SWAP" /* JUPITER_SWAP */]: {
25282
- label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
25283
- },
25284
- // SETUP
25285
- ["CREATE_ACCOUNT" /* CREATE_ACCOUNT */]: { label: () => "Create marginfi account" },
25286
- ["CREATE_ATA" /* CREATE_ATA */]: { label: () => "Configure token account" },
25287
- // ACCOUNT MANAGEMENT
25288
- ["CLOSE_ACCOUNT" /* CLOSE_ACCOUNT */]: { label: () => "Close marginfi account" },
25289
- ["CLOSE_POSITION" /* CLOSE_POSITION */]: { label: () => "Close position" },
25290
- ["MOVE_POSITION_WITHDRAW" /* MOVE_POSITION_WITHDRAW */]: {
25291
- label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
25292
- },
25293
- ["MOVE_POSITION_DEPOSIT" /* MOVE_POSITION_DEPOSIT */]: {
25294
- label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
25295
- },
25296
- ["TRANSFER_AUTH" /* TRANSFER_AUTH */]: { label: () => "Authorize account transfer" },
25297
- // NATIVE STAKE ACTIONS
25298
- ["DEPOSIT_STAKE" /* DEPOSIT_STAKE */]: {
25299
- label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
25300
- },
25301
- ["WITHDRAW_STAKE" /* WITHDRAW_STAKE */]: {
25302
- label: () => "Authorize stake account"
25303
- },
25304
- ["INITIALIZE_STAKED_POOL" /* INITIALIZE_STAKED_POOL */]: { label: () => "Initialize stake pool" },
25305
- ["ADD_STAKED_BANK" /* ADD_STAKED_BANK */]: { label: () => "Create staked asset bank" },
25306
- ["MERGE_STAKE_ACCOUNTS" /* MERGE_STAKE_ACCOUNTS */]: { label: () => "Merge stake accounts" },
25307
- // GAMMA VAULT ACTIONS
25308
- ["VAULT_DEPOSIT" /* VAULT_DEPOSIT */]: {
25309
- label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token} into vault` : "Deposit into vault"
25310
- },
25311
- ["VAULT_WITHDRAW" /* VAULT_WITHDRAW */]: {
25312
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token} from vault` : "Withdraw from vault"
25313
- },
25314
- ["VAULT_COMPLETE_WITHDRAWAL" /* VAULT_COMPLETE_WITHDRAWAL */]: {
25315
- label: () => "Claim vault withdrawal"
25316
- },
25317
- // LST (Liquid Staking Tokens)
25318
- ["STAKE_TO_STAKE" /* STAKE_TO_STAKE */]: { label: () => "Convert stake" },
25319
- ["MINT_LST_NATIVE" /* MINT_LST_NATIVE */]: { label: () => "Mint LST" },
25320
- ["SWAP_TO_SOL" /* SWAP_TO_SOL */]: {
25321
- label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
25322
- },
25323
- ["SOL_TO_LST" /* SOL_TO_LST */]: {
25324
- label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
25325
- },
25326
- ["UNSTAKE_LST" /* UNSTAKE_LST */]: {
25327
- label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST"
25328
- },
25329
- // EMISSIONS
25330
- ["WITHDRAW_EMISSIONS" /* WITHDRAW_EMISSIONS */]: { label: () => "Withdraw emissions" },
25331
- // LIQUIDATE
25332
- ["LIQUIDATE_ACCOUNT" /* LIQUIDATE_ACCOUNT */]: { label: () => "Liquidate account" },
25333
- // BANK and GROUPS
25334
- ["CREATE_PERM_BANK" /* CREATE_PERM_BANK */]: { label: () => "Create permissionless bank" },
25335
- ["CREATE_GROUP" /* CREATE_GROUP */]: { label: () => "Create marginfi group" },
25336
- ["WITHDRAW_ALL" /* WITHDRAW_ALL */]: {
25337
- label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
25338
- }
25339
- };
25340
- var TransactionArenaKeyMap = {
25341
- ["DEPOSIT" /* DEPOSIT */]: new web3_js.PublicKey("ArenaDeposit1111111111111111111111111111111"),
25342
- ["WITHDRAW" /* WITHDRAW */]: new web3_js.PublicKey("ArenaWithdraw111111111111111111111111111111"),
25343
- ["BORROW" /* BORROW */]: new web3_js.PublicKey("ArenaBorrow11111111111111111111111111111111"),
25344
- ["REPAY" /* REPAY */]: new web3_js.PublicKey("ArenaRepay111111111111111111111111111111111"),
25345
- ["REPAY_COLLAT" /* REPAY_COLLAT */]: new web3_js.PublicKey("ArenaRepayCo11at111111111111111111111111111"),
25346
- ["LONG" /* LONG */]: new web3_js.PublicKey("ArenaLong1111111111111111111111111111111111"),
25347
- ["SHORT" /* SHORT */]: new web3_js.PublicKey("ArenaShort111111111111111111111111111111111"),
25348
- ["CLOSE_POSITION" /* CLOSE_POSITION */]: new web3_js.PublicKey("ArenaC1ose111111111111111111111111111111111")
25349
- // Add more mappings if needed
25350
- };
25351
25446
  function serializeBankConfigOpt(bankConfigOpt) {
25352
25447
  const toWrappedI80F48 = (value) => value && bigNumberToWrappedI80F48(value);
25353
25448
  const toBN2 = (value) => value && new BN8__default.default(value.toString());
@@ -25595,6 +25690,7 @@ function toBankDto(bank) {
25595
25690
  premiumTag: bank.premiumTag,
25596
25691
  premiumActive: bank.premiumActive,
25597
25692
  premiumActivatedAt: bank.premiumActivatedAt,
25693
+ kaminoEmergency: bank.kaminoEmergency,
25598
25694
  rateLimiter: bank.rateLimiter ? toBankRateLimiterDto(bank.rateLimiter) : void 0,
25599
25695
  tokenSymbol: bank.tokenSymbol,
25600
25696
  feesDestinationAccount: bank.feesDestinationAccount?.toBase58(),
@@ -25975,6 +26071,7 @@ function parseBankRaw(address, accountParsed, bankMetadata) {
25975
26071
  premiumTag: accountParsed.premiumTag,
25976
26072
  premiumActive,
25977
26073
  premiumActivatedAt: accountParsed.premiumActivatedAt.toNumber(),
26074
+ kaminoEmergency: (flags & KAMINO_MARKET_EMERGENCY_FLAG) > 0,
25978
26075
  rateLimiter,
25979
26076
  tokenSymbol,
25980
26077
  kaminoIntegrationAccounts,
@@ -26020,6 +26117,7 @@ function dtoToBank(bankDto) {
26020
26117
  premiumTag: bankDto.premiumTag ?? 0,
26021
26118
  premiumActive: bankDto.premiumActive ?? false,
26022
26119
  premiumActivatedAt: bankDto.premiumActivatedAt ?? 0,
26120
+ kaminoEmergency: bankDto.kaminoEmergency ?? false,
26023
26121
  rateLimiter: bankDto.rateLimiter ? dtoToBankRateLimiter(bankDto.rateLimiter) : void 0,
26024
26122
  tokenSymbol: bankDto.tokenSymbol,
26025
26123
  feesDestinationAccount: bankDto.feesDestinationAccount ? new web3_js.PublicKey(bankDto.feesDestinationAccount) : void 0,
@@ -26472,6 +26570,10 @@ var AccountFlags = /* @__PURE__ */ ((AccountFlags2) => {
26472
26570
  AccountFlags2[AccountFlags2["ACCOUNT_IN_FLASHLOAN"] = 2] = "ACCOUNT_IN_FLASHLOAN";
26473
26571
  AccountFlags2[AccountFlags2["ACCOUNT_FLAG_DEPRECATED"] = 4] = "ACCOUNT_FLAG_DEPRECATED";
26474
26572
  AccountFlags2[AccountFlags2["ACCOUNT_TRANSFER_AUTHORITY_ALLOWED"] = 8] = "ACCOUNT_TRANSFER_AUTHORITY_ALLOWED";
26573
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_RECEIVERSHIP"] = 16] = "ACCOUNT_IN_RECEIVERSHIP";
26574
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_DELEVERAGE"] = 32] = "ACCOUNT_IN_DELEVERAGE";
26575
+ AccountFlags2[AccountFlags2["ACCOUNT_FROZEN"] = 64] = "ACCOUNT_FROZEN";
26576
+ AccountFlags2[AccountFlags2["ACCOUNT_IN_ORDER_EXECUTION"] = 128] = "ACCOUNT_IN_ORDER_EXECUTION";
26475
26577
  return AccountFlags2;
26476
26578
  })(AccountFlags || {});
26477
26579
  var MarginRequirementType = /* @__PURE__ */ ((MarginRequirementType5) => {
@@ -40634,6 +40736,7 @@ function kaminoReserveToDto(reserve) {
40634
40736
  protocolTakeRatePct: reserve.config.protocolTakeRatePct,
40635
40737
  hostFixedInterestRateBps: reserve.config.hostFixedInterestRateBps,
40636
40738
  interestRateBasis: reserve.config.interestRateBasis ?? 0 /* Legacy */,
40739
+ emergencyMode: reserve.config.emergencyMode,
40637
40740
  depositLimit: reserve.config.depositLimit.toString(),
40638
40741
  borrowLimit: reserve.config.borrowLimit.toString(),
40639
40742
  borrowRateCurve: {
@@ -47167,6 +47270,7 @@ function dtoToKaminoReserve(reserveDto) {
47167
47270
  protocolTakeRatePct: reserveDto.config.protocolTakeRatePct,
47168
47271
  hostFixedInterestRateBps: reserveDto.config.hostFixedInterestRateBps,
47169
47272
  interestRateBasis: reserveDto.config.interestRateBasis ?? 0 /* Legacy */,
47273
+ emergencyMode: reserveDto.config.emergencyMode ?? 0,
47170
47274
  depositLimit: new BN8__default.default(reserveDto.config.depositLimit),
47171
47275
  borrowLimit: new BN8__default.default(reserveDto.config.borrowLimit),
47172
47276
  borrowRateCurve: {
@@ -47467,34 +47571,27 @@ function makeRefreshKaminoBanksIxs(marginfiAccount, bankMap, newBanksPk, bankMet
47467
47571
  const kaminoBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 3 /* KAMINO */);
47468
47572
  if (kaminoBanks.length > 0) {
47469
47573
  const newBanksPkBase = newBanksPk.map((pk2) => pk2.toBase58());
47470
- const banksToRefreshObligations = kaminoBanks.filter(
47471
- (bank) => newBanksPkBase.includes(bank.address.toBase58())
47472
- );
47473
- const refreshReserveData = kaminoBanks.map((kaminoBank) => {
47474
- const bankMetadata = bankMetadataMap?.[kaminoBank.address.toBase58()];
47475
- if (!bankMetadata?.kaminoStates) return;
47476
- if (!kaminoBank.kaminoIntegrationAccounts) return;
47477
- const kaminoReserve = kaminoBank.kaminoIntegrationAccounts.kaminoReserve;
47478
- const lendingMarket = bankMetadata.kaminoStates.reserveState.lendingMarket;
47574
+ const refreshes = kaminoBanks.map((kaminoBank) => {
47575
+ const kaminoStates = bankMetadataMap[kaminoBank.address.toBase58()]?.kaminoStates;
47576
+ if (!kaminoStates || !kaminoBank.kaminoIntegrationAccounts) {
47577
+ throw TransactionBuildingError.kaminoReserveNotFound(
47578
+ kaminoBank.address.toBase58(),
47579
+ kaminoBank.mint.toBase58(),
47580
+ kaminoBank.tokenSymbol
47581
+ );
47582
+ }
47479
47583
  return {
47480
- reserve: kaminoReserve,
47481
- lendingMarket
47584
+ bank: kaminoBank.address.toBase58(),
47585
+ reserve: kaminoBank.kaminoIntegrationAccounts.kaminoReserve,
47586
+ obligation: kaminoBank.kaminoIntegrationAccounts.kaminoObligation,
47587
+ lendingMarket: kaminoStates.reserveState.lendingMarket
47482
47588
  };
47483
- }).filter((bank) => !!bank);
47484
- const reserveIx = makeRefreshReservesBatchIx(refreshReserveData);
47485
- ixs.push(reserveIx);
47486
- for (const kaminoBank of banksToRefreshObligations) {
47487
- const bankMetadata = bankMetadataMap?.[kaminoBank.address.toBase58()];
47488
- if (!bankMetadata?.kaminoStates) continue;
47489
- if (!kaminoBank.kaminoIntegrationAccounts) continue;
47490
- const kaminoReserve = kaminoBank.kaminoIntegrationAccounts.kaminoReserve;
47491
- const lendingMarket = bankMetadata.kaminoStates.reserveState.lendingMarket;
47492
- const obligationIx = makeRefreshObligationIx(
47493
- lendingMarket,
47494
- kaminoBank.kaminoIntegrationAccounts.kaminoObligation,
47495
- kaminoReserve
47496
- );
47497
- ixs.push(obligationIx);
47589
+ });
47590
+ ixs.push(makeRefreshReservesBatchIx(refreshes));
47591
+ for (const { bank, reserve, obligation, lendingMarket } of refreshes) {
47592
+ if (newBanksPkBase.includes(bank)) {
47593
+ ixs.push(makeRefreshObligationIx(lendingMarket, obligation, reserve));
47594
+ }
47498
47595
  }
47499
47596
  }
47500
47597
  return {
@@ -62026,15 +62123,17 @@ function makeUpdateDriftMarketIxs(marginfiAccount, bankMap, banksToExclude, bank
62026
62123
  const allActiveBanks = activeBanksPk.filter((pk2) => !banksToExcludeSet.has(pk2.toBase58())).map((pk2) => bankMap.get(pk2.toBase58()));
62027
62124
  const driftBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 4);
62028
62125
  if (driftBanks.length > 0) {
62029
- const refreshReserveData = driftBanks.map((driftBank) => {
62030
- const bankMetadata = bankMetadataMap?.[driftBank.address.toBase58()];
62031
- if (!bankMetadata?.driftStates) return;
62032
- const driftSpotMarket = bankMetadata.driftStates.spotMarketState;
62033
- return driftSpotMarket;
62034
- }).filter((bank) => !!bank);
62035
- const updateDriftMarketIxs = refreshReserveData.map(
62036
- (market) => makeUpdateSpotMarketIx({ spotMarket: market })
62037
- );
62126
+ const updateDriftMarketIxs = driftBanks.map((driftBank) => {
62127
+ const driftStates = bankMetadataMap[driftBank.address.toBase58()]?.driftStates;
62128
+ if (!driftStates) {
62129
+ throw TransactionBuildingError.driftStateNotFound(
62130
+ driftBank.address.toBase58(),
62131
+ driftBank.mint.toBase58(),
62132
+ driftBank.tokenSymbol
62133
+ );
62134
+ }
62135
+ return makeUpdateSpotMarketIx({ spotMarket: driftStates.spotMarketState });
62136
+ });
62038
62137
  ixs.push(...updateDriftMarketIxs);
62039
62138
  }
62040
62139
  return {
@@ -64323,12 +64422,16 @@ function makeUpdateJupLendRateIxs(marginfiAccount, bankMap, banksToExclude, bank
64323
64422
  const jupLendBanks = allActiveBanks.filter((bank) => bank.config.assetTag === 6 /* JUPLEND */);
64324
64423
  if (jupLendBanks.length > 0) {
64325
64424
  const updateRateIxs = jupLendBanks.map((bank) => {
64326
- const bankMetadata = bankMetadataMap?.[bank.address.toBase58()];
64327
- if (!bankMetadata?.jupLendStates) return;
64328
- return makeUpdateJupLendRate({
64329
- lendingState: bankMetadata.jupLendStates.jupLendingState
64330
- });
64331
- }).filter((ix) => !!ix);
64425
+ const jupLendStates = bankMetadataMap[bank.address.toBase58()]?.jupLendStates;
64426
+ if (!jupLendStates) {
64427
+ throw TransactionBuildingError.jupLendStateNotFound(
64428
+ bank.address.toBase58(),
64429
+ bank.mint.toBase58(),
64430
+ bank.tokenSymbol
64431
+ );
64432
+ }
64433
+ return makeUpdateJupLendRate({ lendingState: jupLendStates.jupLendingState });
64434
+ });
64332
64435
  ixs.push(...updateRateIxs);
64333
64436
  }
64334
64437
  return {
@@ -74885,7 +74988,7 @@ function getAssetWeight(params) {
74885
74988
  if (bank.config.riskTier === "Isolated" /* Isolated */) {
74886
74989
  return new BigNumber3__default.default(0);
74887
74990
  }
74888
- if (marginRequirement === 0 /* Initial */ && bank.config.operationalState === "ReduceOnly" /* ReduceOnly */) {
74991
+ if (marginRequirement === 0 /* Initial */ && (bank.config.operationalState === "ReduceOnly" /* ReduceOnly */ || bank.kaminoEmergency)) {
74889
74992
  return new BigNumber3__default.default(0);
74890
74993
  }
74891
74994
  const assetWeightInit = BigNumber3__default.default.max(
@@ -75134,13 +75237,13 @@ function computeInterestRates(bank) {
75134
75237
  const borrowingRate = baseInterestRate.times(new BigNumber3__default.default(1).plus(rateFee)).plus(fixedFee);
75135
75238
  return { lendingRate, borrowingRate };
75136
75239
  }
75137
- var U32_MAX = 4294967295;
75240
+ var U32_MAX2 = 4294967295;
75138
75241
  function rateFromU32(rate) {
75139
- const ratio = new BigNumber3__default.default(rate).div(U32_MAX);
75242
+ const ratio = new BigNumber3__default.default(rate).div(U32_MAX2);
75140
75243
  return ratio.times(10);
75141
75244
  }
75142
75245
  function utilFromU32(util) {
75143
- return new BigNumber3__default.default(util).div(U32_MAX);
75246
+ return new BigNumber3__default.default(util).div(U32_MAX2);
75144
75247
  }
75145
75248
  function calculateRateBetweenPoints(startX, startY, endX, endY, targetX) {
75146
75249
  if (endX.lte(startX)) return startY;
@@ -75651,6 +75754,10 @@ function makePoolConfigureBankIx(mfiProgram, accounts, args) {
75651
75754
  bank
75652
75755
  }).accountsPartial(optionalAccounts).instruction();
75653
75756
  }
75757
+ function makePoolConfigureBankGovIx(mfiProgram, accounts, args) {
75758
+ const { bank, ...optionalAccounts } = accounts;
75759
+ return mfiProgram.methods.lendingPoolConfigureBankGov(args.bankConfigOpt).accounts({ bank }).accountsPartial(optionalAccounts).instruction();
75760
+ }
75654
75761
  function makeBeginFlashLoanIx(mfiProgram, accounts, args) {
75655
75762
  const { marginfiAccount, ...optionalAccounts } = accounts;
75656
75763
  return mfiProgram.methods.lendingAccountStartFlashloan(args.endIndex).accounts({
@@ -75694,7 +75801,9 @@ async function makeLendingPoolConfigureBankOracleIx(mfProgram, accounts, args, r
75694
75801
  }
75695
75802
  async function makeLendingPoolConfigureBankOracleScopeIx(mfProgram, accounts, args) {
75696
75803
  const { bank, ...optionalAccounts } = accounts;
75697
- return mfProgram.methods.lendingPoolConfigureBankOracleScope(args.oracle, args.entryIndex).accounts({ bank }).accountsPartial(optionalAccounts).remainingAccounts([{ pubkey: args.oracle, isSigner: false, isWritable: false }]).instruction();
75804
+ return mfProgram.methods.lendingPoolConfigureBankOracleScope(args.oracle, args.entryIndex).accounts({ bank }).accountsPartial(optionalAccounts).remainingAccounts(
75805
+ [args.oracle, args.integrationAccount].filter((pubkey) => pubkey !== void 0).map((pubkey) => ({ pubkey, isSigner: false, isWritable: false }))
75806
+ ).instruction();
75698
75807
  }
75699
75808
  async function makeLendingPoolSetOraclePriceIx(mfProgram, accounts, args, remainingAccounts = []) {
75700
75809
  const { bank, ...optionalAccounts } = accounts;
@@ -75750,6 +75859,22 @@ async function makePulseHealthIx(mfProgram, accounts, remainingAccounts = []) {
75750
75859
  group: accounts.group
75751
75860
  }).remainingAccounts(remainingAccounts).instruction();
75752
75861
  }
75862
+ async function makePlaceOrderIx(mfProgram, accounts, args, remainingAccounts = []) {
75863
+ const { marginfiAccount, feePayer, authority, order, globalFeeWallet, ...optionalAccounts } = accounts;
75864
+ return mfProgram.methods.marginfiAccountPlaceOrder(args.bankKeys, args.trigger).accounts({
75865
+ marginfiAccount,
75866
+ feePayer,
75867
+ order
75868
+ }).accountsPartial({ authority, globalFeeWallet, ...optionalAccounts }).remainingAccounts(remainingAccounts).instruction();
75869
+ }
75870
+ async function makeCloseOrderIx(mfProgram, accounts, remainingAccounts = []) {
75871
+ const { marginfiAccount, authority, order, feeRecipient, ...optionalAccounts } = accounts;
75872
+ return mfProgram.methods.marginfiAccountCloseOrder().accounts({
75873
+ authority,
75874
+ order,
75875
+ feeRecipient
75876
+ }).accountsPartial({ marginfiAccount, ...optionalAccounts }).remainingAccounts(remainingAccounts).instruction();
75877
+ }
75753
75878
  var instructions = {
75754
75879
  makeDepositIx,
75755
75880
  makeJuplendDepositIx,
@@ -75766,6 +75891,7 @@ var instructions = {
75766
75891
  makeLendingAccountLiquidateIx,
75767
75892
  makePoolAddBankIx,
75768
75893
  makePoolConfigureBankIx,
75894
+ makePoolConfigureBankGovIx,
75769
75895
  makeBeginFlashLoanIx,
75770
75896
  makeEndFlashLoanIx,
75771
75897
  makeAccountTransferToNewAccountIx,
@@ -75775,37 +75901,30 @@ var instructions = {
75775
75901
  makeLendingPoolConfigureBankOracleIx,
75776
75902
  makeLendingPoolConfigureBankOracleScopeIx,
75777
75903
  makeLendingPoolSetOraclePriceIx,
75778
- makePulseHealthIx
75904
+ makePulseHealthIx,
75905
+ makePlaceOrderIx,
75906
+ makeCloseOrderIx
75779
75907
  };
75780
75908
  var instructions_default3 = instructions;
75781
75909
 
75782
75910
  // src/services/bank/bank.service.ts
75783
- async function freezeBankConfigIx(program, bankAddress, bankConfigOpt) {
75784
- const bankConfigRaw = serializeBankConfigOpt(bankConfigOpt);
75785
- const ix = await instructions_default3.makePoolConfigureBankIx(
75911
+ async function freezeBankConfigIx(program, bankAddress) {
75912
+ const ix = await instructions_default3.makePoolConfigureBankGovIx(
75786
75913
  program,
75787
- {
75788
- bank: bankAddress
75789
- },
75914
+ { bank: bankAddress },
75790
75915
  {
75791
75916
  bankConfigOpt: {
75792
- ...bankConfigRaw,
75793
75917
  assetWeightInit: null,
75794
75918
  assetWeightMaint: null,
75795
75919
  liabilityWeightInit: null,
75796
75920
  liabilityWeightMaint: null,
75797
- depositLimit: null,
75798
- borrowLimit: null,
75921
+ operationalState: null,
75799
75922
  riskTier: null,
75800
75923
  assetTag: null,
75801
- totalAssetValueInitLimit: null,
75802
- interestRateConfig: null,
75803
- operationalState: null,
75804
- oracleMaxAge: null,
75805
- permissionlessBadDebtSettlement: null,
75806
- freezeSettings: true,
75807
75924
  oracleMaxConfidence: null,
75808
- tokenlessRepaymentsAllowed: null
75925
+ oracleMaxAge: null,
75926
+ tokenlessRepaymentsAllowed: null,
75927
+ freezeSettings: true
75809
75928
  }
75810
75929
  }
75811
75930
  );
@@ -75822,11 +75941,12 @@ async function addOracleToBanksIx({
75822
75941
  oracleAccounts,
75823
75942
  setup,
75824
75943
  groupAddress,
75825
- adminAddress
75944
+ governanceAdminAddress
75826
75945
  }) {
75827
- if (setup === "Scope" /* Scope */ || setup === "PTPyth" /* PTPyth */ || setup === "PTFixed" /* PTFixed */ || setup === "Fixed" /* Fixed */ || setup === "FixedKamino" /* FixedKamino */ || setup === "FixedDrift" /* FixedDrift */ || setup === "FixedJuplend" /* FixedJuplend */) {
75946
+ const isScope = setup === "Scope" /* Scope */ || setup === "ScopeKamino" /* ScopeKamino */ || setup === "ScopeJuplend" /* ScopeJuplend */;
75947
+ if (isScope || setup === "PTPyth" /* PTPyth */ || setup === "PTFixed" /* PTFixed */ || setup === "Fixed" /* Fixed */ || setup === "FixedKamino" /* FixedKamino */ || setup === "FixedDrift" /* FixedDrift */ || setup === "FixedJuplend" /* FixedJuplend */) {
75828
75948
  throw new Error(
75829
- `${setup} must be configured with ${setup === "Scope" /* Scope */ ? "configureScopeOracleIx" : "setOraclePriceIx"}`
75949
+ `${setup} must be configured with ${isScope ? "configureScopeOracleIx" : "setOraclePriceIx"}`
75830
75950
  );
75831
75951
  }
75832
75952
  const resolvedOracleAccounts = oracleAccounts ?? (oracleKey ? [oracleKey] : []);
@@ -75844,7 +75964,7 @@ async function addOracleToBanksIx({
75844
75964
  {
75845
75965
  bank: bankAddress,
75846
75966
  group: groupAddress,
75847
- admin: adminAddress
75967
+ governanceAdmin: governanceAdminAddress
75848
75968
  },
75849
75969
  {
75850
75970
  setup: serializeOracleSetupToIndex(setup),
@@ -75868,7 +75988,7 @@ async function setOraclePriceIx({
75868
75988
  setup,
75869
75989
  oracleAccounts = [],
75870
75990
  groupAddress,
75871
- adminAddress
75991
+ governanceAdminAddress
75872
75992
  }) {
75873
75993
  const expectedAccountCount = setup === "PTPyth" /* PTPyth */ ? 2 : setup === "PTFixed" /* PTFixed */ ? 1 : void 0;
75874
75994
  if (expectedAccountCount !== void 0 && oracleAccounts.length !== expectedAccountCount) {
@@ -75879,7 +75999,7 @@ async function setOraclePriceIx({
75879
75999
  {
75880
76000
  bank: bankAddress,
75881
76001
  group: groupAddress,
75882
- admin: adminAddress
76002
+ governanceAdmin: governanceAdminAddress
75883
76003
  },
75884
76004
  {
75885
76005
  price: bigNumberToWrappedI80F48(price),
@@ -75894,22 +76014,24 @@ async function setOraclePriceIx({
75894
76014
  }
75895
76015
  async function configureScopeOracleIx({
75896
76016
  program,
75897
- bankAddress,
76017
+ bank,
75898
76018
  oracle,
75899
76019
  entryIndex,
75900
76020
  groupAddress,
75901
- adminAddress
76021
+ governanceAdminAddress
75902
76022
  }) {
75903
76023
  const ix = await instructions_default3.makeLendingPoolConfigureBankOracleScopeIx(
75904
76024
  program,
75905
76025
  {
75906
- bank: bankAddress,
76026
+ bank: bank.address,
75907
76027
  group: groupAddress,
75908
- admin: adminAddress
76028
+ governanceAdmin: governanceAdminAddress
75909
76029
  },
75910
76030
  {
75911
76031
  oracle,
75912
- entryIndex
76032
+ entryIndex,
76033
+ // ScopeKamino / ScopeJuplend validate the Kamino reserve or JupLend lending account after the feed
76034
+ integrationAccount: bank.config.assetTag === 3 /* KAMINO */ || bank.config.assetTag === 6 /* JUPLEND */ ? bank.config.oracleKeys[1] : void 0
75913
76035
  }
75914
76036
  );
75915
76037
  return {
@@ -75941,9 +76063,25 @@ function decodeAccountRaw(encoded, idl) {
75941
76063
  const coder = new anchor.BorshCoder(idl);
75942
76064
  return coder.accounts.decode("marginfiAccount" /* MarginfiAccount */, encoded);
75943
76065
  }
76066
+ function parseOrderRaw(orderAddress, orderRaw) {
76067
+ let trigger = "stopLoss";
76068
+ if ("takeProfit" in orderRaw.trigger) trigger = "takeProfit";
76069
+ if ("both" in orderRaw.trigger) trigger = "both";
76070
+ return {
76071
+ address: orderAddress,
76072
+ marginfiAccount: orderRaw.marginfiAccount,
76073
+ trigger,
76074
+ stopLoss: trigger === "takeProfit" ? null : wrappedI80F48toBigNumber(orderRaw.stopLoss),
76075
+ takeProfit: trigger === "stopLoss" ? null : wrappedI80F48toBigNumber(orderRaw.takeProfit),
76076
+ tags: [orderRaw.tags[0], orderRaw.tags[1]],
76077
+ createdAt: orderRaw.createdAt.toNumber(),
76078
+ maxSlippagePercent: maxSlippageU32ToPercent(orderRaw.maxSlippage)
76079
+ };
76080
+ }
75944
76081
  function parseBalanceRaw(balanceRaw) {
75945
76082
  const active = typeof balanceRaw.active === "number" ? balanceRaw.active === 1 : balanceRaw.active;
75946
76083
  const bankPk = balanceRaw.bankPk;
76084
+ const tag = balanceRaw.tag;
75947
76085
  const assetShares = wrappedI80F48toBigNumber(balanceRaw.assetShares);
75948
76086
  const liabilityShares = wrappedI80F48toBigNumber(balanceRaw.liabilityShares);
75949
76087
  const premiumRate = rateFromU32(balanceRaw.premiumRateSnapshot);
@@ -75952,6 +76090,7 @@ function parseBalanceRaw(balanceRaw) {
75952
76090
  return {
75953
76091
  active,
75954
76092
  bankPk,
76093
+ tag,
75955
76094
  assetShares,
75956
76095
  liabilityShares,
75957
76096
  premiumRate,
@@ -75999,7 +76138,8 @@ function parseMarginfiAccountRaw(marginfiAccountPk, accountData) {
75999
76138
  balances,
76000
76139
  accountFlags,
76001
76140
  emissionsDestinationAccount,
76002
- healthCache
76141
+ healthCache,
76142
+ activeOrders: accountData.activeOrders
76003
76143
  };
76004
76144
  }
76005
76145
  function getActiveAccountFlags(flags) {
@@ -76055,13 +76195,15 @@ function dtoToMarginfiAccount(marginfiAccountDto) {
76055
76195
  balances: marginfiAccountDto.balances.map(dtoToBalance),
76056
76196
  accountFlags: marginfiAccountDto.accountFlags,
76057
76197
  emissionsDestinationAccount: new web3_js.PublicKey(marginfiAccountDto.emissionsDestinationAccount),
76058
- healthCache: dtoToHealthCache(marginfiAccountDto.healthCache)
76198
+ healthCache: dtoToHealthCache(marginfiAccountDto.healthCache),
76199
+ activeOrders: marginfiAccountDto.activeOrders ?? 0
76059
76200
  };
76060
76201
  }
76061
76202
  function dtoToBalance(balanceDto) {
76062
76203
  return {
76063
76204
  active: balanceDto.active,
76064
76205
  bankPk: new web3_js.PublicKey(balanceDto.bankPk),
76206
+ tag: balanceDto.tag ?? 0,
76065
76207
  assetShares: new BigNumber3__default.default(balanceDto.assetShares),
76066
76208
  liabilityShares: new BigNumber3__default.default(balanceDto.liabilityShares),
76067
76209
  premiumRate: new BigNumber3__default.default(balanceDto.premiumRate),
@@ -76094,13 +76236,15 @@ function marginfiAccountToDto(marginfiAccount) {
76094
76236
  balances: marginfiAccount.balances.map(balanceToDto),
76095
76237
  accountFlags: marginfiAccount.accountFlags,
76096
76238
  emissionsDestinationAccount: marginfiAccount.emissionsDestinationAccount.toBase58(),
76097
- healthCache: healthCacheToDto(marginfiAccount.healthCache)
76239
+ healthCache: healthCacheToDto(marginfiAccount.healthCache),
76240
+ activeOrders: marginfiAccount.activeOrders
76098
76241
  };
76099
76242
  }
76100
76243
  function balanceToDto(balance) {
76101
76244
  return {
76102
76245
  active: balance.active,
76103
76246
  bankPk: balance.bankPk.toBase58(),
76247
+ tag: balance.tag,
76104
76248
  assetShares: balance.assetShares.toString(),
76105
76249
  liabilityShares: balance.liabilityShares.toString(),
76106
76250
  premiumRate: balance.premiumRate.toString(),
@@ -76583,6 +76727,23 @@ function getBalanceUsdValueWithPriceBias(params) {
76583
76727
  );
76584
76728
  return { assets: assetsValue, liabilities: liabilitiesValue };
76585
76729
  }
76730
+ function computeOrderPairNetValue(params) {
76731
+ const { collateral, debt } = params;
76732
+ const { assets: collateralUsd } = getBalanceUsdValueWithPriceBias({
76733
+ balance: collateral.balance,
76734
+ bank: collateral.bank,
76735
+ oraclePrice: collateral.oraclePrice,
76736
+ marginRequirement: 2 /* Equity */,
76737
+ assetShareValueMultiplier: collateral.assetShareValueMultiplier
76738
+ });
76739
+ const { liabilities: debtUsd } = getBalanceUsdValueWithPriceBias({
76740
+ balance: debt.balance,
76741
+ bank: debt.bank,
76742
+ oraclePrice: debt.oraclePrice,
76743
+ marginRequirement: 2 /* Equity */
76744
+ });
76745
+ return { collateralUsd, debtUsd, netUsd: collateralUsd.minus(debtUsd) };
76746
+ }
76586
76747
  function computeQuantity(balance, bank) {
76587
76748
  const assetsQuantity = getAssetQuantity(bank, balance.assetShares);
76588
76749
  const liabilitiesQuantity = getLiabilityQuantity(bank, balance.liabilityShares).plus(
@@ -76804,6 +76965,7 @@ function createEmptyBalance(bankPk) {
76804
76965
  const balance = {
76805
76966
  active: false,
76806
76967
  bankPk,
76968
+ tag: 0,
76807
76969
  assetShares: new BigNumber3__default.default(0),
76808
76970
  liabilityShares: new BigNumber3__default.default(0),
76809
76971
  premiumRate: new BigNumber3__default.default(0),
@@ -76818,6 +76980,18 @@ function getActiveBalances(balances) {
76818
76980
  function getBalance(bankAddress, balances) {
76819
76981
  return balances.filter((b) => b.active).find((b) => b.bankPk.equals(bankAddress)) ?? createEmptyBalance(bankAddress);
76820
76982
  }
76983
+ var EMPTY_BALANCE_THRESHOLD = 1;
76984
+ function resolveOrderLegs(marginfiAccount, order) {
76985
+ const taggedBalances = marginfiAccount.balances.filter(
76986
+ (balance) => balance.active && balance.tag !== 0 && order.tags.includes(balance.tag)
76987
+ );
76988
+ return {
76989
+ collateralBank: taggedBalances.find(
76990
+ (balance) => balance.liabilityShares.lt(EMPTY_BALANCE_THRESHOLD) && balance.assetShares.gte(EMPTY_BALANCE_THRESHOLD)
76991
+ )?.bankPk ?? null,
76992
+ debtBank: taggedBalances.find((balance) => balance.liabilityShares.gte(EMPTY_BALANCE_THRESHOLD))?.bankPk ?? null
76993
+ };
76994
+ }
76821
76995
  function computeAccountValue(marginfiAccount) {
76822
76996
  const { assets, liabilities } = computeHealthComponentsFromCache(
76823
76997
  marginfiAccount,
@@ -77083,6 +77257,7 @@ function computeProjectedActiveBalancesNoCpi({
77083
77257
  const projectedBalances = account.balances.map((b) => ({
77084
77258
  active: b.active,
77085
77259
  bankPk: b.bankPk,
77260
+ tag: b.tag,
77086
77261
  assetShares: new BigNumber3__default.default(b.assetShares),
77087
77262
  liabilityShares: new BigNumber3__default.default(b.liabilityShares),
77088
77263
  premiumRate: new BigNumber3__default.default(b.premiumRate),
@@ -77364,6 +77539,26 @@ var fetchMarginfiAccountData = async (program, marginfiAccountPk, banksMap, bank
77364
77539
  return { marginfiAccount };
77365
77540
  }
77366
77541
  };
77542
+ var fetchOrdersForAccount = async (program, marginfiAccount) => {
77543
+ const orders = await program.account.order.all([
77544
+ {
77545
+ memcmp: {
77546
+ bytes: marginfiAccount.toBase58(),
77547
+ offset: 8
77548
+ // first field after the discriminator
77549
+ }
77550
+ }
77551
+ ]);
77552
+ return orders.map(({ publicKey: publicKey5, account }) => parseOrderRaw(publicKey5, account));
77553
+ };
77554
+ var fetchOrderFees = async (program) => {
77555
+ const [feeStateAddress] = deriveFeeState(program.programId);
77556
+ const feeState = await program.account.feeState.fetch(feeStateAddress);
77557
+ return {
77558
+ placementFeeLamports: feeState.orderInitFlatSolFee,
77559
+ executionMaxFee: wrappedI80F48toBigNumber(feeState.orderExecutionMaxFee)
77560
+ };
77561
+ };
77367
77562
  function randomDistinctIndices(count, maxExclusive) {
77368
77563
  const chosen = /* @__PURE__ */ new Set();
77369
77564
  while (chosen.size < count) {
@@ -77487,18 +77682,27 @@ function computeMaxBorrowForBank(params) {
77487
77682
  BigNumber3__default.default.min(healthMaxBorrow, borrowCapRemaining, availableLiquidity, rateLimitRemaining)
77488
77683
  );
77489
77684
  }
77490
- function computeOutflowRateLimitRemaining(bank, oraclePrice, groupRateLimiter, assetShareValueMultiplier) {
77685
+ function computeBankOutflowRateLimit(bank, assetShareValueMultiplier) {
77686
+ if (!bank.rateLimiter) return null;
77491
77687
  const nowSeconds = Date.now() / 1e3;
77492
- let remaining = new BigNumber3__default.default(Infinity);
77493
- let bankRemaining = computeBankRateLimitRemaining(bank, nowSeconds);
77494
- if (bankRemaining !== null) {
77495
- const limiterInBankMintUnits = bank.config.assetTag === 3 /* KAMINO */ || bank.config.assetTag === 2 /* STAKED */;
77496
- if (limiterInBankMintUnits && assetShareValueMultiplier?.gt(0)) {
77497
- bankRemaining = bankRemaining.times(assetShareValueMultiplier);
77498
- }
77499
- remaining = BigNumber3__default.default.min(remaining, bankRemaining);
77688
+ const limiterToUnderlying = bank.config.assetTag === 2 /* STAKED */ && assetShareValueMultiplier?.gt(0) ? assetShareValueMultiplier : new BigNumber3__default.default(1);
77689
+ let tightest = null;
77690
+ for (const window of ["hourly", "daily"]) {
77691
+ const remainingNative = computeRateLimitWindowRemainingCapacity(
77692
+ bank.rateLimiter[window],
77693
+ nowSeconds
77694
+ );
77695
+ if (!remainingNative) continue;
77696
+ const remaining = BigNumber3__default.default.max(0, nativeToUi(remainingNative, bank.mintDecimals)).times(
77697
+ limiterToUnderlying
77698
+ );
77699
+ if (!tightest || remaining.lt(tightest.remaining)) tightest = { window, remaining };
77500
77700
  }
77501
- const groupRemainingUsd = computeGroupRateLimitRemainingUsd(groupRateLimiter, nowSeconds);
77701
+ return tightest;
77702
+ }
77703
+ function computeOutflowRateLimitRemaining(bank, oraclePrice, groupRateLimiter, assetShareValueMultiplier) {
77704
+ let remaining = computeBankOutflowRateLimit(bank, assetShareValueMultiplier)?.remaining ?? new BigNumber3__default.default(Infinity);
77705
+ const groupRemainingUsd = computeGroupRateLimitRemainingUsd(groupRateLimiter);
77502
77706
  if (groupRemainingUsd !== null) {
77503
77707
  const price = getPrice(oraclePrice, 1 /* None */, false);
77504
77708
  if (price.gt(0)) remaining = BigNumber3__default.default.min(remaining, groupRemainingUsd.div(price));
@@ -78363,6 +78567,26 @@ function isWholePosition(position, amount, mintDecimals) {
78363
78567
  const closePositionTokenAmount = computeClosePositionTokenAmount(position, mintDecimals);
78364
78568
  return amount >= closePositionTokenAmount;
78365
78569
  }
78570
+ function isCostlyBank(bank) {
78571
+ return [
78572
+ 3 /* KAMINO */,
78573
+ 4 /* DRIFT */,
78574
+ 5 /* SOLEND */,
78575
+ 6 /* JUPLEND */,
78576
+ 2 /* STAKED */
78577
+ ].includes(bank.config.assetTag);
78578
+ }
78579
+ function exceedsCostlyPositionLimit(balances, bankMap, bank) {
78580
+ const active = balances.filter((balance) => balance.active);
78581
+ if (!isCostlyBank(bank) || active.some((balance) => balance.bankPk.equals(bank.address))) {
78582
+ return false;
78583
+ }
78584
+ const held = active.filter((balance) => {
78585
+ const heldBank = bankMap.get(balance.bankPk.toBase58());
78586
+ return heldBank !== void 0 && isCostlyBank(heldBank);
78587
+ }).length;
78588
+ return held >= MAX_COSTLY_POSITIONS;
78589
+ }
78366
78590
  var KAMINO_PROGRAM_ID = new web3_js.PublicKey("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD");
78367
78591
  var FARMS_PROGRAM_ID2 = new web3_js.PublicKey("FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr");
78368
78592
  function encodeU642(value) {
@@ -78375,11 +78599,6 @@ function encodeU8(value) {
78375
78599
  buf.writeUInt8(value, 0);
78376
78600
  return buf;
78377
78601
  }
78378
- function encodeU16(value) {
78379
- const buf = Buffer.alloc(2);
78380
- buf.writeUInt16LE(value, 0);
78381
- return buf;
78382
- }
78383
78602
  function encodeBool(value) {
78384
78603
  const buf = Buffer.alloc(1);
78385
78604
  buf.writeUInt8(value ? 1 : 0, 0);
@@ -78397,9 +78616,6 @@ function encodeOptionU8(value) {
78397
78616
  }
78398
78617
  return Buffer.concat([Buffer.from([1]), encodeU8(value)]);
78399
78618
  }
78400
- function encodePublicKey(pubkey) {
78401
- return Buffer.from(pubkey.toBytes());
78402
- }
78403
78619
  var DISCRIMINATORS = {
78404
78620
  MARGINFI_ACCOUNT_INITIALIZE: Buffer.from([43, 78, 61, 255, 148, 52, 249, 154]),
78405
78621
  KAMINO_DEPOSIT: Buffer.from([237, 8, 188, 187, 115, 99, 49, 85]),
@@ -78409,16 +78625,11 @@ var DISCRIMINATORS = {
78409
78625
  LENDING_ACCOUNT_WITHDRAW: Buffer.from([36, 72, 74, 19, 210, 210, 192, 192]),
78410
78626
  LENDING_ACCOUNT_BORROW: Buffer.from([4, 126, 116, 53, 48, 5, 212, 31]),
78411
78627
  LENDING_ACCOUNT_LIQUIDATE: Buffer.from([214, 169, 151, 213, 251, 167, 86, 219]),
78412
- LENDING_POOL_ADD_BANK: Buffer.from([215, 68, 72, 78, 208, 218, 103, 182]),
78413
- LENDING_POOL_CONFIGURE_BANK: Buffer.from([121, 173, 156, 40, 93, 148, 56, 237]),
78414
78628
  LENDING_ACCOUNT_START_FLASHLOAN: Buffer.from([14, 131, 33, 220, 81, 186, 180, 107]),
78415
78629
  LENDING_ACCOUNT_END_FLASHLOAN: Buffer.from([105, 124, 201, 106, 153, 2, 8, 156]),
78416
78630
  TRANSFER_TO_NEW_ACCOUNT: Buffer.from([28, 79, 129, 231, 169, 69, 69, 65]),
78417
- MARGINFI_GROUP_INITIALIZE: Buffer.from([255, 67, 67, 26, 94, 31, 34, 20]),
78418
78631
  MARGINFI_ACCOUNT_CLOSE: Buffer.from([186, 221, 93, 34, 50, 97, 194, 241]),
78419
78632
  LENDING_POOL_ADD_BANK_PERMISSIONLESS: Buffer.from([127, 187, 121, 34, 187, 167, 238, 102]),
78420
- LENDING_POOL_CONFIGURE_BANK_ORACLE: Buffer.from([209, 82, 255, 171, 124, 21, 71, 81]),
78421
- LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE: Buffer.from([134, 228, 127, 3, 117, 132, 85, 146]),
78422
78633
  LENDING_ACCOUNT_PULSE_HEALTH: Buffer.from([186, 52, 117, 97, 34, 74, 39, 253]),
78423
78634
  LENDING_ACCOUNT_SORT_BALANCES: Buffer.from([187, 194, 110, 84, 82, 170, 204, 9]),
78424
78635
  DRIFT_DEPOSIT: Buffer.from([252, 63, 250, 201, 98, 55, 130, 12]),
@@ -78812,103 +79023,6 @@ function makeAccountTransferToNewAccountIx2(programId, accounts) {
78812
79023
  data: DISCRIMINATORS.TRANSFER_TO_NEW_ACCOUNT
78813
79024
  });
78814
79025
  }
78815
- function makeGroupInitIx2(programId, accounts, args) {
78816
- const keys = [
78817
- { pubkey: accounts.marginfiGroup, isSigner: true, isWritable: true },
78818
- { pubkey: accounts.admin, isSigner: true, isWritable: true },
78819
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78820
- { pubkey: web3_js.SystemProgram.programId, isSigner: false, isWritable: false }
78821
- ];
78822
- const data = Buffer.concat([
78823
- DISCRIMINATORS.MARGINFI_GROUP_INITIALIZE,
78824
- encodeBool(args?.isArenaGroup ?? false)
78825
- ]);
78826
- return new web3_js.TransactionInstruction({
78827
- keys,
78828
- programId,
78829
- data
78830
- });
78831
- }
78832
- function makePoolConfigureBankIx2(programId, accounts, _args) {
78833
- const keys = [
78834
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78835
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78836
- { pubkey: accounts.bank, isSigner: false, isWritable: true }
78837
- ];
78838
- return new web3_js.TransactionInstruction({
78839
- keys,
78840
- programId,
78841
- data: DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK
78842
- });
78843
- }
78844
- function makeLendingPoolConfigureBankOracleIx2(programId, accounts, args, remainingAccounts = []) {
78845
- const keys = [
78846
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78847
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78848
- { pubkey: accounts.bank, isSigner: false, isWritable: true }
78849
- ];
78850
- keys.push(...remainingAccounts);
78851
- const data = Buffer.concat([
78852
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE,
78853
- encodeU8(args.setup),
78854
- encodePublicKey(args.feedId)
78855
- ]);
78856
- return new web3_js.TransactionInstruction({
78857
- keys,
78858
- programId,
78859
- data
78860
- });
78861
- }
78862
- function makeLendingPoolConfigureBankOracleScopeIx2(programId, accounts, args) {
78863
- const keys = [
78864
- { pubkey: accounts.group, isSigner: false, isWritable: false },
78865
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78866
- { pubkey: accounts.bank, isSigner: false, isWritable: true },
78867
- { pubkey: args.oracle, isSigner: false, isWritable: false }
78868
- ];
78869
- const data = Buffer.concat([
78870
- DISCRIMINATORS.LENDING_POOL_CONFIGURE_BANK_ORACLE_SCOPE,
78871
- encodePublicKey(args.oracle),
78872
- encodeU16(args.entryIndex)
78873
- ]);
78874
- return new web3_js.TransactionInstruction({
78875
- keys,
78876
- programId,
78877
- data
78878
- });
78879
- }
78880
- function makePoolAddBankIx2(programId, accounts, _args) {
78881
- const keys = [
78882
- { pubkey: accounts.marginfiGroup, isSigner: false, isWritable: true },
78883
- { pubkey: accounts.admin, isSigner: true, isWritable: false },
78884
- { pubkey: accounts.feePayer, isSigner: true, isWritable: true },
78885
- { pubkey: accounts.feeState, isSigner: false, isWritable: false },
78886
- { pubkey: accounts.globalFeeWallet, isSigner: false, isWritable: true },
78887
- { pubkey: accounts.bankMint, isSigner: false, isWritable: false },
78888
- { pubkey: accounts.bank, isSigner: true, isWritable: true },
78889
- {
78890
- pubkey: accounts.liquidityVaultAuthority,
78891
- isSigner: false,
78892
- isWritable: false
78893
- },
78894
- { pubkey: accounts.liquidityVault, isSigner: false, isWritable: true },
78895
- {
78896
- pubkey: accounts.insuranceVaultAuthority,
78897
- isSigner: false,
78898
- isWritable: false
78899
- },
78900
- { pubkey: accounts.insuranceVault, isSigner: false, isWritable: true },
78901
- { pubkey: accounts.feeVaultAuthority, isSigner: false, isWritable: false },
78902
- { pubkey: accounts.feeVault, isSigner: false, isWritable: true },
78903
- { pubkey: accounts.tokenProgram, isSigner: false, isWritable: false },
78904
- { pubkey: web3_js.SystemProgram.programId, isSigner: false, isWritable: false }
78905
- ];
78906
- return new web3_js.TransactionInstruction({
78907
- keys,
78908
- programId,
78909
- data: DISCRIMINATORS.LENDING_POOL_ADD_BANK
78910
- });
78911
- }
78912
79026
  function makeDriftDepositIx2(programId, accounts, args) {
78913
79027
  const liquidityVaultAuthority = deriveBankLiquidityVaultAuthority(programId, accounts.bank)[0];
78914
79028
  const keys = [
@@ -79087,16 +79201,11 @@ var syncInstructions = {
79087
79201
  makeKaminoWithdrawIx: makeKaminoWithdrawIx2,
79088
79202
  makeBorrowIx: makeBorrowIx2,
79089
79203
  makeLendingAccountLiquidateIx: makeLendingAccountLiquidateIx2,
79090
- makePoolAddBankIx: makePoolAddBankIx2,
79091
- makePoolConfigureBankIx: makePoolConfigureBankIx2,
79092
79204
  makeBeginFlashLoanIx: makeBeginFlashLoanIx2,
79093
79205
  makeEndFlashLoanIx: makeEndFlashLoanIx2,
79094
79206
  makeAccountTransferToNewAccountIx: makeAccountTransferToNewAccountIx2,
79095
- makeGroupInitIx: makeGroupInitIx2,
79096
79207
  makeCloseAccountIx: makeCloseAccountIx2,
79097
79208
  makePoolAddPermissionlessStakedBankIx: makePoolAddPermissionlessStakedBankIx2,
79098
- makeLendingPoolConfigureBankOracleIx: makeLendingPoolConfigureBankOracleIx2,
79099
- makeLendingPoolConfigureBankOracleScopeIx: makeLendingPoolConfigureBankOracleScopeIx2,
79100
79209
  makePulseHealthIx: makePulseHealthIx2
79101
79210
  };
79102
79211
  var sync_instructions_default = syncInstructions;
@@ -79296,6 +79405,9 @@ async function makeDriftDepositIx3({
79296
79405
  }
79297
79406
  async function makeDriftDepositTx(params) {
79298
79407
  const { luts, connection, amount, ...depositIxParams } = params;
79408
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79409
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79410
+ }
79299
79411
  if (!depositIxParams.bank.driftIntegrationAccounts) {
79300
79412
  throw new Error("Bank has no drift integration accounts");
79301
79413
  }
@@ -79303,13 +79415,17 @@ async function makeDriftDepositTx(params) {
79303
79415
  amount,
79304
79416
  ...depositIxParams
79305
79417
  });
79306
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79307
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79418
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79419
+ params,
79420
+ depositIxs.instructions,
79421
+ [params.bank.address],
79422
+ []
79423
+ );
79308
79424
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79309
79425
  const depositTx = addTransactionMetadata(
79310
79426
  new web3_js.VersionedTransaction(
79311
79427
  new web3_js.TransactionMessage({
79312
- instructions: [...depositIxs.instructions, ...premiumIxs],
79428
+ instructions: instructions2,
79313
79429
  payerKey: params.authority,
79314
79430
  recentBlockhash: blockhash
79315
79431
  }).compileToV0Message(selectedLuts)
@@ -79415,6 +79531,9 @@ async function makeKaminoDepositIx3({
79415
79531
  }
79416
79532
  async function makeKaminoDepositTx(params) {
79417
79533
  const { luts, connection, amount, ...depositIxParams } = params;
79534
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79535
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79536
+ }
79418
79537
  if (!depositIxParams.bank.kaminoIntegrationAccounts) {
79419
79538
  throw new Error("Bank has no kamino integration accounts");
79420
79539
  }
@@ -79439,13 +79558,17 @@ async function makeKaminoDepositTx(params) {
79439
79558
  amount,
79440
79559
  ...depositIxParams
79441
79560
  });
79442
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79443
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79561
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79562
+ params,
79563
+ [...refreshIxs, ...depositIxs.instructions],
79564
+ [params.bank.address],
79565
+ []
79566
+ );
79444
79567
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79445
79568
  const depositTx = addTransactionMetadata(
79446
79569
  new web3_js.VersionedTransaction(
79447
79570
  new web3_js.TransactionMessage({
79448
- instructions: [...refreshIxs, ...depositIxs.instructions, ...premiumIxs],
79571
+ instructions: instructions2,
79449
79572
  payerKey: params.authority,
79450
79573
  recentBlockhash: blockhash
79451
79574
  }).compileToV0Message(selectedLuts)
@@ -79522,10 +79645,17 @@ async function makeDepositIx3({
79522
79645
  }
79523
79646
  async function makeDepositTx(params) {
79524
79647
  const { luts, ...depositIxParams } = params;
79648
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79649
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79650
+ }
79525
79651
  const ixs = await makeDepositIx3(depositIxParams);
79526
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79527
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79528
- const tx = new web3_js.Transaction().add(...ixs.instructions, ...premiumIxs);
79652
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79653
+ params,
79654
+ ixs.instructions,
79655
+ [params.bank.address],
79656
+ []
79657
+ );
79658
+ const tx = new web3_js.Transaction().add(...instructions2);
79529
79659
  tx.feePayer = params.authority;
79530
79660
  const solanaTx = addTransactionMetadata(tx, {
79531
79661
  type: "DEPOSIT" /* DEPOSIT */,
@@ -79601,6 +79731,9 @@ async function makeJuplendDepositIx2({
79601
79731
  }
79602
79732
  async function makeJuplendDepositTx(params) {
79603
79733
  const { luts, connection, amount, ...depositIxParams } = params;
79734
+ if (exceedsCostlyPositionLimit(params.marginfiAccount.balances, params.bankMap, params.bank)) {
79735
+ throw TransactionBuildingError.costlyPositionLimitExceeded(params.bank.address.toBase58());
79736
+ }
79604
79737
  if (!depositIxParams.bank.jupLendIntegrationAccounts) {
79605
79738
  throw new Error("Bank has no JupLend integration accounts");
79606
79739
  }
@@ -79608,13 +79741,17 @@ async function makeJuplendDepositTx(params) {
79608
79741
  amount,
79609
79742
  ...depositIxParams
79610
79743
  });
79611
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, []) ? await makePremiumRefreshIxs(params.program, params, [params.bank.address], []) : [];
79612
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
79744
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
79745
+ params,
79746
+ depositIxs.instructions,
79747
+ [params.bank.address],
79748
+ []
79749
+ );
79613
79750
  const blockhash = params.blockhash ?? (await connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
79614
79751
  const depositTx = addTransactionMetadata(
79615
79752
  new web3_js.VersionedTransaction(
79616
79753
  new web3_js.TransactionMessage({
79617
- instructions: [...depositIxs.instructions, ...premiumIxs],
79754
+ instructions: instructions2,
79618
79755
  payerKey: params.authority,
79619
79756
  recentBlockhash: blockhash
79620
79757
  }).compileToV0Message(selectedLuts)
@@ -80886,9 +81023,13 @@ async function makeRepayTx(params) {
80886
81023
  const { luts, ...repayIxParams } = params;
80887
81024
  const ixs = await makeRepayIx3(repayIxParams);
80888
81025
  const closedBanks = params.repayAll ? [params.bank.address] : [];
80889
- const premiumIxs = !params.opts?.skipPremiumRefresh && needsPremiumRefresh(params.marginfiAccount, params.bankMap, closedBanks) ? await makePremiumRefreshIxs(params.program, params, [], closedBanks) : [];
80890
- const selectedLuts = premiumIxs.length ? selectLutsForAccountAction(luts, params.bank, params.marginfiAccount.balances, params.bankMap) : selectLutsForBanks(luts, [params.bank]);
80891
- const tx = new web3_js.Transaction().add(...ixs.instructions, ...premiumIxs);
81026
+ const { instructions: instructions2, luts: selectedLuts } = await appendPremiumRefresh(
81027
+ params,
81028
+ ixs.instructions,
81029
+ [],
81030
+ closedBanks
81031
+ );
81032
+ const tx = new web3_js.Transaction().add(...instructions2);
80892
81033
  tx.feePayer = params.authority;
80893
81034
  const solanaTx = addTransactionMetadata(tx, {
80894
81035
  type: "REPAY" /* REPAY */,
@@ -80946,23 +81087,11 @@ async function makeRepayWithCollatTx(params) {
80946
81087
  return true;
80947
81088
  });
80948
81089
  setupIxs.push(...jupiterSetupInstructions);
80949
- const additionalTxs = [];
80950
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
80951
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
80952
- const txs = splitInstructionsToFitTransactions([], ixs, {
80953
- blockhash,
80954
- payerKey: marginfiAccount.authority,
80955
- luts: addressLookupTableAccounts ?? []
80956
- });
80957
- additionalTxs.push(
80958
- ...txs.map(
80959
- (tx) => addTransactionMetadata(tx, {
80960
- type: "CREATE_ATA" /* CREATE_ATA */,
80961
- addressLookupTables: addressLookupTableAccounts
80962
- })
80963
- )
80964
- );
80965
- }
81090
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
81091
+ blockhash,
81092
+ payerKey: marginfiAccount.authority,
81093
+ luts: addressLookupTableAccounts ?? []
81094
+ });
80966
81095
  const transactions = [...additionalTxs, flashloanTx];
80967
81096
  return {
80968
81097
  transactions,
@@ -81905,6 +82034,9 @@ async function makeAccountTransferToNewAccountTx({
81905
82034
  newAuthority,
81906
82035
  feePayer
81907
82036
  }) {
82037
+ if (marginfiAccount.accountFlags.includes(1 /* ACCOUNT_DISABLED */)) {
82038
+ throw TransactionBuildingError.accountDisabled(marginfiAccount.address.toBase58());
82039
+ }
81908
82040
  const feePayerKey = feePayer instanceof web3_js.Keypair ? feePayer.publicKey : feePayer ?? marginfiAccount.authority;
81909
82041
  const [feeStateKey] = web3_js.PublicKey.findProgramAddressSync(
81910
82042
  [Buffer.from("feestate", "utf-8")],
@@ -82096,13 +82228,21 @@ async function makePulseHealthIx3(program, marginfiAccount, banks, mandatoryBank
82096
82228
  return { instructions: [ix], keys: [] };
82097
82229
  }
82098
82230
  async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMetadataMap }, mandatoryBanks, excludedBanks) {
82099
- const refreshIxs = makeRefreshIntegrationBanksIxs(
82100
- marginfiAccount,
82101
- bankMap,
82102
- [],
82103
- bankMetadataMap,
82104
- mandatoryBanks
82105
- );
82231
+ let refreshIxs;
82232
+ try {
82233
+ refreshIxs = makeRefreshIntegrationBanksIxs(
82234
+ marginfiAccount,
82235
+ bankMap,
82236
+ [],
82237
+ bankMetadataMap,
82238
+ mandatoryBanks
82239
+ ).instructions;
82240
+ } catch (error) {
82241
+ 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 */)) {
82242
+ return [];
82243
+ }
82244
+ throw error;
82245
+ }
82106
82246
  const pulseIxs = await makePulseHealthIx3(
82107
82247
  program,
82108
82248
  marginfiAccount,
@@ -82110,13 +82250,38 @@ async function makePremiumRefreshIxs(program, { marginfiAccount, bankMap, bankMe
82110
82250
  mandatoryBanks,
82111
82251
  excludedBanks
82112
82252
  );
82113
- return [...refreshIxs.instructions, ...pulseIxs.instructions];
82253
+ return [...refreshIxs, ...pulseIxs.instructions];
82254
+ }
82255
+ async function appendPremiumRefresh(params, actionIxs, mandatoryBanks, excludedBanks) {
82256
+ const { marginfiAccount, bankMap, bank, luts } = params;
82257
+ const actionOnly = { instructions: actionIxs, luts: selectLutsForBanks(luts, [bank]) };
82258
+ if (params.opts?.skipPremiumRefresh || !needsPremiumRefresh(marginfiAccount, bankMap, excludedBanks)) {
82259
+ return actionOnly;
82260
+ }
82261
+ const premiumIxs = await makePremiumRefreshIxs(
82262
+ params.program,
82263
+ params,
82264
+ mandatoryBanks,
82265
+ excludedBanks
82266
+ );
82267
+ const withPremium = {
82268
+ instructions: [...actionIxs, ...premiumIxs],
82269
+ luts: selectLutsForAccountAction(luts, bank, marginfiAccount.balances, bankMap)
82270
+ };
82271
+ const fits = premiumIxs.length > 0 && fitsInOneTransaction(withPremium.instructions, {
82272
+ payerKey: params.authority,
82273
+ luts: withPremium.luts,
82274
+ sizeMargin: PRIORITY_TX_SIZE + BUNDLE_TX_SIZE,
82275
+ maxAccountLocks: MAX_ACCOUNT_LOCKS - 3
82276
+ });
82277
+ return fits ? withPremium : actionOnly;
82114
82278
  }
82115
82279
  function generateDummyAccount(group, authority, accountKey) {
82116
82280
  const dummyWrappedI80F48 = bigNumberToWrappedI80F48(new BigNumber3__default.default(0));
82117
82281
  const dummyBalances = Array(15).fill({
82118
82282
  active: false,
82119
82283
  bankPk: new web3_js.PublicKey("11111111111111111111111111111111"),
82284
+ tag: 0,
82120
82285
  assetShares: dummyWrappedI80F48,
82121
82286
  liabilityShares: dummyWrappedI80F48,
82122
82287
  premiumRateSnapshot: 0,
@@ -82126,7 +82291,7 @@ function generateDummyAccount(group, authority, accountKey) {
82126
82291
  const rawAccount = {
82127
82292
  group,
82128
82293
  authority,
82129
- lendingAccount: { balances: dummyBalances },
82294
+ lendingAccount: { balances: dummyBalances, lastTagUsed: 0 },
82130
82295
  healthCache: {
82131
82296
  assetValue: {
82132
82297
  value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@@ -82148,14 +82313,15 @@ function generateDummyAccount(group, authority, accountKey) {
82148
82313
  mrgnErr: 0
82149
82314
  },
82150
82315
  emissionsDestinationAccount: new web3_js.PublicKey("11111111111111111111111111111111"),
82151
- accountFlags: new BN8__default.default([0, 0, 0])
82316
+ accountFlags: new BN8__default.default([0, 0, 0]),
82317
+ activeOrders: 0
82152
82318
  };
82153
82319
  return parseMarginfiAccountRaw(accountKey, rawAccount);
82154
82320
  }
82155
82321
 
82156
82322
  // src/models/balance.ts
82157
82323
  var Balance = class _Balance {
82158
- constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate) {
82324
+ constructor(active, bankPk, assetShares, liabilityShares, premiumRate, premiumOutstanding, lastUpdate, tag) {
82159
82325
  this.active = active;
82160
82326
  this.bankPk = bankPk;
82161
82327
  this.assetShares = assetShares;
@@ -82163,6 +82329,7 @@ var Balance = class _Balance {
82163
82329
  this.premiumRate = premiumRate;
82164
82330
  this.premiumOutstanding = premiumOutstanding;
82165
82331
  this.lastUpdate = lastUpdate;
82332
+ this.tag = tag;
82166
82333
  }
82167
82334
  static from(balanceRaw) {
82168
82335
  const props = parseBalanceRaw(balanceRaw);
@@ -82173,7 +82340,8 @@ var Balance = class _Balance {
82173
82340
  props.liabilityShares,
82174
82341
  props.premiumRate,
82175
82342
  props.premiumOutstanding,
82176
- props.lastUpdate
82343
+ props.lastUpdate,
82344
+ props.tag
82177
82345
  );
82178
82346
  }
82179
82347
  static fromBalanceType(balance) {
@@ -82184,7 +82352,8 @@ var Balance = class _Balance {
82184
82352
  balance.liabilityShares,
82185
82353
  balance.premiumRate,
82186
82354
  balance.premiumOutstanding,
82187
- balance.lastUpdate
82355
+ balance.lastUpdate,
82356
+ balance.tag
82188
82357
  );
82189
82358
  }
82190
82359
  static createEmpty(bankPk) {
@@ -82254,7 +82423,7 @@ var HealthCache = class _HealthCache {
82254
82423
 
82255
82424
  // src/models/account.ts
82256
82425
  var MarginfiAccount = class _MarginfiAccount {
82257
- constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache) {
82426
+ constructor(address, group, authority, balances, accountFlags, emissionsDestinationAccount, healthCache, activeOrders = 0) {
82258
82427
  this.address = address;
82259
82428
  this.group = group;
82260
82429
  this.authority = authority;
@@ -82262,6 +82431,7 @@ var MarginfiAccount = class _MarginfiAccount {
82262
82431
  this.accountFlags = accountFlags;
82263
82432
  this.emissionsDestinationAccount = emissionsDestinationAccount;
82264
82433
  this.healthCache = healthCache;
82434
+ this.activeOrders = activeOrders;
82265
82435
  }
82266
82436
  /**
82267
82437
  * Fetches a marginfi account from on-chain data.
@@ -82286,7 +82456,8 @@ var MarginfiAccount = class _MarginfiAccount {
82286
82456
  account.balances.map((b) => Balance.fromBalanceType(b)),
82287
82457
  account.accountFlags,
82288
82458
  account.emissionsDestinationAccount,
82289
- account.healthCache
82459
+ account.healthCache,
82460
+ account.activeOrders
82290
82461
  );
82291
82462
  }
82292
82463
  /**
@@ -82306,7 +82477,8 @@ var MarginfiAccount = class _MarginfiAccount {
82306
82477
  props.balances.map((b) => Balance.fromBalanceType(b)),
82307
82478
  props.accountFlags,
82308
82479
  props.emissionsDestinationAccount,
82309
- HealthCache.fromHealthCacheType(props.healthCache)
82480
+ HealthCache.fromHealthCacheType(props.healthCache),
82481
+ props.activeOrders
82310
82482
  );
82311
82483
  }
82312
82484
  /**
@@ -83145,6 +83317,49 @@ var MarginfiAccount = class _MarginfiAccount {
83145
83317
  }
83146
83318
  });
83147
83319
  }
83320
+ // ----------------------------------------------------------------------------
83321
+ // Orders (take-profit / stop-loss)
83322
+ // ----------------------------------------------------------------------------
83323
+ /**
83324
+ * Creates a place-order instruction for this marginfi account.
83325
+ *
83326
+ * @see {@link makePlaceOrderIx} for detailed implementation
83327
+ */
83328
+ async makePlaceOrderIx(params) {
83329
+ return makePlaceOrderIx2({ ...params, marginfiAccount: this });
83330
+ }
83331
+ /**
83332
+ * Creates a transaction placing a take-profit / stop-loss order on a collateral/debt pair.
83333
+ *
83334
+ * @see {@link makePlaceOrderTx} for detailed implementation
83335
+ */
83336
+ async makePlaceOrderTx(params) {
83337
+ return makePlaceOrderTx({ ...params, marginfiAccount: this });
83338
+ }
83339
+ /**
83340
+ * Creates a close-order instruction for this marginfi account.
83341
+ *
83342
+ * @see {@link makeCloseOrderIx} for detailed implementation
83343
+ */
83344
+ async makeCloseOrderIx(params) {
83345
+ return makeCloseOrderIx2({ ...params, marginfiAccount: this });
83346
+ }
83347
+ /**
83348
+ * Creates a transaction closing an existing order.
83349
+ *
83350
+ * @see {@link makeCloseOrderTx} for detailed implementation
83351
+ */
83352
+ async makeCloseOrderTx(params) {
83353
+ return makeCloseOrderTx({ ...params, marginfiAccount: this });
83354
+ }
83355
+ /**
83356
+ * Creates a transaction replacing the pair's existing order with new thresholds.
83357
+ *
83358
+ * @see {@link makeUpdateOrderTx} for detailed implementation
83359
+ */
83360
+ async makeUpdateOrderTx(params) {
83361
+ return makeUpdateOrderTx({ ...params, marginfiAccount: this });
83362
+ }
83148
83363
  /**
83149
83364
  * Creates a repay transaction.
83150
83365
  *
@@ -83303,7 +83518,8 @@ function projectAccountAfterFirstLeg(account, firstLegFlashloanTxs, program, ban
83303
83518
  projectedBalances.map((b) => Balance.fromBalanceType(b)),
83304
83519
  account.accountFlags,
83305
83520
  account.emissionsDestinationAccount,
83306
- account.healthCache
83521
+ account.healthCache,
83522
+ account.activeOrders
83307
83523
  );
83308
83524
  }
83309
83525
  function composeBundle(firstLegTxs, secondLegTxs, payer, blockhash, maxBundleTxs) {
@@ -83447,23 +83663,15 @@ async function makeSwapDebtTx(params) {
83447
83663
  return true;
83448
83664
  });
83449
83665
  setupIxs.push(...jupiterSetupInstructions);
83450
- const additionalTxs = [];
83451
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83452
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83453
- const txs = splitInstructionsToFitTransactions([], ixs, {
83666
+ const additionalTxs = makePreludeTxs(
83667
+ [...additionalIxs, ...setupIxs],
83668
+ refreshIntegrationIxs.instructions,
83669
+ {
83454
83670
  blockhash,
83455
83671
  payerKey: marginfiAccount.authority,
83456
83672
  luts: addressLookupTableAccounts ?? []
83457
- });
83458
- additionalTxs.push(
83459
- ...txs.map(
83460
- (tx) => addTransactionMetadata(tx, {
83461
- type: "CREATE_ATA" /* CREATE_ATA */,
83462
- addressLookupTables: addressLookupTableAccounts
83463
- })
83464
- )
83465
- );
83466
- }
83673
+ }
83674
+ );
83467
83675
  const transactions = [...additionalTxs, flashloanTx];
83468
83676
  return {
83469
83677
  transactions,
@@ -83747,12 +83955,18 @@ async function tryBridgedDebtSwap(params, bridgeOpts) {
83747
83955
  async function makeLoopTx(params) {
83748
83956
  const {
83749
83957
  marginfiAccount,
83958
+ bankMap,
83750
83959
  depositOpts,
83751
83960
  borrowOpts,
83752
83961
  addressLookupTableAccounts,
83753
83962
  connection,
83754
83963
  additionalIxs = []
83755
83964
  } = params;
83965
+ if (exceedsCostlyPositionLimit(marginfiAccount.balances, bankMap, depositOpts.depositBank)) {
83966
+ throw TransactionBuildingError.costlyPositionLimitExceeded(
83967
+ depositOpts.depositBank.address.toBase58()
83968
+ );
83969
+ }
83756
83970
  const blockhash = (await connection.getLatestBlockhash("confirmed")).blockhash;
83757
83971
  const setupIxs = await makeSetupIx({
83758
83972
  connection,
@@ -83792,28 +84006,20 @@ async function makeLoopTx(params) {
83792
84006
  return true;
83793
84007
  });
83794
84008
  setupIxs.push(...jupiterSetupInstructions);
83795
- const additionalTxs = [];
83796
84009
  if (depositOpts.depositBank.mint.equals(NATIVE_MINT) && depositOpts.inputDepositAmount) {
83797
84010
  setupIxs.push(
83798
84011
  ...makeWrapSolIxs(marginfiAccount.authority, new BigNumber3.BigNumber(depositOpts.inputDepositAmount))
83799
84012
  );
83800
84013
  }
83801
- if (setupIxs.length > 0 || additionalIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
83802
- const ixs = [...additionalIxs, ...setupIxs, ...refreshIntegrationIxs.instructions];
83803
- const txs = splitInstructionsToFitTransactions([], ixs, {
84014
+ const additionalTxs = makePreludeTxs(
84015
+ [...additionalIxs, ...setupIxs],
84016
+ refreshIntegrationIxs.instructions,
84017
+ {
83804
84018
  blockhash,
83805
84019
  payerKey: marginfiAccount.authority,
83806
84020
  luts: addressLookupTableAccounts ?? []
83807
- });
83808
- additionalTxs.push(
83809
- ...txs.map(
83810
- (tx) => addTransactionMetadata(tx, {
83811
- type: "CREATE_ATA" /* CREATE_ATA */,
83812
- addressLookupTables: addressLookupTableAccounts
83813
- })
83814
- )
83815
- );
83816
- }
84021
+ }
84022
+ );
83817
84023
  const transactions = [...additionalTxs, flashloanTx];
83818
84024
  return {
83819
84025
  transactions,
@@ -84260,23 +84466,11 @@ async function makeSwapCollateralTx(params) {
84260
84466
  return true;
84261
84467
  });
84262
84468
  setupIxs.push(...jupiterSetupInstructions);
84263
- const additionalTxs = [];
84264
- if (setupIxs.length > 0 || refreshIntegrationIxs.instructions.length > 0) {
84265
- const ixs = [...setupIxs, ...refreshIntegrationIxs.instructions];
84266
- const txs = splitInstructionsToFitTransactions([], ixs, {
84267
- blockhash,
84268
- payerKey: marginfiAccount.authority,
84269
- luts: addressLookupTableAccounts ?? []
84270
- });
84271
- additionalTxs.push(
84272
- ...txs.map(
84273
- (tx) => addTransactionMetadata(tx, {
84274
- type: "CREATE_ATA" /* CREATE_ATA */,
84275
- addressLookupTables: addressLookupTableAccounts
84276
- })
84277
- )
84278
- );
84279
- }
84469
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84470
+ blockhash,
84471
+ payerKey: marginfiAccount.authority,
84472
+ luts: addressLookupTableAccounts ?? []
84473
+ });
84280
84474
  const transactions = [...additionalTxs, flashloanTx];
84281
84475
  return {
84282
84476
  transactions,
@@ -84316,6 +84510,10 @@ async function buildSwapCollateralFlashloanTx({
84316
84510
  actualWithdrawAmount,
84317
84511
  withdrawBank.mintDecimals
84318
84512
  );
84513
+ const balancesAtDeposit = isFullWithdraw ? marginfiAccount.balances.filter((balance) => !balance.bankPk.equals(withdrawBank.address)) : marginfiAccount.balances;
84514
+ if (exceedsCostlyPositionLimit(balancesAtDeposit, bankMap, depositBank)) {
84515
+ throw TransactionBuildingError.costlyPositionLimitExceeded(depositBank.address.toBase58());
84516
+ }
84319
84517
  const cuRequestIxs = [
84320
84518
  web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 }),
84321
84519
  web3_js.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 })
@@ -84707,6 +84905,8 @@ async function makeRollPtTx(params) {
84707
84905
  const {
84708
84906
  marginfiAccount,
84709
84907
  connection,
84908
+ bankMap,
84909
+ bankMetadataMap,
84710
84910
  withdrawOpts,
84711
84911
  depositOpts,
84712
84912
  rollOpts,
@@ -84741,33 +84941,29 @@ async function makeRollPtTx(params) {
84741
84941
  { mint: depositOpts.depositBank.mint, tokenProgram: depositOpts.tokenProgram }
84742
84942
  ]
84743
84943
  });
84944
+ const refreshIntegrationIxs = makeRefreshIntegrationBanksIxs(
84945
+ marginfiAccount,
84946
+ bankMap,
84947
+ [withdrawOpts.withdrawBank.address, depositOpts.depositBank.address],
84948
+ bankMetadataMap
84949
+ );
84744
84950
  const { flashloanTx, swapQuote } = await buildRollPtFlashloanTx({
84745
84951
  params,
84746
84952
  merge,
84747
84953
  clmm,
84748
84954
  blockhash
84749
84955
  });
84750
- const additionalTxs = [];
84751
- if (setupIxs.length > 0) {
84752
- const txs = splitInstructionsToFitTransactions([], setupIxs, {
84753
- blockhash,
84754
- payerKey: marginfiAccount.authority,
84755
- luts: addressLookupTableAccounts ?? []
84756
- });
84757
- additionalTxs.push(
84758
- ...txs.map(
84759
- (tx) => addTransactionMetadata(tx, {
84760
- type: "CREATE_ATA" /* CREATE_ATA */,
84761
- addressLookupTables: addressLookupTableAccounts
84762
- })
84763
- )
84764
- );
84765
- }
84956
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIntegrationIxs.instructions, {
84957
+ blockhash,
84958
+ payerKey: marginfiAccount.authority,
84959
+ luts: addressLookupTableAccounts ?? []
84960
+ });
84766
84961
  const transactions = [...additionalTxs, flashloanTx];
84767
84962
  return {
84768
84963
  transactions,
84769
84964
  actionTxIndex: transactions.length - 1,
84770
- quoteResponse: swapQuote
84965
+ quoteResponse: swapQuote,
84966
+ mustBeAtomicBundle: refreshIntegrationIxs.instructions.length > 0
84771
84967
  };
84772
84968
  }
84773
84969
  async function buildRollPtFlashloanTx({
@@ -85117,6 +85313,13 @@ function classifyAndValidate(params) {
85117
85313
  );
85118
85314
  }
85119
85315
  }
85316
+ const costlyCountB = destPreexistingBanksOf(accountB, bankMap).filter(isCostlyBank).length + positions.filter((p) => p.side === "collateral" && isCostlyBank(p.bank)).length;
85317
+ if (costlyCountB > MAX_COSTLY_POSITIONS) {
85318
+ throw TransactionBuildingError.transferPositionsInvalidSelection(
85319
+ `destination account cannot hold ${costlyCountB} integration and staked positions (max ${MAX_COSTLY_POSITIONS})`,
85320
+ positions.map((p) => p.bankAddress.toBase58())
85321
+ );
85322
+ }
85120
85323
  return positions;
85121
85324
  }
85122
85325
  function buildIntegrationRefreshIxs(args) {
@@ -85450,20 +85653,11 @@ async function makeTransferPositionsTx(params) {
85450
85653
  bankMap,
85451
85654
  bankMetadataMap
85452
85655
  });
85453
- const additionalTxs = [];
85454
- const preludeIxs = [...setupIxs, ...refreshIxs];
85455
- if (preludeIxs.length > 0) {
85456
- const txs = splitInstructionsToFitTransactions([], preludeIxs, {
85457
- blockhash,
85458
- payerKey: accountA.authority,
85459
- luts
85460
- });
85461
- additionalTxs.push(
85462
- ...txs.map(
85463
- (tx) => addTransactionMetadata(tx, { type: "CREATE_ATA" /* CREATE_ATA */, addressLookupTables: luts })
85464
- )
85465
- );
85466
- }
85656
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85657
+ blockhash,
85658
+ payerKey: accountA.authority,
85659
+ luts
85660
+ });
85467
85661
  const transactions = [...additionalTxs, flashloanTx];
85468
85662
  return {
85469
85663
  transactions,
@@ -85605,48 +85799,22 @@ async function makeBulkWithdrawTx(params) {
85605
85799
  type: "WITHDRAW" /* WITHDRAW */
85606
85800
  })
85607
85801
  );
85608
- const additionalTxs = [];
85609
85802
  const setupIxs = await makeSetupIx({
85610
85803
  connection,
85611
85804
  authority,
85612
85805
  tokens: setupTokens
85613
85806
  });
85614
- if (setupIxs.length > 0) {
85615
- const setupTxs = splitInstructionsToFitTransactions([], setupIxs, {
85616
- blockhash,
85617
- payerKey: authority,
85618
- luts: selectedLuts
85619
- });
85620
- additionalTxs.push(
85621
- ...setupTxs.map(
85622
- (tx) => addTransactionMetadata(tx, {
85623
- type: "CREATE_ATA" /* CREATE_ATA */,
85624
- addressLookupTables: selectedLuts
85625
- })
85626
- )
85627
- );
85628
- }
85629
85807
  const refreshIxs = makeRefreshIntegrationBanksIxs(
85630
85808
  marginfiAccount,
85631
85809
  bankMap,
85632
85810
  bankAddresses,
85633
85811
  bankMetadataMap
85634
85812
  ).instructions;
85635
- if (refreshIxs.length > 0) {
85636
- const refreshTxs = splitInstructionsToFitTransactions([], refreshIxs, {
85637
- blockhash,
85638
- payerKey: authority,
85639
- luts: selectedLuts
85640
- });
85641
- additionalTxs.push(
85642
- ...refreshTxs.map(
85643
- (tx) => addTransactionMetadata(tx, {
85644
- type: "CRANK" /* CRANK */,
85645
- addressLookupTables: selectedLuts
85646
- })
85647
- )
85648
- );
85649
- }
85813
+ const additionalTxs = makePreludeTxs(setupIxs, refreshIxs, {
85814
+ blockhash,
85815
+ payerKey: authority,
85816
+ luts: selectedLuts
85817
+ });
85650
85818
  return {
85651
85819
  transactions: [...additionalTxs, ...withdrawTxs],
85652
85820
  actionTxIndex: additionalTxs.length,
@@ -85691,18 +85859,14 @@ async function makeBulkRepayTx(params) {
85691
85859
  });
85692
85860
  repayIxs.push(...repay.instructions);
85693
85861
  }
85694
- if (!params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses)) {
85695
- repayIxs.push(
85696
- ...await makePremiumRefreshIxs(
85697
- program,
85698
- { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85699
- [],
85700
- bankAddresses
85701
- )
85702
- );
85703
- }
85862
+ const premiumIxs = !params.skipPremiumRefresh && needsPremiumRefresh(marginfiAccount, bankMap, bankAddresses) ? await makePremiumRefreshIxs(
85863
+ program,
85864
+ { marginfiAccount, bankMap, bankMetadataMap: params.bankMetadataMap },
85865
+ [],
85866
+ bankAddresses
85867
+ ) : [];
85704
85868
  const { blockhash } = await connection.getLatestBlockhash("confirmed");
85705
- const transactions = splitInstructionsToFitTransactions([], repayIxs, {
85869
+ const transactions = splitInstructionsToFitTransactions([], [...repayIxs, ...premiumIxs], {
85706
85870
  blockhash,
85707
85871
  payerKey: authority,
85708
85872
  luts,
@@ -85714,7 +85878,117 @@ async function makeBulkRepayTx(params) {
85714
85878
  type: "REPAY" /* REPAY */
85715
85879
  })
85716
85880
  );
85717
- return { transactions, actionTxIndex: 0, mustBeAtomicBundle: false };
85881
+ return {
85882
+ transactions,
85883
+ actionTxIndex: 0,
85884
+ // Venue refreshes only count in the pulse's slot, and the pulse must follow every repay
85885
+ mustBeAtomicBundle: premiumIxs.length > 0 && transactions.length > 1
85886
+ };
85887
+ }
85888
+ function buildOrderTrigger(params) {
85889
+ const { stopLossUsd, takeProfitUsd } = params;
85890
+ const maxSlippage = percentToMaxSlippageU32(params.maxSlippagePercent);
85891
+ const invalidTrigger = (reason) => TransactionBuildingError.orderInvalidTrigger(
85892
+ reason,
85893
+ takeProfitUsd?.toString(),
85894
+ stopLossUsd?.toString()
85895
+ );
85896
+ if (stopLossUsd && !stopLossUsd.gt(0)) {
85897
+ throw invalidTrigger(`stop-loss threshold (${stopLossUsd}) must be above 0`);
85898
+ }
85899
+ if (takeProfitUsd && !takeProfitUsd.gt(0)) {
85900
+ throw invalidTrigger(`take-profit threshold (${takeProfitUsd}) must be above 0`);
85901
+ }
85902
+ if (stopLossUsd && takeProfitUsd) {
85903
+ if (takeProfitUsd.lte(stopLossUsd)) {
85904
+ throw invalidTrigger(
85905
+ `take-profit threshold (${takeProfitUsd}) must be above stop-loss threshold (${stopLossUsd})`
85906
+ );
85907
+ }
85908
+ return {
85909
+ both: {
85910
+ stopLoss: bigNumberToWrappedI80F48(stopLossUsd),
85911
+ takeProfit: bigNumberToWrappedI80F48(takeProfitUsd),
85912
+ maxSlippage
85913
+ }
85914
+ };
85915
+ }
85916
+ if (stopLossUsd) {
85917
+ return { stopLoss: { threshold: bigNumberToWrappedI80F48(stopLossUsd), maxSlippage } };
85918
+ }
85919
+ if (takeProfitUsd) {
85920
+ return { takeProfit: { threshold: bigNumberToWrappedI80F48(takeProfitUsd), maxSlippage } };
85921
+ }
85922
+ throw invalidTrigger("an order needs a stop-loss threshold, a take-profit threshold, or both");
85923
+ }
85924
+ async function makePlaceOrderIx2(params) {
85925
+ const { program, marginfiAccount, collateralBank, debtBank, trigger, feePayer } = params;
85926
+ const [order] = deriveOrderPda(program.programId, marginfiAccount.address, [
85927
+ collateralBank,
85928
+ debtBank
85929
+ ]);
85930
+ const globalFeeWallet = params.globalFeeWallet ?? (await program.account.feeState.fetch(deriveFeeState(program.programId)[0])).globalFeeWallet;
85931
+ const placeOrderIx = await instructions_default3.makePlaceOrderIx(
85932
+ program,
85933
+ {
85934
+ marginfiAccount: marginfiAccount.address,
85935
+ feePayer: feePayer ?? marginfiAccount.authority,
85936
+ authority: marginfiAccount.authority,
85937
+ order,
85938
+ globalFeeWallet,
85939
+ group: marginfiAccount.group
85940
+ },
85941
+ { bankKeys: [collateralBank, debtBank], trigger: buildOrderTrigger(trigger) }
85942
+ );
85943
+ return { instructions: [placeOrderIx], keys: [] };
85944
+ }
85945
+ async function makeCloseOrderIx2(params) {
85946
+ const { program, marginfiAccount, order, feeRecipient } = params;
85947
+ const closeOrderIx = await instructions_default3.makeCloseOrderIx(program, {
85948
+ marginfiAccount: marginfiAccount.address,
85949
+ authority: marginfiAccount.authority,
85950
+ order,
85951
+ feeRecipient: feeRecipient ?? marginfiAccount.authority,
85952
+ group: marginfiAccount.group
85953
+ });
85954
+ return { instructions: [closeOrderIx], keys: [] };
85955
+ }
85956
+ async function compileOrderTx(params, payerKey, ixs, type) {
85957
+ const blockhash = params.blockhash ?? (await params.connection.getLatestBlockhashAndContext("confirmed")).value.blockhash;
85958
+ return addTransactionMetadata(
85959
+ new web3_js.VersionedTransaction(
85960
+ new web3_js.TransactionMessage({
85961
+ instructions: ixs.flatMap((ix) => ix.instructions),
85962
+ payerKey,
85963
+ recentBlockhash: blockhash
85964
+ }).compileToV0Message(params.luts)
85965
+ ),
85966
+ { type, signers: ixs.flatMap((ix) => ix.keys), addressLookupTables: params.luts }
85967
+ );
85968
+ }
85969
+ async function makePlaceOrderTx(params) {
85970
+ const placeIxs = await makePlaceOrderIx2(params);
85971
+ const payerKey = params.feePayer ?? params.marginfiAccount.authority;
85972
+ return compileOrderTx(params, payerKey, [placeIxs], "PLACE_ORDER" /* PLACE_ORDER */);
85973
+ }
85974
+ async function makeCloseOrderTx(params) {
85975
+ const closeIxs = await makeCloseOrderIx2(params);
85976
+ return compileOrderTx(
85977
+ params,
85978
+ params.marginfiAccount.authority,
85979
+ [closeIxs],
85980
+ "CLOSE_ORDER" /* CLOSE_ORDER */
85981
+ );
85982
+ }
85983
+ async function makeUpdateOrderTx(params) {
85984
+ const [order] = deriveOrderPda(params.program.programId, params.marginfiAccount.address, [
85985
+ params.collateralBank,
85986
+ params.debtBank
85987
+ ]);
85988
+ const closeIxs = await makeCloseOrderIx2({ ...params, order, feeRecipient: params.feePayer });
85989
+ const placeIxs = await makePlaceOrderIx2(params);
85990
+ const payerKey = params.feePayer ?? params.marginfiAccount.authority;
85991
+ return compileOrderTx(params, payerKey, [closeIxs, placeIxs], "UPDATE_ORDER" /* UPDATE_ORDER */);
85718
85992
  }
85719
85993
 
85720
85994
  // src/services/account/services/account-simulation.service.ts
@@ -86057,7 +86331,7 @@ function isGroupRateLimiterEnabled(rateLimiter) {
86057
86331
  if (!rateLimiter) return false;
86058
86332
  return rateLimiter.hourly.maxOutflow.gt(0) || rateLimiter.daily.maxOutflow.gt(0);
86059
86333
  }
86060
- async function makePoolConfigureBankIx3(program, bank, args) {
86334
+ async function makePoolConfigureBankIx2(program, bank, args) {
86061
86335
  const ix = await instructions_default3.makePoolConfigureBankIx(
86062
86336
  program,
86063
86337
  {
@@ -86070,6 +86344,17 @@ async function makePoolConfigureBankIx3(program, bank, args) {
86070
86344
  keys: []
86071
86345
  };
86072
86346
  }
86347
+ async function makePoolConfigureBankGovIx2(program, bank, args) {
86348
+ const ix = await instructions_default3.makePoolConfigureBankGovIx(
86349
+ program,
86350
+ { bank },
86351
+ { bankConfigOpt: args }
86352
+ );
86353
+ return {
86354
+ instructions: [ix],
86355
+ keys: []
86356
+ };
86357
+ }
86073
86358
  async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddress, feePayer, pythOracle) {
86074
86359
  const [settingsKey] = web3_js.PublicKey.findProgramAddressSync(
86075
86360
  [Buffer.from("staked_settings", "utf-8"), group.toBuffer()],
@@ -86105,7 +86390,7 @@ async function makeAddPermissionlessStakedBankIx(program, group, voteAccountAddr
86105
86390
  keys: []
86106
86391
  };
86107
86392
  }
86108
- async function makePoolAddBankIx3(program, group, bank, feePayer, bankMint, bankConfig, tokenProgram = TOKEN_PROGRAM_ID, overrideOpt = {}) {
86393
+ async function makePoolAddBankIx2(program, group, bank, feePayer, bankMint, bankConfig, tokenProgram = TOKEN_PROGRAM_ID, overrideOpt = {}) {
86109
86394
  const rawBankConfig = serializeBankConfigOpt(bankConfig);
86110
86395
  const rawBankConfigCompact = {
86111
86396
  ...rawBankConfig,
@@ -87625,6 +87910,9 @@ function getKaminoCTokenMultiplier(reserve) {
87625
87910
  const [totalLiquidity, totalCollateral] = scaledSupplies(reserve);
87626
87911
  return totalCollateral.isZero() ? new BigNumber3__default.default(1) : new BigNumber3__default.default(totalLiquidity.dividedBy(totalCollateral).toString());
87627
87912
  }
87913
+ function withKaminoReserveEmergency(bank, reserve) {
87914
+ return { ...bank, kaminoEmergency: bank.kaminoEmergency || reserve.config.emergencyMode !== 0 };
87915
+ }
87628
87916
 
87629
87917
  // src/services/integration/integration.service.ts
87630
87918
  async function fetchBankIntegrationMetadata(options) {
@@ -87671,7 +87959,7 @@ async function fetchBankIntegrationMetadata(options) {
87671
87959
 
87672
87960
  // src/models/bank.ts
87673
87961
  var Bank = class _Bank {
87674
- 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) {
87962
+ 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) {
87675
87963
  this.address = address;
87676
87964
  this.mint = mint;
87677
87965
  this.mintDecimals = mintDecimals;
@@ -87704,6 +87992,7 @@ var Bank = class _Bank {
87704
87992
  this.premiumTag = premiumTag;
87705
87993
  this.premiumActive = premiumActive;
87706
87994
  this.premiumActivatedAt = premiumActivatedAt;
87995
+ this.kaminoEmergency = kaminoEmergency;
87707
87996
  this.rateLimiter = rateLimiter;
87708
87997
  this.kaminoIntegrationAccounts = kaminoIntegrationAccounts;
87709
87998
  this.driftIntegrationAccounts = driftIntegrationAccounts;
@@ -87779,6 +88068,7 @@ var Bank = class _Bank {
87779
88068
  bankType.premiumTag,
87780
88069
  bankType.premiumActive,
87781
88070
  bankType.premiumActivatedAt,
88071
+ bankType.kaminoEmergency,
87782
88072
  bankType.rateLimiter,
87783
88073
  bankType.kaminoIntegrationAccounts,
87784
88074
  bankType.driftIntegrationAccounts,
@@ -87825,6 +88115,7 @@ var Bank = class _Bank {
87825
88115
  props.premiumTag,
87826
88116
  props.premiumActive,
87827
88117
  props.premiumActivatedAt,
88118
+ props.kaminoEmergency,
87828
88119
  props.rateLimiter,
87829
88120
  props.kaminoIntegrationAccounts,
87830
88121
  props.driftIntegrationAccounts,
@@ -88020,7 +88311,7 @@ var MarginfiGroup = class _MarginfiGroup {
88020
88311
  // (TODO: move to Bank class)
88021
88312
  // ------------------------------------------------------------------------
88022
88313
  async makePoolConfigureBankIx(program, bank, args) {
88023
- return makePoolConfigureBankIx3(program, bank, args);
88314
+ return makePoolConfigureBankIx2(program, bank, args);
88024
88315
  }
88025
88316
  async makeAddPermissionlessStakedBankIx(program, voteAccountAddress, feePayer, pythOracle) {
88026
88317
  return makeAddPermissionlessStakedBankIx(
@@ -88032,7 +88323,7 @@ var MarginfiGroup = class _MarginfiGroup {
88032
88323
  );
88033
88324
  }
88034
88325
  async makePoolAddBankIx(program, bankPubkey, bankMint, bankConfig, feePayer) {
88035
- return makePoolAddBankIx3(
88326
+ return makePoolAddBankIx2(
88036
88327
  program,
88037
88328
  this.address,
88038
88329
  bankPubkey,
@@ -88603,6 +88894,75 @@ var MarginfiAccountWrapper = class {
88603
88894
  opts
88604
88895
  });
88605
88896
  }
88897
+ // ----------------------------------------------------------------------------
88898
+ // Orders (take-profit / stop-loss)
88899
+ // ----------------------------------------------------------------------------
88900
+ /**
88901
+ * Creates a place-order instruction, for composing into a larger transaction.
88902
+ *
88903
+ * @param collateralBank - Bank of the asset-side balance
88904
+ * @param debtBank - Bank of the liability-side balance
88905
+ * @param trigger - USD pair-equity thresholds and max slippage
88906
+ */
88907
+ async makePlaceOrderIx(collateralBank, debtBank, trigger) {
88908
+ return this.account.makePlaceOrderIx({
88909
+ program: this.client.program,
88910
+ collateralBank,
88911
+ debtBank,
88912
+ trigger
88913
+ });
88914
+ }
88915
+ /**
88916
+ * Creates a close-order instruction, for composing into a larger transaction.
88917
+ *
88918
+ * @param order - The order PDA (from `fetchOrdersForAccount` or `deriveOrderPda`)
88919
+ */
88920
+ async makeCloseOrderIx(order) {
88921
+ return this.account.makeCloseOrderIx({ program: this.client.program, order });
88922
+ }
88923
+ /**
88924
+ * Creates a transaction placing a take-profit / stop-loss order on a collateral/debt pair.
88925
+ *
88926
+ * @param collateralBank - Bank of the asset-side balance
88927
+ * @param debtBank - Bank of the liability-side balance
88928
+ * @param trigger - USD pair-equity thresholds and max slippage
88929
+ */
88930
+ async makePlaceOrderTx(collateralBank, debtBank, trigger) {
88931
+ return this.account.makePlaceOrderTx({
88932
+ program: this.client.program,
88933
+ collateralBank,
88934
+ debtBank,
88935
+ trigger,
88936
+ luts: this.client.addressLookupTables,
88937
+ connection: this.client.program.provider.connection
88938
+ });
88939
+ }
88940
+ /**
88941
+ * Creates a transaction replacing the pair's existing order with new thresholds.
88942
+ */
88943
+ async makeUpdateOrderTx(collateralBank, debtBank, trigger) {
88944
+ return this.account.makeUpdateOrderTx({
88945
+ program: this.client.program,
88946
+ collateralBank,
88947
+ debtBank,
88948
+ trigger,
88949
+ luts: this.client.addressLookupTables,
88950
+ connection: this.client.program.provider.connection
88951
+ });
88952
+ }
88953
+ /**
88954
+ * Creates a transaction closing an existing order.
88955
+ *
88956
+ * @param order - The order PDA (from `fetchOrdersForAccount` or `deriveOrderPda`)
88957
+ */
88958
+ async makeCloseOrderTx(order) {
88959
+ return this.account.makeCloseOrderTx({
88960
+ program: this.client.program,
88961
+ order,
88962
+ luts: this.client.addressLookupTables,
88963
+ connection: this.client.program.provider.connection
88964
+ });
88965
+ }
88606
88966
  /**
88607
88967
  * Creates a repay transaction with auto-injected client data.
88608
88968
  *
@@ -89230,6 +89590,10 @@ var Project0Client = class _Project0Client {
89230
89590
  bank.address.toBase58(),
89231
89591
  getKaminoCTokenMultiplier(reserve)
89232
89592
  );
89593
+ bankMap.set(
89594
+ bank.address.toBase58(),
89595
+ Bank.fromBankType(withKaminoReserveEmergency(bank, reserve))
89596
+ );
89233
89597
  break;
89234
89598
  }
89235
89599
  case 4 /* DRIFT */: {
@@ -89353,6 +89717,7 @@ exports.HealthCacheSimulationError = HealthCacheSimulationError;
89353
89717
  exports.HealthCacheStatus = HealthCacheStatus;
89354
89718
  exports.JUPITER_V6_PROGRAM = JUPITER_V6_PROGRAM;
89355
89719
  exports.JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX;
89720
+ exports.KAMINO_MARKET_EMERGENCY_FLAG = KAMINO_MARKET_EMERGENCY_FLAG;
89356
89721
  exports.LST_MINT = LST_MINT;
89357
89722
  exports.MARGINFI_IDL = MARGINFI_IDL;
89358
89723
  exports.MARGINFI_PROGRAM = MARGINFI_PROGRAM;
@@ -89361,6 +89726,7 @@ exports.MARGINFI_PROGRAM_STAGING_ALT = MARGINFI_PROGRAM_STAGING_ALT;
89361
89726
  exports.MARGINFI_SPONSORED_SHARD_ID = MARGINFI_SPONSORED_SHARD_ID;
89362
89727
  exports.MAX_ACCOUNT_LOCKS = MAX_ACCOUNT_LOCKS;
89363
89728
  exports.MAX_CONFIDENCE_INTERVAL_RATIO = MAX_CONFIDENCE_INTERVAL_RATIO;
89729
+ exports.MAX_COSTLY_POSITIONS = MAX_COSTLY_POSITIONS;
89364
89730
  exports.MAX_TX_SIZE = MAX_TX_SIZE;
89365
89731
  exports.MAX_U64 = MAX_U64;
89366
89732
  exports.MPL_METADATA_PROGRAM_ID = MPL_METADATA_PROGRAM_ID;
@@ -89380,6 +89746,7 @@ exports.PDA_BANK_INSURANCE_VAULT_SEED = PDA_BANK_INSURANCE_VAULT_SEED;
89380
89746
  exports.PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED = PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED;
89381
89747
  exports.PDA_BANK_LIQUIDITY_VAULT_SEED = PDA_BANK_LIQUIDITY_VAULT_SEED;
89382
89748
  exports.PDA_MARGINFI_ACCOUNT_SEED = PDA_MARGINFI_ACCOUNT_SEED;
89749
+ exports.PDA_ORDER_SEED = PDA_ORDER_SEED;
89383
89750
  exports.PDA_REBALANCE_FEE_POOL_SEED = PDA_REBALANCE_FEE_POOL_SEED;
89384
89751
  exports.PREMIUM_ACTIVE_FLAG = PREMIUM_ACTIVE_FLAG;
89385
89752
  exports.PRIORITY_TX_SIZE = PRIORITY_TX_SIZE;
@@ -89419,6 +89786,7 @@ exports.accountFlagToBN = accountFlagToBN;
89419
89786
  exports.addOracleToBanksIx = addOracleToBanksIx;
89420
89787
  exports.addTransactionMetadata = addTransactionMetadata;
89421
89788
  exports.adjustPriceComponent = adjustPriceComponent;
89789
+ exports.appendPremiumRefresh = appendPremiumRefresh;
89422
89790
  exports.aprToApy = aprToApy;
89423
89791
  exports.apyToApr = apyToApr;
89424
89792
  exports.balanceToDto = balanceToDto;
@@ -89431,6 +89799,7 @@ exports.bankRawToDto = bankRawToDto;
89431
89799
  exports.bigNumberToWrappedI80F48 = bigNumberToWrappedI80F48;
89432
89800
  exports.bpsToPercentile = bpsToPercentile;
89433
89801
  exports.buildCollateralLegIxs = buildCollateralLegIxs;
89802
+ exports.buildOrderTrigger = buildOrderTrigger;
89434
89803
  exports.calculateApyFromInterest = calculateApyFromInterest;
89435
89804
  exports.calculateInterestFromApy = calculateInterestFromApy;
89436
89805
  exports.capConfidenceInterval = capConfidenceInterval;
@@ -89456,6 +89825,7 @@ exports.computeBankBorrowApy = computeBankBorrowApy;
89456
89825
  exports.computeBankBorrowCapRemaining = computeBankBorrowCapRemaining;
89457
89826
  exports.computeBankDepositCapRemaining = computeBankDepositCapRemaining;
89458
89827
  exports.computeBankMetrics = computeBankMetrics;
89828
+ exports.computeBankOutflowRateLimit = computeBankOutflowRateLimit;
89459
89829
  exports.computeBankPoolSize = computeBankPoolSize;
89460
89830
  exports.computeBankProjectedAvailableLiquidity = computeBankProjectedAvailableLiquidity;
89461
89831
  exports.computeBankRateLimitRemaining = computeBankRateLimitRemaining;
@@ -89491,6 +89861,7 @@ exports.computeMaxWithdrawForBank = computeMaxWithdrawForBank;
89491
89861
  exports.computeNetApy = computeNetApy;
89492
89862
  exports.computeOracleMultiplier = computeOracleMultiplier;
89493
89863
  exports.computeOracleMultipliers = computeOracleMultipliers;
89864
+ exports.computeOrderPairNetValue = computeOrderPairNetValue;
89494
89865
  exports.computePremiumBreakdown = computePremiumBreakdown;
89495
89866
  exports.computePremiumImpact = computePremiumImpact;
89496
89867
  exports.computePremiumRatesByBank = computePremiumRatesByBank;
@@ -89527,6 +89898,7 @@ exports.deriveBankLiquidityVault = deriveBankLiquidityVault;
89527
89898
  exports.deriveBankLiquidityVaultAuthority = deriveBankLiquidityVaultAuthority;
89528
89899
  exports.deriveFeeState = deriveFeeState;
89529
89900
  exports.deriveMarginfiAccount = deriveMarginfiAccount;
89901
+ exports.deriveOrderPda = deriveOrderPda;
89530
89902
  exports.deriveRebalanceFeePool = deriveRebalanceFeePool;
89531
89903
  exports.deserializeInstruction = deserializeInstruction;
89532
89904
  exports.deserializeLut = deserializeLut;
@@ -89550,6 +89922,7 @@ exports.dtoToMarginfiAccount = dtoToMarginfiAccount;
89550
89922
  exports.dtoToOraclePrice = dtoToOraclePrice;
89551
89923
  exports.dtoToValidatorStakeGroup = dtoToValidatorStakeGroup;
89552
89924
  exports.emodeSettingsRawToDto = emodeSettingsRawToDto;
89925
+ exports.exceedsCostlyPositionLimit = exceedsCostlyPositionLimit;
89553
89926
  exports.extractPythOracleKeys = extractPythOracleKeys;
89554
89927
  exports.fetchBank = fetchBank;
89555
89928
  exports.fetchBankIntegrationMetadata = fetchBankIntegrationMetadata;
@@ -89567,6 +89940,8 @@ exports.fetchOracleData = fetchOracleData;
89567
89940
  exports.fetchOracleMultipliers = fetchOracleMultipliers;
89568
89941
  exports.fetchOracleMultipliersFromAPI = fetchOracleMultipliersFromAPI;
89569
89942
  exports.fetchOracleMultipliersFromChain = fetchOracleMultipliersFromChain;
89943
+ exports.fetchOrderFees = fetchOrderFees;
89944
+ exports.fetchOrdersForAccount = fetchOrdersForAccount;
89570
89945
  exports.fetchProgramForMints = fetchProgramForMints;
89571
89946
  exports.fetchPythOracleData = fetchPythOracleData;
89572
89947
  exports.fetchPythOraclePricesFromAPI = fetchPythOraclePricesFromAPI;
@@ -89578,6 +89953,7 @@ exports.fetchStakeAccount = fetchStakeAccount;
89578
89953
  exports.fetchStakePoolActiveStates = fetchStakePoolActiveStates;
89579
89954
  exports.fetchStakePoolMev = fetchStakePoolMev;
89580
89955
  exports.findRandomAvailableAccountIndex = findRandomAvailableAccountIndex;
89956
+ exports.fitsInOneTransaction = fitsInOneTransaction;
89581
89957
  exports.freezeBankConfigIx = freezeBankConfigIx;
89582
89958
  exports.generateDummyAccount = generateDummyAccount;
89583
89959
  exports.getAccountKeys = getAccountKeys;
@@ -89642,6 +90018,7 @@ exports.hasHealthCacheFlag = hasHealthCacheFlag;
89642
90018
  exports.healthCacheToDto = healthCacheToDto;
89643
90019
  exports.isBorrowLimitActive = isBorrowLimitActive;
89644
90020
  exports.isBridgeConflictError = isBridgeConflictError;
90021
+ exports.isCostlyBank = isCostlyBank;
89645
90022
  exports.isDecomposableSwapError = isDecomposableSwapError;
89646
90023
  exports.isDepositIx = isDepositIx;
89647
90024
  exports.isDepositLimitActive = isDepositLimitActive;
@@ -89665,6 +90042,8 @@ exports.makeBulkWithdrawTx = makeBulkWithdrawTx;
89665
90042
  exports.makeBundleTipIx = makeBundleTipIx;
89666
90043
  exports.makeCloseMarginfiAccountIx = makeCloseMarginfiAccountIx;
89667
90044
  exports.makeCloseMarginfiAccountTx = makeCloseMarginfiAccountTx;
90045
+ exports.makeCloseOrderIx = makeCloseOrderIx2;
90046
+ exports.makeCloseOrderTx = makeCloseOrderTx;
89668
90047
  exports.makeCreateAccountIxWithProjection = makeCreateAccountIxWithProjection;
89669
90048
  exports.makeCreateAccountTxWithProjection = makeCreateAccountTxWithProjection;
89670
90049
  exports.makeCreateMarginfiAccountIx = makeCreateMarginfiAccountIx;
@@ -89689,8 +90068,12 @@ exports.makeLoopTx = makeLoopTx;
89689
90068
  exports.makeMergeStakeAccountsTx = makeMergeStakeAccountsTx;
89690
90069
  exports.makeMintStakedLstIx = makeMintStakedLstIx;
89691
90070
  exports.makeMintStakedLstTx = makeMintStakedLstTx;
89692
- exports.makePoolAddBankIx = makePoolAddBankIx3;
89693
- exports.makePoolConfigureBankIx = makePoolConfigureBankIx3;
90071
+ exports.makePlaceOrderIx = makePlaceOrderIx2;
90072
+ exports.makePlaceOrderTx = makePlaceOrderTx;
90073
+ exports.makePoolAddBankIx = makePoolAddBankIx2;
90074
+ exports.makePoolConfigureBankGovIx = makePoolConfigureBankGovIx2;
90075
+ exports.makePoolConfigureBankIx = makePoolConfigureBankIx2;
90076
+ exports.makePreludeTxs = makePreludeTxs;
89694
90077
  exports.makePremiumRefreshIxs = makePremiumRefreshIxs;
89695
90078
  exports.makePriorityFeeIx = makePriorityFeeIx;
89696
90079
  exports.makePriorityFeeMicroIx = makePriorityFeeMicroIx;
@@ -89711,6 +90094,7 @@ exports.makeTxPriorityIx = makeTxPriorityIx;
89711
90094
  exports.makeUnwrapSolIx = makeUnwrapSolIx;
89712
90095
  exports.makeUpdateDriftMarketIxs = makeUpdateDriftMarketIxs;
89713
90096
  exports.makeUpdateJupLendRateIxs = makeUpdateJupLendRateIxs;
90097
+ exports.makeUpdateOrderTx = makeUpdateOrderTx;
89714
90098
  exports.makeVaultCompleteWithdrawalIx = makeVaultCompleteWithdrawalIx;
89715
90099
  exports.makeVaultCompleteWithdrawalTx = makeVaultCompleteWithdrawalTx;
89716
90100
  exports.makeVaultDepositIx = makeVaultDepositIx;
@@ -89725,6 +90109,7 @@ exports.makeWrapSolIxs = makeWrapSolIxs;
89725
90109
  exports.mapJupiterQuoteToSwapQuoteResult = mapJupiterQuoteToSwapQuoteResult;
89726
90110
  exports.mapPythBanksToOraclePrices = mapPythBanksToOraclePrices;
89727
90111
  exports.marginfiAccountToDto = marginfiAccountToDto;
90112
+ exports.maxSlippageU32ToPercent = maxSlippageU32ToPercent;
89728
90113
  exports.mergeBridgeQuotes = mergeBridgeQuotes;
89729
90114
  exports.mergeBridgeQuotesDebt = mergeBridgeQuotesDebt;
89730
90115
  exports.mergeBridgeQuotesLoop = mergeBridgeQuotesLoop;
@@ -89741,15 +90126,18 @@ exports.parseHealthCacheRaw = parseHealthCacheRaw;
89741
90126
  exports.parseMarginfiAccountRaw = parseMarginfiAccountRaw;
89742
90127
  exports.parseOperationalState = parseOperationalState;
89743
90128
  exports.parseOracleSetup = parseOracleSetup;
90129
+ exports.parseOrderRaw = parseOrderRaw;
89744
90130
  exports.parsePriceInfo = parseOraclePriceData;
89745
90131
  exports.parseRiskTier = parseRiskTier;
89746
90132
  exports.parseRpcPythPriceData = parseRpcPythPriceData;
89747
90133
  exports.patchDepositAmount = patchDepositAmount;
90134
+ exports.percentToMaxSlippageU32 = percentToMaxSlippageU32;
89748
90135
  exports.rateFromU32 = rateFromU32;
89749
90136
  exports.requireBank = requireBank;
89750
90137
  exports.requireTokenProgram = requireTokenProgram;
89751
90138
  exports.resolveAmount = resolveAmount;
89752
90139
  exports.resolveBridgeCandidateBanks = resolveBridgeCandidateBanks;
90140
+ exports.resolveOrderLegs = resolveOrderLegs;
89753
90141
  exports.resolvePinnedSwapRoute = resolvePinnedSwapRoute;
89754
90142
  exports.resolveTokenProgramForMint = resolveTokenProgramForMint;
89755
90143
  exports.resolveVaultTokenProgram = resolveVaultTokenProgram;
@@ -89788,6 +90176,7 @@ exports.tryBridgeCandidates = tryBridgeCandidates;
89788
90176
  exports.uiToNative = uiToNative;
89789
90177
  exports.uiToNativeBigNumber = uiToNativeBigNumber;
89790
90178
  exports.validatorStakeGroupToDto = validatorStakeGroupToDto;
90179
+ exports.withKaminoReserveEmergency = withKaminoReserveEmergency;
89791
90180
  exports.wrappedI80F48toBigNumber = wrappedI80F48toBigNumber;
89792
90181
  //# sourceMappingURL=index.cjs.map
89793
90182
  //# sourceMappingURL=index.cjs.map