import * as superstruct from 'superstruct'; import { Infer } from 'superstruct'; import { b as BankType, R as RiskTier, A as AssetTag, c as BankConfigFlag, O as OperationalState, d as OracleSetup, E as EmodeTag, e as EmodeEntryFlags, f as EmodeFlags, W as WrappedI80F48, I as InterestRateConfigRaw, g as OperationalStateRaw, h as OracleSetupRaw, i as RiskTierRaw, M as MarginfiProgram, j as BankConfigOpt, k as InterestRateConfig, l as BankConfigType, m as BankConfigRaw, a as BankConfigOptRaw, n as EmodeSettingsType, o as BankRateLimiterType, p as BankRaw, q as BankRateLimiterRaw, r as EmodeSettingsRaw, s as MarginfiIdlType, H as HealthCacheFlags, t as HealthCacheStatus, u as AccountFlags, v as MarginfiAccountType, w as OraclePrice, P as PriceWithConfidence, x as PriceBias, y as OraclePriceDto, z as BankIntegrationMetadataMap, C as BalanceType, D as HealthCacheType, F as EmodePair, G as ActiveEmodePair, J as ActionEmodeImpact, K as MarginRequirementType, L as EmodeImpactStatus, N as Amount, T as TypedAmount, Q as BankVaultType, S as RateLimitWindowType, U as BankIntegrationMetadataMapDto, V as BankIntegrationMetadataDto, X as BankIntegrationMetadata, Y as Bank, Z as Environment, _ as Project0Config, $ as MintData } from './types-CaxQRqmz.cjs'; export { ax as AccountType, aC as AmountType, aw as BankAddress, a0 as BankConfig, B as BankConfigCompactRaw, az as BankMap, av as BankMetadata, a3 as BankMetadataRaw, ao as ComputeAssetUsdValueParams, am as ComputeLiabilityUsdValueParams, ak as ComputeUsdValueParams, a8 as EmodeConfigRaw, ab as EmodeEntry, ad as EmodeImpact, a1 as EmodeSettings, af as GetAssetWeightParams, a5 as InterestRateConfigCompactRaw, aa as InterestRateConfigOpt, a6 as InterestRateConfigOptRaw, ay as KaminoStates, as as MARGINFI_IDL, aB as MintDataMap, ac as OracleConfigOpt, a7 as OracleConfigOptRaw, aA as OraclePriceMap, ar as PriceWithConfidenceDto, at as Program, a2 as RateLimitWindowRaw, a9 as RatePoint, a4 as RatePointRaw, au as Wallet, ap as computeAssetUsdValue, an as computeLiabilityUsdValue, aj as computeLoopingParams, ai as computeMaxLeverage, aq as computeTvl, al as computeUsdValue, ag as getAssetWeight, ah as getLiabilityWeight, ae as isWeightedPrice, aD as resolveAmount } from './types-CaxQRqmz.cjs'; import * as _solana_web3_js from '@solana/web3.js'; import { VersionedTransaction, Transaction, PublicKey, TransactionError, TransactionInstruction, Keypair, Signer, AddressLookupTableAccount, Blockhash, TransactionMessage, Connection, AccountInfo } from '@solana/web3.js'; import { Idl, Instruction, AnchorProvider, Address } from '@coral-xyz/anchor'; import BigNumber$1 from 'bignumber.js'; import BN from 'bn.js'; import { K as KaminoReserve, D as DriftSpotMarket, d as DriftRewards, J as JupLendingState, f as JupTokenReserve, i as KaminoReserveJSON, j as KaminoObligationJSON, k as KaminoFarmStateJSON, a as KaminoObligation, b as KaminoFarmState, l as DriftSpotMarketJSON, m as DriftUserJSON, n as DriftRewardsJSON, o as DriftUserStatsJSON, c as DriftUser, e as DriftUserStats, p as JupLendingStateJSON, q as JupTokenReserveJSON, r as JupLendingRewardsRateModelJSON, s as JupRateModelJSON, g as JupLendingRewardsRateModel, h as JupRateModel } from './dto-farm.types-BAA9xrey.cjs'; import { JupiterClientConfig, QuoteGetRequest, QuoteResponse } from './jupiter.cjs'; import { F as FeedResponse, E as ExponentVault, G as GammaLpVaultRaw, e as GammaWithdrawReceiptRaw } from './types-BmLq23LD.cjs'; import { Buffer as Buffer$1 } from 'buffer'; interface RpcSimulateBundleTransactionResult { err?: TransactionError; logs: string[]; preExecutionAccounts?: any; postExecutionAccounts?: any; unitsConsumed?: string; returnData?: any; } declare function simulateBundle(rpcEndpoint: string, transactions: (VersionedTransaction | Transaction)[], includeAccounts?: Array): Promise; /** * Creates a compute budget instruction to set the priority fee for a transaction. * The priority fee is specified in micro-lamports per compute unit. * * @param priorityFeeMicro - Priority fee in micro-lamports per compute unit. If not provided, defaults to 1. * @returns A compute budget instruction with the specified priority fee */ declare function makePriorityFeeMicroIx(priorityFeeMicro?: number): TransactionInstruction; declare function makePriorityFeeIx(priorityFeeUi?: number, computeUnitsLimit?: number): TransactionInstruction[]; /** * @deprecated This method is deprecated. * Creates transaction priority instructions for different broadcast types. */ declare function makeTxPriorityIx(feePayer: PublicKey, feeUi: number | undefined, broadcastType: "BUNDLE" | "RPC" | "DYNAMIC"): { bundleTipIx: TransactionInstruction | undefined; priorityFeeIx: TransactionInstruction; }; /** * Creates a bundle tip instruction for Jito bundles. */ declare function makeBundleTipIx(feePayer: PublicKey, bundleTip?: number): TransactionInstruction; interface InstructionsWrapper { instructions: TransactionInstruction[]; keys: Keypair[]; } declare enum TransactionType { DEPOSIT = "DEPOSIT", WITHDRAW = "WITHDRAW", REPAY = "REPAY", BORROW = "BORROW", FLASHLOAN = "FLASHLOAN", LOOP = "LOOP", REPAY_COLLAT = "REPAY_COLLAT", LONG = "LONG", SHORT = "SHORT", CREATE_ACCOUNT = "CREATE_ACCOUNT", CREATE_ATA = "CREATE_ATA", CLOSE_ACCOUNT = "CLOSE_ACCOUNT", CLOSE_POSITION = "CLOSE_POSITION", MOVE_POSITION_WITHDRAW = "MOVE_POSITION_WITHDRAW", MOVE_POSITION_DEPOSIT = "MOVE_POSITION_DEPOSIT", WITHDRAW_ALL = "WITHDRAW_ALL", TRANSFER_AUTH = "TRANSFER_AUTH", CRANK = "CRANK", DEPOSIT_STAKE = "DEPOSIT_STAKE", WITHDRAW_STAKE = "WITHDRAW_STAKE", INITIALIZE_STAKED_POOL = "INITIALIZE_STAKED_POOL", ADD_STAKED_BANK = "ADD_STAKED_BANK", MERGE_STAKE_ACCOUNTS = "MERGE_STAKE_ACCOUNTS", VAULT_DEPOSIT = "VAULT_DEPOSIT", VAULT_WITHDRAW = "VAULT_WITHDRAW", VAULT_COMPLETE_WITHDRAWAL = "VAULT_COMPLETE_WITHDRAWAL", STAKE_TO_STAKE = "STAKE_TO_STAKE", MINT_LST_NATIVE = "MINT_LST_NATIVE", SWAP_TO_SOL = "SWAP_TO_SOL", SOL_TO_LST = "SOL_TO_LST", UNSTAKE_LST = "UNSTAKE_LST", WITHDRAW_EMISSIONS = "WITHDRAW_EMISSIONS", LIQUIDATE_ACCOUNT = "LIQUIDATE_ACCOUNT", CREATE_PERM_BANK = "CREATE_PERM_BANK", CREATE_GROUP = "CREATE_GROUP", JUPITER_SWAP = "JUPITER_SWAP" } interface TransactionConfig { label: (infoProps?: Record) => string; fallback?: string; } declare const TransactionConfigMap: Record; declare const TransactionArenaKeyMap: Partial>; type ExtendedTransactionProperties = { type: TransactionType; signers?: Array; addressLookupTables?: AddressLookupTableAccount[]; unitsConsumed?: number; }; type ExtendedTransaction = Transaction & ExtendedTransactionProperties; type ExtendedV0Transaction = VersionedTransaction & ExtendedTransactionProperties; type SolanaTransaction = ExtendedTransaction | ExtendedV0Transaction; /** * Picks the lean native-stake LUT subset when every involved bank is STAKED or SOL, * otherwise the general subset. Operates on a combined `luts` array (general + * native-stake) by partitioning it against the SDK's known native-stake LUT keys, so * callers only ever pass one array and the right subset is embedded per transaction. * * Native-stake accounts can only supply native-stake positions and borrow SOL, so such * transactions are fully served by the lean set; any non-(STAKED|SOL) bank falls back to * the general set. Degrades gracefully: if the array wasn't split (e.g. only the general * set was provided), it returns the input unchanged. * * @param luts - Combined LUT accounts available to the transaction * @param banks - Every bank the transaction touches (target bank + health-check banks) */ declare function selectLutsForBanks(luts: AddressLookupTableAccount[], banks: BankType[]): AddressLookupTableAccount[]; /** * Convenience wrapper over {@link selectLutsForBanks} for account actions: collects the * banks a transaction touches (the target bank, the account's active-position banks, and * any extra health-check banks) and selects the matching LUT subset. Uses structural * typing for `balances` to avoid an import cycle with the account module. */ declare function selectLutsForAccountAction(luts: AddressLookupTableAccount[], targetBank: BankType, balances: { active: boolean; bankPk: PublicKey; }[], bankMap: Map, extraBankAddresses?: PublicKey[]): AddressLookupTableAccount[]; /** * Determines if a given transaction is a VersionedTransaction. * This function checks for the presence of a 'message' property to identify * if the transaction is of type VersionedTransaction. * * @param tx - The transaction object, which can be either a VersionedTransaction or a Transaction. * @returns A boolean indicating whether the transaction is a VersionedTransaction. */ declare function isV0Tx(tx: Transaction | VersionedTransaction): tx is VersionedTransaction; declare function isFlashloan(tx: SolanaTransaction): boolean; declare function makeVersionedTransaction(blockhash: Blockhash, transaction: Transaction, payer: PublicKey, addressLookupTables?: AddressLookupTableAccount[]): Promise; /** * Splits your instructions into as many VersionedTransactions as needed * so that none exceed MAX_TX_SIZE (minus `sizeMargin`, if given) nor * `maxAccountLocks` account locks (if given). */ declare function splitInstructionsToFitTransactions(mandatoryIxs: TransactionInstruction[], ixs: TransactionInstruction[], opts: { blockhash: string; payerKey: PublicKey; luts: AddressLookupTableAccount[]; /** Bytes reserved below MAX_TX_SIZE, e.g. for compute-budget ixs appended at send time. */ sizeMargin?: number; /** Also cap the total account locks per transaction (e.g. MAX_ACCOUNT_LOCKS). */ maxAccountLocks?: number; }): VersionedTransaction[]; /** * Enhances a given transaction with additional metadata. * * @param transaction - The transaction to be enhanced, can be either VersionedTransaction or Transaction. * @param options - An object containing optional metadata: * - signers: An array of Signer objects that are associated with the transaction. * - addressLookupTables: An array of AddressLookupTableAccount objects for address resolution. * - unitsConsumed: A number representing the compute units consumed by the transaction. * - type: The type of the transaction, as defined by TransactionType. * @returns A SolanaTransaction object that includes the original transaction and the additional metadata. */ declare function addTransactionMetadata(transaction: T, options: ExtendedTransactionProperties): T & ExtendedTransactionProperties; /** * Calculates the size of a Solana transaction in bytes. * This function considers the number of required signatures and other transaction components. * * @param tx - The transaction object, which can be either a VersionedTransaction or a Transaction. * @returns The size of the transaction in bytes. */ declare function getTxSize(tx: VersionedTransaction | Transaction): number; declare function getAccountKeys(tx: VersionedTransaction | Transaction, lookupTableAccounts: AddressLookupTableAccount[]): number; declare function getWritableAccountKeys(tx: VersionedTransaction | Transaction): number; declare function getTotalAccountKeys(tx: VersionedTransaction | Transaction): number; /** * Decodes a Solana transaction instruction using the provided Interface Definition Language (IDL). * This function utilizes the BorshInstructionCoder to interpret the encoded instruction data. * * @param idl - The Interface Definition Language object that defines the structure of the instruction. * @param encoded - The Buffer containing the encoded instruction data. * @returns The decoded instruction object. */ declare function decodeInstruction(idl: Idl, encoded: Buffer): Instruction | null; /** * Decompiles a VersionedTransaction into a TransactionMessage. * * @param tx - The VersionedTransaction to be decompiled. * @param lookupTableAccounts - An array of AddressLookupTableAccount used for decompiling the transaction message. * @returns A TransactionMessage object representing the decompiled transaction. */ declare function decompileV0Transaction(tx: VersionedTransaction, lookupTableAccounts: AddressLookupTableAccount[]): TransactionMessage; declare function makeUnwrapSolIx(walletAddress: PublicKey): TransactionInstruction; declare function makeWrapSolIxs(walletAddress: PublicKey, amount: BigNumber$1): TransactionInstruction[]; interface RatePointDto { util: number; rate: number; } interface InterestRateConfigDto { placeholder0: string; placeholder1: string; placeholder2: string; /** @deprecated pre-0.1.9 name for placeholder0 — only present on old serialized DTOs */ optimalUtilizationRate?: string; /** @deprecated pre-0.1.9 name for placeholder1 — only present on old serialized DTOs */ plateauInterestRate?: string; /** @deprecated pre-0.1.9 name for placeholder2 — only present on old serialized DTOs */ maxInterestRate?: string; insuranceFeeFixedApr: string; insuranceIrFee: string; protocolFixedFeeApr: string; protocolIrFee: string; protocolOriginationFee: string; zeroUtilRate: number; hundredUtilRate: number; points: RatePointDto[]; curveType: number; } interface BankConfigDto { assetWeightInit: string; assetWeightMaint: string; liabilityWeightInit: string; liabilityWeightMaint: string; depositLimit: string; borrowLimit: string; riskTier: RiskTier; totalAssetValueInitLimit: string; assetTag: AssetTag; configFlags?: BankConfigFlag; interestRateConfig: InterestRateConfigDto; operationalState: OperationalState; oracleSetup: OracleSetup; oracleKeys: string[]; oracleMaxAge: number; oracleMaxConfidence: number; fixedPrice: string; scopeEntryIndex?: number; } interface RateLimitWindowDto { maxOutflow: string; windowDuration: number; windowStart: number; prevWindowOutflow: string; curWindowOutflow: string; } interface BankRateLimiterDto { hourly: RateLimitWindowDto; daily: RateLimitWindowDto; } interface EmodeEntryDto { collateralBankEmodeTag: EmodeTag; flags: EmodeEntryFlags[]; assetWeightInit: string; assetWeightMaint: string; } interface EmodeSettingsDto { emodeTag: EmodeTag; timestamp: number; flags: EmodeFlags[]; emodeEntries: EmodeEntryDto[]; } interface BankTypeDto { address: string; tokenSymbol?: string; group: string; mint: string; mintDecimals: number; assetShareValue: string; liabilityShareValue: string; liquidityVault: string; liquidityVaultBump: number; liquidityVaultAuthorityBump: number; insuranceVault: string; insuranceVaultBump: number; insuranceVaultAuthorityBump: number; collectedInsuranceFeesOutstanding: string; feeVault: string; feeVaultBump: number; feeVaultAuthorityBump: number; collectedGroupFeesOutstanding: string; lastUpdate: number; config: BankConfigDto; totalAssetShares: string; totalLiabilityShares: string; emissionsActiveBorrowing: boolean; emissionsActiveLending: boolean; emissionsRate: number; emissionsMint: string; emissionsRemaining: string; collectedProgramFeesOutstanding?: string; stakedOracleDisabled?: boolean; stakedOracleUsesOnramp?: boolean; oracleKey: string; pythShardId?: number; emode: EmodeSettingsDto; rateLimiter?: BankRateLimiterDto; feesDestinationAccount?: string; lendingPositionCount?: string; borrowingPositionCount?: string; kaminoIntegrationAccounts?: { kaminoReserve: string; kaminoObligation: string; }; driftIntegrationAccounts?: { driftSpotMarket: string; driftUser: string; driftUserStats: string; }; solendIntegrationAccounts?: { solendReserve: string; solendObligation: string; }; jupLendIntegrationAccounts?: { jupLendingState: string; jupFTokenVault: string; jupFTokenAta: string; }; stakedIntegrationAccounts?: { validatorVoteAccount: string; }; } interface BankRawDto { group: string; mint: string; mintDecimals: number; assetShareValue: WrappedI80F48; liabilityShareValue: WrappedI80F48; liquidityVault: string; liquidityVaultBump: number; liquidityVaultAuthorityBump: number; insuranceVault: string; insuranceVaultBump: number; insuranceVaultAuthorityBump: number; collectedInsuranceFeesOutstanding: WrappedI80F48; feeVault: string; feeVaultBump: number; feeVaultAuthorityBump: number; collectedGroupFeesOutstanding: WrappedI80F48; lastUpdate: string; config: BankConfigRawDto; totalLiabilityShares: WrappedI80F48; totalAssetShares: WrappedI80F48; integrationAcc1: string; integrationAcc2: string; integrationAcc3: string; flags: string; emissionsRate: string; emissionsRemaining: WrappedI80F48; emissionsMint: string; collectedProgramFeesOutstanding?: WrappedI80F48; rateLimiter?: BankRateLimiterRawDto; feesDestinationAccount?: string; lendingPositionCount?: string; borrowingPositionCount?: string; emode: EmodeSettingsRawDto; } interface RateLimitWindowRawDto { maxOutflow: string; windowDuration: string; windowStart: string; prevWindowOutflow: string; curWindowOutflow: string; } interface BankRateLimiterRawDto { hourly: RateLimitWindowRawDto; daily: RateLimitWindowRawDto; } interface BankConfigRawDto { assetWeightInit: WrappedI80F48; assetWeightMaint: WrappedI80F48; liabilityWeightInit: WrappedI80F48; liabilityWeightMaint: WrappedI80F48; depositLimit: string; interestRateConfig: InterestRateConfigRaw; operationalState: OperationalStateRaw; oracleSetup: OracleSetupRaw; oracleKeys: string[]; borrowLimit: string; riskTier: RiskTierRaw; assetTag: number; configFlags?: number; totalAssetValueInitLimit: string; oracleMaxAge: number; oracleMaxConfidence: number; fixedPrice: WrappedI80F48; scopeEntryIndex?: number; } interface EmodeSettingsRawDto { emodeTag: number; timestamp: string; flags: string; emodeConfig: EmodeConfigRawDto; } interface EmodeConfigRawDto { entries: EmodeEntryRawDto[]; } interface EmodeEntryRawDto { collateralBankEmodeTag: number; flags: number; assetWeightInit: WrappedI80F48; assetWeightMaint: WrappedI80F48; } declare function freezeBankConfigIx(program: MarginfiProgram, bankAddress: PublicKey, bankConfigOpt: BankConfigOpt): Promise; type AddOracleToBanksIxArgs = { program: MarginfiProgram; bankAddress: PublicKey; feedId: PublicKey; /** @deprecated Use oracleAccounts when the setup needs on-chain validation accounts. */ oracleKey?: PublicKey; /** Ordered exactly as the program's oracle accounts for the selected setup. */ oracleAccounts?: PublicKey[]; setup: OracleSetup; groupAddress?: PublicKey; adminAddress?: PublicKey; }; declare function addOracleToBanksIx({ program, bankAddress, feedId, oracleKey, oracleAccounts, setup, groupAddress, adminAddress, }: AddOracleToBanksIxArgs): Promise; type SetOraclePriceIxArgs = { program: MarginfiProgram; bankAddress: PublicKey; price: BigNumber$1; setup: OracleSetup.Fixed | OracleSetup.PTPyth | OracleSetup.PTFixed; /** Fixed venue account, [Pyth, Exponent vault], or [Exponent vault], depending on setup. */ oracleAccounts?: PublicKey[]; groupAddress?: PublicKey; adminAddress?: PublicKey; }; /** Configure a flat fixed price or an Exponent PT price using the 0.1.11 instruction. */ declare function setOraclePriceIx({ program, bankAddress, price, setup, oracleAccounts, groupAddress, adminAddress, }: SetOraclePriceIxArgs): Promise; type ConfigureScopeOracleIxArgs = { program: MarginfiProgram; bankAddress: PublicKey; oracle: PublicKey; entryIndex: number; groupAddress?: PublicKey; adminAddress?: PublicKey; }; declare function configureScopeOracleIx({ program, bankAddress, oracle, entryIndex, groupAddress, adminAddress, }: ConfigureScopeOracleIxArgs): Promise; declare function serializeBankConfigOpt(bankConfigOpt: BankConfigOpt): BankConfigOptRaw; declare function serializeInterestRateConfig(interestRateConfig: InterestRateConfig): InterestRateConfigRaw; declare function serializeRiskTier(riskTier: RiskTier): RiskTierRaw; declare function serializeOperationalState(operationalState: OperationalState): { paused: Record; } | { operational: Record; } | { reduceOnly: Record; }; declare function serializeOracleSetupToIndex(oracleSetup: OracleSetup): number; declare function serializeOracleSetup(oracleSetup: OracleSetup): OracleSetupRaw; declare function toBankDto(bank: BankType): BankTypeDto; declare function toBankRateLimiterDto(rateLimiter: BankRateLimiterType): BankRateLimiterDto; declare function toEmodeSettingsDto(emodeSettings: EmodeSettingsType): EmodeSettingsDto; declare function toBankConfigDto(bankConfig: BankConfigType): BankConfigDto; declare function toInterestRateConfigDto(interestRateConfig: InterestRateConfig): InterestRateConfigDto; declare function bankRawToDto(bankRaw: BankRaw): BankRawDto; declare function bankRateLimiterRawToDto(rateLimiter: BankRateLimiterRaw): BankRateLimiterRawDto; declare function emodeSettingsRawToDto(emodeSettingsRaw: EmodeSettingsRaw): EmodeSettingsRawDto; declare function bankConfigToBankConfigRaw(config: BankConfigType): BankConfigRaw; declare function bankConfigRawToDto(bankConfigRaw: BankConfigRaw): BankConfigRawDto; declare function decodeBankRaw(encoded: Buffer, idl: MarginfiIdlType): BankRaw; declare function parseEmodeSettingsRaw(emodeSettingsRaw: EmodeSettingsRaw): EmodeSettingsType; declare function parseBankRateLimiterRaw(rateLimiter: BankRateLimiterRaw): BankRateLimiterType; interface BankMetadata { tokenAddress: string; tokenName: string; tokenSymbol: string; } declare function parseBankRaw(address: PublicKey, accountParsed: BankRaw, bankMetadata?: BankMetadata): BankType; declare function dtoToBank(bankDto: BankTypeDto): BankType; declare function dtoToBankRateLimiter(rateLimiter: BankRateLimiterDto): BankRateLimiterType; declare function dtoToEmodeSettings(emodeSettingsDto: EmodeSettingsDto): EmodeSettingsType; declare function dtoToBankConfig(bankConfigDto: BankConfigDto): BankConfigType; declare function dtoToInterestRateConfig(interestRateConfigDto: InterestRateConfigDto): InterestRateConfig; declare function dtoToBankRaw(bankDto: BankRawDto): BankRaw; declare function dtoToBankRateLimiterRaw(rateLimiter: BankRateLimiterRawDto): BankRateLimiterRaw; declare function dtoToEmodeSettingsRaw(emodeSettingsDto: EmodeSettingsRawDto): EmodeSettingsRaw; declare function dtoToBankConfigRaw(bankConfigDto: BankConfigRawDto): BankConfigRaw; declare function parseBankConfigRaw(bankConfigRaw: BankConfigRaw): BankConfigType; declare function parseRiskTier(riskTierRaw: RiskTierRaw): RiskTier; declare function parseOperationalState(operationalStateRaw: OperationalStateRaw): OperationalState; declare function parseOracleSetup(oracleSetupRaw: OracleSetupRaw): OracleSetup; /** * Get all active EMode flags as an array of flag names */ declare function getActiveEmodeFlags(flags: BN): EmodeFlags[]; /** * Check if a specific EMode flag is set */ declare function hasEmodeFlag(flags: BN, flag: number): boolean; /** * Get all active EMode entry flags as an array of flag names */ declare function getActiveEmodeEntryFlags(flags: number): EmodeEntryFlags[]; /** * Check if a specific EMode entry flag is set */ declare function hasEmodeEntryFlag(flags: number, flag: number): boolean; /** * Parse a raw EMode tag number into the corresponding EmodeTag enum value */ declare function parseEmodeTag(emodeTagRaw: number): EmodeTag; /** * Share ↔ Quantity Conversion Utilities * ===================================== */ /** * Computes the total asset quantity for a bank (all deposits). * * @param bank - The bank to compute total assets for * @returns Total asset quantity across all positions */ declare function getTotalAssetQuantity(bank: BankType): BigNumber$1; /** * Computes the total liability quantity for a bank (all borrows). * * @param bank - The bank to compute total liabilities for * @returns Total liability quantity across all positions */ declare function getTotalLiabilityQuantity(bank: BankType): BigNumber$1; /** * Converts asset shares to asset quantity. * * @param bank - The bank containing the share value * @param assetShares - The number of asset shares to convert * @returns Asset quantity represented by the shares * * @example * ```typescript * const quantity = getAssetQuantity(bank, new BigNumber(100)); * ``` */ declare function getAssetQuantity(bank: BankType, assetShares: BigNumber$1): BigNumber$1; /** * Converts liability shares to token quantity. * * @param bank - The bank containing the share value * @param liabilityShares - The number of liability shares to convert * @returns Token quantity represented by the shares */ declare function getLiabilityQuantity(bank: BankType, liabilityShares: BigNumber$1): BigNumber$1; /** * Converts token quantity to asset shares. * * @param bank - The bank containing the share value * @param assetQuantity - The token quantity to convert (for integrations, this is the collateral token amount) * @returns Number of asset shares representing the quantity (0 if share value is zero) */ declare function getAssetShares(bank: BankType, assetQuantity: BigNumber$1): BigNumber$1; /** * Converts token quantity to liability shares. * * @param bank - The bank containing the share value * @param liabilityQuantity - The token quantity to convert * @returns Number of liability shares representing the quantity (0 if share value is zero) */ declare function getLiabilityShares(bank: BankType, liabilityQuantity: BigNumber$1): BigNumber$1; interface BalanceRaw { active: boolean | number; bankPk: PublicKey; assetShares: WrappedI80F48; liabilityShares: WrappedI80F48; emissionsOutstanding: WrappedI80F48; lastUpdate: BN; } interface HealthCacheRaw { assetValue: WrappedI80F48; liabilityValue: WrappedI80F48; assetValueMaint: WrappedI80F48; liabilityValueMaint: WrappedI80F48; assetValueEquity: WrappedI80F48; liabilityValueEquity: WrappedI80F48; timestamp: BN; flags: number; prices: number[][]; errIndex: number; internalErr: number; internalBankruptcyErr: number; internalLiqErr: number; mrgnErr: number; } interface MarginfiAccountRaw { group: PublicKey; authority: PublicKey; lendingAccount: { balances: BalanceRaw[]; }; accountFlags: BN; emissionsDestinationAccount: PublicKey; healthCache: HealthCacheRaw; padding0?: BN[]; } type MarginRequirementTypeRaw = { initial: Record; } | { maintenance: Record; } | { equity: Record; }; interface BalanceTypeDto { active: boolean; bankPk: string; assetShares: string; liabilityShares: string; emissionsOutstanding: string; lastUpdate: number; } interface HealthCacheTypeDto { assetValue: string; liabilityValue: string; assetValueMaint: string; liabilityValueMaint: string; assetValueEquity: string; liabilityValueEquity: string; timestamp: string; flags: HealthCacheFlags[]; prices: number[][]; simulationStatus: HealthCacheStatus; } interface MarginfiAccountTypeDto { address: string; group: string; authority: string; balances: BalanceTypeDto[]; accountFlags: AccountFlags[]; emissionsDestinationAccount: string; healthCache: HealthCacheTypeDto; } interface SimulationResultRaw { marginfiAccount: MarginfiAccountType; banks: BankType[]; } /** * Custom error class for health cache simulation failures */ declare class HealthCacheSimulationError extends Error { mrgnErr: number | null; internalErr: number | null; constructor(message: string, mrgnErr: number | null, internalErr: number | null); } /** * The footprint of everything in the flashloan transaction *except* the swap. * Drives both the Titan V3 `transactionTemplate` (precise route sizing) and the * fit check / Jupiter account budget. `instructions` are the non-swap inner ixs * (CU + primary + secondary), with NO begin/end-flashloan wrapper — the wrapper * is optional context for Titan template accuracy only. */ interface TxFootprint { instructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; /** Begin/end-flashloan ixs, for Titan template sizing only (optional). */ wrapperInstructions?: TransactionInstruction[]; payer: PublicKey; /** Available swap byte budget (net of the flashloan wrapper). */ sizeConstraint: number; /** Available swap account-slot budget (net of the flashloan wrapper). */ maxSwapTotalAccounts: number; } /** Provider-agnostic swap request handed to the engine. */ interface SwapEngineRequest { inputMint: string; outputMint: string; /** ExactIn input amount in native (base) units. */ amountNative: number; inputDecimals: number; outputDecimals: number; slippageBps?: number; slippageMode?: "DYNAMIC" | "FIXED"; platformFeeBps?: number; directRoutesOnly?: boolean; taker: PublicKey; destinationTokenAccount: PublicKey; connection: Connection; /** Required for the build path; ignored by the ExactOut estimate path. */ footprint?: TxFootprint; /** Ordered providers to query (each with its own apiConfig). */ providers: SwapProviderEntry[]; /** Optional override for the Jupiter maxAccounts ladder. */ jupiterMaxAccountsLadder?: number[]; } /** A single route returned by a provider adapter, before the engine fit check. */ interface ProviderSwapRoute { provider: SwapProvider; swapInstructions: TransactionInstruction[]; setupInstructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; /** Expected output (ExactIn) in native units. */ outAmountNative: BN; /** Minimum guaranteed output after slippage, in native units. */ otherAmountThresholdNative: BN; quoteResult: SwapQuoteResult; /** Optional label for diagnostics (e.g. Jupiter maxAccounts rung). */ label?: string; } /** A provider route annotated with the engine's fit verdict. */ interface SwapCandidate extends ProviderSwapRoute { fullTxSize: number; totalAccounts: number; fits: boolean; } /** Engine output — the exact shape the flashloan finalize step consumes. */ interface SwapEngineResult { swapInstructions: TransactionInstruction[]; setupInstructions: TransactionInstruction[]; swapLuts: AddressLookupTableAccount[]; quoteResponse: SwapQuoteResult; outputAmountNative: BN; /** Winning provider, for diagnostics. */ provider: SwapProvider; } /** * Pluggable engine executor. Defaults to the in-process `runSwapEngine`; the app * injects a runner that forwards to the server-side `/api/tx/swap-engine` so the * provider fan-out happens once, server-side (Design B). */ type SwapEngineRunner = (req: SwapEngineRequest) => Promise; /** * A provider implementation. Add a provider = add an adapter + register it. * * Note: there is intentionally no ExactOut capability here. Provider ExactOut * quotes are unreliable and Jupiter Router `/build` is ExactIn-only, so callers * that need a target output (e.g. swap-debt) size the input from a market-price * calculation and route ExactIn instead. */ interface SwapAdapter { name: SwapProvider; supportsBuild: boolean; /** Fetch one or more candidate routes (Jupiter returns several rungs). */ buildCandidates(req: SwapEngineRequest, apiConfig?: SwapApiConfig): Promise; } type SwbOracleAiDataByKey = Record; /** * What the multiplier computation needs per bank. Derived from the bank config by * `getOracleMultiplierBankInput`. */ type OracleMultiplierBankInput = { bankAddress: string; oracleSetup: OracleSetup; multiplierAccountKey: string; /** PT start price; only read for PTPyth / PTFixed. */ fixedPrice?: BigNumber$1; }; /** * Decoded multiplier account, JSON-safe so an API route can return it as-is. Big values are * decimal strings. */ type MultiplierAccountState = { kind: "marinade"; msolPrice: string; } | { kind: "stakePool"; exchangeRate: string; lastUpdateEpoch: number; } | { kind: "exponentVault"; startTs: number; duration: number; syForPt: string; ptSupply: string; lastSeenSyExchangeRate: string; allTimeHighSyExchangeRate: string; }; /** Decoded multiplier accounts keyed by account address, plus the epoch they were read at. */ type MultiplierAccountStates = { states: Record; currentEpoch: number; }; declare function getPriceWithConfidence(oraclePrice: OraclePrice, weighted: boolean): PriceWithConfidence; declare function getPrice(oraclePrice: OraclePrice, priceBias?: PriceBias, weightedPrice?: boolean): BigNumber$1; declare function capConfidenceInterval(price: BigNumber$1, confidence: BigNumber$1, maxConfidence: BigNumber$1): BigNumber$1; declare function parseOraclePriceData(oracleSetup: OracleSetup, rawData: Buffer): OraclePrice; declare function oraclePriceToDto(oraclePrice: OraclePrice): OraclePriceDto; declare function dtoToOraclePrice(dto: OraclePriceDto): OraclePrice; /** * Result of checking if an oracle can be cranked */ interface CrankabilityResult { oracle: PublicKey; crankable: boolean; reason?: string; error?: unknown; } /** * Checks if multiple Switchboard Pull oracles can be cranked by simulating feed updates * * @param feedHashes - Array of oracle feed hashes to check * @param crossbarUrl - Crossbar API endpoint (defaults to production) * @returns Promise resolving to map of feedHash to crankability result */ declare function checkBatchOracleCrankability(feedHashes: string[], crossbarUrl?: string): Promise>; /** * Checks crankability for multiple oracles in parallel * * @param banks - Banks to check oracle crankability for * @param oraclePrices - Map of oracle prices (may contain feedHash) * @param connection - Solana connection for fetching missing feed hashes * @param crossbarUrl - Crossbar API endpoint * @returns Promise resolving to map of oracle address to crankability result */ declare function checkMultipleOraclesCrankability(banks: BankType[], oraclePrices: Map, connection?: Connection, crossbarUrl?: string): Promise>; /** * Filters banks into crankable and uncrankable sets */ declare function partitionBanksByCrankability(banks: BankType[], crankabilityResults: Map): { crankable: BankType[]; uncrankable: Array<{ bank: BankType; reason: string; }>; }; /** * Categorizes banks by their oracle setup type into legacy, push, and staked collateral banks * @param banks - Array of bank objects * @returns Object containing categorized banks by oracle type * - pythLegacyBanks: Banks using deprecated Pyth legacy oracles * - pythPushBanks: Banks using Pyth push oracles * - pythStakedCollateralBanks: Banks using staked collateral with Pyth push oracles * - pythPushKaminosBanks: Banks using Kamino with Pyth push oracles * - driftPythPullBanks: Banks using Drift with Pyth pull oracles * - solendPythPullBanks: Banks using Solend with Pyth pull oracles */ declare const categorizePythBanks: (banks: BankType[]) => { pythLegacyBanks: BankType[]; pythPushBanks: BankType[]; pythStakedCollateralBanks: BankType[]; pythPushKaminosBanks: BankType[]; driftPythPullBanks: BankType[]; solendPythPullBanks: BankType[]; juplendPythPullBanks: BankType[]; pythMultipliedBanks: BankType[]; }; /** * Converts vote account coefficients to bank address coefficients for staked collateral pricing * @param pythStakedCollateralBanks - Array of staked collateral banks * @param validatorVoteAccountByBank - Mapping of bank addresses to validator vote accounts * @param voteAccCoeffs - Price coefficients indexed by vote account addresses * @returns Record mapping bank addresses to their corresponding price coefficients */ declare const convertVoteAccCoeffsToBankCoeffs: (pythStakedCollateralBanks: BankType[], validatorVoteAccountByBank: { [address: string]: string; }, voteAccCoeffs: Record) => Record; /** * Extracts oracle keys from Pyth banks for price data fetching * @param pythBanks - Array of Pyth bank objects * @returns Array of oracle key strings in base58 format */ declare const extractPythOracleKeys: (pythBanks: BankType[]) => string[]; /** * Maps banks to their corresponding oracle prices with optional price coefficient adjustments * @param pythPushBanks - Array of Pyth push oracle banks * @param pythStakedCollateralBanks - Array of staked collateral banks requiring price adjustments * @param oraclePrices - Record of oracle prices indexed by oracle key * @param priceCoeffByBank - Price coefficients for staked collateral banks * @returns Map of bank addresses to their corresponding oracle prices */ declare const mapPythBanksToOraclePrices: (pythPushBanks: BankType[], multipliedBanks: BankType[], oraclePrices: Record, priceCoeffByBank: Record) => Map; /** * Adjusts price component values by multiplying with a price coefficient * @param priceComponent - Price component containing price, confidence, and bounds * @param priceCoeff - Multiplier coefficient to adjust the price values * @returns Adjusted price component with multiplied price and bounds */ declare const adjustPriceComponent: (priceComponent: PriceWithConfidence, priceCoeff: number) => { price: BigNumber$1; confidence: BigNumber$1; lowestPrice: BigNumber$1; highestPrice: BigNumber$1; }; /** * Parses raw Pyth price data from RPC into standardized OraclePriceDto format * @param rawData - Raw buffer data from Pyth price account * @returns Parsed oracle price data with realtime and weighted price information */ declare function parseRpcPythPriceData(rawData: Buffer): OraclePrice; /** * Maps Switchboard banks to their corresponding oracle prices using feed data and crossbar responses * @param banks - Array of bank objects * @param swbOracleAiDataByKey - Oracle account information indexed by oracle key * @param crossbarResponse - Crossbar feed response data indexed by feed ID * @returns Map of bank addresses to their corresponding oracle prices */ declare const mapSwbBanksToOraclePrices: (banks: BankType[], swbOracleAiDataByKey: SwbOracleAiDataByKey, crossbarResponse: Record) => Map; /** * Maps broken Switchboard feeds to oracle prices using fallback price data * @param banks - Array of bank objects * @param swbOracleAiDataByKey - Oracle account information indexed by oracle key * @param fallbackPricesByFeedId - Fallback price data indexed by feed ID * @returns Map of bank addresses to their corresponding oracle prices from the price fallback */ declare const mapBrokenFeedsToOraclePrices: (banks: BankType[], swbOracleAiDataByKey: SwbOracleAiDataByKey, fallbackPricesByFeedId: Record) => Map; declare function parseSwbOraclePriceData(price: number[] | BN, stdDev: BN, timestamp: string, oracleData: { queue: string; feedHash: string; maxVariance: string; minResponses: number; rawPrice: string; stdev: string; }): OraclePrice; /** * Fetches fallback token prices for specific mint addresses using the app's * token price endpoint (e.g. /api/tokens/multi). * * @param mintAddresses - Array of mint addresses to fetch prices for * @param apiEndpoint - Base API endpoint URL (without query parameters) * @param opts - Optional configuration object * @param opts.queryKey - Query parameter name for mint list (defaults to "mintList") * @returns Promise resolving to a record mapping mint addresses to their price values */ declare function getFallbackPricesForMints(mintAddresses: string[], apiEndpoint: string, opts?: { queryKey?: string; }): Promise>; /** * @deprecated Renamed to {@link getFallbackPricesForMints} — the endpoint is * no longer Birdeye-backed. */ declare const getBirdeyePricesForMints: typeof getFallbackPricesForMints; /** * Fetches fallback prices and maps them by feed ID * @param feedMint - Array of objects containing feedId and mintAddress pairs * @returns Promise resolving to record of prices indexed by feed ID */ declare const getFallbackPricesByFeedId: (feedMint: { feedId: string; mintAddress: string; }[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * @deprecated Renamed to {@link getFallbackPricesByFeedId} — the endpoint is * no longer Birdeye-backed. */ declare const getBirdeyeFallbackPricesByFeedId: (feedMint: { feedId: string; mintAddress: string; }[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * A combination of banks that need to be cranked */ interface CrankCombination { banks: PublicKey[]; oracleKeys: Array<{ key: PublicKey; price: OraclePrice; }>; healthAfter: BigNumber$1; } /** * Parameters for smart crank calculation */ interface SmartCrankParams { marginfiAccount: MarginfiAccountType; bankMap: Map; oraclePrices: Map; instructions: TransactionInstruction[]; assetShareValueMultiplierByBank: Map; program: MarginfiProgram; connection?: Connection; crossbarUrl?: string; /** * Whether the group's net-outflow rate limiter is enabled (see * `isGroupRateLimiterEnabled(group.rateLimiter)`). While enabled, the program * requires a fresh oracle for every withdrawn bank in the withdraw instruction's * remaining accounts — including withdraw-all, where the bank drops out of the * health pack. When set, those oracles are always cranked and block if * uncrankable. Defaults to false (no behavior change). */ groupRateLimiterEnabled?: boolean; } /** * Result of smart crank analysis */ interface SmartCrankResult { requiredOracles: Array<{ key: PublicKey; price: OraclePrice; }>; /** Banks with liabilities that cannot be cranked - BLOCKS ALL TRANSACTIONS */ uncrankableLiabilities: Array<{ bank: BankType; reason: string; }>; /** Banks with assets that cannot be cranked */ uncrankableAssets: Array<{ bank: BankType; reason: string; }>; isCrankable: boolean; } /** * Determines which oracles need to be cranked for a transaction to succeed. * * Algorithm: * 1. Parse instructions to determine projected active banks after transaction * 2. Check crankability of all relevant oracles * 3. If any liability oracle is uncrankable, throw error (transaction blocked) * 4. Identify required cranks (liabilities + interaction banks) * 5. Calculate health with only required banks cranked * 6. If healthy, return just required banks * 7. If not healthy, find minimal asset combinations to achieve health * * @param params - Smart crank parameters * @returns Smart crank result with ordered combinations */ declare function computeSmartCrank({ marginfiAccount, bankMap, oraclePrices, instructions, program, connection, crossbarUrl, assetShareValueMultiplierByBank, groupRateLimiterEnabled, }: SmartCrankParams): Promise; declare const ORACLE_SOURCES: { readonly switchboard: "Switchboard"; readonly pyth: "Pyth"; readonly fixed: "Fixed"; readonly scope: "Scope"; readonly unknown: "Unknown"; }; type OracleSourceKey = keyof typeof ORACLE_SOURCES; /** * Gets the oracle source from a oracle source key * @param oracleSourceKey - The oracle source key * @returns The oracle source name */ declare function getOracleSourceNameFromKey(oracleSourceKey: string): string; /** * Gets the venue from a bank * @param bank - The bank to get the venue from * @returns The venue */ declare function getOracleSourceFromBank(bank: BankType): { key: OracleSourceKey; name: string; }; declare function getOracleSourceFromOracleSetup(oracleSetup: OracleSetup): { key: "fixed" | "scope" | "switchboard" | "pyth" | "unknown"; name: "Fixed" | "Scope" | "Unknown" | "Switchboard" | "Pyth"; }; type PtVaultFields = Pick; /** * Builds the multiplier input for a bank, or undefined when the bank is not multiplier-priced. */ declare function getOracleMultiplierBankInput(bank: BankType): OracleMultiplierBankInput | undefined; /** * Decodes a multiplier account without knowing its type up front: Exponent vault (Anchor * discriminator), then Marinade state (discriminator), then SPL stake pool (account-type byte). * Returns undefined when none match. */ declare function decodeMultiplierAccount(data: Buffer): MultiplierAccountState | undefined; /** * PT linear rate: accretion from the bank's fixed_price (start price) to par (1.0) over the * vault's [startTs, startTs + duration], clamped at both ends, then capped by the redemption * backing so an under-backed vault cannot mark above what its PT redeems for. Mirrors the * program's `pt_linear_multiplier`. */ declare function computePtMultiplier(vault: PtVaultFields, startPrice: BigNumber$1, nowSeconds: number): BigNumber$1; /** * The multiplier for one bank given its decoded multiplier account. Throws when the account * type does not match the bank's oracle setup or the rate is unusable. */ declare function computeOracleMultiplier(input: OracleMultiplierBankInput, state: MultiplierAccountState, ctx: { currentEpoch: number; nowSeconds: number; }): number; /** * Maps decoded multiplier accounts back onto banks. Banks whose account is missing or unusable * are left out (and end up unpriced downstream). */ declare function computeOracleMultipliers(inputs: OracleMultiplierBankInput[], accountStates: MultiplierAccountStates, nowSeconds?: number): Record; /** * Configuration for simulating account health cache with fallback */ interface SimulateAccountHealthCacheWithFallbackParams { /** The marginfi program instance */ program: MarginfiProgram; /** Map of banks by their address */ banksMap: Map; /** Map of oracle prices by bank address */ oraclePricesByBank: Map; /** The marginfi account to simulate health cache for */ marginfiAccount: MarginfiAccountType; /** Bank integration metadata map (for Kamino, Drift, etc.) */ bankIntegrationMap: BankIntegrationMetadataMap; /** Asset share value multipliers by bank address (for integrated protocols) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; } /** * Simulates the health cache for a marginfi account with fallback computation. * * This function attempts to simulate the on-chain health cache calculation, which provides * accurate health metrics for the account. If simulation fails (e.g., due to RPC issues), * it falls back to computing health components locally. * * **Primary Method (Simulation):** * - Simulates on-chain health pulse instruction * - Returns the health cache as it would exist on-chain * - Most accurate but requires RPC simulation support * * **Fallback Method (Computation):** * - Computes health components locally using balance data * - Calculates Initial, Maintenance, and Equity values * - Used when simulation fails or is unavailable * * **Health Cache Values:** * - **Initial**: For opening new positions (most conservative) * - **Maintenance**: For liquidation threshold * - **Equity**: Actual account value (no risk weighting) * * @param params - Configuration object for health cache simulation * @returns Promise resolving to account with updated health cache and optional error * * @example * ```typescript * const { marginfiAccount, error } = await simulateAccountHealthCacheWithFallback({ * program: client.program, * bankMap: client.bankMap, * oraclePrices: client.oraclePriceByBank, * marginfiAccount: account, * bankMetadataMap: client.bankIntegrationMap, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * }); * * if (error) { * console.warn("Simulation failed, using computed values:", error); * } * * console.log("Health:", marginfiAccount.healthCache); * ``` */ declare function simulateAccountHealthCacheWithFallback(params: SimulateAccountHealthCacheWithFallbackParams): Promise<{ marginfiAccount: MarginfiAccountType; error?: HealthCacheSimulationError; }>; declare function simulateAccountHealthCache(params: { program: MarginfiProgram; banksMap: Map; marginfiAccount: MarginfiAccountType; bankIntegrationMap?: BankIntegrationMetadataMap; }): Promise; declare function getHealthSimulationTransactions({ projectedActiveBanks, bankMap, bankMetadataMap, marginfiAccount, program, authority, luts, includeCrankTx, blockhash, crossbarUrl, }: { projectedActiveBanks: PublicKey[]; bankMap: Map; bankMetadataMap: BankIntegrationMetadataMap; marginfiAccount: MarginfiAccountType; program: MarginfiProgram; authority: PublicKey; luts: AddressLookupTableAccount[]; includeCrankTx: boolean; blockhash: string; crossbarUrl?: string; }): Promise; /** * Wire serialization for the swap engine, so the provider fan-out can run behind * an HTTP endpoint (Design B). The request intentionally omits `connection` and * per-provider `apiConfig` — the server supplies RPC + API keys from its env. */ interface SerializedInstruction { programId: string; keys: { pubkey: string; isSigner: boolean; isWritable: boolean; }[]; data: string; } interface SerializedLut { key: string; addresses: string[]; } interface SerializedTxFootprint { instructions: SerializedInstruction[]; luts: SerializedLut[]; wrapperInstructions?: SerializedInstruction[]; payer: string; sizeConstraint: number; maxSwapTotalAccounts: number; } interface SerializedSwapEngineRequest { inputMint: string; outputMint: string; amountNative: number; inputDecimals: number; outputDecimals: number; slippageBps?: number; slippageMode?: "DYNAMIC" | "FIXED"; platformFeeBps?: number; directRoutesOnly?: boolean; taker: string; destinationTokenAccount: string; footprint?: SerializedTxFootprint; /** Provider names only; the server attaches each provider's apiConfig. */ providers: SwapProvider[]; jupiterMaxAccountsLadder?: number[]; } interface SerializedSwapEngineResult { swapInstructions: SerializedInstruction[]; setupInstructions: SerializedInstruction[]; swapLuts: SerializedLut[]; quoteResponse: SwapEngineResult["quoteResponse"]; outputAmountNative: string; provider: SwapProvider; } declare function serializeInstruction(ix: TransactionInstruction): SerializedInstruction; declare function deserializeInstruction(s: SerializedInstruction): TransactionInstruction; declare function serializeLut(lut: AddressLookupTableAccount): SerializedLut; declare function deserializeLut(s: SerializedLut): AddressLookupTableAccount; declare function serializeSwapEngineRequest(req: SwapEngineRequest): SerializedSwapEngineRequest; /** * Rebuild a `SwapEngineRequest` server-side. The caller supplies the RPC * `connection` and the per-provider `apiConfig` (gateway URLs + API keys) so * those never travel over the wire. */ declare function deserializeSwapEngineRequest(s: SerializedSwapEngineRequest, ctx: { connection: Connection; providerApiConfigs?: Partial>; }): SwapEngineRequest; declare function serializeSwapEngineResult(res: SwapEngineResult): SerializedSwapEngineResult; declare function deserializeSwapEngineResult(s: SerializedSwapEngineResult): SwapEngineResult; /** * Map a `SwapOpts` (primary provider + fallbacks) to the engine's provider list. * The engine queries ALL of them in parallel and picks the best fitting route, * so "fallback" providers become co-equal candidates here. */ declare function swapEngineProvidersFromOpts(swapOpts: SwapOpts): SwapProviderEntry[]; /** Slippage / fee fields pulled from a `SwapOpts` for an engine request. */ declare function swapEngineQuoteFieldsFromOpts(swapOpts: SwapOpts): { slippageBps?: number; slippageMode?: "DYNAMIC" | "FIXED"; platformFeeBps?: number; directRoutesOnly?: boolean; }; /** * Size the borrow amount for a debt swap from a market-price calculation. * * Provider ExactOut quotes are unreliable and Jupiter Router `/build` is * ExactIn-only, so instead of asking a provider "how much input for this output", * we borrow the no-slippage market equivalent of the repay target plus a slippage * buffer, then route ExactIn. For a full repay we add a little extra so a slight * shortfall doesn't fail the repayAll; for a partial repay we keep the buffer * tight to avoid minting more new debt than necessary. */ declare const DEFAULT_REPAY_ALL_EXTRA_BUFFER_BPS = 50; declare function computeBorrowEstimateForRepay(params: { /** Target repay amount in UI units of the repay token. */ repayTargetUi: number; /** Market price (USD/UI) of the repay token. */ repayMarketPrice: number; /** Market price (USD/UI) of the borrow token. */ borrowMarketPrice: number; slippageBps?: number; /** Whether this repays the whole position (adds the extra buffer). */ isRepayAll: boolean; repayAllExtraBufferBps?: number; }): number; /** * Registry of swap providers. To add a provider: implement a `SwapAdapter` and * add one entry here — the engine picks it up automatically for any request that * lists the provider in `providers`. */ declare const SWAP_ADAPTERS: Partial>; declare function getSwapAdapter(provider: SwapProvider): SwapAdapter | undefined; /** * Multi-provider swap engine. Fans out to every configured provider in parallel, * keeps only routes that fit the remaining flashloan budget, and returns the one * with the highest expected output (ExactIn). The returned shape matches the * flashloan finalize seam so callers splice + patch + wrap unchanged. */ declare function runSwapEngine(req: SwapEngineRequest): Promise; declare const EMPTY_HEALTH_CACHE: HealthCacheRaw; declare function decodeAccountRaw(encoded: Buffer, idl: MarginfiIdlType): MarginfiAccountRaw; declare function parseBalanceRaw(balanceRaw: BalanceRaw): BalanceType; declare function parseHealthCacheRaw(healthCacheRaw: HealthCacheRaw): HealthCacheType; declare function parseMarginfiAccountRaw(marginfiAccountPk: PublicKey, accountData: MarginfiAccountRaw): MarginfiAccountType; /** * Get all active account flags as an array of flag names */ declare function getActiveAccountFlags(flags: BN): AccountFlags[]; /** * Check if an account flag is set */ declare function hasAccountFlag(flags: BN, flag: number): boolean; /** * Convert on-chain health cache flags (BN) to an array of HealthCacheFlags enum values * * According to the IDL, health cache flags are defined as: * - HEALTHY = 1 (bit 0) - If set, the account cannot be liquidated * - ENGINE_STATUS_OK = 2 (bit 1) - If set, the engine did not error during health calculation * - ORACLE_OK = 4 (bit 2) - If set, the engine did not encounter oracle issues */ declare function getActiveHealthCacheFlags(flags: number): HealthCacheFlags[]; /** * Check if a health cache flag is set */ declare function hasHealthCacheFlag(flags: number, flag: HealthCacheFlags): boolean; /** * Convert numeric health cache flags to a human-readable status message */ declare function getHealthCacheStatusDescription(flags: number): string; declare function dtoToMarginfiAccount(marginfiAccountDto: MarginfiAccountTypeDto): MarginfiAccountType; declare function dtoToBalance(balanceDto: BalanceTypeDto): BalanceType; declare function dtoToHealthCache(healthCacheDto: HealthCacheTypeDto): HealthCacheType; /** * Convert numeric flag to BN for Solana compatibility */ declare function accountFlagToBN(flag: AccountFlags): BN; declare function marginfiAccountToDto(marginfiAccount: MarginfiAccountType): MarginfiAccountTypeDto; declare function balanceToDto(balance: BalanceType): BalanceTypeDto; declare function healthCacheToDto(healthCache: HealthCacheType): HealthCacheTypeDto; /** * Generates emode pairs from an array of banks by analyzing their emode configurations. * @param banks - Array of banks to analyze for emode relationships * @returns Array of emode pairs defining relationships between liability and collateral banks */ declare function getEmodePairs(banks: BankType[]): EmodePair[]; /** * Computes the lowest emode weights for each collateral bank across all active emode pairs. * Returns a Map keyed by bank address string for consistency with other SDK maps. * * @param emodePairs - Array of emode pairs to analyze * @returns Map of bank address → lowest { assetWeightInit, assetWeightMaint } */ declare function computeLowestEmodeWeights(emodePairs: EmodePair[]): Map; /** * Creates an ActiveEmodePair from a list of active EmodePairs. * Selects the pair with the lowest assetWeightInit and aggregates all banks and tags. */ declare function createActiveEmodePairFromPairs(pairs: EmodePair[]): ActiveEmodePair | undefined; declare function computeEmodeImpacts(emodePairs: EmodePair[], activeLiabilities: PublicKey[], activeCollateral: PublicKey[], allBanks: PublicKey[]): Record; declare function computeActiveEmodePairs(emodePairs: EmodePair[], activeLiabilities: PublicKey[], activeCollateral: PublicKey[]): EmodePair[]; /** * Health & Free Collateral Calculations * ===================================== */ /** * Computes free collateral from an account's cached health data using Initial margin requirements. * * This is a fast lookup function that reads from the account's existing health cache * rather than recalculating from balances. Free collateral represents the amount of value * available for new borrows or withdrawals. * * By default, negative values are clamped to zero (representing no available collateral). * Set `clamped: false` to get the raw signed value, which can be negative when under-collateralized. * * ⚠️ **Warning**: Returns cached values that may be stale if account state has changed * since the last health cache computation. * * @param marginfiAccount - The marginfi account with a populated health cache * @param opts - Optional configuration object * @param opts.clamped - Whether to clamp negative values to zero (default: true) * @returns Free collateral value in USD from cached data (clamped to zero by default) * * @example * ```typescript * // Get available collateral from cache (default clamped) * const freeCollateral = computeFreeCollateralFromCache(account); * * // Get raw signed value from cache (can be negative) * const signedValue = computeFreeCollateralFromCache(account, { clamped: false }); * ``` */ declare function computeFreeCollateralFromCache(marginfiAccount: MarginfiAccountType, opts?: { clamped?: boolean; }): BigNumber$1; /** * Configuration for computing free collateral from balances */ interface ComputeFreeCollateralFromBalancesParams { /** Active account balances to compute free collateral for */ activeBalances: BalanceType[]; /** Map of bank addresses to bank data */ banksMap: Map; /** Map of bank addresses to oracle price data */ oraclePricesByBank: Map; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; /** Whether to clamp negative values to zero (default: true) */ clamped?: boolean; } /** * Computes free collateral from account balances using Initial margin requirements. * * Free collateral represents the amount of value available for new borrows or withdrawals. * It is calculated as: (weighted assets - weighted liabilities) at Initial margin level. * * By default, negative values are clamped to zero (representing no available collateral). * Set `clamped: false` to get the raw signed value, which can be negative when under-collateralized. * * @param params - Configuration object for free collateral computation * @returns Free collateral value in USD (clamped to zero by default) * * @example * ```typescript * // Calculate available collateral for new positions * const freeCollateral = computeFreeCollateralFromBalances({ * activeBalances: account.balances.filter(b => b.active), * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * }); * * // Get raw signed value (can be negative) * const signedValue = computeFreeCollateralFromBalances({ * activeBalances: account.balances.filter(b => b.active), * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * clamped: false, * }); * ``` */ declare function computeFreeCollateralFromBalances(params: ComputeFreeCollateralFromBalancesParams): BigNumber$1; /** * Retrieves pre-computed health components from an account's cached health data. * * This is a fast lookup function that reads from the account's existing health cache * rather than recalculating from balances. Use this when the health cache is already * up-to-date. * * ⚠️ **Warning**: Returns cached values that may be stale if account state has changed * since the last health cache computation. * * @param marginfiAccount - The marginfi account with a populated health cache * @param marginRequirement - Which margin requirement level to retrieve (Equity, Initial, or Maintenance) * @returns Object containing cached asset and liability values in USD * * @example * ```typescript * // Get initial margin requirements from cache * const { assets, liabilities } = computeHealthComponentsFromCache( * account, * MarginRequirementType.Initial * ); * const freeCollateral = assets.minus(liabilities); * ``` */ declare function computeHealthComponentsFromCache(marginfiAccount: MarginfiAccountType, marginRequirement: MarginRequirementType): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Configuration for computing health components from balances */ interface ComputeHealthComponentsFromBalancesParams { /** Active account balances to compute health for */ activeBalances: BalanceType[]; /** Margin requirement type (Equity, Initial, or Maintenance) */ marginRequirement: MarginRequirementType; /** Map of bank addresses to bank data */ banksMap: Map; /** Map of bank addresses to oracle price data */ oraclePricesByBank: Map; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; /** Optional banks to exclude from health calculation */ excludedBanks?: PublicKey[]; } /** * Computes health components (assets and liabilities) from active balances with price bias applied. * * This function: * - Applies price bias (lowest for assets, highest for liabilities) for conservative health estimates * - Supports asset share multipliers for integrated protocols (Kamino, Drift) * - Allows emode weight overrides for specific banks * - Can exclude specific banks from the calculation * * @param params - Configuration object for health computation * @returns Object containing weighted asset and liability values in USD * * @example * ```typescript * const { assets, liabilities } = computeHealthComponentsFromBalances({ * activeBalances: account.balances.filter(b => b.active), * marginRequirement: MarginRequirementType.Initial, * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * }); * ``` */ declare function computeHealthComponentsFromBalances(params: ComputeHealthComponentsFromBalancesParams): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Configuration for computing health cache status */ interface ComputeHealthCacheStatusParams { /** Active account balances to compute health cache for */ activeBalances: BalanceType[]; /** Map of bank addresses to bank data */ banksMap: Map; /** Map of bank addresses to oracle price data */ oraclePricesByBank: Map; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; } /** * Computes a complete health cache with all margin requirement levels. * * This function calculates health components for all three margin requirement types: * - **Equity**: Unbiased prices, used for account value calculations * - **Maintenance**: Conservative prices, determines liquidation threshold * - **Initial**: Conservative prices, determines whether new positions can be opened * * The resulting health cache is typically used for: * - Real-time health monitoring * - Simulating transaction outcomes * - Determining account solvency status * * @param params - Configuration object for health cache computation * @returns Complete health cache with all margin requirement levels * * @example * ```typescript * const healthCache = computeHealthCacheStatus({ * activeBalances: account.balances.filter(b => b.active), * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * activeEmodeWeightsByBank: account.emodeWeights, * }); * ``` */ declare function computeHealthCacheStatus(params: ComputeHealthCacheStatusParams): HealthCacheType; /** * Configuration for computing liability health component */ interface ComputeLiabilityHealthComponentParams { /** All account balances (will be filtered to liability positions) */ balances: BalanceType[]; /** Map of bank addresses to bank data */ banksMap: Map; /** Map of bank addresses to oracle price data */ oraclePricesByBank: Map; /** Specific bank addresses to include as liabilities */ liabilityBanks: PublicKey[]; /** Margin requirement type (Equity, Initial, or Maintenance) */ marginRequirement: MarginRequirementType; } /** * Computes the total weighted liability value for specific liability positions. * * This function filters balances to only include positions in the specified liability banks, * then calculates their total weighted USD value using conservative pricing (highest price bias). * * Useful for: * - Calculating partial health impacts when simulating repayments * - Analyzing liability exposure to specific assets * - Risk assessment for particular debt positions * * @param params - Configuration object for liability health computation * @returns Total weighted liability value in USD for the specified banks * * @example * ```typescript * // Calculate liability value for USDC and SOL positions * const liabilityValue = computeLiabilityHealthComponent({ * balances: account.balances, * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * liabilityBanks: [usdcBankAddress, solBankAddress], * marginRequirement: MarginRequirementType.Initial, * }); * ``` */ declare function computeLiabilityHealthComponent(params: ComputeLiabilityHealthComponentParams): BigNumber$1; /** * Configuration for computing asset health component */ interface ComputeAssetHealthComponentParams { /** All account balances (will be filtered to asset positions) */ balances: BalanceType[]; /** Map of bank addresses to bank data */ banksMap: Map; /** Map of bank addresses to oracle price data */ oraclePricesByBank: Map; /** Specific bank addresses to include as assets */ assetBanks: PublicKey[]; /** Margin requirement type (Equity, Initial, or Maintenance) */ marginRequirement: MarginRequirementType; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; } /** * Computes the total weighted asset value for specific asset positions. * * This function filters balances to only include positions in the specified asset banks, * then calculates their total weighted USD value using conservative pricing (lowest price bias). * * Useful for: * - Calculating partial health impacts when simulating withdrawals * - Analyzing collateral value from specific assets * - Risk assessment for particular lending positions * - Determining borrowing power from subset of collateral * * @param params - Configuration object for asset health computation * @returns Total weighted asset value in USD for the specified banks * * @example * ```typescript * // Calculate asset value for SOL and USDC collateral positions * const assetValue = computeAssetHealthComponent({ * balances: account.balances, * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * assetBanks: [solBankAddress, usdcBankAddress], * marginRequirement: MarginRequirementType.Initial, * assetShareValueMultiplierByBank: client.assetShareMultiplierByBank, * }); * ``` */ declare function computeAssetHealthComponent(params: ComputeAssetHealthComponentParams): BigNumber$1; /** * Balance Value & Quantity Calculations * ===================================== */ /** * Configuration for computing balance USD value */ interface ComputeBalanceUsdValueParams { /** The balance to compute USD value for */ balance: BalanceType; /** The bank containing the balance */ bank: BankType; /** Oracle price data */ oraclePrice: OraclePrice; /** Which margin level (Initial, Maintenance, Equity) */ marginRequirement: MarginRequirementType; /** Asset share value multiplier for integrated protocols (Kamino, Drift) */ assetShareValueMultiplier?: BigNumber$1; /** Optional emode weight overrides */ activeEmodeWeights?: { assetWeightInit: BigNumber$1; assetWeightMaint: BigNumber$1; }; } /** * Computes the USD value of both assets and liabilities for a balance. * * This function returns the USD value of the position's assets (deposits) and * liabilities (borrows) separately, using neutral price bias (no conservative adjustments). * * @param params - Configuration object for balance USD value computation * @returns Object containing assets and liabilities USD values * * @example * ```typescript * const { assets, liabilities } = computeBalanceUsdValue({ * balance, * bank, * oraclePrice, * marginRequirement: MarginRequirementType.Initial, * }); * console.log(`Assets: $${assets.toFormat(2)}, Liabilities: $${liabilities.toFormat(2)}`); * ``` */ declare function computeBalanceUsdValue(params: ComputeBalanceUsdValueParams): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Configuration for computing balance USD value with price bias */ interface GetBalanceUsdValueWithPriceBiasParams { /** The balance to compute USD value for */ balance: BalanceType; /** The bank containing the balance */ bank: BankType; /** Oracle price data */ oraclePrice: OraclePrice; /** Which margin level (Initial, Maintenance, Equity) */ marginRequirement: MarginRequirementType; /** Asset share value multiplier for integrated protocols (Kamino, Drift) */ assetShareValueMultiplier?: BigNumber$1; /** Optional emode weight overrides */ activeEmodeWeights?: { assetWeightInit: BigNumber$1; assetWeightMaint: BigNumber$1; }; } /** * Computes the USD value of both assets and liabilities with conservative price bias. * * This function applies conservative pricing for risk management: * - **Assets**: Uses Lowest price (conservative collateral valuation) * - **Liabilities**: Uses Highest price (conservative debt valuation) * * This is more conservative than `computeBalanceUsdValue` which uses neutral pricing. * Typically used for health checks and liquidation thresholds. * * @param params - Configuration object for balance USD value computation * @returns Object containing assets and liabilities USD values with conservative bias * * @example * ```typescript * const { assets, liabilities } = getBalanceUsdValueWithPriceBias({ * balance, * bank, * oraclePrice, * marginRequirement: MarginRequirementType.Maintenance, * }); * // Conservative health factor calculation * const healthFactor = assets.div(liabilities); * ``` */ declare function getBalanceUsdValueWithPriceBias(params: GetBalanceUsdValueWithPriceBiasParams): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Computes the native token quantities for a balance. * * Converts balance shares to actual token amounts in native units (no decimal scaling). * * @param balance - The balance to compute quantities for * @param bank - The bank containing the balance * @returns Object with assets and liabilities in native token amounts */ declare function computeQuantity(balance: BalanceType, bank: BankType): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Computes the UI-formatted token quantities for a balance. * * This function: * 1. Converts shares → native token amounts * 2. (Optional) Applies cToken exchange rate for integrated protocols * 3. Scales by token decimals for UI display * * **For integrated protocols (Kamino, Drift):** * The `assetShareValueMultiplier` converts cToken amounts to underlying token amounts. * This is crucial because oracle prices are denominated in the underlying token, not the cToken. * * @param balance - The balance to compute quantities for * @param bank - The bank containing the balance * @param assetShareValueMultiplier - Exchange rate for cToken → underlying conversion (Kamino, Drift) * @returns Object with assets and liabilities in UI-formatted amounts * * @example * ```typescript * // Regular bank (USDC) * const { assets, liabilities } = computeQuantityUi(balance, usdcBank); * console.log(`Deposited: ${assets.toFixed(2)} USDC`); * * // Kamino bank (kUSDC → USDC) * const kaminoRate = getDriftCTokenMultiplier(kaminoMarket); * const { assets, liabilities } = computeQuantityUi(balance, kaminoBank, kaminoRate); * console.log(`Deposited: ${assets.toFixed(2)} USDC (underlying)`); * // Now assets matches oracle pricing which is in USDC, not kUSDC * ``` */ declare function computeQuantityUi(balance: BalanceType, bank: BankType, assetShareValueMultiplier?: BigNumber$1): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Balance Helper Utilities * ======================== */ /** * Creates an empty (inactive) balance object for a specific bank. * * This is useful for initializing balance slots or representing non-existent positions. * All numeric fields are set to zero and the balance is marked as inactive. * * @param bankPk - The public key of the bank this balance is associated with * @returns An inactive balance object with all values set to zero * * @example * ```typescript * const emptyBalance = createEmptyBalance(bankAddress); * // emptyBalance.active === false * // emptyBalance.assetShares.eq(0) === true * ``` */ declare function createEmptyBalance(bankPk: PublicKey): BalanceType; /** * Filters an array of balances to return only active positions. * * Active balances are positions that currently have assets or liabilities. * Inactive balances are empty slots available for new positions. * * @param balances - Array of account balances to filter * @returns Array containing only balances where `active === true` * * @example * ```typescript * const activePositions = getActiveBalances(account.balances); * // Returns only balances with actual assets or liabilities * ``` */ declare function getActiveBalances(balances: BalanceType[]): BalanceType[]; /** * Retrieves the balance for a specific bank address from an array of balances. * * If an active balance is found for the bank, it is returned. Otherwise, an empty * (inactive) balance is created for that bank address. * * This function is safe to use without null checks - it always returns a valid balance object. * * @param bankAddress - The public key of the bank to look up * @param balances - Array of account balances to search * @returns The active balance if found, otherwise a newly created empty balance * * @example * ```typescript * const usdcBalance = getBalance(usdcBankAddress, account.balances); * if (usdcBalance.active) { * // User has a USDC position * console.log("Assets:", usdcBalance.assetShares); * } else { * // User has no USDC position (empty balance returned) * } * ``` */ declare function getBalance(bankAddress: PublicKey, balances: BalanceType[]): BalanceType; /** * Account-Level Metrics * ==================== */ declare function computeAccountValue(marginfiAccount: MarginfiAccountType): BigNumber$1; /** * Configuration for computing net APY */ interface ComputeNetApyParams { /** The marginfi account to compute net APY for */ marginfiAccount: MarginfiAccountType; /** Active balances in the account */ activeBalances: BalanceType[]; /** Map of banks by their address */ banksMap: Map; /** Map of oracle prices by bank address */ oraclePricesByBank: Map; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** Optional emode weight overrides by bank address */ activeEmodeWeightsByBank?: Map; } /** * Computes the net APY (Annual Percentage Yield) for a marginfi account. * * The net APY represents the combined annualized return from all lending and borrowing * positions in the account, weighted by their USD values. * * **Calculation:** * 1. Computes weighted APR contributions from each position: * - **Lending positions**: Positive contribution (earning interest) * - **Borrowing positions**: Negative contribution (paying interest) * 2. Weights each position by its USD value relative to total account value * 3. Converts the final APR to APY (accounts for compounding) * * **Example:** * - Account has $1000 net value * - $800 lent at 5% APR = +4% contribution to net APR * - $600 borrowed at 3% APR = -1.8% contribution to net APR * - Net APR = +2.2%, converted to APY * * @param params - Configuration object for net APY computation * @returns Net APY as a decimal (e.g., 0.05 for 5% APY) * * @example * ```typescript * const netApy = computeNetApy({ * marginfiAccount: account, * activeBalances: account.balances.filter(b => b.active), * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * }); * console.log(`Net APY: ${(netApy * 100).toFixed(2)}%`); * ``` */ declare function computeNetApy(params: ComputeNetApyParams): number; /** * Configuration for computing liquidation price for a bank position */ interface ComputeLiquidationPriceForBankParams { /** The bank to compute liquidation price for */ bank: BankType; /** Oracle price data for the bank */ oraclePrice: OraclePrice; /** The marginfi account containing the position */ marginfiAccount: MarginfiAccountType; /** Asset share value multiplier for integrated protocols (Kamino, Drift) */ assetShareValueMultiplier?: BigNumber$1; /** Optional emode weight overrides */ activeEmodeWeights?: { assetWeightInit: BigNumber$1; assetWeightMaint: BigNumber$1; }; } /** * Computes the liquidation price for a specific bank position. * * The liquidation price is the asset price at which the account would be liquidated * based on the current position in this bank and all other positions in the account. * * **For lending (asset) positions:** * - Price where asset value (weighted) + other assets = liabilities * - Lower prices mean less collateral value → liquidation risk * * **For borrowing (liability) positions:** * - Price where assets = liability value (weighted) + other liabilities * - Higher prices mean more debt value → liquidation risk * * Uses maintenance margin requirements and includes oracle price confidence bands. * * @param params - Configuration object for liquidation price computation * @returns Liquidation price in token terms, or null if: * - Position is inactive * - Account has no liabilities (for lending positions) * - Calculation results in invalid number (NaN, negative, infinite) * * @example * ```typescript * // Lending position: at what SOL price would I get liquidated? * const liqPrice = computeLiquidationPriceForBank({ * bank: solBank, * oraclePrice: solOraclePrice, * marginfiAccount: account, * }); * if (liqPrice) { * console.log(`Liquidation at $${liqPrice.toFixed(2)} per SOL`); * } * ``` */ declare function computeLiquidationPriceForBank(params: ComputeLiquidationPriceForBankParams): number | null; /** * Emissions Calculations * ===================== */ /** * Computes the emissions accrued for a balance since its last update. * * This function calculates emissions based on: * - The time elapsed since the balance was last updated * - The bank's emissions rate (tokens per year) * - Whether lending or borrowing emissions are active * - The balance's asset or liability amount * * The calculation is capped by the bank's remaining emissions. * * @deprecated This function is deprecated. Emissions are now distributed offchain and should not be used in new code. * * @param balance - The account balance to compute emissions for * @param bank - The bank configuration containing emissions parameters * @param currentTimestamp - Current timestamp in seconds (Unix time) * @returns Newly accrued emissions since last update (not yet claimed) * * @example * ```typescript * // Calculate emissions accrued up to now * const emissions = computeClaimedEmissions( * balance, * bank, * Date.now() / 1000 * ); * ``` */ declare function computeClaimedEmissions(balance: BalanceType, bank: BankType, currentTimestamp: number): BigNumber$1; /** * Computes the total outstanding emissions for a balance (claimed + unclaimed). * * @deprecated This function is deprecated. Emissions are now distributed offchain and should not be used in new code. * * @param balance - The account balance to compute emissions for * @param bank - The bank configuration containing emissions parameters * @returns Total outstanding emissions (claimed from balance + newly accrued unclaimed) */ declare function computeTotalOutstandingEmissions(balance: BalanceType, bank: BankType): BigNumber$1; /** * Transaction Projection & Health Check Utilities * =============================================== */ /** * Computes the set of banks to include in health check account metas. * * This function determines which banks should be included when performing health checks * by considering active balances, mandatory banks, and exclusions. It intelligently * manages the 16-balance limit by: * - Including all active banks (excluding any in the exclusion list) * - Reserving inactive slots for mandatory banks that aren't currently active * * @param account - The marginfi account whose balances are evaluated * @param banksMap - Map of bank addresses to bank data * @param mandatoryBanks - Banks that must be included (e.g., for pending transactions) * @param excludedBanks - Banks to exclude from health checks * @returns Array of bank objects to include in health check * * @example * ```typescript * const healthCheckBanks = computeHealthCheckAccounts({ * account, * banksMap, * mandatoryBanks: [newBankToDeposit], // Not active yet but will be * excludedBanks: [closingBank], // Being closed in this transaction * }); * ``` */ declare function computeHealthCheckAccounts({ account, banksMap, mandatoryBanks, excludedBanks, }: { account: MarginfiAccountType; banksMap: Map; mandatoryBanks?: PublicKey[]; excludedBanks?: PublicKey[]; }): BankType[]; /** * Converts bank objects to health check account metas (public keys). * * This function generates the list of account public keys needed for health check * instructions. For each bank, it includes: * - The bank address * - The oracle address (if not default) * - Additional integration accounts: * - Kamino: kamino reserve account * - Drift: drift spot market account * * Optionally sorts accounts using `composeRemainingAccounts` to optimize transaction size. * * @param banksToInclude - Array of banks to include in health check * @param enableSorting - Whether to sort/optimize account order (default: true) * @param trailingBanks - Banks whose accounts are appended unsorted after the health pack * (e.g., the withdrawn bank on withdraw-all, for the 1.9 rate-limiter price fetch) * @returns Flattened array of public keys for health check accounts * * @example * ```typescript * const healthAccounts = computeHealthAccountMetas({ * banksToInclude: [usdcBank, solBank, kaminoUsdcBank], * }); * // Returns: [bank1, oracle1, bank2, oracle2, bank3, oracle3, kaminoReserve3, ...] * ``` */ declare function computeHealthAccountMetas({ banksToInclude, enableSorting, trailingBanks, }: { banksToInclude: BankType[]; enableSorting?: boolean; trailingBanks?: BankType[]; }): PublicKey[]; /** * Projects which banks will be active after a series of instructions execute. * * This function simulates instruction execution to determine which bank positions * will be active (non-zero) after the transaction completes. It's used to optimize * health check account inclusion by predicting which banks are relevant. * * **Note**: This does NOT simulate Cross-Program Invocations (CPI). Only direct * marginfi instructions are considered. Instructions operating on a different * marginfi account than `account` are ignored. * * Supported instructions: * - Deposits: `lendingAccountDeposit`, `kaminoDeposit`, `driftDeposit`, `solendDeposit` * - Borrows: `lendingAccountBorrow` * - Repays: `lendingAccountRepay` * - Withdrawals: `lendingAccountWithdraw`, `kaminoWithdraw`, `driftWithdraw`, `solendWithdraw` * * @param account - The marginfi account whose balances are projected * @param instructions - Instructions to simulate * @param program - Marginfi program for instruction decoding * @returns Array of bank public keys that will be active after instruction execution * * @example * ```typescript * const projectedBanks = computeProjectedActiveBanksNoCpi({ * account, * instructions: [depositIx, borrowIx], * program: marginfiProgram, * }); * // Use projectedBanks for health check account selection * ``` */ declare function computeProjectedActiveBanksNoCpi({ account, instructions, program, }: { account: MarginfiAccountType; instructions: TransactionInstruction[]; program: MarginfiProgram; }): PublicKey[]; /** * Computes projected balances after applying a series of instructions. * * Simulates how deposit/borrow/repay/withdraw instructions would change the account balances, * including both active/inactive state AND actual share amounts. This is more comprehensive * than `computeProjectedActiveBanksNoCpi` which only tracks active banks. * * **Note**: This does NOT simulate Cross-Program Invocations (CPI). Only direct * marginfi instructions are considered. Instructions operating on a different * marginfi account than `account` are ignored. * * **Integrated Protocols**: For Kamino/Drift deposits, the `assetShareValueMultiplierByBank` * is used to convert cToken amounts to actual asset quantities before computing shares. * * @param account - The marginfi account whose balances are projected * @param instructions - Instructions to simulate * @param program - Marginfi program for instruction decoding * @param banksMap - Map of bank addresses to bank data (needed for share value conversion) * @param assetShareValueMultiplierByBank - Multipliers for integrated protocols (Kamino, Drift) * @returns Object containing projected balances and lists of impacted banks * @returns projectedBalances - Balance array after instruction simulation * @returns impactedAssetsBanks - Bank addresses where asset shares changed * @returns impactedLiabilityBanks - Bank addresses where liability shares changed * * @example * ```typescript * const result = computeProjectedActiveBalancesNoCpi({ * account, * instructions: [depositIx, borrowIx], * program: marginfiProgram, * banksMap, * assetShareValueMultiplierByBank, * }); * console.log(`Projected ${result.projectedBalances.length} balances`); * console.log(`Impacted ${result.impactedAssetsBanks.length} asset banks`); * ``` */ declare function computeProjectedActiveBalancesNoCpi({ account, instructions, program, banksMap, assetShareValueMultiplierByBank, }: { account: MarginfiAccountType; instructions: TransactionInstruction[]; program: MarginfiProgram; banksMap: Map; assetShareValueMultiplierByBank: Map; }): { projectedBalances: BalanceType[]; impactedAssetsBanks: string[]; impactedLiabilityBanks: string[]; /** * Banks targeted by a withdraw instruction (partial or final). When the group * rate limiter is enabled, the program requires a fresh oracle for these banks * in the withdraw's remaining accounts — even if the position closes. */ withdrawnBanks: string[]; }; declare const fetchMarginfiAccountAddresses: (program: MarginfiProgram, authority: PublicKey, group: PublicKey) => Promise; /** * Fetches the addresses of every marginfi account in a group that holds a position in a * specific bank. Returns only addresses (uses `dataSlice` length 0 so no account data is * transferred or decoded) — important at the ~500k account scale of the group. * * @param program - The marginfi Anchor program (connection is taken from its provider) * @param group - The marginfi group public key * @param bank - The bank public key to search for in account balances * @param options - Optional settings: * - `concurrency`: max number of the 16 slot scans to run at once. Omit (or pass a value * >= 16) to fire all 16 in parallel via `Promise.all`; pass a smaller value (e.g. 4) to * batch them and avoid RPC rate limits. * @returns Deduplicated array of account addresses holding the bank */ declare const fetchMarginfiAccountAddressesHoldingBank: (program: MarginfiProgram, group: PublicKey, bank: PublicKey, options?: { concurrency?: number; }) => Promise; /** One account's active balance position in a specific bank. */ type AccountActiveBalanceForBank = { accountAddress: PublicKey; authority: PublicKey; balance: BalanceType; }; /** * Fetches every marginfi account in a group that holds `bank`, along with its authority and the * active balance (shares) it holds in that bank. * * Unlike {@link fetchMarginfiAccountAddressesHoldingBank}, this fetches full account data so it * can decode the authority and balance shares — heavier, but a single round trip (no separate * hydration). The returned `balance` holds raw asset/liability shares; convert to token amounts * with the bank's share multiplier (e.g. `Balance.computeQuantityUi(bank, multiplier)`). * * @param program - The marginfi Anchor program (connection is taken from its provider) * @param group - The marginfi group public key * @param bank - The bank public key to search for in account balances * @param options - Optional settings: * - `concurrency`: max number of the 16 slot scans to run at once (see above). * @returns One entry per account holding the bank, with authority and the matching balance */ declare const fetchMarginfiAccountActiveBalancesForBank: (program: MarginfiProgram, group: PublicKey, bank: PublicKey, options?: { concurrency?: number; }) => Promise; declare const fetchMarginfiAccountData: (program: MarginfiProgram, marginfiAccountPk: PublicKey, banksMap: Map, bankIntegrationMap?: BankIntegrationMetadataMap) => Promise<{ marginfiAccount: MarginfiAccountType; error?: HealthCacheSimulationError; }>; /** * Generates a random available account index that doesn't collide with existing accounts. * Account indices are 0-255 (u8 range). * * @param connection - Solana connection * @param programId - MarginFi program ID * @param group - MarginFi group public key * @param authority - User's wallet public key * @param thirdPartyId - Third party ID (default 0) * @returns A random available account index (0-255) */ declare function findRandomAvailableAccountIndex(connection: Connection, programId: PublicKey, group: PublicKey, authority: PublicKey, thirdPartyId?: number): Promise; /** * Configuration for computing maximum borrow amount for a bank */ interface ComputeMaxBorrowForBankParams { /** The marginfi account to compute max borrow for */ account: MarginfiAccountType; /** Map of banks by their address */ banksMap: Map; /** Map of oracle prices by bank address */ oraclePricesByBank: Map; /** The bank address to compute max borrow for */ bankAddress: PublicKey; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** E-mode impact status (determines whether to use cache or compute from balances) */ emodeImpactStatus?: EmodeImpactStatus; /** Volatility factor to apply to free collateral (default: 1) */ volatilityFactor?: number; /** Active e-mode pair for applying e-mode weights */ activePair?: ActiveEmodePair; /** * Group-level rate limiter (USD windows). When provided and enabled, the result is also clamped * to the group's remaining outflow capacity converted at the unbiased realtime price. */ groupRateLimiter?: BankRateLimiterType; /** * Skip the bank-level clamps (remaining borrow cap, available liquidity, bank/group rate * limiters) and return the purely health-based amount (default: false) */ ignoreBankLimits?: boolean; } /** * Calculates the maximum amount that can be borrowed from a bank. * * This function computes the borrowing capacity based on: * - **Free collateral**: Available collateral not backing existing liabilities * - **Isolated tier constraints**: Isolated assets cannot be borrowed with active debt * - **E-mode weights**: Enhanced weights for assets in the same e-mode category * - **Oracle prices**: Conservative pricing (lowest for assets, highest for liabilities) * - **Bank limits**: Remaining borrow cap (`borrowLimit - totalBorrows`, interest-buffered), * available liquidity (`totalDeposits - totalBorrows`), the bank's net-outflow rate limiter and * (if `groupRateLimiter` is provided) the group's USD rate limiter — unless `ignoreBankLimits` * * **Isolated Asset Rules:** * - Cannot borrow isolated assets if other liabilities exist * - Cannot borrow new assets if existing debt is in isolated tier * * **Calculation Formula:** * ``` * If assetWeight > 0: * maxBorrow = (min(fc, ucb) / (price_lowest * asset_weight)) + * ((fc - min(fc, ucb)) / (price_highest * liab_weight)) * Else: * maxBorrow = existingAssets + ((fc - ucb) / (price_highest * liab_weight)) * * maxBorrow = min(maxBorrow, remainingBorrowCap, availableLiquidity, rateLimitRemaining) * ``` * All liability-denominated terms are divided by `(1 + protocolOriginationFee)` because the * program books the origination fee as additional borrowed liability. * Where: * - `fc` = free collateral (with volatility factor) * - `ucb` = untied collateral for bank (existing deposits) * * @param params - Configuration object for max borrow computation * @returns Maximum amount that can be borrowed (in UI units) * * @example * ```typescript * const maxBorrow = computeMaxBorrowForBank({ * account, * banks: client.bankMap, * oraclePrices: client.oraclePriceByBank, * bankAddress: usdcBankPk, * volatilityFactor: 0.95, // 5% safety margin * emodeImpactStatus: EmodeImpactStatus.InactiveEmode, * }); * console.log(`Can borrow up to ${maxBorrow.toFixed(2)} USDC`); * ``` */ declare function computeMaxBorrowForBank(params: ComputeMaxBorrowForBankParams): BigNumber$1; /** * Configuration for computing maximum withdraw amount for a bank */ interface ComputeMaxWithdrawForBankParams { /** The marginfi account to compute max withdraw for */ account: MarginfiAccountType; /** Map of banks by their address */ banksMap: Map; /** Map of oracle prices by bank address */ oraclePricesByBank: Map; /** Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift) */ assetShareValueMultiplierByBank?: Map; /** The bank address to compute max withdraw for */ bankAddress: PublicKey; /** Volatility factor to apply to free collateral (default: 1) */ volatilityFactor?: number; /** Active e-mode pair for applying e-mode weights */ activePair?: ActiveEmodePair; /** * Group-level rate limiter (USD windows). When provided and enabled, the result is also clamped * to the group's remaining outflow capacity converted at the unbiased realtime price. */ groupRateLimiter?: BankRateLimiterType; /** * Venue-side account states for integrated banks (Kamino/Drift/JupLend), e.g. * `client.bankIntegrationMap[bankAddress]`. When provided, the result is also clamped to the * venue's own idle liquidity — the marginfi-level totals only describe what marginfi has * delegated, so a fully utilized venue reserve correctly reports 0 withdrawable. */ venueStates?: BankVenueStates; /** * Skip the bank-level clamps (available liquidity, venue liquidity, bank/group rate limiters) * and return the purely health-based amount (default: false) */ ignoreBankLimits?: boolean; } /** * Calculates the maximum amount that can be withdrawn from a bank. * * This function computes the withdrawal capacity based on: * - **Free collateral**: Available collateral after maintaining required margins * - **Asset weights**: Risk-adjusted value of deposits (Initial and Maintenance) * - **E-mode weights**: Enhanced weights for assets in the same e-mode category * - **Oracle prices**: Conservative pricing to ensure safe withdrawals * - **Bank limits**: Result is clamped to available liquidity (`totalDeposits - totalBorrows`), * the bank's net-outflow rate limiter, (if `groupRateLimiter` is provided) the group's USD * rate limiter and (if `venueStates` is provided) the integrated venue's idle liquidity — * unless `ignoreBankLimits` is set * * **Key Differences from Max Borrow:** * - Uses both Initial and Maintenance asset weights * - No isolated tier constraints (can always withdraw your own assets) * - Calculates based on existing deposits, not new positions * * **Safety Mechanism:** * The volatility factor (default: 1.0) can be reduced to add a safety buffer, * preventing withdrawals that would leave the account close to liquidation. * * @param params - Configuration object for max withdraw computation * @returns Maximum amount that can be withdrawn (in UI units) * * @example * ```typescript * const maxWithdraw = computeMaxWithdrawForBank({ * account, * banksMap: client.bankMap, * oraclePricesByBank: client.oraclePriceByBank, * bankAddress: usdcBankPk, * volatilityFactor: 0.98, // 2% safety margin * assetShareValueMultiplierByBank: client.assetShareValueMultiplierByBank, * }); * console.log(`Can withdraw up to ${maxWithdraw.toFixed(2)} USDC`); * ``` */ declare function computeMaxWithdrawForBank(params: ComputeMaxWithdrawForBankParams): BigNumber$1; /** * Configuration for computing maximum deposit amount for a bank */ interface ComputeMaxDepositForBankParams { /** Map of banks by their address */ banksMap: Map; /** The bank address to compute max deposit for */ bankAddress: PublicKey; /** * Asset share value multipliers by bank address (for integrated protocols like Kamino/Drift and * staked-collateral banks). The bank's `depositLimit` is denominated in its native share units; * the multiplier converts the remaining capacity to underlying UI units. */ assetShareValueMultiplierByBank?: Map; /** Wallet token balance in UI units; if provided, the result is capped to it */ walletBalance?: BigNumber$1 | number; } /** * Calculates the maximum amount that can be deposited into a bank. * * Deposits are not constrained by account health, only by the bank's deposit cap * (`depositLimit - totalDeposits`, buffered for interest accrued since the last update) * and, optionally, the caller's wallet balance. * * @param params - Configuration object for max deposit computation * @returns Maximum amount that can be deposited (in UI units) * * @example * ```typescript * const maxDeposit = computeMaxDepositForBank({ * banksMap: client.bankMap, * bankAddress: usdcBankPk, * assetShareValueMultiplierByBank: client.assetShareValueMultiplierByBank, * walletBalance: 1_000, // UI units * }); * ``` */ declare function computeMaxDepositForBank(params: ComputeMaxDepositForBankParams): BigNumber$1; declare const getJupiterReferralFeeAccount: (mint: PublicKey) => string; declare const checkJupiterFeeAccount: (connection: Connection, mint: PublicKey) => Promise<{ feeAccount: string; hasFeeAccount: boolean; }>; declare function toJupiterConfig(apiConfig?: SwapApiConfig): JupiterClientConfig | undefined; type GetJupiterSwapIxsForFlashloanParams = { quoteParams: QuoteGetRequest; authority: PublicKey; connection: Connection; destinationTokenAccount: PublicKey; apiConfig?: SwapApiConfig; maxSwapAccounts?: number; }; declare const getJupiterSwapIxsForFlashloan: ({ quoteParams, authority, connection, destinationTokenAccount, apiConfig, maxSwapAccounts, }: GetJupiterSwapIxsForFlashloanParams) => Promise; declare const checkTitanFeeAccount: (connection: Connection, mint: PublicKey) => Promise<{ feeAccount: PublicKey; hasFeeAccount: boolean; feeWallet: PublicKey; }>; type TitanQuoteParams = { inputMint: string; outputMint: string; amount: number; swapMode: "ExactIn" | "ExactOut"; slippageBps?: number; platformFeeBps?: number; directRoutesOnly?: boolean; sizeConstraint?: number; maxSwapAccounts?: number; maxSwapTotalAccounts?: number; }; type GetTitanSwapIxsParams = { quoteParams: TitanQuoteParams; authority: PublicKey; connection: Connection; destinationTokenAccount: PublicKey; apiConfig?: SwapApiConfig; }; type GetTitanExactOutEstimateParams = { inputMint: string; outputMint: string; amount: number; slippageBps?: number; apiConfig?: SwapApiConfig; }; declare const getTitanSwapIxsForFlashloan: ({ quoteParams, authority, connection, destinationTokenAccount, apiConfig, }: GetTitanSwapIxsParams) => Promise; /** * @deprecated Provider ExactOut quotes are unreliable; size target-output swaps * from a market-price calculation and route ExactIn instead. */ declare const getTitanExactOutEstimate: (params: GetTitanExactOutEstimateParams) => Promise<{ otherAmountThreshold: string; quoteResult: SwapQuoteResult; }>; /** The canonical shape a resolved pinned route yields — mirrors an engine-selected route. */ interface ResolvedPinnedSwapRoute { swapInstructions: TransactionInstruction[]; setupInstructions: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[]; quoteResponse: SwapQuoteResult; /** The route's guaranteed min-out (native) — what sizes the follow-up amount (deposit patch). */ outputAmountNative: BN; } /** * Resolve a caller-pinned swap route (`swapOpts.swapIxs`) into the engine-result shape, validating * the quote so a pinned route can never silently size a zero follow-up amount: * * - `otherAmountThreshold` (min-out) must be a positive integer — it becomes the loop's deposit * byte-patch, exactly like an engine-selected route's min-out. * - `inAmount` must equal the flow's swap input (e.g. the loop's borrow, native units) — a * mismatch means the route was quoted for a different size than the flow will actually swap. * * Throws plain `Error`s (not `TransactionBuildingError`) so caller-input mistakes are never * classified as decomposable swap failures (which would wrongly engage the bridged fallback). */ declare function resolvePinnedSwapRoute(swapIxs: NonNullable, expectedInAmountNative: BN | number): ResolvedPinnedSwapRoute; type GetSwapIxsForFlashloanParams = { inputMint: string; outputMint: string; amount: number; swapMode: "ExactIn" | "ExactOut"; authority: PublicKey; connection: Connection; destinationTokenAccount: PublicKey; swapOpts: SwapOpts; sizeConstraint?: number; maxSwapTotalAccounts?: number; }; declare const getSwapIxsForFlashloan: (params: GetSwapIxsForFlashloanParams) => Promise; type GetExactOutEstimateParams = { inputMint: string; outputMint: string; amount: number; swapOpts: SwapOpts; connection: Connection; }; type ExactOutEstimateResult = { otherAmountThreshold: string; quoteResult: SwapQuoteResult; }; /** * @deprecated Do not use provider ExactOut quotes — they are unreliable and the * Jupiter Router (`/build`) is ExactIn-only. Size a target-output swap from a * market-price calculation and route ExactIn instead (see `makeSwapDebtTx`). */ declare const getExactOutEstimate: (params: GetExactOutEstimateParams) => Promise; declare function mapJupiterQuoteToSwapQuoteResult(quote: QuoteResponse): SwapQuoteResult; declare function computeClosePositionTokenAmount(position: { amount: number; isLending: boolean; }, mintDecimals: number): number; declare function isWholePosition(position: { amount: number; isLending: boolean; }, amount: number, mintDecimals: number): boolean; /** * Synchronous flashloan TX size estimator. * * Estimates the serialized size of a V0 flashloan transaction without compiling * or serializing the message. This allows us to synchronously compute the byte * overhead of non-swap instructions and determine how much budget remains for * the swap IX (e.g. Titan). * * Thoroughly tested using R&D scripts (rnd-flashloan-size.ts) and cross-referenced * against actual serialized transaction sizes across all action types (Loop, Repay, * SwapCollateral, SwapDebt) and asset tag variants (Standard, Kamino, Drift). */ /** * Estimate the serialized size of a V0 transaction from its instructions and LUTs. * Simulates the key resolution logic of TransactionMessage.compileToV0Message * without actually compiling or serializing the message. */ declare function computeV0TxSize(ixs: TransactionInstruction[], payerKey: PublicKey, luts: AddressLookupTableAccount[]): { size: number; accountCount: number; writableAccountCount: number; }; interface FlashloanSwapConstraints { /** Available bytes for swap instruction(s) */ sizeConstraint: number; /** Available total account slots for swap instruction(s) */ maxSwapTotalAccounts: number; } /** * Compute the available byte budget and account budget for swap instructions * in a flashloan TX. Compiles a real V0 message and serializes it for an exact * non-swap byte count. * * @param ixs - The non-swap IXs (CU requests + primary + secondary). * Must NOT include BeginFL/EndFL — those are synthesized internally. */ declare function computeFlashLoanNonSwapBudget({ program, marginfiAccount, ixs, bankMap, addressLookupTableAccounts, }: { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; ixs: TransactionInstruction[]; bankMap: Map; addressLookupTableAccounts: AddressLookupTableAccount[]; }): FlashloanSwapConstraints; interface FlashloanPrecheckResult { /** Exact serialized size of the full flashloan TX */ fullTxSize: number; /** How many bytes over MAX_TX_SIZE (negative = under budget) */ overshoot: number; /** Total writable accounts in the full TX */ writableAccounts: number; /** Total accounts (static + LUT) in the full TX */ totalAccounts: number; } /** * Compile the full flashloan TX (all IXs + all LUTs) and return exact size info. * Call this AFTER receiving swap IXs but BEFORE makeFlashLoanTx to detect overflows * early with good diagnostics. * * Uses a dummy blockhash (same 32 bytes as a real one) so the size is exact. */ declare function compileFlashloanPrecheck({ allIxs, payer, luts, sizeConstraint, swapIxCount, swapLutCount, }: { allIxs: TransactionInstruction[]; payer: PublicKey; luts: AddressLookupTableAccount[]; sizeConstraint: number; swapIxCount: number; swapLutCount: number; }): FlashloanPrecheckResult; type FlashloanBudgetIx = { type: "borrow"; bank: BankType; tokenProgram: PublicKey; } | { type: "repay"; bank: BankType; tokenProgram: PublicKey; } | { type: "deposit"; bank: BankType; tokenProgram: PublicKey; } | { type: "withdraw"; bank: BankType; tokenProgram: PublicKey; }; /** * Compute flashloan swap constraints by building dummy primary + secondary IXs * and measuring the remaining TX budget. Replaces the duplicated switch/case * blocks in each action file. */ declare function computeFlashloanSwapConstraints({ program, marginfiAccount, bankMap, addressLookupTableAccounts, bankMetadataMap, primaryIx, secondaryIx, overrideInferAccounts, }: { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; bankMap: Map; addressLookupTableAccounts: AddressLookupTableAccount[]; bankMetadataMap: BankIntegrationMetadataMap; primaryIx: FlashloanBudgetIx; secondaryIx: FlashloanBudgetIx; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; }): Promise; /** * Returns true if the instruction is a marginfi deposit instruction (any integration). * Used to locate the amount-bearing deposit ix within a flashloan instruction array. */ declare function isDepositIx(ix: TransactionInstruction): boolean; /** * Rewrites the `amount` field of an already-built deposit instruction in place. * * The deferred-swap loop flow builds the deposit instruction with a market-price * estimate before the swap output is known, then patches the real swap output amount * once the swap engine has run. Because the amount is a fixed-offset little-endian u64, * this is a pure byte patch — no account/key changes — so it is safe to apply to an * instruction that is about to be (re)compiled into a flashloan transaction. * * @param ix - The deposit instruction to mutate. * @param amountNative - The new amount in native (base) units. */ declare function patchDepositAmount(ix: TransactionInstruction, amountNative: BN): void; /** * Bridge-token candidate filtering for bridged (double-hop) swaps. * * A **bridge token** is NOT a cross-chain bridge: it is the high-liquidity intermediate token * (e.g. USDC or wSOL) that a swap `A → C` is routed *through* — as `A → bridge` + `bridge → C` in * one atomic bundle — when the direct swap can't fit a single transaction or has no route. This * module owns the mechanical filtering of bridge-token candidates; ordering (product policy) and * the one-call builders live in `bridge-routing.utils.ts` and the `makeBridged*Tx` actions. */ /** * The side of the marginfi account the bridge token sits on while the bridged bundle executes: * - `deposit` — the bridge token is held as *collateral* (a collateral-swap deposits it between * the two legs: withdraw source → deposit bridge, then withdraw bridge → deposit destination). * - `borrow` — the bridge token is held as *debt* (a debt-swap or loop borrows it in the first * leg and repays it exactly in the second). */ type BridgeTokenSide = "deposit" | "borrow"; /** * Whether routing through `bridgeBankPk` as the bridge token would conflict with a position the * account already holds on that bank. marginfi forbids holding an asset and a liability on the * same bank, so the conflict is always *opposite-side*: a deposit-side bridge conflicts with an * existing liability there, a borrow-side bridge with an existing asset. Same-side positions are * fine (partial-withdraw / exact-repay handle them). */ declare function accountConflictsWithBridgeBank(marginfiAccount: MarginfiAccountType, bridgeBankPk: PublicKey, bridgeTokenSide: BridgeTokenSide): boolean; interface ResolveBridgeCandidateBanksParams { /** Candidate bridge-token mints, highest priority first (product policy — see * `bridge-routing.utils.ts` for the default ordering and the per-call override). */ prioritizedBridgeCandidateMints: PublicKey[]; /** Banks to resolve the candidate mints against — typically all banks in the marginfi group. */ groupBanks: BankType[]; /** The account the bridged legs run against (for the conflict check). */ marginfiAccount: MarginfiAccountType; /** Which side the bridge token is held on — picks the standard-bank filter and the conflict * rule. */ bridgeTokenSide: BridgeTokenSide; } /** * Resolve prioritized bridge-token candidate *mints* into candidate *banks*, partitioned into * those safe to route through and those blocked by an existing account position. * * For each mint (deduped, in priority order) it picks the standard bank that fits the side * ({@link isStandardBorrowable} for `borrow`, {@link isStandardDepositable} for `deposit`) — this * skips integration wrappers (`6200`) and `ReduceOnly` banks (`6017`) — then splits by * {@link accountConflictsWithBridgeBank}. The caller supplies the prioritized mint list (product * policy); this owns only the mechanical filtering. * * @returns `usableBridgeBanks` (safe to route through, in priority order) and * `conflictingBridgeBanks` (resolvable but blocked by an opposite-side position — useful for * surfacing a "close that position" message). */ declare function resolveBridgeCandidateBanks(params: ResolveBridgeCandidateBanksParams): { usableBridgeBanks: BankType[]; conflictingBridgeBanks: BankType[]; }; /** * Shared support for the bridged (double-hop) one-call builders. * * A **bridge token** is NOT a cross-chain bridge: it is the high-liquidity intermediate token * (e.g. USDC or wSOL) a swap is routed *through*. When a direct collateral-swap / debt-swap / * loop `A → C` can't be built — the swap doesn't fit one tx (size / account-locks) or has no * route — it can still succeed decomposed into `A → bridge` + `bridge → C`, submitted as ONE * atomic Jito bundle. The per-flow builders live next to their direct builders * (`makeBridgedLoopTx` in `../actions/loop.ts`, `makeBridgedSwapCollateralTx` in * `../actions/swap-collateral.ts`, `makeBridgedSwapDebtTx` in `../actions/swap-debt.ts`); this * module owns the flow-agnostic routing support: candidate ordering/selection, the * candidate-iteration loop (abort / skip-on-failure / conflict surfacing), token-program * resolution, and the shared leg context. * * Candidate *ordering* is product policy: it defaults to {@link DEFAULT_BRIDGE_MINTS} and can be * overridden per call via {@link BridgeOpts.bridgeCandidateMints} (e.g. a correlation-aware * ordering). Candidate *filtering* (standard-bank resolution, opposite-side conflicts) is * mechanical and lives in {@link resolveBridgeCandidateBanks}. */ /** Default bridge-token candidates, most-liquid first. */ declare const DEFAULT_BRIDGE_MINTS: PublicKey[]; /** Per-call knobs for the bridged fallback of the `makeBridged*Tx` builders. */ interface BridgeOpts { /** * Candidate bridge-token mints, highest priority first. Defaults to * {@link DEFAULT_BRIDGE_MINTS} (USDC, wSOL, USDT). Source/destination mints are always skipped. */ bridgeCandidateMints?: PublicKey[]; /** Known token programs by mint (base58) — skips the per-mint RPC owner lookup. */ tokenProgramByMint?: Map; /** Override the bundle-size ceiling (see `composeBridgedSwap`). */ maxBundleTxs?: number; abortSignal?: AbortSignal; } /** Result of a `makeBridged*Tx` builder — the direct build's result, or the bridged bundle. */ interface BridgedTxResult { transactions: SolanaTransaction[]; /** Index of the tx that completes the action (the direct action tx, or the bundle's last leg). */ actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** The bridge token's mint — set only when the bridged double-hop path was used. */ bridgeMint?: PublicKey; /** true → send as ONE atomic Jito bundle (bridged legs are one operation / integration * refreshes go stale within a slot); false → sequential sends are safe (cranked oracles * allow ≥ ~1 min staleness). */ mustBeAtomicBundle: boolean; } /** A mint's token program: the cache (seedable by the caller), else the mint account's owner. */ declare function resolveTokenProgramForMint(mint: PublicKey, connection: Connection, tokenProgramCacheByMint: Map): Promise; /** * Bridge-token candidate banks for routing `source → bridge → destination`, in priority order, * partitioned into usable and conflict-blocked. Source/destination mints are excluded from the * candidates (a token can't bridge itself). */ declare function selectSwapBridges(args: { sourceMint: PublicKey; destinationMint: PublicKey; bankMap: Map; marginfiAccount: MarginfiAccountType; bridgeTokenSide: BridgeTokenSide; bridgeCandidateMints?: PublicKey[]; }): { usableBridgeBanks: BankType[]; conflictingBridgeBanks: BankType[]; }; /** * Try each usable bridge-token candidate in priority order until one composes a bundle. A * `buildBundleThroughBridge` that returns null or throws (build failure) moves on to the next * candidate; abort errors always propagate. When NO candidate is usable but some were dropped * solely for an existing opposite-side position, throws * `TransactionBuildingError.bridgeConflict` (the caller-facing "close that position" signal); * otherwise resolves null and the caller rethrows the direct build's error. */ declare function tryBridgeCandidates(args: { usableBridgeBanks: BankType[]; conflictingBridgeBanks: BankType[]; bridgeTokenSide: BridgeTokenSide; abortSignal?: AbortSignal; /** Build the two-leg bundle through one candidate bank; null = didn't work, try the next. */ buildBundleThroughBridge: (bridgeBank: BankType) => Promise; }): Promise; /** The flow context shared verbatim by both legs of every bridged build. */ type SharedBridgeLegContext = Pick; declare function sharedBridgeLegContext(params: SharedBridgeLegContext): SharedBridgeLegContext; /** * Creates an instruction to close a Marginfi account. * * Generates the instruction needed to close an existing Marginfi account and reclaim rent. * The account must have no active balances before it can be closed. * * @param params - Configuration object * @param params.program - The Marginfi program instance * @param params.marginfiAccount - The Marginfi account to close * @param params.authority - The authority/owner of the account * @returns Instruction to close the account */ declare function makeCloseMarginfiAccountIx({ program, marginfiAccount, authority, }: MakeCloseAccountIxParams): Promise; /** * Creates a transaction to close a Marginfi account. * * Generates a complete transaction to close an existing Marginfi account and reclaim rent. * The account must have no active balances before it can be closed. * * @param params - Configuration object * @param params.connection - Solana connection instance * @param params.program - The Marginfi program instance * @param params.marginfiAccount - The Marginfi account to close * @param params.authority - The authority/owner of the account * @returns Versioned transaction to close the account */ declare function makeCloseMarginfiAccountTx({ connection, program, marginfiAccount, authority, }: MakeCloseAccountTxParams): Promise; /** * Creates a transaction to transfer a Marginfi account to a new authority. * * Migrates the account's positions into a brand-new account (`newMarginfiAccount`) * owned by `newAuthority`; the old account is left disabled. The new-account * keypair signs to create itself, the current authority (the program's provider * wallet) signs to authorize, and `feePayer` pays. `globalFeeWallet` is resolved * from the program's fee state — matching the marginfi implementation. * * @param params - Configuration object * @param params.connection - Solana connection instance * @param params.program - The Marginfi program instance * @param params.marginfiAccount - The account being transferred * @param params.newMarginfiAccount - Freshly generated keypair for the destination account * @param params.newAuthority - The wallet that will own the new account * @param params.feePayer - Optional. Pays rent/fees. A `PublicKey` signs via the * wallet adapter; a `Keypair` is a separate fee payer that signs directly. * Defaults to the account's current authority. * @returns Versioned transaction to transfer the account */ declare function makeAccountTransferToNewAccountTx({ connection, program, marginfiAccount, newMarginfiAccount, newAuthority, feePayer, }: MakeAccountTransferToNewAccountTxParams): Promise; /** * Creates a new Marginfi account transaction with a projected account instance. * * Generates a transaction to create a new Marginfi account and returns a projected account instance * that can be used for operations before the account actually exists on-chain. * * @param props - Configuration object * @param props.program - The Marginfi program instance * @param props.authority - The authority public key for the new account * @param props.group - The Marginfi group public key * @param props.addressLookupTables - Address lookup tables for the transaction * @returns Object containing the projected account and creation transaction */ declare function makeCreateAccountTxWithProjection(props: { program: MarginfiProgram; authority: PublicKey; group: PublicKey; addressLookupTables: AddressLookupTableAccount[]; accountIndex: number; thirdPartyId?: number; }): Promise<{ account: MarginfiAccountType; tx: SolanaTransaction; }>; /** * Creates a new Marginfi account instruction with a projected account instance. * * Generates an instruction to create a new Marginfi account and returns a projected account instance * that can be used for operations before the account actually exists on-chain. * * @param props - Configuration object * @param props.program - The Marginfi program instance * @param props.authority - The authority public key for the new account * @param props.group - The Marginfi group public key * @returns Object containing the projected account and creation instruction */ declare function makeCreateAccountIxWithProjection(props: { program: MarginfiProgram; authority: PublicKey; group: PublicKey; accountIndex: number; thirdPartyId?: number; }): Promise<{ account: MarginfiAccountType; ix: TransactionInstruction; }>; declare function makeCreateMarginfiAccountTx(program: MarginfiProgram, authority: PublicKey, groupAddress: PublicKey, addressLookupTables: AddressLookupTableAccount[], accountIndex: number, thirdPartyId?: number): Promise; declare function makeCreateMarginfiAccountIx(program: MarginfiProgram, authority: PublicKey, groupAddress: PublicKey, accountIndex: number, thirdPartyId?: number): Promise; declare function makeSetupIx({ connection, authority, tokens }: MakeSetupIxParams): Promise; declare function makePulseHealthIx(program: MarginfiProgram, marginfiAccount: MarginfiAccountType, banks: Map, mandatoryBanks: PublicKey[], excludedBanks: PublicKey[]): Promise<{ instructions: TransactionInstruction[]; keys: never[]; }>; declare function generateDummyAccount(group: PublicKey, authority: PublicKey, accountKey: PublicKey): MarginfiAccountType; declare function makeDriftWithdrawIx({ program, bank, bankMap, tokenProgram, amount, marginfiAccount, driftSpotMarket, userRewards, authority, withdrawAll, isSync, opts, }: MakeDriftWithdrawIxParams): Promise; declare function makeDriftWithdrawTx(params: MakeDriftWithdrawTxParams): Promise; declare function makeKaminoWithdrawIx({ program, bank, bankMap, tokenProgram, cTokenAmount, marginfiAccount, reserve, authority, withdrawAll, isSync, opts, }: MakeKaminoWithdrawIxParams): Promise; declare function makeWithdrawIx({ program, bank, bankMap, tokenProgram, amount, marginfiAccount, authority, withdrawAll, isSync, opts, }: MakeWithdrawIxParams): Promise; declare function makeWithdrawTx(params: MakeWithdrawTxParams): Promise; declare function makeKaminoWithdrawTx(params: MakeKaminoWithdrawTxParams): Promise; /** * Creates a JupLend withdraw instruction for withdrawing assets from a JupLend lending pool. * * This function handles: * - Creating the destination ATA if needed (idempotent) * - Computing health check accounts for the withdrawal * - Deriving JupLend protocol accounts via `getAllDerivedJupLendAccounts` (fTokenMint, rateModel, vault, liquidity, lendingAdmin) * - Using on-chain `jupLendingState` values for supplyTokenReservesLiquidity, lendingSupplyPositionOnLiquidity, and rewardsRateModel * - Unwrapping wSOL back to native SOL if needed * * @param params - The parameters for creating the withdraw instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to withdraw from (must have JupLend integration configured) * @param params.bankMap - Map of all banks for health check computation * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to withdraw in UI units * @param params.marginfiAccount - The Marginfi account to withdraw from * @param params.authority - The authority/signer public key * @param params.jupLendingState - The on-chain JupLend lending state (provides token reserve and rewards accounts) * @param params.withdrawAll - Whether to withdraw the full balance (default: false) * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to unwrap wSOL to native SOL (default: true) * @param params.opts.createAtas - Whether to create the destination ATA if missing (default: true) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * @param params.opts.observationBanksOverride - Optional override for health check remaining accounts * * @returns Promise resolving to InstructionsWrapper containing the withdraw instructions */ declare function makeJuplendWithdrawIx({ program, bank, bankMap, tokenProgram, amount, marginfiAccount, jupLendingState, authority, withdrawAll, opts, }: MakeJuplendWithdrawIxParams): Promise; declare function makeJuplendWithdrawTx(params: MakeJuplendWithdrawTxParams): Promise; declare function makeBorrowIx({ program, bank, bankMap, tokenProgram, amount, marginfiAccount, authority, isSync, opts, }: MakeBorrowIxParams): Promise; declare function makeBorrowTx(params: MakeBorrowTxParams): Promise; /** * Creates a Drift deposit instruction for depositing assets into a Drift spot market. * * This function handles: * - Wrapping SOL to wSOL if needed (for native SOL deposits) * - Deriving necessary Drift protocol accounts (state, spot market vault) * - Creating the deposit instruction to the Drift spot market * * @param params - The parameters for creating the deposit instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into (must have Drift integration configured) * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to deposit in UI units * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.driftMarketIndex - The Drift spot market index for the asset * @param params.driftOracle - The Drift oracle account for the asset (optional for USDC/market 0) * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to wrap SOL to wSOL (default: true) * @param params.opts.wSolBalanceUi - Existing wSOL balance to combine with native SOL (default: 0) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * * @returns Promise resolving to InstructionsWrapper containing the deposit instructions */ declare function makeDriftDepositIx({ program, bank, tokenProgram, amount, accountAddress, authority, group, driftMarketIndex, driftOracle, isSync, opts, }: MakeDriftDepositIxParams): Promise; /** * Creates a complete Drift deposit transaction ready to be signed and sent. * * This function builds a full versioned transaction that includes: * - SOL wrapping instructions if depositing native SOL * - The actual deposit instruction to the Drift spot market * * The transaction is constructed with proper metadata, address lookup tables, * and is ready to be signed by the authority and submitted to the network. * * @param params - The parameters for creating the deposit transaction * @param params.luts - Address lookup tables for transaction compression * @param params.connection - Solana connection for fetching blockhash * @param params.amount - The amount to deposit in UI units * @param params.blockhash - Optional recent blockhash (fetched if not provided) * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into (must have driftUser and driftUserStats configured) * @param params.tokenProgram - The token program ID * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.driftMarketIndex - The Drift spot market index for the asset * @param params.driftOracle - The Drift oracle account for the asset * @param params.opts - Optional configuration (wrapping, overrides, etc.) * * @returns Promise resolving to a versioned transaction with metadata * @throws Error if the bank doesn't have Drift user or user stats configured */ declare function makeDriftDepositTx(params: MakeDriftDepositTxParams): Promise; /** * Creates a Kamino deposit instruction for depositing assets into a Kamino reserve. * * This function handles: * - Wrapping SOL to wSOL if needed (for native SOL deposits) * - Deriving all necessary Kamino protocol accounts * - Creating the deposit instruction with proper farm state integration * * @param params - The parameters for creating the deposit instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to deposit in UI units * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.reserve - The Kamino reserve configuration * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to wrap SOL to wSOL (default: true) * @param params.opts.wSolBalanceUi - Existing wSOL balance to combine with native SOL (default: 0) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * * @returns Promise resolving to InstructionsWrapper containing the deposit instructions */ declare function makeKaminoDepositIx({ program, bank, tokenProgram, amount, accountAddress, authority, group, reserve, isSync, opts, }: MakeKaminoDepositIxParams): Promise; /** * Creates a complete Kamino deposit transaction ready to be signed and sent. * * This function builds a full versioned transaction that includes: * - Kamino reserve refresh instructions (to update oracle prices and interest rates) * - SOL wrapping instructions if depositing native SOL * - The actual deposit instruction * * The transaction is constructed with proper metadata, address lookup tables, * and is ready to be signed by the authority and submitted to the network. * * @param params - The parameters for creating the deposit transaction * @param params.luts - Address lookup tables for transaction compression * @param params.connection - Solana connection for fetching blockhash and reserve data * @param params.amount - The amount to deposit in UI units * @param params.blockhash - Optional recent blockhash (fetched if not provided) * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into (must have kaminoReserve and kaminoObligation) * @param params.tokenProgram - The token program ID * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.reserve - The Kamino reserve configuration * @param params.opts - Optional configuration (wrapping, overrides, etc.) * * @returns Promise resolving to a versioned transaction with metadata * @throws Error if the bank doesn't have a Kamino reserve or obligation configured */ declare function makeKaminoDepositTx(params: MakeKaminoDepositTxParams): Promise; /** * Creates a deposit instruction for depositing assets into a Marginfi bank. * * This function handles: * - Wrapping SOL to wSOL if depositing native SOL * - Token-2022 program support with proper remaining accounts * - Creating the deposit instruction to the bank's liquidity vault * * @param params - The parameters for creating the deposit instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to deposit in UI units * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to wrap SOL to wSOL (default: true) * @param params.opts.wSolBalanceUi - Existing wSOL balance to combine with native SOL (default: 0) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * * @returns Promise resolving to InstructionsWrapper containing the deposit instructions */ declare function makeDepositIx({ program, bank, tokenProgram, amount, accountAddress, authority, group, isSync, opts, }: MakeDepositIxParams): Promise; /** * Creates a complete deposit transaction ready to be signed and sent. * * This function builds a full transaction that includes: * - SOL wrapping instructions if depositing native SOL * - The actual deposit instruction to the Marginfi bank * - Proper support for Token-2022 tokens * * The transaction is constructed as a legacy Transaction with proper metadata * and is ready to be signed by the authority and submitted to the network. * * @param params - The parameters for creating the deposit transaction * @param params.luts - Address lookup tables for transaction compression * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to deposit in UI units * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.opts - Optional configuration (wrapping, overrides, etc.) * * @returns Promise resolving to an ExtendedTransaction with metadata */ declare function makeDepositTx(params: MakeDepositTxParams): Promise; /** * Creates a JupLend deposit instruction for depositing assets into a JupLend lending pool. * * This function handles: * - Wrapping SOL to wSOL if needed (for native SOL deposits) * - Deriving all necessary JupLend protocol accounts via `getAllDerivedJupLendAccounts` * - Creating the deposit instruction to the JupLend lending pool * * @param params - The parameters for creating the deposit instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into (must have JupLend integration configured) * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to deposit in UI units * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to wrap SOL to wSOL (default: true) * @param params.opts.wSolBalanceUi - Existing wSOL balance to combine with native SOL (default: 0) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * * @returns Promise resolving to InstructionsWrapper containing the deposit instructions */ declare function makeJuplendDepositIx({ program, bank, tokenProgram, amount, accountAddress, authority, group, opts, }: MakeJuplendDepositIxParams): Promise; /** * Creates a complete JupLend deposit transaction ready to be signed and sent. * * This function builds a full versioned transaction that includes: * - SOL wrapping instructions if depositing native SOL * - The actual deposit instruction to the JupLend lending pool * * The transaction is constructed with proper metadata, address lookup tables, * and is ready to be signed by the authority and submitted to the network. * * @param params - The parameters for creating the deposit transaction * @param params.luts - Address lookup tables for transaction compression * @param params.connection - Solana connection for fetching blockhash * @param params.amount - The amount to deposit in UI units * @param params.blockhash - Optional recent blockhash (fetched if not provided) * @param params.program - The Marginfi program instance * @param params.bank - The bank to deposit into (must have JupLend integration configured) * @param params.tokenProgram - The token program ID * @param params.accountAddress - The Marginfi account address * @param params.authority - The authority/signer public key * @param params.group - The Marginfi group address * @param params.opts - Optional configuration (wrapping, overrides, etc.) * * @returns Promise resolving to a versioned transaction with metadata * @throws Error if the bank doesn't have JupLend integration accounts configured */ declare function makeJuplendDepositTx(params: MakeJuplendDepositTxParams): Promise; declare function makeLoopTx(params: MakeLoopTxParams): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (integration refreshes go stale within a slot); * false → sequential sends are safe (cranked oracles allow ≥ ~1 min staleness). */ mustBeAtomicBundle: boolean; }>; interface MakeBridgedLoopTxParams extends MakeLoopTxParams { bridgeOpts?: BridgeOpts; } /** * {@link makeLoopTx} with a transparent bridged fallback: if the direct loop's borrow→deposit swap * can't fit one tx or has no route, loop P borrowing a value-equivalent amount of a bridge token, * then debt-swap the bridge debt → X, as one atomic bundle. * * Intended for existing accounts — a fresh account's loop has a minimal footprint and fits the * direct path, so callers creating the account in the same flow should call {@link makeLoopTx} * directly. */ declare function makeBridgedLoopTx(params: MakeBridgedLoopTxParams): Promise; /** * Creates a repay instruction for repaying borrowed assets to a Marginfi bank. * * This function handles: * - Wrapping SOL to wSOL if repaying native SOL * - Token-2022 program support with proper remaining accounts * - Full or partial repayment of liabilities * - Creating the repay instruction to return assets to the bank's liquidity vault * * @param params - The parameters for creating the repay instruction * @param params.program - The Marginfi program instance * @param params.bank - The bank to repay to * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to repay in UI units * @param params.authority - The authority/signer public key * @param params.accountAddress - The Marginfi account address * @param params.repayAll - Whether to repay the entire liability (default: false) * @param params.opts - Optional configuration * @param params.opts.wrapAndUnwrapSol - Whether to wrap SOL to wSOL (default: true) * @param params.opts.wSolBalanceUi - Existing wSOL balance to combine with native SOL (default: 0) * @param params.opts.overrideInferAccounts - Optional account overrides for testing/special cases * * @returns Promise resolving to InstructionsWrapper containing the repay instructions */ declare function makeRepayIx({ program, bank, tokenProgram, amount, authority, accountAddress, repayAll, isSync, opts, }: MakeRepayIxParams): Promise<{ instructions: TransactionInstruction[]; keys: never[]; }>; /** * Creates a complete repay transaction ready to be signed and sent. * * This function builds a full transaction that includes: * - SOL wrapping instructions if repaying native SOL * - The actual repay instruction to return assets to the Marginfi bank * - Proper support for Token-2022 tokens * - Support for full or partial repayment * * The transaction is constructed as a legacy Transaction with proper metadata * and is ready to be signed by the authority and submitted to the network. * * @param params - The parameters for creating the repay transaction * @param params.luts - Address lookup tables for transaction compression * @param params.program - The Marginfi program instance * @param params.bank - The bank to repay to * @param params.tokenProgram - The token program ID (TOKEN_PROGRAM or TOKEN_2022_PROGRAM) * @param params.amount - The amount to repay in UI units * @param params.authority - The authority/signer public key * @param params.accountAddress - The Marginfi account address * @param params.repayAll - Whether to repay the entire liability (default: false) * @param params.opts - Optional configuration (wrapping, overrides, etc.) * * @returns Promise resolving to an ExtendedTransaction with metadata */ declare function makeRepayTx(params: MakeRepayTxParams): Promise; declare function makeRepayWithCollatTx(params: MakeRepayWithCollatTxParams): Promise<{ transactions: ExtendedV0Transaction[]; swapQuote: SwapQuoteResult | undefined; amountToRepay: number; mustBeAtomicBundle: boolean; }>; declare function makeBeginFlashLoanIx(program: MarginfiProgram, marginfiAccountPk: PublicKey, endIndex: number, authority?: PublicKey, isSync?: boolean): Promise; declare function makeEndFlashLoanIx(program: MarginfiProgram, marginfiAccountPk: PublicKey, group: PublicKey, projectedActiveBanks: BankType[], authority?: PublicKey, isSync?: boolean): Promise; declare function makeFlashLoanTx({ program, marginfiAccount, ixs, bankMap, blockhash, addressLookupTableAccounts, signers, isSync, }: MakeFlashLoanTxParams): Promise; /** * Creates transactions to swap one collateral position to another using a flash loan. * * This allows users to change their collateral type (e.g., JitoSOL -> mSOL) without * withdrawing and affecting their health during the swap. * * @example * const { transactions, actionTxIndex, quoteResponse } = await makeSwapCollateralTx({ * program, * marginfiAccount, * connection, * bankMap, * oraclePrices, * withdrawOpts: { totalPositionAmount: 10, withdrawBank: jitoSolBank, tokenProgram }, * depositOpts: { depositBank: mSolBank, tokenProgram }, * swapOpts: { swapConfig: { provider: SwapProvider.JUPITER, slippageMode: "DYNAMIC", slippageBps: 50, platformFeeBps: 0 } }, * // ... * }); */ declare function makeSwapCollateralTx(params: MakeSwapCollateralTxParams): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (integration refreshes go stale within a slot); * false → sequential sends are safe (cranked oracles allow ≥ ~1 min staleness). */ mustBeAtomicBundle: boolean; }>; interface MakeBridgedSwapCollateralTxParams extends MakeSwapCollateralTxParams { bridgeOpts?: BridgeOpts; } /** * {@link makeSwapCollateralTx} with a transparent bridged fallback: if the direct swap `A → C` * can't fit one tx or has no route, decompose it into `A → bridge` + `bridge → C` through a * high-liquidity bridge collateral, composed into one atomic bundle. */ declare function makeBridgedSwapCollateralTx(params: MakeBridgedSwapCollateralTxParams): Promise; /** * Creates transactions to swap one debt position to another using a flash loan. * * This allows users to change their debt type (e.g., USDC debt -> SOL debt) without * repaying and affecting their health during the swap. * * @example * const { transactions, actionTxIndex, quoteResponse } = await makeSwapDebtTx({ * program, * marginfiAccount, * connection, * bankMap, * oraclePrices, * repayOpts: { totalPositionAmount: 100, repayBank: usdcBank, tokenProgram }, * borrowOpts: { borrowBank: solBank, tokenProgram }, * swapOpts: { swapConfig: { provider: SwapProvider.JUPITER, slippageMode: "DYNAMIC", slippageBps: 50, platformFeeBps: 0 } }, * // ... * }); */ declare function makeSwapDebtTx(params: MakeSwapDebtTxParams): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (integration refreshes go stale within a slot); * false → sequential sends are safe (cranked oracles allow ≥ ~1 min staleness). */ mustBeAtomicBundle: boolean; }>; interface MakeBridgedSwapDebtTxParams extends MakeSwapDebtTxParams { bridgeOpts?: BridgeOpts; } /** * {@link makeSwapDebtTx} with a transparent bridged fallback: if the direct debt swap `A → C` * (repay A by borrowing C) can't fit one tx or has no route, decompose it into `A → bridge` + * `bridge → C` through a borrowable bridge debt, as one atomic bundle. The first leg repays A by * borrowing the bridge; the second leg repays exactly the bridge the first leg borrowed and * borrows C. */ declare function makeBridgedSwapDebtTx(params: MakeBridgedSwapDebtTxParams): Promise; /** * Roll a matured Exponent PT collateral position into its next-maturity PT, so the **full * deposit ends up as new PT** (no leftover), in one flash-loan-wrapped bundle: * * withdraw PT_old → Exponent `merge` (PT_old → SY) → CLMM `trade_pt` (SY → PT_new) * → deposit PT_new * * The matured PT is redeemed 1:1 to its SY, then the successor PT is bought **directly on its * CLMM (`MarketThree`) PT/SY pool** — no base-token round-trip and no external aggregator. The * newer maturities (e.g. October bulkSOL) only list a CLMM pool (no `MarketTwo`, no order * book), and the CLMM uses a single `ticks` account, so the swap is a fixed, compact account * set regardless of trade size. The caller passes the matured Exponent market/vault + the * successor CLMM pool (`rollOpts`); everything Exponent is resolved internally. The buy is * bounded by the pool's depth. */ declare function makeRollPtTx(params: MakeRollPtTxParams): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; }>; /** A single built swap leg (its txs + the swap-engine quote). */ interface BridgedSwapLeg { transactions: SolanaTransaction[]; quoteResponse: SwapQuoteResult | undefined; } interface ComposeBridgedSwapParams { /** The already-built first leg (A → bridge). */ firstLeg: BridgedSwapLeg; /** * Build the second leg (bridge → C) against the first leg's projected post-state. The caller sizes it * from the first leg's guaranteed output/borrow (so it can't fail from first-leg slippage) and passes * the supplied `projectedAccount` as the leg's marginfi account. */ buildSecondLeg: (projectedAccount: MarginfiAccountType) => Promise; marginfiAccount: MarginfiAccountType; program: MarginfiProgram; banksMap: Map; /** Per-bank cToken multiplier (1 for vanilla SPL banks) — for the first leg's effect projection. */ assetShareValueMultiplierByBank: Map; feePayer: PublicKey; /** Override the bundle-size ceiling (default {@link MAX_BRIDGED_BUNDLE_TXS}). */ maxBundleTxs?: number; } interface ComposeBridgedSwapResult { /** The atomic bundle: `[mergedSetup?, firstLegCrank?, firstLegFL, secondLegCrank?, secondLegFL]`. */ transactions: SolanaTransaction[]; /** * The two legs' raw quotes. Presentation (the user-facing merged quote and destination amount) is * flow-specific — collateral maps `firstLeg.in → secondLeg.out`, debt maps `firstLeg.out → secondLeg.in`, etc. — so the * caller builds it (see {@link mergeBridgeQuotes} for the collateral/loop-deposit shape). */ firstLegQuote: SwapQuoteResult; secondLegQuote: SwapQuoteResult; } /** * Merge two leg quotes for the "in = first-leg input, out = second-leg output" shape * (collateral-swap, loop-deposit): A in → C out, with compounded slippage and price-impact. */ declare function mergeBridgeQuotes(firstLeg: SwapQuoteResult, secondLeg: SwapQuoteResult): SwapQuoteResult; /** * Merge two leg quotes for a bridged DEBT swap (repay A → borrow bridge, then repay bridge → borrow * C). The user-facing quote maps old-debt-repaid (first leg's *output*) → new-debt-borrowed (second * leg's *input*). */ declare function mergeBridgeQuotesDebt(firstLeg: SwapQuoteResult, secondLeg: SwapQuoteResult): SwapQuoteResult; /** * Merge two leg quotes for a bridged LOOP (loop-deposit borrowing the bridge, then debt-swap bridge * → X). The user-facing quote maps new-debt-borrowed (second leg's *input*) → collateral-deposited * (first leg's *output*). */ declare function mergeBridgeQuotesLoop(firstLeg: SwapQuoteResult, secondLeg: SwapQuoteResult): SwapQuoteResult; /** * Compose an already-built first leg and a caller-built second leg into one atomic bridged-swap * bundle. Owns the flow-agnostic mechanics — first-leg-effect projection, separate-crank composition, and * quote merging (see module doc for the invariants). Returns null if the second leg can't be quoted or the * bundle doesn't fit; the caller treats that as "this bridge candidate didn't work, try the next". */ declare function composeBridgedSwap(params: ComposeBridgedSwapParams): Promise; interface ClassifiedPosition { bankAddress: PublicKey; side: TransferPositionSide; /** UI amount of the position (collateral: withdrawn from A / deposited to B; debt: repaid on A). */ uiAmount: BigNumber; bank: BankType; tokenProgram: PublicKey; } /** * Validate the selection, infer each position's side, and resolve its UI amount. Correctness of the * transfer itself (both accounts staying healthy) is enforced on-chain by the flashloan's end health * check on A and each borrow's health check on B — so no client-side health/USD math is needed. */ declare function classifyAndValidate(params: MakeTransferPositionsTxParams): ClassifiedPosition[]; interface BuildContext { program: MarginfiProgram; accountA: MarginfiAccountType; accountB: MarginfiAccountType; bankMap: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; borrowPaddingBps: number; groupRateLimiterEnabled: boolean; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; /** Banks the destination account already holds before the transfer starts. */ destPreexistingBanks: BankType[]; } /** * Build one collateral position's withdraw-from-A + deposit-into-B instructions, dispatching to the * right builder for the bank's asset tag. This is the single place that defines which banks the * action supports: `DEFAULT`/`SOL`/`STAKED` use the standard withdraw/deposit; `KAMINO`/`JUPLEND` * use their dedicated builders (which lock the integration's reserve/vault accounts and, for Kamino, * convert the underlying UI amount to cToken units); anything else throws * `TRANSFER_POSITIONS_UNSUPPORTED_BANK`. The reserve/rate state each integration builder needs is * read from `bankMetadataMap`; the on-chain refresh those reads depend on is emitted separately in * `buildIntegrationRefreshIxs`. * * `observationBanksOverride` controls the withdraw leg's health pack (empty while A is flashloaned * with the group limiter off; the withdrawn bank's oracle when it is on). The deposit leg runs no * health check, so it needs none. */ declare function buildCollateralLegIxs(ctx: BuildContext, position: ClassifiedPosition, isSync: boolean, observationBanksOverride: ReturnType): Promise<{ withdrawIxs: TransactionInstruction[]; depositIxs: TransactionInstruction[]; }>; /** * Atomically move a selected set of positions from account A to account B in a single flashloan. * Per position: collateral → `withdraw(A)` + `deposit(B)`; debt → `borrow(B)` + `repay(A)`. Returns * unsigned transactions ordered for sequential execution (setup/refresh + crank first, then the * flashloan); the caller signs and sends them. * * The whole transfer must fit one v0 transaction — the selection is capped at `maxPositions` * (default 5), and the built flashloan is size-checked, throwing `TRANSFER_POSITIONS_UNSPLITTABLE` * if it still overflows (possible with several integration positions). Transfer larger sets in * batches. Correctness (both accounts staying healthy) is enforced on-chain: `endFL(A)` checks A's * remainder and each `borrow(B)` checks B — no client-side health prediction. * * Supported asset tags: `DEFAULT`/`SOL`/`STAKED` on either leg, and the collateral-only integrations * `KAMINO`/`JUPLEND` on the collateral leg (dedicated builders + a preceding reserve/rate refresh). * `DRIFT`/`SOLEND` are rejected. * * Runtime notes: * - Each borrow-before-repay transiently spikes the debt bank's rate-limit window; a bank near its * cap can revert with `BankHourly/DailyRateLimitExceeded`. The whole flashloan reverts atomically, * so this is safe and retryable — treat it as such. * - Integration (Kamino/JupLend) reserve/rate refresh rides in the prelude transaction and requires * `bankMetadataMap` to carry fresh `kaminoStates`/`jupLendStates`. * - All transactions share one blockhash; execute them in order within its validity window. When * `mustBeAtomicBundle` is true, they must also land atomically in one bundle. * - Dust (borrow padding minus accrued interest; withdraw-all/cToken-conversion excess) remains in * the wallet ATAs. */ declare function makeTransferPositionsTx(params: MakeTransferPositionsTxParams): Promise; /** * Withdraw the FULL position of every given bank, packing as many withdraws * per transaction as fit the size/lock limits. Venue dispatch (Kamino / * JupLend / Drift / standard) and the per-instruction health packs live here: * each withdraw's remaining accounts exclude every bank already closed by the * withdraws before it — across the whole ordered batch — because the on-chain * health check runs against the account's live (shrinking) balance set. * * The returned transactions MUST land as one atomic Jito bundle (same slot, * sequential): the integration refreshes (Kamino reserves + obligations, rate * cranks) live in a single prelude tx rather than in each withdraw tx, and * Klend's slot-based staleness checks only stay satisfied when the withdraws * execute in the refresh's slot. * * Returns `[ATA setup txs…, crank tx?, refresh tx?, withdraw txs…]`; * `actionTxIndex` points at the first withdraw tx. */ declare function makeBulkWithdrawTx(params: MakeBulkWithdrawTxParams): Promise; /** * Repay the FULL debt of every given bank from the wallet, packing as many * repays per transaction as fit. Repays carry no health pack and need no * oracle cranks, so most batches are a single transaction. */ declare function makeBulkRepayTx(params: MakeBulkRepayTxParams): Promise; type MakeSmartCrankSwbFeedIxParams = { marginfiAccount: MarginfiAccountType; bankMap: Map; oraclePrices: Map; assetShareValueMultiplierByBank: Map; instructions: TransactionInstruction[]; program: MarginfiProgram; connection: Connection; crossbarUrl?: string; /** * Pass `isGroupRateLimiterEnabled(group.rateLimiter)`. While the group rate limiter * is enabled, withdrawn banks' switchboard oracles are always cranked (the program * requires a fresh price for every withdraw, even withdraw-all). */ groupRateLimiterEnabled?: boolean; }; declare function makeSmartCrankSwbFeedIx(params: MakeSmartCrankSwbFeedIxParams): Promise<{ instructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; }>; type MakeSmartCrankSwbFeedIxForAccountsParams = Omit & { /** * Accounts targeted by instructions in the set. Each account is projected against * the instructions that operate on it (the projection filters by account), so the * same full instruction list serves every account. The first account's authority * pays the feed updates. */ marginfiAccounts: MarginfiAccountType[]; }; /** * Multi-account variant of {@link makeSmartCrankSwbFeedIx} for instruction sets that * span several marginfi accounts (e.g. transferring positions: the source is cranked * against its withdraws, the destination against its projected post-transfer * deposits). Overlapping feeds across accounts are cranked once. */ declare function makeSmartCrankSwbFeedIxForAccounts(params: MakeSmartCrankSwbFeedIxForAccountsParams): Promise<{ instructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; }>; declare const DEFAULT_CROSSBAR_URL = "https://crossbar.0.xyz"; declare const DEFAULT_FALLBACK_CROSSBAR_URL = "https://crossbar.switchboard.xyz"; declare function makeCrankSwbFeedIx(marginfiAccount: MarginfiAccountType, bankMap: Map, newBanksPk: PublicKey[], provider: AnchorProvider, crossbarUrl?: string): Promise<{ instructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; }>; declare function makeUpdateSwbFeedIx(props: { swbPullOracles: { key: PublicKey; price?: OraclePrice; }[]; feePayer: PublicKey; connection: Connection; crossbarUrl?: string; fallbackCrossbarUrl?: string; }): Promise<{ instructions: TransactionInstruction[]; luts: AddressLookupTableAccount[]; }>; /** * Creates instructions to refresh Kamino lending protocol reserves and obligations. * * This function generates the necessary Solana instructions to update Kamino (Klend) reserve * data and refresh obligations for all active Kamino banks in the marginfi account, plus any * new banks being added. This ensures price and state data is current before executing transactions. * * @param marginfiAccount - The marginfi account containing active bank balances * @param bankMap - Map of bank addresses (base58) to bank instances * @param newBanksPk - Public keys of new banks being added to the account * @param bankMetadataMap - Map containing Bank-specific metadata (reserve states, lending markets) * @returns InstructionsWrapper containing refresh reserve and obligation instructions */ declare function makeRefreshKaminoBanksIxs(marginfiAccount: MarginfiAccountType, bankMap: Map, newBanksPk: PublicKey[], bankMetadataMap: BankIntegrationMetadataMap): InstructionsWrapper; /** * Creates instructions to update Drift protocol spot market data. * * This function generates the necessary Solana instructions to refresh Drift spot market * cumulative interest for all active Drift banks in the marginfi account, excluding any * specified banks. This ensures market state and interest calculations are current before * executing transactions. * * @param marginfiAccount - The marginfi account containing active bank balances * @param bankMap - Map of bank addresses (base58) to bank instances * @param banksToExclude - Public keys of banks to exclude from the update * @param bankMetadataMap - Map containing Bank-specific metadata (Drift spot market states) * @returns InstructionsWrapper containing Drift spot market update instructions */ declare function makeUpdateDriftMarketIxs(marginfiAccount: MarginfiAccountType, bankMap: Map, banksToExclude: PublicKey[], bankMetadataMap: BankIntegrationMetadataMap): InstructionsWrapper; /** * Creates instructions to refresh JupLend exchange rates. * * This function generates permissionless `update_rate` instructions for all active * JupLend banks in the marginfi account, excluding any specified banks. This ensures * exchange rates are current before risk-sensitive flows (liquidation, borrow, * non-JupLend withdraw where JupLend is collateral). * * Note: juplend_deposit and juplend_withdraw call updateRate internally, * so this is only needed for other flows. * * @param marginfiAccount - The marginfi account containing active bank balances * @param bankMap - Map of bank addresses (base58) to bank instances * @param banksToExclude - Public keys of banks to exclude from the update * @param bankMetadataMap - Map containing Bank-specific metadata (JupLend lending states) * @returns InstructionsWrapper containing update_rate instructions */ declare function makeUpdateJupLendRateIxs(marginfiAccount: MarginfiAccountType, bankMap: Map, banksToExclude: PublicKey[], bankMetadataMap: BankIntegrationMetadataMap): InstructionsWrapper; /** * Groups the per-integration refresh/update instructions (Kamino reserve refresh, * Drift spot market update, JupLend rate update) into a single wrapper. * * JupLend and Drift action instructions update their own bank via CPI, so the bank * being acted on is excluded from those updates. Kamino has no such CPI, so the * action bank must be explicitly included in the refresh set instead. * * @param marginfiAccount - The marginfi account containing active bank balances * @param bankMap - Map of bank addresses (base58) to bank instances * @param banksToExclude - Banks skipped for the JupLend/Drift updates (their CPI already updates them) * @param bankMetadataMap - Map containing Bank-specific metadata (integration states) * @param kaminoNewBanksPk - Banks to union into the Kamino refresh set, defaults to `banksToExclude` * @returns InstructionsWrapper with instructions ordered kamino -> drift -> juplend */ declare function makeRefreshIntegrationBanksIxs(marginfiAccount: MarginfiAccountType, bankMap: Map, banksToExclude: PublicKey[], bankMetadataMap: BankIntegrationMetadataMap, kaminoNewBanksPk?: PublicKey[]): InstructionsWrapper; type ValidatorVoteAccountByBank = { [address: string]: string; }; type FetchPythOracleOnChainOpts = { mode: "on-chain"; connection: Connection; validatorVoteAccountByBank?: ValidatorVoteAccountByBank; }; type FetchPythOracleApiOpts = { mode: "api"; pythOnchainData: { endpoint: string; queryKey?: string; }; /** @deprecated Unused; will be removed in a future release. */ stakedCollatData?: { endpoint: string; queryKey?: string; }; validatorVoteAccountByBank?: ValidatorVoteAccountByBank; }; type PythOracleServiceOpts = FetchPythOracleOnChainOpts | FetchPythOracleApiOpts; /** * Fetches comprehensive Pyth oracle data including push oracles and staked collateral data * @param banks - Array of bank objects * @param opts - Optional configuration including API endpoint usage and connection * @returns Promise resolving to map of bank addresses to their oracle prices */ declare const fetchPythOracleData: (banks: BankType[], opts: PythOracleServiceOpts, priceCoeffByBank?: Record) => Promise<{ bankOraclePriceMap: Map; }>; /** * Fetches Pyth oracle price data via internal API endpoint * @param pythOracleKeys - Array of Pyth oracle key strings * @param apiEndpoint - Fetches pyth oracle data with a GET request using the pyth keys as params * @returns Promise resolving to oracle prices indexed by oracle key */ declare const fetchPythOraclePricesFromAPI: (pythOracleKeys: string[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * Fetches Pyth oracle data directly from the blockchain via RPC connection * @param requestedPythOracleKeys - Array of Pyth oracle key strings to fetch * @param connection - Solana RPC connection instance * @returns Promise resolving to oracle price data indexed by oracle key */ declare const fetchPythOraclePricesFromChain: (requestedPythOracleKeys: string[], connection: Connection) => Promise>; type FetchSwbOracleOnChainOpts = { mode: "on-chain"; connection: Connection; crossbarEndpoint?: string; }; type FetchSwbOracleApiOpts = { mode: "api"; swbOnChainData: { endpoint: string; queryKey?: string; }; swbCrossbarPrice: { endpoint: string; queryKey?: string; }; /** @deprecated Unused; will be removed in a future release. */ stakedCollatData?: { endpoint: string; queryKey?: string; }; priceFallback?: { endpoint: string; queryKey?: string; }; /** @deprecated Renamed to `priceFallback` — the endpoint is no longer Birdeye-backed. */ birdeyeFallback?: { endpoint: string; queryKey?: string; }; }; type SwbOracleServiceOpts = FetchSwbOracleOnChainOpts | FetchSwbOracleApiOpts; /** * Fetches comprehensive Switchboard oracle data including price feeds and broken feed detection * @param banks - Array of bank objects * @param opts - Optional configuration including API endpoint usage * @returns Promise resolving to map of bank addresses to their oracle prices */ declare const fetchSwbOracleData: (banks: BankType[], opts: SwbOracleServiceOpts) => Promise<{ bankOraclePriceMap: Map; }>; /** * Fetches Switchboard oracle account information data via internal API endpoint * @param oracleKeys - Array of Switchboard oracle key strings * @returns Promise resolving to oracle account information indexed by oracle key */ declare const fetchSwbOracleAccountsFromAPI: (oracleKeys: string[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise; /** * Fetches Switchboard oracle account information data directly from the blockchain * @param oracleKeys - Array of Switchboard oracle key strings * @param connection - Solana RPC connection instance * @returns Promise resolving to oracle account information indexed by oracle key */ declare const fetchSwbOracleAccountsFromChain: (oracleKeys: string[], connection: Connection) => Promise; /** * Fetches Switchboard oracle price data via internal API endpoint using feed IDs * @param swbFeedIds - Array of Switchboard feed ID strings * @param apiEndpoint - API endpoint for fetching Switchboard oracle prices * @returns Promise resolving to feed response data indexed by feed ID */ declare const fetchSwbOraclePricesFromAPI: (swbFeedIds: string[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * Fetches Switchboard oracle price data via internal API endpoint using feed IDs * @param swbFeedIds - Array of Switchboard feed ID strings * @param apiEndpoint - API endpoint for fetching Switchboard oracle prices * @returns Promise resolving to feed response data indexed by feed ID */ declare const fetchSwbOraclePricesFromCrossbar: (swbFeedIds: string[], primaryCrossbarEndpoint: string, fallbackCrossbarEndpoint: string) => Promise>; type FetchScopeOracleOnChainOpts = { mode: "on-chain"; connection: Connection; }; type FetchScopeOracleApiOpts = { mode: "api"; scopeOnchainData: { endpoint: string; queryKey?: string; }; }; type ScopeOracleServiceOpts = FetchScopeOracleOnChainOpts | FetchScopeOracleApiOpts; /** * Fetches Scope oracle data for all Scope-priced banks * @param banks - Array of bank objects * @param opts - Configuration including API endpoint usage and connection * @returns Promise resolving to map of bank addresses to their oracle prices */ declare const fetchScopeOracleData: (banks: BankType[], opts?: ScopeOracleServiceOpts) => Promise<{ bankOraclePriceMap: Map; }>; /** * Fetches Scope oracle price data via internal API endpoint * @param requestKeys - Array of ":" request keys * @param apiEndpoint - Fetches scope oracle data with a GET request using the request keys as params * @returns Promise resolving to oracle prices indexed by request key */ declare const fetchScopeOraclePricesFromAPI: (requestKeys: string[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * Fetches Scope oracle data directly from the blockchain via RPC connection * @param requestKeys - Array of ":" request keys * @param connection - Solana RPC connection instance * @returns Promise resolving to oracle price data indexed by request key */ declare const fetchScopeOraclePricesFromChain: (requestKeys: string[], connection: Connection) => Promise>; type FetchOracleMultiplierOnChainOpts = { mode: "on-chain"; connection: Connection; }; type FetchOracleMultiplierApiOpts = { mode: "api"; multiplierData: { endpoint: string; queryKey?: string; }; }; type OracleMultiplierServiceOpts = FetchOracleMultiplierOnChainOpts | FetchOracleMultiplierApiOpts; /** * Fetches the exchange-rate multipliers for banks priced as `base feed x on-chain rate` * (Marinade mSOL rate, SPL stake-pool LST rate, Exponent PT linear rate) * @param banks - Array of bank objects * @param opts - Configuration including API endpoint usage and connection * @returns Promise resolving to multipliers indexed by bank address */ declare const fetchOracleMultipliers: (banks: BankType[], opts?: OracleMultiplierServiceOpts) => Promise>; /** * Multipliers for the given banks, reading the accounts via the internal API endpoint. */ declare const fetchOracleMultipliersFromAPI: (inputs: OracleMultiplierBankInput[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise>; /** * Multipliers for the given banks, reading the accounts directly from the chain. */ declare const fetchOracleMultipliersFromChain: (inputs: OracleMultiplierBankInput[], connection: Connection) => Promise>; /** * Reads multiplier accounts via an internal API endpoint that runs `fetchMultiplierAccountStates` * server-side and returns `{ data: MultiplierAccountStates }`. * @param accountKeys - Multiplier account addresses (base58) * @param apiEndpoint - GET endpoint * @param opts.queryKey - Name of the account-list param (default `multiplierAccounts`) */ declare const fetchMultiplierAccountStatesFromAPI: (accountKeys: string[], apiEndpoint: string, opts?: { queryKey?: string; }) => Promise; /** * Reads and decodes multiplier accounts from the chain. * @param accountKeys - Multiplier account addresses (base58) * @param connection - Solana RPC connection instance */ declare const fetchMultiplierAccountStates: (accountKeys: string[], connection: Connection) => Promise; /** * Fetches comprehensive oracle data from multiple providers (Pyth and Switchboard) * Implements intelligent routing based on oracle type and risk tier: * - Zero oracles: Returns 0 price immediately * - Isolated assets: Uses enriched bank price (no external calls) * - Collateral assets: Uses Pyth/Switchboard with price fallback * * @param banks - Array of bank objects * @param opts - Optional configuration including API endpoint usage, connection, and enriched banks * @returns Promise resolving to oracle price maps indexed by bank address and mint address */ declare const fetchOracleData: (banks: BankType[], opts: { pythOpts: PythOracleServiceOpts; swbOpts: SwbOracleServiceOpts; scopeOpts?: ScopeOracleServiceOpts; oracleMultiplierOpts?: OracleMultiplierServiceOpts; isolatedBanksOpts?: { fetchPrices: boolean; staticPricesByBank?: Record; }; }) => Promise<{ bankOraclePriceMap: Map; mintOraclePriceMap: Map; }>; declare enum SwapProvider { JUPITER = "JUPITER", TITAN = "TITAN", DFLOW = "DFLOW" } interface SwapApiConfig { basePath?: string; /** WebSocket endpoint (e.g. `wss:///api/v1/ws`). Used by the Titan V3 * adapter, which sends the full footprint template inline over the socket to * avoid the gateway GET's URL-length limit. */ wsUrl?: string; apiKey?: string; headers?: Record; } interface SwapProviderEntry { provider: SwapProvider; apiConfig?: SwapApiConfig; } interface SwapProviderConfig { provider: SwapProvider; slippageMode: "DYNAMIC" | "FIXED"; slippageBps: number; platformFeeBps: number; directRoutesOnly?: boolean; apiConfig?: SwapApiConfig; fallbackProviders?: SwapProviderEntry[]; } interface SwapOpts { swapConfig?: SwapProviderConfig; /** * Pin an exact, caller-reviewed swap route instead of running the swap engine. * * The caller owns ATA setup for the route, the route's input amount MUST equal the flow's swap * input (e.g. the loop's borrow amount), and the route MUST pay out to the flow's destination * token account. `quoteResponse.otherAmountThreshold` (guaranteed min-out, native units) sizes * the follow-up amount — e.g. the loop's deposit byte-patch — exactly like an engine-selected * route would. For dynamic caller-controlled routing (inspect/veto routes at build time), * prefer `swapEngineRunner`. * * Note: the bridged `makeBridged*Tx` fallbacks are disabled when a pinned route is supplied — * a pinned route belongs to the direct pair and cannot be spliced into SDK-composed legs. */ swapIxs?: { instructions: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[]; /** The pinned route's quote; `otherAmountThreshold` must be the route's min-out (native). */ quoteResponse: SwapQuoteResult; }; } interface SwapQuoteResult { inAmount: string; outAmount: string; otherAmountThreshold: string; slippageBps: number; platformFee?: { amount: string; feeBps: number; }; priceImpactPct?: string; contextSlot?: number; timeTaken?: number; provider?: SwapProvider; } interface SwapIxsResult { swapInstructions: TransactionInstruction[]; setupInstructions: TransactionInstruction[]; addressLookupTableAddresses: AddressLookupTableAccount[]; quoteResponse: SwapQuoteResult; } interface MakeDepositIxOpts { wrapAndUnwrapSol?: boolean; wSolBalanceUi?: number; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; liquidityVault?: PublicKey; }; } interface MakeDepositIxParams { program: MarginfiProgram; bank: BankType; tokenProgram: PublicKey; amount: Amount; accountAddress: PublicKey; authority: PublicKey; group: PublicKey; isSync?: boolean; opts?: MakeDepositIxOpts; } interface MakeJuplendDepositIxParams { program: MarginfiProgram; bank: BankType; tokenProgram: PublicKey; amount: Amount; accountAddress: PublicKey; authority: PublicKey; group: PublicKey; isSync?: boolean; opts?: MakeDepositIxOpts; } interface MakeDriftDepositIxParams { program: MarginfiProgram; bank: BankType; tokenProgram: PublicKey; amount: Amount; accountAddress: PublicKey; authority: PublicKey; group: PublicKey; driftOracle: PublicKey; driftMarketIndex: number; isSync?: boolean; opts?: MakeDepositIxOpts; } interface MakeKaminoDepositIxParams { program: MarginfiProgram; bank: BankType; tokenProgram: PublicKey; amount: Amount; accountAddress: PublicKey; authority: PublicKey; group: PublicKey; reserve: KaminoReserve; isSync?: boolean; opts?: MakeDepositIxOpts; } interface MakeDepositTxParams extends MakeDepositIxParams { luts: AddressLookupTableAccount[]; blockhash?: string; } interface MakeJuplendDepositTxParams extends MakeJuplendDepositIxParams { luts: AddressLookupTableAccount[]; connection: Connection; blockhash?: string; } interface MakeDriftDepositTxParams extends MakeDriftDepositIxParams { luts: AddressLookupTableAccount[]; connection: Connection; blockhash?: string; } interface MakeKaminoDepositTxParams extends MakeKaminoDepositIxParams { luts: AddressLookupTableAccount[]; connection: Connection; blockhash?: string; } interface MakeRepayIxOpts { wrapAndUnwrapSol?: boolean; wSolBalanceUi?: number; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; liquidityVault?: PublicKey; }; } interface MakeRepayIxParams { program: MarginfiProgram; bank: BankType; tokenProgram: PublicKey; amount: Amount; accountAddress: PublicKey; authority: PublicKey; repayAll?: boolean; isSync?: boolean; opts?: MakeRepayIxOpts; } interface MakeRepayTxParams extends MakeRepayIxParams { luts: AddressLookupTableAccount[]; } interface MakeWithdrawIxOpts { observationBanksOverride?: PublicKey[]; wrapAndUnwrapSol?: boolean; createAtas?: boolean; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; } interface MakeDriftWithdrawIxParams { program: MarginfiProgram; bank: BankType; bankMap: Map; tokenProgram: PublicKey; amount: Amount; marginfiAccount: MarginfiAccountType; authority: PublicKey; driftSpotMarket: DriftSpotMarket; userRewards: DriftRewards[]; bankMetadataMap: BankIntegrationMetadataMap; isSync?: boolean; withdrawAll?: boolean; opts?: MakeWithdrawIxOpts; } interface MakeKaminoWithdrawIxParams { program: MarginfiProgram; bank: BankType; bankMap: Map; tokenProgram: PublicKey; cTokenAmount: Amount; marginfiAccount: MarginfiAccountType; authority: PublicKey; reserve: KaminoReserve; bankMetadataMap: BankIntegrationMetadataMap; isSync?: boolean; withdrawAll?: boolean; opts?: MakeWithdrawIxOpts; } interface MakeJuplendWithdrawIxParams { program: MarginfiProgram; bank: BankType; bankMap: Map; tokenProgram: PublicKey; amount: Amount; marginfiAccount: MarginfiAccountType; authority: PublicKey; jupLendingState: JupLendingState; bankMetadataMap: BankIntegrationMetadataMap; isSync?: boolean; withdrawAll?: boolean; opts?: MakeWithdrawIxOpts; } interface MakeWithdrawIxParams { program: MarginfiProgram; bank: BankType; bankMap: Map; tokenProgram: PublicKey; amount: Amount; marginfiAccount: MarginfiAccountType; authority: PublicKey; bankMetadataMap: BankIntegrationMetadataMap; isSync?: boolean; withdrawAll?: boolean; opts?: MakeWithdrawIxOpts; } interface MakeWithdrawTxParams extends MakeWithdrawIxParams { connection: Connection; oraclePrices: Map; assetShareValueMultiplierByBank: Map; luts: AddressLookupTableAccount[]; crossbarUrl?: string; } interface MakeKaminoWithdrawTxParams extends Omit { amount: Amount | TypedAmount; connection: Connection; oraclePrices: Map; assetShareValueMultiplierByBank: Map; luts: AddressLookupTableAccount[]; crossbarUrl?: string; } interface MakeBorrowIxOpts { observationBanksOverride?: PublicKey[]; wrapAndUnwrapSol?: boolean; createAtas?: boolean; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; /** * Additional banks to include in the health check calculation. * Useful for combined operations where a deposit precedes the borrow * and the deposited bank needs to be considered for health calculation. */ additionalHealthCheckBanks?: PublicKey[]; } interface MakeBorrowIxParams { program: MarginfiProgram; bank: BankType; bankMap: Map; tokenProgram: PublicKey; amount: Amount; marginfiAccount: MarginfiAccountType; authority: PublicKey; isSync?: boolean; opts?: MakeBorrowIxOpts; } interface MakeBorrowTxParams extends MakeBorrowIxParams { connection: Connection; oraclePrices: Map; assetShareValueMultiplierByBank: Map; bankMetadataMap: BankIntegrationMetadataMap; luts: AddressLookupTableAccount[]; crossbarUrl?: string; } interface MakeJuplendWithdrawTxParams extends MakeJuplendWithdrawIxParams { connection: Connection; oraclePrices: Map; assetShareValueMultiplierByBank: Map; luts: AddressLookupTableAccount[]; crossbarUrl?: string; } interface MakeDriftWithdrawTxParams extends MakeDriftWithdrawIxParams { connection: Connection; oraclePrices: Map; assetShareValueMultiplierByBank: Map; luts: AddressLookupTableAccount[]; crossbarUrl?: string; } interface MakeCloseAccountIxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; authority: PublicKey; } interface MakeCloseAccountTxParams extends MakeCloseAccountIxParams { connection: Connection; } interface MakeAccountTransferToNewAccountTxParams { connection: Connection; program: MarginfiProgram; /** The account being transferred (its current authority is the signer). */ marginfiAccount: MarginfiAccountType; /** Freshly generated keypair for the destination account; must sign. */ newMarginfiAccount: Signer; /** The wallet that will own the new account. */ newAuthority: PublicKey; /** Optional. Pays rent/fees. A `PublicKey` signs via the wallet adapter; a * `Keypair` is a separate fee payer that signs directly. Defaults to the * account's current authority. */ feePayer?: PublicKey | Keypair; } interface TransactionBuilderResult { transactions: SolanaTransaction[]; actionTxIndex: number; } interface FlashloanActionResult extends TransactionBuilderResult { /** Whether transaction size exceeds limits */ txOverflown: boolean; } interface MakeFlashLoanTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; bankMap: Map; ixs: TransactionInstruction[]; blockhash: string; addressLookupTableAccounts?: AddressLookupTableAccount[]; isSync?: boolean; signers?: Signer[]; } type TransferPositionSide = "collateral" | "debt"; interface MakeTransferPositionsTxParams { program: MarginfiProgram; connection: Connection; /** Source account A (positions move out of this account). */ marginfiAccount: MarginfiAccountType; /** Banks whose A-positions to move; the side is inferred from A's balance. */ bankAddresses: PublicKey[]; /** Destination account B. Omit to create a fresh account inside the flashloan tx. */ destinationAccount?: MarginfiAccountType; /** Only used when `destinationAccount` is omitted. */ createDestinationOpts?: { accountIndex?: number; thirdPartyId?: number; }; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; /** Token program per transferred bank (base58 bank address → token program id). */ tokenProgramsByBank: Map; addressLookupTableAccounts?: AddressLookupTableAccount[]; /** Head-room added to each borrow over the estimated debt for interest accrual. Default 10 bps. */ borrowPaddingBps?: number; /** Max positions per transfer; a larger selection is rejected. Default 5. */ maxPositions?: number; /** Whether the group USD rate limiter is enabled (adds an oracle to each withdraw). Default false. */ groupRateLimiterEnabled?: boolean; crossbarUrl?: string; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; } interface TransferPositionsResult { /** Ordered for execution: [setup/crank txs…, flashloan tx]. */ transactions: ExtendedV0Transaction[]; /** Index of the flashloan tx in `transactions`. */ actionTxIndex: number; /** The destination account (passed-in, or the projected account created in the tx). */ destinationAccount: MarginfiAccountType; /** Whether all transactions must land atomically in one bundle. */ mustBeAtomicBundle: boolean; } interface MakeBulkWithdrawTxParams { program: MarginfiProgram; connection: Connection; marginfiAccount: MarginfiAccountType; /** Banks whose FULL positions to withdraw, in execution order. */ bankAddresses: PublicKey[]; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; /** Token program per withdrawn bank (base58 bank address → token program id). */ tokenProgramsByBank: Map; /** Whether the group USD rate limiter is enabled (adds an oracle to each withdraw). Default false. */ groupRateLimiterEnabled?: boolean; luts: AddressLookupTableAccount[]; crossbarUrl?: string; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; } interface MakeBulkRepayTxParams { program: MarginfiProgram; connection: Connection; marginfiAccount: MarginfiAccountType; /** Banks whose FULL debts to repay from the wallet. */ bankAddresses: PublicKey[]; bankMap: Map; /** Token program per repaid bank (base58 bank address → token program id). */ tokenProgramsByBank: Map; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; } interface BulkLendTxsResult { /** Ordered for execution: [setup/crank txs…, action txs…]. */ transactions: ExtendedV0Transaction[]; /** Index of the first action tx in `transactions`. */ actionTxIndex: number; /** Whether all transactions must land atomically in one bundle. */ mustBeAtomicBundle: boolean; } interface MakeLoopTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; connection: Connection; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; depositOpts: { inputDepositAmount: number; depositBank: BankType; tokenProgram: PublicKey; loopMode: "DEPOSIT" | "BORROW"; marketPrice: number; }; borrowOpts: { borrowAmount: number; borrowBank: BankType; tokenProgram: PublicKey; marketPrice: number; }; swapOpts: SwapOpts; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; additionalIxs?: TransactionInstruction[]; crossbarUrl?: string; /** * Optional override for how the swap engine runs. Defaults to the in-process * `runSwapEngine`; the app injects a runner that forwards to `/api/tx/swap-engine` * so the multi-provider fan-out happens server-side. * * Also the seam for caller-controlled routing: wrap the default runner to inspect, veto, or * replace the selected route before it's spliced into the flashloan (see * `examples/16c-loop-pinned-route.ts`). For a fully static, pre-reviewed route use * `swapOpts.swapIxs` instead. */ swapEngineRunner?: SwapEngineRunner; } /** * Describes a loop flashloan that has been built up to — but not including — the swap. * Handed off to the swap engine, which selects a route against the remaining tx budget * and returns the swap instruction(s) to splice into `innerIxs` at `swapSlotIndex`. * * The flashloan wrapper (begin/end-FL) is intentionally NOT part of `innerIxs`; its size * and account cost are already accounted for in `sizeConstraint` / `maxSwapTotalAccounts`. */ interface LoopFlashloanDescriptor { innerIxs: TransactionInstruction[]; swapSlotIndex: number; depositIxIndex: number; inputMint: string; outputMint: string; inputDecimals: number; outputDecimals: number; inAmountNative: number; destinationTokenAccount: PublicKey; sizeConstraint: number; maxSwapTotalAccounts: number; luts: AddressLookupTableAccount[]; } interface MakeRepayWithCollatTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; connection: Connection; bankMap: Map; oraclePrices: Map; assetShareValueMultiplierByBank: Map; bankMetadataMap: BankIntegrationMetadataMap; withdrawOpts: { totalPositionAmount: number; withdrawAmount: number; withdrawBank: BankType; tokenProgram: PublicKey; }; repayOpts: { repayBank: BankType; tokenProgram: PublicKey; totalPositionAmount: number; repayAmount?: number; }; swapOpts: SwapOpts; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; additionalIxs?: TransactionInstruction[]; crossbarUrl?: string; /** See `MakeLoopTxParams.swapEngineRunner`. */ swapEngineRunner?: SwapEngineRunner; } interface MakeSwapCollateralTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; connection: Connection; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; withdrawOpts: { totalPositionAmount: number; withdrawAmount?: number; withdrawBank: BankType; tokenProgram: PublicKey; }; depositOpts: { depositBank: BankType; tokenProgram: PublicKey; }; swapOpts: SwapOpts; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; additionalIxs?: TransactionInstruction[]; crossbarUrl?: string; /** See `MakeLoopTxParams.swapEngineRunner`. */ swapEngineRunner?: SwapEngineRunner; } /** * Params for {@link makeRollPtTx} — rolling a matured Exponent PT collateral position into * its next-maturity PT, so the **full deposit ends up as new PT** (no leftover), in one * flash-loan-wrapped bundle: * 1. withdraw the old PT, then Exponent `merge` (redeem PT → SY, post-maturity, 1:1) * 2. buy the new PT with that SY directly on the successor's **CLMM** (`MarketThree`) PT/SY * pool via `trade_pt` — no base-token round-trip, no external aggregator * 3. deposit the new PT. * * The buy is liquidity-bounded by the successor pool's depth. The redeem is sized by the * vault's `pt_redemption_rate`; the SY → PT price is quoted by simulating a standalone * `trade_pt`, so the deposit is sized to the guaranteed minimum out. */ interface MakeRollPtTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; connection: Connection; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; withdrawOpts: { totalPositionAmount: number; withdrawAmount?: number; /** The expiring (matured) PT bank. */ withdrawBank: BankType; tokenProgram: PublicKey; }; depositOpts: { /** The successor (next-maturity) PT bank. */ depositBank: BankType; tokenProgram: PublicKey; }; /** Exponent redeem (`merge`) + successor-CLMM buy config for the matured PT. */ rollOpts: RollPtOpts; /** See {@link RollQuoteSimulator}. Defaults to `connection.simulateTransaction`. */ simulateTx?: RollQuoteSimulator; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; crossbarUrl?: string; } /** One token-account balance snapshot from a {@link makeRollPtTx} quote simulation. */ interface RollQuoteTokenBalance { mint: string; owner: string; /** Raw native token amount (integer string). */ amount: string; } /** * Result of one {@link makeRollPtTx} quote simulation. The roll builder prefers the * pre/post token-balance delta (ground truth, reported by bundle-sim transports) and * falls back to `returnData` for plain `simulateTransaction` transports — so pass * through whichever of these the backend provides. */ interface RollQuoteSimResult { err: unknown; logs: string[] | null; returnData?: { programId: string; data: [string, string]; } | null; preTokenBalances?: RollQuoteTokenBalance[] | null; postTokenBalances?: RollQuoteTokenBalance[] | null; } /** * Transport for {@link makeRollPtTx}'s quote simulations (standalone, expected-to-succeed * transactions). The transaction is unsigned, so implementations must simulate with * `sigVerify: false` and `replaceRecentBlockhash: true`. Defaults to * `connection.simulateTransaction`; browsers whose RPC proxy disallows * `simulateTransaction` inject one that routes through an app-side endpoint instead. */ type RollQuoteSimulator = (tx: VersionedTransaction) => Promise; /** * Exponent roll config for {@link makeRollPtTx}. `makeRollPtTx` resolves the matured vault's * `merge` accounts and the successor pool's CLMM `trade_pt` accounts internally from these * addresses — the caller never assembles Exponent accounts/ixs. */ interface RollPtOpts { /** The matured PT's Exponent `MarketTwo` — its `vault` is read (one of market/vault required). */ maturedMarket?: PublicKey; /** …or the matured vault directly. */ maturedVault?: PublicKey; /** The successor maturity's **CLMM** (`MarketThree`) pool — where the new PT trades (SY → PT). */ successorMarket: PublicKey; /** Slippage tolerance (bps) for the SY → PT CLMM swap. Defaults to 50. */ slippageBps?: number; /** Token program for the shared SY mint (defaults to the classic Token program). */ syTokenProgram?: PublicKey; /** * Optional dedicated PT-roll address lookup table (fetched internally) that compresses the * merge + CLMM-swap flashloan bytes (see `examples/create-pt-roll-lut.ts`). Account *locks* * are already bounded by the compact, fixed CLMM footprint. */ lookupTable?: PublicKey; } interface MakeSwapDebtTxParams { program: MarginfiProgram; marginfiAccount: MarginfiAccountType; connection: Connection; bankMap: Map; oraclePrices: Map; bankMetadataMap: BankIntegrationMetadataMap; assetShareValueMultiplierByBank: Map; repayOpts: { totalPositionAmount: number; repayAmount?: number; repayBank: BankType; tokenProgram: PublicKey; marketPrice: number; }; borrowOpts: { borrowBank: BankType; tokenProgram: PublicKey; marketPrice: number; }; swapOpts: SwapOpts; addressLookupTableAccounts?: AddressLookupTableAccount[]; overrideInferAccounts?: { group?: PublicKey; authority?: PublicKey; }; additionalIxs?: TransactionInstruction[]; crossbarUrl?: string; /** See `MakeLoopTxParams.swapEngineRunner`. */ swapEngineRunner?: SwapEngineRunner; } interface MakeSetupIxParams { connection: Connection; authority: PublicKey; tokens: { mint: PublicKey; tokenProgram: PublicKey; }[]; } /** * Vault PDA Utilities * =================== */ /** * Gets the PDA seed for a specific bank vault type. * * @param type - The vault type (Liquidity, Insurance, or Fee) * @returns The PDA seed buffer for the vault * @throws Error if vault type is unknown */ declare function getBankVaultSeeds(type: BankVaultType): Buffer; /** * Computes the Program Derived Address (PDA) for a bank vault authority. * * The vault authority is the account that has signing authority over vault operations. * This is a PDA derived from the vault type seed and bank public key. * * @param bankVaultType - The type of vault (Liquidity, Insurance, or Fee) * @param bankPk - The bank's public key * @param programId - The marginfi program ID * @returns Tuple of [PDA PublicKey, bump seed] * * @example * ```typescript * const [vaultAuthority, bump] = getBankVaultAuthority( * BankVaultType.LiquidityVault, * bankAddress, * MARGINFI_PROGRAM_ID * ); * ``` */ declare function getBankVaultAuthority(bankVaultType: BankVaultType, bankPk: PublicKey, programId: PublicKey): [PublicKey, number]; declare const fetchBank: (program: MarginfiProgram, bankAddress: Address) => Promise<{ address: PublicKey; data: BankRaw; }>; declare const fetchMultipleBanks: (program: MarginfiProgram, opts?: { bankAddresses?: Address[]; groupAddress?: PublicKey; }) => Promise<{ address: PublicKey; data: BankRaw; }[]>; /** On-chain sentinel: a deposit/borrow limit equal to `u64::MAX` means "no limit". */ declare const U64_MAX: BigNumber$1; /** Mirrors `BankConfig::is_deposit_limit_active` (limit != u64::MAX). */ declare function isDepositLimitActive(bank: BankType): boolean; /** Mirrors `BankConfig::is_borrow_limit_active` (limit != u64::MAX). */ declare function isBorrowLimitActive(bank: BankType): boolean; /** * The deposit limit in the same units as `totalAssetShares * assetShareValue`. * * For Drift banks the program compares the limit against the 9-decimal scaled balance, so it * scales `deposit_limit` (mint decimals) by `10^(9 - mint_decimals)` first * (`scale_drift_deposit_limit`). All other banks compare the raw limit. */ declare function getEffectiveDepositLimit(bank: BankType): BigNumber$1; declare function computeInterestRates(bank: BankType): { lendingRate: BigNumber$1; borrowingRate: BigNumber$1; }; declare function computeBaseInterestRate(bank: BankType): BigNumber$1; declare function computeUtilizationRate(bank: BankType): BigNumber$1; /** Mirrors the program's `SECONDS_PER_YEAR` (365 days, no leap adjustment). */ declare const SECONDS_PER_YEAR: number; /** * Minimum execution headroom (seconds) assumed between computing a bank-bounded amount and the * transaction landing on-chain. Interest keeps accruing in that window, so bounds that depend on * accrued interest are projected at least this far ahead. */ declare const EXECUTION_HEADROOM_SECONDS = 120; /** * Seconds of interest accrual to project for a bank-bounded amount: the program accrues * `now - lastUpdate` of interest before applying its checks, and the tx lands some time after * `now`. Uses `max(2 * age, age + EXECUTION_HEADROOM_SECONDS)` — at least as conservative as the * historical "2x accrued" buffer, and never less than the execution headroom even for a bank that * was touched a second ago. */ declare function computeAccrualProjectionSeconds(bank: BankType, nowSeconds?: number): number; declare function computeRemainingCapacity(bank: BankType): { depositCapacity: BigNumber$1; borrowCapacity: BigNumber$1; }; /** * Whether a bank can be borrowed with the standard `lending_account_borrow` instruction. * * Only `DEFAULT`/`SOL` asset-tag banks are borrowable on-chain; the integration wrappers * (KAMINO/DRIFT/SOLEND/JUPLEND) reuse the same mint with `borrowLimit=0` and reject a standard * borrow with `6200 WrongAssetTagForStandardInstructions`. Use this when picking a bank to *borrow* * (e.g. the bridge bank for a debt-swap or loop double-hop). */ declare function isStandardBorrowable(bank: BankType): boolean; /** * Whether a bank accepts standard deposits. `ReduceOnly`/`Paused` banks reject new deposits with * `6017 BankReduceOnly`; integration wrappers aren't standard-depositable either. Use this when * picking a bank to *deposit* into (e.g. the bridge bank for a collateral-swap double-hop). */ declare function isStandardDepositable(bank: BankType): boolean; /** * Computed metrics describing a bank's state at a given moment. * * All amounts are UI-scaled (decimals applied). USD values use the bank's * realtime oracle price without any margin weight applied. */ interface BankMetrics { /** Token symbol hint supplied by the caller (e.g. from bank metadata). Empty string if unknown. */ symbol: string; /** Total deposits in UI units (asset share value multiplier applied). */ totalDeposits: number; /** Total borrows in UI units. */ totalBorrows: number; /** USD value of total deposits (realtime oracle price). */ totalDepositsUsd: number; /** USD value of total borrows (realtime oracle price). */ totalBorrowsUsd: number; /** Utilization rate in [0,1]. */ utilizationRate: number; /** Available liquidity in UI units. */ poolSize: number; /** Deposit cap in UI units. */ depositCap: number; /** Borrow cap in UI units. */ borrowCap: number; /** Remaining deposit capacity. */ depositCapRemaining: number; /** Remaining borrow capacity. */ borrowCapRemaining: number; /** Supply APY (compounded annually from the base lending rate). */ supplyApy: number; /** Borrow APY (compounded annually from the borrowing rate). */ borrowApy: number; } interface ComputeBankMetricsParams { bank: BankType; oraclePrice: OraclePrice; /** Asset share value multiplier (e.g. Kamino). Defaults to 1. */ assetShareValueMultiplier?: BigNumber$1; /** Symbol hint surfaced on the returned metrics. */ symbol?: string; } /** * Total deposits in UI units, with the asset-share-value multiplier applied (defaults to 1). */ declare function computeBankTotalDeposits(bank: BankType, assetShareValueMultiplier?: BigNumber$1): number; /** * Total borrows in UI units. Borrows aren't share-multiplied. */ declare function computeBankTotalBorrows(bank: BankType): number; /** * USD value of total deposits, computed from the realtime oracle price * (no margin weight, no price bias). */ declare function computeBankTotalDepositsUsd(bank: BankType, oraclePrice: OraclePrice, assetShareValueMultiplier?: BigNumber$1): number; /** * USD value of total borrows, computed from the realtime oracle price * (no margin weight, no price bias). */ declare function computeBankTotalBorrowsUsd(bank: BankType, oraclePrice: OraclePrice): number; /** * Available liquidity (UI units) = min(totalDeposits, borrowCap) - totalBorrows, clamped to 0. * Matches the existing UI calculation used to gate borrow-side displays. */ declare function computeBankPoolSize(bank: BankType, assetShareValueMultiplier?: BigNumber$1): number; /** * Available bank liquidity in UI units = max(0, totalDeposits - totalBorrows). * * This is the amount the bank's liquidity vault can actually pay out for a withdraw or borrow, * independent of any account-level health constraints. */ declare function computeBankAvailableLiquidity(bank: BankType, assetShareValueMultiplier?: BigNumber$1): BigNumber$1; /** * Remaining deposit capacity in UI units (cap minus deposits, accounting for accrued interest), * clamped at 0. `Infinity` when the bank's deposit limit is inactive (`u64::MAX`). * * For integrated banks this is in the bank's share units (cToken / Drift scaled balance); * multiply by the bank's `assetShareValueMultiplier` to convert to underlying tokens. */ declare function computeBankDepositCapRemaining(bank: BankType): number; /** * Remaining borrow capacity in UI units (cap minus borrows, accounting for accrued interest), * clamped at 0. `Infinity` when the bank's borrow limit is inactive (`u64::MAX`). */ declare function computeBankBorrowCapRemaining(bank: BankType): number; /** * Available liquidity (UI units) projected through interest accrual: `computeBankAvailableLiquidity` * minus the net liquidity drain of accrual (`liabilities * borrowRate - assets * lendingRate`, * annualized) over {@link computeAccrualProjectionSeconds}. The program runs `accrue_interest` * before its `check_utilization_ratio` (assets >= liabilities) check on withdraws and borrows, * so this is the amount that can actually leave the bank when the tx lands. */ declare function computeBankProjectedAvailableLiquidity(bank: BankType, assetShareValueMultiplier?: BigNumber$1): BigNumber$1; /** * Supply APY, compounded from the base lending rate via the shared `aprToApy` helper. */ declare function computeBankSupplyApy(bank: BankType): number; /** * Borrow APY, compounded from the borrowing rate via the shared `aprToApy` helper. */ declare function computeBankBorrowApy(bank: BankType): number; /** * Aggregator over all per-metric subfunctions. Use this when you want every UI field * for a bank in one call; use the per-metric helpers when you only need one or two * (no need to compute oracle math just to read utilization, etc.). * * Pure: pass whatever `(bank, oraclePrice)` snapshot you want reflected (live, * post-simulation, or synthetically mutated). */ declare function computeBankMetrics(params: ComputeBankMetricsParams): BankMetrics; /** * Lookup-or-throw helpers for action-builder inputs. The optional `makeError` * lets callers throw their own typed error (e.g. a TransactionBuildingError * with user-facing copy) instead of a plain Error. */ declare function requireBank(bankMap: Map, address: PublicKey, makeError?: (message: string) => Error): BankType; declare function requireTokenProgram(tokenProgramsByBank: Map, address: PublicKey, makeError?: (message: string) => Error): PublicKey; /** * Remaining outflow capacity of a single sliding rate-limit window at `nowSeconds`, * mirroring the on-chain `RateLimitWindow::effective_remaining_capacity` (read-only — * applies the pending window roll-over without mutating state). * * Units match the window: native tokens for bank-level limiters, USD for group-level. * * @returns Remaining capacity, or `null` when the window is disabled (`maxOutflow == 0`) */ declare function computeRateLimitWindowRemainingCapacity(window: RateLimitWindowType, nowSeconds: number): BigNumber$1 | null; /** * Remaining outflow capacity across both (hourly, daily) windows of a rate limiter: * the minimum of the enabled windows, in the limiter's native units. * * @returns Remaining capacity, or `null` when no window is enabled (no rate limiting) */ declare function computeRateLimiterRemainingCapacity(rateLimiter: BankRateLimiterType | undefined, nowSeconds: number): BigNumber$1 | null; /** * Remaining bank-level rate-limit outflow capacity (withdraws + borrows) in UI units of the * bank's mint, clamped at 0. * * @returns Remaining capacity in UI units, or `null` when the bank has no rate limiter enabled */ declare function computeBankRateLimitRemaining(bank: BankType, nowSeconds?: number): BigNumber$1 | null; /** * Remaining group-level rate-limit outflow capacity in USD, clamped at 0. * * @returns Remaining capacity in USD, or `null` when the group has no rate limiter enabled */ declare function computeGroupRateLimitRemainingUsd(rateLimiter: BankRateLimiterType | undefined, nowSeconds?: number): BigNumber$1 | null; /** * The venue-side account states needed to derive an integrated bank's true liquidity. * * Structurally compatible with `BankIntegrationMetadata` (`client.bankIntegrationMap[address]`), * so that map's entries can be passed directly. */ interface BankVenueStates { kaminoStates?: { reserveState: KaminoReserve; }; driftStates?: { spotMarketState: DriftSpotMarket; }; jupLendStates?: { jupTokenReserveState: JupTokenReserve; }; } /** * Safety buffer applied to venue idle liquidity. Venue reserve states are snapshots refreshed on * the caller's cadence, and unlike the marginfi bank we don't project the venue's own interest * accrual, so the effective withdrawable amount can drift slightly below what the cached state * reports. Shave ~50 bps to avoid simulation failures right at the reported cap. */ declare const VENUE_AVAILABLE_LIQUIDITY_BUFFER = 0.995; /** * Idle liquidity of the external venue backing an integrated bank (Kamino reserve, Drift spot * market, JupLend token reserve), in UI units of the underlying token, with * {@link VENUE_AVAILABLE_LIQUIDITY_BUFFER} applied. * * For integrated banks the marginfi-level totals only describe what marginfi has delegated to the * venue — the venue's own utilization is the true cap on withdrawals (a fully utilized Kamino * reserve pays out nothing even if marginfi's position is large). Returns `undefined` for banks * without an external venue (DEFAULT/SOL/STAKED) or when the relevant venue state is missing. */ declare function computeVenueAvailableLiquidity(bank: BankType, venueStates?: BankVenueStates): BigNumber$1 | undefined; /** * Fee state cache - stores information from the global FeeState * so the FeeState can be omitted on certain instructions * * Note: This matches the actual deserialized structure from Anchor */ interface FeeStateCache { globalFeeWallet: PublicKey; programFeeFixed: { value: number[]; }; programFeeRate: { value: number[]; }; lastUpdate: BN; } /** * Panic state cache - stores information about temporary panic mode * * Note: This matches the actual deserialized structure from Anchor */ interface PanicStateCache { pauseFlags: number; reserved: number[]; pauseStartTimestamp: BN; lastCacheUpdate: BN; } /** * Withdraw window cache - tracks liquidity withdrawn from the group * over a day as protection against large unwanted withdrawals * * Note: This matches the actual deserialized structure from Anchor */ interface WithdrawWindowCache { dailyLimit: number; withdrawnToday: number; lastDailyResetTimestamp: BN; } /** * MarginfiGroup on-chain account structure */ interface MarginfiGroupRaw { /** Broadly able to modify anything, and can set/remove other admins at will */ admin: PublicKey; /** * Bitmask for group settings flags: * - Bit 0: PROGRAM_FEES_ENABLED - If set, program-level fees are enabled * - Bit 1: ARENA_GROUP - If set, this is an arena group (can only have two banks) * - Bits 2-63: Reserved for future use */ groupFlags: BN; /** * Caches information from the global FeeState so the FeeState * can be omitted on certain instructions */ feeStateCache: FeeStateCache; /** Number of banks in this group */ banks: number; /** Padding */ pad0: number[]; /** * This admin can configure collateral ratios above (but not below) * the collateral ratio of certain banks, e.g. allow SOL to count as * 90% collateral when borrowing an LST instead of the default rate */ emodeAdmin: PublicKey; /** Delegate for curve configuration */ delegateCurveAdmin: PublicKey; /** * Can modify the deposit_limit, borrow_limit, total_asset_value_init_limit * but nothing else, for every bank under this group */ delegateLimitAdmin: PublicKey; /** * Can modify the emissions flags, emissions_rate and emissions_mint, * but nothing else, for every bank under this group */ delegateEmissionsAdmin: PublicKey; /** * When program keeper temporarily puts the program into panic mode, * information about the duration of the lockup will be available here */ panicStateCache: PanicStateCache; /** * Keeps track of the liquidity withdrawn from the group over the day * as a result of deleverages. Used as a protection mechanism against * too big (and unwanted) withdrawals (e.g. when the risk admin is compromised) */ deleverageWithdrawWindowCache: WithdrawWindowCache; /** * Can run bankruptcy and forced deleverage instructions to e.g. * sunset risky/illiquid assets */ riskAdmin: PublicKey; /** Can modify a Bank's metadata, and nothing else */ metadataAdmin: PublicKey; /** * Group-level net-outflow rate limiter, denominated in USD (bank rate limiters * use native tokens). Same window struct as the bank rate limiter. */ rateLimiter?: BankRateLimiterRaw; /** Reserved for future use */ padding0: BN[][]; /** Reserved for future use */ padding1: BN[][]; } type MarginfiGroupType = { admin: PublicKey; address: PublicKey; /** * Group-level net-outflow rate limiter (windows denominated in USD, unlike bank * rate limiters which use native tokens). When any window is enabled, every * withdraw/borrow requires a fresh oracle for the affected bank in remaining * accounts — see {@link isGroupRateLimiterEnabled}. */ rateLimiter?: BankRateLimiterType; }; type MarginfiGroupTypeDto = { admin: string; address: string; rateLimiter?: BankRateLimiterDto; }; /** * Mirrors the on-chain `GroupRateLimiter::is_enabled()`: true when any window has a * non-zero max outflow. While enabled, withdraws (including withdraw-all) and borrows * need the affected bank's oracle present and non-stale in remaining accounts. */ declare function isGroupRateLimiterEnabled(rateLimiter?: BankRateLimiterType): boolean; declare function makePoolConfigureBankIx(program: MarginfiProgram, bank: PublicKey, args: BankConfigOptRaw): Promise; declare function makeAddPermissionlessStakedBankIx(program: MarginfiProgram, group: PublicKey, voteAccountAddress: PublicKey, feePayer: PublicKey, pythOracle: PublicKey): Promise; declare function makePoolAddBankIx(program: MarginfiProgram, group: PublicKey, bank: PublicKey, feePayer: PublicKey, bankMint: PublicKey, bankConfig: BankConfigOpt, tokenProgram?: PublicKey, overrideOpt?: { admin?: PublicKey; globalFeeWallet?: PublicKey; }): Promise; declare function dtoToGroup(groupDto: MarginfiGroupTypeDto): MarginfiGroupType; declare function groupToDto(group: MarginfiGroupType): MarginfiGroupTypeDto; type ValidatorStakeGroup = { validator: PublicKey; poolKey: PublicKey; poolMintKey: PublicKey; totalStake: number; selectedAccount: { pubkey: PublicKey; amount: number; }; accounts: { pubkey: PublicKey; amount: number; }[]; }; type ValidatorStakeGroupDto = { validator: string; poolKey: string; poolMintKey: string; totalStake: number; selectedAccount: { pubkey: string; amount: number; }; accounts: { pubkey: string; amount: number; }[]; }; type StakeAccount = { discriminant: number; meta: { rentExemptReserve: bigint; authorized: { staker: PublicKey; withdrawer: PublicKey; }; lockup: { unixTimestamp: bigint; epoch: bigint; custodian: PublicKey; }; }; stake: { delegation: { voterPubkey: PublicKey; stake: bigint; activationEpoch: bigint; deactivationEpoch: bigint; }; creditsObserved: bigint; }; }; type StakePoolMevMap = Map; type ValidatorRateData = { validator: string; totalApy: number; stakingApy: number; }; type ActiveStakePoolMap = Map; interface MakeMintStakedLstIxParams { amount: Amount; authority: PublicKey; stakeAccountPk: PublicKey; validator: PublicKey; connection: Connection; } interface MakeMintStakedLstTxParams extends MakeMintStakedLstIxParams { luts: AddressLookupTableAccount[]; blockhash?: string; } interface MakeRedeemStakedLstIxParams { amount: Amount; authority: PublicKey; validator: PublicKey; connection: Connection; } interface MakeRedeemStakedLstTxParams extends MakeRedeemStakedLstIxParams { luts: AddressLookupTableAccount[]; blockhash?: string; } interface MakeMergeStakeAccountsTxParams { authority: PublicKey; sourceStakeAccount: PublicKey; destinationStakeAccount: PublicKey; connection: Connection; luts: AddressLookupTableAccount[]; blockhash?: string; } /** * Retrieves all active stake accounts associated with a given public key grouped by validator * * @warning this is an expensive rpc call and should be heavily cached * * @param connection - Solana RPC connection * @param publicKey - Users's public key * @param opts - Options for filtering inactive stake accounts * @returns {Promise} An array of validator stake groups */ declare const fetchNativeStakeAccounts: (connection: Connection, publicKey: PublicKey, opts?: { filterInactive: boolean; }) => Promise; /** * Gets active states for stake pools associated with staked asset banks * * @param connection - Solana RPC connection * @param bankInfos - Array of ExtendedBankInfo objects * @returns Promise> - Map of bank addresses to active states */ declare const fetchStakePoolActiveStates: (connection: Connection, validatorVoteAccounts: PublicKey[]) => Promise>; /** * Gets APY rates for validators associated with staked asset banks * * @param validatorVoteAccounts - Array of validator vote account public keys * @returns Promise> - Map of bank addresses to APY rates */ declare const fetchStakeAccount: (data: Buffer$1) => StakeAccount; declare const fetchStakePoolMev: (connection: Connection, validatorVoteAccounts: PublicKey[]) => Promise; declare function validatorStakeGroupToDto(validatorStakeGroup: ValidatorStakeGroup): ValidatorStakeGroupDto; declare function dtoToValidatorStakeGroup(validatorStakeGroupDto: ValidatorStakeGroupDto): ValidatorStakeGroup; /** * Metadata for a staked bank entry. * Sourced from hardcoded JSON — update via `metadata.data.ts` until dynamic fetching is implemented. */ interface StakedBankMetadata { bankAddress: string; validatorVoteAccount: string; tokenAddress: string; tokenName: string; tokenSymbol: string; } /** * Returns a Map of bankAddress → StakedBankMetadata (lazy-cached). * * @remarks Uses hardcoded data. TODO: Replace with dynamic API fetch. */ declare function getStakedBankMetadataMap(): Map; /** * Returns a Record of bankAddress → validatorVoteAccount (lazy-cached). * * @remarks Uses hardcoded data. TODO: Replace with dynamic API fetch. */ declare function getValidatorVoteAccountByBank(): Record; /** * Minimal bank shape required to compute staked-bank multipliers. * Kept local to avoid a hard dependency on the Bank model. */ interface StakedBankLike { address: PublicKey; } /** * Computes the asset-share multiplier (LST → SOL ratio) for each staked bank. * * For each staked bank: * multiplier = max(stakeLamports - LAMPORTS_PER_SOL, 0) / lstMintSupply * * Banks whose metadata cannot be resolved, or whose pool accounts cannot be * fetched, default to a multiplier of 1. * * @param stakedBanks - Banks with `assetTag === AssetTag.STAKED` * @param connection - Solana RPC connection * @returns Map of bank address (base58) → BigNumber multiplier */ declare function computeStakedBankMultipliers(stakedBanks: StakedBankLike[], connection: Connection): Promise>; /** * Creates instructions to convert a native stake account into LST tokens. * * Steps: * 1. Create LST ATA if needed * 2. Split stake account if partial amount * 3. Authorize staker + withdrawer to pool * 4. Deposit stake into pool → user receives LST */ declare function makeMintStakedLstIx(params: MakeMintStakedLstIxParams): Promise; /** * Creates a versioned transaction to convert a native stake account into LST tokens. */ declare function makeMintStakedLstTx(params: MakeMintStakedLstTxParams): Promise; /** * Creates instructions to convert LST tokens back to a native stake account. * * Steps: * 1. Create new stake account (rent-exempt) * 2. Approve pool mint authority to burn LST * 3. Withdraw stake from pool → user receives stake account */ declare function makeRedeemStakedLstIx(params: MakeRedeemStakedLstIxParams): Promise; /** * Creates a versioned transaction to convert LST tokens back to a native stake account. */ declare function makeRedeemStakedLstTx(params: MakeRedeemStakedLstTxParams): Promise; /** * Creates a versioned transaction to merge two stake accounts. * * The source stake account will be merged into the destination stake account. * Both accounts must share the same authorized staker/withdrawer and vote account. */ declare function makeMergeStakeAccountsTx(params: MakeMergeStakeAccountsTxParams): Promise; /** * Base params shared by every Gamma vault action. * `lpVault` is the vault state account (`LpVault`); its on-chain fields supply * the asset/share mints, the vault asset token account, and the fee recipient. * `tokenProgram` is auto-detected from the asset mint owner when omitted. */ interface VaultActionBaseParams { user: PublicKey; lpVault: PublicKey; connection: Connection; tokenProgram?: PublicKey; } interface VaultTxExtras { luts?: AddressLookupTableAccount[]; blockhash?: string; } /** `amount` is in raw base units of the vault's asset mint. */ interface MakeVaultDepositIxParams extends VaultActionBaseParams { amount: Amount; } interface MakeVaultDepositTxParams extends MakeVaultDepositIxParams, VaultTxExtras { } /** `sharesAmount` is in raw base units of the vault's share mint. */ interface MakeVaultWithdrawIxParams extends VaultActionBaseParams { sharesAmount: Amount; } interface MakeVaultWithdrawTxParams extends MakeVaultWithdrawIxParams, VaultTxExtras { } interface MakeVaultCompleteWithdrawalIxParams extends VaultActionBaseParams { } interface MakeVaultCompleteWithdrawalTxParams extends MakeVaultCompleteWithdrawalIxParams, VaultTxExtras { } /** * Zap-deposit: swap `inputMint` into the vault's asset mint, then deposit. * `inputAmount` is a UI amount of `inputMint`. */ interface MakeVaultDepositWithSwapTxParams extends VaultActionBaseParams, VaultTxExtras { inputMint: string; inputAmount: Amount; inputDecimals: number; swapOpts: SwapOpts; swapEngineRunner?: SwapEngineRunner; } /** Fetch and decode a Gamma `LpVault` account. Throws if it does not exist. */ declare function fetchGammaLpVault(connection: Connection, lpVault: PublicKey): Promise; /** * Fetch and decode a user's `WithdrawReceipt` for a Gamma LP vault. The receipt * is a singleton PDA per (user, vault) that tracks a queued withdrawal * (`pendingShares` awaiting keeper fulfillment → `claimableShares`/ * `claimableAssets` once fulfilled). Returns `null` when no account exists, * i.e. the user has no active withdrawal (the common case — withdrawals only * queue when the vault is temporarily illiquid). */ declare function fetchGammaWithdrawReceipt(connection: Connection, user: PublicKey, lpVault: PublicKey): Promise; /** * Resolve the SPL token program the vault's mints live under by reading the * asset mint's owner. The Gamma program uses a single `token_program` account * for both the asset and share mints, so one lookup is sufficient. */ declare function resolveVaultTokenProgram(connection: Connection, assetsMint: PublicKey): Promise; /** * Build the instruction to deposit into a Gamma LP vault. Instant deposit — * the user receives vault shares in the same transaction. The program creates * the user's share ATA and deposit receipt if they do not yet exist. * * `amount` is interpreted as raw base units of the vault's asset mint. */ declare function makeVaultDepositIx(params: MakeVaultDepositIxParams): Promise; /** Build a versioned transaction to deposit into a Gamma LP vault. */ declare function makeVaultDepositTx(params: MakeVaultDepositTxParams): Promise; /** * Zap-deposit into a Gamma LP vault: swap `inputMint` into the vault's asset * mint and deposit the swapped output — all in one transaction. Mirrors * `makeSwapCollateralTx`'s swap-engine composition, minus the flashloan/withdraw * parts (the input is wallet-funded, not borrowed). * * The deposit is sized from the swap's **minimum guaranteed output** * (`otherAmountThreshold`), so it can never exceed what the swap actually * yields; the small surplus stays in the wallet as dust. * * `inputAmount` is a UI amount of `inputMint`. */ declare function makeVaultDepositWithSwapTx(params: MakeVaultDepositWithSwapTxParams): Promise<{ transaction: ExtendedV0Transaction; quoteResponse: SwapQuoteResult; /** Minimum vault-asset amount received (UI units) — what gets deposited. */ destinationAmount: number; }>; /** * Build the instruction to initiate a withdrawal from a Gamma LP vault. Shares * are escrowed and a WithdrawReceipt is created/updated; the assets become * claimable via {@link makeVaultCompleteWithdrawalIx} once a keeper fulfills * the withdrawal. * * `sharesAmount` is interpreted as raw base units of the vault's share mint. */ declare function makeVaultWithdrawIx(params: MakeVaultWithdrawIxParams): Promise; /** Build a versioned transaction to initiate a withdrawal from a Gamma LP vault. */ declare function makeVaultWithdrawTx(params: MakeVaultWithdrawTxParams): Promise; /** * Build the instruction to claim assets from a fulfilled Gamma withdrawal. * Transfers the claimable assets from the escrow to the user's asset ATA * (created by the program if needed). */ declare function makeVaultCompleteWithdrawalIx(params: MakeVaultCompleteWithdrawalIxParams): Promise; /** Build a versioned transaction to claim a fulfilled Gamma withdrawal. */ declare function makeVaultCompleteWithdrawalTx(params: MakeVaultCompleteWithdrawalTxParams): Promise; /** * Temporary Module for Functions Pending Refactoring * * This file serves as a temporary staging area for utility functions that need proper * categorization and relocation to their appropriate service modules. All functions * placed here should include: * * IMPORTANT: Do not add new features to functions in this file. Instead, refactor * them to their proper location first, then implement new functionality. */ declare function bankMetadataMapToDto(bankMetadataMap: BankIntegrationMetadataMap): BankIntegrationMetadataMapDto; declare function dtoToBankMetadataMap(bankMetadataDto: BankIntegrationMetadataMapDto): BankIntegrationMetadataMap; declare function dtoToBankMetadata(bankMetadataDto: BankIntegrationMetadataDto): BankIntegrationMetadata; declare function bankMetadataToDto(bankMetadata: BankIntegrationMetadata): BankIntegrationMetadataDto; declare function fetchProgramForMints(connection: Connection, mintAddress: PublicKey[]): Promise<{ mint: PublicKey; program: PublicKey; }[]>; declare function chunkedGetRawMultipleAccountInfos(connection: Connection, pks: string[], batchChunkSize?: number, maxAccountsChunkSize?: number): Promise<[number, Map>]>; declare function chunkedGetRawMultipleAccountInfoOrderedWithNulls(connection: Connection, pks: string[], batchChunkSize?: number, maxAccountsChunkSize?: number): Promise | null>>; declare function chunkedGetRawMultipleAccountInfoOrdered(connection: Connection, pks: string[], batchChunkSize?: number, maxAccountsChunkSize?: number): Promise>>; type IntegrationType = "kamino" | "drift" | "juplend"; interface FetchBankIntegrationMetadataOptions { connection: Connection; banks: Bank[]; integrations?: IntegrationType[]; } /** * Fetch metadata from all enabled integrations and merge into single map * * This orchestrator: * 1. Fetches data from all specified integrations in parallel * 2. Merges results into a single BankIntegrationMetadataMap * 3. Each bank can have metadata from multiple integrations * * @param options - Connection, banks, and optional integration filter * @returns Combined metadata map keyed by bank address * * @example * ```typescript * const metadata = await fetchBankIntegrationMetadata({ * connection, * banks: allBanks, * integrations: ["kamino"], // Optional, defaults to all * }); * * // Access Kamino data for a specific bank * const kaminoData = metadata[bankAddress]?.kaminoStates; * ``` */ declare function fetchBankIntegrationMetadata(options: FetchBankIntegrationMetadataOptions): Promise; type KaminoStateJsonByBank = Record; type KaminoStateByBank = Record; interface KaminoMetadata { kaminoStates: { reserveState: KaminoReserve; obligationState: KaminoObligation; farmState?: KaminoFarmState; }; } interface FetchKaminoMetadataOptions { connection: Connection; banks: Bank[]; } interface KaminoBankInput { bankAddress: string; reserve: string; obligation: string; } /** * Fetch Kamino reserve, obligation, and farm states for banks with Kamino integration * * This function: * 1. Filters banks that have Kamino reserves/obligations * 2. Batch fetches all reserve and obligation data in one RPC call * 3. Decodes reserve and obligation states * 4. Identifies farms from reserve.farmCollateral addresses * 5. Batch fetches and decodes farm states in a second RPC call * 6. Returns a complete map keyed by bank address * * @param options - Connection and banks to fetch metadata for * @returns Map of bank addresses to their complete Kamino metadata (reserve, obligation, farm) */ declare function getKaminoMetadata(options: FetchKaminoMetadataOptions): Promise>; declare function getKaminoStatesDto(connection: Connection, kaminoBanks: KaminoBankInput[]): Promise; declare function getKaminoCTokenMultiplier(reserve: KaminoReserve): BigNumber$1; type DriftStateJsonByBank = Record; type DriftStateByBank = Record; interface DriftMetadata { driftStates: { spotMarketState: DriftSpotMarket; userState: DriftUser; userRewards: DriftRewards[]; }; } interface FetchDriftMetadataOptions { connection: Connection; banks: Bank[]; } interface DriftBankInput { bankAddress: string; spotMarket: string; user: string; userStats: string; } /** * Fetch Drift spot market, user, and rewards states for banks with Drift integration * * This function: * 1. Filters banks that have Drift integration accounts * 2. Batch fetches all spot market, user, and userStats data in one RPC call * 3. Decodes spot market and user states * 4. Fetches all required markets for reward calculation * 5. Calculates rewards for all banks * 6. Returns a complete map keyed by bank address * * @param options - Connection and banks to fetch metadata for * @returns Map of bank addresses to their complete Drift metadata (spot market, user, rewards) */ declare function getDriftMetadata(options: FetchDriftMetadataOptions): Promise>; declare function getDriftStatesDto(connection: Connection, driftBanks: DriftBankInput[]): Promise; declare function getDriftCTokenMultiplier(spotMarket: DriftSpotMarket): BigNumber$1; type JupLendStateJsonByBank = Record; type JupLendStateByBank = Record; interface JupLendMetadata { jupLendStates: { jupLendingState: JupLendingState; jupTokenReserveState: JupTokenReserve; jupRewardsRateModel: JupLendingRewardsRateModel | null; jupRateModel: JupRateModel | null; fTokenTotalSupply: BN; }; } interface FetchJupLendMetadataOptions { connection: Connection; banks: Bank[]; } interface JupLendBankInput { bankAddress: string; lendingState: string; } /** * Fetch JupLend Lending state, TokenReserve, and RewardsRateModel for banks with JupLend integration. * * This function: * 1. Filters banks that have JupLend integration accounts * 2. Batch fetches all Lending state accounts in one RPC call * 3. Decodes Lending states to extract TokenReserve and RewardsRateModel addresses * 4. Batch fetches TokenReserve and RewardsRateModel accounts in a second RPC call * 5. Returns a complete map keyed by bank address * * @param options - Connection and banks to fetch metadata for * @returns Map of bank addresses to their complete JupLend metadata */ declare function getJupLendMetadata(options: FetchJupLendMetadataOptions): Promise>; declare function getJupLendStatesDto(connection: Connection, jupLendBanks: JupLendBankInput[]): Promise; /** * Compute the fToken → native multiplier for a JupLend market. * Analogous to `getDriftCTokenMultiplier`. * * Formula: newExchangePrice / EXCHANGE_PRICES_PRECISION (1e12) * * Multiply the result by an fToken share amount to get the equivalent * native token amount (in lamports / base units). * * @param lendingState - The on-chain Lending account * @param tokenReserve - The on-chain TokenReserve account * @param rewardsModel - The on-chain LendingRewardsRateModel (or null) * @param fTokenTotalSupply - Total supply of the fToken mint (raw amount) * @param nowSeconds - Current unix timestamp in seconds * @returns Multiplier as BigNumber (e.g. 1.05 means 1 fToken = 1.05 native tokens) */ declare function getJupLendFTokenMultiplier(lendingState: JupLendingState, tokenReserve: JupTokenReserve, rewardsModel: JupLendingRewardsRateModel | null, fTokenTotalSupply: BN, nowSeconds: number): BigNumber$1; declare const Project0ConfigRaw: superstruct.Struct<{ group: string; program: string; label: "production" | "staging" | "staging-mainnet-clone" | "staging-alt"; }, { label: superstruct.Struct<"production" | "staging" | "staging-mainnet-clone" | "staging-alt", { production: "production"; staging: "staging"; "staging-mainnet-clone": "staging-mainnet-clone"; "staging-alt": "staging-alt"; }>; program: superstruct.Struct; group: superstruct.Struct; }>; type Project0ConfigRaw = Infer; declare const ConfigRaw: superstruct.Struct<{ group: string; program: string; label: "production" | "staging" | "staging-mainnet-clone" | "staging-alt"; }[], superstruct.Struct<{ group: string; program: string; label: "production" | "staging" | "staging-mainnet-clone" | "staging-alt"; }, { label: superstruct.Struct<"production" | "staging" | "staging-mainnet-clone" | "staging-alt", { production: "production"; staging: "staging"; "staging-mainnet-clone": "staging-mainnet-clone"; "staging-alt": "staging-alt"; }>; program: superstruct.Struct; group: superstruct.Struct; }>>; type ConfigRaw = Infer; /** * Retrieve config per environment */ declare function getConfig(environment?: Environment, overrides?: Partial>): Project0Config; /** * Error codes for transaction building failures */ declare enum TransactionBuildingErrorCode { SWAP_SIZE_EXCEEDED_LOOP = "SWAP_SIZE_EXCEEDED_LOOP", SWAP_SIZE_EXCEEDED_REPAY = "SWAP_SIZE_EXCEEDED_REPAY", SWAP_SIZE_EXCEEDED_POSITION_SWAP = "SWAP_SIZE_EXCEEDED_POSITION_SWAP", ORACLE_CRANK_FAILED = "ORACLE_CRANK_FAILED", KAMINO_RESERVE_NOT_FOUND = "KAMINO_RESERVE_NOT_FOUND", DRIFT_STATE_NOT_FOUND = "DRIFT_STATE_NOT_FOUND", JUPLEND_STATE_NOT_FOUND = "JUPLEND_STATE_NOT_FOUND", SWITCHBOARD_FEED_UPDATE_FAILED = "SWITCHBOARD_FEED_UPDATE_FAILED", SWAP_QUOTE_FAILED = "SWAP_QUOTE_FAILED", TRANSFER_POSITIONS_INVALID_SELECTION = "TRANSFER_POSITIONS_INVALID_SELECTION", TRANSFER_POSITIONS_UNSUPPORTED_BANK = "TRANSFER_POSITIONS_UNSUPPORTED_BANK", TRANSFER_POSITIONS_UNSPLITTABLE = "TRANSFER_POSITIONS_UNSPLITTABLE", BRIDGE_CONFLICT = "BRIDGE_CONFLICT" } /** * Typed details for each error code */ interface TransactionBuildingErrorDetails { [TransactionBuildingErrorCode.SWAP_SIZE_EXCEEDED_LOOP]: { bytes: number; accountKeys: number; provider?: string; }; [TransactionBuildingErrorCode.SWAP_SIZE_EXCEEDED_REPAY]: { bytes: number; accountKeys: number; provider?: string; }; [TransactionBuildingErrorCode.SWAP_SIZE_EXCEEDED_POSITION_SWAP]: { bytes: number; accountKeys: number; provider?: string; }; [TransactionBuildingErrorCode.ORACLE_CRANK_FAILED]: { uncrankableLiabilities: Array<{ bankAddress: string; mint: string; symbol?: string; reason: string; }>; uncrankableAssets: Array<{ bankAddress: string; mint: string; symbol?: string; reason: string; }>; }; [TransactionBuildingErrorCode.KAMINO_RESERVE_NOT_FOUND]: { bankAddress: string; bankMint: string; bankSymbol?: string; }; [TransactionBuildingErrorCode.DRIFT_STATE_NOT_FOUND]: { bankAddress: string; bankMint: string; bankSymbol?: string; }; [TransactionBuildingErrorCode.JUPLEND_STATE_NOT_FOUND]: { bankAddress: string; bankMint: string; bankSymbol?: string; }; [TransactionBuildingErrorCode.SWITCHBOARD_FEED_UPDATE_FAILED]: { oracleKeys: string[]; reason: string; }; [TransactionBuildingErrorCode.SWAP_QUOTE_FAILED]: { provider: string; inputMint: string; outputMint: string; reason: string; }; [TransactionBuildingErrorCode.TRANSFER_POSITIONS_INVALID_SELECTION]: { reason: string; bankAddresses: string[]; }; [TransactionBuildingErrorCode.TRANSFER_POSITIONS_UNSUPPORTED_BANK]: { bankAddress: string; assetTag: number; bankSymbol?: string; }; [TransactionBuildingErrorCode.TRANSFER_POSITIONS_UNSPLITTABLE]: { reason: string; sizeBytes?: number; accountCount?: number; }; [TransactionBuildingErrorCode.BRIDGE_CONFLICT]: { /** Bridge-token candidate banks blocked by an existing opposite-side account position. */ conflictingBanks: Array<{ bankAddress: string; mint: string; symbol?: string; }>; /** Whether the bridge token would have been held as collateral ("deposit") or debt ("borrow"). */ bridgeTokenSide: "deposit" | "borrow"; }; } /** * Error thrown during transaction building in the SDK. * Does NOT contain user-facing messages - those are handled in the app layer. * Use factory methods to create instances. */ declare class TransactionBuildingError extends Error { readonly code: T; readonly details: TransactionBuildingErrorDetails[T]; private constructor(); static swapSizeExceededLoop(bytes: number, accountKeys: number, provider?: string): TransactionBuildingError; static swapSizeExceededRepay(bytes: number, accountKeys: number, provider?: string): TransactionBuildingError; static swapSizeExceededPositionSwap(bytes: number, accountKeys: number, provider?: string): TransactionBuildingError; /** * Failed to crank oracles for one or more banks */ static oracleCrankFailed(uncrankableLiabilities: Array<{ bankAddress: string; mint: string; symbol?: string; reason: string; }>, uncrankableAssets: Array<{ bankAddress: string; mint: string; symbol?: string; reason: string; }>): TransactionBuildingError; /** * Failed to refresh reserves for a bank */ static kaminoReserveNotFound(bankAddress: string, bankMint: string, bankSymbol?: string): TransactionBuildingError; /** * Failed to find drift state for a bank */ static driftStateNotFound(bankAddress: string, bankMint: string, bankSymbol?: string): TransactionBuildingError; /** * Failed to find JupLend state for a bank */ static jupLendStateNotFound(bankAddress: string, bankMint: string, bankSymbol?: string): TransactionBuildingError; /** * Failed to update Switchboard price feeds */ static switchboardFeedUpdateFailed(oracleKeys: string[], reason: string): TransactionBuildingError; /** * Failed to get a swap quote from any provider */ static swapQuoteFailed(provider: string, inputMint: string, outputMint: string, reason: string): TransactionBuildingError; /** * The requested set of positions to transfer is invalid (inactive bank on the source, * destination overlap, capacity/slot conflict, group/authority mismatch, etc.). */ static transferPositionsInvalidSelection(reason: string, bankAddresses: string[]): TransactionBuildingError; /** * A selected position lives in a bank whose asset tag is not supported by transfer-positions * (v1 supports DEFAULT and STAKED only). */ static transferPositionsUnsupportedBank(bankAddress: string, assetTag: number, bankSymbol?: string): TransactionBuildingError; /** * The built transfer transaction exceeds the v0 size / account-lock limits even at the position * cap (most likely several integration positions whose reserve accounts overflow the 64-lock cap). * Retry with fewer positions in the selection. */ static transferPositionsUnsplittable(reason: string, sizeBytes?: number, accountCount?: number): TransactionBuildingError; /** * A bridged (double-hop) swap could not route because every bridge-token candidate bank * conflicts with an existing opposite-side position on the account (marginfi forbids holding an * asset and a liability on the same bank). */ static bridgeConflict(conflictingBanks: Array<{ bankAddress: string; mint: string; symbol?: string; }>, bridgeTokenSide: "deposit" | "borrow"): TransactionBuildingError; /** * Generic escape hatch for custom errors */ static custom(code: T, message: string, details: TransactionBuildingErrorDetails[T]): TransactionBuildingError; } /** * Whether a build failure is a *decomposable* swap failure — i.e. the single-route swap couldn't be * built (no route/quote, or the route doesn't fit the per-tx size/account limits), but the swap * could still succeed when split into two legs through a bridge token (a double-hop). * * This is the predicate a caller's catch→retry uses to decide whether to attempt a bridged swap * (see {@link composeBridgedSwap}). Size overflows surface as `SWAP_SIZE_EXCEEDED_*` and no-route / * unquotable failures as `SWAP_QUOTE_FAILED`; the swap engine also classifies an oversized route * (which would otherwise throw a raw serialization `RangeError`) as `SWAP_SIZE_EXCEEDED_LOOP`. */ declare function isDecomposableSwapError(e: unknown): e is TransactionBuildingError; /** * Whether a build failure is a bridged-swap conflict: the direct build failed AND every * bridge-token candidate was blocked by an existing opposite-side position on the account. * Narrows to the typed details (`conflictingBanks`, `bridgeTokenSide`) so callers can surface a * "close that position or pick a different pair" message. */ declare function isBridgeConflictError(e: unknown): e is TransactionBuildingError; declare const PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED: Buffer; declare const PDA_BANK_INSURANCE_VAULT_AUTH_SEED: Buffer; declare const PDA_BANK_FEE_VAULT_AUTH_SEED: Buffer; declare const PDA_BANK_LIQUIDITY_VAULT_SEED: Buffer; declare const PDA_BANK_INSURANCE_VAULT_SEED: Buffer; declare const PDA_BANK_FEE_VAULT_SEED: Buffer; declare const PDA_BANK_FEE_STATE_SEED: Buffer; declare const PDA_BANK_EMISSIONS_AUTH_SEED: Buffer; declare const PDA_BANK_EMISSIONS_VAULT_SEED: Buffer; declare const PDA_MARGINFI_ACCOUNT_SEED: Buffer; /** * Derives the liquidity vault authority PDA for a bank * Seeds: ["liquidity_vault_auth", bank] */ declare function deriveBankLiquidityVaultAuthority(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the liquidity vault PDA for a bank * Seeds: ["liquidity_vault", bank] */ declare function deriveBankLiquidityVault(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the insurance vault authority PDA for a bank * Seeds: ["insurance_vault_auth", bank] */ declare function deriveBankInsuranceVaultAuthority(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the insurance vault PDA for a bank * Seeds: ["insurance_vault", bank] */ declare function deriveBankInsuranceVault(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the fee vault authority PDA for a bank * Seeds: ["fee_vault_auth", bank] */ declare function deriveBankFeeVaultAuthority(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the fee vault PDA for a bank * Seeds: ["fee_vault", bank] */ declare function deriveBankFeeVault(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the fee state PDA * Seeds: ["feestate"] */ declare function deriveFeeState(programId: PublicKey): [PublicKey, number]; /** * Derives the emissions auth PDA for a bank * Seeds: ["emissions_auth_seed", bank] */ declare function deriveBankEmissionsAuth(programId: PublicKey, bank: PublicKey): [PublicKey, number]; /** * Derives the emissions vault PDA for a bank and emissions mint * Seeds: ["emissions_vault", bank, emissionsMint] */ declare function deriveBankEmissionsVault(programId: PublicKey, bank: PublicKey, emissionsMint: PublicKey): [PublicKey, number]; /** * Derives the marginfi account PDA * Seeds: ["marginfi_account", group, authority, accountIndex, thirdPartyId] */ declare function deriveMarginfiAccount(programId: PublicKey, group: PublicKey, authority: PublicKey, accountIndex: number, thirdPartyId?: number): [PublicKey, number]; /** * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies * * @param apy {Number} APY (i.e. 0.06 for 6%) * @param compoundingFrequency {Number} Compounding frequency (times a year) * @returns {Number} APR (i.e. 0.0582 for APY of 0.06) */ declare const apyToApr: (apy: number, compoundingFrequency?: number) => number; /** * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies * * * @param apr {Number} APR (i.e. 0.0582 for 5.82%) * @param compoundingFrequency {Number} Compounding frequency (times a year) * @returns {Number} APY (i.e. 0.06 for APR of 0.0582) */ declare const aprToApy: (apr: number, compoundingFrequency?: number, apyCap?: number) => number; declare function calculateInterestFromApy(principal: number, durationInYears: number, apy: number): number; declare function calculateApyFromInterest(principal: number, durationInYears: number, interest: number): number; declare function wrappedI80F48toBigNumber(wrapped: WrappedI80F48): BigNumber$1; declare function bigNumberToWrappedI80F48(value: Amount): WrappedI80F48; /** * Converts a ui representation of a token amount into its native value as `BN`, given the specified mint decimal amount (default to 6 for USDC). */ declare function toNumber(amount: Amount): number; /** * Converts a ui representation of a token amount into its native value as `BN`, given the specified mint decimal amount (default to 6 for USDC). */ declare function toBigNumber(amount: Amount | BN): BigNumber$1; /** * Converts a UI representation of a token amount into its native value as `BN`, given the specified mint decimal amount (default to 6 for USDC). */ declare function uiToNative(amount: Amount, decimals: number): BN; declare function uiToNativeBigNumber(amount: Amount, decimals: number): BigNumber$1; /** * Converts a native representation of a token amount into its UI value as `number`, given the specified mint decimal amount. */ declare function nativeToUi(amount: Amount | BN, decimals: number): number; declare function shortenAddress(pubkey: Address, chars?: number): string; /** * Converts basis points (bps) to a decimal percentage value. */ declare function bpsToPercentile(bps: number): number; /** * Prepares transaction remaining accounts by processing bank-oracle groups: * 1. Sorts groups in descending order by bank public key (pushes inactive accounts to end) * 2. Flattens the structure into a single public key array * * Stable on most JS implementations (this shouldn't matter since we do not generally have duplicate * banks), in place, and uses the raw 32-byte value to sort in byte-wise lexicographical order (like * Rust's b.key.cmp(&a.key)) * * @param banksAndOracles - Array where each element is a bank-oracle group: [bankPubkey, * oracle1Pubkey, oracle2Pubkey?, ...] Note: SystemProgram keys (111..111) * represent inactive accounts * @returns Flattened array of public keys with inactive accounts at the end, ready for transaction * composition */ declare const composeRemainingAccounts: (banksAndOracles: PublicKey[][]) => PublicKey[]; declare const PYTH_PUSH_ORACLE_ID: PublicKey; declare const PYTH_SPONSORED_SHARD_ID = 0; declare const MARGINFI_SPONSORED_SHARD_ID = 3301; declare const DEFAULT_ORACLE_MAX_AGE = 60; declare const ZERO_ORACLE_KEY = "DMhGWtLAKE5d56WdyHQxqeFncwUeqMEnuC2RvvZfbuur"; declare const PYTH_PRICE_CONF_INTERVALS: BigNumber$1; declare const SWB_PRICE_CONF_INTERVALS: BigNumber$1; declare const MAX_CONFIDENCE_INTERVAL_RATIO: BigNumber$1; declare const DISABLED_FLAG: number; declare const FLASHLOAN_ENABLED_FLAG: number; declare const TRANSFER_ACCOUNT_AUTHORITY_FLAG: number; /** Bank flags bit 9: staked oracle pricing is temporarily disabled */ declare const STAKED_ORACLE_DISABLED_FLAG: number; /** Bank flags bit 10: staked oracle pricing includes the SPL single-pool on-ramp in NAV */ declare const STAKED_ORACLE_USES_ONRAMP_FLAG: number; declare const MARGINFI_PROGRAM: PublicKey; declare const MARGINFI_PROGRAM_STAGING: PublicKey; declare const MARGINFI_PROGRAM_STAGING_ALT: PublicKey; /** * General LUT set per group: covers all banks except native-stake/isolated/reduce-only. * Used for any transaction that touches a non-(STAKED|SOL) bank. */ declare const ADDRESS_LOOKUP_TABLE_FOR_GROUP: { [key: string]: PublicKey[]; }; /** * Native-stake LUT set per group: native-stake banks + the canonical wSOL bank. * Used for transactions that only touch STAKED/SOL banks (native-stake accounts can * only supply native-stake positions and borrow SOL). Groups without an entry fall * back to the general set. */ declare const ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE: { [key: string]: PublicKey[]; }; declare const ADDRESS_LOOKUP_TABLE_FOR_SWAP: PublicKey; declare const JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX = 5; declare const JUPITER_V6_PROGRAM: PublicKey; declare const SINGLE_POOL_PROGRAM_ID: PublicKey; declare const STAKE_PROGRAM_ID: PublicKey; declare const MPL_METADATA_PROGRAM_ID: PublicKey; declare const SYSTEM_PROGRAM_ID: PublicKey; declare const SYSVAR_RENT_ID: PublicKey; declare const SYSVAR_CLOCK_ID: PublicKey; declare const SYSVAR_STAKE_HISTORY_ID: PublicKey; declare const STAKE_CONFIG_ID: PublicKey; declare const HOURS_PER_YEAR: number; declare const MAX_U64: string; declare const MAX_TX_SIZE: number; declare const MAX_ACCOUNT_LOCKS = 64; declare const BUNDLE_TX_SIZE: number; declare const PRIORITY_TX_SIZE: number; declare const WSOL_MINT: PublicKey; declare const LST_MINT: PublicKey; declare const USDC_MINT: PublicKey; declare const USDT_MINT: PublicKey; declare const USDC_DECIMALS = 6; declare class Balance implements BalanceType { active: boolean; bankPk: PublicKey; assetShares: BigNumber$1; liabilityShares: BigNumber$1; emissionsOutstanding: BigNumber$1; lastUpdate: number; constructor(active: boolean, bankPk: PublicKey, assetShares: BigNumber$1, liabilityShares: BigNumber$1, emissionsOutstanding: BigNumber$1, lastUpdate: number); static from(balanceRaw: BalanceRaw): Balance; static fromBalanceType(balance: BalanceType): Balance; static createEmpty(bankPk: PublicKey): Balance; computeUsdValue(bank: Bank, oraclePrice: OraclePrice, marginRequirement?: MarginRequirementType, assetShareValueMultiplier?: BigNumber$1, activeEmodeWeights?: { assetWeightInit: BigNumber$1; assetWeightMaint: BigNumber$1; }): { assets: BigNumber$1; liabilities: BigNumber$1; }; getUsdValueWithPriceBias(bank: Bank, oraclePrice: OraclePrice, marginRequirement?: MarginRequirementType, assetShareValueMultiplier?: BigNumber$1, activeEmodeWeights?: { assetWeightInit: BigNumber$1; assetWeightMaint: BigNumber$1; }): { assets: BigNumber$1; liabilities: BigNumber$1; }; computeQuantity(bank: Bank): { assets: BigNumber$1; liabilities: BigNumber$1; }; computeQuantityUi(bank: Bank, assetShareValueMultiplier?: BigNumber$1): { assets: BigNumber$1; liabilities: BigNumber$1; }; computeTotalOutstandingEmissions(bank: Bank): BigNumber$1; computeClaimedEmissions(bank: Bank, currentTimestamp: number): BigNumber$1; } declare class MarginfiGroup implements MarginfiGroupType { address: PublicKey; admin: PublicKey; /** Group-level net-outflow rate limiter (USD windows); see isGroupRateLimiterEnabled */ rateLimiter?: BankRateLimiterType; constructor(admin: PublicKey, address: PublicKey, rateLimiter?: BankRateLimiterType); static fetch(address: PublicKey, program: MarginfiProgram): Promise; /** * Fetch all banks belonging to this group * * @param program - The Marginfi program instance * @param feedIdMap - Optional Pyth feed ID map for oracle configuration * @returns Array of Bank instances for this group */ fetchBanks(program: MarginfiProgram): Promise; static fromAccountParsed(address: PublicKey, accountData: MarginfiGroupRaw): MarginfiGroup; static fromBuffer(address: PublicKey, rawData: Buffer, idl: MarginfiIdlType): MarginfiGroup; static decode(encoded: Buffer, idl: MarginfiIdlType): MarginfiGroupRaw; static encode(decoded: MarginfiGroupRaw, idl: MarginfiIdlType): Promise; makePoolConfigureBankIx(program: MarginfiProgram, bank: PublicKey, args: BankConfigOptRaw): Promise; makeAddPermissionlessStakedBankIx(program: MarginfiProgram, voteAccountAddress: PublicKey, feePayer: PublicKey, pythOracle: PublicKey): Promise; makePoolAddBankIx(program: MarginfiProgram, bankPubkey: PublicKey, bankMint: PublicKey, bankConfig: BankConfigOpt, feePayer?: PublicKey): Promise; } declare class HealthCache implements HealthCacheType { assetValue: BigNumber$1; liabilityValue: BigNumber$1; assetValueMaint: BigNumber$1; liabilityValueMaint: BigNumber$1; assetValueEquity: BigNumber$1; liabilityValueEquity: BigNumber$1; timestamp: BigNumber$1; flags: HealthCacheFlags[]; prices: number[][]; simulationStatus: HealthCacheStatus; constructor(assetValue: BigNumber$1, liabilityValue: BigNumber$1, assetValueMaint: BigNumber$1, liabilityValueMaint: BigNumber$1, assetValueEquity: BigNumber$1, liabilityValueEquity: BigNumber$1, timestamp: BigNumber$1, flags: HealthCacheFlags[], prices: number[][], simulationStatus: HealthCacheStatus); static fromHealthCacheType(healthCacheType: HealthCacheType): HealthCache; static from(healthCacheRaw: HealthCacheRaw): HealthCache; } declare class MarginfiAccount implements MarginfiAccountType { readonly address: PublicKey; readonly group: PublicKey; readonly authority: PublicKey; readonly balances: Balance[]; readonly accountFlags: AccountFlags[]; readonly emissionsDestinationAccount: PublicKey; healthCache: HealthCache; constructor(address: PublicKey, group: PublicKey, authority: PublicKey, balances: Balance[], accountFlags: AccountFlags[], emissionsDestinationAccount: PublicKey, healthCache: HealthCache); /** * Fetches a marginfi account from on-chain data. * * @param address - The public key of the marginfi account * @param program - The Marginfi program instance * * @returns Promise resolving to a MarginfiAccount instance */ static fetch(address: PublicKey, program: MarginfiProgram): Promise; static decodeAccountRaw(encoded: Buffer, idl: MarginfiIdlType): MarginfiAccountRaw; static fromAccountType(account: MarginfiAccountType): MarginfiAccount; /** * Creates a MarginfiAccount instance from parsed account data. * * @param marginfiAccountPk - The public key of the marginfi account * @param accountData - The raw account data from the program * * @returns A new MarginfiAccount instance */ static fromAccountParsed(marginfiAccountPk: PublicKey, accountData: MarginfiAccountRaw): MarginfiAccount; /** * Simulates and updates the health cache for this account. * * Fetches current oracle prices and computes fresh health values. Returns a new * account instance with updated health cache (does not mutate this instance). * * @param params - Configuration for health cache simulation (excluding marginfiAccount) * @returns Object containing the updated account and any errors */ simulateHealthCache(params: Omit): Promise<{ account: MarginfiAccount; error: HealthCacheSimulationError | undefined; }>; static fromAccountDataRaw(marginfiAccountPk: PublicKey, rawData: Buffer, idl: MarginfiIdlType): MarginfiAccount; /** * Gets all balances that are currently active (non-zero). * * @returns Array of active Balance instances */ get activeBalances(): Balance[]; /** * Gets the balance for a specific bank. * * @param bankPk - The public key of the bank * * @returns The Balance instance for the bank (may be empty) */ getBalance(bankPk: PublicKey): Balance; /** * Checks if the account is disabled. * * @returns True if the account is disabled, false otherwise */ get isDisabled(): boolean; /** * Checks if the account is currently in a flash loan. * * @returns True if a flash loan is active, false otherwise */ get isFlashLoanEnabled(): boolean; /** * Checks if account authority transfer is enabled. * * @returns True if authority transfer is allowed, false otherwise */ get isTransferAccountAuthorityEnabled(): boolean; /** * Sets the health cache for this account. * * Note: This mutates the account instance. Consider using simulateHealthCache() * for a pure functional approach that returns a new account instance. * * @param value - The new health cache to set */ setHealthCache(value: HealthCache): void; /** * Computes free collateral using cached health values. * * Free collateral represents the amount of collateral that is not backing any liabilities. * * @param opts - Optional configuration * @param opts.clamped - If true, clamps negative values to zero * * @returns The free collateral amount in USD */ computeFreeCollateralFromCache(opts?: { clamped?: boolean; }): BigNumber$1; /** * Computes free collateral from balances using Initial margin requirements. * * Free collateral represents the amount of value available for new borrows or withdrawals. * By default, negative values are clamped to zero. * * @param params - Configuration for free collateral computation (excluding activeBalances) * @returns Free collateral value in USD (clamped to zero by default) */ computeFreeCollateralFromBalances(params: Omit): BigNumber$1; /** * Computes health components using cached health values. * * Returns weighted asset and liability values based on the margin requirement type. * * @param marginReqType - The margin requirement type (Initial, Maintenance, or Equity) * * @returns Object containing assets and liabilities values in USD */ computeHealthComponentsFromCache(marginRequirement: MarginRequirementType): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Computes health components from balances with price bias. * * Returns weighted asset and liability values using conservative pricing * (Lowest for assets, Highest for liabilities). * * @param params - Configuration for health computation (excluding activeBalances) * @returns Object containing assets and liabilities values in USD */ computeHealthComponentsFromBalances(params: Omit): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Computes the total account value (equity). * * Account value is calculated as total assets minus total liabilities. * * @returns The account value in USD */ computeAccountValue(): BigNumber$1; /** * Computes the net APY (Annual Percentage Yield) for this account. * * The net APY represents the combined annualized return from all lending and borrowing * positions, weighted by their USD values. * * @param params - Configuration for net APY computation (excluding marginfiAccount and activeBalances) * @returns The net APY as a decimal (e.g., 0.05 = 5%) */ computeNetApy(params: Omit): number; /** * Calculates the maximum amount that can be borrowed from a bank. * * Takes into account: * - Free collateral available * - Existing deposits in the bank * - Risk weights and oracle prices * - E-mode configurations if applicable * * @param params - Configuration for max borrow computation (excluding account) * @returns Maximum borrowable amount in UI units * * @remarks * NOTE FOR LIQUIDATORS: This function doesn't account for collateral received when liquidating. * * @see {@link computeMaxBorrowForBank} for implementation details */ computeMaxBorrowForBank(params: Omit): BigNumber$1; /** * Calculates the maximum amount that can be withdrawn from a bank without borrowing. * * Ensures the account remains healthy after withdrawal by checking collateral requirements. * * @param params - Configuration for max withdraw computation (excluding account) * @returns Maximum withdrawable amount in UI units * * @see {@link computeMaxWithdrawForBank} for implementation details */ computeMaxWithdrawForBank(params: Omit): BigNumber$1; /** * Calculates the maximum amount that can be deposited into a bank. * * Deposits are not constrained by account health, only by the bank's remaining deposit cap * and (optionally) the wallet balance. * * @param params - Configuration for max deposit computation * @returns Maximum depositable amount in UI units * * @see {@link computeMaxDepositForBank} for implementation details */ computeMaxDepositForBank(params: ComputeMaxDepositForBankParams): BigNumber$1; /** * Gets the banks required for health check calculations. * * Returns banks that have active balances, plus any mandatory banks, minus excluded banks. * * @param banks - Map of all available banks * @param mandatoryBanks - Banks to always include * @param excludedBanks - Banks to exclude * * @returns Array of banks needed for health checks */ getHealthCheckAccounts(banks: Map, mandatoryBanks?: PublicKey[], excludedBanks?: PublicKey[]): BankType[]; /** * Determines which E-mode pairs are currently active for this account. * * E-mode (Efficiency Mode) allows for higher leverage when borrowing and lending * related assets (e.g., different stablecoins). * * @param emodePairs - All available E-mode pairs to check * * @returns Array of active E-mode pairs, or empty array if no E-mode is active */ computeActiveEmodePairs(emodePairs: EmodePair[]): EmodePair[]; /** * Calculates how different actions would affect E-mode status. * * For each bank, simulates: * - Borrowing (for banks not currently borrowed from) * - Supplying (for supported collateral banks) * - Repaying (for banks with active liabilities) * - Withdrawing (for banks with active collateral) * * @param emodePairs - All available E-mode pairs * @param banks - Array of bank PublicKeys to analyze * * @returns Object mapping bank addresses to their action impact analysis */ computeEmodeImpacts(emodePairs: EmodePair[], banks: PublicKey[]): Record; /** * Creates a deposit instruction for this marginfi account. * * @param params - Deposit instruction parameters * @returns Promise resolving to InstructionsWrapper containing the deposit instructions * * @see {@link makeDepositIx} for detailed implementation and additional options */ makeDepositIx(params: Omit): Promise; /** * Creates a repay instruction for this marginfi account. * * @param params - Repay instruction parameters * @returns Promise resolving to InstructionsWrapper containing the repay instructions * * @see {@link makeRepayIx} for detailed implementation */ makeRepayIx(params: Omit): Promise; /** * Creates a withdraw instruction for this marginfi account. * * @param params - Withdraw instruction parameters * @returns Promise resolving to InstructionsWrapper containing the withdraw instructions * * @see {@link makeWithdrawIx} for detailed implementation */ makeWithdrawIx(params: Omit): Promise; /** * Creates a borrow instruction for this marginfi account. * * @param params - Borrow instruction parameters * @returns Promise resolving to InstructionsWrapper containing the borrow instructions * * @see {@link makeBorrowIx} for detailed implementation */ makeBorrowIx(params: Omit): Promise; /** * Creates an instruction to begin a flash loan. * * Flash loans allow borrowing assets within a single transaction, which must be * repaid before the transaction completes. * * @param params - Begin flash loan instruction parameters * @returns Promise resolving to InstructionsWrapper containing the begin flash loan instruction * * @see {@link makeBeginFlashLoanIx} for implementation */ makeBeginFlashLoanIx(program: MarginfiProgram, endIndex: number, authority?: PublicKey): Promise; /** * Creates an instruction to end a flash loan. * * Validates that all required banks are available and constructs the end flash loan * instruction with proper health checks. * * @param program - The Marginfi program instance * @param bankMap - Map of all available banks * @param projectedActiveBanks - Banks that will be active after the flash loan * @param authority - Optional authority override (defaults to account authority) * * @returns Promise resolving to InstructionsWrapper containing the end flash loan instruction * * @throws {Error} If any projected active bank is not found in bankMap * * @see {@link makeEndFlashLoanIx} for implementation */ makeEndFlashLoanIx(program: MarginfiProgram, bankMap: Map, projectedActiveBanks: PublicKey[], authority?: PublicKey): Promise; /** * Builds a transaction to transfer this account to a new authority. * * Thin wrapper over the {@link makeAccountTransferToNewAccountTx} action, * injecting the connection and this account from context. The global fee * wallet is derived inside the action from the program's fee state. * * @param program - The Marginfi program instance * @param newMarginfiAccount - Freshly generated keypair for the destination account * @param newAuthority - The new authority public key * @param feePayer - Optional `PublicKey` (adapter-signed) or `Keypair` (separate * payer); defaults to this account's authority * * @returns Promise resolving to the transfer transaction */ makeAccountTransferToNewAccountTx(program: MarginfiProgram, newMarginfiAccount: Keypair, newAuthority: PublicKey, feePayer?: PublicKey | Keypair): Promise; /** * Creates an instruction to close this marginfi account. * * Closes the account and returns rent to the fee payer. The account must have * no active balances before closing. * * @param program - The Marginfi program instance * * @returns Promise resolving to InstructionsWrapper containing the close account instruction * * @see {@link makeCloseAccountIx} for implementation */ makeCloseAccountIx(program: MarginfiProgram): Promise; /** * Creates an instruction to update the account's health cache. * * Pulses the health of the account to ensure the cached health values are current. * * @param program - The Marginfi program instance * @param banks - Map of all available banks * @param mandatoryBanks - Banks that must be included in health calculation * @param excludedBanks - Banks to exclude from health calculation * * @returns Promise resolving to InstructionsWrapper containing the pulse health instruction * * @see {@link makePulseHealthIx} for implementation */ makePulseHealthIx(program: MarginfiProgram, banks: Map, mandatoryBanks: PublicKey[], excludedBanks: PublicKey[]): Promise<{ instructions: TransactionInstruction[]; keys: never[]; }>; /** * Computes which banks will be active after executing the given instructions. * * Analyzes transaction instructions to determine which banks will have active * balances, without making CPI calls. * * @param program - The Marginfi program instance * @param instructions - Transaction instructions to analyze * * @returns Array of PublicKeys for banks that will be active * * @see {@link computeProjectedActiveBanksNoCpi} for implementation */ computeProjectedActiveBanksNoCpi(program: MarginfiProgram, instructions: TransactionInstruction[]): PublicKey[]; /** * Computes projected active balances after executing the given instructions. * * Simulates the effect of instructions on account balances without making CPI calls. * Returns the projected balances and which banks will be impacted. * * @param program - The Marginfi program instance * @param instructions - Transaction instructions to simulate * @param bankMap - Map of all available banks * * @returns Object containing projected balances and impacted banks * * @see {@link computeProjectedActiveBalancesNoCpi} for implementation */ computeProjectedActiveBalancesNoCpi(program: MarginfiProgram, instructions: TransactionInstruction[], banksMap: Map, assetShareValueMultiplierByBank: Map): { projectedBalances: Balance[]; impactedAssetsBanks: string[]; impactedLiabilityBanks: string[]; }; /** * Wraps an instruction with SOL wrapping and unwrapping instructions. * * Useful for instructions that need native SOL to be converted to wSOL. * Automatically unwraps wSOL back to SOL after the instruction executes. * * @param ix - The instruction to wrap * @param amount - The amount of SOL to wrap (defaults to 0) * * @returns Array of instructions: [wrap SOL, original instruction, unwrap SOL] * * @see {@link makeWrapSolIxs} and {@link makeUnwrapSolIx} for wrap/unwrap implementation */ wrapInstructionForWSol(ix: TransactionInstruction, amount?: Amount): TransactionInstruction[]; /** * Creates a loop transaction to leverage a position. * * A loop transaction: * 1. Deposits initial collateral (if in DEPOSIT mode) * 2. Borrows assets via flashloan * 3. Swaps borrowed assets to deposit asset (via Jupiter) * 4. Deposits swapped assets as additional collateral * * This creates a leveraged position by recursively depositing and borrowing. * * @param params - Loop transaction parameters * @param params.connection - Solana connection instance * @param params.oraclePrices - Map of current oracle prices * @param params.depositOpts - Deposit configuration (bank, amount, mode) * @param params.borrowOpts - Borrow configuration (bank, amount) * @param params.swapOpts - Swap configuration (venue, slippage, fees) * @param params.addressLookupTableAccounts - Address lookup tables * @param params.overrideInferAccounts - Optional account overrides * @param params.additionalIxs - Additional instructions to include * @param params.crossbarUrl - Crossbar URL for oracle updates * * @returns Object containing transactions array, action index, and swap quote * * @throws {TransactionBuildingError} If swap exceeds transaction size limits * * @see {@link makeLoopTx} for detailed implementation */ makeLoopTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Atomically move a selected set of positions from this account to a destination account * (same authority, same group) using flashloans, auto-splitting across transactions as needed. * * @see {@link makeTransferPositionsTx} for detailed implementation */ makeTransferPositionsTx(params: Omit): Promise; /** * Creates a loop transaction with a transparent bridged (double-hop) fallback. * * One call: tries the direct {@link makeLoopTx} first; if its borrow→deposit swap can't fit one * transaction (size / account-locks) or has no route, it loops the deposit asset against a * value-equivalent borrow of a high-liquidity bridge token, then debt-swaps the bridge debt to * the requested borrow asset — both legs composed into ONE atomic Jito bundle. * * Bridge candidates default to USDC → wSOL → USDT and can be reordered/overridden via * `params.bridgeOpts.bridgeCandidateMints`; `bridgeOpts` also accepts known token programs (skips RPC * lookups), a bundle-size ceiling, and an abort signal. `result.bridgeMint` is set only when the * bridged path was used. * * Intended for existing accounts — a fresh account's loop fits the direct path, so flows that * create the account in the same action should call {@link makeLoopTx} directly. * * @param params - Loop transaction parameters plus optional `bridgeOpts` * @returns Object containing transactions, action index, merged swap quote, and the bridge mint * * @see {@link makeBridgedLoopTx} for detailed implementation */ makeBridgedLoopTx(params: Omit): Promise; /** * Creates a collateral-swap transaction with a transparent bridged (double-hop) fallback. * * One call: tries the direct {@link makeSwapCollateralTx} first; if the swap `A → C` can't fit * one transaction or has no route, it decomposes into `A → bridge` + `bridge → C` through a * high-liquidity bridge collateral, both legs composed into ONE atomic Jito bundle. See * {@link makeBridgedLoopTx} for the `bridgeOpts` knobs. * * @param params - Swap collateral transaction parameters plus optional `bridgeOpts` * @returns Object containing transactions, action index, merged swap quote, and the bridge mint * * @see {@link makeBridgedSwapCollateralTx} for detailed implementation */ makeBridgedSwapCollateralTx(params: Omit): Promise; /** * Creates a debt-swap transaction with a transparent bridged (double-hop) fallback. * * One call: tries the direct {@link makeSwapDebtTx} first; if the swap `A → C` can't fit one * transaction or has no route, the first leg repays A by borrowing a bridge token and the second * leg repays exactly that bridge debt while borrowing C — both legs composed into ONE atomic * Jito bundle. See {@link makeBridgedLoopTx} for the `bridgeOpts` knobs. * * @param params - Swap debt transaction parameters plus optional `bridgeOpts` * @returns Object containing transactions, action index, merged swap quote, and the bridge mint * * @see {@link makeBridgedSwapDebtTx} for detailed implementation */ makeBridgedSwapDebtTx(params: Omit): Promise; /** * Creates a transaction to repay debt using collateral. * * A repay with collateral transaction: * 1. Withdraws collateral from the account via flashloan * 2. Swaps collateral to debt asset (via Jupiter) * 3. Repays the debt with swapped assets * * This allows users to close or reduce positions without external funds. * * @param params - Repay with collateral transaction parameters * @param params.connection - Solana connection instance * @param params.oraclePrices - Map of current oracle prices * @param params.withdrawOpts - Withdraw configuration (bank, amount) * @param params.repayOpts - Repay configuration (bank, optional amount) * @param params.swapOpts - Swap configuration (venue, slippage, fees) * @param params.addressLookupTableAccounts - Address lookup tables * @param params.overrideInferAccounts - Optional account overrides * @param params.additionalIxs - Additional instructions to include * @param params.crossbarUrl - Crossbar URL for oracle updates * * @returns Object containing transactions array, action index, and swap details * * @throws {TransactionBuildingError} If swap exceeds transaction size limits * @throws {TransactionBuildingError} If Kamino reserve not found * * @see {@link makeRepayWithCollatTx} for detailed implementation */ makeRepayWithCollatTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; swapQuote: SwapQuoteResult | undefined; amountToRepay: number; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Creates a transaction to swap one collateral position to another using a flash loan. * * A swap collateral transaction: * 1. Withdraws existing collateral via flash loan * 2. Swaps collateral to new asset (via Jupiter) * 3. Deposits swapped assets as new collateral * * This allows users to change their collateral type (e.g., JitoSOL -> mSOL) without * withdrawing and affecting their health during the swap. * * @param params - Swap collateral transaction parameters * @param params.connection - Solana connection instance * @param params.oraclePrices - Map of current oracle prices * @param params.withdrawOpts - Withdraw configuration (bank, amount, tokenProgram) * @param params.depositOpts - Deposit configuration (bank, tokenProgram) * @param params.swapOpts - Swap configuration (venue, slippage, fees) * @param params.addressLookupTableAccounts - Address lookup tables * @param params.overrideInferAccounts - Optional account overrides * @param params.additionalIxs - Additional instructions to include * @param params.crossbarUrl - Crossbar URL for oracle updates * * @returns Object containing transactions array, action index, and swap quote * * @throws {TransactionBuildingError} If swap exceeds transaction size limits * @throws {TransactionBuildingError} If Kamino reserve not found * * @see {@link makeSwapCollateralTx} for detailed implementation */ makeSwapCollateralTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Creates a transaction to roll a matured Exponent PT collateral position into its * next-maturity PT, in one flash-loan-wrapped bundle * (withdraw PT_old → `wrapper_merge` to base → swap-engine buy PT_new → deposit). * See {@link makeRollPtTx}. * * @param params - Roll-PT parameters (`withdrawOpts`/`depositOpts`/`swapOpts`/`rollOpts`). */ makeRollPtTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; }>; /** * Creates a transaction to swap one debt position to another using a flash loan. * * A swap debt transaction: * 1. Borrows new asset via flash loan (new debt) * 2. Swaps new asset to old debt asset (via Jupiter) * 3. Repays old debt with swapped assets * * This allows users to change their debt type (e.g., USDC debt -> SOL debt) without * repaying and affecting their health during the swap. * * @param params - Swap debt transaction parameters * @param params.connection - Solana connection instance * @param params.oraclePrices - Map of current oracle prices * @param params.repayOpts - Repay configuration (bank, amount, tokenProgram) * @param params.borrowOpts - Borrow configuration (bank, tokenProgram) * @param params.swapOpts - Swap configuration (venue, slippage, fees) * @param params.addressLookupTableAccounts - Address lookup tables * @param params.overrideInferAccounts - Optional account overrides * @param params.additionalIxs - Additional instructions to include * @param params.crossbarUrl - Crossbar URL for oracle updates * * @returns Object containing transactions array, action index, and swap quote * * @throws {TransactionBuildingError} If swap exceeds transaction size limits * * @see {@link makeSwapDebtTx} for detailed implementation */ makeSwapDebtTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Creates a deposit transaction. * * @param params - Parameters for the deposit transaction * @returns Promise resolving to an ExtendedTransaction * * @see {@link makeDepositTx} for detailed implementation */ makeDepositTx(params: Omit): Promise; /** * Creates a Drift deposit transaction. * * @param params - Parameters for the Drift deposit transaction * @returns Promise resolving to an ExtendedV0Transaction * * @see {@link makeDriftDepositTx} for detailed implementation */ makeDriftDepositTx(params: Omit): Promise; /** * Creates a Kamino deposit transaction. * * @param params - Parameters for the Kamino deposit transaction * @returns Promise resolving to an ExtendedV0Transaction * * @see {@link makeKaminoDepositTx} for detailed implementation */ makeKaminoDepositTx(params: Omit): Promise; /** * Creates a borrow transaction. * * @param params - Parameters for the borrow transaction * @returns Promise resolving to a TransactionBuilderResult * * @see {@link makeBorrowTx} for detailed implementation */ makeBorrowTx(params: Omit): Promise; /** * Creates a repay transaction. * * @param params - Parameters for the repay transaction * @returns Promise resolving to an ExtendedTransaction * * @see {@link makeRepayTx} for detailed implementation */ makeRepayTx(params: Omit): Promise; /** * Creates a withdraw transaction. * * @param params - Parameters for the withdraw transaction * @returns Promise resolving to a TransactionBuilderResult * * @see {@link makeWithdrawTx} for detailed implementation */ makeWithdrawTx(params: Omit): Promise; /** * Creates a Drift withdraw transaction. * * @param params - Parameters for the Drift withdraw transaction * @returns Promise resolving to an ExtendedV0Transaction * * @see {@link makeDriftWithdrawTx} for detailed implementation */ makeDriftWithdrawTx(params: Omit): Promise; /** * Creates a Kamino withdraw transaction. * * @param params - Parameters for the Kamino withdraw transaction * @returns Promise resolving to a TransactionBuilderResult * * @see {@link makeKaminoWithdrawTx} for detailed implementation */ makeKaminoWithdrawTx(params: Omit): Promise; /** * Creates a flash loan transaction. * * @param params - Parameters for the flash loan transaction * @returns Promise resolving to flash loan transaction details * * @see {@link makeFlashLoanTx} for detailed implementation */ makeFlashLoanTx(params: Omit): Promise<_solana_web3_js.VersionedTransaction & ExtendedTransactionProperties>; } /** * An authority's active balance in a specific bank for a queried mint. One row per * (account, bank): a single account can appear multiple times if it holds the mint across * several banks (e.g. a DEFAULT and a Kamino bank for the same mint). Amounts are in UI units * (token decimals + share multiplier applied). */ type MintAuthorityBalance = { authority: PublicKey; accountAddress: PublicKey; bank: PublicKey; assets: BigNumber$1; liabilities: BigNumber$1; }; declare class Project0Client { readonly program: MarginfiProgram; readonly group: MarginfiGroup; readonly bankMap: Map; readonly bankIntegrationMap: BankIntegrationMetadataMap; readonly assetShareValueMultiplierByBank: Map; readonly oraclePriceByBank: Map; readonly mintDataByBank: Map; /** * Combined LUT set (general group followed by native-stake group). The functional * action builders partition this and embed the right subset per transaction via * `selectLutsForBanks`, so consumers only ever pass this one array. */ readonly addressLookupTables: AddressLookupTableAccount[]; readonly emodePairs: EmodePair[]; constructor(program: MarginfiProgram, group: MarginfiGroup, bankMap: Map, bankIntegrationMap: BankIntegrationMetadataMap, assetShareValueMultiplierByBank: Map, oraclePriceByBank: Map, mintDataByBank: Map, /** * Combined LUT set (general group followed by native-stake group). The functional * action builders partition this and embed the right subset per transaction via * `selectLutsForBanks`, so consumers only ever pass this one array. */ addressLookupTables: AddressLookupTableAccount[], emodePairs: EmodePair[]); /** * Gets all banks as an array. * Useful when you need to iterate over all banks. */ get banks(): Bank[]; /** * Gets a bank by its address. */ getBank(address: PublicKey): Bank | undefined; /** * Gets all banks matching the mint address. * * @param mint - The mint address to search for * @param assetTag - Optional asset tag to filter by (e.g., AssetTag.DEFAULT, AssetTag.KAMINO) * @returns Array of all matching banks (empty array if none found) * * @example * // Get all SOL banks * const allSolBanks = client.getBanksByMint(MINTS.SOL); * * // Get all Kamino SOL banks (may be multiple) * const kaminoBanks = client.getBanksByMint(MINTS.SOL, AssetTag.KAMINO); * console.log(`Found ${kaminoBanks.length} Kamino SOL banks`); * * // Iterate through all matching banks * kaminoBanks.forEach((bank) => { * console.log(`Bank: ${bank.address.toBase58()}`); * }); */ getBanksByMint(mint: PublicKey, assetTag?: AssetTag): Bank[]; /** * Creates a transaction to initialize a new marginfi account. * * @param authority - The authority public key for the new account * @param accountIndex - The account index (default: 0) * @param thirdPartyId - Optional third party identifier * @returns A transaction ready to be signed and sent */ createMarginfiAccountTx(authority: PublicKey, accountIndex?: number, thirdPartyId?: number): Promise; /** * Creates a marginfi account instruction with a projected account wrapper. * * Returns a wrapped account instance that can be used for building transactions * before the account actually exists on-chain. Useful for composing multiple * operations including account creation in a single flow. * * @param authority - The authority public key for the new account * @param accountIndex - The account index (default: 0) * @param thirdPartyId - Optional third party identifier * @returns Object containing the wrapped account and creation instruction */ createMarginfiAccountWithProjection(authority: PublicKey, accountIndex?: number, thirdPartyId?: number): Promise<{ wrappedAccount: MarginfiAccountWrapper; ix: _solana_web3_js.TransactionInstruction; }>; /** * Fetches all marginfi account addresses for a given authority (wallet). * * This is useful for account discovery - finding all accounts that belong to a wallet. * * @param authority - The wallet public key to search for * @returns Array of account addresses owned by the authority */ getAccountAddresses(authority: PublicKey): Promise; /** * Fetches the addresses of all marginfi accounts in the group that hold a position in a * specific bank. * * Because a marginfi account holds up to 16 balance slots (sorted descending by bank, so the * target can be at any slot), this scans all 16 slots in parallel via filtered * `getProgramAccounts` calls. It returns only addresses (no account data is transferred), * which keeps it viable across the group's ~500k accounts. Hydrate any address you care about * with `fetchAccount`. * * @param bank - The bank public key to search for in account balances * @param options - Optional settings: * - `concurrency`: max number of the 16 slot scans to run at once. Omit to fire all 16 in * parallel; pass a smaller value (e.g. 4) to batch them and avoid RPC rate limits. * @returns Deduplicated array of account addresses holding the bank */ getAccountAddressesHoldingBank(bank: PublicKey, options?: { concurrency?: number; }): Promise; /** * Fetches every account's active balance for a given mint, with its authority, account * address, and the deposited/borrowed amounts in UI units. * * A mint can map to multiple banks (e.g. DEFAULT + Kamino), so this resolves all matching * banks via {@link getBanksByMint}, scans each for accounts holding it, and emits one row per * (account, bank). An account that holds the mint in several banks yields several rows. * * Amounts are computed with each bank's share multiplier (`assetShareValueMultiplierByBank`) * and the bank's mint decimals, matching `Balance.computeQuantityUi`. * * @param mint - The mint to search account balances for * @param options - Optional settings: * - `assetTag`: restrict to banks with this asset tag (e.g. only Kamino banks for the mint) * - `concurrency`: max number of the 16 slot scans to run at once per bank (see * {@link getAccountAddressesHoldingBank}) * @returns One row per (account, bank) holding the mint */ getAuthorityBalancesForMint(mint: PublicKey, options?: { assetTag?: AssetTag; concurrency?: number; }): Promise; /** * Fetches and wraps a marginfi account in one call. * * This is a convenience method that combines fetching the account data * and wrapping it for easier use. Equivalent to: * ```typescript * const account = await MarginfiAccount.fetch(address, client.program); * const wrapped = new MarginfiAccountWrapper(account, client); * ``` * * @param accountAddress - The public key of the marginfi account * @returns A wrapped account ready to use */ fetchAccount(accountAddress: PublicKey, skipHealthCache?: boolean): Promise; static initialize(connection: Connection, config: Project0Config): Promise; } /** * Wrapper around MarginfiAccount that auto-injects client data for cleaner API. * * Instead of: * await account.makeDepositIx(program, banks, mintDatas, amount, bankAddress) * * Use: * await wrappedAccount.makeDepositIx(amount, bankAddress) * * The wrapper handles all the boilerplate of looking up banks, mint data, etc. */ declare class MarginfiAccountWrapper { private readonly account; private readonly client; constructor(account: MarginfiAccount, client: Project0Client); get address(): PublicKey; get group(): PublicKey; get authority(): PublicKey; get balances(): Balance[]; get activeBalances(): Balance[]; get accountFlags(): number[]; get emissionsDestinationAccount(): PublicKey; get healthCache(): HealthCache; get isDisabled(): boolean; get isFlashLoanEnabled(): boolean; get isTransferAccountAuthorityEnabled(): boolean; getBalance(bankPk: PublicKey): Balance; getBankFromAddress(bankAddress: PublicKey): Promise; getMintDataFromBank(bank: BankType): Promise; /** * Creates a deposit instruction with auto-injected client data. * * Automatically looks up bank and mint data from the client. * * @param bankAddress - Bank address to deposit to * @param amount - Amount to deposit in UI units * @param opts - Optional configuration for wrapping SOL and overrides */ makeDepositIx(bankAddress: PublicKey, amount: Amount, opts?: MakeDepositIxOpts): Promise; /** * Creates a repay instruction with auto-injected client data. * * Automatically looks up bank and mint data from the client. * * @param bankAddress - Bank address to repay to * @param amount - Amount to repay in UI units * @param repayAll - If true, repays the entire borrowed position * @param opts - Optional configuration for wrapping SOL and overrides */ makeRepayIx(bankAddress: PublicKey, amount: Amount, repayAll?: boolean, opts?: MakeRepayIxOpts): Promise; /** * Creates a withdraw instruction with auto-injected client data. * * Automatically looks up bank, mint data, and metadata from the client. * * @param bankAddress - Bank address to withdraw from * @param amount - Amount to withdraw in UI units * @param withdrawAll - If true, withdraws the entire collateral position * @param opts - Optional configuration for unwrapping SOL and overrides */ makeWithdrawIx(bankAddress: PublicKey, amount: Amount, withdrawAll?: boolean, opts?: MakeWithdrawIxOpts): Promise; /** * Creates a borrow instruction with auto-injected client data. * * Automatically looks up bank, mint data, and metadata from the client. * * @param bankAddress - Bank address to borrow from * @param amount - Amount to borrow in UI units * @param opts - Optional configuration for unwrapping SOL and overrides */ makeBorrowIx(bankAddress: PublicKey, amount: Amount, opts?: MakeBorrowIxOpts): Promise; /** * Creates a begin flash loan instruction. * * @param endIndex - End index for the flash loan * @param authority - Optional authority override */ makeBeginFlashLoanIx(endIndex: number, authority?: PublicKey): Promise; /** * Creates an end flash loan instruction with auto-injected client data. * * @param projectedActiveBanks - Array of active bank public keys after flash loan * @param authority - Optional authority override */ makeEndFlashLoanIx(projectedActiveBanks: PublicKey[], authority?: PublicKey): Promise; /** * Builds a transaction to transfer this account to a new authority. * * @param newMarginfiAccount - Freshly generated keypair for the destination account * @param newAuthority - New authority public key * @param feePayer - Optional `PublicKey` (adapter-signed) or `Keypair` (separate * payer); defaults to this account's authority */ makeAccountTransferToNewAccountTx(newMarginfiAccount: Keypair, newAuthority: PublicKey, feePayer?: PublicKey | Keypair): Promise; /** * Creates a close account instruction. */ makeCloseAccountIx(): Promise; /** * Creates a pulse health instruction with auto-injected client data. * * @param mandatoryBanks - Array of mandatory bank public keys * @param excludedBanks - Array of excluded bank public keys */ makePulseHealthIx(mandatoryBanks: PublicKey[], excludedBanks: PublicKey[]): Promise<{ instructions: _solana_web3_js.TransactionInstruction[]; keys: never[]; }>; /** * Creates a loop transaction (leverage) with auto-injected client data. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, addressLookupTables * * @param params - Loop transaction parameters (user provides: connection, depositOpts, borrowOpts, swapOpts, etc.) */ makeLoopTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Atomically move a selected set of positions from this account to a destination account with * auto-injected client data. * * Auto-injects: program, connection, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, * assetShareValueMultiplierByBank, addressLookupTables, tokenProgramsByBank, groupRateLimiterEnabled. */ makeTransferPositionsTx(params: Omit): Promise; /** * Creates a repay with collateral transaction with auto-injected client data. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, addressLookupTables * * @param params - Repay with collateral parameters (user provides: connection, withdrawOpts, repayOpts, swapOpts, etc.) */ makeRepayWithCollatTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; swapQuote: SwapQuoteResult | undefined; amountToRepay: number; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Creates a swap collateral transaction with auto-injected client data. * * Swaps one collateral type for another (e.g., JitoSOL -> mSOL) using a flash loan * so account health is not affected during the swap. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, addressLookupTables * * @param params - Swap collateral parameters (user provides: connection, withdrawOpts, depositOpts, swapOpts, etc.) */ makeSwapCollateralTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Rolls a matured Exponent PT collateral position into its next-maturity PT, with * auto-injected client data (withdraw PT_old → `wrapper_merge` to base → swap-engine buy * PT_new → deposit, flash-loan wrapped). The full deposit ends up as new PT. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, addressLookupTables * * @param params - Roll-PT parameters (user provides: connection, withdrawOpts, depositOpts, rollOpts, etc.) */ makeRollPtTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; }>; /** * Creates a swap debt transaction with auto-injected client data. * * Swaps one debt type for another (e.g., USDC debt -> SOL debt) using a flash loan * so account health is not affected during the swap. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, addressLookupTables * * @param params - Swap debt parameters (user provides: connection, repayOpts, borrowOpts, swapOpts, etc.) */ makeSwapDebtTx(params: Omit): Promise<{ transactions: ExtendedV0Transaction[]; actionTxIndex: number; quoteResponse: SwapQuoteResult | undefined; /** true → send as ONE atomic Jito bundle (bridged legs / integration refreshes); * false → sequential sends are safe. */ mustBeAtomicBundle: boolean; }>; /** * Creates a loop (leverage) transaction with a transparent bridged (double-hop) fallback and * auto-injected client data. * * One call: tries the direct {@link makeLoopTx} first; if its borrow→deposit swap can't fit one * transaction or has no route, it loops the deposit asset against a value-equivalent borrow of a * bridge token (USDC/wSOL/USDT by default, override via `bridgeOpts.bridgeCandidateMints`) and * debt-swaps that bridge debt to the requested borrow asset — one atomic Jito bundle. * `result.bridgeMint` is set only when the bridged path was used. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, * addressLookupTables, assetShareValueMultiplierByBank * * @param params - Loop parameters (user provides: connection, depositOpts, borrowOpts, swapOpts, bridgeOpts?, etc.) */ makeBridgedLoopTx(params: Omit): Promise; /** * Creates a collateral-swap transaction with a transparent bridged (double-hop) fallback and * auto-injected client data. * * One call: tries the direct {@link makeSwapCollateralTx} first; if the swap `A → C` can't fit * one transaction or has no route, it decomposes into `A → bridge` + `bridge → C` through a * bridge token, composed as one atomic Jito bundle. `result.bridgeMint` is set only when the * bridged path was used. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, * addressLookupTables, assetShareValueMultiplierByBank * * @param params - Swap collateral parameters (user provides: connection, withdrawOpts, depositOpts, swapOpts, bridgeOpts?, etc.) */ makeBridgedSwapCollateralTx(params: Omit): Promise; /** * Creates a debt-swap transaction with a transparent bridged (double-hop) fallback and * auto-injected client data. * * One call: tries the direct {@link makeSwapDebtTx} first; if the swap `A → C` can't fit one * transaction or has no route, the first leg repays A by borrowing a bridge token and the second * leg repays exactly that bridge debt while borrowing C — one atomic Jito bundle. * `result.bridgeMint` is set only when the bridged path was used. * * Auto-injects: program, marginfiAccount, bankMap, oraclePrices, bankMetadataMap, * addressLookupTables, assetShareValueMultiplierByBank * * @param params - Swap debt parameters (user provides: connection, repayOpts, borrowOpts, swapOpts, bridgeOpts?, etc.) */ makeBridgedSwapDebtTx(params: Omit): Promise; /** * Creates a deposit transaction with auto-injected client data. * * Automatically looks up bank and mint data, then builds and wraps instruction in a transaction. * * @param bankAddress - Bank address to deposit to * @param amount - Amount to deposit in UI units * @param opts - Optional configuration for wrapping SOL and overrides * @returns Promise resolving to an ExtendedTransaction */ makeDepositTx(bankAddress: PublicKey, amount: Amount, opts?: MakeDepositIxOpts): Promise; /** * Creates a Kamino deposit transaction with auto-injected client data. * * Automatically looks up bank, mint data, and connection. * * @param bankAddress - Bank address to deposit to * @param amount - Amount to deposit in UI units * @param spotMarket - Drift spot market data * @param opts - Optional configuration * @returns Promise resolving to an ExtendedV0Transaction */ makeDriftDepositTx(bankAddress: PublicKey, amount: Amount, spotMarket: DriftSpotMarket, opts?: MakeDepositIxOpts): Promise; /** * Creates a Kamino deposit transaction with auto-injected client data. * * Automatically looks up bank, mint data, and connection. * * @param bankAddress - Bank address to deposit to * @param amount - Amount to deposit in UI units * @param reserve - Kamino reserve data * @param opts - Optional configuration * @returns Promise resolving to an ExtendedV0Transaction */ makeKaminoDepositTx(bankAddress: PublicKey, amount: Amount, reserve: KaminoReserve, opts?: MakeDepositIxOpts): Promise; /** * Creates a borrow transaction with auto-injected client data. * * Automatically looks up bank, mint data, metadata, and oracle prices. * * @param bankAddress - Bank address to borrow from * @param amount - Amount to borrow in UI units * @param opts - Optional configuration * @returns Promise resolving to a TransactionBuilderResult */ makeBorrowTx(bankAddress: PublicKey, amount: Amount, opts?: MakeBorrowIxOpts): Promise; /** * Creates a repay transaction with auto-injected client data. * * Automatically looks up bank and mint data. * * @param bankAddress - Bank address to repay to * @param amount - Amount to repay in UI units * @param repayAll - If true, repays the entire borrowed position * @param opts - Optional configuration * @returns Promise resolving to an ExtendedTransaction */ makeRepayTx(bankAddress: PublicKey, amount: Amount, repayAll?: boolean, opts?: MakeRepayIxOpts): Promise; /** * Creates a withdraw transaction with auto-injected client data. * * Automatically looks up bank, mint data, metadata, and oracle prices. * * @param bankAddress - Bank address to withdraw from * @param amount - Amount to withdraw in UI units * @param withdrawAll - If true, withdraws the entire collateral position * @param opts - Optional configuration * @returns Promise resolving to a TransactionBuilderResult */ makeWithdrawTx(bankAddress: PublicKey, amount: Amount, withdrawAll?: boolean, opts?: MakeWithdrawIxOpts): Promise; /** * Creates a Drift withdraw transaction with auto-injected client data. * * Automatically looks up bank, mint data, metadata, and oracle prices. * * @param bankAddress - Bank address to withdraw from * @param amount - Amount to withdraw in UI units * @param driftSpotMarket - Drift spot market data * @param withdrawAll - If true, withdraws the entire collateral position * @param opts - Optional configuration * @returns Promise resolving to a TransactionBuilderResult */ makeDriftWithdrawTx(bankAddress: PublicKey, amount: Amount, driftSpotMarket: DriftSpotMarket, userRewards: DriftRewards[], withdrawAll?: boolean, opts?: MakeWithdrawIxOpts): Promise; /** * Creates a Kamino withdraw transaction with auto-injected client data. * * Automatically looks up bank, mint data, metadata, and oracle prices. * * @param bankAddress - Bank address to withdraw from * @param amount - Amount to withdraw in UI units * @param reserve - Kamino reserve data * @param withdrawAll - If true, withdraws the entire collateral position * @param opts - Optional configuration * @returns Promise resolving to a TransactionBuilderResult */ makeKaminoWithdrawTx(bankAddress: PublicKey, amount: Amount, reserve: any, withdrawAll?: boolean, opts?: MakeWithdrawIxOpts): Promise; /** * Creates a flash loan transaction with auto-injected client data. * * Auto-injects: program, marginfiAccount * * @param params - Flash loan transaction parameters (user provides: ixs, endIndex, etc.) * @returns Promise resolving to flash loan transaction details */ makeFlashLoanTx(params: Omit): Promise<_solana_web3_js.VersionedTransaction & ExtendedTransactionProperties>; /** * Returns the active emode pairs for this account based on current positions. */ getActiveEmodePairs(): EmodePair[]; /** * Returns the lowest emode weights per collateral bank for currently active pairs. * Keyed by bank address string → { assetWeightInit, assetWeightMaint }. */ getActiveEmodeWeightsByBank(): Map; /** * Computes emode impacts for all banks using the client's emode pairs. */ getEmodeImpacts(): Record; /** * Simulates health cache update with auto-injected client data. */ simulateHealthCache(): Promise<{ account: MarginfiAccount; error: HealthCacheSimulationError | undefined; }>; /** * Computes net APY with auto-injected client data. */ computeNetApy(): number; /** * Computes account value (equity) with auto-injected client data. */ computeAccountValue(): BigNumber$1; /** * Computes health components with auto-injected client data. * * @param marginRequirement - Margin requirement type */ computeHealthComponentsFromCache(marginRequirement: MarginRequirementType): { assets: BigNumber$1; liabilities: BigNumber$1; }; /** * Computes free collateral with auto-injected client data. * * @param opts - Optional configuration */ computeFreeCollateralFromCache(opts?: { clamped?: boolean; }): BigNumber$1; /** * Computes max borrow for a bank with auto-injected client data. * * @param bankAddress - Bank address to check max borrow for * @param opts - Optional configuration for emode and volatility */ computeMaxBorrowForBank(bankAddress: PublicKey, opts?: { volatilityFactor?: number; /** Skip bank-level clamps (remaining borrow cap, available liquidity, rate limiters) */ ignoreBankLimits?: boolean; }): BigNumber$1; /** * Computes max withdraw for a bank with auto-injected client data. * * @param bankAddress - Bank address to check max withdraw for * @param opts - Optional configuration for volatility and emode */ computeMaxWithdrawForBank(bankAddress: PublicKey, opts?: { volatilityFactor?: number; /** Skip bank-level clamps (available liquidity, rate limiters) */ ignoreBankLimits?: boolean; }): BigNumber$1; /** * Computes max deposit for a bank with auto-injected client data. * * Bounded by the bank's remaining deposit cap and, if provided, the wallet balance. * * @param bankAddress - Bank address to check max deposit for * @param opts - Optional wallet balance (UI units) to cap the result */ computeMaxDepositForBank(bankAddress: PublicKey, opts?: { walletBalance?: BigNumber$1 | number; }): BigNumber$1; /** * Computes active emode pairs for custom emode pair sets. * For typical usage, prefer `getActiveEmodePairs()` which uses client data. * * @param emodePairs - All available emode pairs */ computeActiveEmodePairs(emodePairs: EmodePair[]): EmodePair[]; /** * Computes emode impacts for custom emode pair sets. * For typical usage, prefer `getEmodeImpacts()` which uses client data. * * @param emodePairs - All available emode pairs * @param banks - Array of bank addresses to analyze */ computeEmodeImpacts(emodePairs: EmodePair[], banks: PublicKey[]): Record; /** * Gets health check accounts with auto-injected client data. * * @param mandatoryBanks - Array of mandatory bank public keys (default: []) * @param excludedBanks - Array of excluded bank public keys (default: []) */ getHealthCheckAccounts(mandatoryBanks?: PublicKey[], excludedBanks?: PublicKey[]): BankType[]; /** * Gets the underlying MarginfiAccount instance. * Useful for advanced operations that need direct access. */ getUnderlyingAccount(): MarginfiAccount; /** * Gets the client instance. */ getClient(): Project0Client; } export { ADDRESS_LOOKUP_TABLE_FOR_GROUP, ADDRESS_LOOKUP_TABLE_FOR_GROUP_NATIVE_STAKE, ADDRESS_LOOKUP_TABLE_FOR_SWAP, type AccountActiveBalanceForBank, AccountFlags, ActionEmodeImpact, ActiveEmodePair, type ActiveStakePoolMap, Amount, AssetTag, BUNDLE_TX_SIZE, Balance, type BalanceRaw, BalanceType, type BalanceTypeDto, Bank, type BankConfigDto, BankConfigFlag, BankConfigOpt, BankConfigOptRaw, BankConfigRaw, type BankConfigRawDto, BankConfigType, BankIntegrationMetadata, BankIntegrationMetadataDto, BankIntegrationMetadataMap, BankIntegrationMetadataMapDto, type BankMetrics, type BankRateLimiterDto, BankRateLimiterRaw, type BankRateLimiterRawDto, BankRateLimiterType, BankRaw, type BankRawDto, BankType, type BankTypeDto, BankVaultType, type BankVenueStates, type BridgeOpts, type BridgeTokenSide, type BridgedSwapLeg, type BridgedTxResult, type BuildContext, type BulkLendTxsResult, type ClassifiedPosition, type ComposeBridgedSwapParams, type ComposeBridgedSwapResult, type ComputeAssetHealthComponentParams, type ComputeBalanceUsdValueParams, type ComputeBankMetricsParams, type ComputeFreeCollateralFromBalancesParams, type ComputeHealthCacheStatusParams, type ComputeHealthComponentsFromBalancesParams, type ComputeLiabilityHealthComponentParams, type ComputeLiquidationPriceForBankParams, type ComputeMaxBorrowForBankParams, type ComputeMaxDepositForBankParams, type ComputeMaxWithdrawForBankParams, type ComputeNetApyParams, ConfigRaw, type CrankCombination, type CrankabilityResult, DEFAULT_BRIDGE_MINTS, DEFAULT_CROSSBAR_URL, DEFAULT_FALLBACK_CROSSBAR_URL, DEFAULT_ORACLE_MAX_AGE, DEFAULT_REPAY_ALL_EXTRA_BUFFER_BPS, DISABLED_FLAG, type DriftBankInput, type DriftMetadata, type DriftStateByBank, type DriftStateJsonByBank, EMPTY_HEALTH_CACHE, EXECUTION_HEADROOM_SECONDS, type EmodeConfigRawDto, type EmodeEntryDto, EmodeEntryFlags, EmodeFlags, EmodeImpactStatus, EmodePair, type EmodeSettingsDto, EmodeSettingsRaw, type EmodeSettingsRawDto, EmodeSettingsType, EmodeTag, Environment, type ExactOutEstimateResult, type ExtendedTransaction, type ExtendedTransactionProperties, type ExtendedV0Transaction, FLASHLOAN_ENABLED_FLAG, type FeeStateCache, type FetchBankIntegrationMetadataOptions, type FetchDriftMetadataOptions, type FetchJupLendMetadataOptions, type FetchKaminoMetadataOptions, type FlashloanActionResult, type FlashloanBudgetIx, type FlashloanPrecheckResult, type FlashloanSwapConstraints, type GetBalanceUsdValueWithPriceBiasParams, type GetExactOutEstimateParams, type GetSwapIxsForFlashloanParams, type GetTitanExactOutEstimateParams, type GetTitanSwapIxsParams, HOURS_PER_YEAR, HealthCache, HealthCacheFlags, type HealthCacheRaw, HealthCacheSimulationError, HealthCacheStatus, HealthCacheType, type HealthCacheTypeDto, type InstructionsWrapper, type IntegrationType, InterestRateConfig, type InterestRateConfigDto, InterestRateConfigRaw, JUPITER_V6_PROGRAM, JUP_SWAP_LUT_PROGRAM_AUTHORITY_INDEX, type JupLendBankInput, type JupLendMetadata, type JupLendStateByBank, type JupLendStateJsonByBank, type KaminoBankInput, type KaminoMetadata, type KaminoStateByBank, type KaminoStateJsonByBank, LST_MINT, type LoopFlashloanDescriptor, MARGINFI_PROGRAM, MARGINFI_PROGRAM_STAGING, MARGINFI_PROGRAM_STAGING_ALT, MARGINFI_SPONSORED_SHARD_ID, MAX_ACCOUNT_LOCKS, MAX_CONFIDENCE_INTERVAL_RATIO, MAX_TX_SIZE, MAX_U64, MPL_METADATA_PROGRAM_ID, type MakeAccountTransferToNewAccountTxParams, type MakeBorrowIxOpts, type MakeBorrowIxParams, type MakeBorrowTxParams, type MakeBridgedLoopTxParams, type MakeBridgedSwapCollateralTxParams, type MakeBridgedSwapDebtTxParams, type MakeBulkRepayTxParams, type MakeBulkWithdrawTxParams, type MakeCloseAccountIxParams, type MakeCloseAccountTxParams, type MakeDepositIxOpts, type MakeDepositIxParams, type MakeDepositTxParams, type MakeDriftDepositIxParams, type MakeDriftDepositTxParams, type MakeDriftWithdrawIxParams, type MakeDriftWithdrawTxParams, type MakeFlashLoanTxParams, type MakeJuplendDepositIxParams, type MakeJuplendDepositTxParams, type MakeJuplendWithdrawIxParams, type MakeJuplendWithdrawTxParams, type MakeKaminoDepositIxParams, type MakeKaminoDepositTxParams, type MakeKaminoWithdrawIxParams, type MakeKaminoWithdrawTxParams, type MakeLoopTxParams, type MakeMergeStakeAccountsTxParams, type MakeMintStakedLstIxParams, type MakeMintStakedLstTxParams, type MakeRedeemStakedLstIxParams, type MakeRedeemStakedLstTxParams, type MakeRepayIxOpts, type MakeRepayIxParams, type MakeRepayTxParams, type MakeRepayWithCollatTxParams, type MakeRollPtTxParams, type MakeSetupIxParams, type MakeSwapCollateralTxParams, type MakeSwapDebtTxParams, type MakeTransferPositionsTxParams, type MakeVaultCompleteWithdrawalIxParams, type MakeVaultCompleteWithdrawalTxParams, type MakeVaultDepositIxParams, type MakeVaultDepositTxParams, type MakeVaultDepositWithSwapTxParams, type MakeVaultWithdrawIxParams, type MakeVaultWithdrawTxParams, type MakeWithdrawIxOpts, type MakeWithdrawIxParams, type MakeWithdrawTxParams, MarginRequirementType, type MarginRequirementTypeRaw, MarginfiAccount, type MarginfiAccountRaw, MarginfiAccountType, type MarginfiAccountTypeDto, MarginfiAccountWrapper, MarginfiGroup, type MarginfiGroupRaw, type MarginfiGroupType, type MarginfiGroupTypeDto, MarginfiIdlType, MarginfiProgram, type MintAuthorityBalance, MintData, type MultiplierAccountState, type MultiplierAccountStates, OperationalState, OperationalStateRaw, type OracleMultiplierBankInput, type OracleMultiplierServiceOpts, OraclePrice, OraclePriceDto, OracleSetup, OracleSetupRaw, type OracleSourceKey, PDA_BANK_EMISSIONS_AUTH_SEED, PDA_BANK_EMISSIONS_VAULT_SEED, PDA_BANK_FEE_STATE_SEED, PDA_BANK_FEE_VAULT_AUTH_SEED, PDA_BANK_FEE_VAULT_SEED, PDA_BANK_INSURANCE_VAULT_AUTH_SEED, PDA_BANK_INSURANCE_VAULT_SEED, PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED, PDA_BANK_LIQUIDITY_VAULT_SEED, PDA_MARGINFI_ACCOUNT_SEED, PRIORITY_TX_SIZE, PYTH_PRICE_CONF_INTERVALS, PYTH_PUSH_ORACLE_ID, PYTH_SPONSORED_SHARD_ID, type PanicStateCache, PriceBias, PriceWithConfidence, Project0Client, Project0Config, Project0ConfigRaw, type ProviderSwapRoute, type PythOracleServiceOpts, type RateLimitWindowDto, type RateLimitWindowRawDto, RateLimitWindowType, type RatePointDto, type ResolveBridgeCandidateBanksParams, type ResolvedPinnedSwapRoute, RiskTier, RiskTierRaw, type RollPtOpts, type RollQuoteSimResult, type RollQuoteSimulator, type RollQuoteTokenBalance, SECONDS_PER_YEAR, SINGLE_POOL_PROGRAM_ID, STAKED_ORACLE_DISABLED_FLAG, STAKED_ORACLE_USES_ONRAMP_FLAG, STAKE_CONFIG_ID, STAKE_PROGRAM_ID, SWAP_ADAPTERS, SWB_PRICE_CONF_INTERVALS, SYSTEM_PROGRAM_ID, SYSVAR_CLOCK_ID, SYSVAR_RENT_ID, SYSVAR_STAKE_HISTORY_ID, type ScopeOracleServiceOpts, type SerializedInstruction, type SerializedLut, type SerializedSwapEngineRequest, type SerializedSwapEngineResult, type SerializedTxFootprint, type SharedBridgeLegContext, type SimulateAccountHealthCacheWithFallbackParams, type SimulationResultRaw, type SmartCrankParams, type SmartCrankResult, type SolanaTransaction, type StakeAccount, type StakePoolMevMap, type StakedBankMetadata, type SwapAdapter, type SwapApiConfig, type SwapCandidate, type SwapEngineRequest, type SwapEngineResult, type SwapEngineRunner, type SwapIxsResult, type SwapOpts, SwapProvider, type SwapProviderConfig, type SwapProviderEntry, type SwapQuoteResult, type SwbOracleAiDataByKey, type SwbOracleServiceOpts, TRANSFER_ACCOUNT_AUTHORITY_FLAG, type TitanQuoteParams, TransactionArenaKeyMap, type TransactionBuilderResult, TransactionBuildingError, TransactionBuildingErrorCode, type TransactionBuildingErrorDetails, TransactionConfigMap, TransactionType, type TransferPositionSide, type TransferPositionsResult, type TxFootprint, TypedAmount, U64_MAX, USDC_DECIMALS, USDC_MINT, USDT_MINT, VENUE_AVAILABLE_LIQUIDITY_BUFFER, type ValidatorRateData, type ValidatorStakeGroup, type ValidatorStakeGroupDto, WSOL_MINT, type WithdrawWindowCache, WrappedI80F48, ZERO_ORACLE_KEY, accountConflictsWithBridgeBank, accountFlagToBN, addOracleToBanksIx, addTransactionMetadata, adjustPriceComponent, aprToApy, apyToApr, balanceToDto, bankConfigRawToDto, bankConfigToBankConfigRaw, bankMetadataMapToDto, bankMetadataToDto, bankRateLimiterRawToDto, bankRawToDto, bigNumberToWrappedI80F48, bpsToPercentile, buildCollateralLegIxs, calculateApyFromInterest, calculateInterestFromApy, capConfidenceInterval, categorizePythBanks, checkBatchOracleCrankability, checkJupiterFeeAccount, checkMultipleOraclesCrankability, checkTitanFeeAccount, chunkedGetRawMultipleAccountInfoOrdered, chunkedGetRawMultipleAccountInfoOrderedWithNulls, chunkedGetRawMultipleAccountInfos, classifyAndValidate, compileFlashloanPrecheck, composeBridgedSwap, composeRemainingAccounts, computeAccountValue, computeAccrualProjectionSeconds, computeActiveEmodePairs, computeAssetHealthComponent, computeBalanceUsdValue, computeBankAvailableLiquidity, computeBankBorrowApy, computeBankBorrowCapRemaining, computeBankDepositCapRemaining, computeBankMetrics, computeBankPoolSize, computeBankProjectedAvailableLiquidity, computeBankRateLimitRemaining, computeBankSupplyApy, computeBankTotalBorrows, computeBankTotalBorrowsUsd, computeBankTotalDeposits, computeBankTotalDepositsUsd, computeBaseInterestRate, computeBorrowEstimateForRepay, computeClaimedEmissions, computeClosePositionTokenAmount, computeEmodeImpacts, computeFlashLoanNonSwapBudget, computeFlashloanSwapConstraints, computeFreeCollateralFromBalances, computeFreeCollateralFromCache, computeGroupRateLimitRemainingUsd, computeHealthAccountMetas, computeHealthCacheStatus, computeHealthCheckAccounts, computeHealthComponentsFromBalances, computeHealthComponentsFromCache, computeInterestRates, computeLiabilityHealthComponent, computeLiquidationPriceForBank, computeLowestEmodeWeights, computeMaxBorrowForBank, computeMaxDepositForBank, computeMaxWithdrawForBank, computeNetApy, computeOracleMultiplier, computeOracleMultipliers, computeProjectedActiveBalancesNoCpi, computeProjectedActiveBanksNoCpi, computePtMultiplier, computeQuantity, computeQuantityUi, computeRateLimitWindowRemainingCapacity, computeRateLimiterRemainingCapacity, computeRemainingCapacity, computeSmartCrank, computeStakedBankMultipliers, computeTotalOutstandingEmissions, computeUtilizationRate, computeV0TxSize, computeVenueAvailableLiquidity, configureScopeOracleIx, convertVoteAccCoeffsToBankCoeffs, createActiveEmodePairFromPairs, createEmptyBalance, decodeAccountRaw, decodeBankRaw, decodeInstruction, decodeMultiplierAccount, decompileV0Transaction, deriveBankEmissionsAuth, deriveBankEmissionsVault, deriveBankFeeVault, deriveBankFeeVaultAuthority, deriveBankInsuranceVault, deriveBankInsuranceVaultAuthority, deriveBankLiquidityVault, deriveBankLiquidityVaultAuthority, deriveFeeState, deriveMarginfiAccount, deserializeInstruction, deserializeLut, deserializeSwapEngineRequest, deserializeSwapEngineResult, dtoToBalance, dtoToBank, dtoToBankConfig, dtoToBankConfigRaw, dtoToBankMetadata, dtoToBankMetadataMap, dtoToBankRateLimiter, dtoToBankRateLimiterRaw, dtoToBankRaw, dtoToEmodeSettings, dtoToEmodeSettingsRaw, dtoToGroup, dtoToHealthCache, dtoToInterestRateConfig, dtoToMarginfiAccount, dtoToOraclePrice, dtoToValidatorStakeGroup, emodeSettingsRawToDto, extractPythOracleKeys, fetchBank, fetchBankIntegrationMetadata, fetchGammaLpVault, fetchGammaWithdrawReceipt, fetchMarginfiAccountActiveBalancesForBank, fetchMarginfiAccountAddresses, fetchMarginfiAccountAddressesHoldingBank, fetchMarginfiAccountData, fetchMultipleBanks, fetchMultiplierAccountStates, fetchMultiplierAccountStatesFromAPI, fetchNativeStakeAccounts, fetchOracleData, fetchOracleMultipliers, fetchOracleMultipliersFromAPI, fetchOracleMultipliersFromChain, fetchProgramForMints, fetchPythOracleData, fetchPythOraclePricesFromAPI, fetchPythOraclePricesFromChain, fetchScopeOracleData, fetchScopeOraclePricesFromAPI, fetchScopeOraclePricesFromChain, fetchStakeAccount, fetchStakePoolActiveStates, fetchStakePoolMev, fetchSwbOracleAccountsFromAPI, fetchSwbOracleAccountsFromChain, fetchSwbOracleData, fetchSwbOraclePricesFromAPI, fetchSwbOraclePricesFromCrossbar, findRandomAvailableAccountIndex, freezeBankConfigIx, generateDummyAccount, getAccountKeys, getActiveAccountFlags, getActiveBalances, getActiveEmodeEntryFlags, getActiveEmodeFlags, getActiveHealthCacheFlags, getAssetQuantity, getAssetShares, getBalance, getBalanceUsdValueWithPriceBias, getBankVaultAuthority, getBankVaultSeeds, getBirdeyeFallbackPricesByFeedId, getBirdeyePricesForMints, getConfig, getDriftCTokenMultiplier, getDriftMetadata, getDriftStatesDto, getEffectiveDepositLimit, getEmodePairs, getExactOutEstimate, getFallbackPricesByFeedId, getFallbackPricesForMints, getHealthCacheStatusDescription, getHealthSimulationTransactions, getJupLendFTokenMultiplier, getJupLendMetadata, getJupLendStatesDto, getJupiterReferralFeeAccount, getJupiterSwapIxsForFlashloan, getKaminoCTokenMultiplier, getKaminoMetadata, getKaminoStatesDto, getLiabilityQuantity, getLiabilityShares, getOracleMultiplierBankInput, getOracleSourceFromBank, getOracleSourceFromOracleSetup, getOracleSourceNameFromKey, getPrice, getPriceWithConfidence, getStakedBankMetadataMap, getSwapAdapter, getSwapIxsForFlashloan, getTitanExactOutEstimate, getTitanSwapIxsForFlashloan, getTotalAccountKeys, getTotalAssetQuantity, getTotalLiabilityQuantity, getTxSize, getValidatorVoteAccountByBank, getWritableAccountKeys, groupToDto, hasAccountFlag, hasEmodeEntryFlag, hasEmodeFlag, hasHealthCacheFlag, healthCacheToDto, isBorrowLimitActive, isBridgeConflictError, isDecomposableSwapError, isDepositIx, isDepositLimitActive, isFlashloan, isGroupRateLimiterEnabled, isStandardBorrowable, isStandardDepositable, isV0Tx, isWholePosition, makeAccountTransferToNewAccountTx, makeAddPermissionlessStakedBankIx, makeBeginFlashLoanIx, makeBorrowIx, makeBorrowTx, makeBridgedLoopTx, makeBridgedSwapCollateralTx, makeBridgedSwapDebtTx, makeBulkRepayTx, makeBulkWithdrawTx, makeBundleTipIx, makeCloseMarginfiAccountIx, makeCloseMarginfiAccountTx, makeCrankSwbFeedIx, makeCreateAccountIxWithProjection, makeCreateAccountTxWithProjection, makeCreateMarginfiAccountIx, makeCreateMarginfiAccountTx, makeDepositIx, makeDepositTx, makeDriftDepositIx, makeDriftDepositTx, makeDriftWithdrawIx, makeDriftWithdrawTx, makeEndFlashLoanIx, makeFlashLoanTx, makeJuplendDepositIx, makeJuplendDepositTx, makeJuplendWithdrawIx, makeJuplendWithdrawTx, makeKaminoDepositIx, makeKaminoDepositTx, makeKaminoWithdrawIx, makeKaminoWithdrawTx, makeLoopTx, makeMergeStakeAccountsTx, makeMintStakedLstIx, makeMintStakedLstTx, makePoolAddBankIx, makePoolConfigureBankIx, makePriorityFeeIx, makePriorityFeeMicroIx, makePulseHealthIx, makeRedeemStakedLstIx, makeRedeemStakedLstTx, makeRefreshIntegrationBanksIxs, makeRefreshKaminoBanksIxs, makeRepayIx, makeRepayTx, makeRepayWithCollatTx, makeRollPtTx, makeSetupIx, makeSmartCrankSwbFeedIx, makeSmartCrankSwbFeedIxForAccounts, makeSwapCollateralTx, makeSwapDebtTx, makeTransferPositionsTx, makeTxPriorityIx, makeUnwrapSolIx, makeUpdateDriftMarketIxs, makeUpdateJupLendRateIxs, makeUpdateSwbFeedIx, makeVaultCompleteWithdrawalIx, makeVaultCompleteWithdrawalTx, makeVaultDepositIx, makeVaultDepositTx, makeVaultDepositWithSwapTx, makeVaultWithdrawIx, makeVaultWithdrawTx, makeVersionedTransaction, makeWithdrawIx, makeWithdrawTx, makeWrapSolIxs, mapBrokenFeedsToOraclePrices, mapJupiterQuoteToSwapQuoteResult, mapPythBanksToOraclePrices, mapSwbBanksToOraclePrices, marginfiAccountToDto, mergeBridgeQuotes, mergeBridgeQuotesDebt, mergeBridgeQuotesLoop, nativeToUi, oraclePriceToDto, parseBalanceRaw, parseBankConfigRaw, parseBankRateLimiterRaw, parseBankRaw, parseEmodeSettingsRaw, parseEmodeTag, parseHealthCacheRaw, parseMarginfiAccountRaw, parseOperationalState, parseOracleSetup, parseOraclePriceData as parsePriceInfo, parseRiskTier, parseRpcPythPriceData, parseSwbOraclePriceData, partitionBanksByCrankability, patchDepositAmount, requireBank, requireTokenProgram, resolveBridgeCandidateBanks, resolvePinnedSwapRoute, resolveTokenProgramForMint, resolveVaultTokenProgram, runSwapEngine, selectLutsForAccountAction, selectLutsForBanks, selectSwapBridges, serializeBankConfigOpt, serializeInstruction, serializeInterestRateConfig, serializeLut, serializeOperationalState, serializeOracleSetup, serializeOracleSetupToIndex, serializeRiskTier, serializeSwapEngineRequest, serializeSwapEngineResult, setOraclePriceIx, sharedBridgeLegContext, shortenAddress, simulateAccountHealthCache, simulateAccountHealthCacheWithFallback, simulateBundle, splitInstructionsToFitTransactions, swapEngineProvidersFromOpts, swapEngineQuoteFieldsFromOpts, toBankConfigDto, toBankDto, toBankRateLimiterDto, toBigNumber, toEmodeSettingsDto, toInterestRateConfigDto, toJupiterConfig, toNumber, tryBridgeCandidates, uiToNative, uiToNativeBigNumber, validatorStakeGroupToDto, wrappedI80F48toBigNumber };