@0dotxyz/p0-ts-sdk 3.0.0-next.2 → 3.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vendor/single-spl-pool/addresses.ts","../src/vendor/single-spl-pool/instructions.ts","../src/generated/scope/types/datedPrice.ts","../src/generated/scope/types/price.ts","../src/generated/scope/accounts/oraclePrices.ts","../src/generated/scope/programs/scope.ts","../src/vendor/scope/index.ts","../src/vendor/marinade/index.ts","../src/vendor/spl-stake-pool/index.ts","../src/vendor/account-data.ts","../src/generated/kfarms/types/rewardInfo.ts","../src/generated/kfarms/types/rewardPerTimeUnitPoint.ts","../src/generated/kfarms/types/rewardScheduleCurve.ts","../src/generated/kfarms/types/tokenInfo.ts","../src/generated/kfarms/accounts/farmState.ts","../src/generated/kfarms/programs/farms.ts","../src/generated/klend/types/bigFractionBytes.ts","../src/generated/klend/types/borrowOrder.ts","../src/generated/klend/types/borrowRateCurve.ts","../src/generated/klend/types/curvePoint.ts","../src/generated/klend/types/fixedTermBorrowRolloverConfig.ts","../src/generated/klend/types/lastUpdate.ts","../src/generated/klend/types/obligationCollateral.ts","../src/generated/klend/types/obligationLiquidity.ts","../src/generated/klend/types/obligationOrder.ts","../src/generated/klend/types/priceHeuristic.ts","../src/generated/klend/types/pythConfiguration.ts","../src/generated/klend/types/reserveCollateral.ts","../src/generated/klend/types/reserveConfig.ts","../src/generated/klend/types/reserveFees.ts","../src/generated/klend/types/reserveLiquidity.ts","../src/generated/klend/types/scopeConfiguration.ts","../src/generated/klend/types/switchboardConfiguration.ts","../src/generated/klend/types/tokenInfo.ts","../src/generated/klend/types/withdrawalCaps.ts","../src/generated/klend/types/withdrawQueue.ts","../src/generated/klend/accounts/obligation.ts","../src/generated/klend/accounts/reserve.ts","../src/generated/klend/programs/kaminoLending.ts","../src/generated/klend/instructions/refreshObligation.ts","../src/generated/klend/instructions/refreshReserve.ts","../src/generated/klend/instructions/refreshReservesBatch.ts","../src/vendor/klend/accounts.ts","../src/vendor/klend/constants.ts","../src/vendor/klend/fraction.ts","../src/vendor/klend/instructions.ts","../src/vendor/klend/types.ts","../src/vendor/klend/interest-rate.ts","../src/vendor/klend/pda.ts","../src/vendor/klend/rewards.ts","../src/vendor/klend/serialize.ts","../src/constants/misc.consts.ts","../src/utils/accounting.utils.ts","../src/utils/rpc.utils.ts","../src/vendor/klend/states.ts","../src/generated/drift/types/assetTier.ts","../src/generated/drift/types/historicalIndexData.ts","../src/generated/drift/types/historicalOracleData.ts","../src/generated/drift/types/insuranceFund.ts","../src/generated/drift/types/marginMode.ts","../src/generated/drift/types/marketStatus.ts","../src/generated/drift/types/marketType.ts","../src/generated/drift/types/oracleSource.ts","../src/generated/drift/types/order.ts","../src/generated/drift/types/orderStatus.ts","../src/generated/drift/types/orderTriggerCondition.ts","../src/generated/drift/types/orderType.ts","../src/generated/drift/types/perpPosition.ts","../src/generated/drift/types/poolBalance.ts","../src/generated/drift/types/positionDirection.ts","../src/generated/drift/types/spotBalanceType.ts","../src/generated/drift/types/spotPosition.ts","../src/generated/drift/types/userFees.ts","../src/generated/drift/accounts/spotMarket.ts","../src/generated/drift/accounts/user.ts","../src/generated/drift/accounts/userStats.ts","../src/generated/drift/programs/drift.ts","../src/generated/drift/instructions/updateSpotMarketCumulativeInterest.ts","../src/vendor/drift/accounts.ts","../src/vendor/drift/pda.ts","../src/vendor/drift/instructions.ts","../src/vendor/drift/interest-rate.ts","../src/vendor/drift/rewards.ts","../src/vendor/drift/serialize.ts","../src/vendor/drift/states.ts","../src/generated/jup-lend/accounts/lending.ts","../src/generated/jup-lend/accounts/lendingRewardsRateModel.ts","../src/generated/jup-lend/pdas/fTokenMint.ts","../src/generated/jup-lend/pdas/lending.ts","../src/generated/jup-lend/pdas/lendingAdmin.ts","../src/generated/jup-lend/programs/lending.ts","../src/generated/jup-lend/instructions/updateRate.ts","../src/generated/jup-lend-liquidity/accounts/rateModel.ts","../src/generated/jup-lend-liquidity/accounts/tokenReserve.ts","../src/generated/jup-lend-liquidity/pdas/liquidity.ts","../src/generated/jup-lend-liquidity/pdas/rateModel.ts","../src/generated/jup-lend-liquidity/pdas/tokenReserve.ts","../src/generated/jup-lend-liquidity/pdas/userSupplyPosition.ts","../src/generated/jup-lend-liquidity/programs/liquidity.ts","../src/vendor/jup-lend/accounts.ts","../src/vendor/jup-lend/instructions.ts","../src/vendor/jup-lend/interest-rate.ts","../src/vendor/jup-lend/pda.ts","../src/vendor/jup-lend/rewards.ts","../src/vendor/jup-lend/serialize.ts","../src/vendor/jup-lend/states.ts","../src/generated/gamma/accounts/lpVault.ts","../src/generated/gamma/accounts/withdrawReceipt.ts","../src/generated/gamma/pdas/completeWithdrawalWithdrawEscrow.ts","../src/generated/gamma/pdas/withdrawReceipt.ts","../src/generated/gamma/programs/gammaVault.ts","../src/vendor/gamma/accounts.ts","../src/vendor/titan/client.ts","../src/vendor/titan/types.ts","../src/vendor/titan/helpers.ts","../src/vendor/titan/gateway.ts"],"names":["address","getProgramDerivedAddress","getAddressEncoder","AccountRole","TOKEN_PROGRAM_ADDRESS","getU64Encoder","getStructDecoder","getU64Decoder","fixDecoderSize","getBytesDecoder","containsBytes","BigNumber","decoder","getAddressDecoder","getU128Decoder","getU8Decoder","getArrayDecoder","getU32Decoder","getU16Decoder","getTokenInfoDecoder","getI64Decoder","transformEncoder","getStructEncoder","fixEncoderSize","getBytesEncoder","getAccountMetaFactory","getBooleanEncoder","Decimal","KaminoInterestRateBasis","slotAdjustmentFactor","DEFAULT_ADDRESS","aprToApy","parseBase64RpcAccount","AssetTier","getEnumDecoder","MarginMode","MarketStatus","MarketType","OracleSource","getI32Decoder","getBooleanDecoder","OrderStatus","OrderTriggerCondition","OrderType","PositionDirection","SpotBalanceType","getI16Decoder","decodeAccount","fetchEncodedAccounts","getU16Encoder","SLOTS_PER_YEAR","findAssociatedTokenPda","getMintDecoder","addDecoderSizePrefix","getUtf8Decoder","Encoder","Decoder","WebSocket","SwapMode","SwapVersion","upgradeRoleToWritable","upgradeRoleToSigner","getBase64Encoder","fetchJsonParsedAccounts","assertAccountDecoded","isSignerRole","isWritableRole","getBase64Decoder","decode"],"mappings":";;;;;;;;;;;;;;;AAGO,IAAM,2BAAA,GAA8BA,YAAQ,6CAA6C;AAEhG,eAAe,OAAA,CAAQ,aAAsB,MAAA,EAAkC;AAC7E,EAAA,MAAM,CAAC,GAAG,CAAA,GAAI,MAAMC,4BAAA,CAAyB;AAAA,IAC3C,cAAA,EAAgB,2BAAA;AAAA,IAChB,OAAO,CAAC,MAAA,EAAQC,uBAAkB,CAAE,MAAA,CAAO,WAAW,CAAC;AAAA,GACxD,CAAA;AACD,EAAA,OAAO,GAAA;AACT;AAGO,SAAS,gBAAgB,WAAA,EAAwC;AACtE,EAAA,OAAO,OAAA,CAAQ,aAAa,MAAM,CAAA;AACpC;AAGO,SAAS,qBAAqB,IAAA,EAAiC;AACpE,EAAA,OAAO,OAAA,CAAQ,MAAM,OAAO,CAAA;AAC9B;AAGO,SAAS,sBAAsB,IAAA,EAAiC;AACrE,EAAA,OAAO,OAAA,CAAQ,MAAM,QAAQ,CAAA;AAC/B;AAGO,SAAS,oBAAoB,IAAA,EAAiC;AACnE,EAAA,OAAO,OAAA,CAAQ,MAAM,MAAM,CAAA;AAC7B;AAGO,SAAS,8BAA8B,IAAA,EAAiC;AAC7E,EAAA,OAAO,OAAA,CAAQ,MAAM,iBAAiB,CAAA;AACxC;AAGO,SAAS,6BAA6B,IAAA,EAAiC;AAC5E,EAAA,OAAO,OAAA,CAAQ,MAAM,gBAAgB,CAAA;AACvC;ACtBA,IAAM,qBAAA,GAAwBF,YAAQ,6CAA6C,CAAA;AACnF,IAAM,oBAAA,GAAuBA,YAAQ,6CAA6C,CAAA;AAClF,IAAM,4BAAA,GAA+BA,YAAQ,6CAA6C,CAAA;AAE1F,IAAM,aAAA,GAAgB,CAAA;AACtB,IAAM,cAAA,GAAiB,CAAA;A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MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA;AAClC,IAAA,IAAI,MAAA,IAAU,aAAA,CAAc,MAAA,EAAQ,QAAQ,GAAG,OAAO,MAAA;AAAA,EACxD;AAEA,EAAA,OAAO,MAAA,CAAO,MAAA;AAAA,IAAO,CAAC,IAAA,EAAM,KAAA,KAC1B,QAAA,KAAa,YACT,KAAA,CAAM,SAAA,GAAY,IAAA,CAAK,SAAA,GACrB,QACA,IAAA,GACF,KAAA,CAAM,QAAA,GAAW,IAAA,CAAK,WACpB,KAAA,GACA;AAAA,GACR;AACF;AAGO,SAAS,gCAAgC,EAAA,EAAuC;AACrF,EAAA,OAAO;AAAA,IACL,cAAA,EAAgBvD,qBAAAA,EAAkB,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,IAC/C,QAAA,EAAU,EAAA,CAAG,CAAA,CACV,GAAA,CAAI,CAAC,OAAA,MAAa;AAAA,MACjB,OAAA,EAASA,qBAAAA,EAAkB,CAAE,MAAA,CAAO,QAAQ,CAAC,CAAA;AAAA,MAC7C,IAAA,EAAM,gBAAA,CAAiB,OAAA,CAAQ,CAAA,EAAG,QAAQ,CAAC;AAAA,KAC7C,CAAE,EACD,MAAA,CAAO,CAAC,YAAY,CAAC,eAAA,CAAgB,OAAA,CAAQ,OAAO,CAAC,CAAA;AAAA,IACxD,IAAA,EAAM,UAAA,CAAW,IAAA,CAAK,EAAA,CAAG,CAAC;AAAA,GAC5B;AACF","file":"vendor.cjs","sourcesContent":["import { address, getAddressEncoder, getProgramDerivedAddress, type Address } from \"@solana/kit\";\n\n/** SPL Single Pool program. */\nexport const SINGLE_POOL_PROGRAM_ADDRESS = address(\"SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE\");\n\nasync function findPda(baseAddress: Address, prefix: string): Promise<Address> {\n const [pda] = await getProgramDerivedAddress({\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n seeds: [prefix, getAddressEncoder().encode(baseAddress)],\n });\n return pda;\n}\n\n/** Single pool of a validator vote account. */\nexport function findPoolAddress(voteAccount: Address): Promise<Address> {\n return findPda(voteAccount, \"pool\");\n}\n\n/** Pool's main stake account. */\nexport function findPoolStakeAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"stake\");\n}\n\n/** Pool's on-ramp stake account (activates new deposits). */\nexport function findPoolOnRampAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"onramp\");\n}\n\n/** Pool token (LST) mint. */\nexport function findPoolMintAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"mint\");\n}\n\n/** Pool stake authority. */\nexport function findPoolStakeAuthorityAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"stake_authority\");\n}\n\n/** Pool token mint authority. */\nexport function findPoolMintAuthorityAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"mint_authority\");\n}\n","import {\n AccountRole,\n address,\n getAddressEncoder,\n getU64Encoder,\n type Address,\n type Instruction,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\n\nimport {\n findPoolMintAddress,\n findPoolMintAuthorityAddress,\n findPoolOnRampAddress,\n findPoolStakeAddress,\n findPoolStakeAuthorityAddress,\n SINGLE_POOL_PROGRAM_ADDRESS,\n} from \"./addresses\";\n\nconst STAKE_PROGRAM_ADDRESS = address(\"Stake11111111111111111111111111111111111111\");\nconst SYSVAR_CLOCK_ADDRESS = address(\"SysvarC1ock11111111111111111111111111111111\");\nconst SYSVAR_STAKE_HISTORY_ADDRESS = address(\"SysvarStakeHistory1111111111111111111111111\");\n\nconst DEPOSIT_STAKE = 2;\nconst WITHDRAW_STAKE = 3;\n\nasync function poolAccounts(pool: Address) {\n const [stake, onRamp, mint, stakeAuthority, mintAuthority] = await Promise.all([\n findPoolStakeAddress(pool),\n findPoolOnRampAddress(pool),\n findPoolMintAddress(pool),\n findPoolStakeAuthorityAddress(pool),\n findPoolMintAuthorityAddress(pool),\n ]);\n return [\n { address: pool, role: AccountRole.READONLY },\n { address: stake, role: AccountRole.WRITABLE },\n { address: onRamp, role: AccountRole.READONLY },\n { address: mint, role: AccountRole.WRITABLE },\n { address: stakeAuthority, role: AccountRole.READONLY },\n { address: mintAuthority, role: AccountRole.READONLY },\n ];\n}\n\n/**\n * Deposits an active stake account into a single pool, minting pool tokens to `userTokenAccount`;\n * the stake account's excess lamports go to `userLamportAccount`.\n */\nexport async function makeSinglePoolDepositStakeIx(\n pool: Address,\n userStakeAccount: Address,\n userTokenAccount: Address,\n userLamportAccount: Address\n): Promise<Instruction> {\n return {\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n accounts: [\n ...(await poolAccounts(pool)),\n { address: userStakeAccount, role: AccountRole.WRITABLE },\n { address: userTokenAccount, role: AccountRole.WRITABLE },\n { address: userLamportAccount, role: AccountRole.WRITABLE },\n { address: SYSVAR_CLOCK_ADDRESS, role: AccountRole.READONLY },\n { address: SYSVAR_STAKE_HISTORY_ADDRESS, role: AccountRole.READONLY },\n { address: TOKEN_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n { address: STAKE_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n ],\n data: new Uint8Array([DEPOSIT_STAKE]),\n };\n}\n\n/**\n * Burns `tokenAmount` pool tokens (native units, 9 decimals) from `userTokenAccount` and splits that\n * stake into `userStakeAccount`, owned by `userStakeAuthority`.\n */\nexport async function makeSinglePoolWithdrawStakeIx(\n pool: Address,\n userStakeAccount: Address,\n userStakeAuthority: Address,\n userTokenAccount: Address,\n tokenAmount: bigint\n): Promise<Instruction> {\n return {\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n accounts: [\n ...(await poolAccounts(pool)),\n { address: userStakeAccount, role: AccountRole.WRITABLE },\n { address: userTokenAccount, role: AccountRole.WRITABLE },\n { address: SYSVAR_CLOCK_ADDRESS, role: AccountRole.READONLY },\n { address: TOKEN_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n { address: STAKE_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n ],\n data: new Uint8Array([\n WITHDRAW_STAKE,\n ...getAddressEncoder().encode(userStakeAuthority),\n ...getU64Encoder().encode(tokenAmount),\n ]),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { getPriceDecoder, getPriceEncoder, type Price, type PriceArgs } from \".\";\n\nexport type DatedPrice = {\n price: Price;\n lastUpdatedSlot: bigint;\n unixTimestamp: bigint;\n genericData: ReadonlyUint8Array;\n};\n\nexport type DatedPriceArgs = {\n price: PriceArgs;\n lastUpdatedSlot: number | bigint;\n unixTimestamp: number | bigint;\n genericData: ReadonlyUint8Array;\n};\n\nexport function getDatedPriceEncoder(): FixedSizeEncoder<DatedPriceArgs> {\n return getStructEncoder([\n [\"price\", getPriceEncoder()],\n [\"lastUpdatedSlot\", getU64Encoder()],\n [\"unixTimestamp\", getU64Encoder()],\n [\"genericData\", fixEncoderSize(getBytesEncoder(), 24)],\n ]);\n}\n\nexport function getDatedPriceDecoder(): FixedSizeDecoder<DatedPrice> {\n return getStructDecoder([\n [\"price\", getPriceDecoder()],\n [\"lastUpdatedSlot\", getU64Decoder()],\n [\"unixTimestamp\", getU64Decoder()],\n [\"genericData\", fixDecoderSize(getBytesDecoder(), 24)],\n ]);\n}\n\nexport function getDatedPriceCodec(): FixedSizeCodec<DatedPriceArgs, DatedPrice> {\n return combineCodec(getDatedPriceEncoder(), getDatedPriceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type Price = { value: bigint; exp: bigint };\n\nexport type PriceArgs = { value: number | bigint; exp: number | bigint };\n\nexport function getPriceEncoder(): FixedSizeEncoder<PriceArgs> {\n return getStructEncoder([\n [\"value\", getU64Encoder()],\n [\"exp\", getU64Encoder()],\n ]);\n}\n\nexport function getPriceDecoder(): FixedSizeDecoder<Price> {\n return getStructDecoder([\n [\"value\", getU64Decoder()],\n [\"exp\", getU64Decoder()],\n ]);\n}\n\nexport function getPriceCodec(): FixedSizeCodec<PriceArgs, Price> {\n return combineCodec(getPriceEncoder(), getPriceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getDatedPriceDecoder,\n getDatedPriceEncoder,\n type DatedPrice,\n type DatedPriceArgs,\n} from \"../types\";\n\nexport const ORACLE_PRICES_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 89, 128, 118, 221, 6, 72, 180, 146,\n]);\n\nexport function getOraclePricesDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(ORACLE_PRICES_DISCRIMINATOR);\n}\n\nexport type OraclePrices = {\n discriminator: ReadonlyUint8Array;\n oracleMappings: Address;\n prices: Array<DatedPrice>;\n};\n\nexport type OraclePricesArgs = { oracleMappings: Address; prices: Array<DatedPriceArgs> };\n\n/** Gets the encoder for {@link OraclePricesArgs} account data. */\nexport function getOraclePricesEncoder(): FixedSizeEncoder<OraclePricesArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"oracleMappings\", getAddressEncoder()],\n [\"prices\", getArrayEncoder(getDatedPriceEncoder(), { size: 512 })],\n ]),\n (value) => ({ ...value, discriminator: ORACLE_PRICES_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link OraclePrices} account data. */\nexport function getOraclePricesDecoder(): FixedSizeDecoder<OraclePrices> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"oracleMappings\", getAddressDecoder()],\n [\"prices\", getArrayDecoder(getDatedPriceDecoder(), { size: 512 })],\n ]);\n}\n\n/** Gets the codec for {@link OraclePrices} account data. */\nexport function getOraclePricesCodec(): FixedSizeCodec<OraclePricesArgs, OraclePrices> {\n return combineCodec(getOraclePricesEncoder(), getOraclePricesDecoder());\n}\n\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<OraclePrices, TAddress>;\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<OraclePrices, TAddress>;\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<OraclePrices, TAddress> | MaybeAccount<OraclePrices, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getOraclePricesDecoder());\n}\n\nexport async function fetchOraclePrices<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<OraclePrices, TAddress>> {\n const maybeAccount = await fetchMaybeOraclePrices(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeOraclePrices<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<OraclePrices, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeOraclePrices(maybeAccount);\n}\n\nexport async function fetchAllOraclePrices(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<OraclePrices>[]> {\n const maybeAccounts = await fetchAllMaybeOraclePrices(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeOraclePrices(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<OraclePrices>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeOraclePrices(maybeAccount));\n}\n\nexport function getOraclePricesSize(): number {\n return 28712;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport { getOraclePricesCodec, type OraclePrices, type OraclePricesArgs } from \"../accounts\";\n\nexport const SCOPE_PROGRAM_ADDRESS =\n \"HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ\" as Address<\"HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ\">;\n\nexport enum ScopeAccount {\n OraclePrices,\n}\n\nexport function identifyScopeAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ScopeAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([89, 128, 118, 221, 6, 72, 180, 146])\n ),\n 0\n )\n ) {\n return ScopeAccount.OraclePrices;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"scope\",\n });\n}\n\nexport type ScopePlugin = {\n accounts: ScopePluginAccounts;\n identifyAccount: typeof identifyScopeAccount;\n};\n\nexport type ScopePluginAccounts = {\n oraclePrices: ReturnType<typeof getOraclePricesCodec> &\n SelfFetchFunctions<OraclePricesArgs, OraclePrices>;\n};\n\nexport type ScopePluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function scopeProgram() {\n return <T extends ScopePluginRequirements>(\n client: T\n ): ExtendedClient<T, { scope: ScopePlugin }> => {\n return extendClient(client, {\n scope: <ScopePlugin>{\n accounts: { oraclePrices: addSelfFetchFunctions(client, getOraclePricesCodec()) },\n identifyAccount: identifyScopeAccount,\n },\n });\n };\n}\n","import { containsBytes, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nimport {\n getDatedPriceDecoder,\n getOraclePricesSize,\n ORACLE_PRICES_DISCRIMINATOR,\n} from \"~/generated/scope\";\n\nexport { SCOPE_PROGRAM_ADDRESS } from \"~/generated/scope\";\n\n/** Price entries in a Scope `OraclePrices` account. */\nexport const SCOPE_MAX_ENTRIES = 512;\n\n// OraclePrices layout: 8 (discriminator) + 32 (oracle_mappings) + 512 × 56 (DatedPrice entries)\nconst ENTRIES_OFFSET = 40;\nconst DATED_PRICE_SIZE = 56;\n\nexport interface ScopeDatedPrice {\n /** Decimal price, i.e. `value / 10^exp` */\n price: BigNumber;\n lastUpdatedSlot: number;\n unixTimestamp: number;\n}\n\n/**\n * Decodes entry `entryIndex` of a Scope `OraclePrices` account. A never-refreshed entry reads as a\n * zero price.\n * @throws if the account has the wrong size or discriminator, the index is out of range, or the\n * exponent is past the program's power-of-ten table (≥ 24)\n */\nexport function decodeScopePriceAtIndex(\n data: ReadonlyUint8Array,\n entryIndex: number\n): ScopeDatedPrice {\n if (data.length !== getOraclePricesSize()) {\n throw new Error(`Invalid Scope OraclePrices account size: ${data.length}`);\n }\n if (entryIndex < 0 || entryIndex >= SCOPE_MAX_ENTRIES) {\n throw new Error(`Scope entry index out of range: ${entryIndex}`);\n }\n\n if (!containsBytes(data, ORACLE_PRICES_DISCRIMINATOR, 0)) {\n throw new Error(\"Invalid Scope OraclePrices account discriminator\");\n }\n\n // Decode only the requested entry rather than all 512.\n const { price, lastUpdatedSlot, unixTimestamp } = getDatedPriceDecoder().decode(\n data,\n ENTRIES_OFFSET + entryIndex * DATED_PRICE_SIZE\n );\n\n // Same bound as the program's MAX_EXP_10_I80F48\n if (price.exp >= 24n) {\n throw new Error(`Scope entry exponent out of bounds: ${price.exp}`);\n }\n\n return {\n price: new BigNumber(price.value.toString()).shiftedBy(-Number(price.exp)),\n lastUpdatedSlot: Number(lastUpdatedSlot),\n unixTimestamp: Number(unixTimestamp),\n };\n}\n","import { address, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nexport const MARINADE_PROGRAM_ADDRESS = address(\"MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD\");\n\n/** sha256(\"account:State\")[..8] */\nexport const MARINADE_STATE_DISCRIMINATOR = new Uint8Array([216, 146, 107, 94, 104, 75, 182, 177]);\n\n// Absolute byte offsets in Marinade's State account, including the 8-byte Anchor discriminator.\n// These are the fields used by Marinade's `total_virtual_staked_lamports` calculation and by the\n// marginfi program's canonical mSOL/SOL multiplier.\nconst DELAYED_UNSTAKE_COOLING_DOWN_OFFSET = 226;\nconst TOTAL_ACTIVE_BALANCE_OFFSET = 376;\nconst AVAILABLE_RESERVE_BALANCE_OFFSET = 496;\nconst MSOL_SUPPLY_OFFSET = 504;\nconst CIRCULATING_TICKET_BALANCE_OFFSET = 528;\nconst EMERGENCY_COOLING_DOWN_OFFSET = 568;\nexport const MARINADE_STATE_MIN_SIZE = EMERGENCY_COOLING_DOWN_OFFSET + 8;\nconst U64_MAX = (1n << 64n) - 1n;\n\n// Same sanity ceiling as the program's MAX_LST_SOL_RATE\nconst MAX_MSOL_SOL_RATE = 3;\n\nexport interface MarinadeState {\n /** mSOL/SOL exchange rate */\n msolPrice: BigNumber;\n}\n\n/**\n * Decodes the mSOL/SOL rate from a Marinade `State` account.\n * @throws if the account is undersized, has a wrong discriminator, has no mSOL supply, or yields a\n * rate outside (0, 3)\n */\nexport function decodeMarinadeState(data: ReadonlyUint8Array): MarinadeState {\n if (data.length < MARINADE_STATE_MIN_SIZE) {\n throw new Error(`Invalid Marinade State account size: ${data.length}`);\n }\n if (MARINADE_STATE_DISCRIMINATOR.some((byte, i) => data[i] !== byte)) {\n throw new Error(\"Invalid Marinade State discriminator\");\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const u64 = (offset: number) => view.getBigUint64(offset, true);\n\n const msolSupply = u64(MSOL_SUPPLY_OFFSET);\n if (msolSupply === 0n) {\n throw new Error(\"Marinade State has zero mSOL supply\");\n }\n\n const underControl =\n u64(TOTAL_ACTIVE_BALANCE_OFFSET) +\n u64(DELAYED_UNSTAKE_COOLING_DOWN_OFFSET) +\n u64(EMERGENCY_COOLING_DOWN_OFFSET) +\n u64(AVAILABLE_RESERVE_BALANCE_OFFSET);\n if (underControl > U64_MAX) {\n throw new Error(\"Marinade virtual staked balance overflow\");\n }\n\n // Marinade uses saturating subtraction for outstanding delayed-unstake tickets.\n const circulatingTicketBalance = u64(CIRCULATING_TICKET_BALANCE_OFFSET);\n const totalVirtualStakedLamports =\n underControl > circulatingTicketBalance ? underControl - circulatingTicketBalance : 0n;\n const msolPrice = new BigNumber(totalVirtualStakedLamports.toString()).div(msolSupply.toString());\n\n if (!msolPrice.gt(0) || msolPrice.gte(MAX_MSOL_SOL_RATE)) {\n throw new Error(`Marinade mSOL/SOL rate out of bounds: ${msolPrice.toString()}`);\n }\n\n return { msolPrice };\n}\n","import { address, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nexport const SPL_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SPoo1Ku8WFXoNDMHPsrGSTSG1Y47rzgn41SLUNakuHy\"\n);\nexport const SANCTUM_SPL_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SP12tWFxD9oJsVWNavTTBZvMbA6gkAmxtVgxdqvyvhY\"\n);\nexport const SANCTUM_SPL_MULTI_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SPMBzsVUuoHA4Jm6KunbsotaahvVikZs1JyTW6iJvbn\"\n);\n\n// StakePool is borsh-serialized from byte 0: account_type u8 @0, then 8 pubkeys + a bump byte,\n// then total_lamports u64 @258, pool_token_supply u64 @266, last_update_epoch u64 @274.\nconst ACCOUNT_TYPE_STAKE_POOL = 1;\nconst TOTAL_LAMPORTS_OFFSET = 258;\nconst POOL_TOKEN_SUPPLY_OFFSET = 266;\nconst LAST_UPDATE_EPOCH_OFFSET = 274;\nconst MAX_LST_SOL_RATE = 3;\n\nexport interface StakePool {\n totalLamports: bigint;\n poolTokenSupply: bigint;\n lastUpdateEpoch: number;\n /** LST/SOL exchange rate, i.e. `total_lamports / pool_token_supply` */\n exchangeRate: BigNumber;\n}\n\n/**\n * Decodes the balances and LST/SOL rate of an SPL (or Sanctum) stake pool account.\n * @throws if the account is undersized, is not a StakePool, has no token supply, or yields a rate\n * outside (0, 3)\n */\nexport function decodeStakePool(data: ReadonlyUint8Array): StakePool {\n if (data.length < LAST_UPDATE_EPOCH_OFFSET + 8) {\n throw new Error(`Invalid StakePool account size: ${data.length}`);\n }\n if (data[0] !== ACCOUNT_TYPE_STAKE_POOL) {\n throw new Error(`Invalid StakePool account type: ${data[0]}`);\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const totalLamports = view.getBigUint64(TOTAL_LAMPORTS_OFFSET, true);\n const poolTokenSupply = view.getBigUint64(POOL_TOKEN_SUPPLY_OFFSET, true);\n const lastUpdateEpoch = Number(view.getBigUint64(LAST_UPDATE_EPOCH_OFFSET, true));\n\n if (poolTokenSupply === 0n) {\n throw new Error(\"StakePool has zero token supply\");\n }\n\n const exchangeRate = new BigNumber(totalLamports.toString()).div(poolTokenSupply.toString());\n\n // Same sanity bounds as the program's MAX_LST_SOL_RATE\n if (!exchangeRate.gt(0) || exchangeRate.gte(MAX_LST_SOL_RATE)) {\n throw new Error(`StakePool LST/SOL rate out of bounds: ${exchangeRate.toString()}`);\n }\n\n return { totalLamports, poolTokenSupply, lastUpdateEpoch, exchangeRate };\n}\n","import { containsBytes, type Decoder, type ReadonlyUint8Array } from \"@solana/kit\";\n\n// Generated decoders don't check the discriminator; wrappers use this so a wrong account fails loudly.\nexport function decodeAccountData<T>(\n data: ReadonlyUint8Array,\n discriminator: ReadonlyUint8Array,\n decoder: Decoder<T>,\n accountName: string\n): T {\n if (!containsBytes(data, discriminator, 0)) {\n throw new Error(`Invalid ${accountName} account discriminator`);\n }\n return decoder.decode(data);\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getRewardScheduleCurveDecoder,\n getRewardScheduleCurveEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n type RewardScheduleCurve,\n type RewardScheduleCurveArgs,\n type TokenInfo,\n type TokenInfoArgs,\n} from \".\";\n\nexport type RewardInfo = {\n token: TokenInfo;\n rewardsVault: Address;\n rewardsAvailable: bigint;\n rewardScheduleCurve: RewardScheduleCurve;\n minClaimDurationSeconds: bigint;\n lastIssuanceTs: bigint;\n rewardsIssuedUnclaimed: bigint;\n rewardsIssuedCumulative: bigint;\n rewardPerShareScaled: bigint;\n placeholder0: bigint;\n rewardType: number;\n rewardsPerSecondDecimals: number;\n padding0: ReadonlyUint8Array;\n padding1: Array<bigint>;\n};\n\nexport type RewardInfoArgs = {\n token: TokenInfoArgs;\n rewardsVault: Address;\n rewardsAvailable: number | bigint;\n rewardScheduleCurve: RewardScheduleCurveArgs;\n minClaimDurationSeconds: number | bigint;\n lastIssuanceTs: number | bigint;\n rewardsIssuedUnclaimed: number | bigint;\n rewardsIssuedCumulative: number | bigint;\n rewardPerShareScaled: number | bigint;\n placeholder0: number | bigint;\n rewardType: number;\n rewardsPerSecondDecimals: number;\n padding0: ReadonlyUint8Array;\n padding1: Array<number | bigint>;\n};\n\nexport function getRewardInfoEncoder(): FixedSizeEncoder<RewardInfoArgs> {\n return getStructEncoder([\n [\"token\", getTokenInfoEncoder()],\n [\"rewardsVault\", getAddressEncoder()],\n [\"rewardsAvailable\", getU64Encoder()],\n [\"rewardScheduleCurve\", getRewardScheduleCurveEncoder()],\n [\"minClaimDurationSeconds\", getU64Encoder()],\n [\"lastIssuanceTs\", getU64Encoder()],\n [\"rewardsIssuedUnclaimed\", getU64Encoder()],\n [\"rewardsIssuedCumulative\", getU64Encoder()],\n [\"rewardPerShareScaled\", getU128Encoder()],\n [\"placeholder0\", getU64Encoder()],\n [\"rewardType\", getU8Encoder()],\n [\"rewardsPerSecondDecimals\", getU8Encoder()],\n [\"padding0\", fixEncoderSize(getBytesEncoder(), 6)],\n [\"padding1\", getArrayEncoder(getU64Encoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardInfoDecoder(): FixedSizeDecoder<RewardInfo> {\n return getStructDecoder([\n [\"token\", getTokenInfoDecoder()],\n [\"rewardsVault\", getAddressDecoder()],\n [\"rewardsAvailable\", getU64Decoder()],\n [\"rewardScheduleCurve\", getRewardScheduleCurveDecoder()],\n [\"minClaimDurationSeconds\", getU64Decoder()],\n [\"lastIssuanceTs\", getU64Decoder()],\n [\"rewardsIssuedUnclaimed\", getU64Decoder()],\n [\"rewardsIssuedCumulative\", getU64Decoder()],\n [\"rewardPerShareScaled\", getU128Decoder()],\n [\"placeholder0\", getU64Decoder()],\n [\"rewardType\", getU8Decoder()],\n [\"rewardsPerSecondDecimals\", getU8Decoder()],\n [\"padding0\", fixDecoderSize(getBytesDecoder(), 6)],\n [\"padding1\", getArrayDecoder(getU64Decoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardInfoCodec(): FixedSizeCodec<RewardInfoArgs, RewardInfo> {\n return combineCodec(getRewardInfoEncoder(), getRewardInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type RewardPerTimeUnitPoint = { tsStart: bigint; rewardPerTimeUnit: bigint };\n\nexport type RewardPerTimeUnitPointArgs = {\n tsStart: number | bigint;\n rewardPerTimeUnit: number | bigint;\n};\n\nexport function getRewardPerTimeUnitPointEncoder(): FixedSizeEncoder<RewardPerTimeUnitPointArgs> {\n return getStructEncoder([\n [\"tsStart\", getU64Encoder()],\n [\"rewardPerTimeUnit\", getU64Encoder()],\n ]);\n}\n\nexport function getRewardPerTimeUnitPointDecoder(): FixedSizeDecoder<RewardPerTimeUnitPoint> {\n return getStructDecoder([\n [\"tsStart\", getU64Decoder()],\n [\"rewardPerTimeUnit\", getU64Decoder()],\n ]);\n}\n\nexport function getRewardPerTimeUnitPointCodec(): FixedSizeCodec<\n RewardPerTimeUnitPointArgs,\n RewardPerTimeUnitPoint\n> {\n return combineCodec(getRewardPerTimeUnitPointEncoder(), getRewardPerTimeUnitPointDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getRewardPerTimeUnitPointDecoder,\n getRewardPerTimeUnitPointEncoder,\n type RewardPerTimeUnitPoint,\n type RewardPerTimeUnitPointArgs,\n} from \".\";\n\nexport type RewardScheduleCurve = {\n /**\n * This is a stepwise function, meaning that each point represents\n * how many rewards are issued per time unit since the beginning\n * of that point until the beginning of the next point.\n * This is not a linear curve, there is no interpolation going on.\n * A curve can be [[t0, 100], [t1, 50], [t2, 0]]\n * meaning that from t0 to t1, 100 rewards are issued per time unit,\n * from t1 to t2, 50 rewards are issued per time unit, and after t2 it stops\n * Another curve, can be [[t0, 100], [u64::max, 0]]\n * meaning that from t0 to u64::max, 100 rewards are issued per time unit\n */\n points: Array<RewardPerTimeUnitPoint>;\n};\n\nexport type RewardScheduleCurveArgs = {\n /**\n * This is a stepwise function, meaning that each point represents\n * how many rewards are issued per time unit since the beginning\n * of that point until the beginning of the next point.\n * This is not a linear curve, there is no interpolation going on.\n * A curve can be [[t0, 100], [t1, 50], [t2, 0]]\n * meaning that from t0 to t1, 100 rewards are issued per time unit,\n * from t1 to t2, 50 rewards are issued per time unit, and after t2 it stops\n * Another curve, can be [[t0, 100], [u64::max, 0]]\n * meaning that from t0 to u64::max, 100 rewards are issued per time unit\n */\n points: Array<RewardPerTimeUnitPointArgs>;\n};\n\nexport function getRewardScheduleCurveEncoder(): FixedSizeEncoder<RewardScheduleCurveArgs> {\n return getStructEncoder([\n [\"points\", getArrayEncoder(getRewardPerTimeUnitPointEncoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardScheduleCurveDecoder(): FixedSizeDecoder<RewardScheduleCurve> {\n return getStructDecoder([\n [\"points\", getArrayDecoder(getRewardPerTimeUnitPointDecoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardScheduleCurveCodec(): FixedSizeCodec<\n RewardScheduleCurveArgs,\n RewardScheduleCurve\n> {\n return combineCodec(getRewardScheduleCurveEncoder(), getRewardScheduleCurveDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type TokenInfo = {\n mint: Address;\n decimals: bigint;\n tokenProgram: Address;\n padding: Array<bigint>;\n};\n\nexport type TokenInfoArgs = {\n mint: Address;\n decimals: number | bigint;\n tokenProgram: Address;\n padding: Array<number | bigint>;\n};\n\nexport function getTokenInfoEncoder(): FixedSizeEncoder<TokenInfoArgs> {\n return getStructEncoder([\n [\"mint\", getAddressEncoder()],\n [\"decimals\", getU64Encoder()],\n [\"tokenProgram\", getAddressEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 6 })],\n ]);\n}\n\nexport function getTokenInfoDecoder(): FixedSizeDecoder<TokenInfo> {\n return getStructDecoder([\n [\"mint\", getAddressDecoder()],\n [\"decimals\", getU64Decoder()],\n [\"tokenProgram\", getAddressDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 6 })],\n ]);\n}\n\nexport function getTokenInfoCodec(): FixedSizeCodec<TokenInfoArgs, TokenInfo> {\n return combineCodec(getTokenInfoEncoder(), getTokenInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getRewardInfoDecoder,\n getRewardInfoEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n type RewardInfo,\n type RewardInfoArgs,\n type TokenInfo,\n type TokenInfoArgs,\n} from \"../types\";\n\nexport const FARM_STATE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 198, 102, 216, 74, 63, 66, 163, 190,\n]);\n\nexport function getFarmStateDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(FARM_STATE_DISCRIMINATOR);\n}\n\nexport type FarmState = {\n discriminator: ReadonlyUint8Array;\n farmAdmin: Address;\n globalConfig: Address;\n token: TokenInfo;\n rewardInfos: Array<RewardInfo>;\n numRewardTokens: bigint;\n /** Data used to calculate the rewards of the user */\n numUsers: bigint;\n /**\n * The number of token in the `farm_vault` staked (getting rewards and fees)\n * Set such as `farm_vault.amount = total_staked_amount + total_pending_amount`\n */\n totalStakedAmount: bigint;\n farmVault: Address;\n farmVaultsAuthority: Address;\n farmVaultsAuthorityBump: bigint;\n /**\n * Only used for delegate farms\n * Set to `default()` otherwise\n */\n delegateAuthority: Address;\n /**\n * Raw representation of a `TimeUnit`\n * Seconds = 0, Slots = 1\n */\n timeUnit: number;\n /**\n * Automatically set to true in case of a full authority withdrawal\n * If true, the farm is frozen and no more deposits are allowed\n */\n isFarmFrozen: number;\n /**\n * Indicates if the farm is a delegate farm\n * If true, the farm is a delegate farm and the `delegate_authority` is set*\n */\n isFarmDelegated: number;\n /** If set to 1, indicates that the \"reward user once\" feature is enabled */\n isRewardUserOnceEnabled: number;\n isHarvestingPermissionless: number;\n padding0: ReadonlyUint8Array;\n /**\n * Withdraw authority for the farm, allowed to lock deposited funds and withdraw them\n * Set to `default()` if unused (only the depositors can withdraw their funds)\n */\n withdrawAuthority: Address;\n /**\n * Delay between a user deposit and the moment it is considered as staked\n * 0 if unused\n */\n depositWarmupPeriod: number;\n /** Delay between a user unstake and the ability to withdraw his deposit. */\n withdrawalCooldownPeriod: number;\n /** Total active stake of tokens in the farm (scaled from `Decimal` representation). */\n totalActiveStakeScaled: bigint;\n /**\n * Total pending stake of tokens in the farm (scaled from `Decimal` representation).\n * (can be used by `withdraw_authority` but don't get rewards or fees)\n */\n totalPendingStakeScaled: bigint;\n /** Total pending amount of tokens in the farm */\n totalPendingAmount: bigint;\n /** Slashed amounts from early withdrawal */\n slashedAmountCurrent: bigint;\n slashedAmountCumulative: bigint;\n slashedAmountSpillAddress: Address;\n /** Locking stake */\n lockingMode: bigint;\n lockingStartTimestamp: bigint;\n lockingDuration: bigint;\n lockingEarlyWithdrawalPenaltyBps: bigint;\n depositCapAmount: bigint;\n scopePrices: Address;\n scopeOraclePriceId: bigint;\n scopeOracleMaxAge: bigint;\n pendingFarmAdmin: Address;\n strategyId: Address;\n delegatedRpsAdmin: Address;\n vaultId: Address;\n secondDelegatedAuthority: Address;\n padding: Array<bigint>;\n};\n\nexport type FarmStateArgs = {\n farmAdmin: Address;\n globalConfig: Address;\n token: TokenInfoArgs;\n rewardInfos: Array<RewardInfoArgs>;\n numRewardTokens: number | bigint;\n /** Data used to calculate the rewards of the user */\n numUsers: number | bigint;\n /**\n * The number of token in the `farm_vault` staked (getting rewards and fees)\n * Set such as `farm_vault.amount = total_staked_amount + total_pending_amount`\n */\n totalStakedAmount: number | bigint;\n farmVault: Address;\n farmVaultsAuthority: Address;\n farmVaultsAuthorityBump: number | bigint;\n /**\n * Only used for delegate farms\n * Set to `default()` otherwise\n */\n delegateAuthority: Address;\n /**\n * Raw representation of a `TimeUnit`\n * Seconds = 0, Slots = 1\n */\n timeUnit: number;\n /**\n * Automatically set to true in case of a full authority withdrawal\n * If true, the farm is frozen and no more deposits are allowed\n */\n isFarmFrozen: number;\n /**\n * Indicates if the farm is a delegate farm\n * If true, the farm is a delegate farm and the `delegate_authority` is set*\n */\n isFarmDelegated: number;\n /** If set to 1, indicates that the \"reward user once\" feature is enabled */\n isRewardUserOnceEnabled: number;\n isHarvestingPermissionless: number;\n padding0: ReadonlyUint8Array;\n /**\n * Withdraw authority for the farm, allowed to lock deposited funds and withdraw them\n * Set to `default()` if unused (only the depositors can withdraw their funds)\n */\n withdrawAuthority: Address;\n /**\n * Delay between a user deposit and the moment it is considered as staked\n * 0 if unused\n */\n depositWarmupPeriod: number;\n /** Delay between a user unstake and the ability to withdraw his deposit. */\n withdrawalCooldownPeriod: number;\n /** Total active stake of tokens in the farm (scaled from `Decimal` representation). */\n totalActiveStakeScaled: number | bigint;\n /**\n * Total pending stake of tokens in the farm (scaled from `Decimal` representation).\n * (can be used by `withdraw_authority` but don't get rewards or fees)\n */\n totalPendingStakeScaled: number | bigint;\n /** Total pending amount of tokens in the farm */\n totalPendingAmount: number | bigint;\n /** Slashed amounts from early withdrawal */\n slashedAmountCurrent: number | bigint;\n slashedAmountCumulative: number | bigint;\n slashedAmountSpillAddress: Address;\n /** Locking stake */\n lockingMode: number | bigint;\n lockingStartTimestamp: number | bigint;\n lockingDuration: number | bigint;\n lockingEarlyWithdrawalPenaltyBps: number | bigint;\n depositCapAmount: number | bigint;\n scopePrices: Address;\n scopeOraclePriceId: number | bigint;\n scopeOracleMaxAge: number | bigint;\n pendingFarmAdmin: Address;\n strategyId: Address;\n delegatedRpsAdmin: Address;\n vaultId: Address;\n secondDelegatedAuthority: Address;\n padding: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link FarmStateArgs} account data. */\nexport function getFarmStateEncoder(): FixedSizeEncoder<FarmStateArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"farmAdmin\", getAddressEncoder()],\n [\"globalConfig\", getAddressEncoder()],\n [\"token\", getTokenInfoEncoder()],\n [\"rewardInfos\", getArrayEncoder(getRewardInfoEncoder(), { size: 10 })],\n [\"numRewardTokens\", getU64Encoder()],\n [\"numUsers\", getU64Encoder()],\n [\"totalStakedAmount\", getU64Encoder()],\n [\"farmVault\", getAddressEncoder()],\n [\"farmVaultsAuthority\", getAddressEncoder()],\n [\"farmVaultsAuthorityBump\", getU64Encoder()],\n [\"delegateAuthority\", getAddressEncoder()],\n [\"timeUnit\", getU8Encoder()],\n [\"isFarmFrozen\", getU8Encoder()],\n [\"isFarmDelegated\", getU8Encoder()],\n [\"isRewardUserOnceEnabled\", getU8Encoder()],\n [\"isHarvestingPermissionless\", getU8Encoder()],\n [\"padding0\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"withdrawAuthority\", getAddressEncoder()],\n [\"depositWarmupPeriod\", getU32Encoder()],\n [\"withdrawalCooldownPeriod\", getU32Encoder()],\n [\"totalActiveStakeScaled\", getU128Encoder()],\n [\"totalPendingStakeScaled\", getU128Encoder()],\n [\"totalPendingAmount\", getU64Encoder()],\n [\"slashedAmountCurrent\", getU64Encoder()],\n [\"slashedAmountCumulative\", getU64Encoder()],\n [\"slashedAmountSpillAddress\", getAddressEncoder()],\n [\"lockingMode\", getU64Encoder()],\n [\"lockingStartTimestamp\", getU64Encoder()],\n [\"lockingDuration\", getU64Encoder()],\n [\"lockingEarlyWithdrawalPenaltyBps\", getU64Encoder()],\n [\"depositCapAmount\", getU64Encoder()],\n [\"scopePrices\", getAddressEncoder()],\n [\"scopeOraclePriceId\", getU64Encoder()],\n [\"scopeOracleMaxAge\", getU64Encoder()],\n [\"pendingFarmAdmin\", getAddressEncoder()],\n [\"strategyId\", getAddressEncoder()],\n [\"delegatedRpsAdmin\", getAddressEncoder()],\n [\"vaultId\", getAddressEncoder()],\n [\"secondDelegatedAuthority\", getAddressEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 74 })],\n ]),\n (value) => ({ ...value, discriminator: FARM_STATE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link FarmState} account data. */\nexport function getFarmStateDecoder(): FixedSizeDecoder<FarmState> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"farmAdmin\", getAddressDecoder()],\n [\"globalConfig\", getAddressDecoder()],\n [\"token\", getTokenInfoDecoder()],\n [\"rewardInfos\", getArrayDecoder(getRewardInfoDecoder(), { size: 10 })],\n [\"numRewardTokens\", getU64Decoder()],\n [\"numUsers\", getU64Decoder()],\n [\"totalStakedAmount\", getU64Decoder()],\n [\"farmVault\", getAddressDecoder()],\n [\"farmVaultsAuthority\", getAddressDecoder()],\n [\"farmVaultsAuthorityBump\", getU64Decoder()],\n [\"delegateAuthority\", getAddressDecoder()],\n [\"timeUnit\", getU8Decoder()],\n [\"isFarmFrozen\", getU8Decoder()],\n [\"isFarmDelegated\", getU8Decoder()],\n [\"isRewardUserOnceEnabled\", getU8Decoder()],\n [\"isHarvestingPermissionless\", getU8Decoder()],\n [\"padding0\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"withdrawAuthority\", getAddressDecoder()],\n [\"depositWarmupPeriod\", getU32Decoder()],\n [\"withdrawalCooldownPeriod\", getU32Decoder()],\n [\"totalActiveStakeScaled\", getU128Decoder()],\n [\"totalPendingStakeScaled\", getU128Decoder()],\n [\"totalPendingAmount\", getU64Decoder()],\n [\"slashedAmountCurrent\", getU64Decoder()],\n [\"slashedAmountCumulative\", getU64Decoder()],\n [\"slashedAmountSpillAddress\", getAddressDecoder()],\n [\"lockingMode\", getU64Decoder()],\n [\"lockingStartTimestamp\", getU64Decoder()],\n [\"lockingDuration\", getU64Decoder()],\n [\"lockingEarlyWithdrawalPenaltyBps\", getU64Decoder()],\n [\"depositCapAmount\", getU64Decoder()],\n [\"scopePrices\", getAddressDecoder()],\n [\"scopeOraclePriceId\", getU64Decoder()],\n [\"scopeOracleMaxAge\", getU64Decoder()],\n [\"pendingFarmAdmin\", getAddressDecoder()],\n [\"strategyId\", getAddressDecoder()],\n [\"delegatedRpsAdmin\", getAddressDecoder()],\n [\"vaultId\", getAddressDecoder()],\n [\"secondDelegatedAuthority\", getAddressDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 74 })],\n ]);\n}\n\n/** Gets the codec for {@link FarmState} account data. */\nexport function getFarmStateCodec(): FixedSizeCodec<FarmStateArgs, FarmState> {\n return combineCodec(getFarmStateEncoder(), getFarmStateDecoder());\n}\n\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<FarmState, TAddress>;\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<FarmState, TAddress>;\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<FarmState, TAddress> | MaybeAccount<FarmState, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getFarmStateDecoder());\n}\n\nexport async function fetchFarmState<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<FarmState, TAddress>> {\n const maybeAccount = await fetchMaybeFarmState(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeFarmState<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<FarmState, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeFarmState(maybeAccount);\n}\n\nexport async function fetchAllFarmState(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<FarmState>[]> {\n const maybeAccounts = await fetchAllMaybeFarmState(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeFarmState(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<FarmState>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeFarmState(maybeAccount));\n}\n\nexport function getFarmStateSize(): number {\n return 8336;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport { getFarmStateCodec, type FarmState, type FarmStateArgs } from \"../accounts\";\n\nexport const FARMS_PROGRAM_ADDRESS =\n \"FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr\" as Address<\"FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr\">;\n\nexport enum FarmsAccount {\n FarmState,\n}\n\nexport function identifyFarmsAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): FarmsAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([198, 102, 216, 74, 63, 66, 163, 190])\n ),\n 0\n )\n ) {\n return FarmsAccount.FarmState;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"farms\",\n });\n}\n\nexport type FarmsPlugin = {\n accounts: FarmsPluginAccounts;\n identifyAccount: typeof identifyFarmsAccount;\n};\n\nexport type FarmsPluginAccounts = {\n farmState: ReturnType<typeof getFarmStateCodec> & SelfFetchFunctions<FarmStateArgs, FarmState>;\n};\n\nexport type FarmsPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function farmsProgram() {\n return <T extends FarmsPluginRequirements>(\n client: T\n ): ExtendedClient<T, { farms: FarmsPlugin }> => {\n return extendClient(client, {\n farms: <FarmsPlugin>{\n accounts: { farmState: addSelfFetchFunctions(client, getFarmStateCodec()) },\n identifyAccount: identifyFarmsAccount,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type BigFractionBytes = { value: Array<bigint>; padding: Array<bigint> };\n\nexport type BigFractionBytesArgs = {\n value: Array<number | bigint>;\n padding: Array<number | bigint>;\n};\n\nexport function getBigFractionBytesEncoder(): FixedSizeEncoder<BigFractionBytesArgs> {\n return getStructEncoder([\n [\"value\", getArrayEncoder(getU64Encoder(), { size: 4 })],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 2 })],\n ]);\n}\n\nexport function getBigFractionBytesDecoder(): FixedSizeDecoder<BigFractionBytes> {\n return getStructDecoder([\n [\"value\", getArrayDecoder(getU64Decoder(), { size: 4 })],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 2 })],\n ]);\n}\n\nexport function getBigFractionBytesCodec(): FixedSizeCodec<BigFractionBytesArgs, BigFractionBytes> {\n return combineCodec(getBigFractionBytesEncoder(), getBigFractionBytesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type BorrowOrder = {\n debtLiquidityMint: Address;\n remainingDebtAmount: bigint;\n filledDebtDestination: Address;\n minDebtTermSeconds: bigint;\n fillableUntilTimestamp: bigint;\n placedAtTimestamp: bigint;\n lastUpdatedAtTimestamp: bigint;\n requestedDebtAmount: bigint;\n maxBorrowRateBps: number;\n active: number;\n enableAutoRolloverOnFilledBorrows: number;\n padding1: ReadonlyUint8Array;\n endPadding: Array<bigint>;\n};\n\nexport type BorrowOrderArgs = {\n debtLiquidityMint: Address;\n remainingDebtAmount: number | bigint;\n filledDebtDestination: Address;\n minDebtTermSeconds: number | bigint;\n fillableUntilTimestamp: number | bigint;\n placedAtTimestamp: number | bigint;\n lastUpdatedAtTimestamp: number | bigint;\n requestedDebtAmount: number | bigint;\n maxBorrowRateBps: number;\n active: number;\n enableAutoRolloverOnFilledBorrows: number;\n padding1: ReadonlyUint8Array;\n endPadding: Array<number | bigint>;\n};\n\nexport function getBorrowOrderEncoder(): FixedSizeEncoder<BorrowOrderArgs> {\n return getStructEncoder([\n [\"debtLiquidityMint\", getAddressEncoder()],\n [\"remainingDebtAmount\", getU64Encoder()],\n [\"filledDebtDestination\", getAddressEncoder()],\n [\"minDebtTermSeconds\", getU64Encoder()],\n [\"fillableUntilTimestamp\", getU64Encoder()],\n [\"placedAtTimestamp\", getU64Encoder()],\n [\"lastUpdatedAtTimestamp\", getU64Encoder()],\n [\"requestedDebtAmount\", getU64Encoder()],\n [\"maxBorrowRateBps\", getU32Encoder()],\n [\"active\", getU8Encoder()],\n [\"enableAutoRolloverOnFilledBorrows\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"endPadding\", getArrayEncoder(getU64Encoder(), { size: 5 })],\n ]);\n}\n\nexport function getBorrowOrderDecoder(): FixedSizeDecoder<BorrowOrder> {\n return getStructDecoder([\n [\"debtLiquidityMint\", getAddressDecoder()],\n [\"remainingDebtAmount\", getU64Decoder()],\n [\"filledDebtDestination\", getAddressDecoder()],\n [\"minDebtTermSeconds\", getU64Decoder()],\n [\"fillableUntilTimestamp\", getU64Decoder()],\n [\"placedAtTimestamp\", getU64Decoder()],\n [\"lastUpdatedAtTimestamp\", getU64Decoder()],\n [\"requestedDebtAmount\", getU64Decoder()],\n [\"maxBorrowRateBps\", getU32Decoder()],\n [\"active\", getU8Decoder()],\n [\"enableAutoRolloverOnFilledBorrows\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"endPadding\", getArrayDecoder(getU64Decoder(), { size: 5 })],\n ]);\n}\n\nexport function getBorrowOrderCodec(): FixedSizeCodec<BorrowOrderArgs, BorrowOrder> {\n return combineCodec(getBorrowOrderEncoder(), getBorrowOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getCurvePointDecoder,\n getCurvePointEncoder,\n type CurvePoint,\n type CurvePointArgs,\n} from \".\";\n\nexport type BorrowRateCurve = { points: Array<CurvePoint> };\n\nexport type BorrowRateCurveArgs = { points: Array<CurvePointArgs> };\n\nexport function getBorrowRateCurveEncoder(): FixedSizeEncoder<BorrowRateCurveArgs> {\n return getStructEncoder([[\"points\", getArrayEncoder(getCurvePointEncoder(), { size: 11 })]]);\n}\n\nexport function getBorrowRateCurveDecoder(): FixedSizeDecoder<BorrowRateCurve> {\n return getStructDecoder([[\"points\", getArrayDecoder(getCurvePointDecoder(), { size: 11 })]]);\n}\n\nexport function getBorrowRateCurveCodec(): FixedSizeCodec<BorrowRateCurveArgs, BorrowRateCurve> {\n return combineCodec(getBorrowRateCurveEncoder(), getBorrowRateCurveDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type CurvePoint = { utilizationRateBps: number; borrowRateBps: number };\n\nexport type CurvePointArgs = CurvePoint;\n\nexport function getCurvePointEncoder(): FixedSizeEncoder<CurvePointArgs> {\n return getStructEncoder([\n [\"utilizationRateBps\", getU32Encoder()],\n [\"borrowRateBps\", getU32Encoder()],\n ]);\n}\n\nexport function getCurvePointDecoder(): FixedSizeDecoder<CurvePoint> {\n return getStructDecoder([\n [\"utilizationRateBps\", getU32Decoder()],\n [\"borrowRateBps\", getU32Decoder()],\n ]);\n}\n\nexport function getCurvePointCodec(): FixedSizeCodec<CurvePointArgs, CurvePoint> {\n return combineCodec(getCurvePointEncoder(), getCurvePointDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type FixedTermBorrowRolloverConfig = {\n autoRolloverEnabled: number;\n openTermAllowed: number;\n migrationToFixedEnabled: number;\n fixedTermRolloverWindowDurationDays: number;\n maxBorrowRateBps: number;\n minDebtTermSeconds: bigint;\n};\n\nexport type FixedTermBorrowRolloverConfigArgs = {\n autoRolloverEnabled: number;\n openTermAllowed: number;\n migrationToFixedEnabled: number;\n fixedTermRolloverWindowDurationDays: number;\n maxBorrowRateBps: number;\n minDebtTermSeconds: number | bigint;\n};\n\nexport function getFixedTermBorrowRolloverConfigEncoder(): FixedSizeEncoder<FixedTermBorrowRolloverConfigArgs> {\n return getStructEncoder([\n [\"autoRolloverEnabled\", getU8Encoder()],\n [\"openTermAllowed\", getU8Encoder()],\n [\"migrationToFixedEnabled\", getU8Encoder()],\n [\"fixedTermRolloverWindowDurationDays\", getU8Encoder()],\n [\"maxBorrowRateBps\", getU32Encoder()],\n [\"minDebtTermSeconds\", getU64Encoder()],\n ]);\n}\n\nexport function getFixedTermBorrowRolloverConfigDecoder(): FixedSizeDecoder<FixedTermBorrowRolloverConfig> {\n return getStructDecoder([\n [\"autoRolloverEnabled\", getU8Decoder()],\n [\"openTermAllowed\", getU8Decoder()],\n [\"migrationToFixedEnabled\", getU8Decoder()],\n [\"fixedTermRolloverWindowDurationDays\", getU8Decoder()],\n [\"maxBorrowRateBps\", getU32Decoder()],\n [\"minDebtTermSeconds\", getU64Decoder()],\n ]);\n}\n\nexport function getFixedTermBorrowRolloverConfigCodec(): FixedSizeCodec<\n FixedTermBorrowRolloverConfigArgs,\n FixedTermBorrowRolloverConfig\n> {\n return combineCodec(\n getFixedTermBorrowRolloverConfigEncoder(),\n getFixedTermBorrowRolloverConfigDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type LastUpdate = {\n slot: bigint;\n stale: number;\n priceStatus: number;\n alignmentPadding: ReadonlyUint8Array;\n timestamp: number;\n};\n\nexport type LastUpdateArgs = {\n slot: number | bigint;\n stale: number;\n priceStatus: number;\n alignmentPadding: ReadonlyUint8Array;\n timestamp: number;\n};\n\nexport function getLastUpdateEncoder(): FixedSizeEncoder<LastUpdateArgs> {\n return getStructEncoder([\n [\"slot\", getU64Encoder()],\n [\"stale\", getU8Encoder()],\n [\"priceStatus\", getU8Encoder()],\n [\"alignmentPadding\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"timestamp\", getU32Encoder()],\n ]);\n}\n\nexport function getLastUpdateDecoder(): FixedSizeDecoder<LastUpdate> {\n return getStructDecoder([\n [\"slot\", getU64Decoder()],\n [\"stale\", getU8Decoder()],\n [\"priceStatus\", getU8Decoder()],\n [\"alignmentPadding\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"timestamp\", getU32Decoder()],\n ]);\n}\n\nexport function getLastUpdateCodec(): FixedSizeCodec<LastUpdateArgs, LastUpdate> {\n return combineCodec(getLastUpdateEncoder(), getLastUpdateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ObligationCollateral = {\n depositReserve: Address;\n depositedAmount: bigint;\n marketValueSf: bigint;\n borrowedAmountAgainstThisCollateralInElevationGroup: bigint;\n padding: Array<bigint>;\n};\n\nexport type ObligationCollateralArgs = {\n depositReserve: Address;\n depositedAmount: number | bigint;\n marketValueSf: number | bigint;\n borrowedAmountAgainstThisCollateralInElevationGroup: number | bigint;\n padding: Array<number | bigint>;\n};\n\nexport function getObligationCollateralEncoder(): FixedSizeEncoder<ObligationCollateralArgs> {\n return getStructEncoder([\n [\"depositReserve\", getAddressEncoder()],\n [\"depositedAmount\", getU64Encoder()],\n [\"marketValueSf\", getU128Encoder()],\n [\"borrowedAmountAgainstThisCollateralInElevationGroup\", getU64Encoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 9 })],\n ]);\n}\n\nexport function getObligationCollateralDecoder(): FixedSizeDecoder<ObligationCollateral> {\n return getStructDecoder([\n [\"depositReserve\", getAddressDecoder()],\n [\"depositedAmount\", getU64Decoder()],\n [\"marketValueSf\", getU128Decoder()],\n [\"borrowedAmountAgainstThisCollateralInElevationGroup\", getU64Decoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 9 })],\n ]);\n}\n\nexport function getObligationCollateralCodec(): FixedSizeCodec<\n ObligationCollateralArgs,\n ObligationCollateral\n> {\n return combineCodec(getObligationCollateralEncoder(), getObligationCollateralDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getBigFractionBytesDecoder,\n getBigFractionBytesEncoder,\n getFixedTermBorrowRolloverConfigDecoder,\n getFixedTermBorrowRolloverConfigEncoder,\n type BigFractionBytes,\n type BigFractionBytesArgs,\n type FixedTermBorrowRolloverConfig,\n type FixedTermBorrowRolloverConfigArgs,\n} from \".\";\n\nexport type ObligationLiquidity = {\n borrowReserve: Address;\n cumulativeBorrowRateBsf: BigFractionBytes;\n lastBorrowedAtTimestamp: bigint;\n borrowedAmountSf: bigint;\n marketValueSf: bigint;\n borrowFactorAdjustedMarketValueSf: bigint;\n borrowedAmountOutsideElevationGroups: bigint;\n fixedTermBorrowRolloverConfig: FixedTermBorrowRolloverConfig;\n borrowedAmountAtExpiration: bigint;\n padding2: Array<bigint>;\n};\n\nexport type ObligationLiquidityArgs = {\n borrowReserve: Address;\n cumulativeBorrowRateBsf: BigFractionBytesArgs;\n lastBorrowedAtTimestamp: number | bigint;\n borrowedAmountSf: number | bigint;\n marketValueSf: number | bigint;\n borrowFactorAdjustedMarketValueSf: number | bigint;\n borrowedAmountOutsideElevationGroups: number | bigint;\n fixedTermBorrowRolloverConfig: FixedTermBorrowRolloverConfigArgs;\n borrowedAmountAtExpiration: number | bigint;\n padding2: Array<number | bigint>;\n};\n\nexport function getObligationLiquidityEncoder(): FixedSizeEncoder<ObligationLiquidityArgs> {\n return getStructEncoder([\n [\"borrowReserve\", getAddressEncoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesEncoder()],\n [\"lastBorrowedAtTimestamp\", getU64Encoder()],\n [\"borrowedAmountSf\", getU128Encoder()],\n [\"marketValueSf\", getU128Encoder()],\n [\"borrowFactorAdjustedMarketValueSf\", getU128Encoder()],\n [\"borrowedAmountOutsideElevationGroups\", getU64Encoder()],\n [\"fixedTermBorrowRolloverConfig\", getFixedTermBorrowRolloverConfigEncoder()],\n [\"borrowedAmountAtExpiration\", getU64Encoder()],\n [\"padding2\", getArrayEncoder(getU64Encoder(), { size: 4 })],\n ]);\n}\n\nexport function getObligationLiquidityDecoder(): FixedSizeDecoder<ObligationLiquidity> {\n return getStructDecoder([\n [\"borrowReserve\", getAddressDecoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesDecoder()],\n [\"lastBorrowedAtTimestamp\", getU64Decoder()],\n [\"borrowedAmountSf\", getU128Decoder()],\n [\"marketValueSf\", getU128Decoder()],\n [\"borrowFactorAdjustedMarketValueSf\", getU128Decoder()],\n [\"borrowedAmountOutsideElevationGroups\", getU64Decoder()],\n [\"fixedTermBorrowRolloverConfig\", getFixedTermBorrowRolloverConfigDecoder()],\n [\"borrowedAmountAtExpiration\", getU64Decoder()],\n [\"padding2\", getArrayDecoder(getU64Decoder(), { size: 4 })],\n ]);\n}\n\nexport function getObligationLiquidityCodec(): FixedSizeCodec<\n ObligationLiquidityArgs,\n ObligationLiquidity\n> {\n return combineCodec(getObligationLiquidityEncoder(), getObligationLiquidityDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type ObligationOrder = {\n conditionThresholdSf: bigint;\n opportunityParameterSf: bigint;\n minExecutionBonusBps: number;\n maxExecutionBonusBps: number;\n conditionType: number;\n opportunityType: number;\n padding1: ReadonlyUint8Array;\n padding2: Array<bigint>;\n};\n\nexport type ObligationOrderArgs = {\n conditionThresholdSf: number | bigint;\n opportunityParameterSf: number | bigint;\n minExecutionBonusBps: number;\n maxExecutionBonusBps: number;\n conditionType: number;\n opportunityType: number;\n padding1: ReadonlyUint8Array;\n padding2: Array<number | bigint>;\n};\n\nexport function getObligationOrderEncoder(): FixedSizeEncoder<ObligationOrderArgs> {\n return getStructEncoder([\n [\"conditionThresholdSf\", getU128Encoder()],\n [\"opportunityParameterSf\", getU128Encoder()],\n [\"minExecutionBonusBps\", getU16Encoder()],\n [\"maxExecutionBonusBps\", getU16Encoder()],\n [\"conditionType\", getU8Encoder()],\n [\"opportunityType\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 10)],\n [\"padding2\", getArrayEncoder(getU128Encoder(), { size: 5 })],\n ]);\n}\n\nexport function getObligationOrderDecoder(): FixedSizeDecoder<ObligationOrder> {\n return getStructDecoder([\n [\"conditionThresholdSf\", getU128Decoder()],\n [\"opportunityParameterSf\", getU128Decoder()],\n [\"minExecutionBonusBps\", getU16Decoder()],\n [\"maxExecutionBonusBps\", getU16Decoder()],\n [\"conditionType\", getU8Decoder()],\n [\"opportunityType\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 10)],\n [\"padding2\", getArrayDecoder(getU128Decoder(), { size: 5 })],\n ]);\n}\n\nexport function getObligationOrderCodec(): FixedSizeCodec<ObligationOrderArgs, ObligationOrder> {\n return combineCodec(getObligationOrderEncoder(), getObligationOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type PriceHeuristic = { lower: bigint; upper: bigint; exp: bigint };\n\nexport type PriceHeuristicArgs = {\n lower: number | bigint;\n upper: number | bigint;\n exp: number | bigint;\n};\n\nexport function getPriceHeuristicEncoder(): FixedSizeEncoder<PriceHeuristicArgs> {\n return getStructEncoder([\n [\"lower\", getU64Encoder()],\n [\"upper\", getU64Encoder()],\n [\"exp\", getU64Encoder()],\n ]);\n}\n\nexport function getPriceHeuristicDecoder(): FixedSizeDecoder<PriceHeuristic> {\n return getStructDecoder([\n [\"lower\", getU64Decoder()],\n [\"upper\", getU64Decoder()],\n [\"exp\", getU64Decoder()],\n ]);\n}\n\nexport function getPriceHeuristicCodec(): FixedSizeCodec<PriceHeuristicArgs, PriceHeuristic> {\n return combineCodec(getPriceHeuristicEncoder(), getPriceHeuristicDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type PythConfiguration = { price: Address };\n\nexport type PythConfigurationArgs = PythConfiguration;\n\nexport function getPythConfigurationEncoder(): FixedSizeEncoder<PythConfigurationArgs> {\n return getStructEncoder([[\"price\", getAddressEncoder()]]);\n}\n\nexport function getPythConfigurationDecoder(): FixedSizeDecoder<PythConfiguration> {\n return getStructDecoder([[\"price\", getAddressDecoder()]]);\n}\n\nexport function getPythConfigurationCodec(): FixedSizeCodec<\n PythConfigurationArgs,\n PythConfiguration\n> {\n return combineCodec(getPythConfigurationEncoder(), getPythConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ReserveCollateral = {\n mintPubkey: Address;\n mintTotalSupply: bigint;\n supplyVault: Address;\n padding1: Array<bigint>;\n padding2: Array<bigint>;\n};\n\nexport type ReserveCollateralArgs = {\n mintPubkey: Address;\n mintTotalSupply: number | bigint;\n supplyVault: Address;\n padding1: Array<number | bigint>;\n padding2: Array<number | bigint>;\n};\n\nexport function getReserveCollateralEncoder(): FixedSizeEncoder<ReserveCollateralArgs> {\n return getStructEncoder([\n [\"mintPubkey\", getAddressEncoder()],\n [\"mintTotalSupply\", getU64Encoder()],\n [\"supplyVault\", getAddressEncoder()],\n [\"padding1\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n [\"padding2\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveCollateralDecoder(): FixedSizeDecoder<ReserveCollateral> {\n return getStructDecoder([\n [\"mintPubkey\", getAddressDecoder()],\n [\"mintTotalSupply\", getU64Decoder()],\n [\"supplyVault\", getAddressDecoder()],\n [\"padding1\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n [\"padding2\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveCollateralCodec(): FixedSizeCodec<\n ReserveCollateralArgs,\n ReserveCollateral\n> {\n return combineCodec(getReserveCollateralEncoder(), getReserveCollateralDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getBorrowRateCurveDecoder,\n getBorrowRateCurveEncoder,\n getReserveFeesDecoder,\n getReserveFeesEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n getWithdrawalCapsDecoder,\n getWithdrawalCapsEncoder,\n type BorrowRateCurve,\n type BorrowRateCurveArgs,\n type ReserveFees,\n type ReserveFeesArgs,\n type TokenInfo,\n type TokenInfoArgs,\n type WithdrawalCaps,\n type WithdrawalCapsArgs,\n} from \".\";\n\nexport type ReserveConfig = {\n status: number;\n paddingDeprecatedAssetTier: number;\n hostFixedInterestRateBps: number;\n minDeleveragingBonusBps: number;\n blockCtokenUsage: number;\n earlyRepayRemainingInterestPct: number;\n emergencyMode: number;\n interestRateBasis: number;\n reserved1: ReadonlyUint8Array;\n protocolOrderExecutionFeePct: number;\n protocolTakeRatePct: number;\n protocolLiquidationFeePct: number;\n loanToValuePct: number;\n liquidationThresholdPct: number;\n minLiquidationBonusBps: number;\n maxLiquidationBonusBps: number;\n badDebtLiquidationBonusBps: number;\n deleveragingMarginCallPeriodSecs: bigint;\n deleveragingThresholdDecreaseBpsPerDay: bigint;\n fees: ReserveFees;\n borrowRateCurve: BorrowRateCurve;\n borrowFactorPct: bigint;\n depositLimit: bigint;\n borrowLimit: bigint;\n tokenInfo: TokenInfo;\n depositWithdrawalCap: WithdrawalCaps;\n debtWithdrawalCap: WithdrawalCaps;\n elevationGroups: ReadonlyUint8Array;\n disableUsageAsCollOutsideEmode: number;\n utilizationLimitBlockBorrowingAbovePct: number;\n autodeleverageEnabled: number;\n proposerAuthorityLocked: number;\n borrowLimitOutsideElevationGroup: bigint;\n borrowLimitAgainstThisCollateralInElevationGroup: Array<bigint>;\n deleveragingBonusIncreaseBpsPerDay: bigint;\n debtMaturityTimestamp: bigint;\n debtTermSeconds: bigint;\n rewardsAmountPerAccrualUnit: bigint;\n permissionedOps: bigint;\n};\n\nexport type ReserveConfigArgs = {\n status: number;\n paddingDeprecatedAssetTier: number;\n hostFixedInterestRateBps: number;\n minDeleveragingBonusBps: number;\n blockCtokenUsage: number;\n earlyRepayRemainingInterestPct: number;\n emergencyMode: number;\n interestRateBasis: number;\n reserved1: ReadonlyUint8Array;\n protocolOrderExecutionFeePct: number;\n protocolTakeRatePct: number;\n protocolLiquidationFeePct: number;\n loanToValuePct: number;\n liquidationThresholdPct: number;\n minLiquidationBonusBps: number;\n maxLiquidationBonusBps: number;\n badDebtLiquidationBonusBps: number;\n deleveragingMarginCallPeriodSecs: number | bigint;\n deleveragingThresholdDecreaseBpsPerDay: number | bigint;\n fees: ReserveFeesArgs;\n borrowRateCurve: BorrowRateCurveArgs;\n borrowFactorPct: number | bigint;\n depositLimit: number | bigint;\n borrowLimit: number | bigint;\n tokenInfo: TokenInfoArgs;\n depositWithdrawalCap: WithdrawalCapsArgs;\n debtWithdrawalCap: WithdrawalCapsArgs;\n elevationGroups: ReadonlyUint8Array;\n disableUsageAsCollOutsideEmode: number;\n utilizationLimitBlockBorrowingAbovePct: number;\n autodeleverageEnabled: number;\n proposerAuthorityLocked: number;\n borrowLimitOutsideElevationGroup: number | bigint;\n borrowLimitAgainstThisCollateralInElevationGroup: Array<number | bigint>;\n deleveragingBonusIncreaseBpsPerDay: number | bigint;\n debtMaturityTimestamp: number | bigint;\n debtTermSeconds: number | bigint;\n rewardsAmountPerAccrualUnit: number | bigint;\n permissionedOps: number | bigint;\n};\n\nexport function getReserveConfigEncoder(): FixedSizeEncoder<ReserveConfigArgs> {\n return getStructEncoder([\n [\"status\", getU8Encoder()],\n [\"paddingDeprecatedAssetTier\", getU8Encoder()],\n [\"hostFixedInterestRateBps\", getU16Encoder()],\n [\"minDeleveragingBonusBps\", getU16Encoder()],\n [\"blockCtokenUsage\", getU8Encoder()],\n [\"earlyRepayRemainingInterestPct\", getU8Encoder()],\n [\"emergencyMode\", getU8Encoder()],\n [\"interestRateBasis\", getU8Encoder()],\n [\"reserved1\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"protocolOrderExecutionFeePct\", getU8Encoder()],\n [\"protocolTakeRatePct\", getU8Encoder()],\n [\"protocolLiquidationFeePct\", getU8Encoder()],\n [\"loanToValuePct\", getU8Encoder()],\n [\"liquidationThresholdPct\", getU8Encoder()],\n [\"minLiquidationBonusBps\", getU16Encoder()],\n [\"maxLiquidationBonusBps\", getU16Encoder()],\n [\"badDebtLiquidationBonusBps\", getU16Encoder()],\n [\"deleveragingMarginCallPeriodSecs\", getU64Encoder()],\n [\"deleveragingThresholdDecreaseBpsPerDay\", getU64Encoder()],\n [\"fees\", getReserveFeesEncoder()],\n [\"borrowRateCurve\", getBorrowRateCurveEncoder()],\n [\"borrowFactorPct\", getU64Encoder()],\n [\"depositLimit\", getU64Encoder()],\n [\"borrowLimit\", getU64Encoder()],\n [\"tokenInfo\", getTokenInfoEncoder()],\n [\"depositWithdrawalCap\", getWithdrawalCapsEncoder()],\n [\"debtWithdrawalCap\", getWithdrawalCapsEncoder()],\n [\"elevationGroups\", fixEncoderSize(getBytesEncoder(), 20)],\n [\"disableUsageAsCollOutsideEmode\", getU8Encoder()],\n [\"utilizationLimitBlockBorrowingAbovePct\", getU8Encoder()],\n [\"autodeleverageEnabled\", getU8Encoder()],\n [\"proposerAuthorityLocked\", getU8Encoder()],\n [\"borrowLimitOutsideElevationGroup\", getU64Encoder()],\n [\n \"borrowLimitAgainstThisCollateralInElevationGroup\",\n getArrayEncoder(getU64Encoder(), { size: 32 }),\n ],\n [\"deleveragingBonusIncreaseBpsPerDay\", getU64Encoder()],\n [\"debtMaturityTimestamp\", getU64Encoder()],\n [\"debtTermSeconds\", getU64Encoder()],\n [\"rewardsAmountPerAccrualUnit\", getU64Encoder()],\n [\"permissionedOps\", getU64Encoder()],\n ]);\n}\n\nexport function getReserveConfigDecoder(): FixedSizeDecoder<ReserveConfig> {\n return getStructDecoder([\n [\"status\", getU8Decoder()],\n [\"paddingDeprecatedAssetTier\", getU8Decoder()],\n [\"hostFixedInterestRateBps\", getU16Decoder()],\n [\"minDeleveragingBonusBps\", getU16Decoder()],\n [\"blockCtokenUsage\", getU8Decoder()],\n [\"earlyRepayRemainingInterestPct\", getU8Decoder()],\n [\"emergencyMode\", getU8Decoder()],\n [\"interestRateBasis\", getU8Decoder()],\n [\"reserved1\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"protocolOrderExecutionFeePct\", getU8Decoder()],\n [\"protocolTakeRatePct\", getU8Decoder()],\n [\"protocolLiquidationFeePct\", getU8Decoder()],\n [\"loanToValuePct\", getU8Decoder()],\n [\"liquidationThresholdPct\", getU8Decoder()],\n [\"minLiquidationBonusBps\", getU16Decoder()],\n [\"maxLiquidationBonusBps\", getU16Decoder()],\n [\"badDebtLiquidationBonusBps\", getU16Decoder()],\n [\"deleveragingMarginCallPeriodSecs\", getU64Decoder()],\n [\"deleveragingThresholdDecreaseBpsPerDay\", getU64Decoder()],\n [\"fees\", getReserveFeesDecoder()],\n [\"borrowRateCurve\", getBorrowRateCurveDecoder()],\n [\"borrowFactorPct\", getU64Decoder()],\n [\"depositLimit\", getU64Decoder()],\n [\"borrowLimit\", getU64Decoder()],\n [\"tokenInfo\", getTokenInfoDecoder()],\n [\"depositWithdrawalCap\", getWithdrawalCapsDecoder()],\n [\"debtWithdrawalCap\", getWithdrawalCapsDecoder()],\n [\"elevationGroups\", fixDecoderSize(getBytesDecoder(), 20)],\n [\"disableUsageAsCollOutsideEmode\", getU8Decoder()],\n [\"utilizationLimitBlockBorrowingAbovePct\", getU8Decoder()],\n [\"autodeleverageEnabled\", getU8Decoder()],\n [\"proposerAuthorityLocked\", getU8Decoder()],\n [\"borrowLimitOutsideElevationGroup\", getU64Decoder()],\n [\n \"borrowLimitAgainstThisCollateralInElevationGroup\",\n getArrayDecoder(getU64Decoder(), { size: 32 }),\n ],\n [\"deleveragingBonusIncreaseBpsPerDay\", getU64Decoder()],\n [\"debtMaturityTimestamp\", getU64Decoder()],\n [\"debtTermSeconds\", getU64Decoder()],\n [\"rewardsAmountPerAccrualUnit\", getU64Decoder()],\n [\"permissionedOps\", getU64Decoder()],\n ]);\n}\n\nexport function getReserveConfigCodec(): FixedSizeCodec<ReserveConfigArgs, ReserveConfig> {\n return combineCodec(getReserveConfigEncoder(), getReserveConfigDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type ReserveFees = {\n originationFeeSf: bigint;\n flashLoanFeeSf: bigint;\n padding: ReadonlyUint8Array;\n};\n\nexport type ReserveFeesArgs = {\n originationFeeSf: number | bigint;\n flashLoanFeeSf: number | bigint;\n padding: ReadonlyUint8Array;\n};\n\nexport function getReserveFeesEncoder(): FixedSizeEncoder<ReserveFeesArgs> {\n return getStructEncoder([\n [\"originationFeeSf\", getU64Encoder()],\n [\"flashLoanFeeSf\", getU64Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 8)],\n ]);\n}\n\nexport function getReserveFeesDecoder(): FixedSizeDecoder<ReserveFees> {\n return getStructDecoder([\n [\"originationFeeSf\", getU64Decoder()],\n [\"flashLoanFeeSf\", getU64Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 8)],\n ]);\n}\n\nexport function getReserveFeesCodec(): FixedSizeCodec<ReserveFeesArgs, ReserveFees> {\n return combineCodec(getReserveFeesEncoder(), getReserveFeesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getBigFractionBytesDecoder,\n getBigFractionBytesEncoder,\n type BigFractionBytes,\n type BigFractionBytesArgs,\n} from \".\";\n\nexport type ReserveLiquidity = {\n mintPubkey: Address;\n supplyVault: Address;\n feeVault: Address;\n totalAvailableAmount: bigint;\n borrowedAmountSf: bigint;\n marketPriceSf: bigint;\n marketPriceLastUpdatedTs: bigint;\n mintDecimals: bigint;\n depositLimitCrossedTimestamp: bigint;\n borrowLimitCrossedTimestamp: bigint;\n cumulativeBorrowRateBsf: BigFractionBytes;\n accumulatedProtocolFeesSf: bigint;\n accumulatedReferrerFeesSf: bigint;\n pendingReferrerFeesSf: bigint;\n absoluteReferralRateSf: bigint;\n tokenProgram: Address;\n rewardsAmountAvailable: bigint;\n padding2: Array<bigint>;\n padding3: Array<bigint>;\n};\n\nexport type ReserveLiquidityArgs = {\n mintPubkey: Address;\n supplyVault: Address;\n feeVault: Address;\n totalAvailableAmount: number | bigint;\n borrowedAmountSf: number | bigint;\n marketPriceSf: number | bigint;\n marketPriceLastUpdatedTs: number | bigint;\n mintDecimals: number | bigint;\n depositLimitCrossedTimestamp: number | bigint;\n borrowLimitCrossedTimestamp: number | bigint;\n cumulativeBorrowRateBsf: BigFractionBytesArgs;\n accumulatedProtocolFeesSf: number | bigint;\n accumulatedReferrerFeesSf: number | bigint;\n pendingReferrerFeesSf: number | bigint;\n absoluteReferralRateSf: number | bigint;\n tokenProgram: Address;\n rewardsAmountAvailable: number | bigint;\n padding2: Array<number | bigint>;\n padding3: Array<number | bigint>;\n};\n\nexport function getReserveLiquidityEncoder(): FixedSizeEncoder<ReserveLiquidityArgs> {\n return getStructEncoder([\n [\"mintPubkey\", getAddressEncoder()],\n [\"supplyVault\", getAddressEncoder()],\n [\"feeVault\", getAddressEncoder()],\n [\"totalAvailableAmount\", getU64Encoder()],\n [\"borrowedAmountSf\", getU128Encoder()],\n [\"marketPriceSf\", getU128Encoder()],\n [\"marketPriceLastUpdatedTs\", getU64Encoder()],\n [\"mintDecimals\", getU64Encoder()],\n [\"depositLimitCrossedTimestamp\", getU64Encoder()],\n [\"borrowLimitCrossedTimestamp\", getU64Encoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesEncoder()],\n [\"accumulatedProtocolFeesSf\", getU128Encoder()],\n [\"accumulatedReferrerFeesSf\", getU128Encoder()],\n [\"pendingReferrerFeesSf\", getU128Encoder()],\n [\"absoluteReferralRateSf\", getU128Encoder()],\n [\"tokenProgram\", getAddressEncoder()],\n [\"rewardsAmountAvailable\", getU64Encoder()],\n [\"padding2\", getArrayEncoder(getU64Encoder(), { size: 50 })],\n [\"padding3\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveLiquidityDecoder(): FixedSizeDecoder<ReserveLiquidity> {\n return getStructDecoder([\n [\"mintPubkey\", getAddressDecoder()],\n [\"supplyVault\", getAddressDecoder()],\n [\"feeVault\", getAddressDecoder()],\n [\"totalAvailableAmount\", getU64Decoder()],\n [\"borrowedAmountSf\", getU128Decoder()],\n [\"marketPriceSf\", getU128Decoder()],\n [\"marketPriceLastUpdatedTs\", getU64Decoder()],\n [\"mintDecimals\", getU64Decoder()],\n [\"depositLimitCrossedTimestamp\", getU64Decoder()],\n [\"borrowLimitCrossedTimestamp\", getU64Decoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesDecoder()],\n [\"accumulatedProtocolFeesSf\", getU128Decoder()],\n [\"accumulatedReferrerFeesSf\", getU128Decoder()],\n [\"pendingReferrerFeesSf\", getU128Decoder()],\n [\"absoluteReferralRateSf\", getU128Decoder()],\n [\"tokenProgram\", getAddressDecoder()],\n [\"rewardsAmountAvailable\", getU64Decoder()],\n [\"padding2\", getArrayDecoder(getU64Decoder(), { size: 50 })],\n [\"padding3\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveLiquidityCodec(): FixedSizeCodec<ReserveLiquidityArgs, ReserveLiquidity> {\n return combineCodec(getReserveLiquidityEncoder(), getReserveLiquidityDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ScopeConfiguration = {\n priceFeed: Address;\n priceChain: Array<number>;\n twapChain: Array<number>;\n};\n\nexport type ScopeConfigurationArgs = ScopeConfiguration;\n\nexport function getScopeConfigurationEncoder(): FixedSizeEncoder<ScopeConfigurationArgs> {\n return getStructEncoder([\n [\"priceFeed\", getAddressEncoder()],\n [\"priceChain\", getArrayEncoder(getU16Encoder(), { size: 4 })],\n [\"twapChain\", getArrayEncoder(getU16Encoder(), { size: 4 })],\n ]);\n}\n\nexport function getScopeConfigurationDecoder(): FixedSizeDecoder<ScopeConfiguration> {\n return getStructDecoder([\n [\"priceFeed\", getAddressDecoder()],\n [\"priceChain\", getArrayDecoder(getU16Decoder(), { size: 4 })],\n [\"twapChain\", getArrayDecoder(getU16Decoder(), { size: 4 })],\n ]);\n}\n\nexport function getScopeConfigurationCodec(): FixedSizeCodec<\n ScopeConfigurationArgs,\n ScopeConfiguration\n> {\n return combineCodec(getScopeConfigurationEncoder(), getScopeConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type SwitchboardConfiguration = { priceAggregator: Address; twapAggregator: Address };\n\nexport type SwitchboardConfigurationArgs = SwitchboardConfiguration;\n\nexport function getSwitchboardConfigurationEncoder(): FixedSizeEncoder<SwitchboardConfigurationArgs> {\n return getStructEncoder([\n [\"priceAggregator\", getAddressEncoder()],\n [\"twapAggregator\", getAddressEncoder()],\n ]);\n}\n\nexport function getSwitchboardConfigurationDecoder(): FixedSizeDecoder<SwitchboardConfiguration> {\n return getStructDecoder([\n [\"priceAggregator\", getAddressDecoder()],\n [\"twapAggregator\", getAddressDecoder()],\n ]);\n}\n\nexport function getSwitchboardConfigurationCodec(): FixedSizeCodec<\n SwitchboardConfigurationArgs,\n SwitchboardConfiguration\n> {\n return combineCodec(getSwitchboardConfigurationEncoder(), getSwitchboardConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getPriceHeuristicDecoder,\n getPriceHeuristicEncoder,\n getPythConfigurationDecoder,\n getPythConfigurationEncoder,\n getScopeConfigurationDecoder,\n getScopeConfigurationEncoder,\n getSwitchboardConfigurationDecoder,\n getSwitchboardConfigurationEncoder,\n type PriceHeuristic,\n type PriceHeuristicArgs,\n type PythConfiguration,\n type PythConfigurationArgs,\n type ScopeConfiguration,\n type ScopeConfigurationArgs,\n type SwitchboardConfiguration,\n type SwitchboardConfigurationArgs,\n} from \".\";\n\nexport type TokenInfo = {\n name: ReadonlyUint8Array;\n heuristic: PriceHeuristic;\n maxTwapDivergenceBps: bigint;\n maxAgePriceSeconds: bigint;\n maxAgeTwapSeconds: bigint;\n scopeConfiguration: ScopeConfiguration;\n switchboardConfiguration: SwitchboardConfiguration;\n pythConfiguration: PythConfiguration;\n blockPriceUsage: number;\n reserved: ReadonlyUint8Array;\n padding: Array<bigint>;\n};\n\nexport type TokenInfoArgs = {\n name: ReadonlyUint8Array;\n heuristic: PriceHeuristicArgs;\n maxTwapDivergenceBps: number | bigint;\n maxAgePriceSeconds: number | bigint;\n maxAgeTwapSeconds: number | bigint;\n scopeConfiguration: ScopeConfigurationArgs;\n switchboardConfiguration: SwitchboardConfigurationArgs;\n pythConfiguration: PythConfigurationArgs;\n blockPriceUsage: number;\n reserved: ReadonlyUint8Array;\n padding: Array<number | bigint>;\n};\n\nexport function getTokenInfoEncoder(): FixedSizeEncoder<TokenInfoArgs> {\n return getStructEncoder([\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"heuristic\", getPriceHeuristicEncoder()],\n [\"maxTwapDivergenceBps\", getU64Encoder()],\n [\"maxAgePriceSeconds\", getU64Encoder()],\n [\"maxAgeTwapSeconds\", getU64Encoder()],\n [\"scopeConfiguration\", getScopeConfigurationEncoder()],\n [\"switchboardConfiguration\", getSwitchboardConfigurationEncoder()],\n [\"pythConfiguration\", getPythConfigurationEncoder()],\n [\"blockPriceUsage\", getU8Encoder()],\n [\"reserved\", fixEncoderSize(getBytesEncoder(), 7)],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 19 })],\n ]);\n}\n\nexport function getTokenInfoDecoder(): FixedSizeDecoder<TokenInfo> {\n return getStructDecoder([\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"heuristic\", getPriceHeuristicDecoder()],\n [\"maxTwapDivergenceBps\", getU64Decoder()],\n [\"maxAgePriceSeconds\", getU64Decoder()],\n [\"maxAgeTwapSeconds\", getU64Decoder()],\n [\"scopeConfiguration\", getScopeConfigurationDecoder()],\n [\"switchboardConfiguration\", getSwitchboardConfigurationDecoder()],\n [\"pythConfiguration\", getPythConfigurationDecoder()],\n [\"blockPriceUsage\", getU8Decoder()],\n [\"reserved\", fixDecoderSize(getBytesDecoder(), 7)],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 19 })],\n ]);\n}\n\nexport function getTokenInfoCodec(): FixedSizeCodec<TokenInfoArgs, TokenInfo> {\n return combineCodec(getTokenInfoEncoder(), getTokenInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type WithdrawalCaps = {\n configCapacity: bigint;\n currentTotal: bigint;\n lastIntervalStartTimestamp: bigint;\n configIntervalLengthSeconds: bigint;\n};\n\nexport type WithdrawalCapsArgs = {\n configCapacity: number | bigint;\n currentTotal: number | bigint;\n lastIntervalStartTimestamp: number | bigint;\n configIntervalLengthSeconds: number | bigint;\n};\n\nexport function getWithdrawalCapsEncoder(): FixedSizeEncoder<WithdrawalCapsArgs> {\n return getStructEncoder([\n [\"configCapacity\", getI64Encoder()],\n [\"currentTotal\", getI64Encoder()],\n [\"lastIntervalStartTimestamp\", getU64Encoder()],\n [\"configIntervalLengthSeconds\", getU64Encoder()],\n ]);\n}\n\nexport function getWithdrawalCapsDecoder(): FixedSizeDecoder<WithdrawalCaps> {\n return getStructDecoder([\n [\"configCapacity\", getI64Decoder()],\n [\"currentTotal\", getI64Decoder()],\n [\"lastIntervalStartTimestamp\", getU64Decoder()],\n [\"configIntervalLengthSeconds\", getU64Decoder()],\n ]);\n}\n\nexport function getWithdrawalCapsCodec(): FixedSizeCodec<WithdrawalCapsArgs, WithdrawalCaps> {\n return combineCodec(getWithdrawalCapsEncoder(), getWithdrawalCapsDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type WithdrawQueue = {\n queuedCollateralAmount: bigint;\n nextIssuedTicketSequenceNumber: bigint;\n nextWithdrawableTicketSequenceNumber: bigint;\n};\n\nexport type WithdrawQueueArgs = {\n queuedCollateralAmount: number | bigint;\n nextIssuedTicketSequenceNumber: number | bigint;\n nextWithdrawableTicketSequenceNumber: number | bigint;\n};\n\nexport function getWithdrawQueueEncoder(): FixedSizeEncoder<WithdrawQueueArgs> {\n return getStructEncoder([\n [\"queuedCollateralAmount\", getU64Encoder()],\n [\"nextIssuedTicketSequenceNumber\", getU64Encoder()],\n [\"nextWithdrawableTicketSequenceNumber\", getU64Encoder()],\n ]);\n}\n\nexport function getWithdrawQueueDecoder(): FixedSizeDecoder<WithdrawQueue> {\n return getStructDecoder([\n [\"queuedCollateralAmount\", getU64Decoder()],\n [\"nextIssuedTicketSequenceNumber\", getU64Decoder()],\n [\"nextWithdrawableTicketSequenceNumber\", getU64Decoder()],\n ]);\n}\n\nexport function getWithdrawQueueCodec(): FixedSizeCodec<WithdrawQueueArgs, WithdrawQueue> {\n return combineCodec(getWithdrawQueueEncoder(), getWithdrawQueueDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getBorrowOrderDecoder,\n getBorrowOrderEncoder,\n getLastUpdateDecoder,\n getLastUpdateEncoder,\n getObligationCollateralDecoder,\n getObligationCollateralEncoder,\n getObligationLiquidityDecoder,\n getObligationLiquidityEncoder,\n getObligationOrderDecoder,\n getObligationOrderEncoder,\n type BorrowOrder,\n type BorrowOrderArgs,\n type LastUpdate,\n type LastUpdateArgs,\n type ObligationCollateral,\n type ObligationCollateralArgs,\n type ObligationLiquidity,\n type ObligationLiquidityArgs,\n type ObligationOrder,\n type ObligationOrderArgs,\n} from \"../types\";\n\nexport const OBLIGATION_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 168, 206, 141, 106, 88, 76, 172, 167,\n]);\n\nexport function getObligationDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(OBLIGATION_DISCRIMINATOR);\n}\n\nexport type Obligation = {\n discriminator: ReadonlyUint8Array;\n tag: bigint;\n lastUpdate: LastUpdate;\n lendingMarket: Address;\n owner: Address;\n deposits: Array<ObligationCollateral>;\n lowestReserveDepositLiquidationLtv: bigint;\n depositedValueSf: bigint;\n borrows: Array<ObligationLiquidity>;\n borrowFactorAdjustedDebtValueSf: bigint;\n borrowedAssetsMarketValueSf: bigint;\n allowedBorrowValueSf: bigint;\n unhealthyBorrowValueSf: bigint;\n paddingDeprecatedAssetTiers: ReadonlyUint8Array;\n elevationGroup: number;\n numOfObsoleteDepositReserves: number;\n hasDebt: number;\n referrer: Address;\n borrowingDisabled: number;\n autodeleverageTargetLtvPct: number;\n lowestReserveDepositMaxLtvPct: number;\n numOfObsoleteBorrowReserves: number;\n ownershipTransferState: number;\n reserved: ReadonlyUint8Array;\n highestBorrowFactorPct: bigint;\n autodeleverageMarginCallStartedTimestamp: bigint;\n obligationOrders: Array<ObligationOrder>;\n headBorrowOrder: BorrowOrder;\n pendingOwner: Address;\n tailBorrowOrders: Array<BorrowOrder>;\n padding3: Array<bigint>;\n};\n\nexport type ObligationArgs = {\n tag: number | bigint;\n lastUpdate: LastUpdateArgs;\n lendingMarket: Address;\n owner: Address;\n deposits: Array<ObligationCollateralArgs>;\n lowestReserveDepositLiquidationLtv: number | bigint;\n depositedValueSf: number | bigint;\n borrows: Array<ObligationLiquidityArgs>;\n borrowFactorAdjustedDebtValueSf: number | bigint;\n borrowedAssetsMarketValueSf: number | bigint;\n allowedBorrowValueSf: number | bigint;\n unhealthyBorrowValueSf: number | bigint;\n paddingDeprecatedAssetTiers: ReadonlyUint8Array;\n elevationGroup: number;\n numOfObsoleteDepositReserves: number;\n hasDebt: number;\n referrer: Address;\n borrowingDisabled: number;\n autodeleverageTargetLtvPct: number;\n lowestReserveDepositMaxLtvPct: number;\n numOfObsoleteBorrowReserves: number;\n ownershipTransferState: number;\n reserved: ReadonlyUint8Array;\n highestBorrowFactorPct: number | bigint;\n autodeleverageMarginCallStartedTimestamp: number | bigint;\n obligationOrders: Array<ObligationOrderArgs>;\n headBorrowOrder: BorrowOrderArgs;\n pendingOwner: Address;\n tailBorrowOrders: Array<BorrowOrderArgs>;\n padding3: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link ObligationArgs} account data. */\nexport function getObligationEncoder(): FixedSizeEncoder<ObligationArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"tag\", getU64Encoder()],\n [\"lastUpdate\", getLastUpdateEncoder()],\n [\"lendingMarket\", getAddressEncoder()],\n [\"owner\", getAddressEncoder()],\n [\"deposits\", getArrayEncoder(getObligationCollateralEncoder(), { size: 8 })],\n [\"lowestReserveDepositLiquidationLtv\", getU64Encoder()],\n [\"depositedValueSf\", getU128Encoder()],\n [\"borrows\", getArrayEncoder(getObligationLiquidityEncoder(), { size: 5 })],\n [\"borrowFactorAdjustedDebtValueSf\", getU128Encoder()],\n [\"borrowedAssetsMarketValueSf\", getU128Encoder()],\n [\"allowedBorrowValueSf\", getU128Encoder()],\n [\"unhealthyBorrowValueSf\", getU128Encoder()],\n [\"paddingDeprecatedAssetTiers\", fixEncoderSize(getBytesEncoder(), 13)],\n [\"elevationGroup\", getU8Encoder()],\n [\"numOfObsoleteDepositReserves\", getU8Encoder()],\n [\"hasDebt\", getU8Encoder()],\n [\"referrer\", getAddressEncoder()],\n [\"borrowingDisabled\", getU8Encoder()],\n [\"autodeleverageTargetLtvPct\", getU8Encoder()],\n [\"lowestReserveDepositMaxLtvPct\", getU8Encoder()],\n [\"numOfObsoleteBorrowReserves\", getU8Encoder()],\n [\"ownershipTransferState\", getU8Encoder()],\n [\"reserved\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"highestBorrowFactorPct\", getU64Encoder()],\n [\"autodeleverageMarginCallStartedTimestamp\", getU64Encoder()],\n [\"obligationOrders\", getArrayEncoder(getObligationOrderEncoder(), { size: 2 })],\n [\"headBorrowOrder\", getBorrowOrderEncoder()],\n [\"pendingOwner\", getAddressEncoder()],\n [\"tailBorrowOrders\", getArrayEncoder(getBorrowOrderEncoder(), { size: 2 })],\n [\"padding3\", getArrayEncoder(getU64Encoder(), { size: 29 })],\n ]),\n (value) => ({ ...value, discriminator: OBLIGATION_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Obligation} account data. */\nexport function getObligationDecoder(): FixedSizeDecoder<Obligation> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"tag\", getU64Decoder()],\n [\"lastUpdate\", getLastUpdateDecoder()],\n [\"lendingMarket\", getAddressDecoder()],\n [\"owner\", getAddressDecoder()],\n [\"deposits\", getArrayDecoder(getObligationCollateralDecoder(), { size: 8 })],\n [\"lowestReserveDepositLiquidationLtv\", getU64Decoder()],\n [\"depositedValueSf\", getU128Decoder()],\n [\"borrows\", getArrayDecoder(getObligationLiquidityDecoder(), { size: 5 })],\n [\"borrowFactorAdjustedDebtValueSf\", getU128Decoder()],\n [\"borrowedAssetsMarketValueSf\", getU128Decoder()],\n [\"allowedBorrowValueSf\", getU128Decoder()],\n [\"unhealthyBorrowValueSf\", getU128Decoder()],\n [\"paddingDeprecatedAssetTiers\", fixDecoderSize(getBytesDecoder(), 13)],\n [\"elevationGroup\", getU8Decoder()],\n [\"numOfObsoleteDepositReserves\", getU8Decoder()],\n [\"hasDebt\", getU8Decoder()],\n [\"referrer\", getAddressDecoder()],\n [\"borrowingDisabled\", getU8Decoder()],\n [\"autodeleverageTargetLtvPct\", getU8Decoder()],\n [\"lowestReserveDepositMaxLtvPct\", getU8Decoder()],\n [\"numOfObsoleteBorrowReserves\", getU8Decoder()],\n [\"ownershipTransferState\", getU8Decoder()],\n [\"reserved\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"highestBorrowFactorPct\", getU64Decoder()],\n [\"autodeleverageMarginCallStartedTimestamp\", getU64Decoder()],\n [\"obligationOrders\", getArrayDecoder(getObligationOrderDecoder(), { size: 2 })],\n [\"headBorrowOrder\", getBorrowOrderDecoder()],\n [\"pendingOwner\", getAddressDecoder()],\n [\"tailBorrowOrders\", getArrayDecoder(getBorrowOrderDecoder(), { size: 2 })],\n [\"padding3\", getArrayDecoder(getU64Decoder(), { size: 29 })],\n ]);\n}\n\n/** Gets the codec for {@link Obligation} account data. */\nexport function getObligationCodec(): FixedSizeCodec<ObligationArgs, Obligation> {\n return combineCodec(getObligationEncoder(), getObligationDecoder());\n}\n\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Obligation, TAddress>;\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Obligation, TAddress>;\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Obligation, TAddress> | MaybeAccount<Obligation, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getObligationDecoder());\n}\n\nexport async function fetchObligation<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Obligation, TAddress>> {\n const maybeAccount = await fetchMaybeObligation(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeObligation<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Obligation, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeObligation(maybeAccount);\n}\n\nexport async function fetchAllObligation(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Obligation>[]> {\n const maybeAccounts = await fetchAllMaybeObligation(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeObligation(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Obligation>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeObligation(maybeAccount));\n}\n\nexport function getObligationSize(): number {\n return 3344;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getLastUpdateDecoder,\n getLastUpdateEncoder,\n getReserveCollateralDecoder,\n getReserveCollateralEncoder,\n getReserveConfigDecoder,\n getReserveConfigEncoder,\n getReserveLiquidityDecoder,\n getReserveLiquidityEncoder,\n getWithdrawQueueDecoder,\n getWithdrawQueueEncoder,\n type LastUpdate,\n type LastUpdateArgs,\n type ReserveCollateral,\n type ReserveCollateralArgs,\n type ReserveConfig,\n type ReserveConfigArgs,\n type ReserveLiquidity,\n type ReserveLiquidityArgs,\n type WithdrawQueue,\n type WithdrawQueueArgs,\n} from \"../types\";\n\nexport const RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 43, 242, 204, 202, 26, 247, 59, 127,\n]);\n\nexport function getReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(RESERVE_DISCRIMINATOR);\n}\n\nexport type Reserve = {\n discriminator: ReadonlyUint8Array;\n version: bigint;\n lastUpdate: LastUpdate;\n lendingMarket: Address;\n farmCollateral: Address;\n farmDebt: Address;\n liquidity: ReserveLiquidity;\n reserveLiquidityPadding: Array<bigint>;\n collateral: ReserveCollateral;\n reserveCollateralPadding: Array<bigint>;\n config: ReserveConfig;\n configPadding: Array<bigint>;\n borrowedAmountOutsideElevationGroup: bigint;\n borrowedAmountsAgainstThisReserveInElevationGroups: Array<bigint>;\n withdrawQueue: WithdrawQueue;\n padding: Array<bigint>;\n};\n\nexport type ReserveArgs = {\n version: number | bigint;\n lastUpdate: LastUpdateArgs;\n lendingMarket: Address;\n farmCollateral: Address;\n farmDebt: Address;\n liquidity: ReserveLiquidityArgs;\n reserveLiquidityPadding: Array<number | bigint>;\n collateral: ReserveCollateralArgs;\n reserveCollateralPadding: Array<number | bigint>;\n config: ReserveConfigArgs;\n configPadding: Array<number | bigint>;\n borrowedAmountOutsideElevationGroup: number | bigint;\n borrowedAmountsAgainstThisReserveInElevationGroups: Array<number | bigint>;\n withdrawQueue: WithdrawQueueArgs;\n padding: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link ReserveArgs} account data. */\nexport function getReserveEncoder(): FixedSizeEncoder<ReserveArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"version\", getU64Encoder()],\n [\"lastUpdate\", getLastUpdateEncoder()],\n [\"lendingMarket\", getAddressEncoder()],\n [\"farmCollateral\", getAddressEncoder()],\n [\"farmDebt\", getAddressEncoder()],\n [\"liquidity\", getReserveLiquidityEncoder()],\n [\"reserveLiquidityPadding\", getArrayEncoder(getU64Encoder(), { size: 150 })],\n [\"collateral\", getReserveCollateralEncoder()],\n [\"reserveCollateralPadding\", getArrayEncoder(getU64Encoder(), { size: 150 })],\n [\"config\", getReserveConfigEncoder()],\n [\"configPadding\", getArrayEncoder(getU64Encoder(), { size: 112 })],\n [\"borrowedAmountOutsideElevationGroup\", getU64Encoder()],\n [\n \"borrowedAmountsAgainstThisReserveInElevationGroups\",\n getArrayEncoder(getU64Encoder(), { size: 32 }),\n ],\n [\"withdrawQueue\", getWithdrawQueueEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 204 })],\n ]),\n (value) => ({ ...value, discriminator: RESERVE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Reserve} account data. */\nexport function getReserveDecoder(): FixedSizeDecoder<Reserve> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"version\", getU64Decoder()],\n [\"lastUpdate\", getLastUpdateDecoder()],\n [\"lendingMarket\", getAddressDecoder()],\n [\"farmCollateral\", getAddressDecoder()],\n [\"farmDebt\", getAddressDecoder()],\n [\"liquidity\", getReserveLiquidityDecoder()],\n [\"reserveLiquidityPadding\", getArrayDecoder(getU64Decoder(), { size: 150 })],\n [\"collateral\", getReserveCollateralDecoder()],\n [\"reserveCollateralPadding\", getArrayDecoder(getU64Decoder(), { size: 150 })],\n [\"config\", getReserveConfigDecoder()],\n [\"configPadding\", getArrayDecoder(getU64Decoder(), { size: 112 })],\n [\"borrowedAmountOutsideElevationGroup\", getU64Decoder()],\n [\n \"borrowedAmountsAgainstThisReserveInElevationGroups\",\n getArrayDecoder(getU64Decoder(), { size: 32 }),\n ],\n [\"withdrawQueue\", getWithdrawQueueDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 204 })],\n ]);\n}\n\n/** Gets the codec for {@link Reserve} account data. */\nexport function getReserveCodec(): FixedSizeCodec<ReserveArgs, Reserve> {\n return combineCodec(getReserveEncoder(), getReserveDecoder());\n}\n\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Reserve, TAddress>;\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Reserve, TAddress>;\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Reserve, TAddress> | MaybeAccount<Reserve, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getReserveDecoder());\n}\n\nexport async function fetchReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Reserve, TAddress>> {\n const maybeAccount = await fetchMaybeReserve(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Reserve, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeReserve(maybeAccount);\n}\n\nexport async function fetchAllReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Reserve>[]> {\n const maybeAccounts = await fetchAllMaybeReserve(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Reserve>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeReserve(maybeAccount));\n}\n\nexport function getReserveSize(): number {\n return 8624;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getObligationCodec,\n getReserveCodec,\n type Obligation,\n type ObligationArgs,\n type Reserve,\n type ReserveArgs,\n} from \"../accounts\";\nimport {\n getRefreshObligationInstruction,\n getRefreshReserveInstruction,\n getRefreshReservesBatchInstruction,\n parseRefreshObligationInstruction,\n parseRefreshReserveInstruction,\n parseRefreshReservesBatchInstruction,\n type ParsedRefreshObligationInstruction,\n type ParsedRefreshReserveInstruction,\n type ParsedRefreshReservesBatchInstruction,\n type RefreshObligationInput,\n type RefreshReserveInput,\n type RefreshReservesBatchInput,\n} from \"../instructions\";\n\nexport const KAMINO_LENDING_PROGRAM_ADDRESS =\n \"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\" as Address<\"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\">;\n\nexport enum KaminoLendingAccount {\n Obligation,\n Reserve,\n}\n\nexport function identifyKaminoLendingAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): KaminoLendingAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([168, 206, 141, 106, 88, 76, 172, 167])\n ),\n 0\n )\n ) {\n return KaminoLendingAccount.Obligation;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([43, 242, 204, 202, 26, 247, 59, 127])\n ),\n 0\n )\n ) {\n return KaminoLendingAccount.Reserve;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"kaminoLending\",\n });\n}\n\nexport enum KaminoLendingInstruction {\n RefreshReserve,\n RefreshReservesBatch,\n RefreshObligation,\n}\n\nexport function identifyKaminoLendingInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): KaminoLendingInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([2, 218, 138, 235, 79, 201, 25, 102])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshReserve;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([144, 110, 26, 103, 162, 204, 252, 147])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshReservesBatch;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([33, 132, 147, 228, 151, 192, 72, 89])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshObligation;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"kaminoLending\",\n });\n}\n\nexport type ParsedKaminoLendingInstruction<\n TProgram extends string = \"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\",\n> =\n | ({\n instructionType: KaminoLendingInstruction.RefreshReserve;\n } & ParsedRefreshReserveInstruction<TProgram>)\n | ({\n instructionType: KaminoLendingInstruction.RefreshReservesBatch;\n } & ParsedRefreshReservesBatchInstruction<TProgram>)\n | ({\n instructionType: KaminoLendingInstruction.RefreshObligation;\n } & ParsedRefreshObligationInstruction<TProgram>);\n\nexport function parseKaminoLendingInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedKaminoLendingInstruction<TProgram> {\n const instructionType = identifyKaminoLendingInstruction(instruction);\n switch (instructionType) {\n case KaminoLendingInstruction.RefreshReserve: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: KaminoLendingInstruction.RefreshReserve,\n ...parseRefreshReserveInstruction(instruction),\n };\n }\n case KaminoLendingInstruction.RefreshReservesBatch: {\n return {\n instructionType: KaminoLendingInstruction.RefreshReservesBatch,\n ...parseRefreshReservesBatchInstruction(instruction),\n };\n }\n case KaminoLendingInstruction.RefreshObligation: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: KaminoLendingInstruction.RefreshObligation,\n ...parseRefreshObligationInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"kaminoLending\",\n });\n }\n}\n\nexport type KaminoLendingPlugin = {\n accounts: KaminoLendingPluginAccounts;\n instructions: KaminoLendingPluginInstructions;\n identifyAccount: typeof identifyKaminoLendingAccount;\n identifyInstruction: typeof identifyKaminoLendingInstruction;\n parseInstruction: typeof parseKaminoLendingInstruction;\n};\n\nexport type KaminoLendingPluginAccounts = {\n obligation: ReturnType<typeof getObligationCodec> &\n SelfFetchFunctions<ObligationArgs, Obligation>;\n reserve: ReturnType<typeof getReserveCodec> & SelfFetchFunctions<ReserveArgs, Reserve>;\n};\n\nexport type KaminoLendingPluginInstructions = {\n refreshReserve: (\n input: RefreshReserveInput\n ) => ReturnType<typeof getRefreshReserveInstruction> & SelfPlanAndSendFunctions;\n refreshReservesBatch: (\n input: RefreshReservesBatchInput\n ) => ReturnType<typeof getRefreshReservesBatchInstruction> & SelfPlanAndSendFunctions;\n refreshObligation: (\n input: RefreshObligationInput\n ) => ReturnType<typeof getRefreshObligationInstruction> & SelfPlanAndSendFunctions;\n};\n\nexport type KaminoLendingPluginRequirements = ClientWithRpc<\n GetAccountInfoApi & GetMultipleAccountsApi\n> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function kaminoLendingProgram() {\n return <T extends KaminoLendingPluginRequirements>(\n client: T\n ): ExtendedClient<T, { kaminoLending: KaminoLendingPlugin }> => {\n return extendClient(client, {\n kaminoLending: <KaminoLendingPlugin>{\n accounts: {\n obligation: addSelfFetchFunctions(client, getObligationCodec()),\n reserve: addSelfFetchFunctions(client, getReserveCodec()),\n },\n instructions: {\n refreshReserve: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshReserveInstruction(input)),\n refreshReservesBatch: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshReservesBatchInstruction(input)),\n refreshObligation: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshObligationInstruction(input)),\n },\n identifyAccount: identifyKaminoLendingAccount,\n identifyInstruction: identifyKaminoLendingInstruction,\n parseInstruction: parseKaminoLendingInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_OBLIGATION_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 33, 132, 147, 228, 151, 192, 72, 89,\n]);\n\nexport function getRefreshObligationDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_OBLIGATION_DISCRIMINATOR);\n}\n\nexport type RefreshObligationInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountLendingMarket extends string | AccountMeta<string> = string,\n TAccountObligation extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountLendingMarket extends string\n ? ReadonlyAccount<TAccountLendingMarket>\n : TAccountLendingMarket,\n TAccountObligation extends string ? WritableAccount<TAccountObligation> : TAccountObligation,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RefreshObligationInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type RefreshObligationInstructionDataArgs = {};\n\nexport function getRefreshObligationInstructionDataEncoder(): FixedSizeEncoder<RefreshObligationInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: REFRESH_OBLIGATION_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshObligationInstructionDataDecoder(): FixedSizeDecoder<RefreshObligationInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getRefreshObligationInstructionDataCodec(): FixedSizeCodec<\n RefreshObligationInstructionDataArgs,\n RefreshObligationInstructionData\n> {\n return combineCodec(\n getRefreshObligationInstructionDataEncoder(),\n getRefreshObligationInstructionDataDecoder()\n );\n}\n\nexport type RefreshObligationInput<\n TAccountLendingMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountObligation extends InstructionAccountInput = InstructionAccountInput,\n> = {\n lendingMarket: TAccountLendingMarket;\n obligation: TAccountObligation;\n};\n\nexport function getRefreshObligationInstruction<\n TAccountLendingMarket extends InstructionAccountInput,\n TAccountObligation extends InstructionAccountInput,\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshObligationInput<TAccountLendingMarket, TAccountObligation>,\n config?: { programAddress?: TProgramAddress }\n): RefreshObligationInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountObligation,\n InstructionAccountInputAddress<TAccountObligation>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n lendingMarket: { value: input.lendingMarket ?? null, isSigner: false, isWritable: false },\n obligation: { value: input.obligation ?? null, isSigner: false, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"lendingMarket\", accounts.lendingMarket),\n getAccountMeta(\"obligation\", accounts.obligation),\n ],\n data: getRefreshObligationInstructionDataEncoder().encode({}),\n programAddress,\n } as RefreshObligationInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountObligation,\n InstructionAccountInputAddress<TAccountObligation>\n >\n >);\n}\n\nexport type ParsedRefreshObligationInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n lendingMarket: TAccountMetas[0];\n obligation: TAccountMetas[1];\n };\n data: RefreshObligationInstructionData;\n};\n\nexport function parseRefreshObligationInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshObligationInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 2) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 2,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { lendingMarket: getNextAccount(), obligation: getNextAccount() },\n data: getRefreshObligationInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 2, 218, 138, 235, 79, 201, 25, 102,\n]);\n\nexport function getRefreshReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_RESERVE_DISCRIMINATOR);\n}\n\nexport type RefreshReserveInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountReserve extends string | AccountMeta<string> = string,\n TAccountLendingMarket extends string | AccountMeta<string> = string,\n TAccountPythOracle extends string | AccountMeta<string> = string,\n TAccountSwitchboardPriceOracle extends string | AccountMeta<string> = string,\n TAccountSwitchboardTwapOracle extends string | AccountMeta<string> = string,\n TAccountScopePrices extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountReserve extends string ? WritableAccount<TAccountReserve> : TAccountReserve,\n TAccountLendingMarket extends string\n ? ReadonlyAccount<TAccountLendingMarket>\n : TAccountLendingMarket,\n TAccountPythOracle extends string ? ReadonlyAccount<TAccountPythOracle> : TAccountPythOracle,\n TAccountSwitchboardPriceOracle extends string\n ? ReadonlyAccount<TAccountSwitchboardPriceOracle>\n : TAccountSwitchboardPriceOracle,\n TAccountSwitchboardTwapOracle extends string\n ? ReadonlyAccount<TAccountSwitchboardTwapOracle>\n : TAccountSwitchboardTwapOracle,\n TAccountScopePrices extends string\n ? ReadonlyAccount<TAccountScopePrices>\n : TAccountScopePrices,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RefreshReserveInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type RefreshReserveInstructionDataArgs = {};\n\nexport function getRefreshReserveInstructionDataEncoder(): FixedSizeEncoder<RefreshReserveInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: REFRESH_RESERVE_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshReserveInstructionDataDecoder(): FixedSizeDecoder<RefreshReserveInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getRefreshReserveInstructionDataCodec(): FixedSizeCodec<\n RefreshReserveInstructionDataArgs,\n RefreshReserveInstructionData\n> {\n return combineCodec(\n getRefreshReserveInstructionDataEncoder(),\n getRefreshReserveInstructionDataDecoder()\n );\n}\n\nexport type RefreshReserveInput<\n TAccountReserve extends InstructionAccountInput = InstructionAccountInput,\n TAccountLendingMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountPythOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSwitchboardPriceOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSwitchboardTwapOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountScopePrices extends InstructionAccountInput = InstructionAccountInput,\n> = {\n reserve: TAccountReserve;\n lendingMarket: TAccountLendingMarket;\n pythOracle?: TAccountPythOracle;\n switchboardPriceOracle?: TAccountSwitchboardPriceOracle;\n switchboardTwapOracle?: TAccountSwitchboardTwapOracle;\n scopePrices?: TAccountScopePrices;\n};\n\nexport function getRefreshReserveInstruction<\n TAccountReserve extends InstructionAccountInput,\n TAccountLendingMarket extends InstructionAccountInput,\n TAccountPythOracle extends InstructionAccountInput,\n TAccountSwitchboardPriceOracle extends InstructionAccountInput,\n TAccountSwitchboardTwapOracle extends InstructionAccountInput,\n TAccountScopePrices extends InstructionAccountInput,\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshReserveInput<\n TAccountReserve,\n TAccountLendingMarket,\n TAccountPythOracle,\n TAccountSwitchboardPriceOracle,\n TAccountSwitchboardTwapOracle,\n TAccountScopePrices\n >,\n config?: { programAddress?: TProgramAddress }\n): RefreshReserveInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountReserve, InstructionAccountInputAddress<TAccountReserve>>,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountPythOracle,\n InstructionAccountInputAddress<TAccountPythOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardPriceOracle,\n InstructionAccountInputAddress<TAccountSwitchboardPriceOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardTwapOracle,\n InstructionAccountInputAddress<TAccountSwitchboardTwapOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountScopePrices,\n InstructionAccountInputAddress<TAccountScopePrices>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n reserve: { value: input.reserve ?? null, isSigner: false, isWritable: true },\n lendingMarket: { value: input.lendingMarket ?? null, isSigner: false, isWritable: false },\n pythOracle: { value: input.pythOracle ?? null, isSigner: false, isWritable: false },\n switchboardPriceOracle: {\n value: input.switchboardPriceOracle ?? null,\n isSigner: false,\n isWritable: false,\n },\n switchboardTwapOracle: {\n value: input.switchboardTwapOracle ?? null,\n isSigner: false,\n isWritable: false,\n },\n scopePrices: { value: input.scopePrices ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"reserve\", accounts.reserve),\n getAccountMeta(\"lendingMarket\", accounts.lendingMarket),\n getAccountMeta(\"pythOracle\", accounts.pythOracle),\n getAccountMeta(\"switchboardPriceOracle\", accounts.switchboardPriceOracle),\n getAccountMeta(\"switchboardTwapOracle\", accounts.switchboardTwapOracle),\n getAccountMeta(\"scopePrices\", accounts.scopePrices),\n ],\n data: getRefreshReserveInstructionDataEncoder().encode({}),\n programAddress,\n } as RefreshReserveInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountReserve,\n InstructionAccountInputAddress<TAccountReserve>\n >,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountPythOracle,\n InstructionAccountInputAddress<TAccountPythOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardPriceOracle,\n InstructionAccountInputAddress<TAccountSwitchboardPriceOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardTwapOracle,\n InstructionAccountInputAddress<TAccountSwitchboardTwapOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountScopePrices,\n InstructionAccountInputAddress<TAccountScopePrices>\n >\n >);\n}\n\nexport type ParsedRefreshReserveInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n reserve: TAccountMetas[0];\n lendingMarket: TAccountMetas[1];\n pythOracle?: TAccountMetas[2] | undefined;\n switchboardPriceOracle?: TAccountMetas[3] | undefined;\n switchboardTwapOracle?: TAccountMetas[4] | undefined;\n scopePrices?: TAccountMetas[5] | undefined;\n };\n data: RefreshReserveInstructionData;\n};\n\nexport function parseRefreshReserveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshReserveInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 6) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 6,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === KAMINO_LENDING_PROGRAM_ADDRESS ? undefined : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n reserve: getNextAccount(),\n lendingMarket: getNextAccount(),\n pythOracle: getNextOptionalAccount(),\n switchboardPriceOracle: getNextOptionalAccount(),\n switchboardTwapOracle: getNextOptionalAccount(),\n scopePrices: getNextOptionalAccount(),\n },\n data: getRefreshReserveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_RESERVES_BATCH_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 144, 110, 26, 103, 162, 204, 252, 147,\n]);\n\nexport function getRefreshReservesBatchDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_RESERVES_BATCH_DISCRIMINATOR);\n}\n\nexport type RefreshReservesBatchInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<TRemainingAccounts>;\n\nexport type RefreshReservesBatchInstructionData = {\n discriminator: ReadonlyUint8Array;\n skipPriceUpdates: boolean;\n};\n\nexport type RefreshReservesBatchInstructionDataArgs = { skipPriceUpdates: boolean };\n\nexport function getRefreshReservesBatchInstructionDataEncoder(): FixedSizeEncoder<RefreshReservesBatchInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"skipPriceUpdates\", getBooleanEncoder()],\n ]),\n (value) => ({ ...value, discriminator: REFRESH_RESERVES_BATCH_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshReservesBatchInstructionDataDecoder(): FixedSizeDecoder<RefreshReservesBatchInstructionData> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"skipPriceUpdates\", getBooleanDecoder()],\n ]);\n}\n\nexport function getRefreshReservesBatchInstructionDataCodec(): FixedSizeCodec<\n RefreshReservesBatchInstructionDataArgs,\n RefreshReservesBatchInstructionData\n> {\n return combineCodec(\n getRefreshReservesBatchInstructionDataEncoder(),\n getRefreshReservesBatchInstructionDataDecoder()\n );\n}\n\nexport type RefreshReservesBatchInput = {\n skipPriceUpdates: RefreshReservesBatchInstructionDataArgs[\"skipPriceUpdates\"];\n};\n\nexport function getRefreshReservesBatchInstruction<\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshReservesBatchInput,\n config?: { programAddress?: TProgramAddress }\n): RefreshReservesBatchInstruction<TProgramAddress> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRefreshReservesBatchInstructionDataEncoder().encode(\n args as RefreshReservesBatchInstructionDataArgs\n ),\n programAddress,\n } as RefreshReservesBatchInstruction<TProgramAddress>);\n}\n\nexport type ParsedRefreshReservesBatchInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n> = { programAddress: Address<TProgram>; data: RefreshReservesBatchInstructionData };\n\nexport function parseRefreshReservesBatchInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshReservesBatchInstruction<TProgram> {\n return {\n programAddress: instruction.programAddress,\n data: getRefreshReservesBatchInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import type { ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type { KaminoFarmState, KaminoObligation, KaminoReserve } from \"./types\";\n\nimport { FARM_STATE_DISCRIMINATOR, getFarmStateDecoder } from \"~/generated/kfarms\";\nimport {\n getObligationDecoder,\n getReserveDecoder,\n OBLIGATION_DISCRIMINATOR,\n RESERVE_DISCRIMINATOR,\n} from \"~/generated/klend\";\n\nexport { FARMS_PROGRAM_ADDRESS } from \"~/generated/kfarms\";\nexport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"~/generated/klend\";\n\n/**\n * Decodes a Kamino `Reserve` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKlendReserve(data: ReadonlyUint8Array): KaminoReserve {\n return decodeAccountData(data, RESERVE_DISCRIMINATOR, getReserveDecoder(), \"Kamino Reserve\");\n}\n\n/**\n * Decodes a Kamino `Obligation` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKlendObligation(data: ReadonlyUint8Array): KaminoObligation {\n return decodeAccountData(\n data,\n OBLIGATION_DISCRIMINATOR,\n getObligationDecoder(),\n \"Kamino Obligation\"\n );\n}\n\n/**\n * Decodes a Kamino farms `FarmState` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKaminoFarmState(data: ReadonlyUint8Array): KaminoFarmState {\n return decodeAccountData(\n data,\n FARM_STATE_DISCRIMINATOR,\n getFarmStateDecoder(),\n \"Kamino FarmState\"\n );\n}\n","// Slot timing constants (matches Kamino SDK)\nexport const SLOTS_PER_SECOND = 2;\n\nexport const SLOTS_PER_MINUTE = SLOTS_PER_SECOND * 60;\n\nexport const SLOTS_PER_HOUR = SLOTS_PER_MINUTE * 60;\n\nexport const SLOTS_PER_DAY = SLOTS_PER_HOUR * 24;\n\nexport const SLOTS_PER_YEAR = SLOTS_PER_DAY * 365;\n\n// Wall-clock year used by the klend program for `TrueApr` reserves\n// (`SECONDS_PER_YEAR = 60 * 60 * 24 * 365`, no leap-year correction).\nexport const SECONDS_PER_YEAR = 31_536_000;\n\n// Default slot duration in milliseconds (matches klend-sdk >= 11)\nexport const DEFAULT_RECENT_SLOT_DURATION_MS = 350;\n\nexport const ONE_HUNDRED_PCT_IN_BPS = 10_000;\n","import { Decimal } from \"decimal.js\";\n\n// Kamino's fractions exceed Decimal's default 20 significant digits and must round-trip exactly\n// (e.g. u128::MAX means \"withdraw all\"), so they use a private 40-digit clone.\nconst FractionDecimal = Decimal.clone({ precision: 40 });\n\n/** Kamino U68F60 scaled fraction (`*Sf` fields). */\nexport class Fraction {\n static MAX_SIZE_F = 128;\n static MAX_SIZE_BF = 256;\n static FRACTIONS = 60;\n static MULTIPLIER = new FractionDecimal(2).pow(Fraction.FRACTIONS);\n\n static MAX_F = 2n ** BigInt(Fraction.MAX_SIZE_F) - 1n;\n static MAX_BF = 2n ** BigInt(Fraction.MAX_SIZE_BF) - 1n;\n\n valueSf: bigint;\n\n /** @throws if `valueSf` is negative or exceeds 256 bits */\n constructor(valueSf: bigint) {\n if (valueSf < 0n || valueSf > Fraction.MAX_BF) {\n throw new Error(\"Number out of range\");\n }\n this.valueSf = valueSf;\n }\n\n toDecimal(): Decimal {\n return new FractionDecimal(this.valueSf.toString()).div(Fraction.MULTIPLIER);\n }\n\n static fromDecimal(n: Decimal | number): Fraction {\n const scaled = new FractionDecimal(n).mul(Fraction.MULTIPLIER);\n // `toFixed()` avoids the exponential notation `BigInt` can't parse.\n return new Fraction(BigInt(scaled.toDecimalPlaces(0, Decimal.ROUND_HALF_CEIL).toFixed()));\n }\n\n static fromBps(n: Decimal | number): Fraction {\n return Fraction.fromDecimal(new FractionDecimal(n).div(10000));\n }\n\n static fromPercent(n: Decimal | number): Fraction {\n return Fraction.fromDecimal(new FractionDecimal(n).div(100));\n }\n\n getValue(): bigint {\n return this.valueSf;\n }\n\n gt(x: Fraction): boolean {\n return this.valueSf > x.valueSf;\n }\n\n lt(x: Fraction): boolean {\n return this.valueSf < x.valueSf;\n }\n\n gte(x: Fraction): boolean {\n return this.valueSf >= x.valueSf;\n }\n\n lte(x: Fraction): boolean {\n return this.valueSf <= x.valueSf;\n }\n\n eq(x: Fraction): boolean {\n return this.valueSf === x.valueSf;\n }\n}\n","import { AccountRole, type Address, type Instruction } from \"@solana/kit\";\n\nimport type { KaminoReserve } from \"./types\";\n\nimport {\n getRefreshObligationInstruction,\n getRefreshReserveInstruction,\n getRefreshReservesBatchInstruction,\n} from \"~/generated/klend\";\n\nconst DISABLED_ORACLES = new Set([\n \"11111111111111111111111111111111\",\n \"nu11111111111111111111111111111111111111111\",\n]);\n\nfunction enabledOracle(oracle: Address): Address | undefined {\n return DISABLED_ORACLES.has(oracle) ? undefined : oracle;\n}\n\n/** Refreshes `reserve` with whichever of its configured oracles are enabled. */\nexport function makeRefreshReserveIx(reserveAddress: Address, reserve: KaminoReserve): Instruction {\n const { tokenInfo } = reserve.config;\n return getRefreshReserveInstruction({\n reserve: reserveAddress,\n lendingMarket: reserve.lendingMarket,\n pythOracle: enabledOracle(tokenInfo.pythConfiguration.price),\n switchboardPriceOracle: enabledOracle(tokenInfo.switchboardConfiguration.priceAggregator),\n switchboardTwapOracle: enabledOracle(tokenInfo.switchboardConfiguration.twapAggregator),\n scopePrices: enabledOracle(tokenInfo.scopeConfiguration.priceFeed),\n });\n}\n\n/** Refreshes an obligation holding a single position in `reserve`. */\nexport function makeRefreshObligationIx(\n lendingMarket: Address,\n obligation: Address,\n reserve: Address\n): Instruction {\n const ix = getRefreshObligationInstruction({ lendingMarket, obligation });\n return { ...ix, accounts: [...ix.accounts, { address: reserve, role: AccountRole.READONLY }] };\n}\n\n/** Refreshes many reserves in one instruction without updating prices. */\nexport function makeRefreshReservesBatchIx(\n reserves: { reserve: Address; lendingMarket: Address }[]\n): Instruction {\n return {\n ...getRefreshReservesBatchInstruction({ skipPriceUpdates: true }),\n accounts: reserves.flatMap(({ reserve, lendingMarket }) => [\n { address: reserve, role: AccountRole.WRITABLE },\n { address: lendingMarket, role: AccountRole.READONLY },\n ]),\n };\n}\n\n/** Refresh reserve then refresh obligation, as required before a Kamino deposit/withdraw CPI. */\nexport function makeRefreshingIxs(\n reserveAddress: Address,\n reserve: KaminoReserve,\n obligation: Address\n): Instruction[] {\n return [\n makeRefreshReserveIx(reserveAddress, reserve),\n makeRefreshObligationIx(reserve.lendingMarket, obligation, reserveAddress),\n ];\n}\n","import type { Address } from \"@solana/kit\";\n\n/**\n * Curated Kamino Reserve: the subset of the generated `Reserve` the SDK reads. A decoded `Reserve`\n * satisfies it structurally.\n */\nexport interface KaminoReserve {\n lendingMarket: Address;\n farmCollateral: Address;\n liquidity: KaminoReserveLiquidity;\n collateral: KaminoReserveCollateral;\n config: KaminoReserveConfig;\n /** cTokens queued for withdrawal; their liquidity is reserved for the ticket holders */\n withdrawQueue: { queuedCollateralAmount: bigint };\n}\n\nexport interface KaminoReserveLiquidity {\n mintPubkey: Address;\n supplyVault: Address;\n mintDecimals: bigint;\n /** Liquid vault balance, native units */\n totalAvailableAmount: bigint;\n /** Scaled fraction */\n borrowedAmountSf: bigint;\n /** Scaled fraction */\n accumulatedProtocolFeesSf: bigint;\n /** Scaled fraction */\n accumulatedReferrerFeesSf: bigint;\n /** Scaled fraction; claimed in refresh_obligation by referrer or protocol */\n pendingReferrerFeesSf: bigint;\n}\n\nexport interface KaminoReserveCollateral {\n mintPubkey: Address;\n /** cToken supply, used for the exchange rate */\n mintTotalSupply: bigint;\n supplyVault: Address;\n}\n\n/** On-chain `InterestRateBasis`, stored as the `u8` `ReserveConfig.interestRateBasis`. */\nexport enum KaminoInterestRateBasis {\n /** Nominal slot-year APRs (`SLOTS_PER_SECOND`); realized rate scales with slot duration. */\n Legacy = 0,\n /** Wall-clock APRs over `SECONDS_PER_YEAR`. All reserves created by klend >= 1.25.0. */\n TrueApr = 1,\n}\n\nexport interface KaminoReserveConfig {\n /** Share of borrow interest kept by the protocol, percent */\n protocolTakeRatePct: number;\n hostFixedInterestRateBps: number;\n /** See {@link KaminoInterestRateBasis}; absent on DTOs serialized before it existed (= Legacy). */\n interestRateBasis?: number;\n /** Native units, u64::MAX for inf */\n depositLimit: bigint;\n /** Native units, u64::MAX for inf, 0 disables borrows */\n borrowLimit: bigint;\n borrowRateCurve: { points: Array<KaminoBorrowRateCurvePoint> };\n tokenInfo: KaminoReserveTokenInfo;\n /** Nonzero while the reserve is in emergency mode; marginfi then gives its collateral zero initial weight */\n emergencyMode: number;\n}\n\nexport interface KaminoBorrowRateCurvePoint {\n utilizationRateBps: number;\n borrowRateBps: number;\n}\n\n/** Oracle feeds; a feed is disabled when its address is the default or null address. */\nexport interface KaminoReserveTokenInfo {\n scopeConfiguration: { priceFeed: Address };\n switchboardConfiguration: { priceAggregator: Address; twapAggregator: Address };\n pythConfiguration: { price: Address };\n}\n\n/** Curated Kamino Obligation: owner, market and the fixed-size deposit/borrow slots. */\nexport interface KaminoObligation {\n lendingMarket: Address;\n owner: Address;\n deposits: Array<KaminoObligationCollateral>;\n borrows: Array<KaminoObligationLiquidity>;\n}\n\nexport interface KaminoObligationCollateral {\n depositReserve: Address;\n /** cTokens */\n depositedAmount: bigint;\n /** Scaled fraction, quote currency */\n marketValueSf: bigint;\n}\n\nexport interface KaminoObligationLiquidity {\n borrowReserve: Address;\n /** Scaled fraction, includes interest */\n borrowedAmountSf: bigint;\n /** Scaled fraction, quote currency */\n marketValueSf: bigint;\n}\n\n/** Curated Kamino FarmState: staked token and the reward schedules needed for reward APYs. */\nexport interface KaminoFarmState {\n token: KaminoFarmTokenInfo;\n rewardInfos: Array<KaminoFarmRewardInfo>;\n}\n\nexport interface KaminoFarmTokenInfo {\n mint: Address;\n decimals: bigint;\n}\n\nexport interface KaminoFarmRewardInfo {\n token: KaminoFarmTokenInfo;\n /** Rewards left in the rewards vault, native units */\n rewardsAvailable: bigint;\n rewardsPerSecondDecimals: number;\n /** Stepwise: each point's rate applies from its `tsStart` until the next point's. */\n rewardScheduleCurve: { points: Array<KaminoRewardCurvePoint> };\n}\n\nexport interface KaminoRewardCurvePoint {\n tsStart: bigint;\n rewardPerTimeUnit: bigint;\n}\n\n/** JSON DTO of {@link KaminoReserve}: addresses and bigints as strings. */\nexport interface KaminoReserveJSON {\n lendingMarket: string;\n farmCollateral: string;\n liquidity: {\n mintPubkey: string;\n supplyVault: string;\n mintDecimals: string;\n totalAvailableAmount: string;\n borrowedAmountSf: string;\n accumulatedProtocolFeesSf: string;\n accumulatedReferrerFeesSf: string;\n pendingReferrerFeesSf: string;\n };\n collateral: {\n mintPubkey: string;\n mintTotalSupply: string;\n supplyVault: string;\n };\n withdrawQueue: { queuedCollateralAmount: string };\n config: {\n protocolTakeRatePct: number;\n hostFixedInterestRateBps: number;\n interestRateBasis?: number;\n depositLimit: string;\n borrowLimit: string;\n borrowRateCurve: { points: Array<KaminoBorrowRateCurvePoint> };\n tokenInfo: {\n scopeConfiguration: { priceFeed: string };\n switchboardConfiguration: { priceAggregator: string; twapAggregator: string };\n pythConfiguration: { price: string };\n };\n /** Missing on older DTOs (= not in emergency) */\n emergencyMode?: number;\n };\n}\n\n/** JSON DTO of {@link KaminoObligation}: addresses and bigints as strings. */\nexport interface KaminoObligationJSON {\n lendingMarket: string;\n owner: string;\n deposits: Array<{ depositReserve: string; depositedAmount: string; marketValueSf: string }>;\n borrows: Array<{ borrowReserve: string; borrowedAmountSf: string; marketValueSf: string }>;\n}\n\n/** JSON DTO of {@link KaminoFarmState}: addresses and bigints as strings. */\nexport interface KaminoFarmStateJSON {\n token: { mint: string; decimals: string };\n rewardInfos: Array<{\n token: { mint: string; decimals: string };\n rewardsAvailable: string;\n rewardsPerSecondDecimals: number;\n rewardScheduleCurve: { points: Array<{ tsStart: string; rewardPerTimeUnit: string }> };\n }>;\n}\n\n/** A marginfi Kamino bank's venue accounts (its integration accounts 1 and 2). */\nexport interface KaminoBankInput {\n bankAddress: Address;\n reserve: Address;\n obligation: Address;\n}\n\n/** A Kamino bank's venue state: its reserve, obligation and, when the reserve has one, collateral farm. */\nexport interface KaminoStates {\n reserveState: KaminoReserve;\n obligationState: KaminoObligation;\n farmState?: KaminoFarmState;\n}\n\n/** JSON DTO of {@link KaminoStates}. */\nexport interface KaminoStatesJSON {\n reserveState: KaminoReserveJSON;\n obligationState: KaminoObligationJSON;\n farmState?: KaminoFarmStateJSON;\n}\n","/**\n * Kamino Lending Protocol - Interest Rate Utilities\n *\n * Provides utilities for calculating interest rates, reserve metrics, and curve generation\n * for the Kamino lending protocol.\n *\n * Extracted all needed functions & constants out of their SDK.\n *\n * Rates here use the reserve state as of its last refresh. klend-sdk >= 12 instead projects\n * accrual to a ledger instant (`getEstimatedDebtAndSupply`) and adds a reserve-rewards supply APR\n * (`calculateTheoreticalReserveRewardsSupplyAPR`); neither is ported yet.\n */\n\nimport { BigNumber } from \"bignumber.js\";\nimport { Decimal } from \"decimal.js\";\n\nimport {\n ONE_HUNDRED_PCT_IN_BPS,\n SLOTS_PER_YEAR,\n SLOTS_PER_SECOND,\n SECONDS_PER_YEAR,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n} from \"./constants\";\nimport { Fraction } from \"./fraction\";\nimport { KaminoBorrowRateCurvePoint, KaminoInterestRateBasis, KaminoReserve } from \"./types\";\n\n// =============================================================================\n// INTERFACES\n// =============================================================================\n\nexport interface KlendInterestRateCurvePoint {\n utilization: number; // 0-100 percentage\n borrowAPY: number; // percentage\n supplyAPY: number; // percentage\n}\n\nexport interface KaminoReserveCurveData {\n reserveAddress: string;\n curvePoints: KlendInterestRateCurvePoint[];\n}\n\n/**\n * How a reserve's configured (curve) rate is turned into a realized annual rate.\n * `multiplier` scales the curve rate; `periodsPerYear` is the compounding\n * granularity used to convert APR to APY.\n */\nexport interface KaminoRateBasis {\n multiplier: number;\n periodsPerYear: number;\n}\n\n// =============================================================================\n// CORE MATH UTILITIES\n// =============================================================================\n\n/**\n * Linear interpolation between two points\n */\nexport const interpolateLinear = (\n x: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number\n): number => {\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\n};\n\n/**\n * Calculate borrow rate from utilization using interest rate curve\n * @param currentUtilization - Current utilization ratio (0-1)\n * @param curve - Array of [utilization, rate] points\n * @returns Borrow rate for the given utilization\n */\nexport const getKaminoBorrowRate = (\n currentUtilization: number,\n curve: [number, number][]\n): number => {\n let [x0, y0, x1, y1] = [0, 0, 0, 0];\n\n if (currentUtilization > 1) {\n currentUtilization = 1;\n }\n\n for (let i = 1; i < curve.length; i++) {\n const currentPoint = curve[i];\n const previousPoint = curve[i - 1];\n\n if (!currentPoint || !previousPoint) {\n continue;\n }\n\n const [pointUtilization, pointRate] = currentPoint;\n if (pointUtilization === currentUtilization) {\n return pointRate;\n }\n\n if (currentUtilization <= pointUtilization) {\n x0 = previousPoint[0];\n y0 = previousPoint[1];\n x1 = currentPoint[0];\n y1 = currentPoint[1];\n break;\n }\n }\n\n if (x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {\n const lastPoint = curve[curve.length - 1];\n return lastPoint ? lastPoint[1] : 0;\n }\n\n return interpolateLinear(currentUtilization, x0, y0, x1, y1);\n};\n\n// =============================================================================\n// APR/APY CONVERSIONS\n// =============================================================================\n\n/**\n * Convert APR to APY using compound interest formula\n * APY = (1 + APR/n)^n - 1\n * @param apr - Annual Percentage Rate as decimal (e.g., 0.05 for 5%)\n * @param periodsPerYear - Compounding periods per year (defaults to SLOTS_PER_YEAR;\n * use `getKaminoRateBasis(reserve).periodsPerYear` for basis-aware compounding)\n * @returns Annual Percentage Yield as decimal\n */\nexport function calculateAPYFromAPR(apr: number, periodsPerYear: number = SLOTS_PER_YEAR): number {\n return Math.pow(1 + apr / periodsPerYear, periodsPerYear) - 1;\n}\n\n// =============================================================================\n// RESERVE SUPPLY & UTILIZATION\n// =============================================================================\n\n/**\n * Calculate total supply of a reserve\n * Formula: available liquidity + borrowed - protocol fees - referrer fees\n * @param reserve - The Kamino reserve\n * @returns Total supply in lamports\n */\nexport function getKaminoTotalSupply(reserve: KaminoReserve): Decimal {\n const liquidityAvailableAmount = new Decimal(reserve.liquidity.totalAvailableAmount.toString());\n const borrowedAmount = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();\n const accumulatedProtocolFee = new Fraction(\n reserve.liquidity.accumulatedProtocolFeesSf\n ).toDecimal();\n const accumulatedReferrerFees = new Fraction(\n reserve.liquidity.accumulatedReferrerFeesSf\n ).toDecimal();\n const pendingReferrerFees = new Fraction(reserve.liquidity.pendingReferrerFeesSf).toDecimal();\n\n return liquidityAvailableAmount\n .add(borrowedAmount)\n .sub(accumulatedProtocolFee)\n .sub(accumulatedReferrerFees)\n .sub(pendingReferrerFees);\n}\n\n/**\n * Calculate utilization ratio of a reserve\n * Formula: total borrowed / total supply\n * @param reserve - The Kamino reserve\n * @returns Utilization ratio (0-1, e.g., 0.75 = 75% utilized)\n */\nexport function calculateUtilizationRatio(reserve: KaminoReserve): number {\n const totalBorrows = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();\n const totalSupply = getKaminoTotalSupply(reserve);\n if (totalSupply.eq(0)) {\n return 0;\n }\n return totalBorrows.dividedBy(totalSupply).toNumber();\n}\n\n// =============================================================================\n// INTEREST RATE BASIS & SLOT ADJUSTMENT\n// =============================================================================\n\n/**\n * Resolve a reserve's interest rate basis, defaulting to `Legacy` when the\n * field is absent (reserves serialized before it existed).\n * @throws if the on-chain value is not a known basis\n */\nexport function getKaminoInterestRateBasis(reserve: KaminoReserve): KaminoInterestRateBasis {\n const basis = reserve.config.interestRateBasis ?? KaminoInterestRateBasis.Legacy;\n switch (basis) {\n case KaminoInterestRateBasis.Legacy:\n case KaminoInterestRateBasis.TrueApr:\n return basis;\n default:\n throw new Error(`Unsupported Kamino interest rate basis: ${basis}`);\n }\n}\n\n/**\n * Calculate slot adjustment factor based on recent slot duration\n * Used to adjust Legacy-basis rates based on actual blockchain performance\n * @param recentSlotDurationMs - Recent slot duration in milliseconds\n * @returns Slot adjustment factor\n */\nexport function slotAdjustmentFactor(\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n return 1000 / SLOTS_PER_SECOND / recentSlotDurationMs;\n}\n\n/**\n * Rate multiplier and compounding granularity for a reserve, per its\n * interest rate basis (1:1 with klend-sdk `KaminoReserve.rateAdjustmentFactor()`\n * and `accrualUnitsPerYear()`).\n *\n * - `Legacy`: curve rates are slot-year APRs, so they are scaled by the observed\n * slot duration and compounded per slot.\n * - `TrueApr`: curve rates are wall-clock APRs; `recentSlotDurationMs` is ignored\n * and rates compound per second.\n *\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Observed slot duration; only read for `Legacy`\n * @throws for an unsupported basis, or a non-positive slot duration on `Legacy`\n */\nexport function getKaminoRateBasis(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): KaminoRateBasis {\n switch (getKaminoInterestRateBasis(reserve)) {\n case KaminoInterestRateBasis.Legacy:\n if (!Number.isFinite(recentSlotDurationMs) || recentSlotDurationMs <= 0) {\n throw new Error(\n `Kamino recent slot duration must be positive, got ${recentSlotDurationMs}`\n );\n }\n return {\n multiplier: slotAdjustmentFactor(recentSlotDurationMs),\n periodsPerYear: SLOTS_PER_YEAR,\n };\n case KaminoInterestRateBasis.TrueApr:\n return { multiplier: 1, periodsPerYear: SECONDS_PER_YEAR };\n }\n}\n\n/**\n * Calculate the rate multiplier for a reserve (1:1 with klend-sdk\n * `KaminoReserve.rateAdjustmentFactor()`): the slot adjustment factor for a\n * `Legacy` reserve, `1` for a `TrueApr` one.\n */\nexport function calculateSlotAdjustmentFactor(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n return getKaminoRateBasis(reserve, recentSlotDurationMs).multiplier;\n}\n\n// =============================================================================\n// RATE CALCULATIONS\n// =============================================================================\n\n/**\n * Calculate estimated borrow rate for a reserve\n * @param reserve - The reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n * @returns Borrow rate as decimal (e.g., 0.05 = 5%)\n */\nexport function calculateKaminoEstimatedBorrowRate(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const { multiplier } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n const currentUtilization = calculateUtilizationRatio(reserve);\n const curve = truncateBorrowCurve(reserve.config.borrowRateCurve.points);\n return getKaminoBorrowRate(currentUtilization, curve) * multiplier;\n}\n\n/**\n * Calculate estimated supply rate for a reserve\n * Formula: borrow rate × utilization × (1 - protocol take rate)\n * @param reserve - The reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n * @returns Supply rate as decimal (e.g., 0.03 = 3%)\n */\nexport function calculateKaminoEstimatedSupplyRate(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const borrowRate = calculateKaminoEstimatedBorrowRate(reserve, recentSlotDurationMs);\n const currentUtilization = calculateUtilizationRatio(reserve);\n const protocolTakeRatePct = 1 - reserve.config.protocolTakeRatePct / 100;\n\n return borrowRate * currentUtilization * protocolTakeRatePct;\n}\n\n/**\n * Calculate supply APY for a reserve\n * APY includes compounding, making it higher than APR\n * Matches Kamino SDK's reserve.totalSupplyAPY()\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Recent slot duration (defaults to\n * DEFAULT_RECENT_SLOT_DURATION_MS; ignored for TrueApr reserves)\n * @returns Supply APY as decimal (e.g., 0.0512 = 5.12% APY)\n */\nexport function calculateKaminoSupplyAPY(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const { periodsPerYear } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n const supplyApr = calculateKaminoEstimatedSupplyRate(reserve, recentSlotDurationMs);\n return calculateAPYFromAPR(supplyApr, periodsPerYear);\n}\n\nexport function scaledSupplies(state: KaminoReserve): [Decimal, Decimal] {\n const liqMintDecimals = new Decimal(state.liquidity.mintDecimals.toString());\n const totalSupplyLamports = getKaminoTotalSupply(state);\n const mintTotalSupplyLam = new Decimal(state.collateral.mintTotalSupply.toString());\n\n const liqScale = new Decimal(10).pow(liqMintDecimals);\n const collScale = new Decimal(10).pow(liqMintDecimals);\n\n const totalSupply = totalSupplyLamports.div(liqScale);\n const totalCollateral = mintTotalSupplyLam.div(collScale);\n\n return [totalSupply, totalCollateral];\n}\n\n// =============================================================================\n// CURVE PROCESSING\n// =============================================================================\n\n/** Underlying tokens per cToken of `reserve` (1 while it has no collateral). */\nexport function getKaminoCTokenMultiplier(reserve: KaminoReserve): BigNumber {\n const [totalLiquidity, totalCollateral] = scaledSupplies(reserve);\n\n return totalCollateral.isZero()\n ? new BigNumber(1)\n : new BigNumber(totalLiquidity.dividedBy(totalCollateral).toString());\n}\n\n/**\n * Convert raw curve points to normalized [utilization, rate] pairs\n * Truncates curve at 100% utilization\n */\nexport const truncateBorrowCurve = (points: KaminoBorrowRateCurvePoint[]): [number, number][] => {\n const curve: [number, number][] = [];\n for (const { utilizationRateBps, borrowRateBps } of points) {\n curve.push([\n utilizationRateBps / ONE_HUNDRED_PCT_IN_BPS,\n borrowRateBps / ONE_HUNDRED_PCT_IN_BPS,\n ]);\n\n if (utilizationRateBps === ONE_HUNDRED_PCT_IN_BPS) {\n break;\n }\n }\n return curve;\n};\n\n/**\n * Get fixed host interest rate from reserve config (1:1 with Kamino SDK)\n * Source: klend-sdk/src/classes/reserve.ts line 209\n */\nexport function getFixedHostInterestRate(reserve: KaminoReserve): number {\n return reserve.config.hostFixedInterestRateBps / 10_000;\n}\n\n/**\n * Get protocol take rate percentage from reserve config\n */\nexport function getProtocolTakeRatePct(reserve: KaminoReserve): number {\n return 1 - reserve.config.protocolTakeRatePct / 100;\n}\n\n// =============================================================================\n// CURVE GENERATION\n// =============================================================================\n\n/**\n * Generate complete interest rate curve for a reserve\n * Creates 101 data points from 0% to 100% utilization\n * @param curvePoints - Raw curve configuration from reserve\n * @param slotAdjustmentFactor - Rate multiplier (`calculateSlotAdjustmentFactor`;\n * the slot adjustment for Legacy reserves, 1 for TrueApr)\n * @param fixedHostInterestRate - Fixed rate added to all borrow rates\n * @param protocolTakeRatePct - Percentage kept by depositors (1 - protocol fee)\n * @param periodsPerYear - APY compounding periods (`getKaminoRateBasis(reserve).periodsPerYear`;\n * defaults to SLOTS_PER_YEAR)\n * @returns Array of curve points with utilization, borrow APY, and supply APY\n */\nexport function generateKaminoReserveCurve(\n curvePoints: KaminoBorrowRateCurvePoint[],\n slotAdjustmentFactor: number,\n fixedHostInterestRate: number,\n protocolTakeRatePct: number,\n periodsPerYear: number = SLOTS_PER_YEAR\n): KlendInterestRateCurvePoint[] {\n if (curvePoints.length === 0) {\n return [];\n }\n\n const curve = truncateBorrowCurve(curvePoints);\n\n return Array.from({ length: 101 }, (_, i) => {\n const utilization = i / 100;\n\n // Calculate base borrow rate and add fixed host interest\n const baseBorrowRate = getKaminoBorrowRate(utilization, curve) * slotAdjustmentFactor;\n const borrowAPR = baseBorrowRate + fixedHostInterestRate;\n\n // Calculate supply APR (utilization × borrowAPR × protocolTakeRate)\n const supplyAPR = utilization * borrowAPR * protocolTakeRatePct;\n\n // Convert to APY with compounding\n const borrowAPY = calculateAPYFromAPR(borrowAPR, periodsPerYear);\n const supplyAPY = calculateAPYFromAPR(supplyAPR, periodsPerYear);\n\n return {\n utilization: utilization * 100,\n borrowAPY: borrowAPY * 100,\n supplyAPY: supplyAPY * 100,\n };\n });\n}\n\n/**\n * Generate the interest rate curve for a reserve, deriving the rate multiplier\n * and compounding granularity from its interest rate basis.\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n */\nexport function generateKaminoReserveCurveFromReserve(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): KlendInterestRateCurvePoint[] {\n const { multiplier, periodsPerYear } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n return generateKaminoReserveCurve(\n reserve.config.borrowRateCurve.points,\n multiplier,\n getFixedHostInterestRate(reserve),\n getProtocolTakeRatePct(reserve),\n periodsPerYear\n );\n}\n","import {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nimport { FARMS_PROGRAM_ADDRESS } from \"~/generated/kfarms\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"~/generated/klend\";\n\nconst DEFAULT_ADDRESS = \"11111111111111111111111111111111\" as Address;\n\n/** Kamino lending market authority PDA. */\nexport function deriveLendingMarketAuthority(\n lendingMarket: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\"lma\", getAddressEncoder().encode(lendingMarket)],\n });\n}\n\n/** Reserve liquidity supply vault PDA. */\nexport function deriveReserveLiquiditySupply(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_liq_supply\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve fee receiver PDA. */\nexport function deriveFeeReceiver(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"fee_receiver\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve collateral (cToken) mint PDA. */\nexport function deriveReserveCollateralMint(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_coll_mint\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve collateral (cToken) supply vault PDA. */\nexport function deriveReserveCollateralSupply(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_coll_supply\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/**\n * Obligation PDA. Bank obligations use `tag` and `id` 0 with default seed accounts.\n */\nexport function deriveObligation({\n owner,\n lendingMarket,\n tag = 0,\n id = 0,\n seed1 = DEFAULT_ADDRESS,\n seed2 = DEFAULT_ADDRESS,\n}: {\n owner: Address;\n lendingMarket: Address;\n tag?: number;\n id?: number;\n seed1?: Address;\n seed2?: Address;\n}): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n new Uint8Array([tag]),\n new Uint8Array([id]),\n getAddressEncoder().encode(owner),\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(seed1),\n getAddressEncoder().encode(seed2),\n ],\n });\n}\n\n/**\n * Farms program user state PDA for `obligation` in `farmState`: the obligation's rewards\n * position, unrelated to marginfi users.\n */\nexport function deriveUserState(\n farmState: Address,\n obligation: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: FARMS_PROGRAM_ADDRESS,\n seeds: [\"user\", getAddressEncoder().encode(farmState), getAddressEncoder().encode(obligation)],\n });\n}\n","import { Decimal } from \"decimal.js\";\n\nimport { getKaminoTotalSupply } from \"./interest-rate\";\nimport { KaminoFarmRewardInfo, KaminoFarmState, KaminoReserve } from \"./types\";\n\nexport function getRewardPerTimeUnitSecond(reward: KaminoFarmRewardInfo) {\n const now = new Decimal(new Date().getTime()).div(1000);\n let rewardPerTimeUnitSecond = new Decimal(0);\n for (let i = 0; i < reward.rewardScheduleCurve.points.length - 1; i++) {\n const currentPoint = reward.rewardScheduleCurve.points[i];\n const nextPoint = reward.rewardScheduleCurve.points[i + 1];\n\n if (!currentPoint || !nextPoint) {\n continue;\n }\n\n const { tsStart: tsStartThisPoint, rewardPerTimeUnit } = currentPoint;\n const { tsStart: tsStartNextPoint } = nextPoint;\n\n const thisPeriodStart = new Decimal(tsStartThisPoint.toString());\n const thisPeriodEnd = new Decimal(tsStartNextPoint.toString());\n const rps = new Decimal(rewardPerTimeUnit.toString());\n if (thisPeriodStart.lte(now) && thisPeriodEnd.gte(now)) {\n rewardPerTimeUnitSecond = rps;\n break;\n } else if (thisPeriodStart.gt(now) && thisPeriodEnd.gt(now)) {\n rewardPerTimeUnitSecond = rps;\n break;\n }\n }\n\n const rewardTokenDecimals = Number(reward.token.decimals);\n const rewardAmountPerUnitDecimals = new Decimal(10).pow(\n reward.rewardsPerSecondDecimals.toString()\n );\n const rewardAmountPerUnitLamports = new Decimal(10).pow(rewardTokenDecimals.toString());\n\n const rpsAdjusted = new Decimal(rewardPerTimeUnitSecond.toString())\n .div(rewardAmountPerUnitDecimals)\n .div(rewardAmountPerUnitLamports);\n\n return rewardPerTimeUnitSecond ? rpsAdjusted : new Decimal(0);\n}\n\nexport async function getReserveRewardsApy(\n priceByMint: Record<string, number>,\n farmState: KaminoFarmState,\n reserveState: KaminoReserve\n) {\n const rewardApys: {\n rewardApy: Decimal;\n rewardInfo: KaminoFarmRewardInfo;\n rewardApr: Decimal;\n }[] = [];\n\n for (const rewardInfo of farmState.rewardInfos.filter(\n (x) => x.token.mint !== \"11111111111111111111111111111111\"\n )) {\n // Skip if we don't have prices for reserve or reward token\n const reserveMint = reserveState.liquidity.mintPubkey.toString();\n const rewardMint = rewardInfo.token.mint.toString();\n\n const reservePrice = priceByMint[reserveMint];\n const rewardPrice = priceByMint[rewardMint];\n\n // Check for undefined or null (but allow 0 as a valid price)\n if (\n reservePrice === undefined ||\n reservePrice === null ||\n rewardPrice === undefined ||\n rewardPrice === null\n ) {\n continue;\n }\n\n const { apy, apr } = calculateRewardApy(priceByMint, reserveState, rewardInfo);\n rewardApys.push({ rewardApy: apy, rewardInfo, rewardApr: apr });\n }\n\n return rewardApys;\n}\n\nexport function calculateRewardApy(\n priceByMint: Record<string, number>,\n reserve: KaminoReserve,\n rewardInfo: KaminoFarmRewardInfo\n) {\n const decimals = Number(reserve.liquidity.mintDecimals);\n const totalSupply = getKaminoTotalSupply(reserve);\n const mintAddress = reserve.liquidity.mintPubkey;\n const totalAmount = lamportsToNumberDecimal(totalSupply, decimals);\n const mintPrice = priceByMint[mintAddress.toString()] ?? 0;\n const totalValue = totalAmount.mul(mintPrice);\n const rewardPerTimeUnitSecond = getRewardPerTimeUnitSecond(rewardInfo);\n const rewardsInYear = rewardPerTimeUnitSecond.mul(60 * 60 * 24 * 365);\n const rewardTokenPrice = priceByMint[rewardInfo.token.mint.toString()] ?? 0;\n const rewardsInYearValue = rewardsInYear.mul(rewardTokenPrice);\n const apr = rewardsInYearValue.div(totalValue);\n return { apr, apy: aprToApy(apr, 1) };\n}\n\nfunction aprToApy(apr: Decimal, compoundPeriods: number) {\n // if periods = 365 => daily compound\n // periods = 1 => yearly compound\n // (1 + apr / periods) ** periods - 1;\n return new Decimal(1).add(apr.div(compoundPeriods)).pow(compoundPeriods).sub(1);\n}\n\nfunction lamportsToNumberDecimal(amount: Decimal.Value, decimals: number): Decimal {\n const factor = 10 ** decimals;\n return new Decimal(amount).div(factor);\n}\n","import { address } from \"@solana/kit\";\n\nimport {\n KaminoFarmState,\n KaminoFarmStateJSON,\n KaminoInterestRateBasis,\n KaminoObligation,\n KaminoObligationJSON,\n KaminoReserve,\n KaminoReserveJSON,\n} from \"./types\";\n\n/** Serializes a Kamino Obligation (or a decoded `Obligation`) to its JSON DTO. */\nexport function kaminoObligationToDto(obligation: KaminoObligation): KaminoObligationJSON {\n return {\n lendingMarket: obligation.lendingMarket,\n owner: obligation.owner,\n deposits: obligation.deposits.map((item) => ({\n depositReserve: item.depositReserve,\n depositedAmount: item.depositedAmount.toString(),\n marketValueSf: item.marketValueSf.toString(),\n })),\n borrows: obligation.borrows.map((item) => ({\n borrowReserve: item.borrowReserve,\n borrowedAmountSf: item.borrowedAmountSf.toString(),\n marketValueSf: item.marketValueSf.toString(),\n })),\n };\n}\n\n/**\n * Parses a Kamino Obligation DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoObligation(dto: KaminoObligationJSON): KaminoObligation {\n return {\n lendingMarket: address(dto.lendingMarket),\n owner: address(dto.owner),\n // Hosted endpoints may prune empty position arrays from the payload\n deposits: (dto.deposits ?? []).map((item) => ({\n depositReserve: address(item.depositReserve),\n depositedAmount: BigInt(item.depositedAmount),\n marketValueSf: BigInt(item.marketValueSf),\n })),\n borrows: (dto.borrows ?? []).map((item) => ({\n borrowReserve: address(item.borrowReserve),\n borrowedAmountSf: BigInt(item.borrowedAmountSf),\n marketValueSf: BigInt(item.marketValueSf),\n })),\n };\n}\n\n/** Serializes a Kamino Reserve (or a decoded `Reserve`) to its JSON DTO. */\nexport function kaminoReserveToDto(reserve: KaminoReserve): KaminoReserveJSON {\n const { liquidity, collateral, config } = reserve;\n return {\n lendingMarket: reserve.lendingMarket,\n farmCollateral: reserve.farmCollateral,\n liquidity: {\n mintPubkey: liquidity.mintPubkey,\n supplyVault: liquidity.supplyVault,\n mintDecimals: liquidity.mintDecimals.toString(),\n totalAvailableAmount: liquidity.totalAvailableAmount.toString(),\n borrowedAmountSf: liquidity.borrowedAmountSf.toString(),\n accumulatedProtocolFeesSf: liquidity.accumulatedProtocolFeesSf.toString(),\n accumulatedReferrerFeesSf: liquidity.accumulatedReferrerFeesSf.toString(),\n pendingReferrerFeesSf: liquidity.pendingReferrerFeesSf.toString(),\n },\n collateral: {\n mintPubkey: collateral.mintPubkey,\n mintTotalSupply: collateral.mintTotalSupply.toString(),\n supplyVault: collateral.supplyVault,\n },\n withdrawQueue: {\n queuedCollateralAmount: reserve.withdrawQueue.queuedCollateralAmount.toString(),\n },\n config: {\n protocolTakeRatePct: config.protocolTakeRatePct,\n hostFixedInterestRateBps: config.hostFixedInterestRateBps,\n interestRateBasis: config.interestRateBasis ?? KaminoInterestRateBasis.Legacy,\n depositLimit: config.depositLimit.toString(),\n borrowLimit: config.borrowLimit.toString(),\n borrowRateCurve: {\n points: config.borrowRateCurve.points.map(({ utilizationRateBps, borrowRateBps }) => ({\n utilizationRateBps,\n borrowRateBps,\n })),\n },\n tokenInfo: {\n scopeConfiguration: { priceFeed: config.tokenInfo.scopeConfiguration.priceFeed },\n switchboardConfiguration: {\n priceAggregator: config.tokenInfo.switchboardConfiguration.priceAggregator,\n twapAggregator: config.tokenInfo.switchboardConfiguration.twapAggregator,\n },\n pythConfiguration: { price: config.tokenInfo.pythConfiguration.price },\n },\n emergencyMode: config.emergencyMode,\n },\n };\n}\n\n/**\n * Parses a Kamino Reserve DTO; a missing `interestRateBasis` becomes Legacy.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoReserve(dto: KaminoReserveJSON): KaminoReserve {\n const { liquidity, collateral, config } = dto;\n return {\n lendingMarket: address(dto.lendingMarket),\n farmCollateral: address(dto.farmCollateral),\n liquidity: {\n mintPubkey: address(liquidity.mintPubkey),\n supplyVault: address(liquidity.supplyVault),\n mintDecimals: BigInt(liquidity.mintDecimals),\n totalAvailableAmount: BigInt(liquidity.totalAvailableAmount),\n borrowedAmountSf: BigInt(liquidity.borrowedAmountSf),\n accumulatedProtocolFeesSf: BigInt(liquidity.accumulatedProtocolFeesSf),\n accumulatedReferrerFeesSf: BigInt(liquidity.accumulatedReferrerFeesSf),\n pendingReferrerFeesSf: BigInt(liquidity.pendingReferrerFeesSf),\n },\n collateral: {\n mintPubkey: address(collateral.mintPubkey),\n mintTotalSupply: BigInt(collateral.mintTotalSupply),\n supplyVault: address(collateral.supplyVault),\n },\n withdrawQueue: { queuedCollateralAmount: BigInt(dto.withdrawQueue.queuedCollateralAmount) },\n config: {\n protocolTakeRatePct: config.protocolTakeRatePct,\n hostFixedInterestRateBps: config.hostFixedInterestRateBps,\n interestRateBasis: config.interestRateBasis ?? KaminoInterestRateBasis.Legacy,\n depositLimit: BigInt(config.depositLimit),\n borrowLimit: BigInt(config.borrowLimit),\n borrowRateCurve: {\n points: config.borrowRateCurve.points.map(({ utilizationRateBps, borrowRateBps }) => ({\n utilizationRateBps,\n borrowRateBps,\n })),\n },\n tokenInfo: {\n scopeConfiguration: { priceFeed: address(config.tokenInfo.scopeConfiguration.priceFeed) },\n switchboardConfiguration: {\n priceAggregator: address(config.tokenInfo.switchboardConfiguration.priceAggregator),\n twapAggregator: address(config.tokenInfo.switchboardConfiguration.twapAggregator),\n },\n pythConfiguration: { price: address(config.tokenInfo.pythConfiguration.price) },\n },\n emergencyMode: config.emergencyMode ?? 0,\n },\n };\n}\n\n/** Serializes a Kamino FarmState (or a decoded `FarmState`) to its JSON DTO. */\nexport function kaminoFarmStateToDto(farmState: KaminoFarmState): KaminoFarmStateJSON {\n return {\n token: { mint: farmState.token.mint, decimals: farmState.token.decimals.toString() },\n rewardInfos: farmState.rewardInfos.map((item) => ({\n token: { mint: item.token.mint, decimals: item.token.decimals.toString() },\n rewardsAvailable: item.rewardsAvailable.toString(),\n rewardsPerSecondDecimals: item.rewardsPerSecondDecimals,\n rewardScheduleCurve: {\n points: item.rewardScheduleCurve.points.map((point) => ({\n tsStart: point.tsStart.toString(),\n rewardPerTimeUnit: point.rewardPerTimeUnit.toString(),\n })),\n },\n })),\n };\n}\n\n/**\n * Parses a Kamino FarmState DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoFarmState(dto: KaminoFarmStateJSON): KaminoFarmState {\n return {\n token: { mint: address(dto.token.mint), decimals: BigInt(dto.token.decimals) },\n rewardInfos: dto.rewardInfos.map((item) => ({\n token: { mint: address(item.token.mint), decimals: BigInt(item.token.decimals) },\n rewardsAvailable: BigInt(item.rewardsAvailable),\n rewardsPerSecondDecimals: item.rewardsPerSecondDecimals,\n rewardScheduleCurve: {\n points: item.rewardScheduleCurve.points.map((point) => ({\n tsStart: BigInt(point.tsStart),\n rewardPerTimeUnit: BigInt(point.rewardPerTimeUnit),\n })),\n },\n })),\n };\n}\n","import { address } from \"@solana/kit\";\n\nexport const HOURS_PER_YEAR = 365.25 * 24;\n\nexport const MAX_U64 = BigInt(\"18446744073709551615\").toString();\n\n/** The all-zero address (`Pubkey::default()`), used on-chain for unset account fields. */\nexport const DEFAULT_ADDRESS = address(\"11111111111111111111111111111111\");\n\n/** Bytes of a stake account (`StakeStateV2`). */\nexport const STAKE_ACCOUNT_SIZE = 200n;\n","import { HOURS_PER_YEAR } from \"../constants\";\n\n// ================ interest rate helpers ================\n\n/**\n * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies\n *\n * @param apy {Number} APY (i.e. 0.06 for 6%)\n * @param compoundingFrequency {Number} Compounding frequency (times a year)\n * @returns {Number} APR (i.e. 0.0582 for APY of 0.06)\n */\nconst apyToApr = (apy: number, compoundingFrequency: number = HOURS_PER_YEAR): number =>\n ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;\n\n/**\n * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies\n *\n *\n * @param apr {Number} APR (i.e. 0.0582 for 5.82%)\n * @param compoundingFrequency {Number} Compounding frequency (times a year)\n * @returns {Number} APY (i.e. 0.06 for APR of 0.0582)\n */\nconst aprToApy = (\n apr: number,\n compoundingFrequency: number = HOURS_PER_YEAR,\n apyCap: number = 3\n): number => Math.min((1 + apr / compoundingFrequency) ** compoundingFrequency - 1, apyCap);\n\nfunction calculateInterestFromApy(principal: number, durationInYears: number, apy: number): number {\n return principal * apy * durationInYears;\n}\n\nfunction calculateApyFromInterest(\n principal: number,\n durationInYears: number,\n interest: number\n): number {\n return interest / (principal * durationInYears);\n}\n\nexport { apyToApr, aprToApy, calculateInterestFromApy, calculateApyFromInterest };\n","import {\n parseBase64RpcAccount,\n type Address,\n type EncodedAccount,\n type GetMultipleAccountsApi,\n type Rpc,\n type Slot,\n} from \"@solana/kit\";\n\nconst MAX_RETRIES = 3;\n\nasync function fetchAccountsInBatches(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number,\n maxAccountsChunkSize: number\n): Promise<{ slot: Slot; accounts: (EncodedAccount | null)[] }> {\n let slot = 0n;\n const accounts: (EncodedAccount | null)[] = [];\n\n for (const batch of chunkArray(addresses, batchChunkSize)) {\n const chunks = chunkArray(batch, maxAccountsChunkSize);\n\n for (let attempt = 1; ; attempt++) {\n try {\n const responses = await Promise.all(\n chunks.map((chunk) =>\n rpc.getMultipleAccounts(chunk, { commitment: \"confirmed\", encoding: \"base64\" }).send()\n )\n );\n responses.forEach((response, chunkIndex) => {\n slot = response.context.slot > slot ? response.context.slot : slot;\n response.value.forEach((rpcAccount, index) => {\n const account = parseBase64RpcAccount(chunks[chunkIndex][index], rpcAccount);\n accounts.push(account.exists ? account : null);\n });\n });\n break;\n } catch {\n if (attempt === MAX_RETRIES) {\n throw new Error(`Failed to fetch account infos after ${MAX_RETRIES} retries`);\n }\n }\n }\n }\n\n return { slot, accounts };\n}\n\nexport async function chunkedGetRawMultipleAccountInfos(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<[Slot, Map<Address, EncodedAccount>]> {\n const { slot, accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n const accountInfoMap = new Map<Address, EncodedAccount>();\n\n for (const account of accounts) {\n if (account) {\n accountInfoMap.set(account.address, account);\n }\n }\n\n return [slot, accountInfoMap];\n}\n\nexport async function chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<(EncodedAccount | null)[]> {\n const { accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n return accounts;\n}\n\nexport async function chunkedGetRawMultipleAccountInfoOrdered(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<EncodedAccount[]> {\n const { accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n return accounts.filter((account) => account !== null);\n}\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\n\nimport { decodeKaminoFarmState, decodeKlendObligation, decodeKlendReserve } from \"./accounts\";\nimport { kaminoFarmStateToDto, kaminoObligationToDto, kaminoReserveToDto } from \"./serialize\";\nimport type { KaminoBankInput, KaminoStates, KaminoStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link KaminoStates}, keyed by bank address. Banks with a default venue\n * address or a missing reserve or obligation are left out.\n * @throws if a fetched account isn't the Kamino account it should be\n */\nexport async function fetchKaminoStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: KaminoBankInput[]\n): Promise<Record<string, KaminoStates>> {\n const validBanks = banks.filter(\n (bank) => bank.reserve !== DEFAULT_ADDRESS && bank.obligation !== DEFAULT_ADDRESS\n );\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.flatMap((bank) => [bank.reserve, bank.obligation])\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const [reserve, obligation] = accounts.slice(2 * i, 2 * i + 2);\n return reserve && obligation\n ? [\n {\n bankAddress: bank.bankAddress,\n reserveState: decodeKlendReserve(reserve.data),\n obligationState: decodeKlendObligation(obligation.data),\n },\n ]\n : [];\n });\n\n const withFarm = decoded.filter(\n ({ reserveState }) => reserveState.farmCollateral !== DEFAULT_ADDRESS\n );\n const farms = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n withFarm.map(({ reserveState }) => reserveState.farmCollateral)\n );\n const farmByBank = new Map(withFarm.map(({ bankAddress }, i) => [bankAddress, farms[i]]));\n\n return Object.fromEntries(\n decoded.map(({ bankAddress, reserveState, obligationState }) => {\n const farm = farmByBank.get(bankAddress);\n return [\n bankAddress,\n {\n reserveState,\n obligationState,\n farmState: farm ? decodeKaminoFarmState(farm.data) : undefined,\n },\n ];\n })\n );\n}\n\n/**\n * {@link fetchKaminoStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchKaminoStates}\n */\nexport async function fetchKaminoStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: KaminoBankInput[]\n): Promise<Record<string, KaminoStatesJSON>> {\n const states = await fetchKaminoStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, { reserveState, obligationState, farmState }]) => [\n bank,\n {\n reserveState: kaminoReserveToDto(reserveState),\n obligationState: kaminoObligationToDto(obligationState),\n farmState: farmState && kaminoFarmStateToDto(farmState),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum AssetTier {\n Collateral,\n Protected,\n Cross,\n Isolated,\n Unlisted,\n}\n\nexport type AssetTierArgs = AssetTier;\n\nexport function getAssetTierEncoder(): FixedSizeEncoder<AssetTierArgs> {\n return getEnumEncoder(AssetTier);\n}\n\nexport function getAssetTierDecoder(): FixedSizeDecoder<AssetTier> {\n return getEnumDecoder(AssetTier);\n}\n\nexport function getAssetTierCodec(): FixedSizeCodec<AssetTierArgs, AssetTier> {\n return combineCodec(getAssetTierEncoder(), getAssetTierDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type HistoricalIndexData = {\n /** precision: PRICE_PRECISION */\n lastIndexBidPrice: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexAskPrice: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap5min: bigint;\n /** unix_timestamp of last snapshot */\n lastIndexPriceTwapTs: bigint;\n};\n\nexport type HistoricalIndexDataArgs = {\n /** precision: PRICE_PRECISION */\n lastIndexBidPrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexAskPrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap5min: number | bigint;\n /** unix_timestamp of last snapshot */\n lastIndexPriceTwapTs: number | bigint;\n};\n\nexport function getHistoricalIndexDataEncoder(): FixedSizeEncoder<HistoricalIndexDataArgs> {\n return getStructEncoder([\n [\"lastIndexBidPrice\", getU64Encoder()],\n [\"lastIndexAskPrice\", getU64Encoder()],\n [\"lastIndexPriceTwap\", getU64Encoder()],\n [\"lastIndexPriceTwap5min\", getU64Encoder()],\n [\"lastIndexPriceTwapTs\", getI64Encoder()],\n ]);\n}\n\nexport function getHistoricalIndexDataDecoder(): FixedSizeDecoder<HistoricalIndexData> {\n return getStructDecoder([\n [\"lastIndexBidPrice\", getU64Decoder()],\n [\"lastIndexAskPrice\", getU64Decoder()],\n [\"lastIndexPriceTwap\", getU64Decoder()],\n [\"lastIndexPriceTwap5min\", getU64Decoder()],\n [\"lastIndexPriceTwapTs\", getI64Decoder()],\n ]);\n}\n\nexport function getHistoricalIndexDataCodec(): FixedSizeCodec<\n HistoricalIndexDataArgs,\n HistoricalIndexData\n> {\n return combineCodec(getHistoricalIndexDataEncoder(), getHistoricalIndexDataDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type HistoricalOracleData = {\n /** precision: PRICE_PRECISION */\n lastOraclePrice: bigint;\n /** precision: PRICE_PRECISION */\n lastOracleConf: bigint;\n /** number of slots since last update */\n lastOracleDelay: bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap: bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap5min: bigint;\n /** unix_timestamp of last snapshot */\n lastOraclePriceTwapTs: bigint;\n};\n\nexport type HistoricalOracleDataArgs = {\n /** precision: PRICE_PRECISION */\n lastOraclePrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOracleConf: number | bigint;\n /** number of slots since last update */\n lastOracleDelay: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap5min: number | bigint;\n /** unix_timestamp of last snapshot */\n lastOraclePriceTwapTs: number | bigint;\n};\n\nexport function getHistoricalOracleDataEncoder(): FixedSizeEncoder<HistoricalOracleDataArgs> {\n return getStructEncoder([\n [\"lastOraclePrice\", getI64Encoder()],\n [\"lastOracleConf\", getU64Encoder()],\n [\"lastOracleDelay\", getI64Encoder()],\n [\"lastOraclePriceTwap\", getI64Encoder()],\n [\"lastOraclePriceTwap5min\", getI64Encoder()],\n [\"lastOraclePriceTwapTs\", getI64Encoder()],\n ]);\n}\n\nexport function getHistoricalOracleDataDecoder(): FixedSizeDecoder<HistoricalOracleData> {\n return getStructDecoder([\n [\"lastOraclePrice\", getI64Decoder()],\n [\"lastOracleConf\", getU64Decoder()],\n [\"lastOracleDelay\", getI64Decoder()],\n [\"lastOraclePriceTwap\", getI64Decoder()],\n [\"lastOraclePriceTwap5min\", getI64Decoder()],\n [\"lastOraclePriceTwapTs\", getI64Decoder()],\n ]);\n}\n\nexport function getHistoricalOracleDataCodec(): FixedSizeCodec<\n HistoricalOracleDataArgs,\n HistoricalOracleData\n> {\n return combineCodec(getHistoricalOracleDataEncoder(), getHistoricalOracleDataDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU32Decoder,\n getU32Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type InsuranceFund = {\n vault: Address;\n totalShares: bigint;\n userShares: bigint;\n sharesBase: bigint;\n unstakingPeriod: bigint;\n lastRevenueSettleTs: bigint;\n revenueSettlePeriod: bigint;\n totalFactor: number;\n userFactor: number;\n};\n\nexport type InsuranceFundArgs = {\n vault: Address;\n totalShares: number | bigint;\n userShares: number | bigint;\n sharesBase: number | bigint;\n unstakingPeriod: number | bigint;\n lastRevenueSettleTs: number | bigint;\n revenueSettlePeriod: number | bigint;\n totalFactor: number;\n userFactor: number;\n};\n\nexport function getInsuranceFundEncoder(): FixedSizeEncoder<InsuranceFundArgs> {\n return getStructEncoder([\n [\"vault\", getAddressEncoder()],\n [\"totalShares\", getU128Encoder()],\n [\"userShares\", getU128Encoder()],\n [\"sharesBase\", getU128Encoder()],\n [\"unstakingPeriod\", getI64Encoder()],\n [\"lastRevenueSettleTs\", getI64Encoder()],\n [\"revenueSettlePeriod\", getI64Encoder()],\n [\"totalFactor\", getU32Encoder()],\n [\"userFactor\", getU32Encoder()],\n ]);\n}\n\nexport function getInsuranceFundDecoder(): FixedSizeDecoder<InsuranceFund> {\n return getStructDecoder([\n [\"vault\", getAddressDecoder()],\n [\"totalShares\", getU128Decoder()],\n [\"userShares\", getU128Decoder()],\n [\"sharesBase\", getU128Decoder()],\n [\"unstakingPeriod\", getI64Decoder()],\n [\"lastRevenueSettleTs\", getI64Decoder()],\n [\"revenueSettlePeriod\", getI64Decoder()],\n [\"totalFactor\", getU32Decoder()],\n [\"userFactor\", getU32Decoder()],\n ]);\n}\n\nexport function getInsuranceFundCodec(): FixedSizeCodec<InsuranceFundArgs, InsuranceFund> {\n return combineCodec(getInsuranceFundEncoder(), getInsuranceFundDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarginMode {\n Default,\n HighLeverage,\n HighLeverageMaintenance,\n}\n\nexport type MarginModeArgs = MarginMode;\n\nexport function getMarginModeEncoder(): FixedSizeEncoder<MarginModeArgs> {\n return getEnumEncoder(MarginMode);\n}\n\nexport function getMarginModeDecoder(): FixedSizeDecoder<MarginMode> {\n return getEnumDecoder(MarginMode);\n}\n\nexport function getMarginModeCodec(): FixedSizeCodec<MarginModeArgs, MarginMode> {\n return combineCodec(getMarginModeEncoder(), getMarginModeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarketStatus {\n Initialized,\n Active,\n FundingPaused,\n AmmPaused,\n FillPaused,\n WithdrawPaused,\n ReduceOnly,\n Settlement,\n Delisted,\n}\n\nexport type MarketStatusArgs = MarketStatus;\n\nexport function getMarketStatusEncoder(): FixedSizeEncoder<MarketStatusArgs> {\n return getEnumEncoder(MarketStatus);\n}\n\nexport function getMarketStatusDecoder(): FixedSizeDecoder<MarketStatus> {\n return getEnumDecoder(MarketStatus);\n}\n\nexport function getMarketStatusCodec(): FixedSizeCodec<MarketStatusArgs, MarketStatus> {\n return combineCodec(getMarketStatusEncoder(), getMarketStatusDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarketType {\n Spot,\n Perp,\n}\n\nexport type MarketTypeArgs = MarketType;\n\nexport function getMarketTypeEncoder(): FixedSizeEncoder<MarketTypeArgs> {\n return getEnumEncoder(MarketType);\n}\n\nexport function getMarketTypeDecoder(): FixedSizeDecoder<MarketType> {\n return getEnumDecoder(MarketType);\n}\n\nexport function getMarketTypeCodec(): FixedSizeCodec<MarketTypeArgs, MarketType> {\n return combineCodec(getMarketTypeEncoder(), getMarketTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OracleSource {\n Pyth,\n Switchboard,\n QuoteAsset,\n Pyth1K,\n Pyth1M,\n PythStableCoin,\n Prelaunch,\n PythPull,\n Pyth1KPull,\n Pyth1MPull,\n PythStableCoinPull,\n SwitchboardOnDemand,\n PythLazer,\n PythLazer1K,\n PythLazer1M,\n PythLazerStableCoin,\n}\n\nexport type OracleSourceArgs = OracleSource;\n\nexport function getOracleSourceEncoder(): FixedSizeEncoder<OracleSourceArgs> {\n return getEnumEncoder(OracleSource);\n}\n\nexport function getOracleSourceDecoder(): FixedSizeDecoder<OracleSource> {\n return getEnumDecoder(OracleSource);\n}\n\nexport function getOracleSourceCodec(): FixedSizeCodec<OracleSourceArgs, OracleSource> {\n return combineCodec(getOracleSourceEncoder(), getOracleSourceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI32Decoder,\n getI32Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getMarketTypeDecoder,\n getMarketTypeEncoder,\n getOrderStatusDecoder,\n getOrderStatusEncoder,\n getOrderTriggerConditionDecoder,\n getOrderTriggerConditionEncoder,\n getOrderTypeDecoder,\n getOrderTypeEncoder,\n getPositionDirectionDecoder,\n getPositionDirectionEncoder,\n type MarketType,\n type MarketTypeArgs,\n type OrderStatus,\n type OrderStatusArgs,\n type OrderTriggerCondition,\n type OrderTriggerConditionArgs,\n type OrderType,\n type OrderTypeArgs,\n type PositionDirection,\n type PositionDirectionArgs,\n} from \".\";\n\nexport type Order = {\n /** The slot the order was placed */\n slot: bigint;\n /**\n * The limit price for the order (can be 0 for market orders)\n * For orders with an auction, this price isn't used until the auction is complete\n * precision: PRICE_PRECISION\n */\n price: bigint;\n /**\n * The size of the order\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmount: bigint;\n /**\n * The amount of the order filled\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmountFilled: bigint;\n /**\n * The amount of quote filled for the order\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmountFilled: bigint;\n /**\n * At what price the order will be triggered. Only relevant for trigger orders\n * precision: PRICE_PRECISION\n */\n triggerPrice: bigint;\n /**\n * The start price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionStartPrice: bigint;\n /**\n * The end price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionEndPrice: bigint;\n /** The time when the order will expire */\n maxTs: bigint;\n /**\n * If set, the order limit price is the oracle price + this offset\n * precision: PRICE_PRECISION\n */\n oraclePriceOffset: number;\n /** The id for the order. Each users has their own order id space */\n orderId: number;\n /** The perp/spot market index */\n marketIndex: number;\n /** Whether the order is open or unused */\n status: OrderStatus;\n /** The type of order */\n orderType: OrderType;\n /** Whether market is spot or perp */\n marketType: MarketType;\n /** User generated order id. Can make it easier to place/cancel orders */\n userOrderId: number;\n /** What the users position was when the order was placed */\n existingPositionDirection: PositionDirection;\n /** Whether the user is going long or short. LONG = bid, SHORT = ask */\n direction: PositionDirection;\n /** Whether the order is allowed to only reduce position size */\n reduceOnly: boolean;\n /** Whether the order must be a maker */\n postOnly: boolean;\n /** Whether the order must be canceled the same slot it is placed */\n immediateOrCancel: boolean;\n /** Whether the order is triggered above or below the trigger price. Only relevant for trigger orders */\n triggerCondition: OrderTriggerCondition;\n /** How many slots the auction lasts */\n auctionDuration: number;\n /** Last 8 bits of the slot the order was posted on-chain (not order slot for signed msg orders) */\n postedSlotTail: number;\n /**\n * Bitflags for further classification\n * 0: is_signed_message\n */\n bitFlags: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type OrderArgs = {\n /** The slot the order was placed */\n slot: number | bigint;\n /**\n * The limit price for the order (can be 0 for market orders)\n * For orders with an auction, this price isn't used until the auction is complete\n * precision: PRICE_PRECISION\n */\n price: number | bigint;\n /**\n * The size of the order\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmount: number | bigint;\n /**\n * The amount of the order filled\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmountFilled: number | bigint;\n /**\n * The amount of quote filled for the order\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmountFilled: number | bigint;\n /**\n * At what price the order will be triggered. Only relevant for trigger orders\n * precision: PRICE_PRECISION\n */\n triggerPrice: number | bigint;\n /**\n * The start price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionStartPrice: number | bigint;\n /**\n * The end price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionEndPrice: number | bigint;\n /** The time when the order will expire */\n maxTs: number | bigint;\n /**\n * If set, the order limit price is the oracle price + this offset\n * precision: PRICE_PRECISION\n */\n oraclePriceOffset: number;\n /** The id for the order. Each users has their own order id space */\n orderId: number;\n /** The perp/spot market index */\n marketIndex: number;\n /** Whether the order is open or unused */\n status: OrderStatusArgs;\n /** The type of order */\n orderType: OrderTypeArgs;\n /** Whether market is spot or perp */\n marketType: MarketTypeArgs;\n /** User generated order id. Can make it easier to place/cancel orders */\n userOrderId: number;\n /** What the users position was when the order was placed */\n existingPositionDirection: PositionDirectionArgs;\n /** Whether the user is going long or short. LONG = bid, SHORT = ask */\n direction: PositionDirectionArgs;\n /** Whether the order is allowed to only reduce position size */\n reduceOnly: boolean;\n /** Whether the order must be a maker */\n postOnly: boolean;\n /** Whether the order must be canceled the same slot it is placed */\n immediateOrCancel: boolean;\n /** Whether the order is triggered above or below the trigger price. Only relevant for trigger orders */\n triggerCondition: OrderTriggerConditionArgs;\n /** How many slots the auction lasts */\n auctionDuration: number;\n /** Last 8 bits of the slot the order was posted on-chain (not order slot for signed msg orders) */\n postedSlotTail: number;\n /**\n * Bitflags for further classification\n * 0: is_signed_message\n */\n bitFlags: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getOrderEncoder(): FixedSizeEncoder<OrderArgs> {\n return getStructEncoder([\n [\"slot\", getU64Encoder()],\n [\"price\", getU64Encoder()],\n [\"baseAssetAmount\", getU64Encoder()],\n [\"baseAssetAmountFilled\", getU64Encoder()],\n [\"quoteAssetAmountFilled\", getU64Encoder()],\n [\"triggerPrice\", getU64Encoder()],\n [\"auctionStartPrice\", getI64Encoder()],\n [\"auctionEndPrice\", getI64Encoder()],\n [\"maxTs\", getI64Encoder()],\n [\"oraclePriceOffset\", getI32Encoder()],\n [\"orderId\", getU32Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"status\", getOrderStatusEncoder()],\n [\"orderType\", getOrderTypeEncoder()],\n [\"marketType\", getMarketTypeEncoder()],\n [\"userOrderId\", getU8Encoder()],\n [\"existingPositionDirection\", getPositionDirectionEncoder()],\n [\"direction\", getPositionDirectionEncoder()],\n [\"reduceOnly\", getBooleanEncoder()],\n [\"postOnly\", getBooleanEncoder()],\n [\"immediateOrCancel\", getBooleanEncoder()],\n [\"triggerCondition\", getOrderTriggerConditionEncoder()],\n [\"auctionDuration\", getU8Encoder()],\n [\"postedSlotTail\", getU8Encoder()],\n [\"bitFlags\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 1)],\n ]);\n}\n\nexport function getOrderDecoder(): FixedSizeDecoder<Order> {\n return getStructDecoder([\n [\"slot\", getU64Decoder()],\n [\"price\", getU64Decoder()],\n [\"baseAssetAmount\", getU64Decoder()],\n [\"baseAssetAmountFilled\", getU64Decoder()],\n [\"quoteAssetAmountFilled\", getU64Decoder()],\n [\"triggerPrice\", getU64Decoder()],\n [\"auctionStartPrice\", getI64Decoder()],\n [\"auctionEndPrice\", getI64Decoder()],\n [\"maxTs\", getI64Decoder()],\n [\"oraclePriceOffset\", getI32Decoder()],\n [\"orderId\", getU32Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"status\", getOrderStatusDecoder()],\n [\"orderType\", getOrderTypeDecoder()],\n [\"marketType\", getMarketTypeDecoder()],\n [\"userOrderId\", getU8Decoder()],\n [\"existingPositionDirection\", getPositionDirectionDecoder()],\n [\"direction\", getPositionDirectionDecoder()],\n [\"reduceOnly\", getBooleanDecoder()],\n [\"postOnly\", getBooleanDecoder()],\n [\"immediateOrCancel\", getBooleanDecoder()],\n [\"triggerCondition\", getOrderTriggerConditionDecoder()],\n [\"auctionDuration\", getU8Decoder()],\n [\"postedSlotTail\", getU8Decoder()],\n [\"bitFlags\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 1)],\n ]);\n}\n\nexport function getOrderCodec(): FixedSizeCodec<OrderArgs, Order> {\n return combineCodec(getOrderEncoder(), getOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderStatus {\n Init,\n Open,\n Filled,\n Canceled,\n}\n\nexport type OrderStatusArgs = OrderStatus;\n\nexport function getOrderStatusEncoder(): FixedSizeEncoder<OrderStatusArgs> {\n return getEnumEncoder(OrderStatus);\n}\n\nexport function getOrderStatusDecoder(): FixedSizeDecoder<OrderStatus> {\n return getEnumDecoder(OrderStatus);\n}\n\nexport function getOrderStatusCodec(): FixedSizeCodec<OrderStatusArgs, OrderStatus> {\n return combineCodec(getOrderStatusEncoder(), getOrderStatusDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderTriggerCondition {\n Above,\n Below,\n TriggeredAbove,\n TriggeredBelow,\n}\n\nexport type OrderTriggerConditionArgs = OrderTriggerCondition;\n\nexport function getOrderTriggerConditionEncoder(): FixedSizeEncoder<OrderTriggerConditionArgs> {\n return getEnumEncoder(OrderTriggerCondition);\n}\n\nexport function getOrderTriggerConditionDecoder(): FixedSizeDecoder<OrderTriggerCondition> {\n return getEnumDecoder(OrderTriggerCondition);\n}\n\nexport function getOrderTriggerConditionCodec(): FixedSizeCodec<\n OrderTriggerConditionArgs,\n OrderTriggerCondition\n> {\n return combineCodec(getOrderTriggerConditionEncoder(), getOrderTriggerConditionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderType {\n Market,\n Limit,\n TriggerMarket,\n TriggerLimit,\n Oracle,\n}\n\nexport type OrderTypeArgs = OrderType;\n\nexport function getOrderTypeEncoder(): FixedSizeEncoder<OrderTypeArgs> {\n return getEnumEncoder(OrderType);\n}\n\nexport function getOrderTypeDecoder(): FixedSizeDecoder<OrderType> {\n return getEnumDecoder(OrderType);\n}\n\nexport function getOrderTypeCodec(): FixedSizeCodec<OrderTypeArgs, OrderType> {\n return combineCodec(getOrderTypeEncoder(), getOrderTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type PerpPosition = {\n /**\n * The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user\n * precision: FUNDING_RATE_PRECISION\n */\n lastCumulativeFundingRate: bigint;\n /**\n * the size of the users perp position\n * precision: BASE_PRECISION\n */\n baseAssetAmount: bigint;\n /**\n * Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmount: bigint;\n /**\n * The amount of quote the user would need to exit their position at to break even\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteBreakEvenAmount: bigint;\n /**\n * The amount quote the user entered the position with. Equal to base asset amount * avg entry price\n * Updated when the user open/closes position. Excludes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteEntryAmount: bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openBids: bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openAsks: bigint;\n /**\n * The amount of pnl settled in this market since opening the position\n * precision: QUOTE_PRECISION\n */\n settledPnl: bigint;\n /**\n * The number of lp (liquidity provider) shares the user has in this perp market\n * LP shares allow users to provide liquidity via the AMM\n * precision: BASE_PRECISION\n */\n lpShares: bigint;\n /**\n * The scaled balance of the isolated position\n * precision: SPOT_BALANCE_PRECISION\n */\n isolatedPositionScaledBalance: bigint;\n /**\n * The last quote asset amount per lp the amm had\n * Used to settle the users lp position\n * precision: QUOTE_PRECISION\n */\n lastQuoteAssetAmountPerLp: bigint;\n padding: ReadonlyUint8Array;\n maxMarginRatio: number;\n /** The market index for the perp market */\n marketIndex: number;\n /** The number of open orders */\n openOrders: number;\n positionFlag: number;\n};\n\nexport type PerpPositionArgs = {\n /**\n * The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user\n * precision: FUNDING_RATE_PRECISION\n */\n lastCumulativeFundingRate: number | bigint;\n /**\n * the size of the users perp position\n * precision: BASE_PRECISION\n */\n baseAssetAmount: number | bigint;\n /**\n * Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmount: number | bigint;\n /**\n * The amount of quote the user would need to exit their position at to break even\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteBreakEvenAmount: number | bigint;\n /**\n * The amount quote the user entered the position with. Equal to base asset amount * avg entry price\n * Updated when the user open/closes position. Excludes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteEntryAmount: number | bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openBids: number | bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openAsks: number | bigint;\n /**\n * The amount of pnl settled in this market since opening the position\n * precision: QUOTE_PRECISION\n */\n settledPnl: number | bigint;\n /**\n * The number of lp (liquidity provider) shares the user has in this perp market\n * LP shares allow users to provide liquidity via the AMM\n * precision: BASE_PRECISION\n */\n lpShares: number | bigint;\n /**\n * The scaled balance of the isolated position\n * precision: SPOT_BALANCE_PRECISION\n */\n isolatedPositionScaledBalance: number | bigint;\n /**\n * The last quote asset amount per lp the amm had\n * Used to settle the users lp position\n * precision: QUOTE_PRECISION\n */\n lastQuoteAssetAmountPerLp: number | bigint;\n padding: ReadonlyUint8Array;\n maxMarginRatio: number;\n /** The market index for the perp market */\n marketIndex: number;\n /** The number of open orders */\n openOrders: number;\n positionFlag: number;\n};\n\nexport function getPerpPositionEncoder(): FixedSizeEncoder<PerpPositionArgs> {\n return getStructEncoder([\n [\"lastCumulativeFundingRate\", getI64Encoder()],\n [\"baseAssetAmount\", getI64Encoder()],\n [\"quoteAssetAmount\", getI64Encoder()],\n [\"quoteBreakEvenAmount\", getI64Encoder()],\n [\"quoteEntryAmount\", getI64Encoder()],\n [\"openBids\", getI64Encoder()],\n [\"openAsks\", getI64Encoder()],\n [\"settledPnl\", getI64Encoder()],\n [\"lpShares\", getU64Encoder()],\n [\"isolatedPositionScaledBalance\", getU64Encoder()],\n [\"lastQuoteAssetAmountPerLp\", getI64Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"maxMarginRatio\", getU16Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"openOrders\", getU8Encoder()],\n [\"positionFlag\", getU8Encoder()],\n ]);\n}\n\nexport function getPerpPositionDecoder(): FixedSizeDecoder<PerpPosition> {\n return getStructDecoder([\n [\"lastCumulativeFundingRate\", getI64Decoder()],\n [\"baseAssetAmount\", getI64Decoder()],\n [\"quoteAssetAmount\", getI64Decoder()],\n [\"quoteBreakEvenAmount\", getI64Decoder()],\n [\"quoteEntryAmount\", getI64Decoder()],\n [\"openBids\", getI64Decoder()],\n [\"openAsks\", getI64Decoder()],\n [\"settledPnl\", getI64Decoder()],\n [\"lpShares\", getU64Decoder()],\n [\"isolatedPositionScaledBalance\", getU64Decoder()],\n [\"lastQuoteAssetAmountPerLp\", getI64Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"maxMarginRatio\", getU16Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"openOrders\", getU8Decoder()],\n [\"positionFlag\", getU8Decoder()],\n ]);\n}\n\nexport function getPerpPositionCodec(): FixedSizeCodec<PerpPositionArgs, PerpPosition> {\n return combineCodec(getPerpPositionEncoder(), getPerpPositionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type PoolBalance = {\n /**\n * To get the pool's token amount, you must multiply the scaled balance by the market's cumulative\n * deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: bigint;\n /** The spot market the pool is for */\n marketIndex: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type PoolBalanceArgs = {\n /**\n * To get the pool's token amount, you must multiply the scaled balance by the market's cumulative\n * deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: number | bigint;\n /** The spot market the pool is for */\n marketIndex: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getPoolBalanceEncoder(): FixedSizeEncoder<PoolBalanceArgs> {\n return getStructEncoder([\n [\"scaledBalance\", getU128Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 6)],\n ]);\n}\n\nexport function getPoolBalanceDecoder(): FixedSizeDecoder<PoolBalance> {\n return getStructDecoder([\n [\"scaledBalance\", getU128Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 6)],\n ]);\n}\n\nexport function getPoolBalanceCodec(): FixedSizeCodec<PoolBalanceArgs, PoolBalance> {\n return combineCodec(getPoolBalanceEncoder(), getPoolBalanceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum PositionDirection {\n Long,\n Short,\n}\n\nexport type PositionDirectionArgs = PositionDirection;\n\nexport function getPositionDirectionEncoder(): FixedSizeEncoder<PositionDirectionArgs> {\n return getEnumEncoder(PositionDirection);\n}\n\nexport function getPositionDirectionDecoder(): FixedSizeDecoder<PositionDirection> {\n return getEnumDecoder(PositionDirection);\n}\n\nexport function getPositionDirectionCodec(): FixedSizeCodec<\n PositionDirectionArgs,\n PositionDirection\n> {\n return combineCodec(getPositionDirectionEncoder(), getPositionDirectionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum SpotBalanceType {\n Deposit,\n Borrow,\n}\n\nexport type SpotBalanceTypeArgs = SpotBalanceType;\n\nexport function getSpotBalanceTypeEncoder(): FixedSizeEncoder<SpotBalanceTypeArgs> {\n return getEnumEncoder(SpotBalanceType);\n}\n\nexport function getSpotBalanceTypeDecoder(): FixedSizeDecoder<SpotBalanceType> {\n return getEnumDecoder(SpotBalanceType);\n}\n\nexport function getSpotBalanceTypeCodec(): FixedSizeCodec<SpotBalanceTypeArgs, SpotBalanceType> {\n return combineCodec(getSpotBalanceTypeEncoder(), getSpotBalanceTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getSpotBalanceTypeDecoder,\n getSpotBalanceTypeEncoder,\n type SpotBalanceType,\n type SpotBalanceTypeArgs,\n} from \".\";\n\nexport type SpotPosition = {\n /**\n * The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow\n * interest of corresponding market.\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openBids: bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openAsks: bigint;\n /**\n * The cumulative deposits/borrows a user has made into a market\n * precision: token mint precision\n */\n cumulativeDeposits: bigint;\n /** The market index of the corresponding spot market */\n marketIndex: number;\n /** Whether the position is deposit or borrow */\n balanceType: SpotBalanceType;\n /** Number of open orders */\n openOrders: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type SpotPositionArgs = {\n /**\n * The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow\n * interest of corresponding market.\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: number | bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openBids: number | bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openAsks: number | bigint;\n /**\n * The cumulative deposits/borrows a user has made into a market\n * precision: token mint precision\n */\n cumulativeDeposits: number | bigint;\n /** The market index of the corresponding spot market */\n marketIndex: number;\n /** Whether the position is deposit or borrow */\n balanceType: SpotBalanceTypeArgs;\n /** Number of open orders */\n openOrders: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getSpotPositionEncoder(): FixedSizeEncoder<SpotPositionArgs> {\n return getStructEncoder([\n [\"scaledBalance\", getU64Encoder()],\n [\"openBids\", getI64Encoder()],\n [\"openAsks\", getI64Encoder()],\n [\"cumulativeDeposits\", getI64Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"balanceType\", getSpotBalanceTypeEncoder()],\n [\"openOrders\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 4)],\n ]);\n}\n\nexport function getSpotPositionDecoder(): FixedSizeDecoder<SpotPosition> {\n return getStructDecoder([\n [\"scaledBalance\", getU64Decoder()],\n [\"openBids\", getI64Decoder()],\n [\"openAsks\", getI64Decoder()],\n [\"cumulativeDeposits\", getI64Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"balanceType\", getSpotBalanceTypeDecoder()],\n [\"openOrders\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 4)],\n ]);\n}\n\nexport function getSpotPositionCodec(): FixedSizeCodec<SpotPositionArgs, SpotPosition> {\n return combineCodec(getSpotPositionEncoder(), getSpotPositionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type UserFees = {\n /**\n * Total taker fee paid\n * precision: QUOTE_PRECISION\n */\n totalFeePaid: bigint;\n /**\n * Total maker fee rebate\n * precision: QUOTE_PRECISION\n */\n totalFeeRebate: bigint;\n /**\n * Total discount from holding token\n * precision: QUOTE_PRECISION\n */\n totalTokenDiscount: bigint;\n /**\n * Total discount from being referred\n * precision: QUOTE_PRECISION\n */\n totalRefereeDiscount: bigint;\n /**\n * Total reward to referrer\n * precision: QUOTE_PRECISION\n */\n totalReferrerReward: bigint;\n /**\n * Total reward to referrer this epoch\n * precision: QUOTE_PRECISION\n */\n currentEpochReferrerReward: bigint;\n};\n\nexport type UserFeesArgs = {\n /**\n * Total taker fee paid\n * precision: QUOTE_PRECISION\n */\n totalFeePaid: number | bigint;\n /**\n * Total maker fee rebate\n * precision: QUOTE_PRECISION\n */\n totalFeeRebate: number | bigint;\n /**\n * Total discount from holding token\n * precision: QUOTE_PRECISION\n */\n totalTokenDiscount: number | bigint;\n /**\n * Total discount from being referred\n * precision: QUOTE_PRECISION\n */\n totalRefereeDiscount: number | bigint;\n /**\n * Total reward to referrer\n * precision: QUOTE_PRECISION\n */\n totalReferrerReward: number | bigint;\n /**\n * Total reward to referrer this epoch\n * precision: QUOTE_PRECISION\n */\n currentEpochReferrerReward: number | bigint;\n};\n\nexport function getUserFeesEncoder(): FixedSizeEncoder<UserFeesArgs> {\n return getStructEncoder([\n [\"totalFeePaid\", getU64Encoder()],\n [\"totalFeeRebate\", getU64Encoder()],\n [\"totalTokenDiscount\", getU64Encoder()],\n [\"totalRefereeDiscount\", getU64Encoder()],\n [\"totalReferrerReward\", getU64Encoder()],\n [\"currentEpochReferrerReward\", getU64Encoder()],\n ]);\n}\n\nexport function getUserFeesDecoder(): FixedSizeDecoder<UserFees> {\n return getStructDecoder([\n [\"totalFeePaid\", getU64Decoder()],\n [\"totalFeeRebate\", getU64Decoder()],\n [\"totalTokenDiscount\", getU64Decoder()],\n [\"totalRefereeDiscount\", getU64Decoder()],\n [\"totalReferrerReward\", getU64Decoder()],\n [\"currentEpochReferrerReward\", getU64Decoder()],\n ]);\n}\n\nexport function getUserFeesCodec(): FixedSizeCodec<UserFeesArgs, UserFees> {\n return combineCodec(getUserFeesEncoder(), getUserFeesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI16Decoder,\n getI16Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getAssetTierDecoder,\n getAssetTierEncoder,\n getHistoricalIndexDataDecoder,\n getHistoricalIndexDataEncoder,\n getHistoricalOracleDataDecoder,\n getHistoricalOracleDataEncoder,\n getInsuranceFundDecoder,\n getInsuranceFundEncoder,\n getMarketStatusDecoder,\n getMarketStatusEncoder,\n getOracleSourceDecoder,\n getOracleSourceEncoder,\n getPoolBalanceDecoder,\n getPoolBalanceEncoder,\n type AssetTier,\n type AssetTierArgs,\n type HistoricalIndexData,\n type HistoricalIndexDataArgs,\n type HistoricalOracleData,\n type HistoricalOracleDataArgs,\n type InsuranceFund,\n type InsuranceFundArgs,\n type MarketStatus,\n type MarketStatusArgs,\n type OracleSource,\n type OracleSourceArgs,\n type PoolBalance,\n type PoolBalanceArgs,\n} from \"../types\";\n\nexport const SPOT_MARKET_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 100, 177, 8, 107, 168, 65, 65, 39,\n]);\n\nexport function getSpotMarketDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(SPOT_MARKET_DISCRIMINATOR);\n}\n\nexport type SpotMarket = {\n discriminator: ReadonlyUint8Array;\n /** The address of the spot market. It is a pda of the market index */\n pubkey: Address;\n /** The oracle used to price the markets deposits/borrows */\n oracle: Address;\n /** The token mint of the market */\n mint: Address;\n /**\n * The vault used to store the market's deposits\n * The amount in the vault should be equal to or greater than deposits - borrows\n */\n vault: Address;\n /** The encoded display name for the market e.g. SOL */\n name: ReadonlyUint8Array;\n historicalOracleData: HistoricalOracleData;\n historicalIndexData: HistoricalIndexData;\n /**\n * Revenue the protocol has collected in this markets token\n * e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool\n */\n revenuePool: PoolBalance;\n /**\n * The fees collected from swaps between this market and the quote market\n * Is settled to the quote markets revenue pool\n */\n spotFeePool: PoolBalance;\n /**\n * Details on the insurance fund covering bankruptcies in this markets token\n * Covers bankruptcies for borrows with this markets token and perps settling in this markets token\n */\n insuranceFund: InsuranceFund;\n /**\n * The total spot fees collected for this market\n * precision: QUOTE_PRECISION\n */\n totalSpotFee: bigint;\n /**\n * The sum of the scaled balances for deposits across users and pool balances\n * To convert to the deposit token amount, multiply by the cumulative deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n depositBalance: bigint;\n /**\n * The sum of the scaled balances for borrows across users and pool balances\n * To convert to the borrow token amount, multiply by the cumulative borrow interest\n * precision: SPOT_BALANCE_PRECISION\n */\n borrowBalance: bigint;\n /**\n * The cumulative interest earned by depositors\n * Used to calculate the deposit token amount from the deposit balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeDepositInterest: bigint;\n /**\n * The cumulative interest earned by borrowers\n * Used to calculate the borrow token amount from the borrow balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeBorrowInterest: bigint;\n /**\n * The total socialized loss from borrows, in the mint's token\n * precision: token mint precision\n */\n totalSocialLoss: bigint;\n /**\n * The total socialized loss from borrows, in the quote market's token\n * preicision: QUOTE_PRECISION\n */\n totalQuoteSocialLoss: bigint;\n /**\n * no withdraw limits/guards when deposits below this threshold\n * precision: token mint precision\n */\n withdrawGuardThreshold: bigint;\n /**\n * The max amount of token deposits in this market\n * 0 if there is no limit\n * precision: token mint precision\n */\n maxTokenDeposits: bigint;\n /**\n * 24hr average of deposit token amount\n * precision: token mint precision\n */\n depositTokenTwap: bigint;\n /**\n * 24hr average of borrow token amount\n * precision: token mint precision\n */\n borrowTokenTwap: bigint;\n /**\n * 24hr average of utilization\n * which is borrow amount over token amount\n * precision: SPOT_UTILIZATION_PRECISION\n */\n utilizationTwap: bigint;\n /** Last time the cumulative deposit and borrow interest was updated */\n lastInterestTs: bigint;\n /** Last time the deposit/borrow/utilization averages were updated */\n lastTwapTs: bigint;\n /** The time the market is set to expire. Only set if market is in reduce only mode */\n expiryTs: bigint;\n /**\n * Spot orders must be a multiple of the step size\n * precision: token mint precision\n */\n orderStepSize: bigint;\n /**\n * Spot orders must be a multiple of the tick size\n * precision: PRICE_PRECISION\n */\n orderTickSize: bigint;\n /**\n * The minimum order size\n * precision: token mint precision\n */\n minOrderSize: bigint;\n /**\n * The maximum spot position size\n * if the limit is 0, there is no limit\n * precision: token mint precision\n */\n maxPositionSize: bigint;\n /** Every spot trade has a fill record id. This is the next id to use */\n nextFillRecordId: bigint;\n /** Every deposit has a deposit record id. This is the next id to use */\n nextDepositRecordId: bigint;\n /**\n * The initial asset weight used to calculate a deposits contribution to a users initial total collateral\n * e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialAssetWeight: number;\n /**\n * The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral\n * e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceAssetWeight: number;\n /**\n * The initial liability weight used to calculate a borrows contribution to a users initial margin requirement\n * e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialLiabilityWeight: number;\n /**\n * The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement\n * e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceLiabilityWeight: number;\n /**\n * The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions\n * precision: MARGIN_PRECISION\n */\n imfFactor: number;\n /**\n * The fee the liquidator is paid for taking over borrow/deposit\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n liquidatorFee: number;\n /**\n * The fee the insurance fund receives from liquidation\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n ifLiquidationFee: number;\n /**\n * The optimal utilization rate for this market.\n * Used to determine the markets borrow rate\n * precision: SPOT_UTILIZATION_PRECISION\n */\n optimalUtilization: number;\n /**\n * The borrow rate for this market when the market has optimal utilization\n * precision: SPOT_RATE_PRECISION\n */\n optimalBorrowRate: number;\n /**\n * The borrow rate for this market when the market has 1000 utilization\n * precision: SPOT_RATE_PRECISION\n */\n maxBorrowRate: number;\n /** The market's token mint's decimals. To from decimals to a precision, 10^decimals */\n decimals: number;\n marketIndex: number;\n /** Whether or not spot trading is enabled */\n ordersEnabled: boolean;\n oracleSource: OracleSource;\n status: MarketStatus;\n /** The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated */\n assetTier: AssetTier;\n pausedOperations: number;\n ifPausedOperations: number;\n feeAdjustment: number;\n /**\n * What fraction of max_token_deposits\n * disabled when 0, 1 => 1/10000 => .01% of max_token_deposits\n * precision: X/10000\n */\n maxTokenBorrowsFraction: number;\n /**\n * For swaps, the amount of token loaned out in the begin_swap ix\n * precision: token mint precision\n */\n flashLoanAmount: bigint;\n /**\n * For swaps, the amount in the users token account in the begin_swap ix\n * Used to calculate how much of the token left the system in end_swap ix\n * precision: token mint precision\n */\n flashLoanInitialTokenAmount: bigint;\n /**\n * The total fees received from swaps\n * precision: token mint precision\n */\n totalSwapFee: bigint;\n /**\n * When to begin scaling down the initial asset weight\n * disabled when 0\n * precision: QUOTE_PRECISION\n */\n scaleInitialAssetWeightStart: bigint;\n /**\n * The min borrow rate for this market when the market regardless of utilization\n * 1 => 1/200 => .5%\n * precision: X/200\n */\n minBorrowRate: number;\n /**\n * fuel multiplier for spot deposits\n * precision: 10\n */\n fuelBoostDeposits: number;\n /**\n * fuel multiplier for spot borrows\n * precision: 10\n */\n fuelBoostBorrows: number;\n /**\n * fuel multiplier for spot taker\n * precision: 10\n */\n fuelBoostTaker: number;\n /**\n * fuel multiplier for spot maker\n * precision: 10\n */\n fuelBoostMaker: number;\n /**\n * fuel multiplier for spot insurance stake\n * precision: 10\n */\n fuelBoostInsurance: number;\n tokenProgramFlag: number;\n poolId: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type SpotMarketArgs = {\n /** The address of the spot market. It is a pda of the market index */\n pubkey: Address;\n /** The oracle used to price the markets deposits/borrows */\n oracle: Address;\n /** The token mint of the market */\n mint: Address;\n /**\n * The vault used to store the market's deposits\n * The amount in the vault should be equal to or greater than deposits - borrows\n */\n vault: Address;\n /** The encoded display name for the market e.g. SOL */\n name: ReadonlyUint8Array;\n historicalOracleData: HistoricalOracleDataArgs;\n historicalIndexData: HistoricalIndexDataArgs;\n /**\n * Revenue the protocol has collected in this markets token\n * e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool\n */\n revenuePool: PoolBalanceArgs;\n /**\n * The fees collected from swaps between this market and the quote market\n * Is settled to the quote markets revenue pool\n */\n spotFeePool: PoolBalanceArgs;\n /**\n * Details on the insurance fund covering bankruptcies in this markets token\n * Covers bankruptcies for borrows with this markets token and perps settling in this markets token\n */\n insuranceFund: InsuranceFundArgs;\n /**\n * The total spot fees collected for this market\n * precision: QUOTE_PRECISION\n */\n totalSpotFee: number | bigint;\n /**\n * The sum of the scaled balances for deposits across users and pool balances\n * To convert to the deposit token amount, multiply by the cumulative deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n depositBalance: number | bigint;\n /**\n * The sum of the scaled balances for borrows across users and pool balances\n * To convert to the borrow token amount, multiply by the cumulative borrow interest\n * precision: SPOT_BALANCE_PRECISION\n */\n borrowBalance: number | bigint;\n /**\n * The cumulative interest earned by depositors\n * Used to calculate the deposit token amount from the deposit balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeDepositInterest: number | bigint;\n /**\n * The cumulative interest earned by borrowers\n * Used to calculate the borrow token amount from the borrow balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeBorrowInterest: number | bigint;\n /**\n * The total socialized loss from borrows, in the mint's token\n * precision: token mint precision\n */\n totalSocialLoss: number | bigint;\n /**\n * The total socialized loss from borrows, in the quote market's token\n * preicision: QUOTE_PRECISION\n */\n totalQuoteSocialLoss: number | bigint;\n /**\n * no withdraw limits/guards when deposits below this threshold\n * precision: token mint precision\n */\n withdrawGuardThreshold: number | bigint;\n /**\n * The max amount of token deposits in this market\n * 0 if there is no limit\n * precision: token mint precision\n */\n maxTokenDeposits: number | bigint;\n /**\n * 24hr average of deposit token amount\n * precision: token mint precision\n */\n depositTokenTwap: number | bigint;\n /**\n * 24hr average of borrow token amount\n * precision: token mint precision\n */\n borrowTokenTwap: number | bigint;\n /**\n * 24hr average of utilization\n * which is borrow amount over token amount\n * precision: SPOT_UTILIZATION_PRECISION\n */\n utilizationTwap: number | bigint;\n /** Last time the cumulative deposit and borrow interest was updated */\n lastInterestTs: number | bigint;\n /** Last time the deposit/borrow/utilization averages were updated */\n lastTwapTs: number | bigint;\n /** The time the market is set to expire. Only set if market is in reduce only mode */\n expiryTs: number | bigint;\n /**\n * Spot orders must be a multiple of the step size\n * precision: token mint precision\n */\n orderStepSize: number | bigint;\n /**\n * Spot orders must be a multiple of the tick size\n * precision: PRICE_PRECISION\n */\n orderTickSize: number | bigint;\n /**\n * The minimum order size\n * precision: token mint precision\n */\n minOrderSize: number | bigint;\n /**\n * The maximum spot position size\n * if the limit is 0, there is no limit\n * precision: token mint precision\n */\n maxPositionSize: number | bigint;\n /** Every spot trade has a fill record id. This is the next id to use */\n nextFillRecordId: number | bigint;\n /** Every deposit has a deposit record id. This is the next id to use */\n nextDepositRecordId: number | bigint;\n /**\n * The initial asset weight used to calculate a deposits contribution to a users initial total collateral\n * e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialAssetWeight: number;\n /**\n * The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral\n * e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceAssetWeight: number;\n /**\n * The initial liability weight used to calculate a borrows contribution to a users initial margin requirement\n * e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialLiabilityWeight: number;\n /**\n * The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement\n * e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceLiabilityWeight: number;\n /**\n * The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions\n * precision: MARGIN_PRECISION\n */\n imfFactor: number;\n /**\n * The fee the liquidator is paid for taking over borrow/deposit\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n liquidatorFee: number;\n /**\n * The fee the insurance fund receives from liquidation\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n ifLiquidationFee: number;\n /**\n * The optimal utilization rate for this market.\n * Used to determine the markets borrow rate\n * precision: SPOT_UTILIZATION_PRECISION\n */\n optimalUtilization: number;\n /**\n * The borrow rate for this market when the market has optimal utilization\n * precision: SPOT_RATE_PRECISION\n */\n optimalBorrowRate: number;\n /**\n * The borrow rate for this market when the market has 1000 utilization\n * precision: SPOT_RATE_PRECISION\n */\n maxBorrowRate: number;\n /** The market's token mint's decimals. To from decimals to a precision, 10^decimals */\n decimals: number;\n marketIndex: number;\n /** Whether or not spot trading is enabled */\n ordersEnabled: boolean;\n oracleSource: OracleSourceArgs;\n status: MarketStatusArgs;\n /** The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated */\n assetTier: AssetTierArgs;\n pausedOperations: number;\n ifPausedOperations: number;\n feeAdjustment: number;\n /**\n * What fraction of max_token_deposits\n * disabled when 0, 1 => 1/10000 => .01% of max_token_deposits\n * precision: X/10000\n */\n maxTokenBorrowsFraction: number;\n /**\n * For swaps, the amount of token loaned out in the begin_swap ix\n * precision: token mint precision\n */\n flashLoanAmount: number | bigint;\n /**\n * For swaps, the amount in the users token account in the begin_swap ix\n * Used to calculate how much of the token left the system in end_swap ix\n * precision: token mint precision\n */\n flashLoanInitialTokenAmount: number | bigint;\n /**\n * The total fees received from swaps\n * precision: token mint precision\n */\n totalSwapFee: number | bigint;\n /**\n * When to begin scaling down the initial asset weight\n * disabled when 0\n * precision: QUOTE_PRECISION\n */\n scaleInitialAssetWeightStart: number | bigint;\n /**\n * The min borrow rate for this market when the market regardless of utilization\n * 1 => 1/200 => .5%\n * precision: X/200\n */\n minBorrowRate: number;\n /**\n * fuel multiplier for spot deposits\n * precision: 10\n */\n fuelBoostDeposits: number;\n /**\n * fuel multiplier for spot borrows\n * precision: 10\n */\n fuelBoostBorrows: number;\n /**\n * fuel multiplier for spot taker\n * precision: 10\n */\n fuelBoostTaker: number;\n /**\n * fuel multiplier for spot maker\n * precision: 10\n */\n fuelBoostMaker: number;\n /**\n * fuel multiplier for spot insurance stake\n * precision: 10\n */\n fuelBoostInsurance: number;\n tokenProgramFlag: number;\n poolId: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link SpotMarketArgs} account data. */\nexport function getSpotMarketEncoder(): FixedSizeEncoder<SpotMarketArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"pubkey\", getAddressEncoder()],\n [\"oracle\", getAddressEncoder()],\n [\"mint\", getAddressEncoder()],\n [\"vault\", getAddressEncoder()],\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"historicalOracleData\", getHistoricalOracleDataEncoder()],\n [\"historicalIndexData\", getHistoricalIndexDataEncoder()],\n [\"revenuePool\", getPoolBalanceEncoder()],\n [\"spotFeePool\", getPoolBalanceEncoder()],\n [\"insuranceFund\", getInsuranceFundEncoder()],\n [\"totalSpotFee\", getU128Encoder()],\n [\"depositBalance\", getU128Encoder()],\n [\"borrowBalance\", getU128Encoder()],\n [\"cumulativeDepositInterest\", getU128Encoder()],\n [\"cumulativeBorrowInterest\", getU128Encoder()],\n [\"totalSocialLoss\", getU128Encoder()],\n [\"totalQuoteSocialLoss\", getU128Encoder()],\n [\"withdrawGuardThreshold\", getU64Encoder()],\n [\"maxTokenDeposits\", getU64Encoder()],\n [\"depositTokenTwap\", getU64Encoder()],\n [\"borrowTokenTwap\", getU64Encoder()],\n [\"utilizationTwap\", getU64Encoder()],\n [\"lastInterestTs\", getU64Encoder()],\n [\"lastTwapTs\", getU64Encoder()],\n [\"expiryTs\", getI64Encoder()],\n [\"orderStepSize\", getU64Encoder()],\n [\"orderTickSize\", getU64Encoder()],\n [\"minOrderSize\", getU64Encoder()],\n [\"maxPositionSize\", getU64Encoder()],\n [\"nextFillRecordId\", getU64Encoder()],\n [\"nextDepositRecordId\", getU64Encoder()],\n [\"initialAssetWeight\", getU32Encoder()],\n [\"maintenanceAssetWeight\", getU32Encoder()],\n [\"initialLiabilityWeight\", getU32Encoder()],\n [\"maintenanceLiabilityWeight\", getU32Encoder()],\n [\"imfFactor\", getU32Encoder()],\n [\"liquidatorFee\", getU32Encoder()],\n [\"ifLiquidationFee\", getU32Encoder()],\n [\"optimalUtilization\", getU32Encoder()],\n [\"optimalBorrowRate\", getU32Encoder()],\n [\"maxBorrowRate\", getU32Encoder()],\n [\"decimals\", getU32Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"ordersEnabled\", getBooleanEncoder()],\n [\"oracleSource\", getOracleSourceEncoder()],\n [\"status\", getMarketStatusEncoder()],\n [\"assetTier\", getAssetTierEncoder()],\n [\"pausedOperations\", getU8Encoder()],\n [\"ifPausedOperations\", getU8Encoder()],\n [\"feeAdjustment\", getI16Encoder()],\n [\"maxTokenBorrowsFraction\", getU16Encoder()],\n [\"flashLoanAmount\", getU64Encoder()],\n [\"flashLoanInitialTokenAmount\", getU64Encoder()],\n [\"totalSwapFee\", getU64Encoder()],\n [\"scaleInitialAssetWeightStart\", getU64Encoder()],\n [\"minBorrowRate\", getU8Encoder()],\n [\"fuelBoostDeposits\", getU8Encoder()],\n [\"fuelBoostBorrows\", getU8Encoder()],\n [\"fuelBoostTaker\", getU8Encoder()],\n [\"fuelBoostMaker\", getU8Encoder()],\n [\"fuelBoostInsurance\", getU8Encoder()],\n [\"tokenProgramFlag\", getU8Encoder()],\n [\"poolId\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 40)],\n ]),\n (value) => ({ ...value, discriminator: SPOT_MARKET_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link SpotMarket} account data. */\nexport function getSpotMarketDecoder(): FixedSizeDecoder<SpotMarket> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"pubkey\", getAddressDecoder()],\n [\"oracle\", getAddressDecoder()],\n [\"mint\", getAddressDecoder()],\n [\"vault\", getAddressDecoder()],\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"historicalOracleData\", getHistoricalOracleDataDecoder()],\n [\"historicalIndexData\", getHistoricalIndexDataDecoder()],\n [\"revenuePool\", getPoolBalanceDecoder()],\n [\"spotFeePool\", getPoolBalanceDecoder()],\n [\"insuranceFund\", getInsuranceFundDecoder()],\n [\"totalSpotFee\", getU128Decoder()],\n [\"depositBalance\", getU128Decoder()],\n [\"borrowBalance\", getU128Decoder()],\n [\"cumulativeDepositInterest\", getU128Decoder()],\n [\"cumulativeBorrowInterest\", getU128Decoder()],\n [\"totalSocialLoss\", getU128Decoder()],\n [\"totalQuoteSocialLoss\", getU128Decoder()],\n [\"withdrawGuardThreshold\", getU64Decoder()],\n [\"maxTokenDeposits\", getU64Decoder()],\n [\"depositTokenTwap\", getU64Decoder()],\n [\"borrowTokenTwap\", getU64Decoder()],\n [\"utilizationTwap\", getU64Decoder()],\n [\"lastInterestTs\", getU64Decoder()],\n [\"lastTwapTs\", getU64Decoder()],\n [\"expiryTs\", getI64Decoder()],\n [\"orderStepSize\", getU64Decoder()],\n [\"orderTickSize\", getU64Decoder()],\n [\"minOrderSize\", getU64Decoder()],\n [\"maxPositionSize\", getU64Decoder()],\n [\"nextFillRecordId\", getU64Decoder()],\n [\"nextDepositRecordId\", getU64Decoder()],\n [\"initialAssetWeight\", getU32Decoder()],\n [\"maintenanceAssetWeight\", getU32Decoder()],\n [\"initialLiabilityWeight\", getU32Decoder()],\n [\"maintenanceLiabilityWeight\", getU32Decoder()],\n [\"imfFactor\", getU32Decoder()],\n [\"liquidatorFee\", getU32Decoder()],\n [\"ifLiquidationFee\", getU32Decoder()],\n [\"optimalUtilization\", getU32Decoder()],\n [\"optimalBorrowRate\", getU32Decoder()],\n [\"maxBorrowRate\", getU32Decoder()],\n [\"decimals\", getU32Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"ordersEnabled\", getBooleanDecoder()],\n [\"oracleSource\", getOracleSourceDecoder()],\n [\"status\", getMarketStatusDecoder()],\n [\"assetTier\", getAssetTierDecoder()],\n [\"pausedOperations\", getU8Decoder()],\n [\"ifPausedOperations\", getU8Decoder()],\n [\"feeAdjustment\", getI16Decoder()],\n [\"maxTokenBorrowsFraction\", getU16Decoder()],\n [\"flashLoanAmount\", getU64Decoder()],\n [\"flashLoanInitialTokenAmount\", getU64Decoder()],\n [\"totalSwapFee\", getU64Decoder()],\n [\"scaleInitialAssetWeightStart\", getU64Decoder()],\n [\"minBorrowRate\", getU8Decoder()],\n [\"fuelBoostDeposits\", getU8Decoder()],\n [\"fuelBoostBorrows\", getU8Decoder()],\n [\"fuelBoostTaker\", getU8Decoder()],\n [\"fuelBoostMaker\", getU8Decoder()],\n [\"fuelBoostInsurance\", getU8Decoder()],\n [\"tokenProgramFlag\", getU8Decoder()],\n [\"poolId\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 40)],\n ]);\n}\n\n/** Gets the codec for {@link SpotMarket} account data. */\nexport function getSpotMarketCodec(): FixedSizeCodec<SpotMarketArgs, SpotMarket> {\n return combineCodec(getSpotMarketEncoder(), getSpotMarketDecoder());\n}\n\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<SpotMarket, TAddress>;\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<SpotMarket, TAddress>;\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<SpotMarket, TAddress> | MaybeAccount<SpotMarket, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getSpotMarketDecoder());\n}\n\nexport async function fetchSpotMarket<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<SpotMarket, TAddress>> {\n const maybeAccount = await fetchMaybeSpotMarket(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeSpotMarket<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<SpotMarket, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeSpotMarket(maybeAccount);\n}\n\nexport async function fetchAllSpotMarket(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<SpotMarket>[]> {\n const maybeAccounts = await fetchAllMaybeSpotMarket(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeSpotMarket(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<SpotMarket>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeSpotMarket(maybeAccount));\n}\n\nexport function getSpotMarketSize(): number {\n return 776;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getMarginModeDecoder,\n getMarginModeEncoder,\n getOrderDecoder,\n getOrderEncoder,\n getPerpPositionDecoder,\n getPerpPositionEncoder,\n getSpotPositionDecoder,\n getSpotPositionEncoder,\n type MarginMode,\n type MarginModeArgs,\n type Order,\n type OrderArgs,\n type PerpPosition,\n type PerpPositionArgs,\n type SpotPosition,\n type SpotPositionArgs,\n} from \"../types\";\n\nexport const USER_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 159, 117, 95, 227, 239, 151, 58, 236,\n]);\n\nexport function getUserDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(USER_DISCRIMINATOR);\n}\n\nexport type User = {\n discriminator: ReadonlyUint8Array;\n /** The owner/authority of the account */\n authority: Address;\n /** An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw */\n delegate: Address;\n /** Encoded display name e.g. \"toly\" */\n name: ReadonlyUint8Array;\n /** The user's spot positions */\n spotPositions: Array<SpotPosition>;\n /** The user's perp positions */\n perpPositions: Array<PerpPosition>;\n /** The user's orders */\n orders: Array<Order>;\n /** The last time the user added perp lp positions */\n lastAddPerpLpSharesTs: bigint;\n /**\n * The total values of deposits the user has made\n * precision: QUOTE_PRECISION\n */\n totalDeposits: bigint;\n /**\n * The total values of withdrawals the user has made\n * precision: QUOTE_PRECISION\n */\n totalWithdraws: bigint;\n /**\n * The total socialized loss the users has incurred upon the protocol\n * precision: QUOTE_PRECISION\n */\n totalSocialLoss: bigint;\n /**\n * Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps\n * precision: QUOTE_PRECISION\n */\n settledPerpPnl: bigint;\n /**\n * Fees (taker fees, maker rebate, filler reward) for spot\n * precision: QUOTE_PRECISION\n */\n cumulativeSpotFees: bigint;\n /**\n * Cumulative funding paid/received for perps\n * precision: QUOTE_PRECISION\n */\n cumulativePerpFunding: bigint;\n /**\n * The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time\n * Defaults to zero when not being liquidated\n * precision: QUOTE_PRECISION\n */\n liquidationMarginFreed: bigint;\n /** The last slot a user was active. Used to determine if a user is idle */\n lastActiveSlot: bigint;\n /** Every user order has an order id. This is the next order id to be used */\n nextOrderId: number;\n /** Custom max initial margin ratio for the user */\n maxMarginRatio: number;\n /** The next liquidation id to be used for user */\n nextLiquidationId: number;\n /** The sub account id for this user */\n subAccountId: number;\n /** Whether the user is active, being liquidated or bankrupt */\n status: number;\n /** Whether the user has enabled margin trading */\n isMarginTradingEnabled: boolean;\n /**\n * User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows\n * Off-chain keeper bots can ignore users that are idle\n */\n idle: boolean;\n /** number of open orders */\n openOrders: number;\n /** Whether or not user has open order */\n hasOpenOrder: boolean;\n /** number of open orders with auction */\n openAuctions: number;\n /** Whether or not user has open order with auction */\n hasOpenAuction: boolean;\n marginMode: MarginMode;\n poolId: number;\n padding1: ReadonlyUint8Array;\n lastFuelBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type UserArgs = {\n /** The owner/authority of the account */\n authority: Address;\n /** An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw */\n delegate: Address;\n /** Encoded display name e.g. \"toly\" */\n name: ReadonlyUint8Array;\n /** The user's spot positions */\n spotPositions: Array<SpotPositionArgs>;\n /** The user's perp positions */\n perpPositions: Array<PerpPositionArgs>;\n /** The user's orders */\n orders: Array<OrderArgs>;\n /** The last time the user added perp lp positions */\n lastAddPerpLpSharesTs: number | bigint;\n /**\n * The total values of deposits the user has made\n * precision: QUOTE_PRECISION\n */\n totalDeposits: number | bigint;\n /**\n * The total values of withdrawals the user has made\n * precision: QUOTE_PRECISION\n */\n totalWithdraws: number | bigint;\n /**\n * The total socialized loss the users has incurred upon the protocol\n * precision: QUOTE_PRECISION\n */\n totalSocialLoss: number | bigint;\n /**\n * Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps\n * precision: QUOTE_PRECISION\n */\n settledPerpPnl: number | bigint;\n /**\n * Fees (taker fees, maker rebate, filler reward) for spot\n * precision: QUOTE_PRECISION\n */\n cumulativeSpotFees: number | bigint;\n /**\n * Cumulative funding paid/received for perps\n * precision: QUOTE_PRECISION\n */\n cumulativePerpFunding: number | bigint;\n /**\n * The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time\n * Defaults to zero when not being liquidated\n * precision: QUOTE_PRECISION\n */\n liquidationMarginFreed: number | bigint;\n /** The last slot a user was active. Used to determine if a user is idle */\n lastActiveSlot: number | bigint;\n /** Every user order has an order id. This is the next order id to be used */\n nextOrderId: number;\n /** Custom max initial margin ratio for the user */\n maxMarginRatio: number;\n /** The next liquidation id to be used for user */\n nextLiquidationId: number;\n /** The sub account id for this user */\n subAccountId: number;\n /** Whether the user is active, being liquidated or bankrupt */\n status: number;\n /** Whether the user has enabled margin trading */\n isMarginTradingEnabled: boolean;\n /**\n * User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows\n * Off-chain keeper bots can ignore users that are idle\n */\n idle: boolean;\n /** number of open orders */\n openOrders: number;\n /** Whether or not user has open order */\n hasOpenOrder: boolean;\n /** number of open orders with auction */\n openAuctions: number;\n /** Whether or not user has open order with auction */\n hasOpenAuction: boolean;\n marginMode: MarginModeArgs;\n poolId: number;\n padding1: ReadonlyUint8Array;\n lastFuelBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link UserArgs} account data. */\nexport function getUserEncoder(): FixedSizeEncoder<UserArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"authority\", getAddressEncoder()],\n [\"delegate\", getAddressEncoder()],\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"spotPositions\", getArrayEncoder(getSpotPositionEncoder(), { size: 8 })],\n [\"perpPositions\", getArrayEncoder(getPerpPositionEncoder(), { size: 8 })],\n [\"orders\", getArrayEncoder(getOrderEncoder(), { size: 32 })],\n [\"lastAddPerpLpSharesTs\", getI64Encoder()],\n [\"totalDeposits\", getU64Encoder()],\n [\"totalWithdraws\", getU64Encoder()],\n [\"totalSocialLoss\", getU64Encoder()],\n [\"settledPerpPnl\", getI64Encoder()],\n [\"cumulativeSpotFees\", getI64Encoder()],\n [\"cumulativePerpFunding\", getI64Encoder()],\n [\"liquidationMarginFreed\", getU64Encoder()],\n [\"lastActiveSlot\", getU64Encoder()],\n [\"nextOrderId\", getU32Encoder()],\n [\"maxMarginRatio\", getU32Encoder()],\n [\"nextLiquidationId\", getU16Encoder()],\n [\"subAccountId\", getU16Encoder()],\n [\"status\", getU8Encoder()],\n [\"isMarginTradingEnabled\", getBooleanEncoder()],\n [\"idle\", getBooleanEncoder()],\n [\"openOrders\", getU8Encoder()],\n [\"hasOpenOrder\", getBooleanEncoder()],\n [\"openAuctions\", getU8Encoder()],\n [\"hasOpenAuction\", getBooleanEncoder()],\n [\"marginMode\", getMarginModeEncoder()],\n [\"poolId\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"lastFuelBonusUpdateTs\", getU32Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 12)],\n ]),\n (value) => ({ ...value, discriminator: USER_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link User} account data. */\nexport function getUserDecoder(): FixedSizeDecoder<User> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"authority\", getAddressDecoder()],\n [\"delegate\", getAddressDecoder()],\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"spotPositions\", getArrayDecoder(getSpotPositionDecoder(), { size: 8 })],\n [\"perpPositions\", getArrayDecoder(getPerpPositionDecoder(), { size: 8 })],\n [\"orders\", getArrayDecoder(getOrderDecoder(), { size: 32 })],\n [\"lastAddPerpLpSharesTs\", getI64Decoder()],\n [\"totalDeposits\", getU64Decoder()],\n [\"totalWithdraws\", getU64Decoder()],\n [\"totalSocialLoss\", getU64Decoder()],\n [\"settledPerpPnl\", getI64Decoder()],\n [\"cumulativeSpotFees\", getI64Decoder()],\n [\"cumulativePerpFunding\", getI64Decoder()],\n [\"liquidationMarginFreed\", getU64Decoder()],\n [\"lastActiveSlot\", getU64Decoder()],\n [\"nextOrderId\", getU32Decoder()],\n [\"maxMarginRatio\", getU32Decoder()],\n [\"nextLiquidationId\", getU16Decoder()],\n [\"subAccountId\", getU16Decoder()],\n [\"status\", getU8Decoder()],\n [\"isMarginTradingEnabled\", getBooleanDecoder()],\n [\"idle\", getBooleanDecoder()],\n [\"openOrders\", getU8Decoder()],\n [\"hasOpenOrder\", getBooleanDecoder()],\n [\"openAuctions\", getU8Decoder()],\n [\"hasOpenAuction\", getBooleanDecoder()],\n [\"marginMode\", getMarginModeDecoder()],\n [\"poolId\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"lastFuelBonusUpdateTs\", getU32Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 12)],\n ]);\n}\n\n/** Gets the codec for {@link User} account data. */\nexport function getUserCodec(): FixedSizeCodec<UserArgs, User> {\n return combineCodec(getUserEncoder(), getUserDecoder());\n}\n\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<User, TAddress>;\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<User, TAddress>;\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<User, TAddress> | MaybeAccount<User, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getUserDecoder());\n}\n\nexport async function fetchUser<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<User, TAddress>> {\n const maybeAccount = await fetchMaybeUser(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeUser<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<User, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeUser(maybeAccount);\n}\n\nexport async function fetchAllUser(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<User>[]> {\n const maybeAccounts = await fetchAllMaybeUser(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeUser(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<User>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeUser(maybeAccount));\n}\n\nexport function getUserSize(): number {\n return 4376;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { getUserFeesDecoder, getUserFeesEncoder, type UserFees, type UserFeesArgs } from \"../types\";\n\nexport const USER_STATS_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 176, 223, 136, 27, 122, 79, 32, 227,\n]);\n\nexport function getUserStatsDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(USER_STATS_DISCRIMINATOR);\n}\n\nexport type UserStats = {\n discriminator: ReadonlyUint8Array;\n /** The authority for all of a users sub accounts */\n authority: Address;\n /** The address that referred this user */\n referrer: Address;\n /** Stats on the fees paid by the user */\n fees: UserFees;\n /**\n * The timestamp of the next epoch\n * Epoch is used to limit referrer rewards earned in single epoch\n */\n nextEpochTs: bigint;\n /**\n * Rolling 30day maker volume for user\n * precision: QUOTE_PRECISION\n */\n makerVolume30d: bigint;\n /**\n * Rolling 30day taker volume for user\n * precision: QUOTE_PRECISION\n */\n takerVolume30d: bigint;\n /**\n * Rolling 30day filler volume for user\n * precision: QUOTE_PRECISION\n */\n fillerVolume30d: bigint;\n /** last time the maker volume was updated */\n lastMakerVolume30dTs: bigint;\n /** last time the taker volume was updated */\n lastTakerVolume30dTs: bigint;\n /** last time the filler volume was updated */\n lastFillerVolume30dTs: bigint;\n /** The amount of tokens staked in the quote spot markets if */\n ifStakedQuoteAssetAmount: bigint;\n /** The current number of sub accounts */\n numberOfSubAccounts: number;\n /**\n * The number of sub accounts created. Can be greater than the number of sub accounts if user\n * has deleted sub accounts\n */\n numberOfSubAccountsCreated: number;\n /**\n * Flags for referrer status:\n * First bit (LSB): 1 if user is a referrer, 0 otherwise\n * Second bit: 1 if user was referred, 0 otherwise\n */\n referrerStatus: number;\n disableUpdatePerpBidAskTwap: number;\n pausedOperations: number;\n /** whether the user has a FuelOverflow account */\n fuelOverflowStatus: number;\n /** accumulated fuel for token amounts of insurance */\n fuelInsurance: number;\n /** accumulated fuel for notional of deposits */\n fuelDeposits: number;\n /** accumulate fuel bonus for notional of borrows */\n fuelBorrows: number;\n /** accumulated fuel for perp open interest */\n fuelPositions: number;\n /** accumulate fuel bonus for taker volume */\n fuelTaker: number;\n /** accumulate fuel bonus for maker volume */\n fuelMaker: number;\n /** The amount of tokens staked in the governance spot markets if */\n ifStakedGovTokenAmount: bigint;\n /** last unix ts user stats data was used to update if fuel (u32 to save space) */\n lastFuelIfBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type UserStatsArgs = {\n /** The authority for all of a users sub accounts */\n authority: Address;\n /** The address that referred this user */\n referrer: Address;\n /** Stats on the fees paid by the user */\n fees: UserFeesArgs;\n /**\n * The timestamp of the next epoch\n * Epoch is used to limit referrer rewards earned in single epoch\n */\n nextEpochTs: number | bigint;\n /**\n * Rolling 30day maker volume for user\n * precision: QUOTE_PRECISION\n */\n makerVolume30d: number | bigint;\n /**\n * Rolling 30day taker volume for user\n * precision: QUOTE_PRECISION\n */\n takerVolume30d: number | bigint;\n /**\n * Rolling 30day filler volume for user\n * precision: QUOTE_PRECISION\n */\n fillerVolume30d: number | bigint;\n /** last time the maker volume was updated */\n lastMakerVolume30dTs: number | bigint;\n /** last time the taker volume was updated */\n lastTakerVolume30dTs: number | bigint;\n /** last time the filler volume was updated */\n lastFillerVolume30dTs: number | bigint;\n /** The amount of tokens staked in the quote spot markets if */\n ifStakedQuoteAssetAmount: number | bigint;\n /** The current number of sub accounts */\n numberOfSubAccounts: number;\n /**\n * The number of sub accounts created. Can be greater than the number of sub accounts if user\n * has deleted sub accounts\n */\n numberOfSubAccountsCreated: number;\n /**\n * Flags for referrer status:\n * First bit (LSB): 1 if user is a referrer, 0 otherwise\n * Second bit: 1 if user was referred, 0 otherwise\n */\n referrerStatus: number;\n disableUpdatePerpBidAskTwap: number;\n pausedOperations: number;\n /** whether the user has a FuelOverflow account */\n fuelOverflowStatus: number;\n /** accumulated fuel for token amounts of insurance */\n fuelInsurance: number;\n /** accumulated fuel for notional of deposits */\n fuelDeposits: number;\n /** accumulate fuel bonus for notional of borrows */\n fuelBorrows: number;\n /** accumulated fuel for perp open interest */\n fuelPositions: number;\n /** accumulate fuel bonus for taker volume */\n fuelTaker: number;\n /** accumulate fuel bonus for maker volume */\n fuelMaker: number;\n /** The amount of tokens staked in the governance spot markets if */\n ifStakedGovTokenAmount: number | bigint;\n /** last unix ts user stats data was used to update if fuel (u32 to save space) */\n lastFuelIfBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link UserStatsArgs} account data. */\nexport function getUserStatsEncoder(): FixedSizeEncoder<UserStatsArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"authority\", getAddressEncoder()],\n [\"referrer\", getAddressEncoder()],\n [\"fees\", getUserFeesEncoder()],\n [\"nextEpochTs\", getI64Encoder()],\n [\"makerVolume30d\", getU64Encoder()],\n [\"takerVolume30d\", getU64Encoder()],\n [\"fillerVolume30d\", getU64Encoder()],\n [\"lastMakerVolume30dTs\", getI64Encoder()],\n [\"lastTakerVolume30dTs\", getI64Encoder()],\n [\"lastFillerVolume30dTs\", getI64Encoder()],\n [\"ifStakedQuoteAssetAmount\", getU64Encoder()],\n [\"numberOfSubAccounts\", getU16Encoder()],\n [\"numberOfSubAccountsCreated\", getU16Encoder()],\n [\"referrerStatus\", getU8Encoder()],\n [\"disableUpdatePerpBidAskTwap\", getU8Encoder()],\n [\"pausedOperations\", getU8Encoder()],\n [\"fuelOverflowStatus\", getU8Encoder()],\n [\"fuelInsurance\", getU32Encoder()],\n [\"fuelDeposits\", getU32Encoder()],\n [\"fuelBorrows\", getU32Encoder()],\n [\"fuelPositions\", getU32Encoder()],\n [\"fuelTaker\", getU32Encoder()],\n [\"fuelMaker\", getU32Encoder()],\n [\"ifStakedGovTokenAmount\", getU64Encoder()],\n [\"lastFuelIfBonusUpdateTs\", getU32Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 12)],\n ]),\n (value) => ({ ...value, discriminator: USER_STATS_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link UserStats} account data. */\nexport function getUserStatsDecoder(): FixedSizeDecoder<UserStats> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"authority\", getAddressDecoder()],\n [\"referrer\", getAddressDecoder()],\n [\"fees\", getUserFeesDecoder()],\n [\"nextEpochTs\", getI64Decoder()],\n [\"makerVolume30d\", getU64Decoder()],\n [\"takerVolume30d\", getU64Decoder()],\n [\"fillerVolume30d\", getU64Decoder()],\n [\"lastMakerVolume30dTs\", getI64Decoder()],\n [\"lastTakerVolume30dTs\", getI64Decoder()],\n [\"lastFillerVolume30dTs\", getI64Decoder()],\n [\"ifStakedQuoteAssetAmount\", getU64Decoder()],\n [\"numberOfSubAccounts\", getU16Decoder()],\n [\"numberOfSubAccountsCreated\", getU16Decoder()],\n [\"referrerStatus\", getU8Decoder()],\n [\"disableUpdatePerpBidAskTwap\", getU8Decoder()],\n [\"pausedOperations\", getU8Decoder()],\n [\"fuelOverflowStatus\", getU8Decoder()],\n [\"fuelInsurance\", getU32Decoder()],\n [\"fuelDeposits\", getU32Decoder()],\n [\"fuelBorrows\", getU32Decoder()],\n [\"fuelPositions\", getU32Decoder()],\n [\"fuelTaker\", getU32Decoder()],\n [\"fuelMaker\", getU32Decoder()],\n [\"ifStakedGovTokenAmount\", getU64Decoder()],\n [\"lastFuelIfBonusUpdateTs\", getU32Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 12)],\n ]);\n}\n\n/** Gets the codec for {@link UserStats} account data. */\nexport function getUserStatsCodec(): FixedSizeCodec<UserStatsArgs, UserStats> {\n return combineCodec(getUserStatsEncoder(), getUserStatsDecoder());\n}\n\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<UserStats, TAddress>;\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<UserStats, TAddress>;\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<UserStats, TAddress> | MaybeAccount<UserStats, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getUserStatsDecoder());\n}\n\nexport async function fetchUserStats<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<UserStats, TAddress>> {\n const maybeAccount = await fetchMaybeUserStats(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeUserStats<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<UserStats, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeUserStats(maybeAccount);\n}\n\nexport async function fetchAllUserStats(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<UserStats>[]> {\n const maybeAccounts = await fetchAllMaybeUserStats(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeUserStats(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<UserStats>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeUserStats(maybeAccount));\n}\n\nexport function getUserStatsSize(): number {\n return 240;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getSpotMarketCodec,\n getUserCodec,\n getUserStatsCodec,\n type SpotMarket,\n type SpotMarketArgs,\n type User,\n type UserArgs,\n type UserStats,\n type UserStatsArgs,\n} from \"../accounts\";\nimport {\n getUpdateSpotMarketCumulativeInterestInstruction,\n parseUpdateSpotMarketCumulativeInterestInstruction,\n type ParsedUpdateSpotMarketCumulativeInterestInstruction,\n type UpdateSpotMarketCumulativeInterestInput,\n} from \"../instructions\";\n\nexport const DRIFT_PROGRAM_ADDRESS =\n \"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\" as Address<\"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\">;\n\nexport enum DriftAccount {\n SpotMarket,\n User,\n UserStats,\n}\n\nexport function identifyDriftAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): DriftAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([100, 177, 8, 107, 168, 65, 65, 39])\n ),\n 0\n )\n ) {\n return DriftAccount.SpotMarket;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([159, 117, 95, 227, 239, 151, 58, 236])\n ),\n 0\n )\n ) {\n return DriftAccount.User;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([176, 223, 136, 27, 122, 79, 32, 227])\n ),\n 0\n )\n ) {\n return DriftAccount.UserStats;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"drift\",\n });\n}\n\nexport enum DriftInstruction {\n UpdateSpotMarketCumulativeInterest,\n}\n\nexport function identifyDriftInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): DriftInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([39, 166, 139, 243, 158, 165, 155, 225])\n ),\n 0\n )\n ) {\n return DriftInstruction.UpdateSpotMarketCumulativeInterest;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"drift\",\n });\n}\n\nexport type ParsedDriftInstruction<\n TProgram extends string = \"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\",\n> = {\n instructionType: DriftInstruction.UpdateSpotMarketCumulativeInterest;\n} & ParsedUpdateSpotMarketCumulativeInterestInstruction<TProgram>;\n\nexport function parseDriftInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedDriftInstruction<TProgram> {\n const instructionType = identifyDriftInstruction(instruction);\n switch (instructionType) {\n case DriftInstruction.UpdateSpotMarketCumulativeInterest: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: DriftInstruction.UpdateSpotMarketCumulativeInterest,\n ...parseUpdateSpotMarketCumulativeInterestInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"drift\",\n });\n }\n}\n\nexport type DriftPlugin = {\n accounts: DriftPluginAccounts;\n instructions: DriftPluginInstructions;\n identifyAccount: typeof identifyDriftAccount;\n identifyInstruction: typeof identifyDriftInstruction;\n parseInstruction: typeof parseDriftInstruction;\n};\n\nexport type DriftPluginAccounts = {\n spotMarket: ReturnType<typeof getSpotMarketCodec> &\n SelfFetchFunctions<SpotMarketArgs, SpotMarket>;\n user: ReturnType<typeof getUserCodec> & SelfFetchFunctions<UserArgs, User>;\n userStats: ReturnType<typeof getUserStatsCodec> & SelfFetchFunctions<UserStatsArgs, UserStats>;\n};\n\nexport type DriftPluginInstructions = {\n updateSpotMarketCumulativeInterest: (\n input: UpdateSpotMarketCumulativeInterestInput\n ) => ReturnType<typeof getUpdateSpotMarketCumulativeInterestInstruction> &\n SelfPlanAndSendFunctions;\n};\n\nexport type DriftPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function driftProgram() {\n return <T extends DriftPluginRequirements>(\n client: T\n ): ExtendedClient<T, { drift: DriftPlugin }> => {\n return extendClient(client, {\n drift: <DriftPlugin>{\n accounts: {\n spotMarket: addSelfFetchFunctions(client, getSpotMarketCodec()),\n user: addSelfFetchFunctions(client, getUserCodec()),\n userStats: addSelfFetchFunctions(client, getUserStatsCodec()),\n },\n instructions: {\n updateSpotMarketCumulativeInterest: (input) =>\n addSelfPlanAndSendFunctions(\n client,\n getUpdateSpotMarketCumulativeInterestInstruction(input)\n ),\n },\n identifyAccount: identifyDriftAccount,\n identifyInstruction: identifyDriftInstruction,\n parseInstruction: parseDriftInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { DRIFT_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR: ReadonlyUint8Array =\n new Uint8Array([39, 166, 139, 243, 158, 165, 155, 225]);\n\nexport function getUpdateSpotMarketCumulativeInterestDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(\n UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR\n );\n}\n\nexport type UpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string = typeof DRIFT_PROGRAM_ADDRESS,\n TAccountState extends string | AccountMeta<string> = string,\n TAccountSpotMarket extends string | AccountMeta<string> = string,\n TAccountOracle extends string | AccountMeta<string> = string,\n TAccountSpotMarketVault extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountState extends string ? ReadonlyAccount<TAccountState> : TAccountState,\n TAccountSpotMarket extends string ? WritableAccount<TAccountSpotMarket> : TAccountSpotMarket,\n TAccountOracle extends string ? ReadonlyAccount<TAccountOracle> : TAccountOracle,\n TAccountSpotMarketVault extends string\n ? ReadonlyAccount<TAccountSpotMarketVault>\n : TAccountSpotMarketVault,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateSpotMarketCumulativeInterestInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type UpdateSpotMarketCumulativeInterestInstructionDataArgs = {};\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataEncoder(): FixedSizeEncoder<UpdateSpotMarketCumulativeInterestInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR })\n );\n}\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataDecoder(): FixedSizeDecoder<UpdateSpotMarketCumulativeInterestInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataCodec(): FixedSizeCodec<\n UpdateSpotMarketCumulativeInterestInstructionDataArgs,\n UpdateSpotMarketCumulativeInterestInstructionData\n> {\n return combineCodec(\n getUpdateSpotMarketCumulativeInterestInstructionDataEncoder(),\n getUpdateSpotMarketCumulativeInterestInstructionDataDecoder()\n );\n}\n\nexport type UpdateSpotMarketCumulativeInterestInput<\n TAccountState extends InstructionAccountInput = InstructionAccountInput,\n TAccountSpotMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSpotMarketVault extends InstructionAccountInput = InstructionAccountInput,\n> = {\n state: TAccountState;\n spotMarket: TAccountSpotMarket;\n oracle: TAccountOracle;\n spotMarketVault: TAccountSpotMarketVault;\n};\n\nexport function getUpdateSpotMarketCumulativeInterestInstruction<\n TAccountState extends InstructionAccountInput,\n TAccountSpotMarket extends InstructionAccountInput,\n TAccountOracle extends InstructionAccountInput,\n TAccountSpotMarketVault extends InstructionAccountInput,\n TProgramAddress extends Address = typeof DRIFT_PROGRAM_ADDRESS,\n>(\n input: UpdateSpotMarketCumulativeInterestInput<\n TAccountState,\n TAccountSpotMarket,\n TAccountOracle,\n TAccountSpotMarketVault\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateSpotMarketCumulativeInterestInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountState, InstructionAccountInputAddress<TAccountState>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarket,\n InstructionAccountInputAddress<TAccountSpotMarket>\n >,\n ResolvedInstructionAccountMeta<TAccountOracle, InstructionAccountInputAddress<TAccountOracle>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarketVault,\n InstructionAccountInputAddress<TAccountSpotMarketVault>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? DRIFT_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n state: { value: input.state ?? null, isSigner: false, isWritable: false },\n spotMarket: { value: input.spotMarket ?? null, isSigner: false, isWritable: true },\n oracle: { value: input.oracle ?? null, isSigner: false, isWritable: false },\n spotMarketVault: { value: input.spotMarketVault ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"state\", accounts.state),\n getAccountMeta(\"spotMarket\", accounts.spotMarket),\n getAccountMeta(\"oracle\", accounts.oracle),\n getAccountMeta(\"spotMarketVault\", accounts.spotMarketVault),\n ],\n data: getUpdateSpotMarketCumulativeInterestInstructionDataEncoder().encode({}),\n programAddress,\n } as UpdateSpotMarketCumulativeInterestInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountState, InstructionAccountInputAddress<TAccountState>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarket,\n InstructionAccountInputAddress<TAccountSpotMarket>\n >,\n ResolvedInstructionAccountMeta<TAccountOracle, InstructionAccountInputAddress<TAccountOracle>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarketVault,\n InstructionAccountInputAddress<TAccountSpotMarketVault>\n >\n >);\n}\n\nexport type ParsedUpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string = typeof DRIFT_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n state: TAccountMetas[0];\n spotMarket: TAccountMetas[1];\n oracle: TAccountMetas[2];\n spotMarketVault: TAccountMetas[3];\n };\n data: UpdateSpotMarketCumulativeInterestInstructionData;\n};\n\nexport function parseUpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedUpdateSpotMarketCumulativeInterestInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 4) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 4,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n state: getNextAccount(),\n spotMarket: getNextAccount(),\n oracle: getNextAccount(),\n spotMarketVault: getNextAccount(),\n },\n data: getUpdateSpotMarketCumulativeInterestInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import type { ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type { DriftSpotMarket, DriftUser, DriftUserStats } from \"./types\";\n\nimport {\n getSpotMarketDecoder,\n getUserDecoder,\n getUserStatsDecoder,\n SPOT_MARKET_DISCRIMINATOR,\n USER_DISCRIMINATOR,\n USER_STATS_DISCRIMINATOR,\n} from \"~/generated/drift\";\n\nexport { DRIFT_PROGRAM_ADDRESS, SpotBalanceType } from \"~/generated/drift\";\n\n/**\n * Decodes a Drift `SpotMarket` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftSpotMarket(data: ReadonlyUint8Array): DriftSpotMarket {\n return decodeAccountData(\n data,\n SPOT_MARKET_DISCRIMINATOR,\n getSpotMarketDecoder(),\n \"Drift SpotMarket\"\n );\n}\n\n/**\n * Decodes a Drift `User` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftUser(data: ReadonlyUint8Array): DriftUser {\n return decodeAccountData(data, USER_DISCRIMINATOR, getUserDecoder(), \"Drift User\");\n}\n\n/**\n * Decodes a Drift `UserStats` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftUserStats(data: ReadonlyUint8Array): DriftUserStats {\n return decodeAccountData(\n data,\n USER_STATS_DISCRIMINATOR,\n getUserStatsDecoder(),\n \"Drift UserStats\"\n );\n}\n","import {\n getAddressEncoder,\n getProgramDerivedAddress,\n getU16Encoder,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nimport { DRIFT_PROGRAM_ADDRESS } from \"~/generated/drift\";\n\n/** Drift `State` PDA. */\nexport function deriveDriftState(): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"drift_state\"],\n });\n}\n\n/** Drift signer PDA (owns spot market vaults). */\nexport function deriveDriftSigner(): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"drift_signer\"],\n });\n}\n\n/** Drift `User` PDA of `authority` sub-account `subAccountId`. */\nexport function deriveDriftUser(\n authority: Address,\n subAccountId: number\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"user\", getAddressEncoder().encode(authority), getU16Encoder().encode(subAccountId)],\n });\n}\n\n/** Drift `UserStats` PDA of `authority`. */\nexport function deriveDriftUserStats(authority: Address): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"user_stats\", getAddressEncoder().encode(authority)],\n });\n}\n\n/** Drift `SpotMarket` PDA of `marketIndex`. */\nexport function deriveDriftSpotMarket(marketIndex: number): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"spot_market\", getU16Encoder().encode(marketIndex)],\n });\n}\n\n/** Drift spot market token vault PDA of `marketIndex`. */\nexport function deriveDriftSpotMarketVault(marketIndex: number): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"spot_market_vault\", getU16Encoder().encode(marketIndex)],\n });\n}\n\n/** State, signer, spot market and spot market vault of `marketIndex`. */\nexport async function getAllDerivedDriftAccounts(marketIndex: number) {\n const [[driftState], [driftSigner], [driftSpotMarket], [driftSpotMarketVault]] =\n await Promise.all([\n deriveDriftState(),\n deriveDriftSigner(),\n deriveDriftSpotMarket(marketIndex),\n deriveDriftSpotMarketVault(marketIndex),\n ]);\n return { driftState, driftSigner, driftSpotMarket, driftSpotMarketVault };\n}\n","import type { Instruction } from \"@solana/kit\";\n\nimport { deriveDriftSpotMarketVault, deriveDriftState } from \"./pda\";\nimport type { DriftSpotMarket } from \"./types\";\n\nimport { getUpdateSpotMarketCumulativeInterestInstruction } from \"~/generated/drift\";\n\n/**\n * Accrues a Drift spot market's cumulative interest (permissionless crank) so token amounts derived\n * from its scaled balances are current.\n */\nexport async function makeUpdateSpotMarketCumulativeInterestIx(\n spotMarket: DriftSpotMarket\n): Promise<Instruction> {\n const [[state], [spotMarketVault]] = await Promise.all([\n deriveDriftState(),\n deriveDriftSpotMarketVault(spotMarket.marketIndex),\n ]);\n return getUpdateSpotMarketCumulativeInterestInstruction({\n state,\n spotMarket: spotMarket.pubkey,\n oracle: spotMarket.oracle,\n spotMarketVault,\n });\n}\n","import { BigNumber } from \"bignumber.js\";\n\nimport type { DriftSpotMarket } from \"./types\";\n\nimport { SpotBalanceType } from \"~/generated/drift\";\n\nexport const PERCENTAGE_PRECISION = 1_000_000n;\nexport const SPOT_MARKET_RATE_PRECISION = 1_000_000n;\nexport const SPOT_MARKET_UTILIZATION_PRECISION = 1_000_000n;\n/** Seconds */\nexport const ONE_YEAR = 31_536_000n;\n\n/**\n * Token amount (native units) of a scaled spot balance, including accrued interest. Borrows round up.\n */\nexport function getDriftTokenAmount(\n balanceAmount: bigint,\n spotMarket: DriftSpotMarket,\n balanceType: SpotBalanceType\n): bigint {\n const precisionDecrease = 10n ** BigInt(19 - spotMarket.decimals);\n\n if (balanceType === SpotBalanceType.Deposit) {\n return (balanceAmount * spotMarket.cumulativeDepositInterest) / precisionDecrease;\n }\n const scaled = balanceAmount * spotMarket.cumulativeBorrowInterest;\n const quotient = scaled / precisionDecrease;\n return scaled % precisionDecrease > 0n ? quotient + 1n : quotient;\n}\n\n/**\n * Tokens (native units) per scaled deposit balance unit of `spotMarket`: {@link getDriftTokenAmount}\n * for a deposit, without rounding.\n */\nexport function getDriftCTokenMultiplier(spotMarket: DriftSpotMarket): BigNumber {\n return new BigNumber(spotMarket.cumulativeDepositInterest.toString()).dividedBy(\n new BigNumber(10).pow(19 - spotMarket.decimals)\n );\n}\n\n/**\n * Utilization (SPOT_MARKET_UTILIZATION_PRECISION) = borrows / deposits. A positive `delta` adds to\n * deposits, a negative one to borrows (native units).\n */\nexport function calculateDriftUtilization(bank: DriftSpotMarket, delta: bigint = 0n): bigint {\n let deposits = getDriftTokenAmount(bank.depositBalance, bank, SpotBalanceType.Deposit);\n let borrows = getDriftTokenAmount(bank.borrowBalance, bank, SpotBalanceType.Borrow);\n\n if (delta > 0n) {\n deposits += delta;\n } else if (delta < 0n) {\n borrows -= delta;\n }\n\n if (borrows === 0n && deposits === 0n) {\n return 0n;\n }\n if (deposits === 0n) {\n return SPOT_MARKET_UTILIZATION_PRECISION;\n }\n return (borrows * SPOT_MARKET_UTILIZATION_PRECISION) / deposits;\n}\n\n/**\n * Borrow rate (SPOT_MARKET_RATE_PRECISION) at the market's utilization: linear up to the optimal\n * utilization, then Drift's weighted segments up to the max rate, floored at the min rate.\n */\nexport function calculateDriftInterestRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n const utilization = currentUtilization ?? calculateDriftUtilization(bank, delta);\n\n const optimalUtil = BigInt(bank.optimalUtilization);\n const optimalRate = BigInt(bank.optimalBorrowRate);\n const maxRate = BigInt(bank.maxBorrowRate);\n const minRate = BigInt(bank.minBorrowRate) * (PERCENTAGE_PRECISION / 200n);\n\n const segments: [bigint, bigint][] = [\n [850_000n, 50n],\n [900_000n, 100n],\n [950_000n, 150n],\n [990_000n, 200n],\n [995_000n, 250n],\n [SPOT_MARKET_UTILIZATION_PRECISION, 250n],\n ];\n\n let rate: bigint;\n if (utilization <= optimalUtil) {\n const slope = (optimalRate * SPOT_MARKET_UTILIZATION_PRECISION) / optimalUtil;\n rate = (utilization * slope) / SPOT_MARKET_UTILIZATION_PRECISION;\n } else {\n const totalExtraRate = maxRate - optimalRate;\n rate = optimalRate;\n let prevUtil = optimalUtil;\n\n for (const [breakpoint, weight] of segments) {\n const segmentEnd =\n breakpoint > SPOT_MARKET_UTILIZATION_PRECISION\n ? SPOT_MARKET_UTILIZATION_PRECISION\n : breakpoint;\n const segmentRateTotal = (totalExtraRate * weight) / 1000n;\n\n if (utilization <= segmentEnd) {\n rate += (segmentRateTotal * (utilization - prevUtil)) / (segmentEnd - prevUtil);\n break;\n }\n rate += segmentRateTotal;\n prevUtil = segmentEnd;\n }\n }\n\n return rate > minRate ? rate : minRate;\n}\n\n/** Borrow APR, SPOT_MARKET_RATE_PRECISION. */\nexport function calculateDriftBorrowRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return calculateDriftInterestRate(bank, delta, currentUtilization);\n}\n\n/** Deposit APR, SPOT_MARKET_RATE_PRECISION: borrow rate × utilization × (1 − insurance fund factor). */\nexport function calculateDriftDepositRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n const utilization = currentUtilization ?? calculateDriftUtilization(bank, delta);\n const borrowRate = calculateDriftBorrowRate(bank, delta, utilization);\n return (\n (borrowRate * (PERCENTAGE_PRECISION - BigInt(bank.insuranceFund.totalFactor)) * utilization) /\n SPOT_MARKET_UTILIZATION_PRECISION /\n PERCENTAGE_PRECISION\n );\n}\n\n// e^r − 1 by an 8-term Taylor series; rate in SPOT_MARKET_RATE_PRECISION, result in PERCENTAGE_PRECISION.\nfunction continuousApy(rate: bigint): bigint {\n if (rate === 0n) {\n return 0n;\n }\n const precision = 10n ** 18n;\n const r = (rate * precision) / SPOT_MARKET_RATE_PRECISION;\n let term = r;\n let sum = precision + r;\n for (let n = 2n; n <= 8n; n++) {\n term = (term * r) / precision / n;\n sum += term;\n }\n return ((sum - precision) * PERCENTAGE_PRECISION) / precision;\n}\n\n/** Lending APY (continuous compounding), PERCENTAGE_PRECISION. */\nexport function calculateDriftLendingAPY(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return continuousApy(calculateDriftDepositRate(bank, delta, currentUtilization));\n}\n\n/** Lending APR, PERCENTAGE_PRECISION. */\nexport function calculateDriftLendingAPR(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return (\n (calculateDriftDepositRate(bank, delta, currentUtilization) * PERCENTAGE_PRECISION) /\n SPOT_MARKET_RATE_PRECISION\n );\n}\n\n/** Borrow APY (continuous compounding), PERCENTAGE_PRECISION. */\nexport function calculateDriftBorrowAPY(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return continuousApy(calculateDriftBorrowRate(bank, delta, currentUtilization));\n}\n\n/** Borrow APR, PERCENTAGE_PRECISION. */\nexport function calculateDriftBorrowAPR(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return (\n (calculateDriftBorrowRate(bank, delta, currentUtilization) * PERCENTAGE_PRECISION) /\n SPOT_MARKET_RATE_PRECISION\n );\n}\n\nexport interface DriftInterestRateCurvePoint {\n /** Percent (0–100) */\n utilization: number;\n /** Percent */\n borrowAPY: number;\n /** Percent */\n supplyAPY: number;\n}\n\n// 2 slots/s over a 365-day year, matching the Kamino curves.\nconst SLOTS_PER_YEAR = 63_072_000;\n\n/**\n * Borrow and supply APY curve of a Drift spot market at 0–100% utilization (101 points), compounded\n * per slot like the Kamino curves.\n */\nexport function generateDriftReserveCurve(\n spotMarket: DriftSpotMarket\n): DriftInterestRateCurvePoint[] {\n const toApy = (apr: number) =>\n apr === 0 ? 0 : Math.pow(1 + apr / SLOTS_PER_YEAR, SLOTS_PER_YEAR) - 1;\n return Array.from({ length: 101 }, (_, i) => {\n const utilization = BigInt(Math.floor((i / 100) * Number(SPOT_MARKET_UTILIZATION_PRECISION)));\n const borrowApr =\n Number(calculateDriftBorrowRate(spotMarket, 0n, utilization)) /\n Number(SPOT_MARKET_RATE_PRECISION);\n const supplyApr =\n Number(calculateDriftDepositRate(spotMarket, 0n, utilization)) /\n Number(SPOT_MARKET_RATE_PRECISION);\n return {\n utilization: i,\n borrowAPY: toApy(borrowApr) * 100,\n supplyAPY: toApy(supplyApr) * 100,\n };\n });\n}\n","import { address, type Address, type GetMultipleAccountsApi, type Rpc } from \"@solana/kit\";\n\nimport { deriveDriftSpotMarket } from \"./pda\";\nimport type { DriftRewards, DriftSpotMarket, DriftUser } from \"./types\";\n\nimport { fetchAllMaybeSpotMarket } from \"~/generated/drift\";\n\nconst USDC_MINT = address(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\");\n\n/** Returns `spotMarkets` plus any market in `marketIndexes` not among them, fetched. */\nasync function withMissingMarkets(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n marketIndexes: Iterable<number>\n): Promise<Map<number, DriftSpotMarket>> {\n const markets = new Map(spotMarkets.map((market) => [market.marketIndex, market]));\n const missing = [...new Set(marketIndexes)].filter((index) => !markets.has(index));\n const addresses = await Promise.all(\n missing.map(async (index) => (await deriveDriftSpotMarket(index))[0])\n );\n for (const account of addresses.length ? await fetchAllMaybeSpotMarket(rpc, addresses) : []) {\n if (account.exists) {\n markets.set(account.data.marketIndex, account.data);\n } else {\n console.error(\"Missing Drift spot market account\", account.address);\n }\n }\n return markets;\n}\n\n/**\n * Drift rewards of each bank. Rewards are credited as extra spot positions on the bank's Drift user:\n * positions are `[USDC, token, ...rewards]` (`[USDC, ...rewards]` for a USDC bank). Reward markets\n * not in `spotMarkets` are fetched.\n * @returns rewards keyed by bank address\n */\nexport async function getDriftRewards(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n userStates: { bankAddress: Address; marketMint: Address; driftUser: DriftUser }[]\n): Promise<Map<Address, DriftRewards[]>> {\n const rewardsByBank = userStates.map((userState) => ({\n userState,\n rewards: userState.driftUser.spotPositions\n .slice(userState.marketMint === USDC_MINT ? 1 : 2)\n .filter((position) => position.marketIndex !== 0),\n }));\n\n const markets = await withMissingMarkets(\n rpc,\n spotMarkets,\n rewardsByBank.flatMap(({ rewards }) => rewards.map((reward) => reward.marketIndex))\n );\n\n return new Map(\n await Promise.all(\n rewardsByBank.map(async ({ userState, rewards }) => {\n const driftRewards: DriftRewards[] = [];\n for (const reward of rewards) {\n const market = markets.get(reward.marketIndex);\n if (!market) {\n console.error(\"Missing Drift spot market\", reward.marketIndex);\n continue;\n }\n driftRewards.push({\n oracle: market.oracle,\n marketIndex: reward.marketIndex,\n spotMarket: (await deriveDriftSpotMarket(reward.marketIndex))[0],\n mint: market.mint,\n spotPosition: reward,\n });\n }\n return [userState.bankAddress, driftRewards] as const;\n })\n )\n );\n}\n\n/** `spotMarkets` plus every market any of `driftUsers` has a position in, fetched if missing. */\nexport async function getAllRequiredMarkets(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n driftUsers: DriftUser[]\n): Promise<DriftSpotMarket[]> {\n const markets = await withMissingMarkets(\n rpc,\n spotMarkets,\n driftUsers.flatMap((user) => user.spotPositions.map((position) => position.marketIndex))\n );\n return [...markets.values()];\n}\n","import { address } from \"@solana/kit\";\n\nimport type {\n DriftRewards,\n DriftRewardsJSON,\n DriftSpotMarket,\n DriftSpotMarketJSON,\n DriftSpotPosition,\n DriftSpotPositionJSON,\n DriftUser,\n DriftUserJSON,\n DriftUserStats,\n DriftUserStatsJSON,\n} from \"./types\";\n\nfunction spotPositionToDto(position: DriftSpotPosition): DriftSpotPositionJSON {\n return {\n scaledBalance: position.scaledBalance.toString(),\n openBids: position.openBids.toString(),\n openAsks: position.openAsks.toString(),\n cumulativeDeposits: position.cumulativeDeposits.toString(),\n marketIndex: position.marketIndex,\n balanceType: position.balanceType,\n openOrders: position.openOrders,\n padding: [...position.padding],\n };\n}\n\nfunction dtoToSpotPosition(dto: DriftSpotPositionJSON): DriftSpotPosition {\n return {\n scaledBalance: BigInt(dto.scaledBalance),\n openBids: BigInt(dto.openBids),\n openAsks: BigInt(dto.openAsks),\n cumulativeDeposits: BigInt(dto.cumulativeDeposits),\n marketIndex: dto.marketIndex,\n balanceType: dto.balanceType,\n openOrders: dto.openOrders,\n padding: Uint8Array.from(dto.padding),\n };\n}\n\n/** Serializes a Drift spot market (or a decoded `SpotMarket`) to its JSON DTO. */\nexport function driftSpotMarketRawToDto(market: DriftSpotMarket): DriftSpotMarketJSON {\n return {\n pubkey: market.pubkey,\n oracle: market.oracle,\n mint: market.mint,\n decimals: market.decimals,\n marketIndex: market.marketIndex,\n cumulativeDepositInterest: market.cumulativeDepositInterest.toString(),\n cumulativeBorrowInterest: market.cumulativeBorrowInterest.toString(),\n depositBalance: market.depositBalance.toString(),\n borrowBalance: market.borrowBalance.toString(),\n optimalUtilization: market.optimalUtilization,\n optimalBorrowRate: market.optimalBorrowRate,\n maxBorrowRate: market.maxBorrowRate,\n minBorrowRate: market.minBorrowRate,\n insuranceFund: { totalFactor: market.insuranceFund.totalFactor },\n poolId: market.poolId,\n };\n}\n\n/**\n * Parses a Drift spot market DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftSpotMarketRaw(dto: DriftSpotMarketJSON): DriftSpotMarket {\n return {\n pubkey: address(dto.pubkey),\n oracle: address(dto.oracle),\n mint: address(dto.mint),\n decimals: dto.decimals,\n marketIndex: dto.marketIndex,\n cumulativeDepositInterest: BigInt(dto.cumulativeDepositInterest),\n cumulativeBorrowInterest: BigInt(dto.cumulativeBorrowInterest),\n depositBalance: BigInt(dto.depositBalance),\n borrowBalance: BigInt(dto.borrowBalance),\n optimalUtilization: dto.optimalUtilization,\n optimalBorrowRate: dto.optimalBorrowRate,\n maxBorrowRate: dto.maxBorrowRate,\n minBorrowRate: dto.minBorrowRate,\n insuranceFund: { totalFactor: dto.insuranceFund.totalFactor },\n poolId: dto.poolId,\n };\n}\n\n/** Serializes a Drift user (or a decoded `User`) to its JSON DTO. */\nexport function driftUserRawToDto(user: DriftUser): DriftUserJSON {\n return {\n authority: user.authority,\n spotPositions: user.spotPositions.map(spotPositionToDto),\n };\n}\n\n/**\n * Parses a Drift user DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftUserRaw(dto: DriftUserJSON): DriftUser {\n return {\n authority: address(dto.authority),\n spotPositions: dto.spotPositions.map(dtoToSpotPosition),\n };\n}\n\n/** Serializes Drift rewards to their JSON DTO. */\nexport function driftRewardsRawToDto(rewards: DriftRewards): DriftRewardsJSON {\n return {\n oracle: rewards.oracle,\n marketIndex: rewards.marketIndex,\n spotMarket: rewards.spotMarket,\n mint: rewards.mint,\n spotPosition: spotPositionToDto(rewards.spotPosition),\n };\n}\n\n/**\n * Parses a Drift rewards DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftRewardsRaw(dto: DriftRewardsJSON): DriftRewards {\n return {\n oracle: address(dto.oracle),\n marketIndex: dto.marketIndex,\n spotMarket: address(dto.spotMarket),\n mint: address(dto.mint),\n spotPosition: dtoToSpotPosition(dto.spotPosition),\n };\n}\n\n/** Serializes Drift user stats (or a decoded `UserStats`) to their JSON DTO. */\nexport function driftUserStatsRawToDto(stats: DriftUserStats): DriftUserStatsJSON {\n return {\n authority: stats.authority,\n referrer: stats.referrer,\n fees: {\n totalFeePaid: stats.fees.totalFeePaid.toString(),\n totalFeeRebate: stats.fees.totalFeeRebate.toString(),\n totalTokenDiscount: stats.fees.totalTokenDiscount.toString(),\n totalRefereeDiscount: stats.fees.totalRefereeDiscount.toString(),\n totalReferrerReward: stats.fees.totalReferrerReward.toString(),\n currentEpochReferrerReward: stats.fees.currentEpochReferrerReward.toString(),\n },\n nextEpochTs: stats.nextEpochTs.toString(),\n makerVolume30d: stats.makerVolume30d.toString(),\n takerVolume30d: stats.takerVolume30d.toString(),\n fillerVolume30d: stats.fillerVolume30d.toString(),\n lastMakerVolume30dTs: stats.lastMakerVolume30dTs.toString(),\n lastTakerVolume30dTs: stats.lastTakerVolume30dTs.toString(),\n lastFillerVolume30dTs: stats.lastFillerVolume30dTs.toString(),\n ifStakedQuoteAssetAmount: stats.ifStakedQuoteAssetAmount.toString(),\n numberOfSubAccounts: stats.numberOfSubAccounts,\n numberOfSubAccountsCreated: stats.numberOfSubAccountsCreated,\n referrerStatus: stats.referrerStatus,\n disableUpdatePerpBidAskTwap: stats.disableUpdatePerpBidAskTwap,\n pausedOperations: stats.pausedOperations,\n fuelOverflowStatus: stats.fuelOverflowStatus,\n fuelInsurance: stats.fuelInsurance,\n fuelDeposits: stats.fuelDeposits,\n fuelBorrows: stats.fuelBorrows,\n fuelPositions: stats.fuelPositions,\n fuelTaker: stats.fuelTaker,\n fuelMaker: stats.fuelMaker,\n ifStakedGovTokenAmount: stats.ifStakedGovTokenAmount.toString(),\n lastFuelIfBonusUpdateTs: stats.lastFuelIfBonusUpdateTs,\n padding: [...stats.padding],\n };\n}\n\n/**\n * Parses a Drift user stats DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftUserStatsRaw(dto: DriftUserStatsJSON): DriftUserStats {\n return {\n authority: address(dto.authority),\n referrer: address(dto.referrer),\n fees: {\n totalFeePaid: BigInt(dto.fees.totalFeePaid),\n totalFeeRebate: BigInt(dto.fees.totalFeeRebate),\n totalTokenDiscount: BigInt(dto.fees.totalTokenDiscount),\n totalRefereeDiscount: BigInt(dto.fees.totalRefereeDiscount),\n totalReferrerReward: BigInt(dto.fees.totalReferrerReward),\n currentEpochReferrerReward: BigInt(dto.fees.currentEpochReferrerReward),\n },\n nextEpochTs: BigInt(dto.nextEpochTs),\n makerVolume30d: BigInt(dto.makerVolume30d),\n takerVolume30d: BigInt(dto.takerVolume30d),\n fillerVolume30d: BigInt(dto.fillerVolume30d),\n lastMakerVolume30dTs: BigInt(dto.lastMakerVolume30dTs),\n lastTakerVolume30dTs: BigInt(dto.lastTakerVolume30dTs),\n lastFillerVolume30dTs: BigInt(dto.lastFillerVolume30dTs),\n ifStakedQuoteAssetAmount: BigInt(dto.ifStakedQuoteAssetAmount),\n numberOfSubAccounts: dto.numberOfSubAccounts,\n numberOfSubAccountsCreated: dto.numberOfSubAccountsCreated,\n referrerStatus: dto.referrerStatus,\n disableUpdatePerpBidAskTwap: dto.disableUpdatePerpBidAskTwap,\n pausedOperations: dto.pausedOperations,\n fuelOverflowStatus: dto.fuelOverflowStatus,\n fuelInsurance: dto.fuelInsurance,\n fuelDeposits: dto.fuelDeposits,\n fuelBorrows: dto.fuelBorrows,\n fuelPositions: dto.fuelPositions,\n fuelTaker: dto.fuelTaker,\n fuelMaker: dto.fuelMaker,\n ifStakedGovTokenAmount: BigInt(dto.ifStakedGovTokenAmount),\n lastFuelIfBonusUpdateTs: dto.lastFuelIfBonusUpdateTs,\n padding: Uint8Array.from(dto.padding),\n };\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\n\nimport { decodeDriftSpotMarket, decodeDriftUser } from \"./accounts\";\nimport { getAllRequiredMarkets, getDriftRewards } from \"./rewards\";\nimport { driftRewardsRawToDto, driftSpotMarketRawToDto, driftUserRawToDto } from \"./serialize\";\nimport type { DriftBankInput, DriftStates, DriftStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link DriftStates}, keyed by bank address. Reward markets not among the\n * banks' markets are fetched too. Banks with a default venue address or a missing spot market or\n * user are left out.\n * @throws if a fetched account isn't the Drift account it should be\n */\nexport async function fetchDriftStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: DriftBankInput[]\n): Promise<Record<string, DriftStates>> {\n const validBanks = banks.filter(\n (bank) => bank.spotMarket !== DEFAULT_ADDRESS && bank.user !== DEFAULT_ADDRESS\n );\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.flatMap((bank) => [bank.spotMarket, bank.user])\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const [spotMarket, user] = accounts.slice(2 * i, 2 * i + 2);\n return spotMarket && user\n ? [\n {\n bankAddress: bank.bankAddress,\n spotMarketState: decodeDriftSpotMarket(spotMarket.data),\n userState: decodeDriftUser(user.data),\n },\n ]\n : [];\n });\n\n const markets = await getAllRequiredMarkets(\n rpc,\n decoded.map(({ spotMarketState }) => spotMarketState),\n decoded.map(({ userState }) => userState)\n );\n const rewards = await getDriftRewards(\n rpc,\n markets,\n decoded.map(({ bankAddress, spotMarketState, userState }) => ({\n bankAddress,\n marketMint: spotMarketState.mint,\n driftUser: userState,\n }))\n );\n\n return Object.fromEntries(\n decoded.map(({ bankAddress, spotMarketState, userState }) => [\n bankAddress,\n { spotMarketState, userState, userRewards: rewards.get(bankAddress) ?? [] },\n ])\n );\n}\n\n/**\n * {@link fetchDriftStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchDriftStates}\n */\nexport async function fetchDriftStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: DriftBankInput[]\n): Promise<Record<string, DriftStatesJSON>> {\n const states = await fetchDriftStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, { spotMarketState, userState, userRewards }]) => [\n bank,\n {\n spotMarketState: driftSpotMarketRawToDto(spotMarketState),\n userState: driftUserRawToDto(userState),\n userRewards: userRewards.map(driftRewardsRawToDto),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LENDING_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 135, 199, 82, 16, 249, 131, 182, 241,\n]);\n\nexport function getLendingDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LENDING_DISCRIMINATOR);\n}\n\nexport type Lending = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n fTokenMint: Address;\n lendingId: number;\n /** @dev number of decimals for the fToken, same as ASSET */\n decimals: number;\n /** @dev To read PDA of rewards rate model to get_rate instruction */\n rewardsRateModel: Address;\n /** @dev exchange price for the underlying asset in the liquidity protocol (without rewards) */\n liquidityExchangePrice: bigint;\n /** @dev exchange price between fToken and the underlying asset (with rewards) */\n tokenExchangePrice: bigint;\n /** @dev timestamp when exchange prices were updated the last time */\n lastUpdateTimestamp: bigint;\n tokenReservesLiquidity: Address;\n supplyPositionOnLiquidity: Address;\n bump: number;\n};\n\nexport type LendingArgs = {\n mint: Address;\n fTokenMint: Address;\n lendingId: number;\n /** @dev number of decimals for the fToken, same as ASSET */\n decimals: number;\n /** @dev To read PDA of rewards rate model to get_rate instruction */\n rewardsRateModel: Address;\n /** @dev exchange price for the underlying asset in the liquidity protocol (without rewards) */\n liquidityExchangePrice: number | bigint;\n /** @dev exchange price between fToken and the underlying asset (with rewards) */\n tokenExchangePrice: number | bigint;\n /** @dev timestamp when exchange prices were updated the last time */\n lastUpdateTimestamp: number | bigint;\n tokenReservesLiquidity: Address;\n supplyPositionOnLiquidity: Address;\n bump: number;\n};\n\n/** Gets the encoder for {@link LendingArgs} account data. */\nexport function getLendingEncoder(): FixedSizeEncoder<LendingArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"fTokenMint\", getAddressEncoder()],\n [\"lendingId\", getU16Encoder()],\n [\"decimals\", getU8Encoder()],\n [\"rewardsRateModel\", getAddressEncoder()],\n [\"liquidityExchangePrice\", getU64Encoder()],\n [\"tokenExchangePrice\", getU64Encoder()],\n [\"lastUpdateTimestamp\", getU64Encoder()],\n [\"tokenReservesLiquidity\", getAddressEncoder()],\n [\"supplyPositionOnLiquidity\", getAddressEncoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: LENDING_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Lending} account data. */\nexport function getLendingDecoder(): FixedSizeDecoder<Lending> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"fTokenMint\", getAddressDecoder()],\n [\"lendingId\", getU16Decoder()],\n [\"decimals\", getU8Decoder()],\n [\"rewardsRateModel\", getAddressDecoder()],\n [\"liquidityExchangePrice\", getU64Decoder()],\n [\"tokenExchangePrice\", getU64Decoder()],\n [\"lastUpdateTimestamp\", getU64Decoder()],\n [\"tokenReservesLiquidity\", getAddressDecoder()],\n [\"supplyPositionOnLiquidity\", getAddressDecoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link Lending} account data. */\nexport function getLendingCodec(): FixedSizeCodec<LendingArgs, Lending> {\n return combineCodec(getLendingEncoder(), getLendingDecoder());\n}\n\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Lending, TAddress>;\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Lending, TAddress>;\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Lending, TAddress> | MaybeAccount<Lending, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getLendingDecoder());\n}\n\nexport async function fetchLending<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Lending, TAddress>> {\n const maybeAccount = await fetchMaybeLending(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLending<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Lending, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLending(maybeAccount);\n}\n\nexport async function fetchAllLending(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Lending>[]> {\n const maybeAccounts = await fetchAllMaybeLending(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLending(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Lending>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLending(maybeAccount));\n}\n\nexport function getLendingSize(): number {\n return 196;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 166, 72, 71, 131, 172, 74, 166, 181,\n]);\n\nexport function getLendingRewardsRateModelDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR);\n}\n\nexport type LendingRewardsRateModel = {\n discriminator: ReadonlyUint8Array;\n /** @dev mint address */\n mint: Address;\n /**\n * @dev tvl below which rewards rate is 0. If current TVL is below this value, triggering `update_rate()` on the fToken\n * might bring the total TVL above this cut-off.\n */\n startTvl: bigint;\n /** @dev for how long current rewards should run */\n duration: bigint;\n /** @dev when current rewards got started */\n startTime: bigint;\n /** @dev current annualized reward based on input params (duration, rewardAmount) */\n yearlyReward: bigint;\n /** @dev Duration for the next rewards phase */\n nextDuration: bigint;\n /** @dev Amount of rewards for the next phase */\n nextRewardAmount: bigint;\n bump: number;\n};\n\nexport type LendingRewardsRateModelArgs = {\n /** @dev mint address */\n mint: Address;\n /**\n * @dev tvl below which rewards rate is 0. If current TVL is below this value, triggering `update_rate()` on the fToken\n * might bring the total TVL above this cut-off.\n */\n startTvl: number | bigint;\n /** @dev for how long current rewards should run */\n duration: number | bigint;\n /** @dev when current rewards got started */\n startTime: number | bigint;\n /** @dev current annualized reward based on input params (duration, rewardAmount) */\n yearlyReward: number | bigint;\n /** @dev Duration for the next rewards phase */\n nextDuration: number | bigint;\n /** @dev Amount of rewards for the next phase */\n nextRewardAmount: number | bigint;\n bump: number;\n};\n\n/** Gets the encoder for {@link LendingRewardsRateModelArgs} account data. */\nexport function getLendingRewardsRateModelEncoder(): FixedSizeEncoder<LendingRewardsRateModelArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"startTvl\", getU64Encoder()],\n [\"duration\", getU64Encoder()],\n [\"startTime\", getU64Encoder()],\n [\"yearlyReward\", getU64Encoder()],\n [\"nextDuration\", getU64Encoder()],\n [\"nextRewardAmount\", getU64Encoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link LendingRewardsRateModel} account data. */\nexport function getLendingRewardsRateModelDecoder(): FixedSizeDecoder<LendingRewardsRateModel> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"startTvl\", getU64Decoder()],\n [\"duration\", getU64Decoder()],\n [\"startTime\", getU64Decoder()],\n [\"yearlyReward\", getU64Decoder()],\n [\"nextDuration\", getU64Decoder()],\n [\"nextRewardAmount\", getU64Decoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link LendingRewardsRateModel} account data. */\nexport function getLendingRewardsRateModelCodec(): FixedSizeCodec<\n LendingRewardsRateModelArgs,\n LendingRewardsRateModel\n> {\n return combineCodec(getLendingRewardsRateModelEncoder(), getLendingRewardsRateModelDecoder());\n}\n\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<LendingRewardsRateModel, TAddress>;\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<LendingRewardsRateModel, TAddress>;\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<LendingRewardsRateModel, TAddress> | MaybeAccount<LendingRewardsRateModel, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getLendingRewardsRateModelDecoder()\n );\n}\n\nexport async function fetchLendingRewardsRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<LendingRewardsRateModel, TAddress>> {\n const maybeAccount = await fetchMaybeLendingRewardsRateModel(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLendingRewardsRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<LendingRewardsRateModel, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLendingRewardsRateModel(maybeAccount);\n}\n\nexport async function fetchAllLendingRewardsRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<LendingRewardsRateModel>[]> {\n const maybeAccounts = await fetchAllMaybeLendingRewardsRateModel(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLendingRewardsRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<LendingRewardsRateModel>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLendingRewardsRateModel(maybeAccount));\n}\n\nexport function getLendingRewardsRateModelSize(): number {\n return 89;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type FTokenMintSeeds = {\n mint: Address;\n};\n\nexport async function findFTokenMintPda(\n seeds: FTokenMintSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([102, 95, 116, 111, 107, 101, 110, 95, 109, 105, 110, 116])\n ),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type LendingSeeds = {\n mint: Address;\n fTokenMint: Address;\n};\n\nexport async function findLendingPda(\n seeds: LendingSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([108, 101, 110, 100, 105, 110, 103])),\n getAddressEncoder().encode(seeds.mint),\n getAddressEncoder().encode(seeds.fTokenMint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport async function findLendingAdminPda(\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([108, 101, 110, 100, 105, 110, 103, 95, 97, 100, 109, 105, 110])\n ),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getLendingCodec,\n getLendingRewardsRateModelCodec,\n type Lending,\n type LendingArgs,\n type LendingRewardsRateModel,\n type LendingRewardsRateModelArgs,\n} from \"../accounts\";\nimport {\n getUpdateRateInstruction,\n parseUpdateRateInstruction,\n type ParsedUpdateRateInstruction,\n type UpdateRateInput,\n} from \"../instructions\";\nimport { findFTokenMintPda, findLendingAdminPda, findLendingPda } from \"../pdas\";\n\nexport const LENDING_PROGRAM_ADDRESS =\n \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">;\n\nexport enum LendingAccount {\n Lending,\n LendingRewardsRateModel,\n}\n\nexport function identifyLendingAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LendingAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([135, 199, 82, 16, 249, 131, 182, 241])\n ),\n 0\n )\n ) {\n return LendingAccount.Lending;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([166, 72, 71, 131, 172, 74, 166, 181])\n ),\n 0\n )\n ) {\n return LendingAccount.LendingRewardsRateModel;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"lending\",\n });\n}\n\nexport enum LendingInstruction {\n UpdateRate,\n}\n\nexport function identifyLendingInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LendingInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([24, 225, 53, 189, 72, 212, 225, 178])\n ),\n 0\n )\n ) {\n return LendingInstruction.UpdateRate;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"lending\",\n });\n}\n\nexport type ParsedLendingInstruction<\n TProgram extends string = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\",\n> = { instructionType: LendingInstruction.UpdateRate } & ParsedUpdateRateInstruction<TProgram>;\n\nexport function parseLendingInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedLendingInstruction<TProgram> {\n const instructionType = identifyLendingInstruction(instruction);\n switch (instructionType) {\n case LendingInstruction.UpdateRate: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: LendingInstruction.UpdateRate,\n ...parseUpdateRateInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"lending\",\n });\n }\n}\n\nexport type LendingPlugin = {\n accounts: LendingPluginAccounts;\n instructions: LendingPluginInstructions;\n pdas: LendingPluginPdas;\n identifyAccount: typeof identifyLendingAccount;\n identifyInstruction: typeof identifyLendingInstruction;\n parseInstruction: typeof parseLendingInstruction;\n};\n\nexport type LendingPluginAccounts = {\n lending: ReturnType<typeof getLendingCodec> & SelfFetchFunctions<LendingArgs, Lending>;\n lendingRewardsRateModel: ReturnType<typeof getLendingRewardsRateModelCodec> &\n SelfFetchFunctions<LendingRewardsRateModelArgs, LendingRewardsRateModel>;\n};\n\nexport type LendingPluginInstructions = {\n updateRate: (\n input: UpdateRateInput\n ) => ReturnType<typeof getUpdateRateInstruction> & SelfPlanAndSendFunctions;\n};\n\nexport type LendingPluginPdas = {\n fTokenMint: typeof findFTokenMintPda;\n lending: typeof findLendingPda;\n lendingAdmin: typeof findLendingAdminPda;\n};\n\nexport type LendingPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function lendingProgram() {\n return <T extends LendingPluginRequirements>(\n client: T\n ): ExtendedClient<T, { lending: LendingPlugin }> => {\n return extendClient(client, {\n lending: <LendingPlugin>{\n accounts: {\n lending: addSelfFetchFunctions(client, getLendingCodec()),\n lendingRewardsRateModel: addSelfFetchFunctions(client, getLendingRewardsRateModelCodec()),\n },\n instructions: {\n updateRate: (input) =>\n addSelfPlanAndSendFunctions(client, getUpdateRateInstruction(input)),\n },\n pdas: {\n fTokenMint: findFTokenMintPda,\n lending: findLendingPda,\n lendingAdmin: findLendingAdminPda,\n },\n identifyAccount: identifyLendingAccount,\n identifyInstruction: identifyLendingInstruction,\n parseInstruction: parseLendingInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const UPDATE_RATE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 24, 225, 53, 189, 72, 212, 225, 178,\n]);\n\nexport function getUpdateRateDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(UPDATE_RATE_DISCRIMINATOR);\n}\n\nexport type UpdateRateInstruction<\n TProgram extends string = typeof LENDING_PROGRAM_ADDRESS,\n TAccountLending extends string | AccountMeta<string> = string,\n TAccountMint extends string | AccountMeta<string> = string,\n TAccountFTokenMint extends string | AccountMeta<string> = string,\n TAccountSupplyTokenReservesLiquidity extends string | AccountMeta<string> = string,\n TAccountRewardsRateModel extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountLending extends string ? WritableAccount<TAccountLending> : TAccountLending,\n TAccountMint extends string ? ReadonlyAccount<TAccountMint> : TAccountMint,\n TAccountFTokenMint extends string ? ReadonlyAccount<TAccountFTokenMint> : TAccountFTokenMint,\n TAccountSupplyTokenReservesLiquidity extends string\n ? ReadonlyAccount<TAccountSupplyTokenReservesLiquidity>\n : TAccountSupplyTokenReservesLiquidity,\n TAccountRewardsRateModel extends string\n ? ReadonlyAccount<TAccountRewardsRateModel>\n : TAccountRewardsRateModel,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type UpdateRateInstructionDataArgs = {};\n\nexport function getUpdateRateInstructionDataEncoder(): FixedSizeEncoder<UpdateRateInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: UPDATE_RATE_DISCRIMINATOR })\n );\n}\n\nexport function getUpdateRateInstructionDataDecoder(): FixedSizeDecoder<UpdateRateInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getUpdateRateInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInstructionDataArgs,\n UpdateRateInstructionData\n> {\n return combineCodec(getUpdateRateInstructionDataEncoder(), getUpdateRateInstructionDataDecoder());\n}\n\nexport type UpdateRateInput<\n TAccountLending extends InstructionAccountInput = InstructionAccountInput,\n TAccountMint extends InstructionAccountInput = InstructionAccountInput,\n TAccountFTokenMint extends InstructionAccountInput = InstructionAccountInput,\n TAccountSupplyTokenReservesLiquidity extends InstructionAccountInput = InstructionAccountInput,\n TAccountRewardsRateModel extends InstructionAccountInput = InstructionAccountInput,\n> = {\n lending: TAccountLending;\n mint: TAccountMint;\n fTokenMint: TAccountFTokenMint;\n supplyTokenReservesLiquidity: TAccountSupplyTokenReservesLiquidity;\n rewardsRateModel: TAccountRewardsRateModel;\n};\n\nexport function getUpdateRateInstruction<\n TAccountLending extends InstructionAccountInput,\n TAccountMint extends InstructionAccountInput,\n TAccountFTokenMint extends InstructionAccountInput,\n TAccountSupplyTokenReservesLiquidity extends InstructionAccountInput,\n TAccountRewardsRateModel extends InstructionAccountInput,\n TProgramAddress extends Address = typeof LENDING_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInput<\n TAccountLending,\n TAccountMint,\n TAccountFTokenMint,\n TAccountSupplyTokenReservesLiquidity,\n TAccountRewardsRateModel\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountLending, InstructionAccountInputAddress<TAccountLending>>,\n ResolvedInstructionAccountMeta<TAccountMint, InstructionAccountInputAddress<TAccountMint>>,\n ResolvedInstructionAccountMeta<\n TAccountFTokenMint,\n InstructionAccountInputAddress<TAccountFTokenMint>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSupplyTokenReservesLiquidity,\n InstructionAccountInputAddress<TAccountSupplyTokenReservesLiquidity>\n >,\n ResolvedInstructionAccountMeta<\n TAccountRewardsRateModel,\n InstructionAccountInputAddress<TAccountRewardsRateModel>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n lending: { value: input.lending ?? null, isSigner: false, isWritable: true },\n mint: { value: input.mint ?? null, isSigner: false, isWritable: false },\n fTokenMint: { value: input.fTokenMint ?? null, isSigner: false, isWritable: false },\n supplyTokenReservesLiquidity: {\n value: input.supplyTokenReservesLiquidity ?? null,\n isSigner: false,\n isWritable: false,\n },\n rewardsRateModel: { value: input.rewardsRateModel ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"lending\", accounts.lending),\n getAccountMeta(\"mint\", accounts.mint),\n getAccountMeta(\"fTokenMint\", accounts.fTokenMint),\n getAccountMeta(\"supplyTokenReservesLiquidity\", accounts.supplyTokenReservesLiquidity),\n getAccountMeta(\"rewardsRateModel\", accounts.rewardsRateModel),\n ],\n data: getUpdateRateInstructionDataEncoder().encode({}),\n programAddress,\n } as UpdateRateInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLending,\n InstructionAccountInputAddress<TAccountLending>\n >,\n ResolvedInstructionAccountMeta<TAccountMint, InstructionAccountInputAddress<TAccountMint>>,\n ResolvedInstructionAccountMeta<\n TAccountFTokenMint,\n InstructionAccountInputAddress<TAccountFTokenMint>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSupplyTokenReservesLiquidity,\n InstructionAccountInputAddress<TAccountSupplyTokenReservesLiquidity>\n >,\n ResolvedInstructionAccountMeta<\n TAccountRewardsRateModel,\n InstructionAccountInputAddress<TAccountRewardsRateModel>\n >\n >);\n}\n\nexport type ParsedUpdateRateInstruction<\n TProgram extends string = typeof LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n lending: TAccountMetas[0];\n mint: TAccountMetas[1];\n fTokenMint: TAccountMetas[2];\n supplyTokenReservesLiquidity: TAccountMetas[3];\n rewardsRateModel: TAccountMetas[4];\n };\n data: UpdateRateInstructionData;\n};\n\nexport function parseUpdateRateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedUpdateRateInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 5) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 5,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n lending: getNextAccount(),\n mint: getNextAccount(),\n fTokenMint: getNextAccount(),\n supplyTokenReservesLiquidity: getNextAccount(),\n rewardsRateModel: getNextAccount(),\n },\n data: getUpdateRateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const RATE_MODEL_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 94, 3, 203, 219, 107, 137, 4, 162,\n]);\n\nexport function getRateModelDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(RATE_MODEL_DISCRIMINATOR);\n}\n\nexport type RateModel = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n version: number;\n rateAtZero: number;\n kink1Utilization: number;\n rateAtKink1: number;\n rateAtMax: number;\n kink2Utilization: number;\n rateAtKink2: number;\n};\n\nexport type RateModelArgs = {\n mint: Address;\n version: number;\n rateAtZero: number;\n kink1Utilization: number;\n rateAtKink1: number;\n rateAtMax: number;\n kink2Utilization: number;\n rateAtKink2: number;\n};\n\n/** Gets the encoder for {@link RateModelArgs} account data. */\nexport function getRateModelEncoder(): FixedSizeEncoder<RateModelArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"version\", getU8Encoder()],\n [\"rateAtZero\", getU16Encoder()],\n [\"kink1Utilization\", getU16Encoder()],\n [\"rateAtKink1\", getU16Encoder()],\n [\"rateAtMax\", getU16Encoder()],\n [\"kink2Utilization\", getU16Encoder()],\n [\"rateAtKink2\", getU16Encoder()],\n ]),\n (value) => ({ ...value, discriminator: RATE_MODEL_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link RateModel} account data. */\nexport function getRateModelDecoder(): FixedSizeDecoder<RateModel> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"version\", getU8Decoder()],\n [\"rateAtZero\", getU16Decoder()],\n [\"kink1Utilization\", getU16Decoder()],\n [\"rateAtKink1\", getU16Decoder()],\n [\"rateAtMax\", getU16Decoder()],\n [\"kink2Utilization\", getU16Decoder()],\n [\"rateAtKink2\", getU16Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link RateModel} account data. */\nexport function getRateModelCodec(): FixedSizeCodec<RateModelArgs, RateModel> {\n return combineCodec(getRateModelEncoder(), getRateModelDecoder());\n}\n\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<RateModel, TAddress>;\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<RateModel, TAddress>;\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<RateModel, TAddress> | MaybeAccount<RateModel, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getRateModelDecoder());\n}\n\nexport async function fetchRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<RateModel, TAddress>> {\n const maybeAccount = await fetchMaybeRateModel(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<RateModel, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeRateModel(maybeAccount);\n}\n\nexport async function fetchAllRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<RateModel>[]> {\n const maybeAccounts = await fetchAllMaybeRateModel(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<RateModel>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeRateModel(maybeAccount));\n}\n\nexport function getRateModelSize(): number {\n return 53;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const TOKEN_RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 21, 18, 59, 135, 120, 20, 31, 12,\n]);\n\nexport function getTokenReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(TOKEN_RESERVE_DISCRIMINATOR);\n}\n\nexport type TokenReserve = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n vault: Address;\n borrowRate: number;\n feeOnInterest: number;\n lastUtilization: number;\n lastUpdateTimestamp: bigint;\n supplyExchangePrice: bigint;\n borrowExchangePrice: bigint;\n maxUtilization: number;\n totalSupplyWithInterest: bigint;\n totalSupplyInterestFree: bigint;\n totalBorrowWithInterest: bigint;\n totalBorrowInterestFree: bigint;\n totalClaimAmount: bigint;\n interactingProtocol: Address;\n interactingTimestamp: bigint;\n interactingBalance: bigint;\n};\n\nexport type TokenReserveArgs = {\n mint: Address;\n vault: Address;\n borrowRate: number;\n feeOnInterest: number;\n lastUtilization: number;\n lastUpdateTimestamp: number | bigint;\n supplyExchangePrice: number | bigint;\n borrowExchangePrice: number | bigint;\n maxUtilization: number;\n totalSupplyWithInterest: number | bigint;\n totalSupplyInterestFree: number | bigint;\n totalBorrowWithInterest: number | bigint;\n totalBorrowInterestFree: number | bigint;\n totalClaimAmount: number | bigint;\n interactingProtocol: Address;\n interactingTimestamp: number | bigint;\n interactingBalance: number | bigint;\n};\n\n/** Gets the encoder for {@link TokenReserveArgs} account data. */\nexport function getTokenReserveEncoder(): FixedSizeEncoder<TokenReserveArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"vault\", getAddressEncoder()],\n [\"borrowRate\", getU16Encoder()],\n [\"feeOnInterest\", getU16Encoder()],\n [\"lastUtilization\", getU16Encoder()],\n [\"lastUpdateTimestamp\", getU64Encoder()],\n [\"supplyExchangePrice\", getU64Encoder()],\n [\"borrowExchangePrice\", getU64Encoder()],\n [\"maxUtilization\", getU16Encoder()],\n [\"totalSupplyWithInterest\", getU64Encoder()],\n [\"totalSupplyInterestFree\", getU64Encoder()],\n [\"totalBorrowWithInterest\", getU64Encoder()],\n [\"totalBorrowInterestFree\", getU64Encoder()],\n [\"totalClaimAmount\", getU64Encoder()],\n [\"interactingProtocol\", getAddressEncoder()],\n [\"interactingTimestamp\", getU64Encoder()],\n [\"interactingBalance\", getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TOKEN_RESERVE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link TokenReserve} account data. */\nexport function getTokenReserveDecoder(): FixedSizeDecoder<TokenReserve> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"vault\", getAddressDecoder()],\n [\"borrowRate\", getU16Decoder()],\n [\"feeOnInterest\", getU16Decoder()],\n [\"lastUtilization\", getU16Decoder()],\n [\"lastUpdateTimestamp\", getU64Decoder()],\n [\"supplyExchangePrice\", getU64Decoder()],\n [\"borrowExchangePrice\", getU64Decoder()],\n [\"maxUtilization\", getU16Decoder()],\n [\"totalSupplyWithInterest\", getU64Decoder()],\n [\"totalSupplyInterestFree\", getU64Decoder()],\n [\"totalBorrowWithInterest\", getU64Decoder()],\n [\"totalBorrowInterestFree\", getU64Decoder()],\n [\"totalClaimAmount\", getU64Decoder()],\n [\"interactingProtocol\", getAddressDecoder()],\n [\"interactingTimestamp\", getU64Decoder()],\n [\"interactingBalance\", getU64Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link TokenReserve} account data. */\nexport function getTokenReserveCodec(): FixedSizeCodec<TokenReserveArgs, TokenReserve> {\n return combineCodec(getTokenReserveEncoder(), getTokenReserveDecoder());\n}\n\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<TokenReserve, TAddress>;\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<TokenReserve, TAddress>;\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<TokenReserve, TAddress> | MaybeAccount<TokenReserve, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getTokenReserveDecoder());\n}\n\nexport async function fetchTokenReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<TokenReserve, TAddress>> {\n const maybeAccount = await fetchMaybeTokenReserve(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeTokenReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<TokenReserve, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeTokenReserve(maybeAccount);\n}\n\nexport async function fetchAllTokenReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<TokenReserve>[]> {\n const maybeAccounts = await fetchAllMaybeTokenReserve(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeTokenReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<TokenReserve>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeTokenReserve(maybeAccount));\n}\n\nexport function getTokenReserveSize(): number {\n return 192;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport async function findLiquidityPda(\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([108, 105, 113, 117, 105, 100, 105, 116, 121])),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type RateModelSeeds = {\n mint: Address;\n};\n\nexport async function findRateModelPda(\n seeds: RateModelSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([114, 97, 116, 101, 95, 109, 111, 100, 101, 108])),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type TokenReserveSeeds = {\n mint: Address;\n};\n\nexport async function findTokenReservePda(\n seeds: TokenReserveSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([114, 101, 115, 101, 114, 118, 101])),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type UserSupplyPositionSeeds = {\n supplyMint: Address;\n protocol: Address;\n};\n\nexport async function findUserSupplyPositionPda(\n seeds: UserSupplyPositionSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([\n 117, 115, 101, 114, 95, 115, 117, 112, 112, 108, 121, 95, 112, 111, 115, 105, 116, 105,\n 111, 110,\n ])\n ),\n getAddressEncoder().encode(seeds.supplyMint),\n getAddressEncoder().encode(seeds.protocol),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport {\n getRateModelCodec,\n getTokenReserveCodec,\n type RateModel,\n type RateModelArgs,\n type TokenReserve,\n type TokenReserveArgs,\n} from \"../accounts\";\nimport {\n findAuthListPda,\n findClaimAccountPda,\n findLiquidityPda,\n findRateModelPda,\n findTokenReservePda,\n findUserBorrowPositionPda,\n findUserSupplyPositionPda,\n} from \"../pdas\";\n\nexport const LIQUIDITY_PROGRAM_ADDRESS =\n \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">;\n\nexport enum LiquidityAccount {\n RateModel,\n TokenReserve,\n}\n\nexport function identifyLiquidityAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LiquidityAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([94, 3, 203, 219, 107, 137, 4, 162])\n ),\n 0\n )\n ) {\n return LiquidityAccount.RateModel;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([21, 18, 59, 135, 120, 20, 31, 12])\n ),\n 0\n )\n ) {\n return LiquidityAccount.TokenReserve;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"liquidity\",\n });\n}\n\nexport type LiquidityPlugin = {\n accounts: LiquidityPluginAccounts;\n pdas: LiquidityPluginPdas;\n identifyAccount: typeof identifyLiquidityAccount;\n};\n\nexport type LiquidityPluginAccounts = {\n rateModel: ReturnType<typeof getRateModelCodec> & SelfFetchFunctions<RateModelArgs, RateModel>;\n tokenReserve: ReturnType<typeof getTokenReserveCodec> &\n SelfFetchFunctions<TokenReserveArgs, TokenReserve>;\n};\n\nexport type LiquidityPluginPdas = {\n claimAccount: typeof findClaimAccountPda;\n liquidity: typeof findLiquidityPda;\n authList: typeof findAuthListPda;\n userSupplyPosition: typeof findUserSupplyPositionPda;\n userBorrowPosition: typeof findUserBorrowPositionPda;\n rateModel: typeof findRateModelPda;\n tokenReserve: typeof findTokenReservePda;\n};\n\nexport type LiquidityPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function liquidityProgram() {\n return <T extends LiquidityPluginRequirements>(\n client: T\n ): ExtendedClient<T, { liquidity: LiquidityPlugin }> => {\n return extendClient(client, {\n liquidity: <LiquidityPlugin>{\n accounts: {\n rateModel: addSelfFetchFunctions(client, getRateModelCodec()),\n tokenReserve: addSelfFetchFunctions(client, getTokenReserveCodec()),\n },\n pdas: {\n claimAccount: findClaimAccountPda,\n liquidity: findLiquidityPda,\n authList: findAuthListPda,\n userSupplyPosition: findUserSupplyPositionPda,\n userBorrowPosition: findUserBorrowPositionPda,\n rateModel: findRateModelPda,\n tokenReserve: findTokenReservePda,\n },\n identifyAccount: identifyLiquidityAccount,\n },\n });\n };\n}\n","import type { Address, ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type {\n JupLendingRewardsRateModel,\n JupLendingState,\n JupRateModel,\n JupTokenReserve,\n} from \"./types\";\n\nimport {\n getLendingDecoder,\n getLendingRewardsRateModelDecoder,\n LENDING_DISCRIMINATOR,\n LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR,\n} from \"~/generated/jup-lend\";\nimport {\n getRateModelDecoder,\n getTokenReserveDecoder,\n RATE_MODEL_DISCRIMINATOR,\n TOKEN_RESERVE_DISCRIMINATOR,\n} from \"~/generated/jup-lend-liquidity\";\n\nexport { LENDING_PROGRAM_ADDRESS as JUP_LEND_PROGRAM_ADDRESS } from \"~/generated/jup-lend\";\nexport { LIQUIDITY_PROGRAM_ADDRESS as JUP_LIQUIDITY_PROGRAM_ADDRESS } from \"~/generated/jup-lend-liquidity\";\n\n/**\n * Decodes a JupLend `Lending` account at `address`.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupLendingState(address: Address, data: ReadonlyUint8Array): JupLendingState {\n const lending = decodeAccountData(\n data,\n LENDING_DISCRIMINATOR,\n getLendingDecoder(),\n \"JupLend Lending\"\n );\n return {\n pubkey: address,\n mint: lending.mint,\n fTokenMint: lending.fTokenMint,\n lendingId: lending.lendingId,\n decimals: lending.decimals,\n rewardsRateModel: lending.rewardsRateModel,\n liquidityExchangePrice: lending.liquidityExchangePrice,\n tokenExchangePrice: lending.tokenExchangePrice,\n lastUpdateTimestamp: lending.lastUpdateTimestamp,\n tokenReservesLiquidity: lending.tokenReservesLiquidity,\n supplyPositionOnLiquidity: lending.supplyPositionOnLiquidity,\n };\n}\n\n/**\n * Decodes a JupLend liquidity-layer `TokenReserve` account at `address`.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupTokenReserve(address: Address, data: ReadonlyUint8Array): JupTokenReserve {\n const reserve = decodeAccountData(\n data,\n TOKEN_RESERVE_DISCRIMINATOR,\n getTokenReserveDecoder(),\n \"JupLend TokenReserve\"\n );\n return {\n pubkey: address,\n borrowRate: reserve.borrowRate,\n feeOnInterest: reserve.feeOnInterest,\n lastUtilization: reserve.lastUtilization,\n supplyExchangePrice: reserve.supplyExchangePrice,\n borrowExchangePrice: reserve.borrowExchangePrice,\n totalSupplyWithInterest: reserve.totalSupplyWithInterest,\n totalSupplyInterestFree: reserve.totalSupplyInterestFree,\n totalBorrowWithInterest: reserve.totalBorrowWithInterest,\n totalBorrowInterestFree: reserve.totalBorrowInterestFree,\n };\n}\n\n/**\n * Decodes a JupLend liquidity-layer `RateModel` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupRateModel(data: ReadonlyUint8Array): JupRateModel {\n return decodeAccountData(\n data,\n RATE_MODEL_DISCRIMINATOR,\n getRateModelDecoder(),\n \"JupLend RateModel\"\n );\n}\n\n/**\n * Decodes a JupLend `LendingRewardsRateModel` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupLendingRewardsRateModel(\n data: ReadonlyUint8Array\n): JupLendingRewardsRateModel {\n return decodeAccountData(\n data,\n LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR,\n getLendingRewardsRateModelDecoder(),\n \"JupLend LendingRewardsRateModel\"\n );\n}\n","import type { Instruction } from \"@solana/kit\";\n\nimport type { JupLendingState } from \"./types\";\n\nimport { getUpdateRateInstruction } from \"~/generated/jup-lend\";\n\n/**\n * Refreshes a JupLend market's exchange prices (permissionless crank). Needed before risk-sensitive\n * flows (liquidation, borrow, non-JupLend withdraw) for every involved JupLend bank in the same\n * transaction; juplend_deposit and juplend_withdraw already update the rate internally.\n */\nexport function makeUpdateJupLendRateIx(lendingState: JupLendingState): Instruction {\n return getUpdateRateInstruction({\n lending: lendingState.pubkey,\n mint: lendingState.mint,\n fTokenMint: lendingState.fTokenMint,\n supplyTokenReservesLiquidity: lendingState.tokenReservesLiquidity,\n rewardsRateModel: lendingState.rewardsRateModel,\n });\n}\n","import { BigNumber } from \"bignumber.js\";\n\nimport {\n JupLendingState,\n JupLendingRewardsRateModel,\n JupTokenReserve,\n JupRateModel,\n} from \"./types\";\n\nimport { aprToApy } from \"~/utils\";\n\n/**\n * Jup-Lend Interest Rate & Exchange Price Utilities\n *\n * Extracted from the compiled @jup-ag/lend SDK (earn/index.mjs).\n * All functions work on pre-fetched state — no RPC calls.\n *\n * Diverges from @jup-ag/lend 0.3.0-beta.1 `getNewExchangePrice`, which neither scales the rewards\n * term by 100 (1e12 → 1e14) nor zeroes rewards that haven't started or have ended; kept as-is\n * pending confirmation against the on-chain program.\n */\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nexport const JUP_EXCHANGE_PRICES_PRECISION = 1_000_000_000_000n; // 1e12\nexport const JUP_SECONDS_PER_YEAR = 31_536_000n;\nexport const JUP_MAX_REWARDS_RATE = 50_000_000_000_000n; // 50 * 1e12 = 50%\n\n// ============================================================================\n// TOTAL ASSETS\n// ============================================================================\n\n/**\n * Calculate total assets for a jup-lend market.\n * Formula: tokenExchangePrice * fTokenTotalSupply / EXCHANGE_PRICES_PRECISION\n *\n * @param lendingState - The on-chain Lending account\n * @param fTokenTotalSupply - Total supply of the fToken (from getTokenSupply)\n * @returns Total assets in underlying token native units\n */\nexport function calculateJupLendTotalAssets(\n lendingState: JupLendingState,\n fTokenTotalSupply: bigint\n): bigint {\n return (lendingState.tokenExchangePrice * fTokenTotalSupply) / JUP_EXCHANGE_PRICES_PRECISION;\n}\n\n// ============================================================================\n// REWARDS RATE\n// ============================================================================\n\nexport interface JupLendRewardsResult {\n rewardsRate: bigint;\n rewardsEnded: boolean;\n rewardsStartTime: bigint;\n}\n\n/**\n * Calculate the rewards rate from a LendingRewardsRateModel.\n * Extracted from compiled SDK's `calculateRewardsRate`.\n *\n * @param rewardsModel - The on-chain LendingRewardsRateModel account\n * @param totalAssets - Total assets in the market (from calculateJupLendTotalAssets)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Rewards rate, whether rewards ended, and start time\n */\nexport function calculateJupLendRewardsRate(\n rewardsModel: JupLendingRewardsRateModel,\n totalAssets: bigint,\n currentTimestamp: bigint\n): JupLendRewardsResult {\n const defaultResult: JupLendRewardsResult = {\n rewardsRate: 0n,\n rewardsEnded: false,\n rewardsStartTime: rewardsModel.startTime,\n };\n\n if (rewardsModel.startTime === 0n || rewardsModel.duration === 0n) {\n return defaultResult;\n }\n\n if (currentTimestamp > rewardsModel.startTime + rewardsModel.duration) {\n return { ...defaultResult, rewardsEnded: true };\n }\n\n if (totalAssets === 0n || totalAssets < rewardsModel.startTvl) {\n return defaultResult;\n }\n\n let rewardsRate = (rewardsModel.yearlyReward * 10_000n) / totalAssets;\n\n if (rewardsRate > JUP_MAX_REWARDS_RATE) {\n rewardsRate = JUP_MAX_REWARDS_RATE;\n }\n\n return {\n rewardsRate,\n rewardsEnded: false,\n rewardsStartTime: rewardsModel.startTime,\n };\n}\n\n// ============================================================================\n// REWARDS RATE FOR EXCHANGE PRICE (1e12 precision)\n// ============================================================================\n\n/**\n * Calculate the rewards rate at 1e12 precision for use in exchange price projection.\n * Mirrors SDK's `getRewardsRate` (earn/index.mjs line 261), NOT `calculateRewardsRate`.\n *\n * This is distinct from `calculateJupLendRewardsRate` which uses 1e4 precision for APR display.\n *\n * @param rewardsModel - The on-chain LendingRewardsRateModel account\n * @param totalAssets - Total assets in the market (from calculateJupLendTotalAssets)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Rate at 1e12 precision and rewards start time\n */\nexport function calculateJupLendRewardsRateForExchangePrice(\n rewardsModel: JupLendingRewardsRateModel,\n totalAssets: bigint,\n currentTimestamp: bigint\n): { rate: bigint; rewardsStartTime: bigint } {\n const defaultResult = { rate: 0n, rewardsStartTime: rewardsModel.startTime };\n\n if (rewardsModel.startTime === 0n || rewardsModel.duration === 0n) {\n return defaultResult;\n }\n\n if (currentTimestamp > rewardsModel.startTime + rewardsModel.duration) {\n return defaultResult;\n }\n\n if (totalAssets === 0n || totalAssets < rewardsModel.startTvl) {\n return defaultResult;\n }\n\n let rate = (rewardsModel.yearlyReward * JUP_EXCHANGE_PRICES_PRECISION) / totalAssets;\n\n if (rate > JUP_MAX_REWARDS_RATE) {\n rate = JUP_MAX_REWARDS_RATE;\n }\n\n return { rate, rewardsStartTime: rewardsModel.startTime };\n}\n\n// ============================================================================\n// EXCHANGE PRICE PROJECTION\n// ============================================================================\n\n/**\n * Project the new token exchange price offline (no RPC calls).\n * Extracted from compiled SDK's `getNewExchangePrice` (earn/index.mjs line 316).\n *\n * This combines:\n * 1. Rewards rate contribution (time-weighted, 1e12 precision via getRewardsRate)\n * 2. Liquidity exchange price delta (scaled to 1e14)\n *\n * Both components are accumulated in 1e14 space before being applied.\n *\n * @param lendingState - The on-chain Lending account\n * @param tokenReserve - The on-chain TokenReserve account (provides current supplyExchangePrice)\n * @param rewardsModel - The on-chain LendingRewardsRateModel (or null if no rewards)\n * @param fTokenTotalSupply - Total supply of the fToken (for totalAssets calculation)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Projected token exchange price (1e12 precision)\n */\nexport function calculateJupLendNewExchangePrice(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint,\n currentTimestamp: bigint\n): bigint {\n const oldTokenExchangePrice = lendingState.tokenExchangePrice;\n const oldLiquidityExchangePrice = lendingState.liquidityExchangePrice;\n const currentLiquidityExchangePrice = tokenReserve.supplyExchangePrice;\n\n // Rewards component — must use 1e12-precision rate (mirrors SDK getRewardsRate, not calculateRewardsRate)\n let rewardsRate = 0n;\n let rewardsStartTime = lendingState.lastUpdateTimestamp;\n\n if (rewardsModel) {\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const result = calculateJupLendRewardsRateForExchangePrice(\n rewardsModel,\n totalAssets,\n currentTimestamp\n );\n rewardsRate = result.rate;\n rewardsStartTime = result.rewardsStartTime;\n }\n\n let lastUpdateTime = lendingState.lastUpdateTimestamp;\n if (lastUpdateTime < rewardsStartTime) {\n lastUpdateTime = rewardsStartTime;\n }\n\n const secondsElapsed = currentTimestamp - lastUpdateTime;\n\n // Rewards contribution: rate (1e12) * secondsElapsed / SECONDS_PER_YEAR → ~1e12 scale\n // Scaled up to 1e14 to match the liquidity delta component\n let totalReturnPercent = ((rewardsRate * secondsElapsed) / JUP_SECONDS_PER_YEAR) * 100n; // 1e12 → 1e14\n\n // Liquidity exchange price delta contribution (1e14 precision)\n const delta = currentLiquidityExchangePrice - oldLiquidityExchangePrice;\n totalReturnPercent += (delta * 100_000_000_000_000n) / oldLiquidityExchangePrice;\n\n return (\n oldTokenExchangePrice + (oldTokenExchangePrice * totalReturnPercent) / 100_000_000_000_000n\n );\n}\n\n/**\n * Underlying tokens (native units) per fToken at `nowSeconds` (unix seconds): the projected exchange\n * price over its 1e12 precision.\n */\nexport function getJupLendFTokenMultiplier(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint,\n nowSeconds: number\n): BigNumber {\n const exchangePrice = calculateJupLendNewExchangePrice(\n lendingState,\n tokenReserve,\n rewardsModel,\n fTokenTotalSupply,\n BigInt(nowSeconds)\n );\n\n return new BigNumber(exchangePrice.toString()).dividedBy(\n JUP_EXCHANGE_PRICES_PRECISION.toString()\n );\n}\n\n// ============================================================================\n// LIQUIDITY SUPPLY RATE\n// ============================================================================\n\n/**\n * Calculate the liquidity layer supply rate for an asset.\n * Extracted from compiled SDK's `getLiquidityAssetSupplyRate`.\n *\n * Formula: borrowRate * (1 - fee) * borrowWithInterest / supplyWithInterest\n *\n * @param tokenReserve - The on-chain TokenReserve account\n * @returns Supply rate in bps\n */\nexport function calculateJupLendLiquiditySupplyRate(tokenReserve: JupTokenReserve): bigint {\n const borrowRate = BigInt(tokenReserve.borrowRate);\n const fee = BigInt(tokenReserve.feeOnInterest);\n\n if (tokenReserve.totalSupplyWithInterest === 0n) {\n return 0n;\n }\n\n const borrowWithInterestForRate =\n (tokenReserve.totalBorrowWithInterest * tokenReserve.borrowExchangePrice) /\n JUP_EXCHANGE_PRICES_PRECISION;\n\n const supplyWithInterestForRate =\n (tokenReserve.totalSupplyWithInterest * tokenReserve.supplyExchangePrice) /\n JUP_EXCHANGE_PRICES_PRECISION;\n\n if (supplyWithInterestForRate === 0n) {\n return 0n;\n }\n\n return (\n (borrowRate * (10_000n - fee) * borrowWithInterestForRate) /\n (supplyWithInterestForRate * 10_000n)\n );\n}\n\n// ============================================================================\n// COMBINED SUPPLY RATE (APR)\n// ============================================================================\n\n/**\n * Calculate the total supply rate (APR) for a jup-lend market,\n * combining both base liquidity supply rate and rewards rate.\n *\n * Returns a number as a decimal (e.g. 0.05 = 5% APR).\n *\n * @param lendingState - The on-chain Lending account\n * @param tokenReserve - The on-chain TokenReserve account\n * @param rewardsModel - The on-chain LendingRewardsRateModel account (or null if no rewards)\n * @param fTokenTotalSupply - Total supply of the fToken\n * @returns Supply rate as decimal number\n */\nexport function calculateJupLendSupplyRate(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint\n): number {\n const supplyRate = calculateJupLendLiquiditySupplyRate(tokenReserve);\n\n // supplyRate is in bps (e.g. 500 = 5%)\n let totalRateBps = Number(supplyRate);\n\n if (rewardsModel) {\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));\n const { rewardsRate } = calculateJupLendRewardsRate(\n rewardsModel,\n totalAssets,\n currentTimestamp\n );\n // rewardsRate is scaled by 1e4 relative to totalAssets\n totalRateBps += Number(rewardsRate);\n }\n\n return totalRateBps / 10_000;\n}\n\n// ============================================================================\n// SUPPLY APY\n// ============================================================================\n\n/**\n * Calculate the supply APY for a jup-lend market (base rate only, no rewards).\n *\n * Uses hourly compounding: (1 + apr/HOURS_PER_YEAR)^HOURS_PER_YEAR - 1\n *\n * @param tokenReserve - The on-chain TokenReserve account\n * @returns Supply APY as decimal (e.g. 0.0512 = 5.12% APY)\n */\nexport function calculateJupLendSupplyAPY(tokenReserve: JupTokenReserve): number {\n const supplyRateBps = calculateJupLendLiquiditySupplyRate(tokenReserve);\n const apr = Number(supplyRateBps) / 1e4;\n return aprToApy(apr);\n}\n\n// ============================================================================\n// BORROW RATE FROM RATE MODEL (PIECEWISE LINEAR)\n// ============================================================================\n\n/**\n * Calculate the borrow rate at a given utilization using the on-chain RateModel.\n *\n * V1 (version=1, single kink):\n * [0, kink1] → linear rateAtZero → rateAtKink1\n * [kink1, 10000] → linear rateAtKink1 → rateAtMax\n *\n * V2 (version=2, dual kink):\n * [0, kink1] → linear rateAtZero → rateAtKink1\n * [kink1, kink2] → linear rateAtKink1 → rateAtKink2\n * [kink2, 10000] → linear rateAtKink2 → rateAtMax\n *\n * @param rateModel - The on-chain RateModel account\n * @param utilizationBps - Utilization in bps (0–10000)\n * @returns Borrow rate in bps\n */\nexport function calculateJupLendBorrowRate(\n rateModel: JupRateModel,\n utilizationBps: number\n): number {\n const u = Math.max(0, Math.min(10000, utilizationBps));\n\n if (rateModel.version === 2) {\n // V2: dual kink\n if (u <= rateModel.kink1Utilization) {\n return linearInterpolate(\n 0,\n rateModel.rateAtZero,\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n u\n );\n } else if (u <= rateModel.kink2Utilization) {\n return linearInterpolate(\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n rateModel.kink2Utilization,\n rateModel.rateAtKink2,\n u\n );\n } else {\n return linearInterpolate(\n rateModel.kink2Utilization,\n rateModel.rateAtKink2,\n 10000,\n rateModel.rateAtMax,\n u\n );\n }\n } else {\n // V1: single kink\n if (u <= rateModel.kink1Utilization) {\n return linearInterpolate(\n 0,\n rateModel.rateAtZero,\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n u\n );\n } else {\n return linearInterpolate(\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n 10000,\n rateModel.rateAtMax,\n u\n );\n }\n }\n}\n\n/**\n * Linear interpolation between two points.\n */\nfunction linearInterpolate(x0: number, y0: number, x1: number, y1: number, x: number): number {\n if (x1 === x0) return y0;\n return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0);\n}\n\n// ============================================================================\n// SUPPLY INTEREST RATE CURVE\n// ============================================================================\n\n/**\n * Interest rate curve point for visualization (supply only).\n */\nexport interface JupLendInterestRateCurvePoint {\n utilization: number; // 0-100 percentage\n supplyAPY: number; // percentage\n}\n\n/**\n * Generate a supply interest rate curve for a JupLend reserve using the on-chain RateModel.\n *\n * Uses the piecewise linear borrow rate curve from the RateModel account:\n * borrowAPR(U) = calculateJupLendBorrowRate(rateModel, U * 10000)\n * supplyAPR(U) = borrowAPR(U) * (1 - feeOnInterest / 1e4) * U\n * supplyAPY(U) = aprToApy(supplyAPR(U))\n *\n * @param rateModel - The on-chain RateModel account (from liquidity program)\n * @param feeOnInterest - Fee on interest in bps (from TokenReserve.feeOnInterest)\n * @returns 101 curve points (utilization 0–100%)\n */\nexport function generateJupLendSupplyCurve(\n rateModel: JupRateModel,\n feeOnInterest: number\n): JupLendInterestRateCurvePoint[] {\n const feeMultiplier = 1 - feeOnInterest / 1e4;\n\n return Array.from({ length: 101 }, (_, i) => {\n const utilizationFraction = i / 100; // 0.00 to 1.00\n const utilizationBps = i * 100; // 0 to 10000\n\n const borrowRateBps = calculateJupLendBorrowRate(rateModel, utilizationBps);\n const borrowRateDecimal = borrowRateBps / 1e4;\n\n const supplyAPR = borrowRateDecimal * feeMultiplier * utilizationFraction;\n const supplyAPY = aprToApy(supplyAPR);\n\n return {\n utilization: i, // 0-100\n supplyAPY: supplyAPY * 100, // Convert to percentage\n };\n });\n}\n","import {\n address,\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\nimport { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\n\nimport { findFTokenMintPda, findLendingAdminPda, findLendingPda } from \"~/generated/jup-lend\";\nimport {\n findLiquidityPda,\n findRateModelPda,\n findTokenReservePda,\n findUserSupplyPositionPda,\n} from \"~/generated/jup-lend-liquidity\";\n\n/** JupLend rewards rate model program (no IDL client; only its PDA is needed). */\nexport const JUP_REWARDS_PROGRAM_ADDRESS = address(\"jup7TthsMgcR9Y3L277b8Eo9uboVSmu1utkuXHNUKar\");\n\n/** `LendingRewardsRateModel` PDA of `mint`, owned by the rewards program. */\nexport function deriveJupLendLendingRewardsRateModel(\n mint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: JUP_REWARDS_PROGRAM_ADDRESS,\n seeds: [\"lending_rewards_rate_model\", getAddressEncoder().encode(mint)],\n });\n}\n\n/** Liquidity-layer rate model PDA of `mint`. */\nexport function deriveJupLendRateModel(mint: Address): Promise<ProgramDerivedAddress> {\n return findRateModelPda({ mint });\n}\n\n/**\n * All JupLend accounts a deposit/withdraw of `mint` needs, derived locally. `tokenProgram` is the\n * mint's token program (for the liquidity vault ATA).\n */\nexport async function getAllDerivedJupLendAccounts(\n mint: Address,\n tokenProgram: Address = TOKEN_PROGRAM_ADDRESS\n) {\n const [[fTokenMint], [liquidity]] = await Promise.all([\n findFTokenMintPda({ mint }),\n findLiquidityPda(),\n ]);\n const [\n [lending],\n [lendingAdmin],\n [supplyTokenReservesLiquidity],\n [rateModel],\n [vault],\n [rewardsRateModel],\n ] = await Promise.all([\n findLendingPda({ mint, fTokenMint }),\n findLendingAdminPda(),\n findTokenReservePda({ mint }),\n findRateModelPda({ mint }),\n findAssociatedTokenPda({ owner: liquidity, tokenProgram, mint }),\n deriveJupLendLendingRewardsRateModel(mint),\n ]);\n const [lendingSupplyPositionOnLiquidity] = await findUserSupplyPositionPda({\n supplyMint: mint,\n protocol: lending,\n });\n\n return {\n fTokenMint,\n lendingAdmin,\n supplyTokenReservesLiquidity,\n lendingSupplyPositionOnLiquidity,\n rateModel,\n vault,\n liquidity,\n rewardsRateModel,\n };\n}\n","import {\n calculateJupLendRewardsRate,\n calculateJupLendTotalAssets,\n JupLendRewardsResult,\n} from \"./interest-rate\";\nimport { JupLendingRewardsRateModel, JupLendingState } from \"./types\";\n\n/**\n * Rewards info of a JupLend market from pre-fetched state.\n * @param fTokenTotalSupply - fToken supply, native units\n */\nexport function getJupLendRewards(\n lendingState: JupLendingState,\n rewardsModel: JupLendingRewardsRateModel,\n fTokenTotalSupply: bigint\n): JupLendRewardsResult {\n if (lendingState.rewardsRateModel === \"11111111111111111111111111111111\") {\n return { rewardsRate: 0n, rewardsEnded: false, rewardsStartTime: 0n };\n }\n\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));\n\n return calculateJupLendRewardsRate(rewardsModel, totalAssets, currentTimestamp);\n}\n","import { address } from \"@solana/kit\";\n\nimport {\n JupLendingRewardsRateModel,\n JupLendingRewardsRateModelJSON,\n JupLendingState,\n JupLendingStateJSON,\n JupRateModel,\n JupRateModelJSON,\n JupTokenReserve,\n JupTokenReserveJSON,\n} from \"./types\";\n\n/** Serializes a JupLend lending state to its JSON DTO. */\nexport function jupLendingStateRawToDto(state: JupLendingState): JupLendingStateJSON {\n return {\n pubkey: state.pubkey,\n mint: state.mint,\n fTokenMint: state.fTokenMint,\n lendingId: state.lendingId,\n decimals: state.decimals,\n rewardsRateModel: state.rewardsRateModel,\n liquidityExchangePrice: state.liquidityExchangePrice.toString(),\n tokenExchangePrice: state.tokenExchangePrice.toString(),\n lastUpdateTimestamp: state.lastUpdateTimestamp.toString(),\n tokenReservesLiquidity: state.tokenReservesLiquidity,\n supplyPositionOnLiquidity: state.supplyPositionOnLiquidity,\n };\n}\n\n/**\n * Parses a JupLend lending state DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToJupLendingStateRaw(dto: JupLendingStateJSON): JupLendingState {\n return {\n pubkey: address(dto.pubkey),\n mint: address(dto.mint),\n fTokenMint: address(dto.fTokenMint),\n lendingId: dto.lendingId,\n decimals: dto.decimals,\n rewardsRateModel: address(dto.rewardsRateModel),\n liquidityExchangePrice: BigInt(dto.liquidityExchangePrice),\n tokenExchangePrice: BigInt(dto.tokenExchangePrice),\n lastUpdateTimestamp: BigInt(dto.lastUpdateTimestamp),\n tokenReservesLiquidity: address(dto.tokenReservesLiquidity),\n supplyPositionOnLiquidity: address(dto.supplyPositionOnLiquidity),\n };\n}\n\n/** Serializes a JupLend token reserve to its JSON DTO. */\nexport function jupTokenReserveRawToDto(reserve: JupTokenReserve): JupTokenReserveJSON {\n return {\n pubkey: reserve.pubkey,\n borrowRate: reserve.borrowRate,\n feeOnInterest: reserve.feeOnInterest,\n lastUtilization: reserve.lastUtilization,\n supplyExchangePrice: reserve.supplyExchangePrice.toString(),\n borrowExchangePrice: reserve.borrowExchangePrice.toString(),\n totalSupplyWithInterest: reserve.totalSupplyWithInterest.toString(),\n totalSupplyInterestFree: reserve.totalSupplyInterestFree.toString(),\n totalBorrowWithInterest: reserve.totalBorrowWithInterest.toString(),\n totalBorrowInterestFree: reserve.totalBorrowInterestFree.toString(),\n };\n}\n\n/**\n * Parses a JupLend token reserve DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToJupTokenReserveRaw(dto: JupTokenReserveJSON): JupTokenReserve {\n return {\n pubkey: address(dto.pubkey),\n borrowRate: dto.borrowRate,\n feeOnInterest: dto.feeOnInterest,\n lastUtilization: dto.lastUtilization,\n supplyExchangePrice: BigInt(dto.supplyExchangePrice),\n borrowExchangePrice: BigInt(dto.borrowExchangePrice),\n totalSupplyWithInterest: BigInt(dto.totalSupplyWithInterest),\n totalSupplyInterestFree: BigInt(dto.totalSupplyInterestFree),\n totalBorrowWithInterest: BigInt(dto.totalBorrowWithInterest),\n totalBorrowInterestFree: BigInt(dto.totalBorrowInterestFree),\n };\n}\n\n/** Serializes a JupLend rewards rate model to its JSON DTO. */\nexport function jupLendingRewardsRateModelRawToDto(\n model: JupLendingRewardsRateModel\n): JupLendingRewardsRateModelJSON {\n return {\n startTvl: model.startTvl.toString(),\n duration: model.duration.toString(),\n startTime: model.startTime.toString(),\n yearlyReward: model.yearlyReward.toString(),\n };\n}\n\n/** Parses a JupLend rewards rate model DTO. */\nexport function dtoToJupLendingRewardsRateModelRaw(\n dto: JupLendingRewardsRateModelJSON\n): JupLendingRewardsRateModel {\n return {\n startTvl: BigInt(dto.startTvl),\n duration: BigInt(dto.duration),\n startTime: BigInt(dto.startTime),\n yearlyReward: BigInt(dto.yearlyReward),\n };\n}\n\n/** Serializes a JupLend rate model to its JSON DTO. */\nexport function jupRateModelRawToDto(model: JupRateModel): JupRateModelJSON {\n return {\n version: model.version,\n rateAtZero: model.rateAtZero,\n kink1Utilization: model.kink1Utilization,\n rateAtKink1: model.rateAtKink1,\n rateAtMax: model.rateAtMax,\n kink2Utilization: model.kink2Utilization,\n rateAtKink2: model.rateAtKink2,\n };\n}\n\n/** Parses a JupLend rate model DTO. */\nexport function dtoToJupRateModelRaw(dto: JupRateModelJSON): JupRateModel {\n return {\n version: dto.version,\n rateAtZero: dto.rateAtZero,\n kink1Utilization: dto.kink1Utilization,\n rateAtKink1: dto.rateAtKink1,\n rateAtMax: dto.rateAtMax,\n kink2Utilization: dto.kink2Utilization,\n rateAtKink2: dto.rateAtKink2,\n };\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\nimport { getMintDecoder } from \"@solana-program/token\";\n\nimport {\n decodeJupLendingRewardsRateModel,\n decodeJupLendingState,\n decodeJupRateModel,\n decodeJupTokenReserve,\n} from \"./accounts\";\nimport { deriveJupLendRateModel } from \"./pda\";\nimport {\n jupLendingRewardsRateModelRawToDto,\n jupLendingStateRawToDto,\n jupRateModelRawToDto,\n jupTokenReserveRawToDto,\n} from \"./serialize\";\nimport type { JupLendBankInput, JupLendStates, JupLendStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link JupLendStates}, keyed by bank address. Banks with a default lending\n * state or a missing lending state, token reserve or fToken mint are left out.\n * @throws if a fetched account isn't the JupLend account it should be\n */\nexport async function fetchJupLendStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: JupLendBankInput[]\n): Promise<Record<string, JupLendStates>> {\n const validBanks = banks.filter((bank) => bank.lendingState !== DEFAULT_ADDRESS);\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.map((bank) => bank.lendingState)\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const lending = accounts[i];\n return lending\n ? [\n {\n bankAddress: bank.bankAddress,\n lendingState: decodeJupLendingState(bank.lendingState, lending.data),\n },\n ]\n : [];\n });\n\n const rateModels = await Promise.all(\n decoded.map(async ({ lendingState }) => (await deriveJupLendRateModel(lendingState.mint))[0])\n );\n const venueAccounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n decoded.flatMap(({ lendingState }, i) => [\n lendingState.tokenReservesLiquidity,\n lendingState.rewardsRateModel,\n lendingState.fTokenMint,\n rateModels[i],\n ])\n );\n\n return Object.fromEntries(\n decoded.flatMap(({ bankAddress, lendingState }, i) => {\n const [tokenReserve, rewardsRateModel, fTokenMint, rateModel] = venueAccounts.slice(\n 4 * i,\n 4 * i + 4\n );\n return tokenReserve && fTokenMint\n ? [\n [\n bankAddress,\n {\n lendingState,\n tokenReserveState: decodeJupTokenReserve(\n lendingState.tokenReservesLiquidity,\n tokenReserve.data\n ),\n rewardsRateModel:\n rewardsRateModel && lendingState.rewardsRateModel !== DEFAULT_ADDRESS\n ? decodeJupLendingRewardsRateModel(rewardsRateModel.data)\n : null,\n rateModel: rateModel ? decodeJupRateModel(rateModel.data) : null,\n fTokenTotalSupply: getMintDecoder().decode(fTokenMint.data).supply,\n },\n ],\n ]\n : [];\n })\n );\n}\n\n/**\n * {@link fetchJupLendStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchJupLendStates}\n */\nexport async function fetchJupLendStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: JupLendBankInput[]\n): Promise<Record<string, JupLendStatesJSON>> {\n const states = await fetchJupLendStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, state]) => [\n bank,\n {\n lendingState: jupLendingStateRawToDto(state.lendingState),\n tokenReserveState: jupTokenReserveRawToDto(state.tokenReserveState),\n rewardsRateModel:\n state.rewardsRateModel && jupLendingRewardsRateModelRawToDto(state.rewardsRateModel),\n rateModel: state.rateModel && jupRateModelRawToDto(state.rateModel),\n fTokenTotalSupply: state.fTokenTotalSupply.toString(),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LP_VAULT_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 189, 45, 167, 23, 91, 118, 105, 190,\n]);\n\nexport function getLpVaultDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LP_VAULT_DISCRIMINATOR);\n}\n\nexport type LpVault = {\n discriminator: ReadonlyUint8Array;\n /** USDC TokenAccount where users deposit, funds agent operations. */\n assetsAccount: Address;\n /** TokenAccount where shares are held during queued (illiquid) withdrawals. */\n pendingSharesAccount: Address;\n /** Derived mint (created on initialize) that represents LP tokens or shares. */\n sharesMint: Address;\n /** Mint corresponding to the asset, most of the time USDC. */\n assetsMint: Address;\n /** Pubkey authorized to withdraw assets from assets_account and update NAV. */\n fundAuthority: Address;\n /** Current Net Asset Value (total vault value in asset decimals). */\n nav: bigint;\n /**\n * Total shares outstanding (cached for efficiency). May temporarily diverge\n * from shares_mint.supply during the escrow withdrawal flow (between\n * fulfill_withdrawal and complete_withdrawal).\n */\n totalShares: bigint;\n /** Timestamp for when NAV was last updated. */\n navUpdatedAt: bigint;\n /**\n * Maximum NAV staleness for user operations (in seconds).\n * Deposits and withdrawals fail if NAV is older than this.\n */\n navMaxStaleness: bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n vaultName: string;\n /**\n * Total value of pending withdrawals awaiting liquidity.\n * When a withdrawal cannot be fulfilled instantly due to insufficient\n * liquid assets, the value is tracked here. This is approximate — the\n * value recorded at withdrawal time may differ from the value at\n * fulfillment time (recomputed at current NAV). Used for operator\n * visibility only, not for critical calculations.\n */\n pendingWithdrawalValue: bigint;\n /** Shares token account that receives fee shares. Pubkey::default() = disabled. */\n feeRecipient: Address;\n /** Performance fee rate in basis points (2000 = 20%). 0 = disabled. */\n performanceFeeBps: number;\n /** How often scheduled fees are assessed (seconds). E.g., 86400 = 24h. */\n assessmentIntervalSecs: bigint;\n /** Unix timestamp of last fee event (scheduled or withdrawal-triggered). */\n lastAssessmentTimestamp: bigint;\n /** PPS at last fee event, scaled by PRICE_SCALE. High-water mark for fees. */\n pricePerShareAtLastAssessment: bigint;\n /**\n * Optional keeper authority. When set (non-default), this key can call\n * fulfill_withdrawal in addition to fund_authority. Allows the keeper\n * process to use a separate key from the agent/fund_authority.\n * Pubkey::default() = not set (only fund_authority can fulfill).\n */\n keeperAuthority: Address;\n};\n\nexport type LpVaultArgs = {\n /** USDC TokenAccount where users deposit, funds agent operations. */\n assetsAccount: Address;\n /** TokenAccount where shares are held during queued (illiquid) withdrawals. */\n pendingSharesAccount: Address;\n /** Derived mint (created on initialize) that represents LP tokens or shares. */\n sharesMint: Address;\n /** Mint corresponding to the asset, most of the time USDC. */\n assetsMint: Address;\n /** Pubkey authorized to withdraw assets from assets_account and update NAV. */\n fundAuthority: Address;\n /** Current Net Asset Value (total vault value in asset decimals). */\n nav: number | bigint;\n /**\n * Total shares outstanding (cached for efficiency). May temporarily diverge\n * from shares_mint.supply during the escrow withdrawal flow (between\n * fulfill_withdrawal and complete_withdrawal).\n */\n totalShares: number | bigint;\n /** Timestamp for when NAV was last updated. */\n navUpdatedAt: number | bigint;\n /**\n * Maximum NAV staleness for user operations (in seconds).\n * Deposits and withdrawals fail if NAV is older than this.\n */\n navMaxStaleness: number | bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n vaultName: string;\n /**\n * Total value of pending withdrawals awaiting liquidity.\n * When a withdrawal cannot be fulfilled instantly due to insufficient\n * liquid assets, the value is tracked here. This is approximate — the\n * value recorded at withdrawal time may differ from the value at\n * fulfillment time (recomputed at current NAV). Used for operator\n * visibility only, not for critical calculations.\n */\n pendingWithdrawalValue: number | bigint;\n /** Shares token account that receives fee shares. Pubkey::default() = disabled. */\n feeRecipient: Address;\n /** Performance fee rate in basis points (2000 = 20%). 0 = disabled. */\n performanceFeeBps: number;\n /** How often scheduled fees are assessed (seconds). E.g., 86400 = 24h. */\n assessmentIntervalSecs: number | bigint;\n /** Unix timestamp of last fee event (scheduled or withdrawal-triggered). */\n lastAssessmentTimestamp: number | bigint;\n /** PPS at last fee event, scaled by PRICE_SCALE. High-water mark for fees. */\n pricePerShareAtLastAssessment: number | bigint;\n /**\n * Optional keeper authority. When set (non-default), this key can call\n * fulfill_withdrawal in addition to fund_authority. Allows the keeper\n * process to use a separate key from the agent/fund_authority.\n * Pubkey::default() = not set (only fund_authority can fulfill).\n */\n keeperAuthority: Address;\n};\n\n/** Gets the encoder for {@link LpVaultArgs} account data. */\nexport function getLpVaultEncoder(): Encoder<LpVaultArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"assetsAccount\", getAddressEncoder()],\n [\"pendingSharesAccount\", getAddressEncoder()],\n [\"sharesMint\", getAddressEncoder()],\n [\"assetsMint\", getAddressEncoder()],\n [\"fundAuthority\", getAddressEncoder()],\n [\"nav\", getU64Encoder()],\n [\"totalShares\", getU64Encoder()],\n [\"navUpdatedAt\", getI64Encoder()],\n [\"navMaxStaleness\", getU64Encoder()],\n [\"bump\", getU8Encoder()],\n [\"vaultName\", addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\"pendingWithdrawalValue\", getU64Encoder()],\n [\"feeRecipient\", getAddressEncoder()],\n [\"performanceFeeBps\", getU16Encoder()],\n [\"assessmentIntervalSecs\", getI64Encoder()],\n [\"lastAssessmentTimestamp\", getI64Encoder()],\n [\"pricePerShareAtLastAssessment\", getU64Encoder()],\n [\"keeperAuthority\", getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: LP_VAULT_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link LpVault} account data. */\nexport function getLpVaultDecoder(): Decoder<LpVault> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"assetsAccount\", getAddressDecoder()],\n [\"pendingSharesAccount\", getAddressDecoder()],\n [\"sharesMint\", getAddressDecoder()],\n [\"assetsMint\", getAddressDecoder()],\n [\"fundAuthority\", getAddressDecoder()],\n [\"nav\", getU64Decoder()],\n [\"totalShares\", getU64Decoder()],\n [\"navUpdatedAt\", getI64Decoder()],\n [\"navMaxStaleness\", getU64Decoder()],\n [\"bump\", getU8Decoder()],\n [\"vaultName\", addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\"pendingWithdrawalValue\", getU64Decoder()],\n [\"feeRecipient\", getAddressDecoder()],\n [\"performanceFeeBps\", getU16Decoder()],\n [\"assessmentIntervalSecs\", getI64Decoder()],\n [\"lastAssessmentTimestamp\", getI64Decoder()],\n [\"pricePerShareAtLastAssessment\", getU64Decoder()],\n [\"keeperAuthority\", getAddressDecoder()],\n ]);\n}\n\n/** Gets the codec for {@link LpVault} account data. */\nexport function getLpVaultCodec(): Codec<LpVaultArgs, LpVault> {\n return combineCodec(getLpVaultEncoder(), getLpVaultDecoder());\n}\n\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<LpVault, TAddress>;\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<LpVault, TAddress>;\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<LpVault, TAddress> | MaybeAccount<LpVault, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getLpVaultDecoder());\n}\n\nexport async function fetchLpVault<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<LpVault, TAddress>> {\n const maybeAccount = await fetchMaybeLpVault(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLpVault<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<LpVault, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLpVault(maybeAccount);\n}\n\nexport async function fetchAllLpVault(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<LpVault>[]> {\n const maybeAccounts = await fetchAllMaybeLpVault(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLpVault(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<LpVault>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLpVault(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const WITHDRAW_RECEIPT_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 132, 238, 44, 182, 207, 9, 124, 140,\n]);\n\nexport function getWithdrawReceiptDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(WITHDRAW_RECEIPT_DISCRIMINATOR);\n}\n\nexport type WithdrawReceipt = {\n discriminator: ReadonlyUint8Array;\n /** User requesting withdrawal. */\n user: Address;\n /** Vault where the user has invested. */\n lpVault: Address;\n /**\n * Shares waiting for liquidity (keeper needs to fulfill these).\n * These shares are held in the escrow_shares_account.\n */\n pendingShares: bigint;\n /**\n * Shares that have been fulfilled and are ready to claim.\n * These shares are also in escrow_shares_account, waiting to be burned on claim.\n */\n claimableShares: bigint;\n /** Asset value ready to claim (held in escrow_assets_account). */\n claimableAssets: bigint;\n /**\n * NAV ordering floor for the whole `pending_shares` aggregate, re-derived on\n * the MOST RECENT addition.\n *\n * Despite the name and the `i64` type this is NOT a wall-clock timestamp of\n * the addition: it stores `observed_nav_updated_at + 1`, i.e. one past the\n * NAV version in force when that addition was queued. It shares the\n * `nav_updated_at` number space, which is why the existing `>=` comparisons\n * in the program and the keeper keep working unchanged.\n *\n * `fulfill_withdrawal` prices all of `pending_shares` at once and requires\n * `nav_updated_at >= oldest_pending_at`, so this must track the newest\n * request, not the first: a first-request-only stamp lets every subsequent\n * addition settle against a NAV that predates it.\n *\n * NOTE: the field name is retained for wire/IDL compatibility — the keeper\n * reads it by name and orders fulfilment on it. Renaming it to\n * `newest_pending_at` is a follow-up that must land with a keeper change.\n *\n * The floor is derived from the NAV VERSION the request observed —\n * `lp_vault.nav_updated_at + 1` — not from the wall clock. Combined with\n * fulfilment's `nav_updated_at >= oldest_pending_at`, that requires a NAV\n * write STRICTLY NEWER than the one in force when the request was queued.\n *\n * KNOWN RESIDUAL — a newer VERSION does not prove a later VALUATION. An\n * `update_nav_checked` prepared BEFORE the request can still land after it:\n * its compare-and-set covers only `(nav, total_shares, nav_updated_at)`, and\n * a fee-free illiquid queue changes none of them. `apply_illiquid_withdrawal`\n * adds only `fee_shares` (zero here) to `total_shares` and moves\n * `pending_withdrawal_value`, which is NOT part of the CAS tuple — the\n * cross-chain path passes `fee_shares = 0` explicitly. So the prepared\n * update still validates, advances the timestamp past the floor, and\n * fulfilment settles against a valuation computed before the request.\n *\n * Two writers, two different bounds:\n *\n * - `update_nav_checked` — bounded by the publisher's prepare-to-publish\n * interval (`NAV_PUBLISH_INTENT_MAX_AGE_MS`, 120s in gamma-vault-agents),\n * because a prepared intent older than that is discarded client-side.\n * - `update_nav` (legacy, `handler`) — **UNBOUNDED**. It validates no\n * expected state and carries no age limit, so a valuation computed\n * arbitrarily long before the request can be published at any later time\n * and will advance `nav_updated_at` past the floor.\n *\n * This residual is still reachable WITHOUT any privileged actor: a holder\n * only has to queue between an honest publisher's prepare and its publish.\n * No compromised key and no operator error is required — only timing inside\n * that window. What the `+1` narrows is the SIZE of the window (from \"any\n * NAV after the first request on the receipt\" to \"the publisher's in-flight\n * interval\"), not the privilege needed to hit it.\n *\n * The legacy entrypoint is already slated for removal (gamma-vault-agents\n * calls only `update_nav_checked`, with no fallback, and the legacy client\n * helper has no callers). Deleting it closes the unbounded half of this\n * residual and should be sequenced with removing the web-server's\n * `/gamma/update-vault-nav` route.\n *\n * Either way this is strictly narrower than the pre-fix behaviour, which\n * accepted any NAV after the FIRST request on the receipt.\n *\n * Closing it requires the queue to invalidate in-flight NAV writes — i.e.\n * extending the CAS tuple with `pending_withdrawal_value` (or a receipt\n * version). That changes `update_nav_checked`'s signature, so it is a\n * coordinated program + IDL + agent + web-server change and an on-chain\n * upgrade; the agent calls `update_nav_checked` with no fallback, so a\n * required new argument breaks it against the deployed program until all\n * four ship together. Deliberately not bundled here.\n *\n * This needs no new state and no change to either comparison:\n * `next_nav_updated_at` already guarantees `nav_updated_at` strictly\n * increases on every NAV write (`max(clock_now, previous + 1)`), so\n * `observed + 1` is always reachable by the next write. It proves only that\n * the version ALREADY OBSERVED cannot settle the request — a stale\n * valuation that becomes the next write still passes, which is exactly the\n * residual above. The keeper's mirrored `>=` check keeps working unchanged.\n *\n * A wall-clock floor left a same-second hole: `Clock::unix_timestamp` is\n * second-resolution and the comparison is `>=`, so a NAV published earlier\n * in the same second as the request compared equal and passed.\n *\n * UPGRADE GATE — receipts already pending at the upgrade carry a LEGACY\n * floor. Accounts survive a program upgrade, and nothing re-stamps a\n * receipt until its next `withdraw`, so a receipt queued under the previous\n * release keeps a wall-clock, first-request-only value that\n * `fulfill_withdrawal` still accepts. Concretely: 1 share queued at T0,\n * NAV published at T1, an unrecorded loss, then 1,000,000 shares added —\n * all pre-upgrade — leaves the receipt at T0, and post-upgrade fulfilment\n * accepts the stale T1 NAV.\n *\n * Publishing a fresh NAV after the upgrade does NOT fix this: any NAV after\n * T0 satisfies a T0 floor, which is the whole defect. The gate is therefore\n * to DRAIN pending receipts before the upgrade, so no legacy floor survives\n * it.\n *\n * A scan alone is NOT sufficient: `withdraw` intake is permissionless, so a\n * user can create a fresh legacy-floor receipt between the scan and the\n * upgrade, and no off-chain maintenance mode can stop a direct transaction.\n *\n * There is no withdrawal pause flag for the native path — `withdrawals_enabled`\n * gates only the cross-chain intake, and zeroing the `WithdrawalPolicy` caps\n * REMOVES the limits rather than applying them. The one enforceable on-chain\n * lever is NAV staleness: `withdraw` begins with `require_fresh_nav`, so once\n * NAV ages past `nav_max_staleness` every new intake reverts with `StaleNav`.\n * `fulfill_withdrawal` requires fresh NAV too, so draining must finish first:\n *\n * 1. drain — fulfil until `pending_shares == 0` on EVERY receipt, with NAV\n * still being published. \"Every receipt\" means an on-chain\n * `getProgramAccounts` scan for `WithdrawReceipt` filtered by\n * `lp_vault`; the off-chain `gamma_pending_withdrawals` table is NOT a\n * valid inventory — it tracks only agent-managed parent-to-child Gamma\n * withdrawals for dedup and NAV enumeration, and omits ordinary user\n * and cross-chain receipts entirely;\n * 2. stop publishing NAV and wait out `nav_max_staleness` (1800s on prod\n * STBL1). New `withdraw` calls now revert on-chain, not by convention;\n * 3. RE-CHECK that every receipt is still at zero — nothing can have been\n * added during step 2;\n * 4. upgrade;\n * 5. resume NAV publication, which re-opens intake.\n *\n * No production pre-verification is claimed here: the scan in step 1 has not\n * been run, and the agent-side table cannot stand in for it. Steps 2 and 3\n * are required regardless, because the count can otherwise change under you.\n */\n oldestPendingAt: bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n};\n\nexport type WithdrawReceiptArgs = {\n /** User requesting withdrawal. */\n user: Address;\n /** Vault where the user has invested. */\n lpVault: Address;\n /**\n * Shares waiting for liquidity (keeper needs to fulfill these).\n * These shares are held in the escrow_shares_account.\n */\n pendingShares: number | bigint;\n /**\n * Shares that have been fulfilled and are ready to claim.\n * These shares are also in escrow_shares_account, waiting to be burned on claim.\n */\n claimableShares: number | bigint;\n /** Asset value ready to claim (held in escrow_assets_account). */\n claimableAssets: number | bigint;\n /**\n * NAV ordering floor for the whole `pending_shares` aggregate, re-derived on\n * the MOST RECENT addition.\n *\n * Despite the name and the `i64` type this is NOT a wall-clock timestamp of\n * the addition: it stores `observed_nav_updated_at + 1`, i.e. one past the\n * NAV version in force when that addition was queued. It shares the\n * `nav_updated_at` number space, which is why the existing `>=` comparisons\n * in the program and the keeper keep working unchanged.\n *\n * `fulfill_withdrawal` prices all of `pending_shares` at once and requires\n * `nav_updated_at >= oldest_pending_at`, so this must track the newest\n * request, not the first: a first-request-only stamp lets every subsequent\n * addition settle against a NAV that predates it.\n *\n * NOTE: the field name is retained for wire/IDL compatibility — the keeper\n * reads it by name and orders fulfilment on it. Renaming it to\n * `newest_pending_at` is a follow-up that must land with a keeper change.\n *\n * The floor is derived from the NAV VERSION the request observed —\n * `lp_vault.nav_updated_at + 1` — not from the wall clock. Combined with\n * fulfilment's `nav_updated_at >= oldest_pending_at`, that requires a NAV\n * write STRICTLY NEWER than the one in force when the request was queued.\n *\n * KNOWN RESIDUAL — a newer VERSION does not prove a later VALUATION. An\n * `update_nav_checked` prepared BEFORE the request can still land after it:\n * its compare-and-set covers only `(nav, total_shares, nav_updated_at)`, and\n * a fee-free illiquid queue changes none of them. `apply_illiquid_withdrawal`\n * adds only `fee_shares` (zero here) to `total_shares` and moves\n * `pending_withdrawal_value`, which is NOT part of the CAS tuple — the\n * cross-chain path passes `fee_shares = 0` explicitly. So the prepared\n * update still validates, advances the timestamp past the floor, and\n * fulfilment settles against a valuation computed before the request.\n *\n * Two writers, two different bounds:\n *\n * - `update_nav_checked` — bounded by the publisher's prepare-to-publish\n * interval (`NAV_PUBLISH_INTENT_MAX_AGE_MS`, 120s in gamma-vault-agents),\n * because a prepared intent older than that is discarded client-side.\n * - `update_nav` (legacy, `handler`) — **UNBOUNDED**. It validates no\n * expected state and carries no age limit, so a valuation computed\n * arbitrarily long before the request can be published at any later time\n * and will advance `nav_updated_at` past the floor.\n *\n * This residual is still reachable WITHOUT any privileged actor: a holder\n * only has to queue between an honest publisher's prepare and its publish.\n * No compromised key and no operator error is required — only timing inside\n * that window. What the `+1` narrows is the SIZE of the window (from \"any\n * NAV after the first request on the receipt\" to \"the publisher's in-flight\n * interval\"), not the privilege needed to hit it.\n *\n * The legacy entrypoint is already slated for removal (gamma-vault-agents\n * calls only `update_nav_checked`, with no fallback, and the legacy client\n * helper has no callers). Deleting it closes the unbounded half of this\n * residual and should be sequenced with removing the web-server's\n * `/gamma/update-vault-nav` route.\n *\n * Either way this is strictly narrower than the pre-fix behaviour, which\n * accepted any NAV after the FIRST request on the receipt.\n *\n * Closing it requires the queue to invalidate in-flight NAV writes — i.e.\n * extending the CAS tuple with `pending_withdrawal_value` (or a receipt\n * version). That changes `update_nav_checked`'s signature, so it is a\n * coordinated program + IDL + agent + web-server change and an on-chain\n * upgrade; the agent calls `update_nav_checked` with no fallback, so a\n * required new argument breaks it against the deployed program until all\n * four ship together. Deliberately not bundled here.\n *\n * This needs no new state and no change to either comparison:\n * `next_nav_updated_at` already guarantees `nav_updated_at` strictly\n * increases on every NAV write (`max(clock_now, previous + 1)`), so\n * `observed + 1` is always reachable by the next write. It proves only that\n * the version ALREADY OBSERVED cannot settle the request — a stale\n * valuation that becomes the next write still passes, which is exactly the\n * residual above. The keeper's mirrored `>=` check keeps working unchanged.\n *\n * A wall-clock floor left a same-second hole: `Clock::unix_timestamp` is\n * second-resolution and the comparison is `>=`, so a NAV published earlier\n * in the same second as the request compared equal and passed.\n *\n * UPGRADE GATE — receipts already pending at the upgrade carry a LEGACY\n * floor. Accounts survive a program upgrade, and nothing re-stamps a\n * receipt until its next `withdraw`, so a receipt queued under the previous\n * release keeps a wall-clock, first-request-only value that\n * `fulfill_withdrawal` still accepts. Concretely: 1 share queued at T0,\n * NAV published at T1, an unrecorded loss, then 1,000,000 shares added —\n * all pre-upgrade — leaves the receipt at T0, and post-upgrade fulfilment\n * accepts the stale T1 NAV.\n *\n * Publishing a fresh NAV after the upgrade does NOT fix this: any NAV after\n * T0 satisfies a T0 floor, which is the whole defect. The gate is therefore\n * to DRAIN pending receipts before the upgrade, so no legacy floor survives\n * it.\n *\n * A scan alone is NOT sufficient: `withdraw` intake is permissionless, so a\n * user can create a fresh legacy-floor receipt between the scan and the\n * upgrade, and no off-chain maintenance mode can stop a direct transaction.\n *\n * There is no withdrawal pause flag for the native path — `withdrawals_enabled`\n * gates only the cross-chain intake, and zeroing the `WithdrawalPolicy` caps\n * REMOVES the limits rather than applying them. The one enforceable on-chain\n * lever is NAV staleness: `withdraw` begins with `require_fresh_nav`, so once\n * NAV ages past `nav_max_staleness` every new intake reverts with `StaleNav`.\n * `fulfill_withdrawal` requires fresh NAV too, so draining must finish first:\n *\n * 1. drain — fulfil until `pending_shares == 0` on EVERY receipt, with NAV\n * still being published. \"Every receipt\" means an on-chain\n * `getProgramAccounts` scan for `WithdrawReceipt` filtered by\n * `lp_vault`; the off-chain `gamma_pending_withdrawals` table is NOT a\n * valid inventory — it tracks only agent-managed parent-to-child Gamma\n * withdrawals for dedup and NAV enumeration, and omits ordinary user\n * and cross-chain receipts entirely;\n * 2. stop publishing NAV and wait out `nav_max_staleness` (1800s on prod\n * STBL1). New `withdraw` calls now revert on-chain, not by convention;\n * 3. RE-CHECK that every receipt is still at zero — nothing can have been\n * added during step 2;\n * 4. upgrade;\n * 5. resume NAV publication, which re-opens intake.\n *\n * No production pre-verification is claimed here: the scan in step 1 has not\n * been run, and the agent-side table cannot stand in for it. Steps 2 and 3\n * are required regardless, because the count can otherwise change under you.\n */\n oldestPendingAt: number | bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n};\n\n/** Gets the encoder for {@link WithdrawReceiptArgs} account data. */\nexport function getWithdrawReceiptEncoder(): FixedSizeEncoder<WithdrawReceiptArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"user\", getAddressEncoder()],\n [\"lpVault\", getAddressEncoder()],\n [\"pendingShares\", getU64Encoder()],\n [\"claimableShares\", getU64Encoder()],\n [\"claimableAssets\", getU64Encoder()],\n [\"oldestPendingAt\", getI64Encoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: WITHDRAW_RECEIPT_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link WithdrawReceipt} account data. */\nexport function getWithdrawReceiptDecoder(): FixedSizeDecoder<WithdrawReceipt> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"user\", getAddressDecoder()],\n [\"lpVault\", getAddressDecoder()],\n [\"pendingShares\", getU64Decoder()],\n [\"claimableShares\", getU64Decoder()],\n [\"claimableAssets\", getU64Decoder()],\n [\"oldestPendingAt\", getI64Decoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link WithdrawReceipt} account data. */\nexport function getWithdrawReceiptCodec(): FixedSizeCodec<WithdrawReceiptArgs, WithdrawReceipt> {\n return combineCodec(getWithdrawReceiptEncoder(), getWithdrawReceiptDecoder());\n}\n\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<WithdrawReceipt, TAddress>;\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<WithdrawReceipt, TAddress>;\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<WithdrawReceipt, TAddress> | MaybeAccount<WithdrawReceipt, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getWithdrawReceiptDecoder()\n );\n}\n\nexport async function fetchWithdrawReceipt<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<WithdrawReceipt, TAddress>> {\n const maybeAccount = await fetchMaybeWithdrawReceipt(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeWithdrawReceipt<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<WithdrawReceipt, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeWithdrawReceipt(maybeAccount);\n}\n\nexport async function fetchAllWithdrawReceipt(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<WithdrawReceipt>[]> {\n const maybeAccounts = await fetchAllMaybeWithdrawReceipt(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeWithdrawReceipt(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<WithdrawReceipt>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeWithdrawReceipt(maybeAccount));\n}\n\nexport function getWithdrawReceiptSize(): number {\n return 105;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type CompleteWithdrawalWithdrawEscrowSeeds = {\n user: Address;\n lpVault: Address;\n};\n\nexport async function findCompleteWithdrawalWithdrawEscrowPda(\n seeds: CompleteWithdrawalWithdrawEscrowSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([119, 105, 116, 104, 100, 114, 97, 119, 95, 101, 115, 99, 114, 111, 119])\n ),\n getAddressEncoder().encode(seeds.user),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type WithdrawReceiptSeeds = {\n crossChainWithdrawer: Address;\n lpVault: Address;\n};\n\nexport async function findWithdrawReceiptPda(\n seeds: WithdrawReceiptSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([\n 119, 105, 116, 104, 100, 114, 97, 119, 95, 114, 101, 99, 101, 105, 112, 116,\n ])\n ),\n getAddressEncoder().encode(seeds.crossChainWithdrawer),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getLpVaultCodec,\n getWithdrawReceiptCodec,\n type LpVault,\n type LpVaultArgs,\n type WithdrawReceipt,\n type WithdrawReceiptArgs,\n} from \"../accounts\";\nimport {\n getCompleteWithdrawalInstructionAsync,\n getDepositInstructionAsync,\n getWithdrawInstructionAsync,\n parseCompleteWithdrawalInstruction,\n parseDepositInstruction,\n parseWithdrawInstruction,\n type CompleteWithdrawalAsyncInput,\n type DepositAsyncInput,\n type ParsedCompleteWithdrawalInstruction,\n type ParsedDepositInstruction,\n type ParsedWithdrawInstruction,\n type WithdrawAsyncInput,\n} from \"../instructions\";\nimport {\n findAssetsAccountPda,\n findCompleteWithdrawalWithdrawEscrowPda,\n findCompleteWithdrawalWithdrawReceiptPda,\n findCrossChainConfigPda,\n findCrossChainDepositAndBridgeDepositReceiptPda,\n findCrossChainIntentPda,\n findCrossChainSenderPda,\n findCrossChainVaultRoutePda,\n findCrossChainWithdrawerPda,\n findDepositPolicyPda,\n findDepositReceiptPda,\n findGlobalConfigPda,\n findLpVaultPda,\n findNavUpdatePolicyPda,\n findPendingSharesAccountPda,\n findReceiveCrossChainWithdrawalCrossChainIntentPda,\n findSharesMintPda,\n findWithdrawalPolicyPda,\n findWithdrawEscrowPda,\n findWithdrawReceiptPda,\n} from \"../pdas\";\n\nexport const GAMMA_VAULT_PROGRAM_ADDRESS =\n \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">;\n\nexport enum GammaVaultAccount {\n LpVault,\n WithdrawReceipt,\n}\n\nexport function identifyGammaVaultAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): GammaVaultAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([189, 45, 167, 23, 91, 118, 105, 190])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.LpVault;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([132, 238, 44, 182, 207, 9, 124, 140])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.WithdrawReceipt;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"gammaVault\",\n });\n}\n\nexport enum GammaVaultInstruction {\n CompleteWithdrawal,\n Deposit,\n Withdraw,\n}\n\nexport function identifyGammaVaultInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): GammaVaultInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([107, 98, 134, 131, 74, 120, 174, 121])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.CompleteWithdrawal;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([242, 35, 198, 137, 82, 225, 242, 182])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.Deposit;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([183, 18, 70, 156, 148, 109, 161, 34])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.Withdraw;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"gammaVault\",\n });\n}\n\nexport type ParsedGammaVaultInstruction<\n TProgram extends string = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\",\n> =\n | ({\n instructionType: GammaVaultInstruction.CompleteWithdrawal;\n } & ParsedCompleteWithdrawalInstruction<TProgram>)\n | ({ instructionType: GammaVaultInstruction.Deposit } & ParsedDepositInstruction<TProgram>)\n | ({ instructionType: GammaVaultInstruction.Withdraw } & ParsedWithdrawInstruction<TProgram>);\n\nexport function parseGammaVaultInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedGammaVaultInstruction<TProgram> {\n const instructionType = identifyGammaVaultInstruction(instruction);\n switch (instructionType) {\n case GammaVaultInstruction.CompleteWithdrawal: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.CompleteWithdrawal,\n ...parseCompleteWithdrawalInstruction(instruction),\n };\n }\n case GammaVaultInstruction.Deposit: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.Deposit,\n ...parseDepositInstruction(instruction),\n };\n }\n case GammaVaultInstruction.Withdraw: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.Withdraw,\n ...parseWithdrawInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"gammaVault\",\n });\n }\n}\n\nexport type GammaVaultPlugin = {\n accounts: GammaVaultPluginAccounts;\n instructions: GammaVaultPluginInstructions;\n pdas: GammaVaultPluginPdas;\n identifyAccount: typeof identifyGammaVaultAccount;\n identifyInstruction: typeof identifyGammaVaultInstruction;\n parseInstruction: typeof parseGammaVaultInstruction;\n};\n\nexport type GammaVaultPluginAccounts = {\n lpVault: ReturnType<typeof getLpVaultCodec> & SelfFetchFunctions<LpVaultArgs, LpVault>;\n withdrawReceipt: ReturnType<typeof getWithdrawReceiptCodec> &\n SelfFetchFunctions<WithdrawReceiptArgs, WithdrawReceipt>;\n};\n\nexport type GammaVaultPluginInstructions = {\n completeWithdrawal: (\n input: CompleteWithdrawalAsyncInput\n ) => ReturnType<typeof getCompleteWithdrawalInstructionAsync> & SelfPlanAndSendFunctions;\n deposit: (\n input: DepositAsyncInput\n ) => ReturnType<typeof getDepositInstructionAsync> & SelfPlanAndSendFunctions;\n withdraw: (\n input: WithdrawAsyncInput\n ) => ReturnType<typeof getWithdrawInstructionAsync> & SelfPlanAndSendFunctions;\n};\n\nexport type GammaVaultPluginPdas = {\n crossChainWithdrawer: typeof findCrossChainWithdrawerPda;\n withdrawReceipt: typeof findWithdrawReceiptPda;\n withdrawEscrow: typeof findWithdrawEscrowPda;\n depositReceipt: typeof findDepositReceiptPda;\n completeWithdrawalWithdrawEscrow: typeof findCompleteWithdrawalWithdrawEscrowPda;\n completeWithdrawalWithdrawReceipt: typeof findCompleteWithdrawalWithdrawReceiptPda;\n crossChainConfig: typeof findCrossChainConfigPda;\n crossChainVaultRoute: typeof findCrossChainVaultRoutePda;\n crossChainIntent: typeof findCrossChainIntentPda;\n crossChainSender: typeof findCrossChainSenderPda;\n crossChainDepositAndBridgeDepositReceipt: typeof findCrossChainDepositAndBridgeDepositReceiptPda;\n withdrawalPolicy: typeof findWithdrawalPolicyPda;\n depositPolicy: typeof findDepositPolicyPda;\n globalConfig: typeof findGlobalConfigPda;\n navUpdatePolicy: typeof findNavUpdatePolicyPda;\n lpVault: typeof findLpVaultPda;\n sharesMint: typeof findSharesMintPda;\n assetsAccount: typeof findAssetsAccountPda;\n pendingSharesAccount: typeof findPendingSharesAccountPda;\n receiveCrossChainWithdrawalCrossChainIntent: typeof findReceiveCrossChainWithdrawalCrossChainIntentPda;\n};\n\nexport type GammaVaultPluginRequirements = ClientWithRpc<\n GetAccountInfoApi & GetMultipleAccountsApi\n> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function gammaVaultProgram() {\n return <T extends GammaVaultPluginRequirements>(\n client: T\n ): ExtendedClient<T, { gammaVault: GammaVaultPlugin }> => {\n return extendClient(client, {\n gammaVault: <GammaVaultPlugin>{\n accounts: {\n lpVault: addSelfFetchFunctions(client, getLpVaultCodec()),\n withdrawReceipt: addSelfFetchFunctions(client, getWithdrawReceiptCodec()),\n },\n instructions: {\n completeWithdrawal: (input) =>\n addSelfPlanAndSendFunctions(client, getCompleteWithdrawalInstructionAsync(input)),\n deposit: (input) =>\n addSelfPlanAndSendFunctions(client, getDepositInstructionAsync(input)),\n withdraw: (input) =>\n addSelfPlanAndSendFunctions(client, getWithdrawInstructionAsync(input)),\n },\n pdas: {\n crossChainWithdrawer: findCrossChainWithdrawerPda,\n withdrawReceipt: findWithdrawReceiptPda,\n withdrawEscrow: findWithdrawEscrowPda,\n depositReceipt: findDepositReceiptPda,\n completeWithdrawalWithdrawEscrow: findCompleteWithdrawalWithdrawEscrowPda,\n completeWithdrawalWithdrawReceipt: findCompleteWithdrawalWithdrawReceiptPda,\n crossChainConfig: findCrossChainConfigPda,\n crossChainVaultRoute: findCrossChainVaultRoutePda,\n crossChainIntent: findCrossChainIntentPda,\n crossChainSender: findCrossChainSenderPda,\n crossChainDepositAndBridgeDepositReceipt: findCrossChainDepositAndBridgeDepositReceiptPda,\n withdrawalPolicy: findWithdrawalPolicyPda,\n depositPolicy: findDepositPolicyPda,\n globalConfig: findGlobalConfigPda,\n navUpdatePolicy: findNavUpdatePolicyPda,\n lpVault: findLpVaultPda,\n sharesMint: findSharesMintPda,\n assetsAccount: findAssetsAccountPda,\n pendingSharesAccount: findPendingSharesAccountPda,\n receiveCrossChainWithdrawalCrossChainIntent:\n findReceiveCrossChainWithdrawalCrossChainIntentPda,\n },\n identifyAccount: identifyGammaVaultAccount,\n identifyInstruction: identifyGammaVaultInstruction,\n parseInstruction: parseGammaVaultInstruction,\n },\n });\n };\n}\n","import type { Address, ProgramDerivedAddress, ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type { GammaLpVault, GammaWithdrawReceipt } from \"./types\";\n\nimport {\n findCompleteWithdrawalWithdrawEscrowPda,\n findWithdrawReceiptPda,\n getLpVaultDecoder,\n getWithdrawReceiptDecoder,\n LP_VAULT_DISCRIMINATOR,\n WITHDRAW_RECEIPT_DISCRIMINATOR,\n} from \"~/generated/gamma\";\n\nexport { GAMMA_VAULT_PROGRAM_ADDRESS } from \"~/generated/gamma\";\n\n/**\n * Decodes a Gamma `LpVault` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaLpVault(data: ReadonlyUint8Array): GammaLpVault {\n return decodeAccountData(data, LP_VAULT_DISCRIMINATOR, getLpVaultDecoder(), \"Gamma LpVault\");\n}\n\n/**\n * Decodes a Gamma `WithdrawReceipt` account (a user's pending → claimable withdrawal).\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaWithdrawReceipt(data: ReadonlyUint8Array): GammaWithdrawReceipt {\n return decodeAccountData(\n data,\n WITHDRAW_RECEIPT_DISCRIMINATOR,\n getWithdrawReceiptDecoder(),\n \"Gamma WithdrawReceipt\"\n );\n}\n\n/** `user`'s withdraw receipt PDA for `lpVault`. */\nexport function deriveGammaWithdrawReceipt(\n user: Address,\n lpVault: Address\n): Promise<ProgramDerivedAddress> {\n return findWithdrawReceiptPda({ crossChainWithdrawer: user, lpVault });\n}\n\n/** `user`'s withdraw escrow PDA for `lpVault` (owner of the escrow token accounts). */\nexport function deriveGammaWithdrawEscrow(\n user: Address,\n lpVault: Address\n): Promise<ProgramDerivedAddress> {\n return findCompleteWithdrawalWithdrawEscrowPda({ user, lpVault });\n}\n","// Minimal Titan V1 WebSocket client — vendored from @titanexchange/sdk-ts\n// Source: https://github.com/Titan-Pathfinder/titan-sdk-ts (MIT)\n//\n// Differences from upstream:\n// - No compression (negotiates only \"v1.api.titan.ag\" subprotocol)\n// - Uses `ws` package instead of `websocket`\n// - Only implements connect, newSwapQuoteStream, stopStream, close\n\nimport { Encoder, Decoder } from \"@msgpack/msgpack\";\nimport WebSocket from \"ws\";\n\nimport type {\n ClientRequest,\n SwapQuoteRequest,\n ServerMessage,\n ResponseSuccess,\n ResponseError,\n StreamData,\n StreamEnd,\n SwapQuotes,\n QuoteSwapStreamResponse,\n StopStreamResponse,\n} from \"./types\";\n\nconst SUBPROTOCOL = \"v1.api.titan.ag\";\nconst UINT64_MAX = (1n << 64n) - 1n;\n\nfunction toBigInt(value: number | bigint): bigint {\n if (typeof value === \"bigint\") {\n if (value < 0n || value > UINT64_MAX) {\n throw new RangeError(`Amount out of uint64 range: ${value}`);\n }\n return value;\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`Amount must be a whole number, got ${value}`);\n }\n if (value < 0) {\n throw new RangeError(`Amount must be non-negative, got ${value}`);\n }\n return BigInt(value);\n}\n\n// --- Error classes ---\n\nexport class ConnectionClosed extends Error {\n code: number;\n reason: string;\n\n constructor(code: number, reason: string) {\n super(`Client WebSocket closed with code ${code}: ${reason}`);\n this.name = \"ConnectionClosed\";\n Object.setPrototypeOf(this, ConnectionClosed.prototype);\n this.code = code;\n this.reason = reason;\n }\n}\n\nexport class ErrorResponse extends Error {\n response: ResponseError;\n\n constructor(response: ResponseError) {\n super(`Request ${response.requestId} failed with code ${response.code}: ${response.message}`);\n this.name = \"ErrorResponse\";\n Object.setPrototypeOf(this, ErrorResponse.prototype);\n this.response = response;\n }\n}\n\nexport class StreamError extends Error {\n streamId: number;\n errorCode: number;\n errorMessage: string;\n\n constructor(packet: StreamEnd) {\n const code = packet.errorCode ?? 0;\n const message = packet.errorMessage ?? \"\";\n super(`Stream ${packet.id} ended with error code ${code}: ${message}`);\n this.name = \"StreamError\";\n Object.setPrototypeOf(this, StreamError.prototype);\n this.streamId = packet.id;\n this.errorCode = code;\n this.errorMessage = message;\n }\n}\n\n// --- Response handler types ---\n\nexport interface ResponseWithStream<T, D> {\n response: T;\n stream: ReadableStream<D>;\n streamId: number;\n}\n\ntype Resolver<T> = (value: T | PromiseLike<T>) => void;\ntype Rejector = (reason?: unknown) => void;\n\ninterface PendingRequest {\n resolve: Resolver<unknown>;\n reject: Rejector;\n kind: \"NewSwapQuoteStream\" | \"StopStream\";\n}\n\n// --- Codec (msgpack, no compression) ---\n\nconst encoder = new Encoder({ useBigInt64: true });\nconst decoder = new Decoder({ useBigInt64: true });\n\n// --- V1Client ---\n\nexport class V1Client {\n private socket: WebSocket;\n private nextId = 0;\n private _closed = false;\n private _closing = false;\n\n private pending = new Map<number, PendingRequest>();\n private streams = new Map<number, ReadableStreamDefaultController<SwapQuotes>>();\n private streamStopping = new Map<number, boolean>();\n private closeListeners: { resolve: Resolver<void>; reject: Rejector }[] = [];\n\n // --- Static connect ---\n\n static connect(url: string): Promise<V1Client> {\n return new Promise<V1Client>((resolve, reject) => {\n const ws = new WebSocket(url, [SUBPROTOCOL]);\n\n ws.binaryType = \"arraybuffer\";\n\n const onOpen = () => {\n // ws doesn't populate .protocol when using the `ws` library in Node\n // but since we only offer one subprotocol, the server must accept it.\n ws.off(\"error\", onError);\n ws.off(\"close\", onClose);\n resolve(new V1Client(ws));\n };\n const onError = (err: Error) => {\n ws.off(\"open\", onOpen);\n ws.off(\"close\", onClose);\n reject(err);\n };\n // Guard against the socket closing before `open` fires without a\n // preceding `error` (e.g. a clean close during handshake). Without this\n // the promise would hang forever.\n const onClose = (code: number, reason: Buffer) => {\n ws.off(\"open\", onOpen);\n ws.off(\"error\", onError);\n reject(\n new Error(\n `WebSocket closed before open (code=${code}${\n reason.length ? `, reason=${reason.toString()}` : \"\"\n })`\n )\n );\n };\n\n ws.once(\"open\", onOpen);\n ws.once(\"error\", onError);\n ws.once(\"close\", onClose);\n });\n }\n\n // --- Constructor ---\n\n private constructor(socket: WebSocket) {\n this.socket = socket;\n\n this.socket.on(\"message\", (data: WebSocket.RawData) => {\n this.handleMessage(data);\n });\n this.socket.on(\"close\", (code: number, reason: Buffer) => {\n this.handleClose(code, reason.toString());\n });\n this.socket.on(\"error\", (err: Error) => {\n this.handleError(err);\n });\n }\n\n private nextRequestId(): number {\n return this.nextId++;\n }\n\n // --- Public API ---\n\n public get closed(): boolean {\n return this._closed;\n }\n\n public close(): Promise<void> {\n if (this._closed) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n this.closeListeners.push({ resolve, reject });\n if (!this._closing) {\n this._closing = true;\n this.socket.close();\n }\n });\n }\n\n public newSwapQuoteStream(\n params: SwapQuoteRequest\n ): Promise<ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes>> {\n const requestId = this.nextRequestId();\n\n const promise = new Promise<ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes>>(\n (resolve, reject) => {\n this.pending.set(requestId, {\n resolve: resolve as Resolver<unknown>,\n reject,\n kind: \"NewSwapQuoteStream\",\n });\n }\n );\n\n const normalized: SwapQuoteRequest = {\n ...params,\n swap: { ...params.swap, amount: toBigInt(params.swap.amount) },\n };\n\n const message: ClientRequest = {\n id: requestId,\n data: { NewSwapQuoteStream: normalized },\n };\n this.send(message);\n\n return promise;\n }\n\n public stopStream(streamId: number): Promise<StopStreamResponse> {\n const requestId = this.nextRequestId();\n\n const promise = new Promise<StopStreamResponse>((resolve, reject) => {\n this.pending.set(requestId, {\n resolve: resolve as Resolver<unknown>,\n reject,\n kind: \"StopStream\",\n });\n });\n\n const message: ClientRequest = {\n id: requestId,\n data: { StopStream: { id: streamId } },\n };\n this.send(message);\n\n return promise;\n }\n\n // --- Send ---\n\n private send(message: ClientRequest): void {\n try {\n const encoded = encoder.encode(message);\n this.socket.send(encoded);\n } catch (err) {\n const req = this.pending.get(message.id);\n if (req) {\n this.pending.delete(message.id);\n req.reject(err);\n }\n }\n }\n\n // --- Message handling ---\n\n private handleMessage(raw: WebSocket.RawData): void {\n let buf: Uint8Array;\n if (raw instanceof ArrayBuffer) {\n buf = new Uint8Array(raw);\n } else if (Buffer.isBuffer(raw)) {\n buf = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n } else if (Array.isArray(raw)) {\n buf = new Uint8Array(Buffer.concat(raw));\n } else {\n return;\n }\n\n let message: ServerMessage;\n try {\n message = decoder.decode(buf) as ServerMessage;\n } catch {\n this.socket.close(3002, \"failed to decode message\");\n return;\n }\n\n if (\"Response\" in message) {\n this.handleResponse(message.Response);\n } else if (\"Error\" in message) {\n this.handleResponseError(message.Error);\n } else if (\"StreamData\" in message) {\n this.handleStreamData(message.StreamData);\n } else if (\"StreamEnd\" in message) {\n this.handleStreamEnd(message.StreamEnd);\n }\n }\n\n private handleResponse(msg: ResponseSuccess): void {\n const req = this.pending.get(msg.requestId);\n if (!req) return;\n this.pending.delete(msg.requestId);\n\n if (\"NewSwapQuoteStream\" in msg.data && req.kind === \"NewSwapQuoteStream\") {\n const streamInfo = msg.stream;\n if (!streamInfo) {\n req.reject(new Error(\"No stream associated with NewSwapQuoteStream response\"));\n return;\n }\n const stream = new ReadableStream<SwapQuotes>({\n start: (controller) => {\n this.streams.set(streamInfo.id, controller);\n },\n cancel: () => {\n return this.cancelStream(streamInfo.id);\n },\n });\n const result: ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes> = {\n response: msg.data.NewSwapQuoteStream,\n stream,\n streamId: streamInfo.id,\n };\n req.resolve(result);\n } else if (\"StreamStopped\" in msg.data && req.kind === \"StopStream\") {\n req.resolve(msg.data.StreamStopped);\n } else {\n req.reject(new Error(`Unexpected response type for ${req.kind}`));\n }\n }\n\n private handleResponseError(error: ResponseError): void {\n const req = this.pending.get(error.requestId);\n if (!req) return;\n this.pending.delete(error.requestId);\n req.reject(new ErrorResponse(error));\n }\n\n private handleStreamData(packet: StreamData): void {\n const controller = this.streams.get(packet.id);\n if (!controller) return;\n if (packet.payload.SwapQuotes !== undefined) {\n controller.enqueue(packet.payload.SwapQuotes);\n }\n }\n\n private handleStreamEnd(packet: StreamEnd): void {\n const controller = this.streams.get(packet.id);\n if (!controller) return;\n this.streams.delete(packet.id);\n this.streamStopping.delete(packet.id);\n\n if (packet.errorCode !== undefined) {\n controller.error(new StreamError(packet));\n } else {\n controller.close();\n }\n }\n\n private async cancelStream(streamId: number): Promise<void> {\n if (this.streamStopping.get(streamId) || !this.streams.has(streamId)) return;\n this.streamStopping.set(streamId, true);\n await this.stopStream(streamId);\n }\n\n // --- Connection lifecycle ---\n\n private rejectAll(error: Error): void {\n for (const req of this.pending.values()) {\n req.reject(error);\n }\n this.pending.clear();\n for (const controller of this.streams.values()) {\n controller.error(error);\n }\n this.streams.clear();\n this.streamStopping.clear();\n }\n\n private handleClose(code: number, reason: string): void {\n this._closed = true;\n this.rejectAll(new ConnectionClosed(code, reason));\n for (const listener of this.closeListeners) {\n listener.resolve();\n }\n this.closeListeners = [];\n }\n\n private handleError(err: Error): void {\n this.rejectAll(err);\n this.socket.close(3002);\n }\n}\n","// Vendored Titan protocol types — cherry-picked from @titanexchange/sdk-ts\n// Source: https://github.com/Titan-Pathfinder/titan-sdk-ts (MIT)\n\n// --- Common types ---\n\n/** A Solana account public key, encoded as 32 bytes by msgpack. */\nexport type Pubkey = Uint8Array;\n\n/** Solana account metadata for an instruction. */\nexport interface AccountMeta {\n /** Public key for the account. */\n p: Pubkey;\n /** Whether the account is a signer. */\n s: boolean;\n /** Whether the account is writable. */\n w: boolean;\n}\n\n/** A single instruction to be executed as part of a transaction. */\nexport interface Instruction {\n /** Program id. */\n p: Pubkey;\n /** Account metadata. */\n a: AccountMeta[];\n /** Instruction data. */\n d: Uint8Array;\n}\n\n/** An address lookup table referenced by a transaction template (key + inner addresses). */\nexport interface TransactionTemplateLut {\n /** ALT account address. */\n p: Pubkey;\n /** Addresses stored inside the ALT, in order. */\n a: Pubkey[];\n}\n\n/**\n * Footprint of the instructions/ALTs surrounding the swap, so the router sizes\n * routes to fit alongside them. Wire format uses single-letter fields: `i`\n * instructions, `a` ALTs, `m` extra account metas. See the gateway helper\n * `buildTitanTemplate`. Over the WebSocket this is sent as a native msgpack\n * object (no base64) — unlike the gateway GET there is no URL-length limit, so\n * large ALTs are fine.\n */\nexport interface TransactionTemplate {\n i: Instruction[];\n a: TransactionTemplateLut[];\n m: AccountMeta[];\n /** Transaction-level compute budget; required with `transactionFormat: 1`, ignored for v0. */\n c?: TransactionConfigParams;\n}\n\n/** Compute budget a v1 transaction carries in its message; omitted fields use the runtime default. */\nexport interface TransactionConfigParams {\n priorityFee?: number;\n computeUnitLimit?: number;\n loadedAccountsDataSizeLimit?: number;\n}\n\nexport enum SwapMode {\n ExactIn = \"ExactIn\",\n ExactOut = \"ExactOut\",\n}\n\n// --- Client request types ---\n\nexport type Uint64 = number | bigint;\n\nexport interface ClientRequest {\n id: number;\n data: RequestData;\n}\n\nexport type RequestData =\n | { NewSwapQuoteStream: SwapQuoteRequest }\n | { StopStream: StopStreamRequest };\n\nexport interface SwapQuoteRequest {\n swap: SwapParams;\n transaction: TransactionParams;\n update?: QuoteUpdateParams;\n}\n\nexport interface SwapParams {\n inputMint: Pubkey;\n outputMint: Pubkey;\n amount: Uint64;\n swapMode?: SwapMode;\n slippageBps?: number;\n dexes?: string[];\n excludeDexes?: string[];\n /**\n * Exclude the server-configured \"vote account\" venues from routing. Those venues touch validator\n * vote accounts, which Jito refuses to bundle — so a swap that routes through them can't land inside\n * our flashloan/double-hop Jito bundles. Set `true` for bundled flows. Available since Titan v1.6.\n */\n noVoteAccounts?: boolean;\n onlyDirectRoutes?: boolean;\n addSizeConstraint?: boolean;\n sizeConstraint?: number;\n providers?: string[];\n /** Limit total number of accounts used by routes. Default: 256. Available since v1.1. */\n accountsLimitTotal?: number;\n /** Limit writable accounts used by routes. Default: 64. Available since v1.1. */\n accountsLimitWritable?: number;\n /**\n * Reserve room for the surrounding (non-swap) instructions + ALTs so the\n * router sizes routes to fit. Mutually exclusive with `sizeConstraint` /\n * `accountsLimitTotal` / `accountsLimitWritable`. Available since v1.2.\n */\n transactionTemplate?: TransactionTemplate;\n}\n\nexport interface TransactionParams {\n userPublicKey: Pubkey;\n closeInputTokenAccount?: boolean;\n createOutputTokenAccount?: boolean;\n feeAccount?: Pubkey;\n feeBps?: number;\n feeFromInputMint?: boolean;\n outputAccount?: Pubkey;\n titanSwapVersion?: SwapVersion;\n /**\n * `true` leaves a wSOL output as wrapped SOL (the wSOL SPL token) instead of\n * unwrapping it to native lamports. Default `false`. Only has an effect when\n * `outputMint == wSOL`; ignored otherwise. Requires `titanSwapVersion=3`.\n */\n outputWsol?: boolean;\n /**\n * Transaction format routes are sized for: `0` (default) a v0 transaction of 1232 bytes, `1` a\n * v1 transaction of 4096 bytes without ALTs, which needs the template's `c` and\n * `titanSwapVersion=3`.\n */\n transactionFormat?: 0 | 1;\n}\n\nexport enum SwapVersion {\n V2 = 2,\n V3 = 3,\n}\n\nexport interface QuoteUpdateParams {\n intervalMs?: Uint64;\n num_quotes: number;\n}\n\nexport interface StopStreamRequest {\n id: number;\n}\n\n// --- Server message types ---\n\nexport type ServerMessage =\n | { Response: ResponseSuccess }\n | { Error: ResponseError }\n | { StreamData: StreamData }\n | { StreamEnd: StreamEnd };\n\nexport type ResponseData =\n | { NewSwapQuoteStream: QuoteSwapStreamResponse }\n | { StreamStopped: StopStreamResponse };\n\nexport interface StreamStart {\n id: number;\n dataType: string;\n}\n\nexport interface ResponseSuccess {\n requestId: number;\n data: ResponseData;\n stream?: StreamStart;\n}\n\nexport interface ResponseError {\n requestId: number;\n code: number;\n message: string;\n}\n\nexport type StreamDataPayload = { SwapQuotes: SwapQuotes };\n\nexport interface StreamData {\n id: number;\n seq: number;\n payload: StreamDataPayload;\n}\n\nexport interface StreamEnd {\n id: number;\n errorCode?: number;\n errorMessage?: string;\n}\n\nexport interface QuoteSwapStreamResponse {\n intervalMs: number;\n}\n\nexport interface StopStreamResponse {\n id: number;\n}\n\n// --- Quote / Route types ---\n\nexport interface SwapQuotes {\n id: string;\n inputMint: Uint8Array;\n outputMint: Uint8Array;\n swapMode: SwapMode;\n amount: number;\n quotes: { [key: string]: SwapRoute };\n /** Present when DART is enabled; names the route Titan recommends. */\n metadata?: { ExpectedWinner?: string };\n}\n\nexport interface SwapRoute {\n inAmount: number;\n outAmount: number;\n slippageBps: number;\n platformFee?: PlatformFee;\n steps: RoutePlanStep[];\n instructions: Instruction[];\n addressLookupTables: Pubkey[];\n contextSlot?: number;\n timeTaken?: number;\n expiresAtMs?: number;\n expiresAfterSlot?: number;\n computeUnits?: number;\n computeUnitsSafe?: number;\n transaction?: Uint8Array;\n referenceId?: string;\n}\n\nexport interface PlatformFee {\n amount: number;\n fee_bps: number;\n}\n\nexport interface RoutePlanStep {\n ammKey: Uint8Array;\n label: string;\n inputMint: Uint8Array;\n outputMint: Uint8Array;\n inAmount: number;\n outAmount: number;\n allocPpb: number;\n feeMint?: Uint8Array;\n feeAmount?: number;\n contextSlot?: number;\n}\n","// Shared Titan proxy response helpers — used by both SDK and web app\n// to deserialize, select, and build results from the HTTP proxy's\n// base64-serialized responses.\n\nimport {\n AccountRole,\n assertAccountDecoded,\n fetchJsonParsedAccounts,\n getAddressDecoder,\n getBase64Encoder,\n upgradeRoleToSigner,\n upgradeRoleToWritable,\n type Address,\n type AddressesByLookupTableAddress,\n type GetMultipleAccountsApi,\n type Instruction,\n type Rpc,\n} from \"@solana/kit\";\n\n// --- Serialized (base64) types from the HTTP proxy ---\n\nexport interface SerializedInstruction {\n p: string; // base64 program id\n a: { p: string; s: boolean; w: boolean }[]; // base64 accounts\n d: string; // base64 data\n}\n\nexport interface SerializedSwapRoute {\n inAmount: number;\n outAmount: number;\n slippageBps: number;\n platformFee?: { amount: number; fee_bps: number };\n instructions: SerializedInstruction[];\n addressLookupTables: string[]; // base64 encoded pubkeys\n contextSlot?: number;\n timeTaken?: number;\n}\n\nexport interface TitanProxySwapQuoteResponse {\n quotes: { [providerId: string]: SerializedSwapRoute };\n inputMint: string; // base64\n outputMint: string; // base64\n swapMode: string;\n amount: number;\n}\n\nexport interface TitanProxyExactOutResponse {\n inAmount: number;\n outAmount: number;\n otherAmountThreshold: string;\n slippageBps: number;\n}\n\n// --- Deserialization ---\n\n/**\n * Titan's router stamps a read-only `jitodontfront…` MEV-guard account onto the\n * swap instruction. Jito refuses to bundle any transaction that touches a `jito*`\n * marker, so we drop it to keep the swap landable inside a Jito bundle (our\n * flashloan swaps are bundled).\n */\nexport const isJitoDontFront = (address: Address) => address.startsWith(\"jitodontfront\");\n\n/** Kit account role for Titan's `s` (signer) / `w` (writable) flags. */\nexport function titanAccountRole(isSigner: boolean, isWritable: boolean): AccountRole {\n const role = isWritable ? upgradeRoleToWritable(AccountRole.READONLY) : AccountRole.READONLY;\n return isSigner ? upgradeRoleToSigner(role) : role;\n}\n\n/** Deserializes a base64 HTTP-proxy instruction, dropping the `jitodontfront` marker account. */\nexport function deserializeSerializedInstruction(ix: SerializedInstruction): Instruction {\n const fromBase64 = (value: string) =>\n getAddressDecoder().decode(getBase64Encoder().encode(value));\n return {\n programAddress: fromBase64(ix.p),\n accounts: ix.a\n .map((account) => ({\n address: fromBase64(account.p),\n role: titanAccountRole(account.s, account.w),\n }))\n .filter((account) => !isJitoDontFront(account.address)),\n data: getBase64Encoder().encode(ix.d),\n };\n}\n\n// --- Route selection ---\n\nexport function selectBestRoute<T extends { inAmount: number; outAmount: number }>(\n quotes: { [id: string]: T },\n swapMode: \"ExactIn\" | \"ExactOut\"\n): T | null {\n const routes = Object.values(quotes);\n if (routes.length === 0) return null;\n return routes.reduce((best, route) => {\n if (swapMode === \"ExactIn\") {\n return route.outAmount > best.outAmount ? route : best;\n } else {\n return route.inAmount < best.inAmount ? route : best;\n }\n });\n}\n\n// --- Quote result builder ---\n\nexport interface TitanSwapQuoteResult {\n inAmount: string;\n outAmount: string;\n otherAmountThreshold: string;\n slippageBps: number;\n platformFee?: { amount: string; feeBps: number };\n contextSlot?: number;\n timeTaken?: number;\n}\n\nexport function buildSwapQuoteResult(\n route: {\n inAmount: number | bigint;\n outAmount: number | bigint;\n slippageBps: number;\n platformFee?: { amount: number | bigint; fee_bps: number };\n contextSlot?: number;\n timeTaken?: number;\n },\n swapMode: \"ExactIn\" | \"ExactOut\"\n): TitanSwapQuoteResult {\n const slippageBps = route.slippageBps;\n // The WebSocket/protobuf path decodes int64 amounts as BigInt; token amounts fit safely in a\n // JS number, so coerce for the slippage float math (BigInt × number throws).\n const outAmount = Number(route.outAmount);\n const inAmount = Number(route.inAmount);\n\n let otherAmountThreshold: string;\n if (swapMode === \"ExactIn\") {\n otherAmountThreshold = String(Math.floor(outAmount * (1 - slippageBps / 10000)));\n } else {\n otherAmountThreshold = String(Math.ceil(inAmount * (1 + slippageBps / 10000)));\n }\n\n return {\n inAmount: String(route.inAmount),\n outAmount: String(route.outAmount),\n otherAmountThreshold,\n slippageBps,\n platformFee: route.platformFee\n ? {\n amount: String(route.platformFee.amount),\n feeBps: route.platformFee.fee_bps,\n }\n : undefined,\n contextSlot: route.contextSlot,\n timeTaken: route.timeTaken,\n };\n}\n\n// --- LUT resolution ---\n\n/** Fetches the addresses of the given lookup tables; missing tables are omitted. */\nexport async function resolveLookupTables(\n rpc: Rpc<GetMultipleAccountsApi>,\n lookupTables: Address[]\n): Promise<AddressesByLookupTableAddress> {\n if (lookupTables.length === 0) return {};\n const accounts = await fetchJsonParsedAccounts<{ addresses: Address[] }[]>(rpc, lookupTables);\n const addressesByLookupTable: AddressesByLookupTableAddress = {};\n for (const account of accounts) {\n if (!account.exists) continue;\n assertAccountDecoded(account);\n addressesByLookupTable[account.address] = account.data.addresses;\n }\n return addressesByLookupTable;\n}\n","// Titan Swap V3 gateway (REST) helpers.\n//\n// Unlike the legacy HTTP proxy path (which posts JSON to an app-side proxy that\n// translates to/from msgpack), this talks to the Titan gateway directly using\n// the msgpack wire protocol. It is meant to run server-side where the Titan API\n// key is available. V3 (`titanSwapVersion: 3`) + `transactionTemplate` let the\n// router size routes against the footprint of the rest of the transaction.\n//\n// Docs: developer-doc/swap-api/guides/transaction-template\n// developer-doc/swap-api/reference/gateway/gateway-quote-swap\n\nimport { Encoder, decode } from \"@msgpack/msgpack\";\nimport {\n getAddressDecoder,\n getAddressEncoder,\n getBase64Decoder,\n isSignerRole,\n isWritableRole,\n type AccountMeta,\n type Address,\n type AddressesByLookupTableAddress,\n type Instruction,\n} from \"@solana/kit\";\n\nimport { isJitoDontFront, titanAccountRole } from \"./helpers\";\nimport type { Instruction as TitanWireInstruction, SwapRoute } from \"./types\";\n\nconst msgpackEncoder = new Encoder({ useBigInt64: true });\n\n// --- Transaction template (wire format) ---\n//\n// Single-letter field names, raw bytes for pubkeys + instruction data. See the\n// \"Transaction Template\" guide. `i` = instructions sharing the tx, `a` = ALTs\n// already referenced (order is load-bearing), `m` = extra account metas.\n\nexport interface TitanTemplateLut {\n /** ALT account address (32 raw bytes). */\n p: Uint8Array;\n /** Addresses stored inside the ALT, in order (32 raw bytes each). */\n a: Uint8Array[];\n}\n\nexport interface TitanTransactionTemplate {\n i: TitanWireInstruction[];\n a: TitanTemplateLut[];\n m: { p: Uint8Array; s: boolean; w: boolean }[];\n}\n\nconst addressBytes = (address: Address) => Uint8Array.from(getAddressEncoder().encode(address));\n\nconst accountMetaToTitanWire = (account: AccountMeta) => ({\n p: addressBytes(account.address),\n s: isSignerRole(account.role),\n w: isWritableRole(account.role),\n});\n\n/**\n * Build a Titan `transactionTemplate` from the surrounding (non-swap) footprint.\n * ALT order is preserved — insert the tables in the order the final message will use.\n */\nexport function buildTitanTemplate(footprint: {\n instructions: Instruction[];\n luts: AddressesByLookupTableAddress;\n extraAccountMetas?: AccountMeta[];\n}): TitanTransactionTemplate {\n return {\n i: footprint.instructions.map((ix) => ({\n p: addressBytes(ix.programAddress),\n a: (ix.accounts ?? []).map(accountMetaToTitanWire),\n d: Uint8Array.from(ix.data ?? []),\n })),\n a: Object.entries(footprint.luts).map(([lookupTable, addresses]) => ({\n p: addressBytes(lookupTable as Address),\n a: addresses.map(addressBytes),\n })),\n m: (footprint.extraAccountMetas ?? []).map(accountMetaToTitanWire),\n };\n}\n\n/** msgpack-encode then base64 a template for the gateway query string. */\nexport function encodeTitanTemplate(template: TitanTransactionTemplate): string {\n return getBase64Decoder().decode(msgpackEncoder.encode(template));\n}\n\n// --- Gateway quote/swap (V3) ---\n\nexport interface TitanGatewayQuoteParams {\n /** Gateway base path, e.g. `https://<host>/api/v1`. `/quote/swap` is appended. */\n basePath: string;\n apiKey?: string;\n headers?: Record<string, string>;\n\n inputMint: string;\n outputMint: string;\n amount: number;\n userPublicKey: string;\n outputAccount: string;\n slippageBps?: number;\n swapMode?: \"ExactIn\" | \"ExactOut\";\n dexes?: string[];\n excludeDexes?: string[];\n onlyDirectRoutes?: boolean;\n /** Allowlist of quote providers by id. The gateway has no exclude-list, so to\n * drop a provider (e.g. Titan-DART) we list the ones we want. */\n providers?: string[];\n\n /** msgpack+base64 template. Mutually exclusive with the size/account limits\n * below. Note: sent as a query-string value, so a template that embeds large\n * ALTs can exceed the gateway's URI limit (414) — prefer the numeric limits\n * for flashloan footprints that reference big lookup tables. */\n transactionTemplate?: string;\n\n /** Numeric sizing (small query params; safe for LUT-heavy footprints). */\n addSizeConstraint?: boolean;\n sizeConstraint?: number;\n accountsLimitTotal?: number;\n accountsLimitWritable?: number;\n\n feeBps?: number;\n feeAccount?: string;\n}\n\nexport interface TitanGatewayQuoteResponse {\n quotes: { [id: string]: SwapRoute };\n metadata?: { ExpectedWinner?: string };\n}\n\n/**\n * Fetch a V3 quote/swap from the Titan gateway and return the best route.\n * Honors the gateway's `ExpectedWinner` when present, otherwise falls back to\n * `selectBestRoute` semantics (max out for ExactIn, min in for ExactOut).\n */\nexport async function fetchTitanQuoteSwapV3(\n params: TitanGatewayQuoteParams\n): Promise<{ route: SwapRoute; raw: TitanGatewayQuoteResponse }> {\n const {\n basePath,\n apiKey,\n headers,\n inputMint,\n outputMint,\n amount,\n userPublicKey,\n outputAccount,\n slippageBps,\n swapMode,\n dexes,\n excludeDexes,\n onlyDirectRoutes,\n providers,\n transactionTemplate,\n addSizeConstraint,\n sizeConstraint,\n accountsLimitTotal,\n accountsLimitWritable,\n feeBps,\n feeAccount,\n } = params;\n\n const query = new URLSearchParams({\n inputMint,\n outputMint,\n amount: String(amount),\n userPublicKey,\n outputAccount,\n titanSwapVersion: \"3\",\n simulate: \"false\",\n });\n if (slippageBps !== undefined) query.set(\"slippageBps\", String(slippageBps));\n if (swapMode) query.set(\"swapMode\", swapMode);\n if (dexes?.length) query.set(\"dexes\", dexes.join(\",\"));\n if (excludeDexes?.length) query.set(\"excludeDexes\", excludeDexes.join(\",\"));\n if (providers?.length) query.set(\"providers\", providers.join(\",\"));\n if (onlyDirectRoutes) query.set(\"onlyDirectRoutes\", \"true\");\n if (transactionTemplate) {\n query.set(\"transactionTemplate\", transactionTemplate);\n } else {\n // Numeric sizing (mutually exclusive with the template).\n if (addSizeConstraint) query.set(\"addSizeConstraint\", \"true\");\n if (sizeConstraint !== undefined) query.set(\"sizeConstraint\", String(sizeConstraint));\n if (accountsLimitTotal !== undefined) {\n query.set(\"accountsLimitTotal\", String(accountsLimitTotal));\n }\n if (accountsLimitWritable !== undefined) {\n query.set(\"accountsLimitWritable\", String(accountsLimitWritable));\n }\n }\n if (feeBps !== undefined && feeAccount) {\n query.set(\"feeBps\", String(feeBps));\n query.set(\"feeAccount\", feeAccount);\n }\n\n const response = await fetch(`${basePath}/quote/swap?${query.toString()}`, {\n method: \"GET\",\n headers: {\n Accept: \"application/vnd.msgpack\",\n ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n ...(headers ?? {}),\n },\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Titan gateway error (${response.status}): ${text || response.statusText}`);\n }\n\n // The gateway occasionally returns a truncated / non-msgpack body (e.g. an\n // empty \"no route\" response); decode it defensively so callers get a clean\n // error instead of an opaque msgpack RangeError.\n let raw: TitanGatewayQuoteResponse;\n try {\n raw = decode(new Uint8Array(await response.arrayBuffer())) as TitanGatewayQuoteResponse;\n } catch {\n throw new Error(\n `Titan gateway returned an undecodable response for ${inputMint} -> ${outputMint}`\n );\n }\n\n const route = selectGatewayRoute(raw, swapMode ?? \"ExactIn\");\n if (!route) {\n throw new Error(`No Titan V3 route found for ${inputMint} -> ${outputMint}`);\n }\n return { route, raw };\n}\n\n/**\n * A route is only usable if it quotes a real amount. Titan occasionally returns\n * a single `Titan-DART` (RFQ / private-swap) route that quotes `outAmount: 0` —\n * DART settles via a separate auction/signature and isn't composable inside a\n * flashloan, so we treat zero-amount routes as non-viable.\n */\nfunction isViableRoute(route: SwapRoute, swapMode: \"ExactIn\" | \"ExactOut\"): boolean {\n return swapMode === \"ExactIn\" ? route.outAmount > 0 : route.inAmount > 0;\n}\n\n/**\n * Pick the best usable route from a quotes map, honoring Titan's\n * `ExpectedWinner` when present and skipping non-viable (zero-amount) routes.\n * Shared by the gateway REST path and the WebSocket adapter.\n */\nexport function selectGatewayRoute(\n raw: TitanGatewayQuoteResponse,\n swapMode: \"ExactIn\" | \"ExactOut\"\n): SwapRoute | null {\n const viable = Object.values(raw.quotes ?? {}).filter((r) => isViableRoute(r, swapMode));\n if (viable.length === 0) return null;\n\n // Honor Titan's recommended winner only when it is itself a viable route.\n const winnerId = raw.metadata?.ExpectedWinner;\n if (winnerId) {\n const winner = raw.quotes[winnerId];\n if (winner && isViableRoute(winner, swapMode)) return winner;\n }\n\n return viable.reduce((best, route) =>\n swapMode === \"ExactIn\"\n ? route.outAmount > best.outAmount\n ? route\n : best\n : route.inAmount < best.inAmount\n ? route\n : best\n );\n}\n\n/** Deserialize a Titan wire instruction (raw bytes), dropping the `jitodontfront` marker account. */\nexport function deserializeTitanWireInstruction(ix: TitanWireInstruction): Instruction {\n return {\n programAddress: getAddressDecoder().decode(ix.p),\n accounts: ix.a\n .map((account) => ({\n address: getAddressDecoder().decode(account.p),\n role: titanAccountRole(account.s, account.w),\n }))\n .filter((account) => !isJitoDontFront(account.address)),\n data: Uint8Array.from(ix.d),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/vendor/single-spl-pool/addresses.ts","../src/vendor/single-spl-pool/instructions.ts","../src/generated/scope/types/datedPrice.ts","../src/generated/scope/types/price.ts","../src/generated/scope/accounts/oraclePrices.ts","../src/generated/scope/programs/scope.ts","../src/vendor/scope/index.ts","../src/vendor/marinade/index.ts","../src/vendor/spl-stake-pool/index.ts","../src/vendor/account-data.ts","../src/generated/kfarms/types/rewardInfo.ts","../src/generated/kfarms/types/rewardPerTimeUnitPoint.ts","../src/generated/kfarms/types/rewardScheduleCurve.ts","../src/generated/kfarms/types/tokenInfo.ts","../src/generated/kfarms/accounts/farmState.ts","../src/generated/kfarms/programs/farms.ts","../src/generated/klend/types/bigFractionBytes.ts","../src/generated/klend/types/borrowOrder.ts","../src/generated/klend/types/borrowRateCurve.ts","../src/generated/klend/types/curvePoint.ts","../src/generated/klend/types/fixedTermBorrowRolloverConfig.ts","../src/generated/klend/types/lastUpdate.ts","../src/generated/klend/types/obligationCollateral.ts","../src/generated/klend/types/obligationLiquidity.ts","../src/generated/klend/types/obligationOrder.ts","../src/generated/klend/types/priceHeuristic.ts","../src/generated/klend/types/pythConfiguration.ts","../src/generated/klend/types/reserveCollateral.ts","../src/generated/klend/types/reserveConfig.ts","../src/generated/klend/types/reserveFees.ts","../src/generated/klend/types/reserveLiquidity.ts","../src/generated/klend/types/scopeConfiguration.ts","../src/generated/klend/types/switchboardConfiguration.ts","../src/generated/klend/types/tokenInfo.ts","../src/generated/klend/types/withdrawalCaps.ts","../src/generated/klend/types/withdrawQueue.ts","../src/generated/klend/accounts/obligation.ts","../src/generated/klend/accounts/reserve.ts","../src/generated/klend/programs/kaminoLending.ts","../src/generated/klend/instructions/refreshObligation.ts","../src/generated/klend/instructions/refreshReserve.ts","../src/generated/klend/instructions/refreshReservesBatch.ts","../src/vendor/klend/accounts.ts","../src/vendor/klend/constants.ts","../src/vendor/klend/fraction.ts","../src/vendor/klend/instructions.ts","../src/vendor/klend/types.ts","../src/vendor/klend/interest-rate.ts","../src/vendor/klend/pda.ts","../src/vendor/klend/rewards.ts","../src/vendor/klend/serialize.ts","../src/constants/misc.consts.ts","../src/utils/accounting.utils.ts","../src/utils/rpc.utils.ts","../src/vendor/klend/states.ts","../src/generated/drift/types/assetTier.ts","../src/generated/drift/types/historicalIndexData.ts","../src/generated/drift/types/historicalOracleData.ts","../src/generated/drift/types/insuranceFund.ts","../src/generated/drift/types/marginMode.ts","../src/generated/drift/types/marketStatus.ts","../src/generated/drift/types/marketType.ts","../src/generated/drift/types/oracleSource.ts","../src/generated/drift/types/order.ts","../src/generated/drift/types/orderStatus.ts","../src/generated/drift/types/orderTriggerCondition.ts","../src/generated/drift/types/orderType.ts","../src/generated/drift/types/perpPosition.ts","../src/generated/drift/types/poolBalance.ts","../src/generated/drift/types/positionDirection.ts","../src/generated/drift/types/spotBalanceType.ts","../src/generated/drift/types/spotPosition.ts","../src/generated/drift/types/userFees.ts","../src/generated/drift/accounts/spotMarket.ts","../src/generated/drift/accounts/user.ts","../src/generated/drift/accounts/userStats.ts","../src/generated/drift/programs/drift.ts","../src/generated/drift/instructions/updateSpotMarketCumulativeInterest.ts","../src/vendor/drift/accounts.ts","../src/vendor/drift/pda.ts","../src/vendor/drift/instructions.ts","../src/vendor/drift/interest-rate.ts","../src/vendor/drift/rewards.ts","../src/vendor/drift/serialize.ts","../src/vendor/drift/states.ts","../src/generated/jup-lend/accounts/lending.ts","../src/generated/jup-lend/accounts/lendingRewardsRateModel.ts","../src/generated/jup-lend/pdas/fTokenMint.ts","../src/generated/jup-lend/pdas/lending.ts","../src/generated/jup-lend/pdas/lendingAdmin.ts","../src/generated/jup-lend/programs/lending.ts","../src/generated/jup-lend/instructions/updateRate.ts","../src/generated/jup-lend-liquidity/accounts/rateModel.ts","../src/generated/jup-lend-liquidity/accounts/tokenReserve.ts","../src/generated/jup-lend-liquidity/pdas/liquidity.ts","../src/generated/jup-lend-liquidity/pdas/rateModel.ts","../src/generated/jup-lend-liquidity/pdas/tokenReserve.ts","../src/generated/jup-lend-liquidity/pdas/userSupplyPosition.ts","../src/generated/jup-lend-liquidity/programs/liquidity.ts","../src/vendor/jup-lend/accounts.ts","../src/vendor/jup-lend/instructions.ts","../src/vendor/jup-lend/interest-rate.ts","../src/vendor/jup-lend/pda.ts","../src/vendor/jup-lend/rewards.ts","../src/vendor/jup-lend/serialize.ts","../src/vendor/jup-lend/states.ts","../src/generated/gamma/accounts/depositPolicy.ts","../src/generated/gamma/accounts/lpVault.ts","../src/generated/gamma/accounts/withdrawalPolicy.ts","../src/generated/gamma/accounts/withdrawReceipt.ts","../src/generated/gamma/pdas/completeWithdrawalWithdrawEscrow.ts","../src/generated/gamma/pdas/depositPolicy.ts","../src/generated/gamma/pdas/withdrawalPolicy.ts","../src/generated/gamma/pdas/withdrawReceipt.ts","../src/generated/gamma/programs/gammaVault.ts","../src/vendor/gamma/accounts.ts","../src/vendor/titan/client.ts","../src/vendor/titan/types.ts","../src/vendor/titan/helpers.ts","../src/vendor/titan/gateway.ts"],"names":["address","getProgramDerivedAddress","getAddressEncoder","AccountRole","TOKEN_PROGRAM_ADDRESS","getU64Encoder","getStructDecoder","getU64Decoder","fixDecoderSize","getBytesDecoder","containsBytes","BigNumber","decoder","getAddressDecoder","getU128Decoder","getU8Decoder","getArrayDecoder","getU32Decoder","getU16Decoder","getTokenInfoDecoder","getI64Decoder","transformEncoder","getStructEncoder","fixEncoderSize","getBytesEncoder","getAccountMetaFactory","getBooleanEncoder","Decimal","KaminoInterestRateBasis","slotAdjustmentFactor","DEFAULT_ADDRESS","aprToApy","parseBase64RpcAccount","AssetTier","getEnumDecoder","MarginMode","MarketStatus","MarketType","OracleSource","getI32Decoder","getBooleanDecoder","OrderStatus","OrderTriggerCondition","OrderType","PositionDirection","SpotBalanceType","getI16Decoder","decodeAccount","fetchEncodedAccounts","getU16Encoder","SLOTS_PER_YEAR","findAssociatedTokenPda","getMintDecoder","addDecoderSizePrefix","getUtf8Decoder","Encoder","Decoder","WebSocket","SwapMode","SwapVersion","upgradeRoleToWritable","upgradeRoleToSigner","getBase64Encoder","fetchJsonParsedAccounts","assertAccountDecoded","isSignerRole","isWritableRole","getBase64Decoder","decode"],"mappings":";;;;;;;;;;;;;;;AAGO,IAAM,2BAAA,GAA8BA,YAAQ,6CAA6C;AAEhG,eAAe,OAAA,CAAQ,aAAsB,MAAA,EAAkC;AAC7E,EAAA,MAAM,CAAC,GAAG,CAAA,GAAI,MAAMC,4BAAA,CAAyB;AAAA,IAC3C,cAAA,EAAgB,2BAAA;AAAA,IAChB,OAAO,CAAC,MAAA,EAAQC,uBAAkB,CAAE,MAAA,CAAO,WAAW,CAAC;AAAA,GACxD,CAAA;AACD,EAAA,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it\";\n\n/** SPL Single Pool program. */\nexport const SINGLE_POOL_PROGRAM_ADDRESS = address(\"SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE\");\n\nasync function findPda(baseAddress: Address, prefix: string): Promise<Address> {\n const [pda] = await getProgramDerivedAddress({\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n seeds: [prefix, getAddressEncoder().encode(baseAddress)],\n });\n return pda;\n}\n\n/** Single pool of a validator vote account. */\nexport function findPoolAddress(voteAccount: Address): Promise<Address> {\n return findPda(voteAccount, \"pool\");\n}\n\n/** Pool's main stake account. */\nexport function findPoolStakeAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"stake\");\n}\n\n/** Pool's on-ramp stake account (activates new deposits). */\nexport function findPoolOnRampAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"onramp\");\n}\n\n/** Pool token (LST) mint. */\nexport function findPoolMintAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"mint\");\n}\n\n/** Pool stake authority. */\nexport function findPoolStakeAuthorityAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"stake_authority\");\n}\n\n/** Pool token mint authority. */\nexport function findPoolMintAuthorityAddress(pool: Address): Promise<Address> {\n return findPda(pool, \"mint_authority\");\n}\n","import {\n AccountRole,\n address,\n getAddressEncoder,\n getU64Encoder,\n type Address,\n type Instruction,\n} from \"@solana/kit\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\n\nimport {\n findPoolMintAddress,\n findPoolMintAuthorityAddress,\n findPoolOnRampAddress,\n findPoolStakeAddress,\n findPoolStakeAuthorityAddress,\n SINGLE_POOL_PROGRAM_ADDRESS,\n} from \"./addresses\";\n\nconst STAKE_PROGRAM_ADDRESS = address(\"Stake11111111111111111111111111111111111111\");\nconst SYSVAR_CLOCK_ADDRESS = address(\"SysvarC1ock11111111111111111111111111111111\");\nconst SYSVAR_STAKE_HISTORY_ADDRESS = address(\"SysvarStakeHistory1111111111111111111111111\");\n\nconst DEPOSIT_STAKE = 2;\nconst WITHDRAW_STAKE = 3;\n\nasync function poolAccounts(pool: Address) {\n const [stake, onRamp, mint, stakeAuthority, mintAuthority] = await Promise.all([\n findPoolStakeAddress(pool),\n findPoolOnRampAddress(pool),\n findPoolMintAddress(pool),\n findPoolStakeAuthorityAddress(pool),\n findPoolMintAuthorityAddress(pool),\n ]);\n return [\n { address: pool, role: AccountRole.READONLY },\n { address: stake, role: AccountRole.WRITABLE },\n { address: onRamp, role: AccountRole.READONLY },\n { address: mint, role: AccountRole.WRITABLE },\n { address: stakeAuthority, role: AccountRole.READONLY },\n { address: mintAuthority, role: AccountRole.READONLY },\n ];\n}\n\n/**\n * Deposits an active stake account into a single pool, minting pool tokens to `userTokenAccount`;\n * the stake account's excess lamports go to `userLamportAccount`.\n */\nexport async function makeSinglePoolDepositStakeIx(\n pool: Address,\n userStakeAccount: Address,\n userTokenAccount: Address,\n userLamportAccount: Address\n): Promise<Instruction> {\n return {\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n accounts: [\n ...(await poolAccounts(pool)),\n { address: userStakeAccount, role: AccountRole.WRITABLE },\n { address: userTokenAccount, role: AccountRole.WRITABLE },\n { address: userLamportAccount, role: AccountRole.WRITABLE },\n { address: SYSVAR_CLOCK_ADDRESS, role: AccountRole.READONLY },\n { address: SYSVAR_STAKE_HISTORY_ADDRESS, role: AccountRole.READONLY },\n { address: TOKEN_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n { address: STAKE_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n ],\n data: new Uint8Array([DEPOSIT_STAKE]),\n };\n}\n\n/**\n * Burns `tokenAmount` pool tokens (native units, 9 decimals) from `userTokenAccount` and splits that\n * stake into `userStakeAccount`, owned by `userStakeAuthority`.\n */\nexport async function makeSinglePoolWithdrawStakeIx(\n pool: Address,\n userStakeAccount: Address,\n userStakeAuthority: Address,\n userTokenAccount: Address,\n tokenAmount: bigint\n): Promise<Instruction> {\n return {\n programAddress: SINGLE_POOL_PROGRAM_ADDRESS,\n accounts: [\n ...(await poolAccounts(pool)),\n { address: userStakeAccount, role: AccountRole.WRITABLE },\n { address: userTokenAccount, role: AccountRole.WRITABLE },\n { address: SYSVAR_CLOCK_ADDRESS, role: AccountRole.READONLY },\n { address: TOKEN_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n { address: STAKE_PROGRAM_ADDRESS, role: AccountRole.READONLY },\n ],\n data: new Uint8Array([\n WITHDRAW_STAKE,\n ...getAddressEncoder().encode(userStakeAuthority),\n ...getU64Encoder().encode(tokenAmount),\n ]),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { getPriceDecoder, getPriceEncoder, type Price, type PriceArgs } from \".\";\n\nexport type DatedPrice = {\n price: Price;\n lastUpdatedSlot: bigint;\n unixTimestamp: bigint;\n genericData: ReadonlyUint8Array;\n};\n\nexport type DatedPriceArgs = {\n price: PriceArgs;\n lastUpdatedSlot: number | bigint;\n unixTimestamp: number | bigint;\n genericData: ReadonlyUint8Array;\n};\n\nexport function getDatedPriceEncoder(): FixedSizeEncoder<DatedPriceArgs> {\n return getStructEncoder([\n [\"price\", getPriceEncoder()],\n [\"lastUpdatedSlot\", getU64Encoder()],\n [\"unixTimestamp\", getU64Encoder()],\n [\"genericData\", fixEncoderSize(getBytesEncoder(), 24)],\n ]);\n}\n\nexport function getDatedPriceDecoder(): FixedSizeDecoder<DatedPrice> {\n return getStructDecoder([\n [\"price\", getPriceDecoder()],\n [\"lastUpdatedSlot\", getU64Decoder()],\n [\"unixTimestamp\", getU64Decoder()],\n [\"genericData\", fixDecoderSize(getBytesDecoder(), 24)],\n ]);\n}\n\nexport function getDatedPriceCodec(): FixedSizeCodec<DatedPriceArgs, DatedPrice> {\n return combineCodec(getDatedPriceEncoder(), getDatedPriceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type Price = { value: bigint; exp: bigint };\n\nexport type PriceArgs = { value: number | bigint; exp: number | bigint };\n\nexport function getPriceEncoder(): FixedSizeEncoder<PriceArgs> {\n return getStructEncoder([\n [\"value\", getU64Encoder()],\n [\"exp\", getU64Encoder()],\n ]);\n}\n\nexport function getPriceDecoder(): FixedSizeDecoder<Price> {\n return getStructDecoder([\n [\"value\", getU64Decoder()],\n [\"exp\", getU64Decoder()],\n ]);\n}\n\nexport function getPriceCodec(): FixedSizeCodec<PriceArgs, Price> {\n return combineCodec(getPriceEncoder(), getPriceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getDatedPriceDecoder,\n getDatedPriceEncoder,\n type DatedPrice,\n type DatedPriceArgs,\n} from \"../types\";\n\nexport const ORACLE_PRICES_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 89, 128, 118, 221, 6, 72, 180, 146,\n]);\n\nexport function getOraclePricesDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(ORACLE_PRICES_DISCRIMINATOR);\n}\n\nexport type OraclePrices = {\n discriminator: ReadonlyUint8Array;\n oracleMappings: Address;\n prices: Array<DatedPrice>;\n};\n\nexport type OraclePricesArgs = { oracleMappings: Address; prices: Array<DatedPriceArgs> };\n\n/** Gets the encoder for {@link OraclePricesArgs} account data. */\nexport function getOraclePricesEncoder(): FixedSizeEncoder<OraclePricesArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"oracleMappings\", getAddressEncoder()],\n [\"prices\", getArrayEncoder(getDatedPriceEncoder(), { size: 512 })],\n ]),\n (value) => ({ ...value, discriminator: ORACLE_PRICES_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link OraclePrices} account data. */\nexport function getOraclePricesDecoder(): FixedSizeDecoder<OraclePrices> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"oracleMappings\", getAddressDecoder()],\n [\"prices\", getArrayDecoder(getDatedPriceDecoder(), { size: 512 })],\n ]);\n}\n\n/** Gets the codec for {@link OraclePrices} account data. */\nexport function getOraclePricesCodec(): FixedSizeCodec<OraclePricesArgs, OraclePrices> {\n return combineCodec(getOraclePricesEncoder(), getOraclePricesDecoder());\n}\n\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<OraclePrices, TAddress>;\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<OraclePrices, TAddress>;\nexport function decodeOraclePrices<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<OraclePrices, TAddress> | MaybeAccount<OraclePrices, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getOraclePricesDecoder());\n}\n\nexport async function fetchOraclePrices<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<OraclePrices, TAddress>> {\n const maybeAccount = await fetchMaybeOraclePrices(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeOraclePrices<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<OraclePrices, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeOraclePrices(maybeAccount);\n}\n\nexport async function fetchAllOraclePrices(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<OraclePrices>[]> {\n const maybeAccounts = await fetchAllMaybeOraclePrices(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeOraclePrices(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<OraclePrices>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeOraclePrices(maybeAccount));\n}\n\nexport function getOraclePricesSize(): number {\n return 28712;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport { getOraclePricesCodec, type OraclePrices, type OraclePricesArgs } from \"../accounts\";\n\nexport const SCOPE_PROGRAM_ADDRESS =\n \"HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ\" as Address<\"HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ\">;\n\nexport enum ScopeAccount {\n OraclePrices,\n}\n\nexport function identifyScopeAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): ScopeAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([89, 128, 118, 221, 6, 72, 180, 146])\n ),\n 0\n )\n ) {\n return ScopeAccount.OraclePrices;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"scope\",\n });\n}\n\nexport type ScopePlugin = {\n accounts: ScopePluginAccounts;\n identifyAccount: typeof identifyScopeAccount;\n};\n\nexport type ScopePluginAccounts = {\n oraclePrices: ReturnType<typeof getOraclePricesCodec> &\n SelfFetchFunctions<OraclePricesArgs, OraclePrices>;\n};\n\nexport type ScopePluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function scopeProgram() {\n return <T extends ScopePluginRequirements>(\n client: T\n ): ExtendedClient<T, { scope: ScopePlugin }> => {\n return extendClient(client, {\n scope: <ScopePlugin>{\n accounts: { oraclePrices: addSelfFetchFunctions(client, getOraclePricesCodec()) },\n identifyAccount: identifyScopeAccount,\n },\n });\n };\n}\n","import { containsBytes, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nimport {\n getDatedPriceDecoder,\n getOraclePricesSize,\n ORACLE_PRICES_DISCRIMINATOR,\n} from \"~/generated/scope\";\n\nexport { SCOPE_PROGRAM_ADDRESS } from \"~/generated/scope\";\n\n/** Price entries in a Scope `OraclePrices` account. */\nexport const SCOPE_MAX_ENTRIES = 512;\n\n// OraclePrices layout: 8 (discriminator) + 32 (oracle_mappings) + 512 × 56 (DatedPrice entries)\nconst ENTRIES_OFFSET = 40;\nconst DATED_PRICE_SIZE = 56;\n\nexport interface ScopeDatedPrice {\n /** Decimal price, i.e. `value / 10^exp` */\n price: BigNumber;\n lastUpdatedSlot: number;\n unixTimestamp: number;\n}\n\n/**\n * Decodes entry `entryIndex` of a Scope `OraclePrices` account. A never-refreshed entry reads as a\n * zero price.\n * @throws if the account has the wrong size or discriminator, the index is out of range, or the\n * exponent is past the program's power-of-ten table (≥ 24)\n */\nexport function decodeScopePriceAtIndex(\n data: ReadonlyUint8Array,\n entryIndex: number\n): ScopeDatedPrice {\n if (data.length !== getOraclePricesSize()) {\n throw new Error(`Invalid Scope OraclePrices account size: ${data.length}`);\n }\n if (entryIndex < 0 || entryIndex >= SCOPE_MAX_ENTRIES) {\n throw new Error(`Scope entry index out of range: ${entryIndex}`);\n }\n\n if (!containsBytes(data, ORACLE_PRICES_DISCRIMINATOR, 0)) {\n throw new Error(\"Invalid Scope OraclePrices account discriminator\");\n }\n\n // Decode only the requested entry rather than all 512.\n const { price, lastUpdatedSlot, unixTimestamp } = getDatedPriceDecoder().decode(\n data,\n ENTRIES_OFFSET + entryIndex * DATED_PRICE_SIZE\n );\n\n // Same bound as the program's MAX_EXP_10_I80F48\n if (price.exp >= 24n) {\n throw new Error(`Scope entry exponent out of bounds: ${price.exp}`);\n }\n\n return {\n price: new BigNumber(price.value.toString()).shiftedBy(-Number(price.exp)),\n lastUpdatedSlot: Number(lastUpdatedSlot),\n unixTimestamp: Number(unixTimestamp),\n };\n}\n","import { address, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nexport const MARINADE_PROGRAM_ADDRESS = address(\"MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD\");\n\n/** sha256(\"account:State\")[..8] */\nexport const MARINADE_STATE_DISCRIMINATOR = new Uint8Array([216, 146, 107, 94, 104, 75, 182, 177]);\n\n// Absolute byte offsets in Marinade's State account, including the 8-byte Anchor discriminator.\n// These are the fields used by Marinade's `total_virtual_staked_lamports` calculation and by the\n// marginfi program's canonical mSOL/SOL multiplier.\nconst DELAYED_UNSTAKE_COOLING_DOWN_OFFSET = 226;\nconst TOTAL_ACTIVE_BALANCE_OFFSET = 376;\nconst AVAILABLE_RESERVE_BALANCE_OFFSET = 496;\nconst MSOL_SUPPLY_OFFSET = 504;\nconst CIRCULATING_TICKET_BALANCE_OFFSET = 528;\nconst EMERGENCY_COOLING_DOWN_OFFSET = 568;\nexport const MARINADE_STATE_MIN_SIZE = EMERGENCY_COOLING_DOWN_OFFSET + 8;\nconst U64_MAX = (1n << 64n) - 1n;\n\n// Same sanity ceiling as the program's MAX_LST_SOL_RATE\nconst MAX_MSOL_SOL_RATE = 3;\n\nexport interface MarinadeState {\n /** mSOL/SOL exchange rate */\n msolPrice: BigNumber;\n}\n\n/**\n * Decodes the mSOL/SOL rate from a Marinade `State` account.\n * @throws if the account is undersized, has a wrong discriminator, has no mSOL supply, or yields a\n * rate outside (0, 3)\n */\nexport function decodeMarinadeState(data: ReadonlyUint8Array): MarinadeState {\n if (data.length < MARINADE_STATE_MIN_SIZE) {\n throw new Error(`Invalid Marinade State account size: ${data.length}`);\n }\n if (MARINADE_STATE_DISCRIMINATOR.some((byte, i) => data[i] !== byte)) {\n throw new Error(\"Invalid Marinade State discriminator\");\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const u64 = (offset: number) => view.getBigUint64(offset, true);\n\n const msolSupply = u64(MSOL_SUPPLY_OFFSET);\n if (msolSupply === 0n) {\n throw new Error(\"Marinade State has zero mSOL supply\");\n }\n\n const underControl =\n u64(TOTAL_ACTIVE_BALANCE_OFFSET) +\n u64(DELAYED_UNSTAKE_COOLING_DOWN_OFFSET) +\n u64(EMERGENCY_COOLING_DOWN_OFFSET) +\n u64(AVAILABLE_RESERVE_BALANCE_OFFSET);\n if (underControl > U64_MAX) {\n throw new Error(\"Marinade virtual staked balance overflow\");\n }\n\n // Marinade uses saturating subtraction for outstanding delayed-unstake tickets.\n const circulatingTicketBalance = u64(CIRCULATING_TICKET_BALANCE_OFFSET);\n const totalVirtualStakedLamports =\n underControl > circulatingTicketBalance ? underControl - circulatingTicketBalance : 0n;\n const msolPrice = new BigNumber(totalVirtualStakedLamports.toString()).div(msolSupply.toString());\n\n if (!msolPrice.gt(0) || msolPrice.gte(MAX_MSOL_SOL_RATE)) {\n throw new Error(`Marinade mSOL/SOL rate out of bounds: ${msolPrice.toString()}`);\n }\n\n return { msolPrice };\n}\n","import { address, type ReadonlyUint8Array } from \"@solana/kit\";\nimport { BigNumber } from \"bignumber.js\";\n\nexport const SPL_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SPoo1Ku8WFXoNDMHPsrGSTSG1Y47rzgn41SLUNakuHy\"\n);\nexport const SANCTUM_SPL_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SP12tWFxD9oJsVWNavTTBZvMbA6gkAmxtVgxdqvyvhY\"\n);\nexport const SANCTUM_SPL_MULTI_STAKE_POOL_PROGRAM_ADDRESS = address(\n \"SPMBzsVUuoHA4Jm6KunbsotaahvVikZs1JyTW6iJvbn\"\n);\n\n// StakePool is borsh-serialized from byte 0: account_type u8 @0, then 8 pubkeys + a bump byte,\n// then total_lamports u64 @258, pool_token_supply u64 @266, last_update_epoch u64 @274.\nconst ACCOUNT_TYPE_STAKE_POOL = 1;\nconst TOTAL_LAMPORTS_OFFSET = 258;\nconst POOL_TOKEN_SUPPLY_OFFSET = 266;\nconst LAST_UPDATE_EPOCH_OFFSET = 274;\nconst MAX_LST_SOL_RATE = 3;\n\nexport interface StakePool {\n totalLamports: bigint;\n poolTokenSupply: bigint;\n lastUpdateEpoch: number;\n /** LST/SOL exchange rate, i.e. `total_lamports / pool_token_supply` */\n exchangeRate: BigNumber;\n}\n\n/**\n * Decodes the balances and LST/SOL rate of an SPL (or Sanctum) stake pool account.\n * @throws if the account is undersized, is not a StakePool, has no token supply, or yields a rate\n * outside (0, 3)\n */\nexport function decodeStakePool(data: ReadonlyUint8Array): StakePool {\n if (data.length < LAST_UPDATE_EPOCH_OFFSET + 8) {\n throw new Error(`Invalid StakePool account size: ${data.length}`);\n }\n if (data[0] !== ACCOUNT_TYPE_STAKE_POOL) {\n throw new Error(`Invalid StakePool account type: ${data[0]}`);\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const totalLamports = view.getBigUint64(TOTAL_LAMPORTS_OFFSET, true);\n const poolTokenSupply = view.getBigUint64(POOL_TOKEN_SUPPLY_OFFSET, true);\n const lastUpdateEpoch = Number(view.getBigUint64(LAST_UPDATE_EPOCH_OFFSET, true));\n\n if (poolTokenSupply === 0n) {\n throw new Error(\"StakePool has zero token supply\");\n }\n\n const exchangeRate = new BigNumber(totalLamports.toString()).div(poolTokenSupply.toString());\n\n // Same sanity bounds as the program's MAX_LST_SOL_RATE\n if (!exchangeRate.gt(0) || exchangeRate.gte(MAX_LST_SOL_RATE)) {\n throw new Error(`StakePool LST/SOL rate out of bounds: ${exchangeRate.toString()}`);\n }\n\n return { totalLamports, poolTokenSupply, lastUpdateEpoch, exchangeRate };\n}\n","import { containsBytes, type Decoder, type ReadonlyUint8Array } from \"@solana/kit\";\n\n// Generated decoders don't check the discriminator; wrappers use this so a wrong account fails loudly.\nexport function decodeAccountData<T>(\n data: ReadonlyUint8Array,\n discriminator: ReadonlyUint8Array,\n decoder: Decoder<T>,\n accountName: string\n): T {\n if (!containsBytes(data, discriminator, 0)) {\n throw new Error(`Invalid ${accountName} account discriminator`);\n }\n return decoder.decode(data);\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getRewardScheduleCurveDecoder,\n getRewardScheduleCurveEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n type RewardScheduleCurve,\n type RewardScheduleCurveArgs,\n type TokenInfo,\n type TokenInfoArgs,\n} from \".\";\n\nexport type RewardInfo = {\n token: TokenInfo;\n rewardsVault: Address;\n rewardsAvailable: bigint;\n rewardScheduleCurve: RewardScheduleCurve;\n minClaimDurationSeconds: bigint;\n lastIssuanceTs: bigint;\n rewardsIssuedUnclaimed: bigint;\n rewardsIssuedCumulative: bigint;\n rewardPerShareScaled: bigint;\n placeholder0: bigint;\n rewardType: number;\n rewardsPerSecondDecimals: number;\n padding0: ReadonlyUint8Array;\n padding1: Array<bigint>;\n};\n\nexport type RewardInfoArgs = {\n token: TokenInfoArgs;\n rewardsVault: Address;\n rewardsAvailable: number | bigint;\n rewardScheduleCurve: RewardScheduleCurveArgs;\n minClaimDurationSeconds: number | bigint;\n lastIssuanceTs: number | bigint;\n rewardsIssuedUnclaimed: number | bigint;\n rewardsIssuedCumulative: number | bigint;\n rewardPerShareScaled: number | bigint;\n placeholder0: number | bigint;\n rewardType: number;\n rewardsPerSecondDecimals: number;\n padding0: ReadonlyUint8Array;\n padding1: Array<number | bigint>;\n};\n\nexport function getRewardInfoEncoder(): FixedSizeEncoder<RewardInfoArgs> {\n return getStructEncoder([\n [\"token\", getTokenInfoEncoder()],\n [\"rewardsVault\", getAddressEncoder()],\n [\"rewardsAvailable\", getU64Encoder()],\n [\"rewardScheduleCurve\", getRewardScheduleCurveEncoder()],\n [\"minClaimDurationSeconds\", getU64Encoder()],\n [\"lastIssuanceTs\", getU64Encoder()],\n [\"rewardsIssuedUnclaimed\", getU64Encoder()],\n [\"rewardsIssuedCumulative\", getU64Encoder()],\n [\"rewardPerShareScaled\", getU128Encoder()],\n [\"placeholder0\", getU64Encoder()],\n [\"rewardType\", getU8Encoder()],\n [\"rewardsPerSecondDecimals\", getU8Encoder()],\n [\"padding0\", fixEncoderSize(getBytesEncoder(), 6)],\n [\"padding1\", getArrayEncoder(getU64Encoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardInfoDecoder(): FixedSizeDecoder<RewardInfo> {\n return getStructDecoder([\n [\"token\", getTokenInfoDecoder()],\n [\"rewardsVault\", getAddressDecoder()],\n [\"rewardsAvailable\", getU64Decoder()],\n [\"rewardScheduleCurve\", getRewardScheduleCurveDecoder()],\n [\"minClaimDurationSeconds\", getU64Decoder()],\n [\"lastIssuanceTs\", getU64Decoder()],\n [\"rewardsIssuedUnclaimed\", getU64Decoder()],\n [\"rewardsIssuedCumulative\", getU64Decoder()],\n [\"rewardPerShareScaled\", getU128Decoder()],\n [\"placeholder0\", getU64Decoder()],\n [\"rewardType\", getU8Decoder()],\n [\"rewardsPerSecondDecimals\", getU8Decoder()],\n [\"padding0\", fixDecoderSize(getBytesDecoder(), 6)],\n [\"padding1\", getArrayDecoder(getU64Decoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardInfoCodec(): FixedSizeCodec<RewardInfoArgs, RewardInfo> {\n return combineCodec(getRewardInfoEncoder(), getRewardInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type RewardPerTimeUnitPoint = { tsStart: bigint; rewardPerTimeUnit: bigint };\n\nexport type RewardPerTimeUnitPointArgs = {\n tsStart: number | bigint;\n rewardPerTimeUnit: number | bigint;\n};\n\nexport function getRewardPerTimeUnitPointEncoder(): FixedSizeEncoder<RewardPerTimeUnitPointArgs> {\n return getStructEncoder([\n [\"tsStart\", getU64Encoder()],\n [\"rewardPerTimeUnit\", getU64Encoder()],\n ]);\n}\n\nexport function getRewardPerTimeUnitPointDecoder(): FixedSizeDecoder<RewardPerTimeUnitPoint> {\n return getStructDecoder([\n [\"tsStart\", getU64Decoder()],\n [\"rewardPerTimeUnit\", getU64Decoder()],\n ]);\n}\n\nexport function getRewardPerTimeUnitPointCodec(): FixedSizeCodec<\n RewardPerTimeUnitPointArgs,\n RewardPerTimeUnitPoint\n> {\n return combineCodec(getRewardPerTimeUnitPointEncoder(), getRewardPerTimeUnitPointDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getRewardPerTimeUnitPointDecoder,\n getRewardPerTimeUnitPointEncoder,\n type RewardPerTimeUnitPoint,\n type RewardPerTimeUnitPointArgs,\n} from \".\";\n\nexport type RewardScheduleCurve = {\n /**\n * This is a stepwise function, meaning that each point represents\n * how many rewards are issued per time unit since the beginning\n * of that point until the beginning of the next point.\n * This is not a linear curve, there is no interpolation going on.\n * A curve can be [[t0, 100], [t1, 50], [t2, 0]]\n * meaning that from t0 to t1, 100 rewards are issued per time unit,\n * from t1 to t2, 50 rewards are issued per time unit, and after t2 it stops\n * Another curve, can be [[t0, 100], [u64::max, 0]]\n * meaning that from t0 to u64::max, 100 rewards are issued per time unit\n */\n points: Array<RewardPerTimeUnitPoint>;\n};\n\nexport type RewardScheduleCurveArgs = {\n /**\n * This is a stepwise function, meaning that each point represents\n * how many rewards are issued per time unit since the beginning\n * of that point until the beginning of the next point.\n * This is not a linear curve, there is no interpolation going on.\n * A curve can be [[t0, 100], [t1, 50], [t2, 0]]\n * meaning that from t0 to t1, 100 rewards are issued per time unit,\n * from t1 to t2, 50 rewards are issued per time unit, and after t2 it stops\n * Another curve, can be [[t0, 100], [u64::max, 0]]\n * meaning that from t0 to u64::max, 100 rewards are issued per time unit\n */\n points: Array<RewardPerTimeUnitPointArgs>;\n};\n\nexport function getRewardScheduleCurveEncoder(): FixedSizeEncoder<RewardScheduleCurveArgs> {\n return getStructEncoder([\n [\"points\", getArrayEncoder(getRewardPerTimeUnitPointEncoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardScheduleCurveDecoder(): FixedSizeDecoder<RewardScheduleCurve> {\n return getStructDecoder([\n [\"points\", getArrayDecoder(getRewardPerTimeUnitPointDecoder(), { size: 20 })],\n ]);\n}\n\nexport function getRewardScheduleCurveCodec(): FixedSizeCodec<\n RewardScheduleCurveArgs,\n RewardScheduleCurve\n> {\n return combineCodec(getRewardScheduleCurveEncoder(), getRewardScheduleCurveDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type TokenInfo = {\n mint: Address;\n decimals: bigint;\n tokenProgram: Address;\n padding: Array<bigint>;\n};\n\nexport type TokenInfoArgs = {\n mint: Address;\n decimals: number | bigint;\n tokenProgram: Address;\n padding: Array<number | bigint>;\n};\n\nexport function getTokenInfoEncoder(): FixedSizeEncoder<TokenInfoArgs> {\n return getStructEncoder([\n [\"mint\", getAddressEncoder()],\n [\"decimals\", getU64Encoder()],\n [\"tokenProgram\", getAddressEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 6 })],\n ]);\n}\n\nexport function getTokenInfoDecoder(): FixedSizeDecoder<TokenInfo> {\n return getStructDecoder([\n [\"mint\", getAddressDecoder()],\n [\"decimals\", getU64Decoder()],\n [\"tokenProgram\", getAddressDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 6 })],\n ]);\n}\n\nexport function getTokenInfoCodec(): FixedSizeCodec<TokenInfoArgs, TokenInfo> {\n return combineCodec(getTokenInfoEncoder(), getTokenInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getRewardInfoDecoder,\n getRewardInfoEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n type RewardInfo,\n type RewardInfoArgs,\n type TokenInfo,\n type TokenInfoArgs,\n} from \"../types\";\n\nexport const FARM_STATE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 198, 102, 216, 74, 63, 66, 163, 190,\n]);\n\nexport function getFarmStateDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(FARM_STATE_DISCRIMINATOR);\n}\n\nexport type FarmState = {\n discriminator: ReadonlyUint8Array;\n farmAdmin: Address;\n globalConfig: Address;\n token: TokenInfo;\n rewardInfos: Array<RewardInfo>;\n numRewardTokens: bigint;\n /** Data used to calculate the rewards of the user */\n numUsers: bigint;\n /**\n * The number of token in the `farm_vault` staked (getting rewards and fees)\n * Set such as `farm_vault.amount = total_staked_amount + total_pending_amount`\n */\n totalStakedAmount: bigint;\n farmVault: Address;\n farmVaultsAuthority: Address;\n farmVaultsAuthorityBump: bigint;\n /**\n * Only used for delegate farms\n * Set to `default()` otherwise\n */\n delegateAuthority: Address;\n /**\n * Raw representation of a `TimeUnit`\n * Seconds = 0, Slots = 1\n */\n timeUnit: number;\n /**\n * Automatically set to true in case of a full authority withdrawal\n * If true, the farm is frozen and no more deposits are allowed\n */\n isFarmFrozen: number;\n /**\n * Indicates if the farm is a delegate farm\n * If true, the farm is a delegate farm and the `delegate_authority` is set*\n */\n isFarmDelegated: number;\n /** If set to 1, indicates that the \"reward user once\" feature is enabled */\n isRewardUserOnceEnabled: number;\n isHarvestingPermissionless: number;\n padding0: ReadonlyUint8Array;\n /**\n * Withdraw authority for the farm, allowed to lock deposited funds and withdraw them\n * Set to `default()` if unused (only the depositors can withdraw their funds)\n */\n withdrawAuthority: Address;\n /**\n * Delay between a user deposit and the moment it is considered as staked\n * 0 if unused\n */\n depositWarmupPeriod: number;\n /** Delay between a user unstake and the ability to withdraw his deposit. */\n withdrawalCooldownPeriod: number;\n /** Total active stake of tokens in the farm (scaled from `Decimal` representation). */\n totalActiveStakeScaled: bigint;\n /**\n * Total pending stake of tokens in the farm (scaled from `Decimal` representation).\n * (can be used by `withdraw_authority` but don't get rewards or fees)\n */\n totalPendingStakeScaled: bigint;\n /** Total pending amount of tokens in the farm */\n totalPendingAmount: bigint;\n /** Slashed amounts from early withdrawal */\n slashedAmountCurrent: bigint;\n slashedAmountCumulative: bigint;\n slashedAmountSpillAddress: Address;\n /** Locking stake */\n lockingMode: bigint;\n lockingStartTimestamp: bigint;\n lockingDuration: bigint;\n lockingEarlyWithdrawalPenaltyBps: bigint;\n depositCapAmount: bigint;\n scopePrices: Address;\n scopeOraclePriceId: bigint;\n scopeOracleMaxAge: bigint;\n pendingFarmAdmin: Address;\n strategyId: Address;\n delegatedRpsAdmin: Address;\n vaultId: Address;\n secondDelegatedAuthority: Address;\n padding: Array<bigint>;\n};\n\nexport type FarmStateArgs = {\n farmAdmin: Address;\n globalConfig: Address;\n token: TokenInfoArgs;\n rewardInfos: Array<RewardInfoArgs>;\n numRewardTokens: number | bigint;\n /** Data used to calculate the rewards of the user */\n numUsers: number | bigint;\n /**\n * The number of token in the `farm_vault` staked (getting rewards and fees)\n * Set such as `farm_vault.amount = total_staked_amount + total_pending_amount`\n */\n totalStakedAmount: number | bigint;\n farmVault: Address;\n farmVaultsAuthority: Address;\n farmVaultsAuthorityBump: number | bigint;\n /**\n * Only used for delegate farms\n * Set to `default()` otherwise\n */\n delegateAuthority: Address;\n /**\n * Raw representation of a `TimeUnit`\n * Seconds = 0, Slots = 1\n */\n timeUnit: number;\n /**\n * Automatically set to true in case of a full authority withdrawal\n * If true, the farm is frozen and no more deposits are allowed\n */\n isFarmFrozen: number;\n /**\n * Indicates if the farm is a delegate farm\n * If true, the farm is a delegate farm and the `delegate_authority` is set*\n */\n isFarmDelegated: number;\n /** If set to 1, indicates that the \"reward user once\" feature is enabled */\n isRewardUserOnceEnabled: number;\n isHarvestingPermissionless: number;\n padding0: ReadonlyUint8Array;\n /**\n * Withdraw authority for the farm, allowed to lock deposited funds and withdraw them\n * Set to `default()` if unused (only the depositors can withdraw their funds)\n */\n withdrawAuthority: Address;\n /**\n * Delay between a user deposit and the moment it is considered as staked\n * 0 if unused\n */\n depositWarmupPeriod: number;\n /** Delay between a user unstake and the ability to withdraw his deposit. */\n withdrawalCooldownPeriod: number;\n /** Total active stake of tokens in the farm (scaled from `Decimal` representation). */\n totalActiveStakeScaled: number | bigint;\n /**\n * Total pending stake of tokens in the farm (scaled from `Decimal` representation).\n * (can be used by `withdraw_authority` but don't get rewards or fees)\n */\n totalPendingStakeScaled: number | bigint;\n /** Total pending amount of tokens in the farm */\n totalPendingAmount: number | bigint;\n /** Slashed amounts from early withdrawal */\n slashedAmountCurrent: number | bigint;\n slashedAmountCumulative: number | bigint;\n slashedAmountSpillAddress: Address;\n /** Locking stake */\n lockingMode: number | bigint;\n lockingStartTimestamp: number | bigint;\n lockingDuration: number | bigint;\n lockingEarlyWithdrawalPenaltyBps: number | bigint;\n depositCapAmount: number | bigint;\n scopePrices: Address;\n scopeOraclePriceId: number | bigint;\n scopeOracleMaxAge: number | bigint;\n pendingFarmAdmin: Address;\n strategyId: Address;\n delegatedRpsAdmin: Address;\n vaultId: Address;\n secondDelegatedAuthority: Address;\n padding: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link FarmStateArgs} account data. */\nexport function getFarmStateEncoder(): FixedSizeEncoder<FarmStateArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"farmAdmin\", getAddressEncoder()],\n [\"globalConfig\", getAddressEncoder()],\n [\"token\", getTokenInfoEncoder()],\n [\"rewardInfos\", getArrayEncoder(getRewardInfoEncoder(), { size: 10 })],\n [\"numRewardTokens\", getU64Encoder()],\n [\"numUsers\", getU64Encoder()],\n [\"totalStakedAmount\", getU64Encoder()],\n [\"farmVault\", getAddressEncoder()],\n [\"farmVaultsAuthority\", getAddressEncoder()],\n [\"farmVaultsAuthorityBump\", getU64Encoder()],\n [\"delegateAuthority\", getAddressEncoder()],\n [\"timeUnit\", getU8Encoder()],\n [\"isFarmFrozen\", getU8Encoder()],\n [\"isFarmDelegated\", getU8Encoder()],\n [\"isRewardUserOnceEnabled\", getU8Encoder()],\n [\"isHarvestingPermissionless\", getU8Encoder()],\n [\"padding0\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"withdrawAuthority\", getAddressEncoder()],\n [\"depositWarmupPeriod\", getU32Encoder()],\n [\"withdrawalCooldownPeriod\", getU32Encoder()],\n [\"totalActiveStakeScaled\", getU128Encoder()],\n [\"totalPendingStakeScaled\", getU128Encoder()],\n [\"totalPendingAmount\", getU64Encoder()],\n [\"slashedAmountCurrent\", getU64Encoder()],\n [\"slashedAmountCumulative\", getU64Encoder()],\n [\"slashedAmountSpillAddress\", getAddressEncoder()],\n [\"lockingMode\", getU64Encoder()],\n [\"lockingStartTimestamp\", getU64Encoder()],\n [\"lockingDuration\", getU64Encoder()],\n [\"lockingEarlyWithdrawalPenaltyBps\", getU64Encoder()],\n [\"depositCapAmount\", getU64Encoder()],\n [\"scopePrices\", getAddressEncoder()],\n [\"scopeOraclePriceId\", getU64Encoder()],\n [\"scopeOracleMaxAge\", getU64Encoder()],\n [\"pendingFarmAdmin\", getAddressEncoder()],\n [\"strategyId\", getAddressEncoder()],\n [\"delegatedRpsAdmin\", getAddressEncoder()],\n [\"vaultId\", getAddressEncoder()],\n [\"secondDelegatedAuthority\", getAddressEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 74 })],\n ]),\n (value) => ({ ...value, discriminator: FARM_STATE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link FarmState} account data. */\nexport function getFarmStateDecoder(): FixedSizeDecoder<FarmState> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"farmAdmin\", getAddressDecoder()],\n [\"globalConfig\", getAddressDecoder()],\n [\"token\", getTokenInfoDecoder()],\n [\"rewardInfos\", getArrayDecoder(getRewardInfoDecoder(), { size: 10 })],\n [\"numRewardTokens\", getU64Decoder()],\n [\"numUsers\", getU64Decoder()],\n [\"totalStakedAmount\", getU64Decoder()],\n [\"farmVault\", getAddressDecoder()],\n [\"farmVaultsAuthority\", getAddressDecoder()],\n [\"farmVaultsAuthorityBump\", getU64Decoder()],\n [\"delegateAuthority\", getAddressDecoder()],\n [\"timeUnit\", getU8Decoder()],\n [\"isFarmFrozen\", getU8Decoder()],\n [\"isFarmDelegated\", getU8Decoder()],\n [\"isRewardUserOnceEnabled\", getU8Decoder()],\n [\"isHarvestingPermissionless\", getU8Decoder()],\n [\"padding0\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"withdrawAuthority\", getAddressDecoder()],\n [\"depositWarmupPeriod\", getU32Decoder()],\n [\"withdrawalCooldownPeriod\", getU32Decoder()],\n [\"totalActiveStakeScaled\", getU128Decoder()],\n [\"totalPendingStakeScaled\", getU128Decoder()],\n [\"totalPendingAmount\", getU64Decoder()],\n [\"slashedAmountCurrent\", getU64Decoder()],\n [\"slashedAmountCumulative\", getU64Decoder()],\n [\"slashedAmountSpillAddress\", getAddressDecoder()],\n [\"lockingMode\", getU64Decoder()],\n [\"lockingStartTimestamp\", getU64Decoder()],\n [\"lockingDuration\", getU64Decoder()],\n [\"lockingEarlyWithdrawalPenaltyBps\", getU64Decoder()],\n [\"depositCapAmount\", getU64Decoder()],\n [\"scopePrices\", getAddressDecoder()],\n [\"scopeOraclePriceId\", getU64Decoder()],\n [\"scopeOracleMaxAge\", getU64Decoder()],\n [\"pendingFarmAdmin\", getAddressDecoder()],\n [\"strategyId\", getAddressDecoder()],\n [\"delegatedRpsAdmin\", getAddressDecoder()],\n [\"vaultId\", getAddressDecoder()],\n [\"secondDelegatedAuthority\", getAddressDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 74 })],\n ]);\n}\n\n/** Gets the codec for {@link FarmState} account data. */\nexport function getFarmStateCodec(): FixedSizeCodec<FarmStateArgs, FarmState> {\n return combineCodec(getFarmStateEncoder(), getFarmStateDecoder());\n}\n\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<FarmState, TAddress>;\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<FarmState, TAddress>;\nexport function decodeFarmState<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<FarmState, TAddress> | MaybeAccount<FarmState, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getFarmStateDecoder());\n}\n\nexport async function fetchFarmState<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<FarmState, TAddress>> {\n const maybeAccount = await fetchMaybeFarmState(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeFarmState<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<FarmState, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeFarmState(maybeAccount);\n}\n\nexport async function fetchAllFarmState(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<FarmState>[]> {\n const maybeAccounts = await fetchAllMaybeFarmState(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeFarmState(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<FarmState>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeFarmState(maybeAccount));\n}\n\nexport function getFarmStateSize(): number {\n return 8336;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport { getFarmStateCodec, type FarmState, type FarmStateArgs } from \"../accounts\";\n\nexport const FARMS_PROGRAM_ADDRESS =\n \"FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr\" as Address<\"FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr\">;\n\nexport enum FarmsAccount {\n FarmState,\n}\n\nexport function identifyFarmsAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): FarmsAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([198, 102, 216, 74, 63, 66, 163, 190])\n ),\n 0\n )\n ) {\n return FarmsAccount.FarmState;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"farms\",\n });\n}\n\nexport type FarmsPlugin = {\n accounts: FarmsPluginAccounts;\n identifyAccount: typeof identifyFarmsAccount;\n};\n\nexport type FarmsPluginAccounts = {\n farmState: ReturnType<typeof getFarmStateCodec> & SelfFetchFunctions<FarmStateArgs, FarmState>;\n};\n\nexport type FarmsPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function farmsProgram() {\n return <T extends FarmsPluginRequirements>(\n client: T\n ): ExtendedClient<T, { farms: FarmsPlugin }> => {\n return extendClient(client, {\n farms: <FarmsPlugin>{\n accounts: { farmState: addSelfFetchFunctions(client, getFarmStateCodec()) },\n identifyAccount: identifyFarmsAccount,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type BigFractionBytes = { value: Array<bigint>; padding: Array<bigint> };\n\nexport type BigFractionBytesArgs = {\n value: Array<number | bigint>;\n padding: Array<number | bigint>;\n};\n\nexport function getBigFractionBytesEncoder(): FixedSizeEncoder<BigFractionBytesArgs> {\n return getStructEncoder([\n [\"value\", getArrayEncoder(getU64Encoder(), { size: 4 })],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 2 })],\n ]);\n}\n\nexport function getBigFractionBytesDecoder(): FixedSizeDecoder<BigFractionBytes> {\n return getStructDecoder([\n [\"value\", getArrayDecoder(getU64Decoder(), { size: 4 })],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 2 })],\n ]);\n}\n\nexport function getBigFractionBytesCodec(): FixedSizeCodec<BigFractionBytesArgs, BigFractionBytes> {\n return combineCodec(getBigFractionBytesEncoder(), getBigFractionBytesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type BorrowOrder = {\n debtLiquidityMint: Address;\n remainingDebtAmount: bigint;\n filledDebtDestination: Address;\n minDebtTermSeconds: bigint;\n fillableUntilTimestamp: bigint;\n placedAtTimestamp: bigint;\n lastUpdatedAtTimestamp: bigint;\n requestedDebtAmount: bigint;\n maxBorrowRateBps: number;\n active: number;\n enableAutoRolloverOnFilledBorrows: number;\n padding1: ReadonlyUint8Array;\n endPadding: Array<bigint>;\n};\n\nexport type BorrowOrderArgs = {\n debtLiquidityMint: Address;\n remainingDebtAmount: number | bigint;\n filledDebtDestination: Address;\n minDebtTermSeconds: number | bigint;\n fillableUntilTimestamp: number | bigint;\n placedAtTimestamp: number | bigint;\n lastUpdatedAtTimestamp: number | bigint;\n requestedDebtAmount: number | bigint;\n maxBorrowRateBps: number;\n active: number;\n enableAutoRolloverOnFilledBorrows: number;\n padding1: ReadonlyUint8Array;\n endPadding: Array<number | bigint>;\n};\n\nexport function getBorrowOrderEncoder(): FixedSizeEncoder<BorrowOrderArgs> {\n return getStructEncoder([\n [\"debtLiquidityMint\", getAddressEncoder()],\n [\"remainingDebtAmount\", getU64Encoder()],\n [\"filledDebtDestination\", getAddressEncoder()],\n [\"minDebtTermSeconds\", getU64Encoder()],\n [\"fillableUntilTimestamp\", getU64Encoder()],\n [\"placedAtTimestamp\", getU64Encoder()],\n [\"lastUpdatedAtTimestamp\", getU64Encoder()],\n [\"requestedDebtAmount\", getU64Encoder()],\n [\"maxBorrowRateBps\", getU32Encoder()],\n [\"active\", getU8Encoder()],\n [\"enableAutoRolloverOnFilledBorrows\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"endPadding\", getArrayEncoder(getU64Encoder(), { size: 5 })],\n ]);\n}\n\nexport function getBorrowOrderDecoder(): FixedSizeDecoder<BorrowOrder> {\n return getStructDecoder([\n [\"debtLiquidityMint\", getAddressDecoder()],\n [\"remainingDebtAmount\", getU64Decoder()],\n [\"filledDebtDestination\", getAddressDecoder()],\n [\"minDebtTermSeconds\", getU64Decoder()],\n [\"fillableUntilTimestamp\", getU64Decoder()],\n [\"placedAtTimestamp\", getU64Decoder()],\n [\"lastUpdatedAtTimestamp\", getU64Decoder()],\n [\"requestedDebtAmount\", getU64Decoder()],\n [\"maxBorrowRateBps\", getU32Decoder()],\n [\"active\", getU8Decoder()],\n [\"enableAutoRolloverOnFilledBorrows\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"endPadding\", getArrayDecoder(getU64Decoder(), { size: 5 })],\n ]);\n}\n\nexport function getBorrowOrderCodec(): FixedSizeCodec<BorrowOrderArgs, BorrowOrder> {\n return combineCodec(getBorrowOrderEncoder(), getBorrowOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getCurvePointDecoder,\n getCurvePointEncoder,\n type CurvePoint,\n type CurvePointArgs,\n} from \".\";\n\nexport type BorrowRateCurve = { points: Array<CurvePoint> };\n\nexport type BorrowRateCurveArgs = { points: Array<CurvePointArgs> };\n\nexport function getBorrowRateCurveEncoder(): FixedSizeEncoder<BorrowRateCurveArgs> {\n return getStructEncoder([[\"points\", getArrayEncoder(getCurvePointEncoder(), { size: 11 })]]);\n}\n\nexport function getBorrowRateCurveDecoder(): FixedSizeDecoder<BorrowRateCurve> {\n return getStructDecoder([[\"points\", getArrayDecoder(getCurvePointDecoder(), { size: 11 })]]);\n}\n\nexport function getBorrowRateCurveCodec(): FixedSizeCodec<BorrowRateCurveArgs, BorrowRateCurve> {\n return combineCodec(getBorrowRateCurveEncoder(), getBorrowRateCurveDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type CurvePoint = { utilizationRateBps: number; borrowRateBps: number };\n\nexport type CurvePointArgs = CurvePoint;\n\nexport function getCurvePointEncoder(): FixedSizeEncoder<CurvePointArgs> {\n return getStructEncoder([\n [\"utilizationRateBps\", getU32Encoder()],\n [\"borrowRateBps\", getU32Encoder()],\n ]);\n}\n\nexport function getCurvePointDecoder(): FixedSizeDecoder<CurvePoint> {\n return getStructDecoder([\n [\"utilizationRateBps\", getU32Decoder()],\n [\"borrowRateBps\", getU32Decoder()],\n ]);\n}\n\nexport function getCurvePointCodec(): FixedSizeCodec<CurvePointArgs, CurvePoint> {\n return combineCodec(getCurvePointEncoder(), getCurvePointDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type FixedTermBorrowRolloverConfig = {\n autoRolloverEnabled: number;\n openTermAllowed: number;\n migrationToFixedEnabled: number;\n fixedTermRolloverWindowDurationDays: number;\n maxBorrowRateBps: number;\n minDebtTermSeconds: bigint;\n};\n\nexport type FixedTermBorrowRolloverConfigArgs = {\n autoRolloverEnabled: number;\n openTermAllowed: number;\n migrationToFixedEnabled: number;\n fixedTermRolloverWindowDurationDays: number;\n maxBorrowRateBps: number;\n minDebtTermSeconds: number | bigint;\n};\n\nexport function getFixedTermBorrowRolloverConfigEncoder(): FixedSizeEncoder<FixedTermBorrowRolloverConfigArgs> {\n return getStructEncoder([\n [\"autoRolloverEnabled\", getU8Encoder()],\n [\"openTermAllowed\", getU8Encoder()],\n [\"migrationToFixedEnabled\", getU8Encoder()],\n [\"fixedTermRolloverWindowDurationDays\", getU8Encoder()],\n [\"maxBorrowRateBps\", getU32Encoder()],\n [\"minDebtTermSeconds\", getU64Encoder()],\n ]);\n}\n\nexport function getFixedTermBorrowRolloverConfigDecoder(): FixedSizeDecoder<FixedTermBorrowRolloverConfig> {\n return getStructDecoder([\n [\"autoRolloverEnabled\", getU8Decoder()],\n [\"openTermAllowed\", getU8Decoder()],\n [\"migrationToFixedEnabled\", getU8Decoder()],\n [\"fixedTermRolloverWindowDurationDays\", getU8Decoder()],\n [\"maxBorrowRateBps\", getU32Decoder()],\n [\"minDebtTermSeconds\", getU64Decoder()],\n ]);\n}\n\nexport function getFixedTermBorrowRolloverConfigCodec(): FixedSizeCodec<\n FixedTermBorrowRolloverConfigArgs,\n FixedTermBorrowRolloverConfig\n> {\n return combineCodec(\n getFixedTermBorrowRolloverConfigEncoder(),\n getFixedTermBorrowRolloverConfigDecoder()\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type LastUpdate = {\n slot: bigint;\n stale: number;\n priceStatus: number;\n alignmentPadding: ReadonlyUint8Array;\n timestamp: number;\n};\n\nexport type LastUpdateArgs = {\n slot: number | bigint;\n stale: number;\n priceStatus: number;\n alignmentPadding: ReadonlyUint8Array;\n timestamp: number;\n};\n\nexport function getLastUpdateEncoder(): FixedSizeEncoder<LastUpdateArgs> {\n return getStructEncoder([\n [\"slot\", getU64Encoder()],\n [\"stale\", getU8Encoder()],\n [\"priceStatus\", getU8Encoder()],\n [\"alignmentPadding\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"timestamp\", getU32Encoder()],\n ]);\n}\n\nexport function getLastUpdateDecoder(): FixedSizeDecoder<LastUpdate> {\n return getStructDecoder([\n [\"slot\", getU64Decoder()],\n [\"stale\", getU8Decoder()],\n [\"priceStatus\", getU8Decoder()],\n [\"alignmentPadding\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"timestamp\", getU32Decoder()],\n ]);\n}\n\nexport function getLastUpdateCodec(): FixedSizeCodec<LastUpdateArgs, LastUpdate> {\n return combineCodec(getLastUpdateEncoder(), getLastUpdateDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ObligationCollateral = {\n depositReserve: Address;\n depositedAmount: bigint;\n marketValueSf: bigint;\n borrowedAmountAgainstThisCollateralInElevationGroup: bigint;\n padding: Array<bigint>;\n};\n\nexport type ObligationCollateralArgs = {\n depositReserve: Address;\n depositedAmount: number | bigint;\n marketValueSf: number | bigint;\n borrowedAmountAgainstThisCollateralInElevationGroup: number | bigint;\n padding: Array<number | bigint>;\n};\n\nexport function getObligationCollateralEncoder(): FixedSizeEncoder<ObligationCollateralArgs> {\n return getStructEncoder([\n [\"depositReserve\", getAddressEncoder()],\n [\"depositedAmount\", getU64Encoder()],\n [\"marketValueSf\", getU128Encoder()],\n [\"borrowedAmountAgainstThisCollateralInElevationGroup\", getU64Encoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 9 })],\n ]);\n}\n\nexport function getObligationCollateralDecoder(): FixedSizeDecoder<ObligationCollateral> {\n return getStructDecoder([\n [\"depositReserve\", getAddressDecoder()],\n [\"depositedAmount\", getU64Decoder()],\n [\"marketValueSf\", getU128Decoder()],\n [\"borrowedAmountAgainstThisCollateralInElevationGroup\", getU64Decoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 9 })],\n ]);\n}\n\nexport function getObligationCollateralCodec(): FixedSizeCodec<\n ObligationCollateralArgs,\n ObligationCollateral\n> {\n return combineCodec(getObligationCollateralEncoder(), getObligationCollateralDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getBigFractionBytesDecoder,\n getBigFractionBytesEncoder,\n getFixedTermBorrowRolloverConfigDecoder,\n getFixedTermBorrowRolloverConfigEncoder,\n type BigFractionBytes,\n type BigFractionBytesArgs,\n type FixedTermBorrowRolloverConfig,\n type FixedTermBorrowRolloverConfigArgs,\n} from \".\";\n\nexport type ObligationLiquidity = {\n borrowReserve: Address;\n cumulativeBorrowRateBsf: BigFractionBytes;\n lastBorrowedAtTimestamp: bigint;\n borrowedAmountSf: bigint;\n marketValueSf: bigint;\n borrowFactorAdjustedMarketValueSf: bigint;\n borrowedAmountOutsideElevationGroups: bigint;\n fixedTermBorrowRolloverConfig: FixedTermBorrowRolloverConfig;\n borrowedAmountAtExpiration: bigint;\n padding2: Array<bigint>;\n};\n\nexport type ObligationLiquidityArgs = {\n borrowReserve: Address;\n cumulativeBorrowRateBsf: BigFractionBytesArgs;\n lastBorrowedAtTimestamp: number | bigint;\n borrowedAmountSf: number | bigint;\n marketValueSf: number | bigint;\n borrowFactorAdjustedMarketValueSf: number | bigint;\n borrowedAmountOutsideElevationGroups: number | bigint;\n fixedTermBorrowRolloverConfig: FixedTermBorrowRolloverConfigArgs;\n borrowedAmountAtExpiration: number | bigint;\n padding2: Array<number | bigint>;\n};\n\nexport function getObligationLiquidityEncoder(): FixedSizeEncoder<ObligationLiquidityArgs> {\n return getStructEncoder([\n [\"borrowReserve\", getAddressEncoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesEncoder()],\n [\"lastBorrowedAtTimestamp\", getU64Encoder()],\n [\"borrowedAmountSf\", getU128Encoder()],\n [\"marketValueSf\", getU128Encoder()],\n [\"borrowFactorAdjustedMarketValueSf\", getU128Encoder()],\n [\"borrowedAmountOutsideElevationGroups\", getU64Encoder()],\n [\"fixedTermBorrowRolloverConfig\", getFixedTermBorrowRolloverConfigEncoder()],\n [\"borrowedAmountAtExpiration\", getU64Encoder()],\n [\"padding2\", getArrayEncoder(getU64Encoder(), { size: 4 })],\n ]);\n}\n\nexport function getObligationLiquidityDecoder(): FixedSizeDecoder<ObligationLiquidity> {\n return getStructDecoder([\n [\"borrowReserve\", getAddressDecoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesDecoder()],\n [\"lastBorrowedAtTimestamp\", getU64Decoder()],\n [\"borrowedAmountSf\", getU128Decoder()],\n [\"marketValueSf\", getU128Decoder()],\n [\"borrowFactorAdjustedMarketValueSf\", getU128Decoder()],\n [\"borrowedAmountOutsideElevationGroups\", getU64Decoder()],\n [\"fixedTermBorrowRolloverConfig\", getFixedTermBorrowRolloverConfigDecoder()],\n [\"borrowedAmountAtExpiration\", getU64Decoder()],\n [\"padding2\", getArrayDecoder(getU64Decoder(), { size: 4 })],\n ]);\n}\n\nexport function getObligationLiquidityCodec(): FixedSizeCodec<\n ObligationLiquidityArgs,\n ObligationLiquidity\n> {\n return combineCodec(getObligationLiquidityEncoder(), getObligationLiquidityDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type ObligationOrder = {\n conditionThresholdSf: bigint;\n opportunityParameterSf: bigint;\n minExecutionBonusBps: number;\n maxExecutionBonusBps: number;\n conditionType: number;\n opportunityType: number;\n padding1: ReadonlyUint8Array;\n padding2: Array<bigint>;\n};\n\nexport type ObligationOrderArgs = {\n conditionThresholdSf: number | bigint;\n opportunityParameterSf: number | bigint;\n minExecutionBonusBps: number;\n maxExecutionBonusBps: number;\n conditionType: number;\n opportunityType: number;\n padding1: ReadonlyUint8Array;\n padding2: Array<number | bigint>;\n};\n\nexport function getObligationOrderEncoder(): FixedSizeEncoder<ObligationOrderArgs> {\n return getStructEncoder([\n [\"conditionThresholdSf\", getU128Encoder()],\n [\"opportunityParameterSf\", getU128Encoder()],\n [\"minExecutionBonusBps\", getU16Encoder()],\n [\"maxExecutionBonusBps\", getU16Encoder()],\n [\"conditionType\", getU8Encoder()],\n [\"opportunityType\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 10)],\n [\"padding2\", getArrayEncoder(getU128Encoder(), { size: 5 })],\n ]);\n}\n\nexport function getObligationOrderDecoder(): FixedSizeDecoder<ObligationOrder> {\n return getStructDecoder([\n [\"conditionThresholdSf\", getU128Decoder()],\n [\"opportunityParameterSf\", getU128Decoder()],\n [\"minExecutionBonusBps\", getU16Decoder()],\n [\"maxExecutionBonusBps\", getU16Decoder()],\n [\"conditionType\", getU8Decoder()],\n [\"opportunityType\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 10)],\n [\"padding2\", getArrayDecoder(getU128Decoder(), { size: 5 })],\n ]);\n}\n\nexport function getObligationOrderCodec(): FixedSizeCodec<ObligationOrderArgs, ObligationOrder> {\n return combineCodec(getObligationOrderEncoder(), getObligationOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type PriceHeuristic = { lower: bigint; upper: bigint; exp: bigint };\n\nexport type PriceHeuristicArgs = {\n lower: number | bigint;\n upper: number | bigint;\n exp: number | bigint;\n};\n\nexport function getPriceHeuristicEncoder(): FixedSizeEncoder<PriceHeuristicArgs> {\n return getStructEncoder([\n [\"lower\", getU64Encoder()],\n [\"upper\", getU64Encoder()],\n [\"exp\", getU64Encoder()],\n ]);\n}\n\nexport function getPriceHeuristicDecoder(): FixedSizeDecoder<PriceHeuristic> {\n return getStructDecoder([\n [\"lower\", getU64Decoder()],\n [\"upper\", getU64Decoder()],\n [\"exp\", getU64Decoder()],\n ]);\n}\n\nexport function getPriceHeuristicCodec(): FixedSizeCodec<PriceHeuristicArgs, PriceHeuristic> {\n return combineCodec(getPriceHeuristicEncoder(), getPriceHeuristicDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type PythConfiguration = { price: Address };\n\nexport type PythConfigurationArgs = PythConfiguration;\n\nexport function getPythConfigurationEncoder(): FixedSizeEncoder<PythConfigurationArgs> {\n return getStructEncoder([[\"price\", getAddressEncoder()]]);\n}\n\nexport function getPythConfigurationDecoder(): FixedSizeDecoder<PythConfiguration> {\n return getStructDecoder([[\"price\", getAddressDecoder()]]);\n}\n\nexport function getPythConfigurationCodec(): FixedSizeCodec<\n PythConfigurationArgs,\n PythConfiguration\n> {\n return combineCodec(getPythConfigurationEncoder(), getPythConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ReserveCollateral = {\n mintPubkey: Address;\n mintTotalSupply: bigint;\n supplyVault: Address;\n padding1: Array<bigint>;\n padding2: Array<bigint>;\n};\n\nexport type ReserveCollateralArgs = {\n mintPubkey: Address;\n mintTotalSupply: number | bigint;\n supplyVault: Address;\n padding1: Array<number | bigint>;\n padding2: Array<number | bigint>;\n};\n\nexport function getReserveCollateralEncoder(): FixedSizeEncoder<ReserveCollateralArgs> {\n return getStructEncoder([\n [\"mintPubkey\", getAddressEncoder()],\n [\"mintTotalSupply\", getU64Encoder()],\n [\"supplyVault\", getAddressEncoder()],\n [\"padding1\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n [\"padding2\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveCollateralDecoder(): FixedSizeDecoder<ReserveCollateral> {\n return getStructDecoder([\n [\"mintPubkey\", getAddressDecoder()],\n [\"mintTotalSupply\", getU64Decoder()],\n [\"supplyVault\", getAddressDecoder()],\n [\"padding1\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n [\"padding2\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveCollateralCodec(): FixedSizeCodec<\n ReserveCollateralArgs,\n ReserveCollateral\n> {\n return combineCodec(getReserveCollateralEncoder(), getReserveCollateralDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getBorrowRateCurveDecoder,\n getBorrowRateCurveEncoder,\n getReserveFeesDecoder,\n getReserveFeesEncoder,\n getTokenInfoDecoder,\n getTokenInfoEncoder,\n getWithdrawalCapsDecoder,\n getWithdrawalCapsEncoder,\n type BorrowRateCurve,\n type BorrowRateCurveArgs,\n type ReserveFees,\n type ReserveFeesArgs,\n type TokenInfo,\n type TokenInfoArgs,\n type WithdrawalCaps,\n type WithdrawalCapsArgs,\n} from \".\";\n\nexport type ReserveConfig = {\n status: number;\n paddingDeprecatedAssetTier: number;\n hostFixedInterestRateBps: number;\n minDeleveragingBonusBps: number;\n blockCtokenUsage: number;\n earlyRepayRemainingInterestPct: number;\n emergencyMode: number;\n interestRateBasis: number;\n reserved1: ReadonlyUint8Array;\n protocolOrderExecutionFeePct: number;\n protocolTakeRatePct: number;\n protocolLiquidationFeePct: number;\n loanToValuePct: number;\n liquidationThresholdPct: number;\n minLiquidationBonusBps: number;\n maxLiquidationBonusBps: number;\n badDebtLiquidationBonusBps: number;\n deleveragingMarginCallPeriodSecs: bigint;\n deleveragingThresholdDecreaseBpsPerDay: bigint;\n fees: ReserveFees;\n borrowRateCurve: BorrowRateCurve;\n borrowFactorPct: bigint;\n depositLimit: bigint;\n borrowLimit: bigint;\n tokenInfo: TokenInfo;\n depositWithdrawalCap: WithdrawalCaps;\n debtWithdrawalCap: WithdrawalCaps;\n elevationGroups: ReadonlyUint8Array;\n disableUsageAsCollOutsideEmode: number;\n utilizationLimitBlockBorrowingAbovePct: number;\n autodeleverageEnabled: number;\n proposerAuthorityLocked: number;\n borrowLimitOutsideElevationGroup: bigint;\n borrowLimitAgainstThisCollateralInElevationGroup: Array<bigint>;\n deleveragingBonusIncreaseBpsPerDay: bigint;\n debtMaturityTimestamp: bigint;\n debtTermSeconds: bigint;\n rewardsAmountPerAccrualUnit: bigint;\n permissionedOps: bigint;\n};\n\nexport type ReserveConfigArgs = {\n status: number;\n paddingDeprecatedAssetTier: number;\n hostFixedInterestRateBps: number;\n minDeleveragingBonusBps: number;\n blockCtokenUsage: number;\n earlyRepayRemainingInterestPct: number;\n emergencyMode: number;\n interestRateBasis: number;\n reserved1: ReadonlyUint8Array;\n protocolOrderExecutionFeePct: number;\n protocolTakeRatePct: number;\n protocolLiquidationFeePct: number;\n loanToValuePct: number;\n liquidationThresholdPct: number;\n minLiquidationBonusBps: number;\n maxLiquidationBonusBps: number;\n badDebtLiquidationBonusBps: number;\n deleveragingMarginCallPeriodSecs: number | bigint;\n deleveragingThresholdDecreaseBpsPerDay: number | bigint;\n fees: ReserveFeesArgs;\n borrowRateCurve: BorrowRateCurveArgs;\n borrowFactorPct: number | bigint;\n depositLimit: number | bigint;\n borrowLimit: number | bigint;\n tokenInfo: TokenInfoArgs;\n depositWithdrawalCap: WithdrawalCapsArgs;\n debtWithdrawalCap: WithdrawalCapsArgs;\n elevationGroups: ReadonlyUint8Array;\n disableUsageAsCollOutsideEmode: number;\n utilizationLimitBlockBorrowingAbovePct: number;\n autodeleverageEnabled: number;\n proposerAuthorityLocked: number;\n borrowLimitOutsideElevationGroup: number | bigint;\n borrowLimitAgainstThisCollateralInElevationGroup: Array<number | bigint>;\n deleveragingBonusIncreaseBpsPerDay: number | bigint;\n debtMaturityTimestamp: number | bigint;\n debtTermSeconds: number | bigint;\n rewardsAmountPerAccrualUnit: number | bigint;\n permissionedOps: number | bigint;\n};\n\nexport function getReserveConfigEncoder(): FixedSizeEncoder<ReserveConfigArgs> {\n return getStructEncoder([\n [\"status\", getU8Encoder()],\n [\"paddingDeprecatedAssetTier\", getU8Encoder()],\n [\"hostFixedInterestRateBps\", getU16Encoder()],\n [\"minDeleveragingBonusBps\", getU16Encoder()],\n [\"blockCtokenUsage\", getU8Encoder()],\n [\"earlyRepayRemainingInterestPct\", getU8Encoder()],\n [\"emergencyMode\", getU8Encoder()],\n [\"interestRateBasis\", getU8Encoder()],\n [\"reserved1\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"protocolOrderExecutionFeePct\", getU8Encoder()],\n [\"protocolTakeRatePct\", getU8Encoder()],\n [\"protocolLiquidationFeePct\", getU8Encoder()],\n [\"loanToValuePct\", getU8Encoder()],\n [\"liquidationThresholdPct\", getU8Encoder()],\n [\"minLiquidationBonusBps\", getU16Encoder()],\n [\"maxLiquidationBonusBps\", getU16Encoder()],\n [\"badDebtLiquidationBonusBps\", getU16Encoder()],\n [\"deleveragingMarginCallPeriodSecs\", getU64Encoder()],\n [\"deleveragingThresholdDecreaseBpsPerDay\", getU64Encoder()],\n [\"fees\", getReserveFeesEncoder()],\n [\"borrowRateCurve\", getBorrowRateCurveEncoder()],\n [\"borrowFactorPct\", getU64Encoder()],\n [\"depositLimit\", getU64Encoder()],\n [\"borrowLimit\", getU64Encoder()],\n [\"tokenInfo\", getTokenInfoEncoder()],\n [\"depositWithdrawalCap\", getWithdrawalCapsEncoder()],\n [\"debtWithdrawalCap\", getWithdrawalCapsEncoder()],\n [\"elevationGroups\", fixEncoderSize(getBytesEncoder(), 20)],\n [\"disableUsageAsCollOutsideEmode\", getU8Encoder()],\n [\"utilizationLimitBlockBorrowingAbovePct\", getU8Encoder()],\n [\"autodeleverageEnabled\", getU8Encoder()],\n [\"proposerAuthorityLocked\", getU8Encoder()],\n [\"borrowLimitOutsideElevationGroup\", getU64Encoder()],\n [\n \"borrowLimitAgainstThisCollateralInElevationGroup\",\n getArrayEncoder(getU64Encoder(), { size: 32 }),\n ],\n [\"deleveragingBonusIncreaseBpsPerDay\", getU64Encoder()],\n [\"debtMaturityTimestamp\", getU64Encoder()],\n [\"debtTermSeconds\", getU64Encoder()],\n [\"rewardsAmountPerAccrualUnit\", getU64Encoder()],\n [\"permissionedOps\", getU64Encoder()],\n ]);\n}\n\nexport function getReserveConfigDecoder(): FixedSizeDecoder<ReserveConfig> {\n return getStructDecoder([\n [\"status\", getU8Decoder()],\n [\"paddingDeprecatedAssetTier\", getU8Decoder()],\n [\"hostFixedInterestRateBps\", getU16Decoder()],\n [\"minDeleveragingBonusBps\", getU16Decoder()],\n [\"blockCtokenUsage\", getU8Decoder()],\n [\"earlyRepayRemainingInterestPct\", getU8Decoder()],\n [\"emergencyMode\", getU8Decoder()],\n [\"interestRateBasis\", getU8Decoder()],\n [\"reserved1\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"protocolOrderExecutionFeePct\", getU8Decoder()],\n [\"protocolTakeRatePct\", getU8Decoder()],\n [\"protocolLiquidationFeePct\", getU8Decoder()],\n [\"loanToValuePct\", getU8Decoder()],\n [\"liquidationThresholdPct\", getU8Decoder()],\n [\"minLiquidationBonusBps\", getU16Decoder()],\n [\"maxLiquidationBonusBps\", getU16Decoder()],\n [\"badDebtLiquidationBonusBps\", getU16Decoder()],\n [\"deleveragingMarginCallPeriodSecs\", getU64Decoder()],\n [\"deleveragingThresholdDecreaseBpsPerDay\", getU64Decoder()],\n [\"fees\", getReserveFeesDecoder()],\n [\"borrowRateCurve\", getBorrowRateCurveDecoder()],\n [\"borrowFactorPct\", getU64Decoder()],\n [\"depositLimit\", getU64Decoder()],\n [\"borrowLimit\", getU64Decoder()],\n [\"tokenInfo\", getTokenInfoDecoder()],\n [\"depositWithdrawalCap\", getWithdrawalCapsDecoder()],\n [\"debtWithdrawalCap\", getWithdrawalCapsDecoder()],\n [\"elevationGroups\", fixDecoderSize(getBytesDecoder(), 20)],\n [\"disableUsageAsCollOutsideEmode\", getU8Decoder()],\n [\"utilizationLimitBlockBorrowingAbovePct\", getU8Decoder()],\n [\"autodeleverageEnabled\", getU8Decoder()],\n [\"proposerAuthorityLocked\", getU8Decoder()],\n [\"borrowLimitOutsideElevationGroup\", getU64Decoder()],\n [\n \"borrowLimitAgainstThisCollateralInElevationGroup\",\n getArrayDecoder(getU64Decoder(), { size: 32 }),\n ],\n [\"deleveragingBonusIncreaseBpsPerDay\", getU64Decoder()],\n [\"debtMaturityTimestamp\", getU64Decoder()],\n [\"debtTermSeconds\", getU64Decoder()],\n [\"rewardsAmountPerAccrualUnit\", getU64Decoder()],\n [\"permissionedOps\", getU64Decoder()],\n ]);\n}\n\nexport function getReserveConfigCodec(): FixedSizeCodec<ReserveConfigArgs, ReserveConfig> {\n return combineCodec(getReserveConfigEncoder(), getReserveConfigDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type ReserveFees = {\n originationFeeSf: bigint;\n flashLoanFeeSf: bigint;\n padding: ReadonlyUint8Array;\n};\n\nexport type ReserveFeesArgs = {\n originationFeeSf: number | bigint;\n flashLoanFeeSf: number | bigint;\n padding: ReadonlyUint8Array;\n};\n\nexport function getReserveFeesEncoder(): FixedSizeEncoder<ReserveFeesArgs> {\n return getStructEncoder([\n [\"originationFeeSf\", getU64Encoder()],\n [\"flashLoanFeeSf\", getU64Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 8)],\n ]);\n}\n\nexport function getReserveFeesDecoder(): FixedSizeDecoder<ReserveFees> {\n return getStructDecoder([\n [\"originationFeeSf\", getU64Decoder()],\n [\"flashLoanFeeSf\", getU64Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 8)],\n ]);\n}\n\nexport function getReserveFeesCodec(): FixedSizeCodec<ReserveFeesArgs, ReserveFees> {\n return combineCodec(getReserveFeesEncoder(), getReserveFeesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\nimport {\n getBigFractionBytesDecoder,\n getBigFractionBytesEncoder,\n type BigFractionBytes,\n type BigFractionBytesArgs,\n} from \".\";\n\nexport type ReserveLiquidity = {\n mintPubkey: Address;\n supplyVault: Address;\n feeVault: Address;\n totalAvailableAmount: bigint;\n borrowedAmountSf: bigint;\n marketPriceSf: bigint;\n marketPriceLastUpdatedTs: bigint;\n mintDecimals: bigint;\n depositLimitCrossedTimestamp: bigint;\n borrowLimitCrossedTimestamp: bigint;\n cumulativeBorrowRateBsf: BigFractionBytes;\n accumulatedProtocolFeesSf: bigint;\n accumulatedReferrerFeesSf: bigint;\n pendingReferrerFeesSf: bigint;\n absoluteReferralRateSf: bigint;\n tokenProgram: Address;\n rewardsAmountAvailable: bigint;\n padding2: Array<bigint>;\n padding3: Array<bigint>;\n};\n\nexport type ReserveLiquidityArgs = {\n mintPubkey: Address;\n supplyVault: Address;\n feeVault: Address;\n totalAvailableAmount: number | bigint;\n borrowedAmountSf: number | bigint;\n marketPriceSf: number | bigint;\n marketPriceLastUpdatedTs: number | bigint;\n mintDecimals: number | bigint;\n depositLimitCrossedTimestamp: number | bigint;\n borrowLimitCrossedTimestamp: number | bigint;\n cumulativeBorrowRateBsf: BigFractionBytesArgs;\n accumulatedProtocolFeesSf: number | bigint;\n accumulatedReferrerFeesSf: number | bigint;\n pendingReferrerFeesSf: number | bigint;\n absoluteReferralRateSf: number | bigint;\n tokenProgram: Address;\n rewardsAmountAvailable: number | bigint;\n padding2: Array<number | bigint>;\n padding3: Array<number | bigint>;\n};\n\nexport function getReserveLiquidityEncoder(): FixedSizeEncoder<ReserveLiquidityArgs> {\n return getStructEncoder([\n [\"mintPubkey\", getAddressEncoder()],\n [\"supplyVault\", getAddressEncoder()],\n [\"feeVault\", getAddressEncoder()],\n [\"totalAvailableAmount\", getU64Encoder()],\n [\"borrowedAmountSf\", getU128Encoder()],\n [\"marketPriceSf\", getU128Encoder()],\n [\"marketPriceLastUpdatedTs\", getU64Encoder()],\n [\"mintDecimals\", getU64Encoder()],\n [\"depositLimitCrossedTimestamp\", getU64Encoder()],\n [\"borrowLimitCrossedTimestamp\", getU64Encoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesEncoder()],\n [\"accumulatedProtocolFeesSf\", getU128Encoder()],\n [\"accumulatedReferrerFeesSf\", getU128Encoder()],\n [\"pendingReferrerFeesSf\", getU128Encoder()],\n [\"absoluteReferralRateSf\", getU128Encoder()],\n [\"tokenProgram\", getAddressEncoder()],\n [\"rewardsAmountAvailable\", getU64Encoder()],\n [\"padding2\", getArrayEncoder(getU64Encoder(), { size: 50 })],\n [\"padding3\", getArrayEncoder(getU128Encoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveLiquidityDecoder(): FixedSizeDecoder<ReserveLiquidity> {\n return getStructDecoder([\n [\"mintPubkey\", getAddressDecoder()],\n [\"supplyVault\", getAddressDecoder()],\n [\"feeVault\", getAddressDecoder()],\n [\"totalAvailableAmount\", getU64Decoder()],\n [\"borrowedAmountSf\", getU128Decoder()],\n [\"marketPriceSf\", getU128Decoder()],\n [\"marketPriceLastUpdatedTs\", getU64Decoder()],\n [\"mintDecimals\", getU64Decoder()],\n [\"depositLimitCrossedTimestamp\", getU64Decoder()],\n [\"borrowLimitCrossedTimestamp\", getU64Decoder()],\n [\"cumulativeBorrowRateBsf\", getBigFractionBytesDecoder()],\n [\"accumulatedProtocolFeesSf\", getU128Decoder()],\n [\"accumulatedReferrerFeesSf\", getU128Decoder()],\n [\"pendingReferrerFeesSf\", getU128Decoder()],\n [\"absoluteReferralRateSf\", getU128Decoder()],\n [\"tokenProgram\", getAddressDecoder()],\n [\"rewardsAmountAvailable\", getU64Decoder()],\n [\"padding2\", getArrayDecoder(getU64Decoder(), { size: 50 })],\n [\"padding3\", getArrayDecoder(getU128Decoder(), { size: 32 })],\n ]);\n}\n\nexport function getReserveLiquidityCodec(): FixedSizeCodec<ReserveLiquidityArgs, ReserveLiquidity> {\n return combineCodec(getReserveLiquidityEncoder(), getReserveLiquidityDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type ScopeConfiguration = {\n priceFeed: Address;\n priceChain: Array<number>;\n twapChain: Array<number>;\n};\n\nexport type ScopeConfigurationArgs = ScopeConfiguration;\n\nexport function getScopeConfigurationEncoder(): FixedSizeEncoder<ScopeConfigurationArgs> {\n return getStructEncoder([\n [\"priceFeed\", getAddressEncoder()],\n [\"priceChain\", getArrayEncoder(getU16Encoder(), { size: 4 })],\n [\"twapChain\", getArrayEncoder(getU16Encoder(), { size: 4 })],\n ]);\n}\n\nexport function getScopeConfigurationDecoder(): FixedSizeDecoder<ScopeConfiguration> {\n return getStructDecoder([\n [\"priceFeed\", getAddressDecoder()],\n [\"priceChain\", getArrayDecoder(getU16Decoder(), { size: 4 })],\n [\"twapChain\", getArrayDecoder(getU16Decoder(), { size: 4 })],\n ]);\n}\n\nexport function getScopeConfigurationCodec(): FixedSizeCodec<\n ScopeConfigurationArgs,\n ScopeConfiguration\n> {\n return combineCodec(getScopeConfigurationEncoder(), getScopeConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getStructDecoder,\n getStructEncoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type SwitchboardConfiguration = { priceAggregator: Address; twapAggregator: Address };\n\nexport type SwitchboardConfigurationArgs = SwitchboardConfiguration;\n\nexport function getSwitchboardConfigurationEncoder(): FixedSizeEncoder<SwitchboardConfigurationArgs> {\n return getStructEncoder([\n [\"priceAggregator\", getAddressEncoder()],\n [\"twapAggregator\", getAddressEncoder()],\n ]);\n}\n\nexport function getSwitchboardConfigurationDecoder(): FixedSizeDecoder<SwitchboardConfiguration> {\n return getStructDecoder([\n [\"priceAggregator\", getAddressDecoder()],\n [\"twapAggregator\", getAddressDecoder()],\n ]);\n}\n\nexport function getSwitchboardConfigurationCodec(): FixedSizeCodec<\n SwitchboardConfigurationArgs,\n SwitchboardConfiguration\n> {\n return combineCodec(getSwitchboardConfigurationEncoder(), getSwitchboardConfigurationDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getPriceHeuristicDecoder,\n getPriceHeuristicEncoder,\n getPythConfigurationDecoder,\n getPythConfigurationEncoder,\n getScopeConfigurationDecoder,\n getScopeConfigurationEncoder,\n getSwitchboardConfigurationDecoder,\n getSwitchboardConfigurationEncoder,\n type PriceHeuristic,\n type PriceHeuristicArgs,\n type PythConfiguration,\n type PythConfigurationArgs,\n type ScopeConfiguration,\n type ScopeConfigurationArgs,\n type SwitchboardConfiguration,\n type SwitchboardConfigurationArgs,\n} from \".\";\n\nexport type TokenInfo = {\n name: ReadonlyUint8Array;\n heuristic: PriceHeuristic;\n maxTwapDivergenceBps: bigint;\n maxAgePriceSeconds: bigint;\n maxAgeTwapSeconds: bigint;\n scopeConfiguration: ScopeConfiguration;\n switchboardConfiguration: SwitchboardConfiguration;\n pythConfiguration: PythConfiguration;\n blockPriceUsage: number;\n reserved: ReadonlyUint8Array;\n padding: Array<bigint>;\n};\n\nexport type TokenInfoArgs = {\n name: ReadonlyUint8Array;\n heuristic: PriceHeuristicArgs;\n maxTwapDivergenceBps: number | bigint;\n maxAgePriceSeconds: number | bigint;\n maxAgeTwapSeconds: number | bigint;\n scopeConfiguration: ScopeConfigurationArgs;\n switchboardConfiguration: SwitchboardConfigurationArgs;\n pythConfiguration: PythConfigurationArgs;\n blockPriceUsage: number;\n reserved: ReadonlyUint8Array;\n padding: Array<number | bigint>;\n};\n\nexport function getTokenInfoEncoder(): FixedSizeEncoder<TokenInfoArgs> {\n return getStructEncoder([\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"heuristic\", getPriceHeuristicEncoder()],\n [\"maxTwapDivergenceBps\", getU64Encoder()],\n [\"maxAgePriceSeconds\", getU64Encoder()],\n [\"maxAgeTwapSeconds\", getU64Encoder()],\n [\"scopeConfiguration\", getScopeConfigurationEncoder()],\n [\"switchboardConfiguration\", getSwitchboardConfigurationEncoder()],\n [\"pythConfiguration\", getPythConfigurationEncoder()],\n [\"blockPriceUsage\", getU8Encoder()],\n [\"reserved\", fixEncoderSize(getBytesEncoder(), 7)],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 19 })],\n ]);\n}\n\nexport function getTokenInfoDecoder(): FixedSizeDecoder<TokenInfo> {\n return getStructDecoder([\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"heuristic\", getPriceHeuristicDecoder()],\n [\"maxTwapDivergenceBps\", getU64Decoder()],\n [\"maxAgePriceSeconds\", getU64Decoder()],\n [\"maxAgeTwapSeconds\", getU64Decoder()],\n [\"scopeConfiguration\", getScopeConfigurationDecoder()],\n [\"switchboardConfiguration\", getSwitchboardConfigurationDecoder()],\n [\"pythConfiguration\", getPythConfigurationDecoder()],\n [\"blockPriceUsage\", getU8Decoder()],\n [\"reserved\", fixDecoderSize(getBytesDecoder(), 7)],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 19 })],\n ]);\n}\n\nexport function getTokenInfoCodec(): FixedSizeCodec<TokenInfoArgs, TokenInfo> {\n return combineCodec(getTokenInfoEncoder(), getTokenInfoDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type WithdrawalCaps = {\n configCapacity: bigint;\n currentTotal: bigint;\n lastIntervalStartTimestamp: bigint;\n configIntervalLengthSeconds: bigint;\n};\n\nexport type WithdrawalCapsArgs = {\n configCapacity: number | bigint;\n currentTotal: number | bigint;\n lastIntervalStartTimestamp: number | bigint;\n configIntervalLengthSeconds: number | bigint;\n};\n\nexport function getWithdrawalCapsEncoder(): FixedSizeEncoder<WithdrawalCapsArgs> {\n return getStructEncoder([\n [\"configCapacity\", getI64Encoder()],\n [\"currentTotal\", getI64Encoder()],\n [\"lastIntervalStartTimestamp\", getU64Encoder()],\n [\"configIntervalLengthSeconds\", getU64Encoder()],\n ]);\n}\n\nexport function getWithdrawalCapsDecoder(): FixedSizeDecoder<WithdrawalCaps> {\n return getStructDecoder([\n [\"configCapacity\", getI64Decoder()],\n [\"currentTotal\", getI64Decoder()],\n [\"lastIntervalStartTimestamp\", getU64Decoder()],\n [\"configIntervalLengthSeconds\", getU64Decoder()],\n ]);\n}\n\nexport function getWithdrawalCapsCodec(): FixedSizeCodec<WithdrawalCapsArgs, WithdrawalCaps> {\n return combineCodec(getWithdrawalCapsEncoder(), getWithdrawalCapsDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type WithdrawQueue = {\n queuedCollateralAmount: bigint;\n nextIssuedTicketSequenceNumber: bigint;\n nextWithdrawableTicketSequenceNumber: bigint;\n};\n\nexport type WithdrawQueueArgs = {\n queuedCollateralAmount: number | bigint;\n nextIssuedTicketSequenceNumber: number | bigint;\n nextWithdrawableTicketSequenceNumber: number | bigint;\n};\n\nexport function getWithdrawQueueEncoder(): FixedSizeEncoder<WithdrawQueueArgs> {\n return getStructEncoder([\n [\"queuedCollateralAmount\", getU64Encoder()],\n [\"nextIssuedTicketSequenceNumber\", getU64Encoder()],\n [\"nextWithdrawableTicketSequenceNumber\", getU64Encoder()],\n ]);\n}\n\nexport function getWithdrawQueueDecoder(): FixedSizeDecoder<WithdrawQueue> {\n return getStructDecoder([\n [\"queuedCollateralAmount\", getU64Decoder()],\n [\"nextIssuedTicketSequenceNumber\", getU64Decoder()],\n [\"nextWithdrawableTicketSequenceNumber\", getU64Decoder()],\n ]);\n}\n\nexport function getWithdrawQueueCodec(): FixedSizeCodec<WithdrawQueueArgs, WithdrawQueue> {\n return combineCodec(getWithdrawQueueEncoder(), getWithdrawQueueDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getBorrowOrderDecoder,\n getBorrowOrderEncoder,\n getLastUpdateDecoder,\n getLastUpdateEncoder,\n getObligationCollateralDecoder,\n getObligationCollateralEncoder,\n getObligationLiquidityDecoder,\n getObligationLiquidityEncoder,\n getObligationOrderDecoder,\n getObligationOrderEncoder,\n type BorrowOrder,\n type BorrowOrderArgs,\n type LastUpdate,\n type LastUpdateArgs,\n type ObligationCollateral,\n type ObligationCollateralArgs,\n type ObligationLiquidity,\n type ObligationLiquidityArgs,\n type ObligationOrder,\n type ObligationOrderArgs,\n} from \"../types\";\n\nexport const OBLIGATION_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 168, 206, 141, 106, 88, 76, 172, 167,\n]);\n\nexport function getObligationDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(OBLIGATION_DISCRIMINATOR);\n}\n\nexport type Obligation = {\n discriminator: ReadonlyUint8Array;\n tag: bigint;\n lastUpdate: LastUpdate;\n lendingMarket: Address;\n owner: Address;\n deposits: Array<ObligationCollateral>;\n lowestReserveDepositLiquidationLtv: bigint;\n depositedValueSf: bigint;\n borrows: Array<ObligationLiquidity>;\n borrowFactorAdjustedDebtValueSf: bigint;\n borrowedAssetsMarketValueSf: bigint;\n allowedBorrowValueSf: bigint;\n unhealthyBorrowValueSf: bigint;\n paddingDeprecatedAssetTiers: ReadonlyUint8Array;\n elevationGroup: number;\n numOfObsoleteDepositReserves: number;\n hasDebt: number;\n referrer: Address;\n borrowingDisabled: number;\n autodeleverageTargetLtvPct: number;\n lowestReserveDepositMaxLtvPct: number;\n numOfObsoleteBorrowReserves: number;\n ownershipTransferState: number;\n reserved: ReadonlyUint8Array;\n highestBorrowFactorPct: bigint;\n autodeleverageMarginCallStartedTimestamp: bigint;\n obligationOrders: Array<ObligationOrder>;\n headBorrowOrder: BorrowOrder;\n pendingOwner: Address;\n tailBorrowOrders: Array<BorrowOrder>;\n padding3: Array<bigint>;\n};\n\nexport type ObligationArgs = {\n tag: number | bigint;\n lastUpdate: LastUpdateArgs;\n lendingMarket: Address;\n owner: Address;\n deposits: Array<ObligationCollateralArgs>;\n lowestReserveDepositLiquidationLtv: number | bigint;\n depositedValueSf: number | bigint;\n borrows: Array<ObligationLiquidityArgs>;\n borrowFactorAdjustedDebtValueSf: number | bigint;\n borrowedAssetsMarketValueSf: number | bigint;\n allowedBorrowValueSf: number | bigint;\n unhealthyBorrowValueSf: number | bigint;\n paddingDeprecatedAssetTiers: ReadonlyUint8Array;\n elevationGroup: number;\n numOfObsoleteDepositReserves: number;\n hasDebt: number;\n referrer: Address;\n borrowingDisabled: number;\n autodeleverageTargetLtvPct: number;\n lowestReserveDepositMaxLtvPct: number;\n numOfObsoleteBorrowReserves: number;\n ownershipTransferState: number;\n reserved: ReadonlyUint8Array;\n highestBorrowFactorPct: number | bigint;\n autodeleverageMarginCallStartedTimestamp: number | bigint;\n obligationOrders: Array<ObligationOrderArgs>;\n headBorrowOrder: BorrowOrderArgs;\n pendingOwner: Address;\n tailBorrowOrders: Array<BorrowOrderArgs>;\n padding3: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link ObligationArgs} account data. */\nexport function getObligationEncoder(): FixedSizeEncoder<ObligationArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"tag\", getU64Encoder()],\n [\"lastUpdate\", getLastUpdateEncoder()],\n [\"lendingMarket\", getAddressEncoder()],\n [\"owner\", getAddressEncoder()],\n [\"deposits\", getArrayEncoder(getObligationCollateralEncoder(), { size: 8 })],\n [\"lowestReserveDepositLiquidationLtv\", getU64Encoder()],\n [\"depositedValueSf\", getU128Encoder()],\n [\"borrows\", getArrayEncoder(getObligationLiquidityEncoder(), { size: 5 })],\n [\"borrowFactorAdjustedDebtValueSf\", getU128Encoder()],\n [\"borrowedAssetsMarketValueSf\", getU128Encoder()],\n [\"allowedBorrowValueSf\", getU128Encoder()],\n [\"unhealthyBorrowValueSf\", getU128Encoder()],\n [\"paddingDeprecatedAssetTiers\", fixEncoderSize(getBytesEncoder(), 13)],\n [\"elevationGroup\", getU8Encoder()],\n [\"numOfObsoleteDepositReserves\", getU8Encoder()],\n [\"hasDebt\", getU8Encoder()],\n [\"referrer\", getAddressEncoder()],\n [\"borrowingDisabled\", getU8Encoder()],\n [\"autodeleverageTargetLtvPct\", getU8Encoder()],\n [\"lowestReserveDepositMaxLtvPct\", getU8Encoder()],\n [\"numOfObsoleteBorrowReserves\", getU8Encoder()],\n [\"ownershipTransferState\", getU8Encoder()],\n [\"reserved\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"highestBorrowFactorPct\", getU64Encoder()],\n [\"autodeleverageMarginCallStartedTimestamp\", getU64Encoder()],\n [\"obligationOrders\", getArrayEncoder(getObligationOrderEncoder(), { size: 2 })],\n [\"headBorrowOrder\", getBorrowOrderEncoder()],\n [\"pendingOwner\", getAddressEncoder()],\n [\"tailBorrowOrders\", getArrayEncoder(getBorrowOrderEncoder(), { size: 2 })],\n [\"padding3\", getArrayEncoder(getU64Encoder(), { size: 29 })],\n ]),\n (value) => ({ ...value, discriminator: OBLIGATION_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Obligation} account data. */\nexport function getObligationDecoder(): FixedSizeDecoder<Obligation> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"tag\", getU64Decoder()],\n [\"lastUpdate\", getLastUpdateDecoder()],\n [\"lendingMarket\", getAddressDecoder()],\n [\"owner\", getAddressDecoder()],\n [\"deposits\", getArrayDecoder(getObligationCollateralDecoder(), { size: 8 })],\n [\"lowestReserveDepositLiquidationLtv\", getU64Decoder()],\n [\"depositedValueSf\", getU128Decoder()],\n [\"borrows\", getArrayDecoder(getObligationLiquidityDecoder(), { size: 5 })],\n [\"borrowFactorAdjustedDebtValueSf\", getU128Decoder()],\n [\"borrowedAssetsMarketValueSf\", getU128Decoder()],\n [\"allowedBorrowValueSf\", getU128Decoder()],\n [\"unhealthyBorrowValueSf\", getU128Decoder()],\n [\"paddingDeprecatedAssetTiers\", fixDecoderSize(getBytesDecoder(), 13)],\n [\"elevationGroup\", getU8Decoder()],\n [\"numOfObsoleteDepositReserves\", getU8Decoder()],\n [\"hasDebt\", getU8Decoder()],\n [\"referrer\", getAddressDecoder()],\n [\"borrowingDisabled\", getU8Decoder()],\n [\"autodeleverageTargetLtvPct\", getU8Decoder()],\n [\"lowestReserveDepositMaxLtvPct\", getU8Decoder()],\n [\"numOfObsoleteBorrowReserves\", getU8Decoder()],\n [\"ownershipTransferState\", getU8Decoder()],\n [\"reserved\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"highestBorrowFactorPct\", getU64Decoder()],\n [\"autodeleverageMarginCallStartedTimestamp\", getU64Decoder()],\n [\"obligationOrders\", getArrayDecoder(getObligationOrderDecoder(), { size: 2 })],\n [\"headBorrowOrder\", getBorrowOrderDecoder()],\n [\"pendingOwner\", getAddressDecoder()],\n [\"tailBorrowOrders\", getArrayDecoder(getBorrowOrderDecoder(), { size: 2 })],\n [\"padding3\", getArrayDecoder(getU64Decoder(), { size: 29 })],\n ]);\n}\n\n/** Gets the codec for {@link Obligation} account data. */\nexport function getObligationCodec(): FixedSizeCodec<ObligationArgs, Obligation> {\n return combineCodec(getObligationEncoder(), getObligationDecoder());\n}\n\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Obligation, TAddress>;\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Obligation, TAddress>;\nexport function decodeObligation<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Obligation, TAddress> | MaybeAccount<Obligation, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getObligationDecoder());\n}\n\nexport async function fetchObligation<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Obligation, TAddress>> {\n const maybeAccount = await fetchMaybeObligation(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeObligation<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Obligation, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeObligation(maybeAccount);\n}\n\nexport async function fetchAllObligation(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Obligation>[]> {\n const maybeAccounts = await fetchAllMaybeObligation(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeObligation(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Obligation>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeObligation(maybeAccount));\n}\n\nexport function getObligationSize(): number {\n return 3344;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getLastUpdateDecoder,\n getLastUpdateEncoder,\n getReserveCollateralDecoder,\n getReserveCollateralEncoder,\n getReserveConfigDecoder,\n getReserveConfigEncoder,\n getReserveLiquidityDecoder,\n getReserveLiquidityEncoder,\n getWithdrawQueueDecoder,\n getWithdrawQueueEncoder,\n type LastUpdate,\n type LastUpdateArgs,\n type ReserveCollateral,\n type ReserveCollateralArgs,\n type ReserveConfig,\n type ReserveConfigArgs,\n type ReserveLiquidity,\n type ReserveLiquidityArgs,\n type WithdrawQueue,\n type WithdrawQueueArgs,\n} from \"../types\";\n\nexport const RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 43, 242, 204, 202, 26, 247, 59, 127,\n]);\n\nexport function getReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(RESERVE_DISCRIMINATOR);\n}\n\nexport type Reserve = {\n discriminator: ReadonlyUint8Array;\n version: bigint;\n lastUpdate: LastUpdate;\n lendingMarket: Address;\n farmCollateral: Address;\n farmDebt: Address;\n liquidity: ReserveLiquidity;\n reserveLiquidityPadding: Array<bigint>;\n collateral: ReserveCollateral;\n reserveCollateralPadding: Array<bigint>;\n config: ReserveConfig;\n configPadding: Array<bigint>;\n borrowedAmountOutsideElevationGroup: bigint;\n borrowedAmountsAgainstThisReserveInElevationGroups: Array<bigint>;\n withdrawQueue: WithdrawQueue;\n padding: Array<bigint>;\n};\n\nexport type ReserveArgs = {\n version: number | bigint;\n lastUpdate: LastUpdateArgs;\n lendingMarket: Address;\n farmCollateral: Address;\n farmDebt: Address;\n liquidity: ReserveLiquidityArgs;\n reserveLiquidityPadding: Array<number | bigint>;\n collateral: ReserveCollateralArgs;\n reserveCollateralPadding: Array<number | bigint>;\n config: ReserveConfigArgs;\n configPadding: Array<number | bigint>;\n borrowedAmountOutsideElevationGroup: number | bigint;\n borrowedAmountsAgainstThisReserveInElevationGroups: Array<number | bigint>;\n withdrawQueue: WithdrawQueueArgs;\n padding: Array<number | bigint>;\n};\n\n/** Gets the encoder for {@link ReserveArgs} account data. */\nexport function getReserveEncoder(): FixedSizeEncoder<ReserveArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"version\", getU64Encoder()],\n [\"lastUpdate\", getLastUpdateEncoder()],\n [\"lendingMarket\", getAddressEncoder()],\n [\"farmCollateral\", getAddressEncoder()],\n [\"farmDebt\", getAddressEncoder()],\n [\"liquidity\", getReserveLiquidityEncoder()],\n [\"reserveLiquidityPadding\", getArrayEncoder(getU64Encoder(), { size: 150 })],\n [\"collateral\", getReserveCollateralEncoder()],\n [\"reserveCollateralPadding\", getArrayEncoder(getU64Encoder(), { size: 150 })],\n [\"config\", getReserveConfigEncoder()],\n [\"configPadding\", getArrayEncoder(getU64Encoder(), { size: 112 })],\n [\"borrowedAmountOutsideElevationGroup\", getU64Encoder()],\n [\n \"borrowedAmountsAgainstThisReserveInElevationGroups\",\n getArrayEncoder(getU64Encoder(), { size: 32 }),\n ],\n [\"withdrawQueue\", getWithdrawQueueEncoder()],\n [\"padding\", getArrayEncoder(getU64Encoder(), { size: 204 })],\n ]),\n (value) => ({ ...value, discriminator: RESERVE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Reserve} account data. */\nexport function getReserveDecoder(): FixedSizeDecoder<Reserve> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"version\", getU64Decoder()],\n [\"lastUpdate\", getLastUpdateDecoder()],\n [\"lendingMarket\", getAddressDecoder()],\n [\"farmCollateral\", getAddressDecoder()],\n [\"farmDebt\", getAddressDecoder()],\n [\"liquidity\", getReserveLiquidityDecoder()],\n [\"reserveLiquidityPadding\", getArrayDecoder(getU64Decoder(), { size: 150 })],\n [\"collateral\", getReserveCollateralDecoder()],\n [\"reserveCollateralPadding\", getArrayDecoder(getU64Decoder(), { size: 150 })],\n [\"config\", getReserveConfigDecoder()],\n [\"configPadding\", getArrayDecoder(getU64Decoder(), { size: 112 })],\n [\"borrowedAmountOutsideElevationGroup\", getU64Decoder()],\n [\n \"borrowedAmountsAgainstThisReserveInElevationGroups\",\n getArrayDecoder(getU64Decoder(), { size: 32 }),\n ],\n [\"withdrawQueue\", getWithdrawQueueDecoder()],\n [\"padding\", getArrayDecoder(getU64Decoder(), { size: 204 })],\n ]);\n}\n\n/** Gets the codec for {@link Reserve} account data. */\nexport function getReserveCodec(): FixedSizeCodec<ReserveArgs, Reserve> {\n return combineCodec(getReserveEncoder(), getReserveDecoder());\n}\n\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Reserve, TAddress>;\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Reserve, TAddress>;\nexport function decodeReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Reserve, TAddress> | MaybeAccount<Reserve, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getReserveDecoder());\n}\n\nexport async function fetchReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Reserve, TAddress>> {\n const maybeAccount = await fetchMaybeReserve(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Reserve, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeReserve(maybeAccount);\n}\n\nexport async function fetchAllReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Reserve>[]> {\n const maybeAccounts = await fetchAllMaybeReserve(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Reserve>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeReserve(maybeAccount));\n}\n\nexport function getReserveSize(): number {\n return 8624;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getObligationCodec,\n getReserveCodec,\n type Obligation,\n type ObligationArgs,\n type Reserve,\n type ReserveArgs,\n} from \"../accounts\";\nimport {\n getRefreshObligationInstruction,\n getRefreshReserveInstruction,\n getRefreshReservesBatchInstruction,\n parseRefreshObligationInstruction,\n parseRefreshReserveInstruction,\n parseRefreshReservesBatchInstruction,\n type ParsedRefreshObligationInstruction,\n type ParsedRefreshReserveInstruction,\n type ParsedRefreshReservesBatchInstruction,\n type RefreshObligationInput,\n type RefreshReserveInput,\n type RefreshReservesBatchInput,\n} from \"../instructions\";\n\nexport const KAMINO_LENDING_PROGRAM_ADDRESS =\n \"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\" as Address<\"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\">;\n\nexport enum KaminoLendingAccount {\n Obligation,\n Reserve,\n}\n\nexport function identifyKaminoLendingAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): KaminoLendingAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([168, 206, 141, 106, 88, 76, 172, 167])\n ),\n 0\n )\n ) {\n return KaminoLendingAccount.Obligation;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([43, 242, 204, 202, 26, 247, 59, 127])\n ),\n 0\n )\n ) {\n return KaminoLendingAccount.Reserve;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"kaminoLending\",\n });\n}\n\nexport enum KaminoLendingInstruction {\n RefreshReserve,\n RefreshReservesBatch,\n RefreshObligation,\n}\n\nexport function identifyKaminoLendingInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): KaminoLendingInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([2, 218, 138, 235, 79, 201, 25, 102])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshReserve;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([144, 110, 26, 103, 162, 204, 252, 147])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshReservesBatch;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([33, 132, 147, 228, 151, 192, 72, 89])\n ),\n 0\n )\n ) {\n return KaminoLendingInstruction.RefreshObligation;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"kaminoLending\",\n });\n}\n\nexport type ParsedKaminoLendingInstruction<\n TProgram extends string = \"KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD\",\n> =\n | ({\n instructionType: KaminoLendingInstruction.RefreshReserve;\n } & ParsedRefreshReserveInstruction<TProgram>)\n | ({\n instructionType: KaminoLendingInstruction.RefreshReservesBatch;\n } & ParsedRefreshReservesBatchInstruction<TProgram>)\n | ({\n instructionType: KaminoLendingInstruction.RefreshObligation;\n } & ParsedRefreshObligationInstruction<TProgram>);\n\nexport function parseKaminoLendingInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedKaminoLendingInstruction<TProgram> {\n const instructionType = identifyKaminoLendingInstruction(instruction);\n switch (instructionType) {\n case KaminoLendingInstruction.RefreshReserve: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: KaminoLendingInstruction.RefreshReserve,\n ...parseRefreshReserveInstruction(instruction),\n };\n }\n case KaminoLendingInstruction.RefreshReservesBatch: {\n return {\n instructionType: KaminoLendingInstruction.RefreshReservesBatch,\n ...parseRefreshReservesBatchInstruction(instruction),\n };\n }\n case KaminoLendingInstruction.RefreshObligation: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: KaminoLendingInstruction.RefreshObligation,\n ...parseRefreshObligationInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"kaminoLending\",\n });\n }\n}\n\nexport type KaminoLendingPlugin = {\n accounts: KaminoLendingPluginAccounts;\n instructions: KaminoLendingPluginInstructions;\n identifyAccount: typeof identifyKaminoLendingAccount;\n identifyInstruction: typeof identifyKaminoLendingInstruction;\n parseInstruction: typeof parseKaminoLendingInstruction;\n};\n\nexport type KaminoLendingPluginAccounts = {\n obligation: ReturnType<typeof getObligationCodec> &\n SelfFetchFunctions<ObligationArgs, Obligation>;\n reserve: ReturnType<typeof getReserveCodec> & SelfFetchFunctions<ReserveArgs, Reserve>;\n};\n\nexport type KaminoLendingPluginInstructions = {\n refreshReserve: (\n input: RefreshReserveInput\n ) => ReturnType<typeof getRefreshReserveInstruction> & SelfPlanAndSendFunctions;\n refreshReservesBatch: (\n input: RefreshReservesBatchInput\n ) => ReturnType<typeof getRefreshReservesBatchInstruction> & SelfPlanAndSendFunctions;\n refreshObligation: (\n input: RefreshObligationInput\n ) => ReturnType<typeof getRefreshObligationInstruction> & SelfPlanAndSendFunctions;\n};\n\nexport type KaminoLendingPluginRequirements = ClientWithRpc<\n GetAccountInfoApi & GetMultipleAccountsApi\n> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function kaminoLendingProgram() {\n return <T extends KaminoLendingPluginRequirements>(\n client: T\n ): ExtendedClient<T, { kaminoLending: KaminoLendingPlugin }> => {\n return extendClient(client, {\n kaminoLending: <KaminoLendingPlugin>{\n accounts: {\n obligation: addSelfFetchFunctions(client, getObligationCodec()),\n reserve: addSelfFetchFunctions(client, getReserveCodec()),\n },\n instructions: {\n refreshReserve: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshReserveInstruction(input)),\n refreshReservesBatch: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshReservesBatchInstruction(input)),\n refreshObligation: (input) =>\n addSelfPlanAndSendFunctions(client, getRefreshObligationInstruction(input)),\n },\n identifyAccount: identifyKaminoLendingAccount,\n identifyInstruction: identifyKaminoLendingInstruction,\n parseInstruction: parseKaminoLendingInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_OBLIGATION_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 33, 132, 147, 228, 151, 192, 72, 89,\n]);\n\nexport function getRefreshObligationDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_OBLIGATION_DISCRIMINATOR);\n}\n\nexport type RefreshObligationInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountLendingMarket extends string | AccountMeta<string> = string,\n TAccountObligation extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountLendingMarket extends string\n ? ReadonlyAccount<TAccountLendingMarket>\n : TAccountLendingMarket,\n TAccountObligation extends string ? WritableAccount<TAccountObligation> : TAccountObligation,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RefreshObligationInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type RefreshObligationInstructionDataArgs = {};\n\nexport function getRefreshObligationInstructionDataEncoder(): FixedSizeEncoder<RefreshObligationInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: REFRESH_OBLIGATION_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshObligationInstructionDataDecoder(): FixedSizeDecoder<RefreshObligationInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getRefreshObligationInstructionDataCodec(): FixedSizeCodec<\n RefreshObligationInstructionDataArgs,\n RefreshObligationInstructionData\n> {\n return combineCodec(\n getRefreshObligationInstructionDataEncoder(),\n getRefreshObligationInstructionDataDecoder()\n );\n}\n\nexport type RefreshObligationInput<\n TAccountLendingMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountObligation extends InstructionAccountInput = InstructionAccountInput,\n> = {\n lendingMarket: TAccountLendingMarket;\n obligation: TAccountObligation;\n};\n\nexport function getRefreshObligationInstruction<\n TAccountLendingMarket extends InstructionAccountInput,\n TAccountObligation extends InstructionAccountInput,\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshObligationInput<TAccountLendingMarket, TAccountObligation>,\n config?: { programAddress?: TProgramAddress }\n): RefreshObligationInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountObligation,\n InstructionAccountInputAddress<TAccountObligation>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n lendingMarket: { value: input.lendingMarket ?? null, isSigner: false, isWritable: false },\n obligation: { value: input.obligation ?? null, isSigner: false, isWritable: true },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"lendingMarket\", accounts.lendingMarket),\n getAccountMeta(\"obligation\", accounts.obligation),\n ],\n data: getRefreshObligationInstructionDataEncoder().encode({}),\n programAddress,\n } as RefreshObligationInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountObligation,\n InstructionAccountInputAddress<TAccountObligation>\n >\n >);\n}\n\nexport type ParsedRefreshObligationInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n lendingMarket: TAccountMetas[0];\n obligation: TAccountMetas[1];\n };\n data: RefreshObligationInstructionData;\n};\n\nexport function parseRefreshObligationInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshObligationInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 2) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 2,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: { lendingMarket: getNextAccount(), obligation: getNextAccount() },\n data: getRefreshObligationInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 2, 218, 138, 235, 79, 201, 25, 102,\n]);\n\nexport function getRefreshReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_RESERVE_DISCRIMINATOR);\n}\n\nexport type RefreshReserveInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountReserve extends string | AccountMeta<string> = string,\n TAccountLendingMarket extends string | AccountMeta<string> = string,\n TAccountPythOracle extends string | AccountMeta<string> = string,\n TAccountSwitchboardPriceOracle extends string | AccountMeta<string> = string,\n TAccountSwitchboardTwapOracle extends string | AccountMeta<string> = string,\n TAccountScopePrices extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountReserve extends string ? WritableAccount<TAccountReserve> : TAccountReserve,\n TAccountLendingMarket extends string\n ? ReadonlyAccount<TAccountLendingMarket>\n : TAccountLendingMarket,\n TAccountPythOracle extends string ? ReadonlyAccount<TAccountPythOracle> : TAccountPythOracle,\n TAccountSwitchboardPriceOracle extends string\n ? ReadonlyAccount<TAccountSwitchboardPriceOracle>\n : TAccountSwitchboardPriceOracle,\n TAccountSwitchboardTwapOracle extends string\n ? ReadonlyAccount<TAccountSwitchboardTwapOracle>\n : TAccountSwitchboardTwapOracle,\n TAccountScopePrices extends string\n ? ReadonlyAccount<TAccountScopePrices>\n : TAccountScopePrices,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type RefreshReserveInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type RefreshReserveInstructionDataArgs = {};\n\nexport function getRefreshReserveInstructionDataEncoder(): FixedSizeEncoder<RefreshReserveInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: REFRESH_RESERVE_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshReserveInstructionDataDecoder(): FixedSizeDecoder<RefreshReserveInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getRefreshReserveInstructionDataCodec(): FixedSizeCodec<\n RefreshReserveInstructionDataArgs,\n RefreshReserveInstructionData\n> {\n return combineCodec(\n getRefreshReserveInstructionDataEncoder(),\n getRefreshReserveInstructionDataDecoder()\n );\n}\n\nexport type RefreshReserveInput<\n TAccountReserve extends InstructionAccountInput = InstructionAccountInput,\n TAccountLendingMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountPythOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSwitchboardPriceOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSwitchboardTwapOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountScopePrices extends InstructionAccountInput = InstructionAccountInput,\n> = {\n reserve: TAccountReserve;\n lendingMarket: TAccountLendingMarket;\n pythOracle?: TAccountPythOracle;\n switchboardPriceOracle?: TAccountSwitchboardPriceOracle;\n switchboardTwapOracle?: TAccountSwitchboardTwapOracle;\n scopePrices?: TAccountScopePrices;\n};\n\nexport function getRefreshReserveInstruction<\n TAccountReserve extends InstructionAccountInput,\n TAccountLendingMarket extends InstructionAccountInput,\n TAccountPythOracle extends InstructionAccountInput,\n TAccountSwitchboardPriceOracle extends InstructionAccountInput,\n TAccountSwitchboardTwapOracle extends InstructionAccountInput,\n TAccountScopePrices extends InstructionAccountInput,\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshReserveInput<\n TAccountReserve,\n TAccountLendingMarket,\n TAccountPythOracle,\n TAccountSwitchboardPriceOracle,\n TAccountSwitchboardTwapOracle,\n TAccountScopePrices\n >,\n config?: { programAddress?: TProgramAddress }\n): RefreshReserveInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountReserve, InstructionAccountInputAddress<TAccountReserve>>,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountPythOracle,\n InstructionAccountInputAddress<TAccountPythOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardPriceOracle,\n InstructionAccountInputAddress<TAccountSwitchboardPriceOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardTwapOracle,\n InstructionAccountInputAddress<TAccountSwitchboardTwapOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountScopePrices,\n InstructionAccountInputAddress<TAccountScopePrices>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n reserve: { value: input.reserve ?? null, isSigner: false, isWritable: true },\n lendingMarket: { value: input.lendingMarket ?? null, isSigner: false, isWritable: false },\n pythOracle: { value: input.pythOracle ?? null, isSigner: false, isWritable: false },\n switchboardPriceOracle: {\n value: input.switchboardPriceOracle ?? null,\n isSigner: false,\n isWritable: false,\n },\n switchboardTwapOracle: {\n value: input.switchboardTwapOracle ?? null,\n isSigner: false,\n isWritable: false,\n },\n scopePrices: { value: input.scopePrices ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"reserve\", accounts.reserve),\n getAccountMeta(\"lendingMarket\", accounts.lendingMarket),\n getAccountMeta(\"pythOracle\", accounts.pythOracle),\n getAccountMeta(\"switchboardPriceOracle\", accounts.switchboardPriceOracle),\n getAccountMeta(\"switchboardTwapOracle\", accounts.switchboardTwapOracle),\n getAccountMeta(\"scopePrices\", accounts.scopePrices),\n ],\n data: getRefreshReserveInstructionDataEncoder().encode({}),\n programAddress,\n } as RefreshReserveInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountReserve,\n InstructionAccountInputAddress<TAccountReserve>\n >,\n ResolvedInstructionAccountMeta<\n TAccountLendingMarket,\n InstructionAccountInputAddress<TAccountLendingMarket>\n >,\n ResolvedInstructionAccountMeta<\n TAccountPythOracle,\n InstructionAccountInputAddress<TAccountPythOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardPriceOracle,\n InstructionAccountInputAddress<TAccountSwitchboardPriceOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSwitchboardTwapOracle,\n InstructionAccountInputAddress<TAccountSwitchboardTwapOracle>\n >,\n ResolvedInstructionAccountMeta<\n TAccountScopePrices,\n InstructionAccountInputAddress<TAccountScopePrices>\n >\n >);\n}\n\nexport type ParsedRefreshReserveInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n reserve: TAccountMetas[0];\n lendingMarket: TAccountMetas[1];\n pythOracle?: TAccountMetas[2] | undefined;\n switchboardPriceOracle?: TAccountMetas[3] | undefined;\n switchboardTwapOracle?: TAccountMetas[4] | undefined;\n scopePrices?: TAccountMetas[5] | undefined;\n };\n data: RefreshReserveInstructionData;\n};\n\nexport function parseRefreshReserveInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshReserveInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 6) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 6,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n const getNextOptionalAccount = () => {\n const accountMeta = getNextAccount();\n return accountMeta.address === KAMINO_LENDING_PROGRAM_ADDRESS ? undefined : accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n reserve: getNextAccount(),\n lendingMarket: getNextAccount(),\n pythOracle: getNextOptionalAccount(),\n switchboardPriceOracle: getNextOptionalAccount(),\n switchboardTwapOracle: getNextOptionalAccount(),\n scopePrices: getNextOptionalAccount(),\n },\n data: getRefreshReserveInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const REFRESH_RESERVES_BATCH_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 144, 110, 26, 103, 162, 204, 252, 147,\n]);\n\nexport function getRefreshReservesBatchDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(REFRESH_RESERVES_BATCH_DISCRIMINATOR);\n}\n\nexport type RefreshReservesBatchInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<TRemainingAccounts>;\n\nexport type RefreshReservesBatchInstructionData = {\n discriminator: ReadonlyUint8Array;\n skipPriceUpdates: boolean;\n};\n\nexport type RefreshReservesBatchInstructionDataArgs = { skipPriceUpdates: boolean };\n\nexport function getRefreshReservesBatchInstructionDataEncoder(): FixedSizeEncoder<RefreshReservesBatchInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"skipPriceUpdates\", getBooleanEncoder()],\n ]),\n (value) => ({ ...value, discriminator: REFRESH_RESERVES_BATCH_DISCRIMINATOR })\n );\n}\n\nexport function getRefreshReservesBatchInstructionDataDecoder(): FixedSizeDecoder<RefreshReservesBatchInstructionData> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"skipPriceUpdates\", getBooleanDecoder()],\n ]);\n}\n\nexport function getRefreshReservesBatchInstructionDataCodec(): FixedSizeCodec<\n RefreshReservesBatchInstructionDataArgs,\n RefreshReservesBatchInstructionData\n> {\n return combineCodec(\n getRefreshReservesBatchInstructionDataEncoder(),\n getRefreshReservesBatchInstructionDataDecoder()\n );\n}\n\nexport type RefreshReservesBatchInput = {\n skipPriceUpdates: RefreshReservesBatchInstructionDataArgs[\"skipPriceUpdates\"];\n};\n\nexport function getRefreshReservesBatchInstruction<\n TProgramAddress extends Address = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n>(\n input: RefreshReservesBatchInput,\n config?: { programAddress?: TProgramAddress }\n): RefreshReservesBatchInstruction<TProgramAddress> {\n // Program address.\n const programAddress = config?.programAddress ?? KAMINO_LENDING_PROGRAM_ADDRESS;\n\n // Original args.\n const args = { ...input };\n\n return Object.freeze({\n data: getRefreshReservesBatchInstructionDataEncoder().encode(\n args as RefreshReservesBatchInstructionDataArgs\n ),\n programAddress,\n } as RefreshReservesBatchInstruction<TProgramAddress>);\n}\n\nexport type ParsedRefreshReservesBatchInstruction<\n TProgram extends string = typeof KAMINO_LENDING_PROGRAM_ADDRESS,\n> = { programAddress: Address<TProgram>; data: RefreshReservesBatchInstructionData };\n\nexport function parseRefreshReservesBatchInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedRefreshReservesBatchInstruction<TProgram> {\n return {\n programAddress: instruction.programAddress,\n data: getRefreshReservesBatchInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import type { ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type { KaminoFarmState, KaminoObligation, KaminoReserve } from \"./types\";\n\nimport { FARM_STATE_DISCRIMINATOR, getFarmStateDecoder } from \"~/generated/kfarms\";\nimport {\n getObligationDecoder,\n getReserveDecoder,\n OBLIGATION_DISCRIMINATOR,\n RESERVE_DISCRIMINATOR,\n} from \"~/generated/klend\";\n\nexport { FARMS_PROGRAM_ADDRESS } from \"~/generated/kfarms\";\nexport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"~/generated/klend\";\n\n/**\n * Decodes a Kamino `Reserve` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKlendReserve(data: ReadonlyUint8Array): KaminoReserve {\n return decodeAccountData(data, RESERVE_DISCRIMINATOR, getReserveDecoder(), \"Kamino Reserve\");\n}\n\n/**\n * Decodes a Kamino `Obligation` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKlendObligation(data: ReadonlyUint8Array): KaminoObligation {\n return decodeAccountData(\n data,\n OBLIGATION_DISCRIMINATOR,\n getObligationDecoder(),\n \"Kamino Obligation\"\n );\n}\n\n/**\n * Decodes a Kamino farms `FarmState` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeKaminoFarmState(data: ReadonlyUint8Array): KaminoFarmState {\n return decodeAccountData(\n data,\n FARM_STATE_DISCRIMINATOR,\n getFarmStateDecoder(),\n \"Kamino FarmState\"\n );\n}\n","// Slot timing constants (matches Kamino SDK)\nexport const SLOTS_PER_SECOND = 2;\n\nexport const SLOTS_PER_MINUTE = SLOTS_PER_SECOND * 60;\n\nexport const SLOTS_PER_HOUR = SLOTS_PER_MINUTE * 60;\n\nexport const SLOTS_PER_DAY = SLOTS_PER_HOUR * 24;\n\nexport const SLOTS_PER_YEAR = SLOTS_PER_DAY * 365;\n\n// Wall-clock year used by the klend program for `TrueApr` reserves\n// (`SECONDS_PER_YEAR = 60 * 60 * 24 * 365`, no leap-year correction).\nexport const SECONDS_PER_YEAR = 31_536_000;\n\n// Default slot duration in milliseconds (matches klend-sdk >= 11)\nexport const DEFAULT_RECENT_SLOT_DURATION_MS = 350;\n\nexport const ONE_HUNDRED_PCT_IN_BPS = 10_000;\n","import { Decimal } from \"decimal.js\";\n\n// Kamino's fractions exceed Decimal's default 20 significant digits and must round-trip exactly\n// (e.g. u128::MAX means \"withdraw all\"), so they use a private 40-digit clone.\nconst FractionDecimal = Decimal.clone({ precision: 40 });\n\n/** Kamino U68F60 scaled fraction (`*Sf` fields). */\nexport class Fraction {\n static MAX_SIZE_F = 128;\n static MAX_SIZE_BF = 256;\n static FRACTIONS = 60;\n static MULTIPLIER = new FractionDecimal(2).pow(Fraction.FRACTIONS);\n\n static MAX_F = 2n ** BigInt(Fraction.MAX_SIZE_F) - 1n;\n static MAX_BF = 2n ** BigInt(Fraction.MAX_SIZE_BF) - 1n;\n\n valueSf: bigint;\n\n /** @throws if `valueSf` is negative or exceeds 256 bits */\n constructor(valueSf: bigint) {\n if (valueSf < 0n || valueSf > Fraction.MAX_BF) {\n throw new Error(\"Number out of range\");\n }\n this.valueSf = valueSf;\n }\n\n toDecimal(): Decimal {\n return new FractionDecimal(this.valueSf.toString()).div(Fraction.MULTIPLIER);\n }\n\n static fromDecimal(n: Decimal | number): Fraction {\n const scaled = new FractionDecimal(n).mul(Fraction.MULTIPLIER);\n // `toFixed()` avoids the exponential notation `BigInt` can't parse.\n return new Fraction(BigInt(scaled.toDecimalPlaces(0, Decimal.ROUND_HALF_CEIL).toFixed()));\n }\n\n static fromBps(n: Decimal | number): Fraction {\n return Fraction.fromDecimal(new FractionDecimal(n).div(10000));\n }\n\n static fromPercent(n: Decimal | number): Fraction {\n return Fraction.fromDecimal(new FractionDecimal(n).div(100));\n }\n\n getValue(): bigint {\n return this.valueSf;\n }\n\n gt(x: Fraction): boolean {\n return this.valueSf > x.valueSf;\n }\n\n lt(x: Fraction): boolean {\n return this.valueSf < x.valueSf;\n }\n\n gte(x: Fraction): boolean {\n return this.valueSf >= x.valueSf;\n }\n\n lte(x: Fraction): boolean {\n return this.valueSf <= x.valueSf;\n }\n\n eq(x: Fraction): boolean {\n return this.valueSf === x.valueSf;\n }\n}\n","import { AccountRole, type Address, type Instruction } from \"@solana/kit\";\n\nimport type { KaminoReserve } from \"./types\";\n\nimport {\n getRefreshObligationInstruction,\n getRefreshReserveInstruction,\n getRefreshReservesBatchInstruction,\n} from \"~/generated/klend\";\n\nconst DISABLED_ORACLES = new Set([\n \"11111111111111111111111111111111\",\n \"nu11111111111111111111111111111111111111111\",\n]);\n\nfunction enabledOracle(oracle: Address): Address | undefined {\n return DISABLED_ORACLES.has(oracle) ? undefined : oracle;\n}\n\n/** Refreshes `reserve` with whichever of its configured oracles are enabled. */\nexport function makeRefreshReserveIx(reserveAddress: Address, reserve: KaminoReserve): Instruction {\n const { tokenInfo } = reserve.config;\n return getRefreshReserveInstruction({\n reserve: reserveAddress,\n lendingMarket: reserve.lendingMarket,\n pythOracle: enabledOracle(tokenInfo.pythConfiguration.price),\n switchboardPriceOracle: enabledOracle(tokenInfo.switchboardConfiguration.priceAggregator),\n switchboardTwapOracle: enabledOracle(tokenInfo.switchboardConfiguration.twapAggregator),\n scopePrices: enabledOracle(tokenInfo.scopeConfiguration.priceFeed),\n });\n}\n\n/** Refreshes an obligation holding a single position in `reserve`. */\nexport function makeRefreshObligationIx(\n lendingMarket: Address,\n obligation: Address,\n reserve: Address\n): Instruction {\n const ix = getRefreshObligationInstruction({ lendingMarket, obligation });\n return { ...ix, accounts: [...ix.accounts, { address: reserve, role: AccountRole.READONLY }] };\n}\n\n/** Refreshes many reserves in one instruction without updating prices. */\nexport function makeRefreshReservesBatchIx(\n reserves: { reserve: Address; lendingMarket: Address }[]\n): Instruction {\n return {\n ...getRefreshReservesBatchInstruction({ skipPriceUpdates: true }),\n accounts: reserves.flatMap(({ reserve, lendingMarket }) => [\n { address: reserve, role: AccountRole.WRITABLE },\n { address: lendingMarket, role: AccountRole.READONLY },\n ]),\n };\n}\n\n/** Refresh reserve then refresh obligation, as required before a Kamino deposit/withdraw CPI. */\nexport function makeRefreshingIxs(\n reserveAddress: Address,\n reserve: KaminoReserve,\n obligation: Address\n): Instruction[] {\n return [\n makeRefreshReserveIx(reserveAddress, reserve),\n makeRefreshObligationIx(reserve.lendingMarket, obligation, reserveAddress),\n ];\n}\n","import type { Address } from \"@solana/kit\";\n\n/**\n * Curated Kamino Reserve: the subset of the generated `Reserve` the SDK reads. A decoded `Reserve`\n * satisfies it structurally.\n */\nexport interface KaminoReserve {\n lendingMarket: Address;\n farmCollateral: Address;\n liquidity: KaminoReserveLiquidity;\n collateral: KaminoReserveCollateral;\n config: KaminoReserveConfig;\n /** cTokens queued for withdrawal; their liquidity is reserved for the ticket holders */\n withdrawQueue: { queuedCollateralAmount: bigint };\n}\n\nexport interface KaminoReserveLiquidity {\n mintPubkey: Address;\n supplyVault: Address;\n mintDecimals: bigint;\n /** Liquid vault balance, native units */\n totalAvailableAmount: bigint;\n /** Scaled fraction */\n borrowedAmountSf: bigint;\n /** Scaled fraction */\n accumulatedProtocolFeesSf: bigint;\n /** Scaled fraction */\n accumulatedReferrerFeesSf: bigint;\n /** Scaled fraction; claimed in refresh_obligation by referrer or protocol */\n pendingReferrerFeesSf: bigint;\n}\n\nexport interface KaminoReserveCollateral {\n mintPubkey: Address;\n /** cToken supply, used for the exchange rate */\n mintTotalSupply: bigint;\n supplyVault: Address;\n}\n\n/** On-chain `InterestRateBasis`, stored as the `u8` `ReserveConfig.interestRateBasis`. */\nexport enum KaminoInterestRateBasis {\n /** Nominal slot-year APRs (`SLOTS_PER_SECOND`); realized rate scales with slot duration. */\n Legacy = 0,\n /** Wall-clock APRs over `SECONDS_PER_YEAR`. All reserves created by klend >= 1.25.0. */\n TrueApr = 1,\n}\n\nexport interface KaminoReserveConfig {\n /** Share of borrow interest kept by the protocol, percent */\n protocolTakeRatePct: number;\n hostFixedInterestRateBps: number;\n /** See {@link KaminoInterestRateBasis}; absent on DTOs serialized before it existed (= Legacy). */\n interestRateBasis?: number;\n /** Native units, u64::MAX for inf */\n depositLimit: bigint;\n /** Native units, u64::MAX for inf, 0 disables borrows */\n borrowLimit: bigint;\n borrowRateCurve: { points: Array<KaminoBorrowRateCurvePoint> };\n tokenInfo: KaminoReserveTokenInfo;\n /** Nonzero while the reserve is in emergency mode; marginfi then gives its collateral zero initial weight */\n emergencyMode: number;\n}\n\nexport interface KaminoBorrowRateCurvePoint {\n utilizationRateBps: number;\n borrowRateBps: number;\n}\n\n/** Oracle feeds; a feed is disabled when its address is the default or null address. */\nexport interface KaminoReserveTokenInfo {\n scopeConfiguration: { priceFeed: Address };\n switchboardConfiguration: { priceAggregator: Address; twapAggregator: Address };\n pythConfiguration: { price: Address };\n}\n\n/** Curated Kamino Obligation: owner, market and the fixed-size deposit/borrow slots. */\nexport interface KaminoObligation {\n lendingMarket: Address;\n owner: Address;\n deposits: Array<KaminoObligationCollateral>;\n borrows: Array<KaminoObligationLiquidity>;\n}\n\nexport interface KaminoObligationCollateral {\n depositReserve: Address;\n /** cTokens */\n depositedAmount: bigint;\n /** Scaled fraction, quote currency */\n marketValueSf: bigint;\n}\n\nexport interface KaminoObligationLiquidity {\n borrowReserve: Address;\n /** Scaled fraction, includes interest */\n borrowedAmountSf: bigint;\n /** Scaled fraction, quote currency */\n marketValueSf: bigint;\n}\n\n/** Curated Kamino FarmState: staked token and the reward schedules needed for reward APYs. */\nexport interface KaminoFarmState {\n token: KaminoFarmTokenInfo;\n rewardInfos: Array<KaminoFarmRewardInfo>;\n}\n\nexport interface KaminoFarmTokenInfo {\n mint: Address;\n decimals: bigint;\n}\n\nexport interface KaminoFarmRewardInfo {\n token: KaminoFarmTokenInfo;\n /** Rewards left in the rewards vault, native units */\n rewardsAvailable: bigint;\n rewardsPerSecondDecimals: number;\n /** Stepwise: each point's rate applies from its `tsStart` until the next point's. */\n rewardScheduleCurve: { points: Array<KaminoRewardCurvePoint> };\n}\n\nexport interface KaminoRewardCurvePoint {\n tsStart: bigint;\n rewardPerTimeUnit: bigint;\n}\n\n/** JSON DTO of {@link KaminoReserve}: addresses and bigints as strings. */\nexport interface KaminoReserveJSON {\n lendingMarket: string;\n farmCollateral: string;\n liquidity: {\n mintPubkey: string;\n supplyVault: string;\n mintDecimals: string;\n totalAvailableAmount: string;\n borrowedAmountSf: string;\n accumulatedProtocolFeesSf: string;\n accumulatedReferrerFeesSf: string;\n pendingReferrerFeesSf: string;\n };\n collateral: {\n mintPubkey: string;\n mintTotalSupply: string;\n supplyVault: string;\n };\n withdrawQueue: { queuedCollateralAmount: string };\n config: {\n protocolTakeRatePct: number;\n hostFixedInterestRateBps: number;\n interestRateBasis?: number;\n depositLimit: string;\n borrowLimit: string;\n borrowRateCurve: { points: Array<KaminoBorrowRateCurvePoint> };\n tokenInfo: {\n scopeConfiguration: { priceFeed: string };\n switchboardConfiguration: { priceAggregator: string; twapAggregator: string };\n pythConfiguration: { price: string };\n };\n /** Missing on older DTOs (= not in emergency) */\n emergencyMode?: number;\n };\n}\n\n/** JSON DTO of {@link KaminoObligation}: addresses and bigints as strings. */\nexport interface KaminoObligationJSON {\n lendingMarket: string;\n owner: string;\n deposits: Array<{ depositReserve: string; depositedAmount: string; marketValueSf: string }>;\n borrows: Array<{ borrowReserve: string; borrowedAmountSf: string; marketValueSf: string }>;\n}\n\n/** JSON DTO of {@link KaminoFarmState}: addresses and bigints as strings. */\nexport interface KaminoFarmStateJSON {\n token: { mint: string; decimals: string };\n rewardInfos: Array<{\n token: { mint: string; decimals: string };\n rewardsAvailable: string;\n rewardsPerSecondDecimals: number;\n rewardScheduleCurve: { points: Array<{ tsStart: string; rewardPerTimeUnit: string }> };\n }>;\n}\n\n/** A marginfi Kamino bank's venue accounts (its integration accounts 1 and 2). */\nexport interface KaminoBankInput {\n bankAddress: Address;\n reserve: Address;\n obligation: Address;\n}\n\n/** A Kamino bank's venue state: its reserve, obligation and, when the reserve has one, collateral farm. */\nexport interface KaminoStates {\n reserveState: KaminoReserve;\n obligationState: KaminoObligation;\n farmState?: KaminoFarmState;\n}\n\n/** JSON DTO of {@link KaminoStates}. */\nexport interface KaminoStatesJSON {\n reserveState: KaminoReserveJSON;\n obligationState: KaminoObligationJSON;\n farmState?: KaminoFarmStateJSON;\n}\n","/**\n * Kamino Lending Protocol - Interest Rate Utilities\n *\n * Provides utilities for calculating interest rates, reserve metrics, and curve generation\n * for the Kamino lending protocol.\n *\n * Extracted all needed functions & constants out of their SDK.\n *\n * Rates here use the reserve state as of its last refresh. klend-sdk >= 12 instead projects\n * accrual to a ledger instant (`getEstimatedDebtAndSupply`) and adds a reserve-rewards supply APR\n * (`calculateTheoreticalReserveRewardsSupplyAPR`); neither is ported yet.\n */\n\nimport { BigNumber } from \"bignumber.js\";\nimport { Decimal } from \"decimal.js\";\n\nimport {\n ONE_HUNDRED_PCT_IN_BPS,\n SLOTS_PER_YEAR,\n SLOTS_PER_SECOND,\n SECONDS_PER_YEAR,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n} from \"./constants\";\nimport { Fraction } from \"./fraction\";\nimport { KaminoBorrowRateCurvePoint, KaminoInterestRateBasis, KaminoReserve } from \"./types\";\n\n// =============================================================================\n// INTERFACES\n// =============================================================================\n\nexport interface KlendInterestRateCurvePoint {\n utilization: number; // 0-100 percentage\n borrowAPY: number; // percentage\n supplyAPY: number; // percentage\n}\n\nexport interface KaminoReserveCurveData {\n reserveAddress: string;\n curvePoints: KlendInterestRateCurvePoint[];\n}\n\n/**\n * How a reserve's configured (curve) rate is turned into a realized annual rate.\n * `multiplier` scales the curve rate; `periodsPerYear` is the compounding\n * granularity used to convert APR to APY.\n */\nexport interface KaminoRateBasis {\n multiplier: number;\n periodsPerYear: number;\n}\n\n// =============================================================================\n// CORE MATH UTILITIES\n// =============================================================================\n\n/**\n * Linear interpolation between two points\n */\nexport const interpolateLinear = (\n x: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number\n): number => {\n return y0 + ((x - x0) * (y1 - y0)) / (x1 - x0);\n};\n\n/**\n * Calculate borrow rate from utilization using interest rate curve\n * @param currentUtilization - Current utilization ratio (0-1)\n * @param curve - Array of [utilization, rate] points\n * @returns Borrow rate for the given utilization\n */\nexport const getKaminoBorrowRate = (\n currentUtilization: number,\n curve: [number, number][]\n): number => {\n let [x0, y0, x1, y1] = [0, 0, 0, 0];\n\n if (currentUtilization > 1) {\n currentUtilization = 1;\n }\n\n for (let i = 1; i < curve.length; i++) {\n const currentPoint = curve[i];\n const previousPoint = curve[i - 1];\n\n if (!currentPoint || !previousPoint) {\n continue;\n }\n\n const [pointUtilization, pointRate] = currentPoint;\n if (pointUtilization === currentUtilization) {\n return pointRate;\n }\n\n if (currentUtilization <= pointUtilization) {\n x0 = previousPoint[0];\n y0 = previousPoint[1];\n x1 = currentPoint[0];\n y1 = currentPoint[1];\n break;\n }\n }\n\n if (x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {\n const lastPoint = curve[curve.length - 1];\n return lastPoint ? lastPoint[1] : 0;\n }\n\n return interpolateLinear(currentUtilization, x0, y0, x1, y1);\n};\n\n// =============================================================================\n// APR/APY CONVERSIONS\n// =============================================================================\n\n/**\n * Convert APR to APY using compound interest formula\n * APY = (1 + APR/n)^n - 1\n * @param apr - Annual Percentage Rate as decimal (e.g., 0.05 for 5%)\n * @param periodsPerYear - Compounding periods per year (defaults to SLOTS_PER_YEAR;\n * use `getKaminoRateBasis(reserve).periodsPerYear` for basis-aware compounding)\n * @returns Annual Percentage Yield as decimal\n */\nexport function calculateAPYFromAPR(apr: number, periodsPerYear: number = SLOTS_PER_YEAR): number {\n return Math.pow(1 + apr / periodsPerYear, periodsPerYear) - 1;\n}\n\n// =============================================================================\n// RESERVE SUPPLY & UTILIZATION\n// =============================================================================\n\n/**\n * Calculate total supply of a reserve\n * Formula: available liquidity + borrowed - protocol fees - referrer fees\n * @param reserve - The Kamino reserve\n * @returns Total supply in lamports\n */\nexport function getKaminoTotalSupply(reserve: KaminoReserve): Decimal {\n const liquidityAvailableAmount = new Decimal(reserve.liquidity.totalAvailableAmount.toString());\n const borrowedAmount = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();\n const accumulatedProtocolFee = new Fraction(\n reserve.liquidity.accumulatedProtocolFeesSf\n ).toDecimal();\n const accumulatedReferrerFees = new Fraction(\n reserve.liquidity.accumulatedReferrerFeesSf\n ).toDecimal();\n const pendingReferrerFees = new Fraction(reserve.liquidity.pendingReferrerFeesSf).toDecimal();\n\n return liquidityAvailableAmount\n .add(borrowedAmount)\n .sub(accumulatedProtocolFee)\n .sub(accumulatedReferrerFees)\n .sub(pendingReferrerFees);\n}\n\n/**\n * Calculate utilization ratio of a reserve\n * Formula: total borrowed / total supply\n * @param reserve - The Kamino reserve\n * @returns Utilization ratio (0-1, e.g., 0.75 = 75% utilized)\n */\nexport function calculateUtilizationRatio(reserve: KaminoReserve): number {\n const totalBorrows = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();\n const totalSupply = getKaminoTotalSupply(reserve);\n if (totalSupply.eq(0)) {\n return 0;\n }\n return totalBorrows.dividedBy(totalSupply).toNumber();\n}\n\n// =============================================================================\n// INTEREST RATE BASIS & SLOT ADJUSTMENT\n// =============================================================================\n\n/**\n * Resolve a reserve's interest rate basis, defaulting to `Legacy` when the\n * field is absent (reserves serialized before it existed).\n * @throws if the on-chain value is not a known basis\n */\nexport function getKaminoInterestRateBasis(reserve: KaminoReserve): KaminoInterestRateBasis {\n const basis = reserve.config.interestRateBasis ?? KaminoInterestRateBasis.Legacy;\n switch (basis) {\n case KaminoInterestRateBasis.Legacy:\n case KaminoInterestRateBasis.TrueApr:\n return basis;\n default:\n throw new Error(`Unsupported Kamino interest rate basis: ${basis}`);\n }\n}\n\n/**\n * Calculate slot adjustment factor based on recent slot duration\n * Used to adjust Legacy-basis rates based on actual blockchain performance\n * @param recentSlotDurationMs - Recent slot duration in milliseconds\n * @returns Slot adjustment factor\n */\nexport function slotAdjustmentFactor(\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n return 1000 / SLOTS_PER_SECOND / recentSlotDurationMs;\n}\n\n/**\n * Rate multiplier and compounding granularity for a reserve, per its\n * interest rate basis (1:1 with klend-sdk `KaminoReserve.rateAdjustmentFactor()`\n * and `accrualUnitsPerYear()`).\n *\n * - `Legacy`: curve rates are slot-year APRs, so they are scaled by the observed\n * slot duration and compounded per slot.\n * - `TrueApr`: curve rates are wall-clock APRs; `recentSlotDurationMs` is ignored\n * and rates compound per second.\n *\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Observed slot duration; only read for `Legacy`\n * @throws for an unsupported basis, or a non-positive slot duration on `Legacy`\n */\nexport function getKaminoRateBasis(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): KaminoRateBasis {\n switch (getKaminoInterestRateBasis(reserve)) {\n case KaminoInterestRateBasis.Legacy:\n if (!Number.isFinite(recentSlotDurationMs) || recentSlotDurationMs <= 0) {\n throw new Error(\n `Kamino recent slot duration must be positive, got ${recentSlotDurationMs}`\n );\n }\n return {\n multiplier: slotAdjustmentFactor(recentSlotDurationMs),\n periodsPerYear: SLOTS_PER_YEAR,\n };\n case KaminoInterestRateBasis.TrueApr:\n return { multiplier: 1, periodsPerYear: SECONDS_PER_YEAR };\n }\n}\n\n/**\n * Calculate the rate multiplier for a reserve (1:1 with klend-sdk\n * `KaminoReserve.rateAdjustmentFactor()`): the slot adjustment factor for a\n * `Legacy` reserve, `1` for a `TrueApr` one.\n */\nexport function calculateSlotAdjustmentFactor(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n return getKaminoRateBasis(reserve, recentSlotDurationMs).multiplier;\n}\n\n// =============================================================================\n// RATE CALCULATIONS\n// =============================================================================\n\n/**\n * Calculate estimated borrow rate for a reserve\n * @param reserve - The reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n * @returns Borrow rate as decimal (e.g., 0.05 = 5%)\n */\nexport function calculateKaminoEstimatedBorrowRate(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const { multiplier } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n const currentUtilization = calculateUtilizationRatio(reserve);\n const curve = truncateBorrowCurve(reserve.config.borrowRateCurve.points);\n return getKaminoBorrowRate(currentUtilization, curve) * multiplier;\n}\n\n/**\n * Calculate estimated supply rate for a reserve\n * Formula: borrow rate × utilization × (1 - protocol take rate)\n * @param reserve - The reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n * @returns Supply rate as decimal (e.g., 0.03 = 3%)\n */\nexport function calculateKaminoEstimatedSupplyRate(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const borrowRate = calculateKaminoEstimatedBorrowRate(reserve, recentSlotDurationMs);\n const currentUtilization = calculateUtilizationRatio(reserve);\n const protocolTakeRatePct = 1 - reserve.config.protocolTakeRatePct / 100;\n\n return borrowRate * currentUtilization * protocolTakeRatePct;\n}\n\n/**\n * Calculate supply APY for a reserve\n * APY includes compounding, making it higher than APR\n * Matches Kamino SDK's reserve.totalSupplyAPY()\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Recent slot duration (defaults to\n * DEFAULT_RECENT_SLOT_DURATION_MS; ignored for TrueApr reserves)\n * @returns Supply APY as decimal (e.g., 0.0512 = 5.12% APY)\n */\nexport function calculateKaminoSupplyAPY(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): number {\n const { periodsPerYear } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n const supplyApr = calculateKaminoEstimatedSupplyRate(reserve, recentSlotDurationMs);\n return calculateAPYFromAPR(supplyApr, periodsPerYear);\n}\n\nexport function scaledSupplies(state: KaminoReserve): [Decimal, Decimal] {\n const liqMintDecimals = new Decimal(state.liquidity.mintDecimals.toString());\n const totalSupplyLamports = getKaminoTotalSupply(state);\n const mintTotalSupplyLam = new Decimal(state.collateral.mintTotalSupply.toString());\n\n const liqScale = new Decimal(10).pow(liqMintDecimals);\n const collScale = new Decimal(10).pow(liqMintDecimals);\n\n const totalSupply = totalSupplyLamports.div(liqScale);\n const totalCollateral = mintTotalSupplyLam.div(collScale);\n\n return [totalSupply, totalCollateral];\n}\n\n// =============================================================================\n// CURVE PROCESSING\n// =============================================================================\n\n/** Underlying tokens per cToken of `reserve` (1 while it has no collateral). */\nexport function getKaminoCTokenMultiplier(reserve: KaminoReserve): BigNumber {\n const [totalLiquidity, totalCollateral] = scaledSupplies(reserve);\n\n return totalCollateral.isZero()\n ? new BigNumber(1)\n : new BigNumber(totalLiquidity.dividedBy(totalCollateral).toString());\n}\n\n/**\n * Convert raw curve points to normalized [utilization, rate] pairs\n * Truncates curve at 100% utilization\n */\nexport const truncateBorrowCurve = (points: KaminoBorrowRateCurvePoint[]): [number, number][] => {\n const curve: [number, number][] = [];\n for (const { utilizationRateBps, borrowRateBps } of points) {\n curve.push([\n utilizationRateBps / ONE_HUNDRED_PCT_IN_BPS,\n borrowRateBps / ONE_HUNDRED_PCT_IN_BPS,\n ]);\n\n if (utilizationRateBps === ONE_HUNDRED_PCT_IN_BPS) {\n break;\n }\n }\n return curve;\n};\n\n/**\n * Get fixed host interest rate from reserve config (1:1 with Kamino SDK)\n * Source: klend-sdk/src/classes/reserve.ts line 209\n */\nexport function getFixedHostInterestRate(reserve: KaminoReserve): number {\n return reserve.config.hostFixedInterestRateBps / 10_000;\n}\n\n/**\n * Get protocol take rate percentage from reserve config\n */\nexport function getProtocolTakeRatePct(reserve: KaminoReserve): number {\n return 1 - reserve.config.protocolTakeRatePct / 100;\n}\n\n// =============================================================================\n// CURVE GENERATION\n// =============================================================================\n\n/**\n * Generate complete interest rate curve for a reserve\n * Creates 101 data points from 0% to 100% utilization\n * @param curvePoints - Raw curve configuration from reserve\n * @param slotAdjustmentFactor - Rate multiplier (`calculateSlotAdjustmentFactor`;\n * the slot adjustment for Legacy reserves, 1 for TrueApr)\n * @param fixedHostInterestRate - Fixed rate added to all borrow rates\n * @param protocolTakeRatePct - Percentage kept by depositors (1 - protocol fee)\n * @param periodsPerYear - APY compounding periods (`getKaminoRateBasis(reserve).periodsPerYear`;\n * defaults to SLOTS_PER_YEAR)\n * @returns Array of curve points with utilization, borrow APY, and supply APY\n */\nexport function generateKaminoReserveCurve(\n curvePoints: KaminoBorrowRateCurvePoint[],\n slotAdjustmentFactor: number,\n fixedHostInterestRate: number,\n protocolTakeRatePct: number,\n periodsPerYear: number = SLOTS_PER_YEAR\n): KlendInterestRateCurvePoint[] {\n if (curvePoints.length === 0) {\n return [];\n }\n\n const curve = truncateBorrowCurve(curvePoints);\n\n return Array.from({ length: 101 }, (_, i) => {\n const utilization = i / 100;\n\n // Calculate base borrow rate and add fixed host interest\n const baseBorrowRate = getKaminoBorrowRate(utilization, curve) * slotAdjustmentFactor;\n const borrowAPR = baseBorrowRate + fixedHostInterestRate;\n\n // Calculate supply APR (utilization × borrowAPR × protocolTakeRate)\n const supplyAPR = utilization * borrowAPR * protocolTakeRatePct;\n\n // Convert to APY with compounding\n const borrowAPY = calculateAPYFromAPR(borrowAPR, periodsPerYear);\n const supplyAPY = calculateAPYFromAPR(supplyAPR, periodsPerYear);\n\n return {\n utilization: utilization * 100,\n borrowAPY: borrowAPY * 100,\n supplyAPY: supplyAPY * 100,\n };\n });\n}\n\n/**\n * Generate the interest rate curve for a reserve, deriving the rate multiplier\n * and compounding granularity from its interest rate basis.\n * @param reserve - The Kamino reserve\n * @param recentSlotDurationMs - Recent slot duration (optional; ignored for TrueApr reserves)\n */\nexport function generateKaminoReserveCurveFromReserve(\n reserve: KaminoReserve,\n recentSlotDurationMs: number = DEFAULT_RECENT_SLOT_DURATION_MS\n): KlendInterestRateCurvePoint[] {\n const { multiplier, periodsPerYear } = getKaminoRateBasis(reserve, recentSlotDurationMs);\n return generateKaminoReserveCurve(\n reserve.config.borrowRateCurve.points,\n multiplier,\n getFixedHostInterestRate(reserve),\n getProtocolTakeRatePct(reserve),\n periodsPerYear\n );\n}\n","import {\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nimport { FARMS_PROGRAM_ADDRESS } from \"~/generated/kfarms\";\nimport { KAMINO_LENDING_PROGRAM_ADDRESS } from \"~/generated/klend\";\n\nconst DEFAULT_ADDRESS = \"11111111111111111111111111111111\" as Address;\n\n/** Kamino lending market authority PDA. */\nexport function deriveLendingMarketAuthority(\n lendingMarket: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\"lma\", getAddressEncoder().encode(lendingMarket)],\n });\n}\n\n/** Reserve liquidity supply vault PDA. */\nexport function deriveReserveLiquiditySupply(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_liq_supply\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve fee receiver PDA. */\nexport function deriveFeeReceiver(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"fee_receiver\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve collateral (cToken) mint PDA. */\nexport function deriveReserveCollateralMint(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_coll_mint\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/** Reserve collateral (cToken) supply vault PDA. */\nexport function deriveReserveCollateralSupply(\n lendingMarket: Address,\n reserveLiquidityMint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n \"reserve_coll_supply\",\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(reserveLiquidityMint),\n ],\n });\n}\n\n/**\n * Obligation PDA. Bank obligations use `tag` and `id` 0 with default seed accounts.\n */\nexport function deriveObligation({\n owner,\n lendingMarket,\n tag = 0,\n id = 0,\n seed1 = DEFAULT_ADDRESS,\n seed2 = DEFAULT_ADDRESS,\n}: {\n owner: Address;\n lendingMarket: Address;\n tag?: number;\n id?: number;\n seed1?: Address;\n seed2?: Address;\n}): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: KAMINO_LENDING_PROGRAM_ADDRESS,\n seeds: [\n new Uint8Array([tag]),\n new Uint8Array([id]),\n getAddressEncoder().encode(owner),\n getAddressEncoder().encode(lendingMarket),\n getAddressEncoder().encode(seed1),\n getAddressEncoder().encode(seed2),\n ],\n });\n}\n\n/**\n * Farms program user state PDA for `obligation` in `farmState`: the obligation's rewards\n * position, unrelated to marginfi users.\n */\nexport function deriveUserState(\n farmState: Address,\n obligation: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: FARMS_PROGRAM_ADDRESS,\n seeds: [\"user\", getAddressEncoder().encode(farmState), getAddressEncoder().encode(obligation)],\n });\n}\n","import { Decimal } from \"decimal.js\";\n\nimport { getKaminoTotalSupply } from \"./interest-rate\";\nimport { KaminoFarmRewardInfo, KaminoFarmState, KaminoReserve } from \"./types\";\n\nexport function getRewardPerTimeUnitSecond(reward: KaminoFarmRewardInfo) {\n const now = new Decimal(new Date().getTime()).div(1000);\n let rewardPerTimeUnitSecond = new Decimal(0);\n for (let i = 0; i < reward.rewardScheduleCurve.points.length - 1; i++) {\n const currentPoint = reward.rewardScheduleCurve.points[i];\n const nextPoint = reward.rewardScheduleCurve.points[i + 1];\n\n if (!currentPoint || !nextPoint) {\n continue;\n }\n\n const { tsStart: tsStartThisPoint, rewardPerTimeUnit } = currentPoint;\n const { tsStart: tsStartNextPoint } = nextPoint;\n\n const thisPeriodStart = new Decimal(tsStartThisPoint.toString());\n const thisPeriodEnd = new Decimal(tsStartNextPoint.toString());\n const rps = new Decimal(rewardPerTimeUnit.toString());\n if (thisPeriodStart.lte(now) && thisPeriodEnd.gte(now)) {\n rewardPerTimeUnitSecond = rps;\n break;\n } else if (thisPeriodStart.gt(now) && thisPeriodEnd.gt(now)) {\n rewardPerTimeUnitSecond = rps;\n break;\n }\n }\n\n const rewardTokenDecimals = Number(reward.token.decimals);\n const rewardAmountPerUnitDecimals = new Decimal(10).pow(\n reward.rewardsPerSecondDecimals.toString()\n );\n const rewardAmountPerUnitLamports = new Decimal(10).pow(rewardTokenDecimals.toString());\n\n const rpsAdjusted = new Decimal(rewardPerTimeUnitSecond.toString())\n .div(rewardAmountPerUnitDecimals)\n .div(rewardAmountPerUnitLamports);\n\n return rewardPerTimeUnitSecond ? rpsAdjusted : new Decimal(0);\n}\n\nexport async function getReserveRewardsApy(\n priceByMint: Record<string, number>,\n farmState: KaminoFarmState,\n reserveState: KaminoReserve\n) {\n const rewardApys: {\n rewardApy: Decimal;\n rewardInfo: KaminoFarmRewardInfo;\n rewardApr: Decimal;\n }[] = [];\n\n for (const rewardInfo of farmState.rewardInfos.filter(\n (x) => x.token.mint !== \"11111111111111111111111111111111\"\n )) {\n // Skip if we don't have prices for reserve or reward token\n const reserveMint = reserveState.liquidity.mintPubkey.toString();\n const rewardMint = rewardInfo.token.mint.toString();\n\n const reservePrice = priceByMint[reserveMint];\n const rewardPrice = priceByMint[rewardMint];\n\n // Check for undefined or null (but allow 0 as a valid price)\n if (\n reservePrice === undefined ||\n reservePrice === null ||\n rewardPrice === undefined ||\n rewardPrice === null\n ) {\n continue;\n }\n\n const { apy, apr } = calculateRewardApy(priceByMint, reserveState, rewardInfo);\n rewardApys.push({ rewardApy: apy, rewardInfo, rewardApr: apr });\n }\n\n return rewardApys;\n}\n\nexport function calculateRewardApy(\n priceByMint: Record<string, number>,\n reserve: KaminoReserve,\n rewardInfo: KaminoFarmRewardInfo\n) {\n const decimals = Number(reserve.liquidity.mintDecimals);\n const totalSupply = getKaminoTotalSupply(reserve);\n const mintAddress = reserve.liquidity.mintPubkey;\n const totalAmount = lamportsToNumberDecimal(totalSupply, decimals);\n const mintPrice = priceByMint[mintAddress.toString()] ?? 0;\n const totalValue = totalAmount.mul(mintPrice);\n const rewardPerTimeUnitSecond = getRewardPerTimeUnitSecond(rewardInfo);\n const rewardsInYear = rewardPerTimeUnitSecond.mul(60 * 60 * 24 * 365);\n const rewardTokenPrice = priceByMint[rewardInfo.token.mint.toString()] ?? 0;\n const rewardsInYearValue = rewardsInYear.mul(rewardTokenPrice);\n const apr = rewardsInYearValue.div(totalValue);\n return { apr, apy: aprToApy(apr, 1) };\n}\n\nfunction aprToApy(apr: Decimal, compoundPeriods: number) {\n // if periods = 365 => daily compound\n // periods = 1 => yearly compound\n // (1 + apr / periods) ** periods - 1;\n return new Decimal(1).add(apr.div(compoundPeriods)).pow(compoundPeriods).sub(1);\n}\n\nfunction lamportsToNumberDecimal(amount: Decimal.Value, decimals: number): Decimal {\n const factor = 10 ** decimals;\n return new Decimal(amount).div(factor);\n}\n","import { address } from \"@solana/kit\";\n\nimport {\n KaminoFarmState,\n KaminoFarmStateJSON,\n KaminoInterestRateBasis,\n KaminoObligation,\n KaminoObligationJSON,\n KaminoReserve,\n KaminoReserveJSON,\n} from \"./types\";\n\n/** Serializes a Kamino Obligation (or a decoded `Obligation`) to its JSON DTO. */\nexport function kaminoObligationToDto(obligation: KaminoObligation): KaminoObligationJSON {\n return {\n lendingMarket: obligation.lendingMarket,\n owner: obligation.owner,\n deposits: obligation.deposits.map((item) => ({\n depositReserve: item.depositReserve,\n depositedAmount: item.depositedAmount.toString(),\n marketValueSf: item.marketValueSf.toString(),\n })),\n borrows: obligation.borrows.map((item) => ({\n borrowReserve: item.borrowReserve,\n borrowedAmountSf: item.borrowedAmountSf.toString(),\n marketValueSf: item.marketValueSf.toString(),\n })),\n };\n}\n\n/**\n * Parses a Kamino Obligation DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoObligation(dto: KaminoObligationJSON): KaminoObligation {\n return {\n lendingMarket: address(dto.lendingMarket),\n owner: address(dto.owner),\n // Hosted endpoints may prune empty position arrays from the payload\n deposits: (dto.deposits ?? []).map((item) => ({\n depositReserve: address(item.depositReserve),\n depositedAmount: BigInt(item.depositedAmount),\n marketValueSf: BigInt(item.marketValueSf),\n })),\n borrows: (dto.borrows ?? []).map((item) => ({\n borrowReserve: address(item.borrowReserve),\n borrowedAmountSf: BigInt(item.borrowedAmountSf),\n marketValueSf: BigInt(item.marketValueSf),\n })),\n };\n}\n\n/** Serializes a Kamino Reserve (or a decoded `Reserve`) to its JSON DTO. */\nexport function kaminoReserveToDto(reserve: KaminoReserve): KaminoReserveJSON {\n const { liquidity, collateral, config } = reserve;\n return {\n lendingMarket: reserve.lendingMarket,\n farmCollateral: reserve.farmCollateral,\n liquidity: {\n mintPubkey: liquidity.mintPubkey,\n supplyVault: liquidity.supplyVault,\n mintDecimals: liquidity.mintDecimals.toString(),\n totalAvailableAmount: liquidity.totalAvailableAmount.toString(),\n borrowedAmountSf: liquidity.borrowedAmountSf.toString(),\n accumulatedProtocolFeesSf: liquidity.accumulatedProtocolFeesSf.toString(),\n accumulatedReferrerFeesSf: liquidity.accumulatedReferrerFeesSf.toString(),\n pendingReferrerFeesSf: liquidity.pendingReferrerFeesSf.toString(),\n },\n collateral: {\n mintPubkey: collateral.mintPubkey,\n mintTotalSupply: collateral.mintTotalSupply.toString(),\n supplyVault: collateral.supplyVault,\n },\n withdrawQueue: {\n queuedCollateralAmount: reserve.withdrawQueue.queuedCollateralAmount.toString(),\n },\n config: {\n protocolTakeRatePct: config.protocolTakeRatePct,\n hostFixedInterestRateBps: config.hostFixedInterestRateBps,\n interestRateBasis: config.interestRateBasis ?? KaminoInterestRateBasis.Legacy,\n depositLimit: config.depositLimit.toString(),\n borrowLimit: config.borrowLimit.toString(),\n borrowRateCurve: {\n points: config.borrowRateCurve.points.map(({ utilizationRateBps, borrowRateBps }) => ({\n utilizationRateBps,\n borrowRateBps,\n })),\n },\n tokenInfo: {\n scopeConfiguration: { priceFeed: config.tokenInfo.scopeConfiguration.priceFeed },\n switchboardConfiguration: {\n priceAggregator: config.tokenInfo.switchboardConfiguration.priceAggregator,\n twapAggregator: config.tokenInfo.switchboardConfiguration.twapAggregator,\n },\n pythConfiguration: { price: config.tokenInfo.pythConfiguration.price },\n },\n emergencyMode: config.emergencyMode,\n },\n };\n}\n\n/**\n * Parses a Kamino Reserve DTO; a missing `interestRateBasis` becomes Legacy.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoReserve(dto: KaminoReserveJSON): KaminoReserve {\n const { liquidity, collateral, config } = dto;\n return {\n lendingMarket: address(dto.lendingMarket),\n farmCollateral: address(dto.farmCollateral),\n liquidity: {\n mintPubkey: address(liquidity.mintPubkey),\n supplyVault: address(liquidity.supplyVault),\n mintDecimals: BigInt(liquidity.mintDecimals),\n totalAvailableAmount: BigInt(liquidity.totalAvailableAmount),\n borrowedAmountSf: BigInt(liquidity.borrowedAmountSf),\n accumulatedProtocolFeesSf: BigInt(liquidity.accumulatedProtocolFeesSf),\n accumulatedReferrerFeesSf: BigInt(liquidity.accumulatedReferrerFeesSf),\n pendingReferrerFeesSf: BigInt(liquidity.pendingReferrerFeesSf),\n },\n collateral: {\n mintPubkey: address(collateral.mintPubkey),\n mintTotalSupply: BigInt(collateral.mintTotalSupply),\n supplyVault: address(collateral.supplyVault),\n },\n withdrawQueue: { queuedCollateralAmount: BigInt(dto.withdrawQueue.queuedCollateralAmount) },\n config: {\n protocolTakeRatePct: config.protocolTakeRatePct,\n hostFixedInterestRateBps: config.hostFixedInterestRateBps,\n interestRateBasis: config.interestRateBasis ?? KaminoInterestRateBasis.Legacy,\n depositLimit: BigInt(config.depositLimit),\n borrowLimit: BigInt(config.borrowLimit),\n borrowRateCurve: {\n points: config.borrowRateCurve.points.map(({ utilizationRateBps, borrowRateBps }) => ({\n utilizationRateBps,\n borrowRateBps,\n })),\n },\n tokenInfo: {\n scopeConfiguration: { priceFeed: address(config.tokenInfo.scopeConfiguration.priceFeed) },\n switchboardConfiguration: {\n priceAggregator: address(config.tokenInfo.switchboardConfiguration.priceAggregator),\n twapAggregator: address(config.tokenInfo.switchboardConfiguration.twapAggregator),\n },\n pythConfiguration: { price: address(config.tokenInfo.pythConfiguration.price) },\n },\n emergencyMode: config.emergencyMode ?? 0,\n },\n };\n}\n\n/** Serializes a Kamino FarmState (or a decoded `FarmState`) to its JSON DTO. */\nexport function kaminoFarmStateToDto(farmState: KaminoFarmState): KaminoFarmStateJSON {\n return {\n token: { mint: farmState.token.mint, decimals: farmState.token.decimals.toString() },\n rewardInfos: farmState.rewardInfos.map((item) => ({\n token: { mint: item.token.mint, decimals: item.token.decimals.toString() },\n rewardsAvailable: item.rewardsAvailable.toString(),\n rewardsPerSecondDecimals: item.rewardsPerSecondDecimals,\n rewardScheduleCurve: {\n points: item.rewardScheduleCurve.points.map((point) => ({\n tsStart: point.tsStart.toString(),\n rewardPerTimeUnit: point.rewardPerTimeUnit.toString(),\n })),\n },\n })),\n };\n}\n\n/**\n * Parses a Kamino FarmState DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToKaminoFarmState(dto: KaminoFarmStateJSON): KaminoFarmState {\n return {\n token: { mint: address(dto.token.mint), decimals: BigInt(dto.token.decimals) },\n rewardInfos: dto.rewardInfos.map((item) => ({\n token: { mint: address(item.token.mint), decimals: BigInt(item.token.decimals) },\n rewardsAvailable: BigInt(item.rewardsAvailable),\n rewardsPerSecondDecimals: item.rewardsPerSecondDecimals,\n rewardScheduleCurve: {\n points: item.rewardScheduleCurve.points.map((point) => ({\n tsStart: BigInt(point.tsStart),\n rewardPerTimeUnit: BigInt(point.rewardPerTimeUnit),\n })),\n },\n })),\n };\n}\n","import { address } from \"@solana/kit\";\n\nexport const HOURS_PER_YEAR = 365.25 * 24;\n\nexport const MAX_U64 = BigInt(\"18446744073709551615\").toString();\n\n/** The all-zero address (`Pubkey::default()`), used on-chain for unset account fields. */\nexport const DEFAULT_ADDRESS = address(\"11111111111111111111111111111111\");\n\n/** Bytes of a stake account (`StakeStateV2`). */\nexport const STAKE_ACCOUNT_SIZE = 200n;\n","import { HOURS_PER_YEAR } from \"../constants\";\n\n// ================ interest rate helpers ================\n\n/**\n * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies\n *\n * @param apy {Number} APY (i.e. 0.06 for 6%)\n * @param compoundingFrequency {Number} Compounding frequency (times a year)\n * @returns {Number} APR (i.e. 0.0582 for APY of 0.06)\n */\nconst apyToApr = (apy: number, compoundingFrequency: number = HOURS_PER_YEAR): number =>\n ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;\n\n/**\n * Formula source: http://www.linked8.com/blog/158-apy-to-apr-and-apr-to-apy-calculation-methodologies\n *\n *\n * @param apr {Number} APR (i.e. 0.0582 for 5.82%)\n * @param compoundingFrequency {Number} Compounding frequency (times a year)\n * @returns {Number} APY (i.e. 0.06 for APR of 0.0582)\n */\nconst aprToApy = (\n apr: number,\n compoundingFrequency: number = HOURS_PER_YEAR,\n apyCap: number = 3\n): number => Math.min((1 + apr / compoundingFrequency) ** compoundingFrequency - 1, apyCap);\n\nfunction calculateInterestFromApy(principal: number, durationInYears: number, apy: number): number {\n return principal * apy * durationInYears;\n}\n\nfunction calculateApyFromInterest(\n principal: number,\n durationInYears: number,\n interest: number\n): number {\n return interest / (principal * durationInYears);\n}\n\nexport { apyToApr, aprToApy, calculateInterestFromApy, calculateApyFromInterest };\n","import {\n parseBase64RpcAccount,\n type Address,\n type EncodedAccount,\n type GetMultipleAccountsApi,\n type Rpc,\n type Slot,\n} from \"@solana/kit\";\n\nconst MAX_RETRIES = 3;\n\nasync function fetchAccountsInBatches(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number,\n maxAccountsChunkSize: number\n): Promise<{ slot: Slot; accounts: (EncodedAccount | null)[] }> {\n let slot = 0n;\n const accounts: (EncodedAccount | null)[] = [];\n\n for (const batch of chunkArray(addresses, batchChunkSize)) {\n const chunks = chunkArray(batch, maxAccountsChunkSize);\n\n for (let attempt = 1; ; attempt++) {\n try {\n const responses = await Promise.all(\n chunks.map((chunk) =>\n rpc.getMultipleAccounts(chunk, { commitment: \"confirmed\", encoding: \"base64\" }).send()\n )\n );\n responses.forEach((response, chunkIndex) => {\n slot = response.context.slot > slot ? response.context.slot : slot;\n response.value.forEach((rpcAccount, index) => {\n const account = parseBase64RpcAccount(chunks[chunkIndex][index], rpcAccount);\n accounts.push(account.exists ? account : null);\n });\n });\n break;\n } catch {\n if (attempt === MAX_RETRIES) {\n throw new Error(`Failed to fetch account infos after ${MAX_RETRIES} retries`);\n }\n }\n }\n }\n\n return { slot, accounts };\n}\n\nexport async function chunkedGetRawMultipleAccountInfos(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<[Slot, Map<Address, EncodedAccount>]> {\n const { slot, accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n const accountInfoMap = new Map<Address, EncodedAccount>();\n\n for (const account of accounts) {\n if (account) {\n accountInfoMap.set(account.address, account);\n }\n }\n\n return [slot, accountInfoMap];\n}\n\nexport async function chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<(EncodedAccount | null)[]> {\n const { accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n return accounts;\n}\n\nexport async function chunkedGetRawMultipleAccountInfoOrdered(\n rpc: Rpc<GetMultipleAccountsApi>,\n addresses: Address[],\n batchChunkSize: number = 1000,\n maxAccountsChunkSize: number = 100\n): Promise<EncodedAccount[]> {\n const { accounts } = await fetchAccountsInBatches(\n rpc,\n addresses,\n batchChunkSize,\n maxAccountsChunkSize\n );\n return accounts.filter((account) => account !== null);\n}\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\n\nimport { decodeKaminoFarmState, decodeKlendObligation, decodeKlendReserve } from \"./accounts\";\nimport { kaminoFarmStateToDto, kaminoObligationToDto, kaminoReserveToDto } from \"./serialize\";\nimport type { KaminoBankInput, KaminoStates, KaminoStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link KaminoStates}, keyed by bank address. Banks with a default venue\n * address or a missing reserve or obligation are left out.\n * @throws if a fetched account isn't the Kamino account it should be\n */\nexport async function fetchKaminoStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: KaminoBankInput[]\n): Promise<Record<string, KaminoStates>> {\n const validBanks = banks.filter(\n (bank) => bank.reserve !== DEFAULT_ADDRESS && bank.obligation !== DEFAULT_ADDRESS\n );\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.flatMap((bank) => [bank.reserve, bank.obligation])\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const [reserve, obligation] = accounts.slice(2 * i, 2 * i + 2);\n return reserve && obligation\n ? [\n {\n bankAddress: bank.bankAddress,\n reserveState: decodeKlendReserve(reserve.data),\n obligationState: decodeKlendObligation(obligation.data),\n },\n ]\n : [];\n });\n\n const withFarm = decoded.filter(\n ({ reserveState }) => reserveState.farmCollateral !== DEFAULT_ADDRESS\n );\n const farms = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n withFarm.map(({ reserveState }) => reserveState.farmCollateral)\n );\n const farmByBank = new Map(withFarm.map(({ bankAddress }, i) => [bankAddress, farms[i]]));\n\n return Object.fromEntries(\n decoded.map(({ bankAddress, reserveState, obligationState }) => {\n const farm = farmByBank.get(bankAddress);\n return [\n bankAddress,\n {\n reserveState,\n obligationState,\n farmState: farm ? decodeKaminoFarmState(farm.data) : undefined,\n },\n ];\n })\n );\n}\n\n/**\n * {@link fetchKaminoStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchKaminoStates}\n */\nexport async function fetchKaminoStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: KaminoBankInput[]\n): Promise<Record<string, KaminoStatesJSON>> {\n const states = await fetchKaminoStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, { reserveState, obligationState, farmState }]) => [\n bank,\n {\n reserveState: kaminoReserveToDto(reserveState),\n obligationState: kaminoObligationToDto(obligationState),\n farmState: farmState && kaminoFarmStateToDto(farmState),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum AssetTier {\n Collateral,\n Protected,\n Cross,\n Isolated,\n Unlisted,\n}\n\nexport type AssetTierArgs = AssetTier;\n\nexport function getAssetTierEncoder(): FixedSizeEncoder<AssetTierArgs> {\n return getEnumEncoder(AssetTier);\n}\n\nexport function getAssetTierDecoder(): FixedSizeDecoder<AssetTier> {\n return getEnumDecoder(AssetTier);\n}\n\nexport function getAssetTierCodec(): FixedSizeCodec<AssetTierArgs, AssetTier> {\n return combineCodec(getAssetTierEncoder(), getAssetTierDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type HistoricalIndexData = {\n /** precision: PRICE_PRECISION */\n lastIndexBidPrice: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexAskPrice: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap: bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap5min: bigint;\n /** unix_timestamp of last snapshot */\n lastIndexPriceTwapTs: bigint;\n};\n\nexport type HistoricalIndexDataArgs = {\n /** precision: PRICE_PRECISION */\n lastIndexBidPrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexAskPrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap: number | bigint;\n /** precision: PRICE_PRECISION */\n lastIndexPriceTwap5min: number | bigint;\n /** unix_timestamp of last snapshot */\n lastIndexPriceTwapTs: number | bigint;\n};\n\nexport function getHistoricalIndexDataEncoder(): FixedSizeEncoder<HistoricalIndexDataArgs> {\n return getStructEncoder([\n [\"lastIndexBidPrice\", getU64Encoder()],\n [\"lastIndexAskPrice\", getU64Encoder()],\n [\"lastIndexPriceTwap\", getU64Encoder()],\n [\"lastIndexPriceTwap5min\", getU64Encoder()],\n [\"lastIndexPriceTwapTs\", getI64Encoder()],\n ]);\n}\n\nexport function getHistoricalIndexDataDecoder(): FixedSizeDecoder<HistoricalIndexData> {\n return getStructDecoder([\n [\"lastIndexBidPrice\", getU64Decoder()],\n [\"lastIndexAskPrice\", getU64Decoder()],\n [\"lastIndexPriceTwap\", getU64Decoder()],\n [\"lastIndexPriceTwap5min\", getU64Decoder()],\n [\"lastIndexPriceTwapTs\", getI64Decoder()],\n ]);\n}\n\nexport function getHistoricalIndexDataCodec(): FixedSizeCodec<\n HistoricalIndexDataArgs,\n HistoricalIndexData\n> {\n return combineCodec(getHistoricalIndexDataEncoder(), getHistoricalIndexDataDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type HistoricalOracleData = {\n /** precision: PRICE_PRECISION */\n lastOraclePrice: bigint;\n /** precision: PRICE_PRECISION */\n lastOracleConf: bigint;\n /** number of slots since last update */\n lastOracleDelay: bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap: bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap5min: bigint;\n /** unix_timestamp of last snapshot */\n lastOraclePriceTwapTs: bigint;\n};\n\nexport type HistoricalOracleDataArgs = {\n /** precision: PRICE_PRECISION */\n lastOraclePrice: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOracleConf: number | bigint;\n /** number of slots since last update */\n lastOracleDelay: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap: number | bigint;\n /** precision: PRICE_PRECISION */\n lastOraclePriceTwap5min: number | bigint;\n /** unix_timestamp of last snapshot */\n lastOraclePriceTwapTs: number | bigint;\n};\n\nexport function getHistoricalOracleDataEncoder(): FixedSizeEncoder<HistoricalOracleDataArgs> {\n return getStructEncoder([\n [\"lastOraclePrice\", getI64Encoder()],\n [\"lastOracleConf\", getU64Encoder()],\n [\"lastOracleDelay\", getI64Encoder()],\n [\"lastOraclePriceTwap\", getI64Encoder()],\n [\"lastOraclePriceTwap5min\", getI64Encoder()],\n [\"lastOraclePriceTwapTs\", getI64Encoder()],\n ]);\n}\n\nexport function getHistoricalOracleDataDecoder(): FixedSizeDecoder<HistoricalOracleData> {\n return getStructDecoder([\n [\"lastOraclePrice\", getI64Decoder()],\n [\"lastOracleConf\", getU64Decoder()],\n [\"lastOracleDelay\", getI64Decoder()],\n [\"lastOraclePriceTwap\", getI64Decoder()],\n [\"lastOraclePriceTwap5min\", getI64Decoder()],\n [\"lastOraclePriceTwapTs\", getI64Decoder()],\n ]);\n}\n\nexport function getHistoricalOracleDataCodec(): FixedSizeCodec<\n HistoricalOracleDataArgs,\n HistoricalOracleData\n> {\n return combineCodec(getHistoricalOracleDataEncoder(), getHistoricalOracleDataDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getAddressDecoder,\n getAddressEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU32Decoder,\n getU32Encoder,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type InsuranceFund = {\n vault: Address;\n totalShares: bigint;\n userShares: bigint;\n sharesBase: bigint;\n unstakingPeriod: bigint;\n lastRevenueSettleTs: bigint;\n revenueSettlePeriod: bigint;\n totalFactor: number;\n userFactor: number;\n};\n\nexport type InsuranceFundArgs = {\n vault: Address;\n totalShares: number | bigint;\n userShares: number | bigint;\n sharesBase: number | bigint;\n unstakingPeriod: number | bigint;\n lastRevenueSettleTs: number | bigint;\n revenueSettlePeriod: number | bigint;\n totalFactor: number;\n userFactor: number;\n};\n\nexport function getInsuranceFundEncoder(): FixedSizeEncoder<InsuranceFundArgs> {\n return getStructEncoder([\n [\"vault\", getAddressEncoder()],\n [\"totalShares\", getU128Encoder()],\n [\"userShares\", getU128Encoder()],\n [\"sharesBase\", getU128Encoder()],\n [\"unstakingPeriod\", getI64Encoder()],\n [\"lastRevenueSettleTs\", getI64Encoder()],\n [\"revenueSettlePeriod\", getI64Encoder()],\n [\"totalFactor\", getU32Encoder()],\n [\"userFactor\", getU32Encoder()],\n ]);\n}\n\nexport function getInsuranceFundDecoder(): FixedSizeDecoder<InsuranceFund> {\n return getStructDecoder([\n [\"vault\", getAddressDecoder()],\n [\"totalShares\", getU128Decoder()],\n [\"userShares\", getU128Decoder()],\n [\"sharesBase\", getU128Decoder()],\n [\"unstakingPeriod\", getI64Decoder()],\n [\"lastRevenueSettleTs\", getI64Decoder()],\n [\"revenueSettlePeriod\", getI64Decoder()],\n [\"totalFactor\", getU32Decoder()],\n [\"userFactor\", getU32Decoder()],\n ]);\n}\n\nexport function getInsuranceFundCodec(): FixedSizeCodec<InsuranceFundArgs, InsuranceFund> {\n return combineCodec(getInsuranceFundEncoder(), getInsuranceFundDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarginMode {\n Default,\n HighLeverage,\n HighLeverageMaintenance,\n}\n\nexport type MarginModeArgs = MarginMode;\n\nexport function getMarginModeEncoder(): FixedSizeEncoder<MarginModeArgs> {\n return getEnumEncoder(MarginMode);\n}\n\nexport function getMarginModeDecoder(): FixedSizeDecoder<MarginMode> {\n return getEnumDecoder(MarginMode);\n}\n\nexport function getMarginModeCodec(): FixedSizeCodec<MarginModeArgs, MarginMode> {\n return combineCodec(getMarginModeEncoder(), getMarginModeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarketStatus {\n Initialized,\n Active,\n FundingPaused,\n AmmPaused,\n FillPaused,\n WithdrawPaused,\n ReduceOnly,\n Settlement,\n Delisted,\n}\n\nexport type MarketStatusArgs = MarketStatus;\n\nexport function getMarketStatusEncoder(): FixedSizeEncoder<MarketStatusArgs> {\n return getEnumEncoder(MarketStatus);\n}\n\nexport function getMarketStatusDecoder(): FixedSizeDecoder<MarketStatus> {\n return getEnumDecoder(MarketStatus);\n}\n\nexport function getMarketStatusCodec(): FixedSizeCodec<MarketStatusArgs, MarketStatus> {\n return combineCodec(getMarketStatusEncoder(), getMarketStatusDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum MarketType {\n Spot,\n Perp,\n}\n\nexport type MarketTypeArgs = MarketType;\n\nexport function getMarketTypeEncoder(): FixedSizeEncoder<MarketTypeArgs> {\n return getEnumEncoder(MarketType);\n}\n\nexport function getMarketTypeDecoder(): FixedSizeDecoder<MarketType> {\n return getEnumDecoder(MarketType);\n}\n\nexport function getMarketTypeCodec(): FixedSizeCodec<MarketTypeArgs, MarketType> {\n return combineCodec(getMarketTypeEncoder(), getMarketTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OracleSource {\n Pyth,\n Switchboard,\n QuoteAsset,\n Pyth1K,\n Pyth1M,\n PythStableCoin,\n Prelaunch,\n PythPull,\n Pyth1KPull,\n Pyth1MPull,\n PythStableCoinPull,\n SwitchboardOnDemand,\n PythLazer,\n PythLazer1K,\n PythLazer1M,\n PythLazerStableCoin,\n}\n\nexport type OracleSourceArgs = OracleSource;\n\nexport function getOracleSourceEncoder(): FixedSizeEncoder<OracleSourceArgs> {\n return getEnumEncoder(OracleSource);\n}\n\nexport function getOracleSourceDecoder(): FixedSizeDecoder<OracleSource> {\n return getEnumDecoder(OracleSource);\n}\n\nexport function getOracleSourceCodec(): FixedSizeCodec<OracleSourceArgs, OracleSource> {\n return combineCodec(getOracleSourceEncoder(), getOracleSourceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI32Decoder,\n getI32Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getMarketTypeDecoder,\n getMarketTypeEncoder,\n getOrderStatusDecoder,\n getOrderStatusEncoder,\n getOrderTriggerConditionDecoder,\n getOrderTriggerConditionEncoder,\n getOrderTypeDecoder,\n getOrderTypeEncoder,\n getPositionDirectionDecoder,\n getPositionDirectionEncoder,\n type MarketType,\n type MarketTypeArgs,\n type OrderStatus,\n type OrderStatusArgs,\n type OrderTriggerCondition,\n type OrderTriggerConditionArgs,\n type OrderType,\n type OrderTypeArgs,\n type PositionDirection,\n type PositionDirectionArgs,\n} from \".\";\n\nexport type Order = {\n /** The slot the order was placed */\n slot: bigint;\n /**\n * The limit price for the order (can be 0 for market orders)\n * For orders with an auction, this price isn't used until the auction is complete\n * precision: PRICE_PRECISION\n */\n price: bigint;\n /**\n * The size of the order\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmount: bigint;\n /**\n * The amount of the order filled\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmountFilled: bigint;\n /**\n * The amount of quote filled for the order\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmountFilled: bigint;\n /**\n * At what price the order will be triggered. Only relevant for trigger orders\n * precision: PRICE_PRECISION\n */\n triggerPrice: bigint;\n /**\n * The start price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionStartPrice: bigint;\n /**\n * The end price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionEndPrice: bigint;\n /** The time when the order will expire */\n maxTs: bigint;\n /**\n * If set, the order limit price is the oracle price + this offset\n * precision: PRICE_PRECISION\n */\n oraclePriceOffset: number;\n /** The id for the order. Each users has their own order id space */\n orderId: number;\n /** The perp/spot market index */\n marketIndex: number;\n /** Whether the order is open or unused */\n status: OrderStatus;\n /** The type of order */\n orderType: OrderType;\n /** Whether market is spot or perp */\n marketType: MarketType;\n /** User generated order id. Can make it easier to place/cancel orders */\n userOrderId: number;\n /** What the users position was when the order was placed */\n existingPositionDirection: PositionDirection;\n /** Whether the user is going long or short. LONG = bid, SHORT = ask */\n direction: PositionDirection;\n /** Whether the order is allowed to only reduce position size */\n reduceOnly: boolean;\n /** Whether the order must be a maker */\n postOnly: boolean;\n /** Whether the order must be canceled the same slot it is placed */\n immediateOrCancel: boolean;\n /** Whether the order is triggered above or below the trigger price. Only relevant for trigger orders */\n triggerCondition: OrderTriggerCondition;\n /** How many slots the auction lasts */\n auctionDuration: number;\n /** Last 8 bits of the slot the order was posted on-chain (not order slot for signed msg orders) */\n postedSlotTail: number;\n /**\n * Bitflags for further classification\n * 0: is_signed_message\n */\n bitFlags: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type OrderArgs = {\n /** The slot the order was placed */\n slot: number | bigint;\n /**\n * The limit price for the order (can be 0 for market orders)\n * For orders with an auction, this price isn't used until the auction is complete\n * precision: PRICE_PRECISION\n */\n price: number | bigint;\n /**\n * The size of the order\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmount: number | bigint;\n /**\n * The amount of the order filled\n * precision for perps: BASE_PRECISION\n * precision for spot: token mint precision\n */\n baseAssetAmountFilled: number | bigint;\n /**\n * The amount of quote filled for the order\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmountFilled: number | bigint;\n /**\n * At what price the order will be triggered. Only relevant for trigger orders\n * precision: PRICE_PRECISION\n */\n triggerPrice: number | bigint;\n /**\n * The start price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionStartPrice: number | bigint;\n /**\n * The end price for the auction. Only relevant for market/oracle orders\n * precision: PRICE_PRECISION\n */\n auctionEndPrice: number | bigint;\n /** The time when the order will expire */\n maxTs: number | bigint;\n /**\n * If set, the order limit price is the oracle price + this offset\n * precision: PRICE_PRECISION\n */\n oraclePriceOffset: number;\n /** The id for the order. Each users has their own order id space */\n orderId: number;\n /** The perp/spot market index */\n marketIndex: number;\n /** Whether the order is open or unused */\n status: OrderStatusArgs;\n /** The type of order */\n orderType: OrderTypeArgs;\n /** Whether market is spot or perp */\n marketType: MarketTypeArgs;\n /** User generated order id. Can make it easier to place/cancel orders */\n userOrderId: number;\n /** What the users position was when the order was placed */\n existingPositionDirection: PositionDirectionArgs;\n /** Whether the user is going long or short. LONG = bid, SHORT = ask */\n direction: PositionDirectionArgs;\n /** Whether the order is allowed to only reduce position size */\n reduceOnly: boolean;\n /** Whether the order must be a maker */\n postOnly: boolean;\n /** Whether the order must be canceled the same slot it is placed */\n immediateOrCancel: boolean;\n /** Whether the order is triggered above or below the trigger price. Only relevant for trigger orders */\n triggerCondition: OrderTriggerConditionArgs;\n /** How many slots the auction lasts */\n auctionDuration: number;\n /** Last 8 bits of the slot the order was posted on-chain (not order slot for signed msg orders) */\n postedSlotTail: number;\n /**\n * Bitflags for further classification\n * 0: is_signed_message\n */\n bitFlags: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getOrderEncoder(): FixedSizeEncoder<OrderArgs> {\n return getStructEncoder([\n [\"slot\", getU64Encoder()],\n [\"price\", getU64Encoder()],\n [\"baseAssetAmount\", getU64Encoder()],\n [\"baseAssetAmountFilled\", getU64Encoder()],\n [\"quoteAssetAmountFilled\", getU64Encoder()],\n [\"triggerPrice\", getU64Encoder()],\n [\"auctionStartPrice\", getI64Encoder()],\n [\"auctionEndPrice\", getI64Encoder()],\n [\"maxTs\", getI64Encoder()],\n [\"oraclePriceOffset\", getI32Encoder()],\n [\"orderId\", getU32Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"status\", getOrderStatusEncoder()],\n [\"orderType\", getOrderTypeEncoder()],\n [\"marketType\", getMarketTypeEncoder()],\n [\"userOrderId\", getU8Encoder()],\n [\"existingPositionDirection\", getPositionDirectionEncoder()],\n [\"direction\", getPositionDirectionEncoder()],\n [\"reduceOnly\", getBooleanEncoder()],\n [\"postOnly\", getBooleanEncoder()],\n [\"immediateOrCancel\", getBooleanEncoder()],\n [\"triggerCondition\", getOrderTriggerConditionEncoder()],\n [\"auctionDuration\", getU8Encoder()],\n [\"postedSlotTail\", getU8Encoder()],\n [\"bitFlags\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 1)],\n ]);\n}\n\nexport function getOrderDecoder(): FixedSizeDecoder<Order> {\n return getStructDecoder([\n [\"slot\", getU64Decoder()],\n [\"price\", getU64Decoder()],\n [\"baseAssetAmount\", getU64Decoder()],\n [\"baseAssetAmountFilled\", getU64Decoder()],\n [\"quoteAssetAmountFilled\", getU64Decoder()],\n [\"triggerPrice\", getU64Decoder()],\n [\"auctionStartPrice\", getI64Decoder()],\n [\"auctionEndPrice\", getI64Decoder()],\n [\"maxTs\", getI64Decoder()],\n [\"oraclePriceOffset\", getI32Decoder()],\n [\"orderId\", getU32Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"status\", getOrderStatusDecoder()],\n [\"orderType\", getOrderTypeDecoder()],\n [\"marketType\", getMarketTypeDecoder()],\n [\"userOrderId\", getU8Decoder()],\n [\"existingPositionDirection\", getPositionDirectionDecoder()],\n [\"direction\", getPositionDirectionDecoder()],\n [\"reduceOnly\", getBooleanDecoder()],\n [\"postOnly\", getBooleanDecoder()],\n [\"immediateOrCancel\", getBooleanDecoder()],\n [\"triggerCondition\", getOrderTriggerConditionDecoder()],\n [\"auctionDuration\", getU8Decoder()],\n [\"postedSlotTail\", getU8Decoder()],\n [\"bitFlags\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 1)],\n ]);\n}\n\nexport function getOrderCodec(): FixedSizeCodec<OrderArgs, Order> {\n return combineCodec(getOrderEncoder(), getOrderDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderStatus {\n Init,\n Open,\n Filled,\n Canceled,\n}\n\nexport type OrderStatusArgs = OrderStatus;\n\nexport function getOrderStatusEncoder(): FixedSizeEncoder<OrderStatusArgs> {\n return getEnumEncoder(OrderStatus);\n}\n\nexport function getOrderStatusDecoder(): FixedSizeDecoder<OrderStatus> {\n return getEnumDecoder(OrderStatus);\n}\n\nexport function getOrderStatusCodec(): FixedSizeCodec<OrderStatusArgs, OrderStatus> {\n return combineCodec(getOrderStatusEncoder(), getOrderStatusDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderTriggerCondition {\n Above,\n Below,\n TriggeredAbove,\n TriggeredBelow,\n}\n\nexport type OrderTriggerConditionArgs = OrderTriggerCondition;\n\nexport function getOrderTriggerConditionEncoder(): FixedSizeEncoder<OrderTriggerConditionArgs> {\n return getEnumEncoder(OrderTriggerCondition);\n}\n\nexport function getOrderTriggerConditionDecoder(): FixedSizeDecoder<OrderTriggerCondition> {\n return getEnumDecoder(OrderTriggerCondition);\n}\n\nexport function getOrderTriggerConditionCodec(): FixedSizeCodec<\n OrderTriggerConditionArgs,\n OrderTriggerCondition\n> {\n return combineCodec(getOrderTriggerConditionEncoder(), getOrderTriggerConditionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum OrderType {\n Market,\n Limit,\n TriggerMarket,\n TriggerLimit,\n Oracle,\n}\n\nexport type OrderTypeArgs = OrderType;\n\nexport function getOrderTypeEncoder(): FixedSizeEncoder<OrderTypeArgs> {\n return getEnumEncoder(OrderType);\n}\n\nexport function getOrderTypeDecoder(): FixedSizeDecoder<OrderType> {\n return getEnumDecoder(OrderType);\n}\n\nexport function getOrderTypeCodec(): FixedSizeCodec<OrderTypeArgs, OrderType> {\n return combineCodec(getOrderTypeEncoder(), getOrderTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type PerpPosition = {\n /**\n * The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user\n * precision: FUNDING_RATE_PRECISION\n */\n lastCumulativeFundingRate: bigint;\n /**\n * the size of the users perp position\n * precision: BASE_PRECISION\n */\n baseAssetAmount: bigint;\n /**\n * Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmount: bigint;\n /**\n * The amount of quote the user would need to exit their position at to break even\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteBreakEvenAmount: bigint;\n /**\n * The amount quote the user entered the position with. Equal to base asset amount * avg entry price\n * Updated when the user open/closes position. Excludes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteEntryAmount: bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openBids: bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openAsks: bigint;\n /**\n * The amount of pnl settled in this market since opening the position\n * precision: QUOTE_PRECISION\n */\n settledPnl: bigint;\n /**\n * The number of lp (liquidity provider) shares the user has in this perp market\n * LP shares allow users to provide liquidity via the AMM\n * precision: BASE_PRECISION\n */\n lpShares: bigint;\n /**\n * The scaled balance of the isolated position\n * precision: SPOT_BALANCE_PRECISION\n */\n isolatedPositionScaledBalance: bigint;\n /**\n * The last quote asset amount per lp the amm had\n * Used to settle the users lp position\n * precision: QUOTE_PRECISION\n */\n lastQuoteAssetAmountPerLp: bigint;\n padding: ReadonlyUint8Array;\n maxMarginRatio: number;\n /** The market index for the perp market */\n marketIndex: number;\n /** The number of open orders */\n openOrders: number;\n positionFlag: number;\n};\n\nexport type PerpPositionArgs = {\n /**\n * The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user\n * precision: FUNDING_RATE_PRECISION\n */\n lastCumulativeFundingRate: number | bigint;\n /**\n * the size of the users perp position\n * precision: BASE_PRECISION\n */\n baseAssetAmount: number | bigint;\n /**\n * Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteAssetAmount: number | bigint;\n /**\n * The amount of quote the user would need to exit their position at to break even\n * Updated when the user open/closes position or settles pnl. Includes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteBreakEvenAmount: number | bigint;\n /**\n * The amount quote the user entered the position with. Equal to base asset amount * avg entry price\n * Updated when the user open/closes position. Excludes fees/funding\n * precision: QUOTE_PRECISION\n */\n quoteEntryAmount: number | bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openBids: number | bigint;\n /**\n * The amount of non reduce only trigger orders the user has open\n * precision: BASE_PRECISION\n */\n openAsks: number | bigint;\n /**\n * The amount of pnl settled in this market since opening the position\n * precision: QUOTE_PRECISION\n */\n settledPnl: number | bigint;\n /**\n * The number of lp (liquidity provider) shares the user has in this perp market\n * LP shares allow users to provide liquidity via the AMM\n * precision: BASE_PRECISION\n */\n lpShares: number | bigint;\n /**\n * The scaled balance of the isolated position\n * precision: SPOT_BALANCE_PRECISION\n */\n isolatedPositionScaledBalance: number | bigint;\n /**\n * The last quote asset amount per lp the amm had\n * Used to settle the users lp position\n * precision: QUOTE_PRECISION\n */\n lastQuoteAssetAmountPerLp: number | bigint;\n padding: ReadonlyUint8Array;\n maxMarginRatio: number;\n /** The market index for the perp market */\n marketIndex: number;\n /** The number of open orders */\n openOrders: number;\n positionFlag: number;\n};\n\nexport function getPerpPositionEncoder(): FixedSizeEncoder<PerpPositionArgs> {\n return getStructEncoder([\n [\"lastCumulativeFundingRate\", getI64Encoder()],\n [\"baseAssetAmount\", getI64Encoder()],\n [\"quoteAssetAmount\", getI64Encoder()],\n [\"quoteBreakEvenAmount\", getI64Encoder()],\n [\"quoteEntryAmount\", getI64Encoder()],\n [\"openBids\", getI64Encoder()],\n [\"openAsks\", getI64Encoder()],\n [\"settledPnl\", getI64Encoder()],\n [\"lpShares\", getU64Encoder()],\n [\"isolatedPositionScaledBalance\", getU64Encoder()],\n [\"lastQuoteAssetAmountPerLp\", getI64Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 2)],\n [\"maxMarginRatio\", getU16Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"openOrders\", getU8Encoder()],\n [\"positionFlag\", getU8Encoder()],\n ]);\n}\n\nexport function getPerpPositionDecoder(): FixedSizeDecoder<PerpPosition> {\n return getStructDecoder([\n [\"lastCumulativeFundingRate\", getI64Decoder()],\n [\"baseAssetAmount\", getI64Decoder()],\n [\"quoteAssetAmount\", getI64Decoder()],\n [\"quoteBreakEvenAmount\", getI64Decoder()],\n [\"quoteEntryAmount\", getI64Decoder()],\n [\"openBids\", getI64Decoder()],\n [\"openAsks\", getI64Decoder()],\n [\"settledPnl\", getI64Decoder()],\n [\"lpShares\", getU64Decoder()],\n [\"isolatedPositionScaledBalance\", getU64Decoder()],\n [\"lastQuoteAssetAmountPerLp\", getI64Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 2)],\n [\"maxMarginRatio\", getU16Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"openOrders\", getU8Decoder()],\n [\"positionFlag\", getU8Decoder()],\n ]);\n}\n\nexport function getPerpPositionCodec(): FixedSizeCodec<PerpPositionArgs, PerpPosition> {\n return combineCodec(getPerpPositionEncoder(), getPerpPositionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport type PoolBalance = {\n /**\n * To get the pool's token amount, you must multiply the scaled balance by the market's cumulative\n * deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: bigint;\n /** The spot market the pool is for */\n marketIndex: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type PoolBalanceArgs = {\n /**\n * To get the pool's token amount, you must multiply the scaled balance by the market's cumulative\n * deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: number | bigint;\n /** The spot market the pool is for */\n marketIndex: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getPoolBalanceEncoder(): FixedSizeEncoder<PoolBalanceArgs> {\n return getStructEncoder([\n [\"scaledBalance\", getU128Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 6)],\n ]);\n}\n\nexport function getPoolBalanceDecoder(): FixedSizeDecoder<PoolBalance> {\n return getStructDecoder([\n [\"scaledBalance\", getU128Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 6)],\n ]);\n}\n\nexport function getPoolBalanceCodec(): FixedSizeCodec<PoolBalanceArgs, PoolBalance> {\n return combineCodec(getPoolBalanceEncoder(), getPoolBalanceDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum PositionDirection {\n Long,\n Short,\n}\n\nexport type PositionDirectionArgs = PositionDirection;\n\nexport function getPositionDirectionEncoder(): FixedSizeEncoder<PositionDirectionArgs> {\n return getEnumEncoder(PositionDirection);\n}\n\nexport function getPositionDirectionDecoder(): FixedSizeDecoder<PositionDirection> {\n return getEnumDecoder(PositionDirection);\n}\n\nexport function getPositionDirectionCodec(): FixedSizeCodec<\n PositionDirectionArgs,\n PositionDirection\n> {\n return combineCodec(getPositionDirectionEncoder(), getPositionDirectionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getEnumDecoder,\n getEnumEncoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport enum SpotBalanceType {\n Deposit,\n Borrow,\n}\n\nexport type SpotBalanceTypeArgs = SpotBalanceType;\n\nexport function getSpotBalanceTypeEncoder(): FixedSizeEncoder<SpotBalanceTypeArgs> {\n return getEnumEncoder(SpotBalanceType);\n}\n\nexport function getSpotBalanceTypeDecoder(): FixedSizeDecoder<SpotBalanceType> {\n return getEnumDecoder(SpotBalanceType);\n}\n\nexport function getSpotBalanceTypeCodec(): FixedSizeCodec<SpotBalanceTypeArgs, SpotBalanceType> {\n return combineCodec(getSpotBalanceTypeEncoder(), getSpotBalanceTypeDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getSpotBalanceTypeDecoder,\n getSpotBalanceTypeEncoder,\n type SpotBalanceType,\n type SpotBalanceTypeArgs,\n} from \".\";\n\nexport type SpotPosition = {\n /**\n * The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow\n * interest of corresponding market.\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openBids: bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openAsks: bigint;\n /**\n * The cumulative deposits/borrows a user has made into a market\n * precision: token mint precision\n */\n cumulativeDeposits: bigint;\n /** The market index of the corresponding spot market */\n marketIndex: number;\n /** Whether the position is deposit or borrow */\n balanceType: SpotBalanceType;\n /** Number of open orders */\n openOrders: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type SpotPositionArgs = {\n /**\n * The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow\n * interest of corresponding market.\n * precision: SPOT_BALANCE_PRECISION\n */\n scaledBalance: number | bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openBids: number | bigint;\n /**\n * How many spot non reduce only trigger orders the user has open\n * precision: token mint precision\n */\n openAsks: number | bigint;\n /**\n * The cumulative deposits/borrows a user has made into a market\n * precision: token mint precision\n */\n cumulativeDeposits: number | bigint;\n /** The market index of the corresponding spot market */\n marketIndex: number;\n /** Whether the position is deposit or borrow */\n balanceType: SpotBalanceTypeArgs;\n /** Number of open orders */\n openOrders: number;\n padding: ReadonlyUint8Array;\n};\n\nexport function getSpotPositionEncoder(): FixedSizeEncoder<SpotPositionArgs> {\n return getStructEncoder([\n [\"scaledBalance\", getU64Encoder()],\n [\"openBids\", getI64Encoder()],\n [\"openAsks\", getI64Encoder()],\n [\"cumulativeDeposits\", getI64Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"balanceType\", getSpotBalanceTypeEncoder()],\n [\"openOrders\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 4)],\n ]);\n}\n\nexport function getSpotPositionDecoder(): FixedSizeDecoder<SpotPosition> {\n return getStructDecoder([\n [\"scaledBalance\", getU64Decoder()],\n [\"openBids\", getI64Decoder()],\n [\"openAsks\", getI64Decoder()],\n [\"cumulativeDeposits\", getI64Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"balanceType\", getSpotBalanceTypeDecoder()],\n [\"openOrders\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 4)],\n ]);\n}\n\nexport function getSpotPositionCodec(): FixedSizeCodec<SpotPositionArgs, SpotPosition> {\n return combineCodec(getSpotPositionEncoder(), getSpotPositionDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n} from \"@solana/kit\";\n\nexport type UserFees = {\n /**\n * Total taker fee paid\n * precision: QUOTE_PRECISION\n */\n totalFeePaid: bigint;\n /**\n * Total maker fee rebate\n * precision: QUOTE_PRECISION\n */\n totalFeeRebate: bigint;\n /**\n * Total discount from holding token\n * precision: QUOTE_PRECISION\n */\n totalTokenDiscount: bigint;\n /**\n * Total discount from being referred\n * precision: QUOTE_PRECISION\n */\n totalRefereeDiscount: bigint;\n /**\n * Total reward to referrer\n * precision: QUOTE_PRECISION\n */\n totalReferrerReward: bigint;\n /**\n * Total reward to referrer this epoch\n * precision: QUOTE_PRECISION\n */\n currentEpochReferrerReward: bigint;\n};\n\nexport type UserFeesArgs = {\n /**\n * Total taker fee paid\n * precision: QUOTE_PRECISION\n */\n totalFeePaid: number | bigint;\n /**\n * Total maker fee rebate\n * precision: QUOTE_PRECISION\n */\n totalFeeRebate: number | bigint;\n /**\n * Total discount from holding token\n * precision: QUOTE_PRECISION\n */\n totalTokenDiscount: number | bigint;\n /**\n * Total discount from being referred\n * precision: QUOTE_PRECISION\n */\n totalRefereeDiscount: number | bigint;\n /**\n * Total reward to referrer\n * precision: QUOTE_PRECISION\n */\n totalReferrerReward: number | bigint;\n /**\n * Total reward to referrer this epoch\n * precision: QUOTE_PRECISION\n */\n currentEpochReferrerReward: number | bigint;\n};\n\nexport function getUserFeesEncoder(): FixedSizeEncoder<UserFeesArgs> {\n return getStructEncoder([\n [\"totalFeePaid\", getU64Encoder()],\n [\"totalFeeRebate\", getU64Encoder()],\n [\"totalTokenDiscount\", getU64Encoder()],\n [\"totalRefereeDiscount\", getU64Encoder()],\n [\"totalReferrerReward\", getU64Encoder()],\n [\"currentEpochReferrerReward\", getU64Encoder()],\n ]);\n}\n\nexport function getUserFeesDecoder(): FixedSizeDecoder<UserFees> {\n return getStructDecoder([\n [\"totalFeePaid\", getU64Decoder()],\n [\"totalFeeRebate\", getU64Decoder()],\n [\"totalTokenDiscount\", getU64Decoder()],\n [\"totalRefereeDiscount\", getU64Decoder()],\n [\"totalReferrerReward\", getU64Decoder()],\n [\"currentEpochReferrerReward\", getU64Decoder()],\n ]);\n}\n\nexport function getUserFeesCodec(): FixedSizeCodec<UserFeesArgs, UserFees> {\n return combineCodec(getUserFeesEncoder(), getUserFeesDecoder());\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI16Decoder,\n getI16Encoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU128Decoder,\n getU128Encoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getAssetTierDecoder,\n getAssetTierEncoder,\n getHistoricalIndexDataDecoder,\n getHistoricalIndexDataEncoder,\n getHistoricalOracleDataDecoder,\n getHistoricalOracleDataEncoder,\n getInsuranceFundDecoder,\n getInsuranceFundEncoder,\n getMarketStatusDecoder,\n getMarketStatusEncoder,\n getOracleSourceDecoder,\n getOracleSourceEncoder,\n getPoolBalanceDecoder,\n getPoolBalanceEncoder,\n type AssetTier,\n type AssetTierArgs,\n type HistoricalIndexData,\n type HistoricalIndexDataArgs,\n type HistoricalOracleData,\n type HistoricalOracleDataArgs,\n type InsuranceFund,\n type InsuranceFundArgs,\n type MarketStatus,\n type MarketStatusArgs,\n type OracleSource,\n type OracleSourceArgs,\n type PoolBalance,\n type PoolBalanceArgs,\n} from \"../types\";\n\nexport const SPOT_MARKET_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 100, 177, 8, 107, 168, 65, 65, 39,\n]);\n\nexport function getSpotMarketDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(SPOT_MARKET_DISCRIMINATOR);\n}\n\nexport type SpotMarket = {\n discriminator: ReadonlyUint8Array;\n /** The address of the spot market. It is a pda of the market index */\n pubkey: Address;\n /** The oracle used to price the markets deposits/borrows */\n oracle: Address;\n /** The token mint of the market */\n mint: Address;\n /**\n * The vault used to store the market's deposits\n * The amount in the vault should be equal to or greater than deposits - borrows\n */\n vault: Address;\n /** The encoded display name for the market e.g. SOL */\n name: ReadonlyUint8Array;\n historicalOracleData: HistoricalOracleData;\n historicalIndexData: HistoricalIndexData;\n /**\n * Revenue the protocol has collected in this markets token\n * e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool\n */\n revenuePool: PoolBalance;\n /**\n * The fees collected from swaps between this market and the quote market\n * Is settled to the quote markets revenue pool\n */\n spotFeePool: PoolBalance;\n /**\n * Details on the insurance fund covering bankruptcies in this markets token\n * Covers bankruptcies for borrows with this markets token and perps settling in this markets token\n */\n insuranceFund: InsuranceFund;\n /**\n * The total spot fees collected for this market\n * precision: QUOTE_PRECISION\n */\n totalSpotFee: bigint;\n /**\n * The sum of the scaled balances for deposits across users and pool balances\n * To convert to the deposit token amount, multiply by the cumulative deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n depositBalance: bigint;\n /**\n * The sum of the scaled balances for borrows across users and pool balances\n * To convert to the borrow token amount, multiply by the cumulative borrow interest\n * precision: SPOT_BALANCE_PRECISION\n */\n borrowBalance: bigint;\n /**\n * The cumulative interest earned by depositors\n * Used to calculate the deposit token amount from the deposit balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeDepositInterest: bigint;\n /**\n * The cumulative interest earned by borrowers\n * Used to calculate the borrow token amount from the borrow balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeBorrowInterest: bigint;\n /**\n * The total socialized loss from borrows, in the mint's token\n * precision: token mint precision\n */\n totalSocialLoss: bigint;\n /**\n * The total socialized loss from borrows, in the quote market's token\n * preicision: QUOTE_PRECISION\n */\n totalQuoteSocialLoss: bigint;\n /**\n * no withdraw limits/guards when deposits below this threshold\n * precision: token mint precision\n */\n withdrawGuardThreshold: bigint;\n /**\n * The max amount of token deposits in this market\n * 0 if there is no limit\n * precision: token mint precision\n */\n maxTokenDeposits: bigint;\n /**\n * 24hr average of deposit token amount\n * precision: token mint precision\n */\n depositTokenTwap: bigint;\n /**\n * 24hr average of borrow token amount\n * precision: token mint precision\n */\n borrowTokenTwap: bigint;\n /**\n * 24hr average of utilization\n * which is borrow amount over token amount\n * precision: SPOT_UTILIZATION_PRECISION\n */\n utilizationTwap: bigint;\n /** Last time the cumulative deposit and borrow interest was updated */\n lastInterestTs: bigint;\n /** Last time the deposit/borrow/utilization averages were updated */\n lastTwapTs: bigint;\n /** The time the market is set to expire. Only set if market is in reduce only mode */\n expiryTs: bigint;\n /**\n * Spot orders must be a multiple of the step size\n * precision: token mint precision\n */\n orderStepSize: bigint;\n /**\n * Spot orders must be a multiple of the tick size\n * precision: PRICE_PRECISION\n */\n orderTickSize: bigint;\n /**\n * The minimum order size\n * precision: token mint precision\n */\n minOrderSize: bigint;\n /**\n * The maximum spot position size\n * if the limit is 0, there is no limit\n * precision: token mint precision\n */\n maxPositionSize: bigint;\n /** Every spot trade has a fill record id. This is the next id to use */\n nextFillRecordId: bigint;\n /** Every deposit has a deposit record id. This is the next id to use */\n nextDepositRecordId: bigint;\n /**\n * The initial asset weight used to calculate a deposits contribution to a users initial total collateral\n * e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialAssetWeight: number;\n /**\n * The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral\n * e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceAssetWeight: number;\n /**\n * The initial liability weight used to calculate a borrows contribution to a users initial margin requirement\n * e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialLiabilityWeight: number;\n /**\n * The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement\n * e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceLiabilityWeight: number;\n /**\n * The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions\n * precision: MARGIN_PRECISION\n */\n imfFactor: number;\n /**\n * The fee the liquidator is paid for taking over borrow/deposit\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n liquidatorFee: number;\n /**\n * The fee the insurance fund receives from liquidation\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n ifLiquidationFee: number;\n /**\n * The optimal utilization rate for this market.\n * Used to determine the markets borrow rate\n * precision: SPOT_UTILIZATION_PRECISION\n */\n optimalUtilization: number;\n /**\n * The borrow rate for this market when the market has optimal utilization\n * precision: SPOT_RATE_PRECISION\n */\n optimalBorrowRate: number;\n /**\n * The borrow rate for this market when the market has 1000 utilization\n * precision: SPOT_RATE_PRECISION\n */\n maxBorrowRate: number;\n /** The market's token mint's decimals. To from decimals to a precision, 10^decimals */\n decimals: number;\n marketIndex: number;\n /** Whether or not spot trading is enabled */\n ordersEnabled: boolean;\n oracleSource: OracleSource;\n status: MarketStatus;\n /** The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated */\n assetTier: AssetTier;\n pausedOperations: number;\n ifPausedOperations: number;\n feeAdjustment: number;\n /**\n * What fraction of max_token_deposits\n * disabled when 0, 1 => 1/10000 => .01% of max_token_deposits\n * precision: X/10000\n */\n maxTokenBorrowsFraction: number;\n /**\n * For swaps, the amount of token loaned out in the begin_swap ix\n * precision: token mint precision\n */\n flashLoanAmount: bigint;\n /**\n * For swaps, the amount in the users token account in the begin_swap ix\n * Used to calculate how much of the token left the system in end_swap ix\n * precision: token mint precision\n */\n flashLoanInitialTokenAmount: bigint;\n /**\n * The total fees received from swaps\n * precision: token mint precision\n */\n totalSwapFee: bigint;\n /**\n * When to begin scaling down the initial asset weight\n * disabled when 0\n * precision: QUOTE_PRECISION\n */\n scaleInitialAssetWeightStart: bigint;\n /**\n * The min borrow rate for this market when the market regardless of utilization\n * 1 => 1/200 => .5%\n * precision: X/200\n */\n minBorrowRate: number;\n /**\n * fuel multiplier for spot deposits\n * precision: 10\n */\n fuelBoostDeposits: number;\n /**\n * fuel multiplier for spot borrows\n * precision: 10\n */\n fuelBoostBorrows: number;\n /**\n * fuel multiplier for spot taker\n * precision: 10\n */\n fuelBoostTaker: number;\n /**\n * fuel multiplier for spot maker\n * precision: 10\n */\n fuelBoostMaker: number;\n /**\n * fuel multiplier for spot insurance stake\n * precision: 10\n */\n fuelBoostInsurance: number;\n tokenProgramFlag: number;\n poolId: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type SpotMarketArgs = {\n /** The address of the spot market. It is a pda of the market index */\n pubkey: Address;\n /** The oracle used to price the markets deposits/borrows */\n oracle: Address;\n /** The token mint of the market */\n mint: Address;\n /**\n * The vault used to store the market's deposits\n * The amount in the vault should be equal to or greater than deposits - borrows\n */\n vault: Address;\n /** The encoded display name for the market e.g. SOL */\n name: ReadonlyUint8Array;\n historicalOracleData: HistoricalOracleDataArgs;\n historicalIndexData: HistoricalIndexDataArgs;\n /**\n * Revenue the protocol has collected in this markets token\n * e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool\n */\n revenuePool: PoolBalanceArgs;\n /**\n * The fees collected from swaps between this market and the quote market\n * Is settled to the quote markets revenue pool\n */\n spotFeePool: PoolBalanceArgs;\n /**\n * Details on the insurance fund covering bankruptcies in this markets token\n * Covers bankruptcies for borrows with this markets token and perps settling in this markets token\n */\n insuranceFund: InsuranceFundArgs;\n /**\n * The total spot fees collected for this market\n * precision: QUOTE_PRECISION\n */\n totalSpotFee: number | bigint;\n /**\n * The sum of the scaled balances for deposits across users and pool balances\n * To convert to the deposit token amount, multiply by the cumulative deposit interest\n * precision: SPOT_BALANCE_PRECISION\n */\n depositBalance: number | bigint;\n /**\n * The sum of the scaled balances for borrows across users and pool balances\n * To convert to the borrow token amount, multiply by the cumulative borrow interest\n * precision: SPOT_BALANCE_PRECISION\n */\n borrowBalance: number | bigint;\n /**\n * The cumulative interest earned by depositors\n * Used to calculate the deposit token amount from the deposit balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeDepositInterest: number | bigint;\n /**\n * The cumulative interest earned by borrowers\n * Used to calculate the borrow token amount from the borrow balance\n * precision: SPOT_CUMULATIVE_INTEREST_PRECISION\n */\n cumulativeBorrowInterest: number | bigint;\n /**\n * The total socialized loss from borrows, in the mint's token\n * precision: token mint precision\n */\n totalSocialLoss: number | bigint;\n /**\n * The total socialized loss from borrows, in the quote market's token\n * preicision: QUOTE_PRECISION\n */\n totalQuoteSocialLoss: number | bigint;\n /**\n * no withdraw limits/guards when deposits below this threshold\n * precision: token mint precision\n */\n withdrawGuardThreshold: number | bigint;\n /**\n * The max amount of token deposits in this market\n * 0 if there is no limit\n * precision: token mint precision\n */\n maxTokenDeposits: number | bigint;\n /**\n * 24hr average of deposit token amount\n * precision: token mint precision\n */\n depositTokenTwap: number | bigint;\n /**\n * 24hr average of borrow token amount\n * precision: token mint precision\n */\n borrowTokenTwap: number | bigint;\n /**\n * 24hr average of utilization\n * which is borrow amount over token amount\n * precision: SPOT_UTILIZATION_PRECISION\n */\n utilizationTwap: number | bigint;\n /** Last time the cumulative deposit and borrow interest was updated */\n lastInterestTs: number | bigint;\n /** Last time the deposit/borrow/utilization averages were updated */\n lastTwapTs: number | bigint;\n /** The time the market is set to expire. Only set if market is in reduce only mode */\n expiryTs: number | bigint;\n /**\n * Spot orders must be a multiple of the step size\n * precision: token mint precision\n */\n orderStepSize: number | bigint;\n /**\n * Spot orders must be a multiple of the tick size\n * precision: PRICE_PRECISION\n */\n orderTickSize: number | bigint;\n /**\n * The minimum order size\n * precision: token mint precision\n */\n minOrderSize: number | bigint;\n /**\n * The maximum spot position size\n * if the limit is 0, there is no limit\n * precision: token mint precision\n */\n maxPositionSize: number | bigint;\n /** Every spot trade has a fill record id. This is the next id to use */\n nextFillRecordId: number | bigint;\n /** Every deposit has a deposit record id. This is the next id to use */\n nextDepositRecordId: number | bigint;\n /**\n * The initial asset weight used to calculate a deposits contribution to a users initial total collateral\n * e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialAssetWeight: number;\n /**\n * The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral\n * e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceAssetWeight: number;\n /**\n * The initial liability weight used to calculate a borrows contribution to a users initial margin requirement\n * e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n initialLiabilityWeight: number;\n /**\n * The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement\n * e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement\n * precision: SPOT_WEIGHT_PRECISION\n */\n maintenanceLiabilityWeight: number;\n /**\n * The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions\n * precision: MARGIN_PRECISION\n */\n imfFactor: number;\n /**\n * The fee the liquidator is paid for taking over borrow/deposit\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n liquidatorFee: number;\n /**\n * The fee the insurance fund receives from liquidation\n * precision: LIQUIDATOR_FEE_PRECISION\n */\n ifLiquidationFee: number;\n /**\n * The optimal utilization rate for this market.\n * Used to determine the markets borrow rate\n * precision: SPOT_UTILIZATION_PRECISION\n */\n optimalUtilization: number;\n /**\n * The borrow rate for this market when the market has optimal utilization\n * precision: SPOT_RATE_PRECISION\n */\n optimalBorrowRate: number;\n /**\n * The borrow rate for this market when the market has 1000 utilization\n * precision: SPOT_RATE_PRECISION\n */\n maxBorrowRate: number;\n /** The market's token mint's decimals. To from decimals to a precision, 10^decimals */\n decimals: number;\n marketIndex: number;\n /** Whether or not spot trading is enabled */\n ordersEnabled: boolean;\n oracleSource: OracleSourceArgs;\n status: MarketStatusArgs;\n /** The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated */\n assetTier: AssetTierArgs;\n pausedOperations: number;\n ifPausedOperations: number;\n feeAdjustment: number;\n /**\n * What fraction of max_token_deposits\n * disabled when 0, 1 => 1/10000 => .01% of max_token_deposits\n * precision: X/10000\n */\n maxTokenBorrowsFraction: number;\n /**\n * For swaps, the amount of token loaned out in the begin_swap ix\n * precision: token mint precision\n */\n flashLoanAmount: number | bigint;\n /**\n * For swaps, the amount in the users token account in the begin_swap ix\n * Used to calculate how much of the token left the system in end_swap ix\n * precision: token mint precision\n */\n flashLoanInitialTokenAmount: number | bigint;\n /**\n * The total fees received from swaps\n * precision: token mint precision\n */\n totalSwapFee: number | bigint;\n /**\n * When to begin scaling down the initial asset weight\n * disabled when 0\n * precision: QUOTE_PRECISION\n */\n scaleInitialAssetWeightStart: number | bigint;\n /**\n * The min borrow rate for this market when the market regardless of utilization\n * 1 => 1/200 => .5%\n * precision: X/200\n */\n minBorrowRate: number;\n /**\n * fuel multiplier for spot deposits\n * precision: 10\n */\n fuelBoostDeposits: number;\n /**\n * fuel multiplier for spot borrows\n * precision: 10\n */\n fuelBoostBorrows: number;\n /**\n * fuel multiplier for spot taker\n * precision: 10\n */\n fuelBoostTaker: number;\n /**\n * fuel multiplier for spot maker\n * precision: 10\n */\n fuelBoostMaker: number;\n /**\n * fuel multiplier for spot insurance stake\n * precision: 10\n */\n fuelBoostInsurance: number;\n tokenProgramFlag: number;\n poolId: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link SpotMarketArgs} account data. */\nexport function getSpotMarketEncoder(): FixedSizeEncoder<SpotMarketArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"pubkey\", getAddressEncoder()],\n [\"oracle\", getAddressEncoder()],\n [\"mint\", getAddressEncoder()],\n [\"vault\", getAddressEncoder()],\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"historicalOracleData\", getHistoricalOracleDataEncoder()],\n [\"historicalIndexData\", getHistoricalIndexDataEncoder()],\n [\"revenuePool\", getPoolBalanceEncoder()],\n [\"spotFeePool\", getPoolBalanceEncoder()],\n [\"insuranceFund\", getInsuranceFundEncoder()],\n [\"totalSpotFee\", getU128Encoder()],\n [\"depositBalance\", getU128Encoder()],\n [\"borrowBalance\", getU128Encoder()],\n [\"cumulativeDepositInterest\", getU128Encoder()],\n [\"cumulativeBorrowInterest\", getU128Encoder()],\n [\"totalSocialLoss\", getU128Encoder()],\n [\"totalQuoteSocialLoss\", getU128Encoder()],\n [\"withdrawGuardThreshold\", getU64Encoder()],\n [\"maxTokenDeposits\", getU64Encoder()],\n [\"depositTokenTwap\", getU64Encoder()],\n [\"borrowTokenTwap\", getU64Encoder()],\n [\"utilizationTwap\", getU64Encoder()],\n [\"lastInterestTs\", getU64Encoder()],\n [\"lastTwapTs\", getU64Encoder()],\n [\"expiryTs\", getI64Encoder()],\n [\"orderStepSize\", getU64Encoder()],\n [\"orderTickSize\", getU64Encoder()],\n [\"minOrderSize\", getU64Encoder()],\n [\"maxPositionSize\", getU64Encoder()],\n [\"nextFillRecordId\", getU64Encoder()],\n [\"nextDepositRecordId\", getU64Encoder()],\n [\"initialAssetWeight\", getU32Encoder()],\n [\"maintenanceAssetWeight\", getU32Encoder()],\n [\"initialLiabilityWeight\", getU32Encoder()],\n [\"maintenanceLiabilityWeight\", getU32Encoder()],\n [\"imfFactor\", getU32Encoder()],\n [\"liquidatorFee\", getU32Encoder()],\n [\"ifLiquidationFee\", getU32Encoder()],\n [\"optimalUtilization\", getU32Encoder()],\n [\"optimalBorrowRate\", getU32Encoder()],\n [\"maxBorrowRate\", getU32Encoder()],\n [\"decimals\", getU32Encoder()],\n [\"marketIndex\", getU16Encoder()],\n [\"ordersEnabled\", getBooleanEncoder()],\n [\"oracleSource\", getOracleSourceEncoder()],\n [\"status\", getMarketStatusEncoder()],\n [\"assetTier\", getAssetTierEncoder()],\n [\"pausedOperations\", getU8Encoder()],\n [\"ifPausedOperations\", getU8Encoder()],\n [\"feeAdjustment\", getI16Encoder()],\n [\"maxTokenBorrowsFraction\", getU16Encoder()],\n [\"flashLoanAmount\", getU64Encoder()],\n [\"flashLoanInitialTokenAmount\", getU64Encoder()],\n [\"totalSwapFee\", getU64Encoder()],\n [\"scaleInitialAssetWeightStart\", getU64Encoder()],\n [\"minBorrowRate\", getU8Encoder()],\n [\"fuelBoostDeposits\", getU8Encoder()],\n [\"fuelBoostBorrows\", getU8Encoder()],\n [\"fuelBoostTaker\", getU8Encoder()],\n [\"fuelBoostMaker\", getU8Encoder()],\n [\"fuelBoostInsurance\", getU8Encoder()],\n [\"tokenProgramFlag\", getU8Encoder()],\n [\"poolId\", getU8Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 40)],\n ]),\n (value) => ({ ...value, discriminator: SPOT_MARKET_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link SpotMarket} account data. */\nexport function getSpotMarketDecoder(): FixedSizeDecoder<SpotMarket> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"pubkey\", getAddressDecoder()],\n [\"oracle\", getAddressDecoder()],\n [\"mint\", getAddressDecoder()],\n [\"vault\", getAddressDecoder()],\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"historicalOracleData\", getHistoricalOracleDataDecoder()],\n [\"historicalIndexData\", getHistoricalIndexDataDecoder()],\n [\"revenuePool\", getPoolBalanceDecoder()],\n [\"spotFeePool\", getPoolBalanceDecoder()],\n [\"insuranceFund\", getInsuranceFundDecoder()],\n [\"totalSpotFee\", getU128Decoder()],\n [\"depositBalance\", getU128Decoder()],\n [\"borrowBalance\", getU128Decoder()],\n [\"cumulativeDepositInterest\", getU128Decoder()],\n [\"cumulativeBorrowInterest\", getU128Decoder()],\n [\"totalSocialLoss\", getU128Decoder()],\n [\"totalQuoteSocialLoss\", getU128Decoder()],\n [\"withdrawGuardThreshold\", getU64Decoder()],\n [\"maxTokenDeposits\", getU64Decoder()],\n [\"depositTokenTwap\", getU64Decoder()],\n [\"borrowTokenTwap\", getU64Decoder()],\n [\"utilizationTwap\", getU64Decoder()],\n [\"lastInterestTs\", getU64Decoder()],\n [\"lastTwapTs\", getU64Decoder()],\n [\"expiryTs\", getI64Decoder()],\n [\"orderStepSize\", getU64Decoder()],\n [\"orderTickSize\", getU64Decoder()],\n [\"minOrderSize\", getU64Decoder()],\n [\"maxPositionSize\", getU64Decoder()],\n [\"nextFillRecordId\", getU64Decoder()],\n [\"nextDepositRecordId\", getU64Decoder()],\n [\"initialAssetWeight\", getU32Decoder()],\n [\"maintenanceAssetWeight\", getU32Decoder()],\n [\"initialLiabilityWeight\", getU32Decoder()],\n [\"maintenanceLiabilityWeight\", getU32Decoder()],\n [\"imfFactor\", getU32Decoder()],\n [\"liquidatorFee\", getU32Decoder()],\n [\"ifLiquidationFee\", getU32Decoder()],\n [\"optimalUtilization\", getU32Decoder()],\n [\"optimalBorrowRate\", getU32Decoder()],\n [\"maxBorrowRate\", getU32Decoder()],\n [\"decimals\", getU32Decoder()],\n [\"marketIndex\", getU16Decoder()],\n [\"ordersEnabled\", getBooleanDecoder()],\n [\"oracleSource\", getOracleSourceDecoder()],\n [\"status\", getMarketStatusDecoder()],\n [\"assetTier\", getAssetTierDecoder()],\n [\"pausedOperations\", getU8Decoder()],\n [\"ifPausedOperations\", getU8Decoder()],\n [\"feeAdjustment\", getI16Decoder()],\n [\"maxTokenBorrowsFraction\", getU16Decoder()],\n [\"flashLoanAmount\", getU64Decoder()],\n [\"flashLoanInitialTokenAmount\", getU64Decoder()],\n [\"totalSwapFee\", getU64Decoder()],\n [\"scaleInitialAssetWeightStart\", getU64Decoder()],\n [\"minBorrowRate\", getU8Decoder()],\n [\"fuelBoostDeposits\", getU8Decoder()],\n [\"fuelBoostBorrows\", getU8Decoder()],\n [\"fuelBoostTaker\", getU8Decoder()],\n [\"fuelBoostMaker\", getU8Decoder()],\n [\"fuelBoostInsurance\", getU8Decoder()],\n [\"tokenProgramFlag\", getU8Decoder()],\n [\"poolId\", getU8Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 40)],\n ]);\n}\n\n/** Gets the codec for {@link SpotMarket} account data. */\nexport function getSpotMarketCodec(): FixedSizeCodec<SpotMarketArgs, SpotMarket> {\n return combineCodec(getSpotMarketEncoder(), getSpotMarketDecoder());\n}\n\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<SpotMarket, TAddress>;\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<SpotMarket, TAddress>;\nexport function decodeSpotMarket<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<SpotMarket, TAddress> | MaybeAccount<SpotMarket, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getSpotMarketDecoder());\n}\n\nexport async function fetchSpotMarket<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<SpotMarket, TAddress>> {\n const maybeAccount = await fetchMaybeSpotMarket(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeSpotMarket<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<SpotMarket, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeSpotMarket(maybeAccount);\n}\n\nexport async function fetchAllSpotMarket(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<SpotMarket>[]> {\n const maybeAccounts = await fetchAllMaybeSpotMarket(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeSpotMarket(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<SpotMarket>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeSpotMarket(maybeAccount));\n}\n\nexport function getSpotMarketSize(): number {\n return 776;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n getMarginModeDecoder,\n getMarginModeEncoder,\n getOrderDecoder,\n getOrderEncoder,\n getPerpPositionDecoder,\n getPerpPositionEncoder,\n getSpotPositionDecoder,\n getSpotPositionEncoder,\n type MarginMode,\n type MarginModeArgs,\n type Order,\n type OrderArgs,\n type PerpPosition,\n type PerpPositionArgs,\n type SpotPosition,\n type SpotPositionArgs,\n} from \"../types\";\n\nexport const USER_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 159, 117, 95, 227, 239, 151, 58, 236,\n]);\n\nexport function getUserDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(USER_DISCRIMINATOR);\n}\n\nexport type User = {\n discriminator: ReadonlyUint8Array;\n /** The owner/authority of the account */\n authority: Address;\n /** An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw */\n delegate: Address;\n /** Encoded display name e.g. \"toly\" */\n name: ReadonlyUint8Array;\n /** The user's spot positions */\n spotPositions: Array<SpotPosition>;\n /** The user's perp positions */\n perpPositions: Array<PerpPosition>;\n /** The user's orders */\n orders: Array<Order>;\n /** The last time the user added perp lp positions */\n lastAddPerpLpSharesTs: bigint;\n /**\n * The total values of deposits the user has made\n * precision: QUOTE_PRECISION\n */\n totalDeposits: bigint;\n /**\n * The total values of withdrawals the user has made\n * precision: QUOTE_PRECISION\n */\n totalWithdraws: bigint;\n /**\n * The total socialized loss the users has incurred upon the protocol\n * precision: QUOTE_PRECISION\n */\n totalSocialLoss: bigint;\n /**\n * Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps\n * precision: QUOTE_PRECISION\n */\n settledPerpPnl: bigint;\n /**\n * Fees (taker fees, maker rebate, filler reward) for spot\n * precision: QUOTE_PRECISION\n */\n cumulativeSpotFees: bigint;\n /**\n * Cumulative funding paid/received for perps\n * precision: QUOTE_PRECISION\n */\n cumulativePerpFunding: bigint;\n /**\n * The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time\n * Defaults to zero when not being liquidated\n * precision: QUOTE_PRECISION\n */\n liquidationMarginFreed: bigint;\n /** The last slot a user was active. Used to determine if a user is idle */\n lastActiveSlot: bigint;\n /** Every user order has an order id. This is the next order id to be used */\n nextOrderId: number;\n /** Custom max initial margin ratio for the user */\n maxMarginRatio: number;\n /** The next liquidation id to be used for user */\n nextLiquidationId: number;\n /** The sub account id for this user */\n subAccountId: number;\n /** Whether the user is active, being liquidated or bankrupt */\n status: number;\n /** Whether the user has enabled margin trading */\n isMarginTradingEnabled: boolean;\n /**\n * User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows\n * Off-chain keeper bots can ignore users that are idle\n */\n idle: boolean;\n /** number of open orders */\n openOrders: number;\n /** Whether or not user has open order */\n hasOpenOrder: boolean;\n /** number of open orders with auction */\n openAuctions: number;\n /** Whether or not user has open order with auction */\n hasOpenAuction: boolean;\n marginMode: MarginMode;\n poolId: number;\n padding1: ReadonlyUint8Array;\n lastFuelBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type UserArgs = {\n /** The owner/authority of the account */\n authority: Address;\n /** An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw */\n delegate: Address;\n /** Encoded display name e.g. \"toly\" */\n name: ReadonlyUint8Array;\n /** The user's spot positions */\n spotPositions: Array<SpotPositionArgs>;\n /** The user's perp positions */\n perpPositions: Array<PerpPositionArgs>;\n /** The user's orders */\n orders: Array<OrderArgs>;\n /** The last time the user added perp lp positions */\n lastAddPerpLpSharesTs: number | bigint;\n /**\n * The total values of deposits the user has made\n * precision: QUOTE_PRECISION\n */\n totalDeposits: number | bigint;\n /**\n * The total values of withdrawals the user has made\n * precision: QUOTE_PRECISION\n */\n totalWithdraws: number | bigint;\n /**\n * The total socialized loss the users has incurred upon the protocol\n * precision: QUOTE_PRECISION\n */\n totalSocialLoss: number | bigint;\n /**\n * Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps\n * precision: QUOTE_PRECISION\n */\n settledPerpPnl: number | bigint;\n /**\n * Fees (taker fees, maker rebate, filler reward) for spot\n * precision: QUOTE_PRECISION\n */\n cumulativeSpotFees: number | bigint;\n /**\n * Cumulative funding paid/received for perps\n * precision: QUOTE_PRECISION\n */\n cumulativePerpFunding: number | bigint;\n /**\n * The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time\n * Defaults to zero when not being liquidated\n * precision: QUOTE_PRECISION\n */\n liquidationMarginFreed: number | bigint;\n /** The last slot a user was active. Used to determine if a user is idle */\n lastActiveSlot: number | bigint;\n /** Every user order has an order id. This is the next order id to be used */\n nextOrderId: number;\n /** Custom max initial margin ratio for the user */\n maxMarginRatio: number;\n /** The next liquidation id to be used for user */\n nextLiquidationId: number;\n /** The sub account id for this user */\n subAccountId: number;\n /** Whether the user is active, being liquidated or bankrupt */\n status: number;\n /** Whether the user has enabled margin trading */\n isMarginTradingEnabled: boolean;\n /**\n * User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows\n * Off-chain keeper bots can ignore users that are idle\n */\n idle: boolean;\n /** number of open orders */\n openOrders: number;\n /** Whether or not user has open order */\n hasOpenOrder: boolean;\n /** number of open orders with auction */\n openAuctions: number;\n /** Whether or not user has open order with auction */\n hasOpenAuction: boolean;\n marginMode: MarginModeArgs;\n poolId: number;\n padding1: ReadonlyUint8Array;\n lastFuelBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link UserArgs} account data. */\nexport function getUserEncoder(): FixedSizeEncoder<UserArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"authority\", getAddressEncoder()],\n [\"delegate\", getAddressEncoder()],\n [\"name\", fixEncoderSize(getBytesEncoder(), 32)],\n [\"spotPositions\", getArrayEncoder(getSpotPositionEncoder(), { size: 8 })],\n [\"perpPositions\", getArrayEncoder(getPerpPositionEncoder(), { size: 8 })],\n [\"orders\", getArrayEncoder(getOrderEncoder(), { size: 32 })],\n [\"lastAddPerpLpSharesTs\", getI64Encoder()],\n [\"totalDeposits\", getU64Encoder()],\n [\"totalWithdraws\", getU64Encoder()],\n [\"totalSocialLoss\", getU64Encoder()],\n [\"settledPerpPnl\", getI64Encoder()],\n [\"cumulativeSpotFees\", getI64Encoder()],\n [\"cumulativePerpFunding\", getI64Encoder()],\n [\"liquidationMarginFreed\", getU64Encoder()],\n [\"lastActiveSlot\", getU64Encoder()],\n [\"nextOrderId\", getU32Encoder()],\n [\"maxMarginRatio\", getU32Encoder()],\n [\"nextLiquidationId\", getU16Encoder()],\n [\"subAccountId\", getU16Encoder()],\n [\"status\", getU8Encoder()],\n [\"isMarginTradingEnabled\", getBooleanEncoder()],\n [\"idle\", getBooleanEncoder()],\n [\"openOrders\", getU8Encoder()],\n [\"hasOpenOrder\", getBooleanEncoder()],\n [\"openAuctions\", getU8Encoder()],\n [\"hasOpenAuction\", getBooleanEncoder()],\n [\"marginMode\", getMarginModeEncoder()],\n [\"poolId\", getU8Encoder()],\n [\"padding1\", fixEncoderSize(getBytesEncoder(), 3)],\n [\"lastFuelBonusUpdateTs\", getU32Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 12)],\n ]),\n (value) => ({ ...value, discriminator: USER_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link User} account data. */\nexport function getUserDecoder(): FixedSizeDecoder<User> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"authority\", getAddressDecoder()],\n [\"delegate\", getAddressDecoder()],\n [\"name\", fixDecoderSize(getBytesDecoder(), 32)],\n [\"spotPositions\", getArrayDecoder(getSpotPositionDecoder(), { size: 8 })],\n [\"perpPositions\", getArrayDecoder(getPerpPositionDecoder(), { size: 8 })],\n [\"orders\", getArrayDecoder(getOrderDecoder(), { size: 32 })],\n [\"lastAddPerpLpSharesTs\", getI64Decoder()],\n [\"totalDeposits\", getU64Decoder()],\n [\"totalWithdraws\", getU64Decoder()],\n [\"totalSocialLoss\", getU64Decoder()],\n [\"settledPerpPnl\", getI64Decoder()],\n [\"cumulativeSpotFees\", getI64Decoder()],\n [\"cumulativePerpFunding\", getI64Decoder()],\n [\"liquidationMarginFreed\", getU64Decoder()],\n [\"lastActiveSlot\", getU64Decoder()],\n [\"nextOrderId\", getU32Decoder()],\n [\"maxMarginRatio\", getU32Decoder()],\n [\"nextLiquidationId\", getU16Decoder()],\n [\"subAccountId\", getU16Decoder()],\n [\"status\", getU8Decoder()],\n [\"isMarginTradingEnabled\", getBooleanDecoder()],\n [\"idle\", getBooleanDecoder()],\n [\"openOrders\", getU8Decoder()],\n [\"hasOpenOrder\", getBooleanDecoder()],\n [\"openAuctions\", getU8Decoder()],\n [\"hasOpenAuction\", getBooleanDecoder()],\n [\"marginMode\", getMarginModeDecoder()],\n [\"poolId\", getU8Decoder()],\n [\"padding1\", fixDecoderSize(getBytesDecoder(), 3)],\n [\"lastFuelBonusUpdateTs\", getU32Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 12)],\n ]);\n}\n\n/** Gets the codec for {@link User} account data. */\nexport function getUserCodec(): FixedSizeCodec<UserArgs, User> {\n return combineCodec(getUserEncoder(), getUserDecoder());\n}\n\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<User, TAddress>;\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<User, TAddress>;\nexport function decodeUser<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<User, TAddress> | MaybeAccount<User, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getUserDecoder());\n}\n\nexport async function fetchUser<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<User, TAddress>> {\n const maybeAccount = await fetchMaybeUser(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeUser<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<User, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeUser(maybeAccount);\n}\n\nexport async function fetchAllUser(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<User>[]> {\n const maybeAccounts = await fetchAllMaybeUser(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeUser(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<User>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeUser(maybeAccount));\n}\n\nexport function getUserSize(): number {\n return 4376;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { getUserFeesDecoder, getUserFeesEncoder, type UserFees, type UserFeesArgs } from \"../types\";\n\nexport const USER_STATS_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 176, 223, 136, 27, 122, 79, 32, 227,\n]);\n\nexport function getUserStatsDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(USER_STATS_DISCRIMINATOR);\n}\n\nexport type UserStats = {\n discriminator: ReadonlyUint8Array;\n /** The authority for all of a users sub accounts */\n authority: Address;\n /** The address that referred this user */\n referrer: Address;\n /** Stats on the fees paid by the user */\n fees: UserFees;\n /**\n * The timestamp of the next epoch\n * Epoch is used to limit referrer rewards earned in single epoch\n */\n nextEpochTs: bigint;\n /**\n * Rolling 30day maker volume for user\n * precision: QUOTE_PRECISION\n */\n makerVolume30d: bigint;\n /**\n * Rolling 30day taker volume for user\n * precision: QUOTE_PRECISION\n */\n takerVolume30d: bigint;\n /**\n * Rolling 30day filler volume for user\n * precision: QUOTE_PRECISION\n */\n fillerVolume30d: bigint;\n /** last time the maker volume was updated */\n lastMakerVolume30dTs: bigint;\n /** last time the taker volume was updated */\n lastTakerVolume30dTs: bigint;\n /** last time the filler volume was updated */\n lastFillerVolume30dTs: bigint;\n /** The amount of tokens staked in the quote spot markets if */\n ifStakedQuoteAssetAmount: bigint;\n /** The current number of sub accounts */\n numberOfSubAccounts: number;\n /**\n * The number of sub accounts created. Can be greater than the number of sub accounts if user\n * has deleted sub accounts\n */\n numberOfSubAccountsCreated: number;\n /**\n * Flags for referrer status:\n * First bit (LSB): 1 if user is a referrer, 0 otherwise\n * Second bit: 1 if user was referred, 0 otherwise\n */\n referrerStatus: number;\n disableUpdatePerpBidAskTwap: number;\n pausedOperations: number;\n /** whether the user has a FuelOverflow account */\n fuelOverflowStatus: number;\n /** accumulated fuel for token amounts of insurance */\n fuelInsurance: number;\n /** accumulated fuel for notional of deposits */\n fuelDeposits: number;\n /** accumulate fuel bonus for notional of borrows */\n fuelBorrows: number;\n /** accumulated fuel for perp open interest */\n fuelPositions: number;\n /** accumulate fuel bonus for taker volume */\n fuelTaker: number;\n /** accumulate fuel bonus for maker volume */\n fuelMaker: number;\n /** The amount of tokens staked in the governance spot markets if */\n ifStakedGovTokenAmount: bigint;\n /** last unix ts user stats data was used to update if fuel (u32 to save space) */\n lastFuelIfBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\nexport type UserStatsArgs = {\n /** The authority for all of a users sub accounts */\n authority: Address;\n /** The address that referred this user */\n referrer: Address;\n /** Stats on the fees paid by the user */\n fees: UserFeesArgs;\n /**\n * The timestamp of the next epoch\n * Epoch is used to limit referrer rewards earned in single epoch\n */\n nextEpochTs: number | bigint;\n /**\n * Rolling 30day maker volume for user\n * precision: QUOTE_PRECISION\n */\n makerVolume30d: number | bigint;\n /**\n * Rolling 30day taker volume for user\n * precision: QUOTE_PRECISION\n */\n takerVolume30d: number | bigint;\n /**\n * Rolling 30day filler volume for user\n * precision: QUOTE_PRECISION\n */\n fillerVolume30d: number | bigint;\n /** last time the maker volume was updated */\n lastMakerVolume30dTs: number | bigint;\n /** last time the taker volume was updated */\n lastTakerVolume30dTs: number | bigint;\n /** last time the filler volume was updated */\n lastFillerVolume30dTs: number | bigint;\n /** The amount of tokens staked in the quote spot markets if */\n ifStakedQuoteAssetAmount: number | bigint;\n /** The current number of sub accounts */\n numberOfSubAccounts: number;\n /**\n * The number of sub accounts created. Can be greater than the number of sub accounts if user\n * has deleted sub accounts\n */\n numberOfSubAccountsCreated: number;\n /**\n * Flags for referrer status:\n * First bit (LSB): 1 if user is a referrer, 0 otherwise\n * Second bit: 1 if user was referred, 0 otherwise\n */\n referrerStatus: number;\n disableUpdatePerpBidAskTwap: number;\n pausedOperations: number;\n /** whether the user has a FuelOverflow account */\n fuelOverflowStatus: number;\n /** accumulated fuel for token amounts of insurance */\n fuelInsurance: number;\n /** accumulated fuel for notional of deposits */\n fuelDeposits: number;\n /** accumulate fuel bonus for notional of borrows */\n fuelBorrows: number;\n /** accumulated fuel for perp open interest */\n fuelPositions: number;\n /** accumulate fuel bonus for taker volume */\n fuelTaker: number;\n /** accumulate fuel bonus for maker volume */\n fuelMaker: number;\n /** The amount of tokens staked in the governance spot markets if */\n ifStakedGovTokenAmount: number | bigint;\n /** last unix ts user stats data was used to update if fuel (u32 to save space) */\n lastFuelIfBonusUpdateTs: number;\n padding: ReadonlyUint8Array;\n};\n\n/** Gets the encoder for {@link UserStatsArgs} account data. */\nexport function getUserStatsEncoder(): FixedSizeEncoder<UserStatsArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"authority\", getAddressEncoder()],\n [\"referrer\", getAddressEncoder()],\n [\"fees\", getUserFeesEncoder()],\n [\"nextEpochTs\", getI64Encoder()],\n [\"makerVolume30d\", getU64Encoder()],\n [\"takerVolume30d\", getU64Encoder()],\n [\"fillerVolume30d\", getU64Encoder()],\n [\"lastMakerVolume30dTs\", getI64Encoder()],\n [\"lastTakerVolume30dTs\", getI64Encoder()],\n [\"lastFillerVolume30dTs\", getI64Encoder()],\n [\"ifStakedQuoteAssetAmount\", getU64Encoder()],\n [\"numberOfSubAccounts\", getU16Encoder()],\n [\"numberOfSubAccountsCreated\", getU16Encoder()],\n [\"referrerStatus\", getU8Encoder()],\n [\"disableUpdatePerpBidAskTwap\", getU8Encoder()],\n [\"pausedOperations\", getU8Encoder()],\n [\"fuelOverflowStatus\", getU8Encoder()],\n [\"fuelInsurance\", getU32Encoder()],\n [\"fuelDeposits\", getU32Encoder()],\n [\"fuelBorrows\", getU32Encoder()],\n [\"fuelPositions\", getU32Encoder()],\n [\"fuelTaker\", getU32Encoder()],\n [\"fuelMaker\", getU32Encoder()],\n [\"ifStakedGovTokenAmount\", getU64Encoder()],\n [\"lastFuelIfBonusUpdateTs\", getU32Encoder()],\n [\"padding\", fixEncoderSize(getBytesEncoder(), 12)],\n ]),\n (value) => ({ ...value, discriminator: USER_STATS_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link UserStats} account data. */\nexport function getUserStatsDecoder(): FixedSizeDecoder<UserStats> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"authority\", getAddressDecoder()],\n [\"referrer\", getAddressDecoder()],\n [\"fees\", getUserFeesDecoder()],\n [\"nextEpochTs\", getI64Decoder()],\n [\"makerVolume30d\", getU64Decoder()],\n [\"takerVolume30d\", getU64Decoder()],\n [\"fillerVolume30d\", getU64Decoder()],\n [\"lastMakerVolume30dTs\", getI64Decoder()],\n [\"lastTakerVolume30dTs\", getI64Decoder()],\n [\"lastFillerVolume30dTs\", getI64Decoder()],\n [\"ifStakedQuoteAssetAmount\", getU64Decoder()],\n [\"numberOfSubAccounts\", getU16Decoder()],\n [\"numberOfSubAccountsCreated\", getU16Decoder()],\n [\"referrerStatus\", getU8Decoder()],\n [\"disableUpdatePerpBidAskTwap\", getU8Decoder()],\n [\"pausedOperations\", getU8Decoder()],\n [\"fuelOverflowStatus\", getU8Decoder()],\n [\"fuelInsurance\", getU32Decoder()],\n [\"fuelDeposits\", getU32Decoder()],\n [\"fuelBorrows\", getU32Decoder()],\n [\"fuelPositions\", getU32Decoder()],\n [\"fuelTaker\", getU32Decoder()],\n [\"fuelMaker\", getU32Decoder()],\n [\"ifStakedGovTokenAmount\", getU64Decoder()],\n [\"lastFuelIfBonusUpdateTs\", getU32Decoder()],\n [\"padding\", fixDecoderSize(getBytesDecoder(), 12)],\n ]);\n}\n\n/** Gets the codec for {@link UserStats} account data. */\nexport function getUserStatsCodec(): FixedSizeCodec<UserStatsArgs, UserStats> {\n return combineCodec(getUserStatsEncoder(), getUserStatsDecoder());\n}\n\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<UserStats, TAddress>;\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<UserStats, TAddress>;\nexport function decodeUserStats<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<UserStats, TAddress> | MaybeAccount<UserStats, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getUserStatsDecoder());\n}\n\nexport async function fetchUserStats<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<UserStats, TAddress>> {\n const maybeAccount = await fetchMaybeUserStats(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeUserStats<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<UserStats, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeUserStats(maybeAccount);\n}\n\nexport async function fetchAllUserStats(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<UserStats>[]> {\n const maybeAccounts = await fetchAllMaybeUserStats(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeUserStats(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<UserStats>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeUserStats(maybeAccount));\n}\n\nexport function getUserStatsSize(): number {\n return 240;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getSpotMarketCodec,\n getUserCodec,\n getUserStatsCodec,\n type SpotMarket,\n type SpotMarketArgs,\n type User,\n type UserArgs,\n type UserStats,\n type UserStatsArgs,\n} from \"../accounts\";\nimport {\n getUpdateSpotMarketCumulativeInterestInstruction,\n parseUpdateSpotMarketCumulativeInterestInstruction,\n type ParsedUpdateSpotMarketCumulativeInterestInstruction,\n type UpdateSpotMarketCumulativeInterestInput,\n} from \"../instructions\";\n\nexport const DRIFT_PROGRAM_ADDRESS =\n \"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\" as Address<\"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\">;\n\nexport enum DriftAccount {\n SpotMarket,\n User,\n UserStats,\n}\n\nexport function identifyDriftAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): DriftAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([100, 177, 8, 107, 168, 65, 65, 39])\n ),\n 0\n )\n ) {\n return DriftAccount.SpotMarket;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([159, 117, 95, 227, 239, 151, 58, 236])\n ),\n 0\n )\n ) {\n return DriftAccount.User;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([176, 223, 136, 27, 122, 79, 32, 227])\n ),\n 0\n )\n ) {\n return DriftAccount.UserStats;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"drift\",\n });\n}\n\nexport enum DriftInstruction {\n UpdateSpotMarketCumulativeInterest,\n}\n\nexport function identifyDriftInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): DriftInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([39, 166, 139, 243, 158, 165, 155, 225])\n ),\n 0\n )\n ) {\n return DriftInstruction.UpdateSpotMarketCumulativeInterest;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"drift\",\n });\n}\n\nexport type ParsedDriftInstruction<\n TProgram extends string = \"dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH\",\n> = {\n instructionType: DriftInstruction.UpdateSpotMarketCumulativeInterest;\n} & ParsedUpdateSpotMarketCumulativeInterestInstruction<TProgram>;\n\nexport function parseDriftInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedDriftInstruction<TProgram> {\n const instructionType = identifyDriftInstruction(instruction);\n switch (instructionType) {\n case DriftInstruction.UpdateSpotMarketCumulativeInterest: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: DriftInstruction.UpdateSpotMarketCumulativeInterest,\n ...parseUpdateSpotMarketCumulativeInterestInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"drift\",\n });\n }\n}\n\nexport type DriftPlugin = {\n accounts: DriftPluginAccounts;\n instructions: DriftPluginInstructions;\n identifyAccount: typeof identifyDriftAccount;\n identifyInstruction: typeof identifyDriftInstruction;\n parseInstruction: typeof parseDriftInstruction;\n};\n\nexport type DriftPluginAccounts = {\n spotMarket: ReturnType<typeof getSpotMarketCodec> &\n SelfFetchFunctions<SpotMarketArgs, SpotMarket>;\n user: ReturnType<typeof getUserCodec> & SelfFetchFunctions<UserArgs, User>;\n userStats: ReturnType<typeof getUserStatsCodec> & SelfFetchFunctions<UserStatsArgs, UserStats>;\n};\n\nexport type DriftPluginInstructions = {\n updateSpotMarketCumulativeInterest: (\n input: UpdateSpotMarketCumulativeInterestInput\n ) => ReturnType<typeof getUpdateSpotMarketCumulativeInterestInstruction> &\n SelfPlanAndSendFunctions;\n};\n\nexport type DriftPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function driftProgram() {\n return <T extends DriftPluginRequirements>(\n client: T\n ): ExtendedClient<T, { drift: DriftPlugin }> => {\n return extendClient(client, {\n drift: <DriftPlugin>{\n accounts: {\n spotMarket: addSelfFetchFunctions(client, getSpotMarketCodec()),\n user: addSelfFetchFunctions(client, getUserCodec()),\n userStats: addSelfFetchFunctions(client, getUserStatsCodec()),\n },\n instructions: {\n updateSpotMarketCumulativeInterest: (input) =>\n addSelfPlanAndSendFunctions(\n client,\n getUpdateSpotMarketCumulativeInterestInstruction(input)\n ),\n },\n identifyAccount: identifyDriftAccount,\n identifyInstruction: identifyDriftInstruction,\n parseInstruction: parseDriftInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { DRIFT_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR: ReadonlyUint8Array =\n new Uint8Array([39, 166, 139, 243, 158, 165, 155, 225]);\n\nexport function getUpdateSpotMarketCumulativeInterestDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(\n UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR\n );\n}\n\nexport type UpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string = typeof DRIFT_PROGRAM_ADDRESS,\n TAccountState extends string | AccountMeta<string> = string,\n TAccountSpotMarket extends string | AccountMeta<string> = string,\n TAccountOracle extends string | AccountMeta<string> = string,\n TAccountSpotMarketVault extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountState extends string ? ReadonlyAccount<TAccountState> : TAccountState,\n TAccountSpotMarket extends string ? WritableAccount<TAccountSpotMarket> : TAccountSpotMarket,\n TAccountOracle extends string ? ReadonlyAccount<TAccountOracle> : TAccountOracle,\n TAccountSpotMarketVault extends string\n ? ReadonlyAccount<TAccountSpotMarketVault>\n : TAccountSpotMarketVault,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateSpotMarketCumulativeInterestInstructionData = {\n discriminator: ReadonlyUint8Array;\n};\n\nexport type UpdateSpotMarketCumulativeInterestInstructionDataArgs = {};\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataEncoder(): FixedSizeEncoder<UpdateSpotMarketCumulativeInterestInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: UPDATE_SPOT_MARKET_CUMULATIVE_INTEREST_DISCRIMINATOR })\n );\n}\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataDecoder(): FixedSizeDecoder<UpdateSpotMarketCumulativeInterestInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getUpdateSpotMarketCumulativeInterestInstructionDataCodec(): FixedSizeCodec<\n UpdateSpotMarketCumulativeInterestInstructionDataArgs,\n UpdateSpotMarketCumulativeInterestInstructionData\n> {\n return combineCodec(\n getUpdateSpotMarketCumulativeInterestInstructionDataEncoder(),\n getUpdateSpotMarketCumulativeInterestInstructionDataDecoder()\n );\n}\n\nexport type UpdateSpotMarketCumulativeInterestInput<\n TAccountState extends InstructionAccountInput = InstructionAccountInput,\n TAccountSpotMarket extends InstructionAccountInput = InstructionAccountInput,\n TAccountOracle extends InstructionAccountInput = InstructionAccountInput,\n TAccountSpotMarketVault extends InstructionAccountInput = InstructionAccountInput,\n> = {\n state: TAccountState;\n spotMarket: TAccountSpotMarket;\n oracle: TAccountOracle;\n spotMarketVault: TAccountSpotMarketVault;\n};\n\nexport function getUpdateSpotMarketCumulativeInterestInstruction<\n TAccountState extends InstructionAccountInput,\n TAccountSpotMarket extends InstructionAccountInput,\n TAccountOracle extends InstructionAccountInput,\n TAccountSpotMarketVault extends InstructionAccountInput,\n TProgramAddress extends Address = typeof DRIFT_PROGRAM_ADDRESS,\n>(\n input: UpdateSpotMarketCumulativeInterestInput<\n TAccountState,\n TAccountSpotMarket,\n TAccountOracle,\n TAccountSpotMarketVault\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateSpotMarketCumulativeInterestInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountState, InstructionAccountInputAddress<TAccountState>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarket,\n InstructionAccountInputAddress<TAccountSpotMarket>\n >,\n ResolvedInstructionAccountMeta<TAccountOracle, InstructionAccountInputAddress<TAccountOracle>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarketVault,\n InstructionAccountInputAddress<TAccountSpotMarketVault>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? DRIFT_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n state: { value: input.state ?? null, isSigner: false, isWritable: false },\n spotMarket: { value: input.spotMarket ?? null, isSigner: false, isWritable: true },\n oracle: { value: input.oracle ?? null, isSigner: false, isWritable: false },\n spotMarketVault: { value: input.spotMarketVault ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"state\", accounts.state),\n getAccountMeta(\"spotMarket\", accounts.spotMarket),\n getAccountMeta(\"oracle\", accounts.oracle),\n getAccountMeta(\"spotMarketVault\", accounts.spotMarketVault),\n ],\n data: getUpdateSpotMarketCumulativeInterestInstructionDataEncoder().encode({}),\n programAddress,\n } as UpdateSpotMarketCumulativeInterestInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountState, InstructionAccountInputAddress<TAccountState>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarket,\n InstructionAccountInputAddress<TAccountSpotMarket>\n >,\n ResolvedInstructionAccountMeta<TAccountOracle, InstructionAccountInputAddress<TAccountOracle>>,\n ResolvedInstructionAccountMeta<\n TAccountSpotMarketVault,\n InstructionAccountInputAddress<TAccountSpotMarketVault>\n >\n >);\n}\n\nexport type ParsedUpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string = typeof DRIFT_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n state: TAccountMetas[0];\n spotMarket: TAccountMetas[1];\n oracle: TAccountMetas[2];\n spotMarketVault: TAccountMetas[3];\n };\n data: UpdateSpotMarketCumulativeInterestInstructionData;\n};\n\nexport function parseUpdateSpotMarketCumulativeInterestInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedUpdateSpotMarketCumulativeInterestInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 4) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 4,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n state: getNextAccount(),\n spotMarket: getNextAccount(),\n oracle: getNextAccount(),\n spotMarketVault: getNextAccount(),\n },\n data: getUpdateSpotMarketCumulativeInterestInstructionDataDecoder().decode(instruction.data),\n };\n}\n","import type { ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type { DriftSpotMarket, DriftUser, DriftUserStats } from \"./types\";\n\nimport {\n getSpotMarketDecoder,\n getUserDecoder,\n getUserStatsDecoder,\n SPOT_MARKET_DISCRIMINATOR,\n USER_DISCRIMINATOR,\n USER_STATS_DISCRIMINATOR,\n} from \"~/generated/drift\";\n\nexport { DRIFT_PROGRAM_ADDRESS, SpotBalanceType } from \"~/generated/drift\";\n\n/**\n * Decodes a Drift `SpotMarket` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftSpotMarket(data: ReadonlyUint8Array): DriftSpotMarket {\n return decodeAccountData(\n data,\n SPOT_MARKET_DISCRIMINATOR,\n getSpotMarketDecoder(),\n \"Drift SpotMarket\"\n );\n}\n\n/**\n * Decodes a Drift `User` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftUser(data: ReadonlyUint8Array): DriftUser {\n return decodeAccountData(data, USER_DISCRIMINATOR, getUserDecoder(), \"Drift User\");\n}\n\n/**\n * Decodes a Drift `UserStats` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeDriftUserStats(data: ReadonlyUint8Array): DriftUserStats {\n return decodeAccountData(\n data,\n USER_STATS_DISCRIMINATOR,\n getUserStatsDecoder(),\n \"Drift UserStats\"\n );\n}\n","import {\n getAddressEncoder,\n getProgramDerivedAddress,\n getU16Encoder,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nimport { DRIFT_PROGRAM_ADDRESS } from \"~/generated/drift\";\n\n/** Drift `State` PDA. */\nexport function deriveDriftState(): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"drift_state\"],\n });\n}\n\n/** Drift signer PDA (owns spot market vaults). */\nexport function deriveDriftSigner(): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"drift_signer\"],\n });\n}\n\n/** Drift `User` PDA of `authority` sub-account `subAccountId`. */\nexport function deriveDriftUser(\n authority: Address,\n subAccountId: number\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"user\", getAddressEncoder().encode(authority), getU16Encoder().encode(subAccountId)],\n });\n}\n\n/** Drift `UserStats` PDA of `authority`. */\nexport function deriveDriftUserStats(authority: Address): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"user_stats\", getAddressEncoder().encode(authority)],\n });\n}\n\n/** Drift `SpotMarket` PDA of `marketIndex`. */\nexport function deriveDriftSpotMarket(marketIndex: number): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"spot_market\", getU16Encoder().encode(marketIndex)],\n });\n}\n\n/** Drift spot market token vault PDA of `marketIndex`. */\nexport function deriveDriftSpotMarketVault(marketIndex: number): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: DRIFT_PROGRAM_ADDRESS,\n seeds: [\"spot_market_vault\", getU16Encoder().encode(marketIndex)],\n });\n}\n\n/** State, signer, spot market and spot market vault of `marketIndex`. */\nexport async function getAllDerivedDriftAccounts(marketIndex: number) {\n const [[driftState], [driftSigner], [driftSpotMarket], [driftSpotMarketVault]] =\n await Promise.all([\n deriveDriftState(),\n deriveDriftSigner(),\n deriveDriftSpotMarket(marketIndex),\n deriveDriftSpotMarketVault(marketIndex),\n ]);\n return { driftState, driftSigner, driftSpotMarket, driftSpotMarketVault };\n}\n","import type { Instruction } from \"@solana/kit\";\n\nimport { deriveDriftSpotMarketVault, deriveDriftState } from \"./pda\";\nimport type { DriftSpotMarket } from \"./types\";\n\nimport { getUpdateSpotMarketCumulativeInterestInstruction } from \"~/generated/drift\";\n\n/**\n * Accrues a Drift spot market's cumulative interest (permissionless crank) so token amounts derived\n * from its scaled balances are current.\n */\nexport async function makeUpdateSpotMarketCumulativeInterestIx(\n spotMarket: DriftSpotMarket\n): Promise<Instruction> {\n const [[state], [spotMarketVault]] = await Promise.all([\n deriveDriftState(),\n deriveDriftSpotMarketVault(spotMarket.marketIndex),\n ]);\n return getUpdateSpotMarketCumulativeInterestInstruction({\n state,\n spotMarket: spotMarket.pubkey,\n oracle: spotMarket.oracle,\n spotMarketVault,\n });\n}\n","import { BigNumber } from \"bignumber.js\";\n\nimport type { DriftSpotMarket } from \"./types\";\n\nimport { SpotBalanceType } from \"~/generated/drift\";\n\nexport const PERCENTAGE_PRECISION = 1_000_000n;\nexport const SPOT_MARKET_RATE_PRECISION = 1_000_000n;\nexport const SPOT_MARKET_UTILIZATION_PRECISION = 1_000_000n;\n/** Seconds */\nexport const ONE_YEAR = 31_536_000n;\n\n/**\n * Token amount (native units) of a scaled spot balance, including accrued interest. Borrows round up.\n */\nexport function getDriftTokenAmount(\n balanceAmount: bigint,\n spotMarket: DriftSpotMarket,\n balanceType: SpotBalanceType\n): bigint {\n const precisionDecrease = 10n ** BigInt(19 - spotMarket.decimals);\n\n if (balanceType === SpotBalanceType.Deposit) {\n return (balanceAmount * spotMarket.cumulativeDepositInterest) / precisionDecrease;\n }\n const scaled = balanceAmount * spotMarket.cumulativeBorrowInterest;\n const quotient = scaled / precisionDecrease;\n return scaled % precisionDecrease > 0n ? quotient + 1n : quotient;\n}\n\n/**\n * Tokens (native units) per scaled deposit balance unit of `spotMarket`: {@link getDriftTokenAmount}\n * for a deposit, without rounding.\n */\nexport function getDriftCTokenMultiplier(spotMarket: DriftSpotMarket): BigNumber {\n return new BigNumber(spotMarket.cumulativeDepositInterest.toString()).dividedBy(\n new BigNumber(10).pow(19 - spotMarket.decimals)\n );\n}\n\n/**\n * Utilization (SPOT_MARKET_UTILIZATION_PRECISION) = borrows / deposits. A positive `delta` adds to\n * deposits, a negative one to borrows (native units).\n */\nexport function calculateDriftUtilization(bank: DriftSpotMarket, delta: bigint = 0n): bigint {\n let deposits = getDriftTokenAmount(bank.depositBalance, bank, SpotBalanceType.Deposit);\n let borrows = getDriftTokenAmount(bank.borrowBalance, bank, SpotBalanceType.Borrow);\n\n if (delta > 0n) {\n deposits += delta;\n } else if (delta < 0n) {\n borrows -= delta;\n }\n\n if (borrows === 0n && deposits === 0n) {\n return 0n;\n }\n if (deposits === 0n) {\n return SPOT_MARKET_UTILIZATION_PRECISION;\n }\n return (borrows * SPOT_MARKET_UTILIZATION_PRECISION) / deposits;\n}\n\n/**\n * Borrow rate (SPOT_MARKET_RATE_PRECISION) at the market's utilization: linear up to the optimal\n * utilization, then Drift's weighted segments up to the max rate, floored at the min rate.\n */\nexport function calculateDriftInterestRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n const utilization = currentUtilization ?? calculateDriftUtilization(bank, delta);\n\n const optimalUtil = BigInt(bank.optimalUtilization);\n const optimalRate = BigInt(bank.optimalBorrowRate);\n const maxRate = BigInt(bank.maxBorrowRate);\n const minRate = BigInt(bank.minBorrowRate) * (PERCENTAGE_PRECISION / 200n);\n\n const segments: [bigint, bigint][] = [\n [850_000n, 50n],\n [900_000n, 100n],\n [950_000n, 150n],\n [990_000n, 200n],\n [995_000n, 250n],\n [SPOT_MARKET_UTILIZATION_PRECISION, 250n],\n ];\n\n let rate: bigint;\n if (utilization <= optimalUtil) {\n const slope = (optimalRate * SPOT_MARKET_UTILIZATION_PRECISION) / optimalUtil;\n rate = (utilization * slope) / SPOT_MARKET_UTILIZATION_PRECISION;\n } else {\n const totalExtraRate = maxRate - optimalRate;\n rate = optimalRate;\n let prevUtil = optimalUtil;\n\n for (const [breakpoint, weight] of segments) {\n const segmentEnd =\n breakpoint > SPOT_MARKET_UTILIZATION_PRECISION\n ? SPOT_MARKET_UTILIZATION_PRECISION\n : breakpoint;\n const segmentRateTotal = (totalExtraRate * weight) / 1000n;\n\n if (utilization <= segmentEnd) {\n rate += (segmentRateTotal * (utilization - prevUtil)) / (segmentEnd - prevUtil);\n break;\n }\n rate += segmentRateTotal;\n prevUtil = segmentEnd;\n }\n }\n\n return rate > minRate ? rate : minRate;\n}\n\n/** Borrow APR, SPOT_MARKET_RATE_PRECISION. */\nexport function calculateDriftBorrowRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return calculateDriftInterestRate(bank, delta, currentUtilization);\n}\n\n/** Deposit APR, SPOT_MARKET_RATE_PRECISION: borrow rate × utilization × (1 − insurance fund factor). */\nexport function calculateDriftDepositRate(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n const utilization = currentUtilization ?? calculateDriftUtilization(bank, delta);\n const borrowRate = calculateDriftBorrowRate(bank, delta, utilization);\n return (\n (borrowRate * (PERCENTAGE_PRECISION - BigInt(bank.insuranceFund.totalFactor)) * utilization) /\n SPOT_MARKET_UTILIZATION_PRECISION /\n PERCENTAGE_PRECISION\n );\n}\n\n// e^r − 1 by an 8-term Taylor series; rate in SPOT_MARKET_RATE_PRECISION, result in PERCENTAGE_PRECISION.\nfunction continuousApy(rate: bigint): bigint {\n if (rate === 0n) {\n return 0n;\n }\n const precision = 10n ** 18n;\n const r = (rate * precision) / SPOT_MARKET_RATE_PRECISION;\n let term = r;\n let sum = precision + r;\n for (let n = 2n; n <= 8n; n++) {\n term = (term * r) / precision / n;\n sum += term;\n }\n return ((sum - precision) * PERCENTAGE_PRECISION) / precision;\n}\n\n/** Lending APY (continuous compounding), PERCENTAGE_PRECISION. */\nexport function calculateDriftLendingAPY(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return continuousApy(calculateDriftDepositRate(bank, delta, currentUtilization));\n}\n\n/** Lending APR, PERCENTAGE_PRECISION. */\nexport function calculateDriftLendingAPR(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return (\n (calculateDriftDepositRate(bank, delta, currentUtilization) * PERCENTAGE_PRECISION) /\n SPOT_MARKET_RATE_PRECISION\n );\n}\n\n/** Borrow APY (continuous compounding), PERCENTAGE_PRECISION. */\nexport function calculateDriftBorrowAPY(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return continuousApy(calculateDriftBorrowRate(bank, delta, currentUtilization));\n}\n\n/** Borrow APR, PERCENTAGE_PRECISION. */\nexport function calculateDriftBorrowAPR(\n bank: DriftSpotMarket,\n delta: bigint = 0n,\n currentUtilization: bigint | null = null\n): bigint {\n return (\n (calculateDriftBorrowRate(bank, delta, currentUtilization) * PERCENTAGE_PRECISION) /\n SPOT_MARKET_RATE_PRECISION\n );\n}\n\nexport interface DriftInterestRateCurvePoint {\n /** Percent (0–100) */\n utilization: number;\n /** Percent */\n borrowAPY: number;\n /** Percent */\n supplyAPY: number;\n}\n\n// 2 slots/s over a 365-day year, matching the Kamino curves.\nconst SLOTS_PER_YEAR = 63_072_000;\n\n/**\n * Borrow and supply APY curve of a Drift spot market at 0–100% utilization (101 points), compounded\n * per slot like the Kamino curves.\n */\nexport function generateDriftReserveCurve(\n spotMarket: DriftSpotMarket\n): DriftInterestRateCurvePoint[] {\n const toApy = (apr: number) =>\n apr === 0 ? 0 : Math.pow(1 + apr / SLOTS_PER_YEAR, SLOTS_PER_YEAR) - 1;\n return Array.from({ length: 101 }, (_, i) => {\n const utilization = BigInt(Math.floor((i / 100) * Number(SPOT_MARKET_UTILIZATION_PRECISION)));\n const borrowApr =\n Number(calculateDriftBorrowRate(spotMarket, 0n, utilization)) /\n Number(SPOT_MARKET_RATE_PRECISION);\n const supplyApr =\n Number(calculateDriftDepositRate(spotMarket, 0n, utilization)) /\n Number(SPOT_MARKET_RATE_PRECISION);\n return {\n utilization: i,\n borrowAPY: toApy(borrowApr) * 100,\n supplyAPY: toApy(supplyApr) * 100,\n };\n });\n}\n","import { address, type Address, type GetMultipleAccountsApi, type Rpc } from \"@solana/kit\";\n\nimport { deriveDriftSpotMarket } from \"./pda\";\nimport type { DriftRewards, DriftSpotMarket, DriftUser } from \"./types\";\n\nimport { fetchAllMaybeSpotMarket } from \"~/generated/drift\";\n\nconst USDC_MINT = address(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\");\n\n/** Returns `spotMarkets` plus any market in `marketIndexes` not among them, fetched. */\nasync function withMissingMarkets(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n marketIndexes: Iterable<number>\n): Promise<Map<number, DriftSpotMarket>> {\n const markets = new Map(spotMarkets.map((market) => [market.marketIndex, market]));\n const missing = [...new Set(marketIndexes)].filter((index) => !markets.has(index));\n const addresses = await Promise.all(\n missing.map(async (index) => (await deriveDriftSpotMarket(index))[0])\n );\n for (const account of addresses.length ? await fetchAllMaybeSpotMarket(rpc, addresses) : []) {\n if (account.exists) {\n markets.set(account.data.marketIndex, account.data);\n } else {\n console.error(\"Missing Drift spot market account\", account.address);\n }\n }\n return markets;\n}\n\n/**\n * Drift rewards of each bank. Rewards are credited as extra spot positions on the bank's Drift user:\n * positions are `[USDC, token, ...rewards]` (`[USDC, ...rewards]` for a USDC bank). Reward markets\n * not in `spotMarkets` are fetched.\n * @returns rewards keyed by bank address\n */\nexport async function getDriftRewards(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n userStates: { bankAddress: Address; marketMint: Address; driftUser: DriftUser }[]\n): Promise<Map<Address, DriftRewards[]>> {\n const rewardsByBank = userStates.map((userState) => ({\n userState,\n rewards: userState.driftUser.spotPositions\n .slice(userState.marketMint === USDC_MINT ? 1 : 2)\n .filter((position) => position.marketIndex !== 0),\n }));\n\n const markets = await withMissingMarkets(\n rpc,\n spotMarkets,\n rewardsByBank.flatMap(({ rewards }) => rewards.map((reward) => reward.marketIndex))\n );\n\n return new Map(\n await Promise.all(\n rewardsByBank.map(async ({ userState, rewards }) => {\n const driftRewards: DriftRewards[] = [];\n for (const reward of rewards) {\n const market = markets.get(reward.marketIndex);\n if (!market) {\n console.error(\"Missing Drift spot market\", reward.marketIndex);\n continue;\n }\n driftRewards.push({\n oracle: market.oracle,\n marketIndex: reward.marketIndex,\n spotMarket: (await deriveDriftSpotMarket(reward.marketIndex))[0],\n mint: market.mint,\n spotPosition: reward,\n });\n }\n return [userState.bankAddress, driftRewards] as const;\n })\n )\n );\n}\n\n/** `spotMarkets` plus every market any of `driftUsers` has a position in, fetched if missing. */\nexport async function getAllRequiredMarkets(\n rpc: Rpc<GetMultipleAccountsApi>,\n spotMarkets: DriftSpotMarket[],\n driftUsers: DriftUser[]\n): Promise<DriftSpotMarket[]> {\n const markets = await withMissingMarkets(\n rpc,\n spotMarkets,\n driftUsers.flatMap((user) => user.spotPositions.map((position) => position.marketIndex))\n );\n return [...markets.values()];\n}\n","import { address } from \"@solana/kit\";\n\nimport type {\n DriftRewards,\n DriftRewardsJSON,\n DriftSpotMarket,\n DriftSpotMarketJSON,\n DriftSpotPosition,\n DriftSpotPositionJSON,\n DriftUser,\n DriftUserJSON,\n DriftUserStats,\n DriftUserStatsJSON,\n} from \"./types\";\n\nfunction spotPositionToDto(position: DriftSpotPosition): DriftSpotPositionJSON {\n return {\n scaledBalance: position.scaledBalance.toString(),\n openBids: position.openBids.toString(),\n openAsks: position.openAsks.toString(),\n cumulativeDeposits: position.cumulativeDeposits.toString(),\n marketIndex: position.marketIndex,\n balanceType: position.balanceType,\n openOrders: position.openOrders,\n padding: [...position.padding],\n };\n}\n\nfunction dtoToSpotPosition(dto: DriftSpotPositionJSON): DriftSpotPosition {\n return {\n scaledBalance: BigInt(dto.scaledBalance),\n openBids: BigInt(dto.openBids),\n openAsks: BigInt(dto.openAsks),\n cumulativeDeposits: BigInt(dto.cumulativeDeposits),\n marketIndex: dto.marketIndex,\n balanceType: dto.balanceType,\n openOrders: dto.openOrders,\n padding: Uint8Array.from(dto.padding),\n };\n}\n\n/** Serializes a Drift spot market (or a decoded `SpotMarket`) to its JSON DTO. */\nexport function driftSpotMarketRawToDto(market: DriftSpotMarket): DriftSpotMarketJSON {\n return {\n pubkey: market.pubkey,\n oracle: market.oracle,\n mint: market.mint,\n decimals: market.decimals,\n marketIndex: market.marketIndex,\n cumulativeDepositInterest: market.cumulativeDepositInterest.toString(),\n cumulativeBorrowInterest: market.cumulativeBorrowInterest.toString(),\n depositBalance: market.depositBalance.toString(),\n borrowBalance: market.borrowBalance.toString(),\n optimalUtilization: market.optimalUtilization,\n optimalBorrowRate: market.optimalBorrowRate,\n maxBorrowRate: market.maxBorrowRate,\n minBorrowRate: market.minBorrowRate,\n insuranceFund: { totalFactor: market.insuranceFund.totalFactor },\n poolId: market.poolId,\n };\n}\n\n/**\n * Parses a Drift spot market DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftSpotMarketRaw(dto: DriftSpotMarketJSON): DriftSpotMarket {\n return {\n pubkey: address(dto.pubkey),\n oracle: address(dto.oracle),\n mint: address(dto.mint),\n decimals: dto.decimals,\n marketIndex: dto.marketIndex,\n cumulativeDepositInterest: BigInt(dto.cumulativeDepositInterest),\n cumulativeBorrowInterest: BigInt(dto.cumulativeBorrowInterest),\n depositBalance: BigInt(dto.depositBalance),\n borrowBalance: BigInt(dto.borrowBalance),\n optimalUtilization: dto.optimalUtilization,\n optimalBorrowRate: dto.optimalBorrowRate,\n maxBorrowRate: dto.maxBorrowRate,\n minBorrowRate: dto.minBorrowRate,\n insuranceFund: { totalFactor: dto.insuranceFund.totalFactor },\n poolId: dto.poolId,\n };\n}\n\n/** Serializes a Drift user (or a decoded `User`) to its JSON DTO. */\nexport function driftUserRawToDto(user: DriftUser): DriftUserJSON {\n return {\n authority: user.authority,\n spotPositions: user.spotPositions.map(spotPositionToDto),\n };\n}\n\n/**\n * Parses a Drift user DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftUserRaw(dto: DriftUserJSON): DriftUser {\n return {\n authority: address(dto.authority),\n spotPositions: dto.spotPositions.map(dtoToSpotPosition),\n };\n}\n\n/** Serializes Drift rewards to their JSON DTO. */\nexport function driftRewardsRawToDto(rewards: DriftRewards): DriftRewardsJSON {\n return {\n oracle: rewards.oracle,\n marketIndex: rewards.marketIndex,\n spotMarket: rewards.spotMarket,\n mint: rewards.mint,\n spotPosition: spotPositionToDto(rewards.spotPosition),\n };\n}\n\n/**\n * Parses a Drift rewards DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftRewardsRaw(dto: DriftRewardsJSON): DriftRewards {\n return {\n oracle: address(dto.oracle),\n marketIndex: dto.marketIndex,\n spotMarket: address(dto.spotMarket),\n mint: address(dto.mint),\n spotPosition: dtoToSpotPosition(dto.spotPosition),\n };\n}\n\n/** Serializes Drift user stats (or a decoded `UserStats`) to their JSON DTO. */\nexport function driftUserStatsRawToDto(stats: DriftUserStats): DriftUserStatsJSON {\n return {\n authority: stats.authority,\n referrer: stats.referrer,\n fees: {\n totalFeePaid: stats.fees.totalFeePaid.toString(),\n totalFeeRebate: stats.fees.totalFeeRebate.toString(),\n totalTokenDiscount: stats.fees.totalTokenDiscount.toString(),\n totalRefereeDiscount: stats.fees.totalRefereeDiscount.toString(),\n totalReferrerReward: stats.fees.totalReferrerReward.toString(),\n currentEpochReferrerReward: stats.fees.currentEpochReferrerReward.toString(),\n },\n nextEpochTs: stats.nextEpochTs.toString(),\n makerVolume30d: stats.makerVolume30d.toString(),\n takerVolume30d: stats.takerVolume30d.toString(),\n fillerVolume30d: stats.fillerVolume30d.toString(),\n lastMakerVolume30dTs: stats.lastMakerVolume30dTs.toString(),\n lastTakerVolume30dTs: stats.lastTakerVolume30dTs.toString(),\n lastFillerVolume30dTs: stats.lastFillerVolume30dTs.toString(),\n ifStakedQuoteAssetAmount: stats.ifStakedQuoteAssetAmount.toString(),\n numberOfSubAccounts: stats.numberOfSubAccounts,\n numberOfSubAccountsCreated: stats.numberOfSubAccountsCreated,\n referrerStatus: stats.referrerStatus,\n disableUpdatePerpBidAskTwap: stats.disableUpdatePerpBidAskTwap,\n pausedOperations: stats.pausedOperations,\n fuelOverflowStatus: stats.fuelOverflowStatus,\n fuelInsurance: stats.fuelInsurance,\n fuelDeposits: stats.fuelDeposits,\n fuelBorrows: stats.fuelBorrows,\n fuelPositions: stats.fuelPositions,\n fuelTaker: stats.fuelTaker,\n fuelMaker: stats.fuelMaker,\n ifStakedGovTokenAmount: stats.ifStakedGovTokenAmount.toString(),\n lastFuelIfBonusUpdateTs: stats.lastFuelIfBonusUpdateTs,\n padding: [...stats.padding],\n };\n}\n\n/**\n * Parses a Drift user stats DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToDriftUserStatsRaw(dto: DriftUserStatsJSON): DriftUserStats {\n return {\n authority: address(dto.authority),\n referrer: address(dto.referrer),\n fees: {\n totalFeePaid: BigInt(dto.fees.totalFeePaid),\n totalFeeRebate: BigInt(dto.fees.totalFeeRebate),\n totalTokenDiscount: BigInt(dto.fees.totalTokenDiscount),\n totalRefereeDiscount: BigInt(dto.fees.totalRefereeDiscount),\n totalReferrerReward: BigInt(dto.fees.totalReferrerReward),\n currentEpochReferrerReward: BigInt(dto.fees.currentEpochReferrerReward),\n },\n nextEpochTs: BigInt(dto.nextEpochTs),\n makerVolume30d: BigInt(dto.makerVolume30d),\n takerVolume30d: BigInt(dto.takerVolume30d),\n fillerVolume30d: BigInt(dto.fillerVolume30d),\n lastMakerVolume30dTs: BigInt(dto.lastMakerVolume30dTs),\n lastTakerVolume30dTs: BigInt(dto.lastTakerVolume30dTs),\n lastFillerVolume30dTs: BigInt(dto.lastFillerVolume30dTs),\n ifStakedQuoteAssetAmount: BigInt(dto.ifStakedQuoteAssetAmount),\n numberOfSubAccounts: dto.numberOfSubAccounts,\n numberOfSubAccountsCreated: dto.numberOfSubAccountsCreated,\n referrerStatus: dto.referrerStatus,\n disableUpdatePerpBidAskTwap: dto.disableUpdatePerpBidAskTwap,\n pausedOperations: dto.pausedOperations,\n fuelOverflowStatus: dto.fuelOverflowStatus,\n fuelInsurance: dto.fuelInsurance,\n fuelDeposits: dto.fuelDeposits,\n fuelBorrows: dto.fuelBorrows,\n fuelPositions: dto.fuelPositions,\n fuelTaker: dto.fuelTaker,\n fuelMaker: dto.fuelMaker,\n ifStakedGovTokenAmount: BigInt(dto.ifStakedGovTokenAmount),\n lastFuelIfBonusUpdateTs: dto.lastFuelIfBonusUpdateTs,\n padding: Uint8Array.from(dto.padding),\n };\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\n\nimport { decodeDriftSpotMarket, decodeDriftUser } from \"./accounts\";\nimport { getAllRequiredMarkets, getDriftRewards } from \"./rewards\";\nimport { driftRewardsRawToDto, driftSpotMarketRawToDto, driftUserRawToDto } from \"./serialize\";\nimport type { DriftBankInput, DriftStates, DriftStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link DriftStates}, keyed by bank address. Reward markets not among the\n * banks' markets are fetched too. Banks with a default venue address or a missing spot market or\n * user are left out.\n * @throws if a fetched account isn't the Drift account it should be\n */\nexport async function fetchDriftStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: DriftBankInput[]\n): Promise<Record<string, DriftStates>> {\n const validBanks = banks.filter(\n (bank) => bank.spotMarket !== DEFAULT_ADDRESS && bank.user !== DEFAULT_ADDRESS\n );\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.flatMap((bank) => [bank.spotMarket, bank.user])\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const [spotMarket, user] = accounts.slice(2 * i, 2 * i + 2);\n return spotMarket && user\n ? [\n {\n bankAddress: bank.bankAddress,\n spotMarketState: decodeDriftSpotMarket(spotMarket.data),\n userState: decodeDriftUser(user.data),\n },\n ]\n : [];\n });\n\n const markets = await getAllRequiredMarkets(\n rpc,\n decoded.map(({ spotMarketState }) => spotMarketState),\n decoded.map(({ userState }) => userState)\n );\n const rewards = await getDriftRewards(\n rpc,\n markets,\n decoded.map(({ bankAddress, spotMarketState, userState }) => ({\n bankAddress,\n marketMint: spotMarketState.mint,\n driftUser: userState,\n }))\n );\n\n return Object.fromEntries(\n decoded.map(({ bankAddress, spotMarketState, userState }) => [\n bankAddress,\n { spotMarketState, userState, userRewards: rewards.get(bankAddress) ?? [] },\n ])\n );\n}\n\n/**\n * {@link fetchDriftStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchDriftStates}\n */\nexport async function fetchDriftStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: DriftBankInput[]\n): Promise<Record<string, DriftStatesJSON>> {\n const states = await fetchDriftStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, { spotMarketState, userState, userRewards }]) => [\n bank,\n {\n spotMarketState: driftSpotMarketRawToDto(spotMarketState),\n userState: driftUserRawToDto(userState),\n userRewards: userRewards.map(driftRewardsRawToDto),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LENDING_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 135, 199, 82, 16, 249, 131, 182, 241,\n]);\n\nexport function getLendingDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LENDING_DISCRIMINATOR);\n}\n\nexport type Lending = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n fTokenMint: Address;\n lendingId: number;\n /** @dev number of decimals for the fToken, same as ASSET */\n decimals: number;\n /** @dev To read PDA of rewards rate model to get_rate instruction */\n rewardsRateModel: Address;\n /** @dev exchange price for the underlying asset in the liquidity protocol (without rewards) */\n liquidityExchangePrice: bigint;\n /** @dev exchange price between fToken and the underlying asset (with rewards) */\n tokenExchangePrice: bigint;\n /** @dev timestamp when exchange prices were updated the last time */\n lastUpdateTimestamp: bigint;\n tokenReservesLiquidity: Address;\n supplyPositionOnLiquidity: Address;\n bump: number;\n};\n\nexport type LendingArgs = {\n mint: Address;\n fTokenMint: Address;\n lendingId: number;\n /** @dev number of decimals for the fToken, same as ASSET */\n decimals: number;\n /** @dev To read PDA of rewards rate model to get_rate instruction */\n rewardsRateModel: Address;\n /** @dev exchange price for the underlying asset in the liquidity protocol (without rewards) */\n liquidityExchangePrice: number | bigint;\n /** @dev exchange price between fToken and the underlying asset (with rewards) */\n tokenExchangePrice: number | bigint;\n /** @dev timestamp when exchange prices were updated the last time */\n lastUpdateTimestamp: number | bigint;\n tokenReservesLiquidity: Address;\n supplyPositionOnLiquidity: Address;\n bump: number;\n};\n\n/** Gets the encoder for {@link LendingArgs} account data. */\nexport function getLendingEncoder(): FixedSizeEncoder<LendingArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"fTokenMint\", getAddressEncoder()],\n [\"lendingId\", getU16Encoder()],\n [\"decimals\", getU8Encoder()],\n [\"rewardsRateModel\", getAddressEncoder()],\n [\"liquidityExchangePrice\", getU64Encoder()],\n [\"tokenExchangePrice\", getU64Encoder()],\n [\"lastUpdateTimestamp\", getU64Encoder()],\n [\"tokenReservesLiquidity\", getAddressEncoder()],\n [\"supplyPositionOnLiquidity\", getAddressEncoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: LENDING_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link Lending} account data. */\nexport function getLendingDecoder(): FixedSizeDecoder<Lending> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"fTokenMint\", getAddressDecoder()],\n [\"lendingId\", getU16Decoder()],\n [\"decimals\", getU8Decoder()],\n [\"rewardsRateModel\", getAddressDecoder()],\n [\"liquidityExchangePrice\", getU64Decoder()],\n [\"tokenExchangePrice\", getU64Decoder()],\n [\"lastUpdateTimestamp\", getU64Decoder()],\n [\"tokenReservesLiquidity\", getAddressDecoder()],\n [\"supplyPositionOnLiquidity\", getAddressDecoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link Lending} account data. */\nexport function getLendingCodec(): FixedSizeCodec<LendingArgs, Lending> {\n return combineCodec(getLendingEncoder(), getLendingDecoder());\n}\n\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<Lending, TAddress>;\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<Lending, TAddress>;\nexport function decodeLending<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<Lending, TAddress> | MaybeAccount<Lending, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getLendingDecoder());\n}\n\nexport async function fetchLending<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<Lending, TAddress>> {\n const maybeAccount = await fetchMaybeLending(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLending<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<Lending, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLending(maybeAccount);\n}\n\nexport async function fetchAllLending(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<Lending>[]> {\n const maybeAccounts = await fetchAllMaybeLending(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLending(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<Lending>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLending(maybeAccount));\n}\n\nexport function getLendingSize(): number {\n return 196;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 166, 72, 71, 131, 172, 74, 166, 181,\n]);\n\nexport function getLendingRewardsRateModelDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR);\n}\n\nexport type LendingRewardsRateModel = {\n discriminator: ReadonlyUint8Array;\n /** @dev mint address */\n mint: Address;\n /**\n * @dev tvl below which rewards rate is 0. If current TVL is below this value, triggering `update_rate()` on the fToken\n * might bring the total TVL above this cut-off.\n */\n startTvl: bigint;\n /** @dev for how long current rewards should run */\n duration: bigint;\n /** @dev when current rewards got started */\n startTime: bigint;\n /** @dev current annualized reward based on input params (duration, rewardAmount) */\n yearlyReward: bigint;\n /** @dev Duration for the next rewards phase */\n nextDuration: bigint;\n /** @dev Amount of rewards for the next phase */\n nextRewardAmount: bigint;\n bump: number;\n};\n\nexport type LendingRewardsRateModelArgs = {\n /** @dev mint address */\n mint: Address;\n /**\n * @dev tvl below which rewards rate is 0. If current TVL is below this value, triggering `update_rate()` on the fToken\n * might bring the total TVL above this cut-off.\n */\n startTvl: number | bigint;\n /** @dev for how long current rewards should run */\n duration: number | bigint;\n /** @dev when current rewards got started */\n startTime: number | bigint;\n /** @dev current annualized reward based on input params (duration, rewardAmount) */\n yearlyReward: number | bigint;\n /** @dev Duration for the next rewards phase */\n nextDuration: number | bigint;\n /** @dev Amount of rewards for the next phase */\n nextRewardAmount: number | bigint;\n bump: number;\n};\n\n/** Gets the encoder for {@link LendingRewardsRateModelArgs} account data. */\nexport function getLendingRewardsRateModelEncoder(): FixedSizeEncoder<LendingRewardsRateModelArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"startTvl\", getU64Encoder()],\n [\"duration\", getU64Encoder()],\n [\"startTime\", getU64Encoder()],\n [\"yearlyReward\", getU64Encoder()],\n [\"nextDuration\", getU64Encoder()],\n [\"nextRewardAmount\", getU64Encoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link LendingRewardsRateModel} account data. */\nexport function getLendingRewardsRateModelDecoder(): FixedSizeDecoder<LendingRewardsRateModel> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"startTvl\", getU64Decoder()],\n [\"duration\", getU64Decoder()],\n [\"startTime\", getU64Decoder()],\n [\"yearlyReward\", getU64Decoder()],\n [\"nextDuration\", getU64Decoder()],\n [\"nextRewardAmount\", getU64Decoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link LendingRewardsRateModel} account data. */\nexport function getLendingRewardsRateModelCodec(): FixedSizeCodec<\n LendingRewardsRateModelArgs,\n LendingRewardsRateModel\n> {\n return combineCodec(getLendingRewardsRateModelEncoder(), getLendingRewardsRateModelDecoder());\n}\n\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<LendingRewardsRateModel, TAddress>;\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<LendingRewardsRateModel, TAddress>;\nexport function decodeLendingRewardsRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<LendingRewardsRateModel, TAddress> | MaybeAccount<LendingRewardsRateModel, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getLendingRewardsRateModelDecoder()\n );\n}\n\nexport async function fetchLendingRewardsRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<LendingRewardsRateModel, TAddress>> {\n const maybeAccount = await fetchMaybeLendingRewardsRateModel(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLendingRewardsRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<LendingRewardsRateModel, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLendingRewardsRateModel(maybeAccount);\n}\n\nexport async function fetchAllLendingRewardsRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<LendingRewardsRateModel>[]> {\n const maybeAccounts = await fetchAllMaybeLendingRewardsRateModel(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLendingRewardsRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<LendingRewardsRateModel>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLendingRewardsRateModel(maybeAccount));\n}\n\nexport function getLendingRewardsRateModelSize(): number {\n return 89;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type FTokenMintSeeds = {\n mint: Address;\n};\n\nexport async function findFTokenMintPda(\n seeds: FTokenMintSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([102, 95, 116, 111, 107, 101, 110, 95, 109, 105, 110, 116])\n ),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type LendingSeeds = {\n mint: Address;\n fTokenMint: Address;\n};\n\nexport async function findLendingPda(\n seeds: LendingSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([108, 101, 110, 100, 105, 110, 103])),\n getAddressEncoder().encode(seeds.mint),\n getAddressEncoder().encode(seeds.fTokenMint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport async function findLendingAdminPda(\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([108, 101, 110, 100, 105, 110, 103, 95, 97, 100, 109, 105, 110])\n ),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getLendingCodec,\n getLendingRewardsRateModelCodec,\n type Lending,\n type LendingArgs,\n type LendingRewardsRateModel,\n type LendingRewardsRateModelArgs,\n} from \"../accounts\";\nimport {\n getUpdateRateInstruction,\n parseUpdateRateInstruction,\n type ParsedUpdateRateInstruction,\n type UpdateRateInput,\n} from \"../instructions\";\nimport { findFTokenMintPda, findLendingAdminPda, findLendingPda } from \"../pdas\";\n\nexport const LENDING_PROGRAM_ADDRESS =\n \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\" as Address<\"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\">;\n\nexport enum LendingAccount {\n Lending,\n LendingRewardsRateModel,\n}\n\nexport function identifyLendingAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LendingAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([135, 199, 82, 16, 249, 131, 182, 241])\n ),\n 0\n )\n ) {\n return LendingAccount.Lending;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([166, 72, 71, 131, 172, 74, 166, 181])\n ),\n 0\n )\n ) {\n return LendingAccount.LendingRewardsRateModel;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"lending\",\n });\n}\n\nexport enum LendingInstruction {\n UpdateRate,\n}\n\nexport function identifyLendingInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LendingInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([24, 225, 53, 189, 72, 212, 225, 178])\n ),\n 0\n )\n ) {\n return LendingInstruction.UpdateRate;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"lending\",\n });\n}\n\nexport type ParsedLendingInstruction<\n TProgram extends string = \"jup3YeL8QhtSx1e253b2FDvsMNC87fDrgQZivbrndc9\",\n> = { instructionType: LendingInstruction.UpdateRate } & ParsedUpdateRateInstruction<TProgram>;\n\nexport function parseLendingInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedLendingInstruction<TProgram> {\n const instructionType = identifyLendingInstruction(instruction);\n switch (instructionType) {\n case LendingInstruction.UpdateRate: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: LendingInstruction.UpdateRate,\n ...parseUpdateRateInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"lending\",\n });\n }\n}\n\nexport type LendingPlugin = {\n accounts: LendingPluginAccounts;\n instructions: LendingPluginInstructions;\n pdas: LendingPluginPdas;\n identifyAccount: typeof identifyLendingAccount;\n identifyInstruction: typeof identifyLendingInstruction;\n parseInstruction: typeof parseLendingInstruction;\n};\n\nexport type LendingPluginAccounts = {\n lending: ReturnType<typeof getLendingCodec> & SelfFetchFunctions<LendingArgs, Lending>;\n lendingRewardsRateModel: ReturnType<typeof getLendingRewardsRateModelCodec> &\n SelfFetchFunctions<LendingRewardsRateModelArgs, LendingRewardsRateModel>;\n};\n\nexport type LendingPluginInstructions = {\n updateRate: (\n input: UpdateRateInput\n ) => ReturnType<typeof getUpdateRateInstruction> & SelfPlanAndSendFunctions;\n};\n\nexport type LendingPluginPdas = {\n fTokenMint: typeof findFTokenMintPda;\n lending: typeof findLendingPda;\n lendingAdmin: typeof findLendingAdminPda;\n};\n\nexport type LendingPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function lendingProgram() {\n return <T extends LendingPluginRequirements>(\n client: T\n ): ExtendedClient<T, { lending: LendingPlugin }> => {\n return extendClient(client, {\n lending: <LendingPlugin>{\n accounts: {\n lending: addSelfFetchFunctions(client, getLendingCodec()),\n lendingRewardsRateModel: addSelfFetchFunctions(client, getLendingRewardsRateModelCodec()),\n },\n instructions: {\n updateRate: (input) =>\n addSelfPlanAndSendFunctions(client, getUpdateRateInstruction(input)),\n },\n pdas: {\n fTokenMint: findFTokenMintPda,\n lending: findLendingPda,\n lendingAdmin: findLendingAdminPda,\n },\n identifyAccount: identifyLendingAccount,\n identifyInstruction: identifyLendingInstruction,\n parseInstruction: parseLendingInstruction,\n },\n });\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n combineCodec,\n fixDecoderSize,\n fixEncoderSize,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS,\n SolanaError,\n transformEncoder,\n type AccountMeta,\n type Address,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type Instruction,\n type InstructionWithAccounts,\n type InstructionWithData,\n type ReadonlyAccount,\n type ReadonlyUint8Array,\n type WritableAccount,\n} from \"@solana/kit\";\nimport {\n getAccountMetaFactory,\n type InstructionAccountInput,\n type InstructionAccountInputAddress,\n type ResolvedInstructionAccount,\n type ResolvedInstructionAccountMeta,\n} from \"@solana/kit/program-client-core\";\nimport { LENDING_PROGRAM_ADDRESS } from \"../programs\";\n\nexport const UPDATE_RATE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 24, 225, 53, 189, 72, 212, 225, 178,\n]);\n\nexport function getUpdateRateDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(UPDATE_RATE_DISCRIMINATOR);\n}\n\nexport type UpdateRateInstruction<\n TProgram extends string = typeof LENDING_PROGRAM_ADDRESS,\n TAccountLending extends string | AccountMeta<string> = string,\n TAccountMint extends string | AccountMeta<string> = string,\n TAccountFTokenMint extends string | AccountMeta<string> = string,\n TAccountSupplyTokenReservesLiquidity extends string | AccountMeta<string> = string,\n TAccountRewardsRateModel extends string | AccountMeta<string> = string,\n TRemainingAccounts extends readonly AccountMeta<string>[] = [],\n> = Instruction<TProgram> &\n InstructionWithData<ReadonlyUint8Array> &\n InstructionWithAccounts<\n [\n TAccountLending extends string ? WritableAccount<TAccountLending> : TAccountLending,\n TAccountMint extends string ? ReadonlyAccount<TAccountMint> : TAccountMint,\n TAccountFTokenMint extends string ? ReadonlyAccount<TAccountFTokenMint> : TAccountFTokenMint,\n TAccountSupplyTokenReservesLiquidity extends string\n ? ReadonlyAccount<TAccountSupplyTokenReservesLiquidity>\n : TAccountSupplyTokenReservesLiquidity,\n TAccountRewardsRateModel extends string\n ? ReadonlyAccount<TAccountRewardsRateModel>\n : TAccountRewardsRateModel,\n ...TRemainingAccounts,\n ]\n >;\n\nexport type UpdateRateInstructionData = { discriminator: ReadonlyUint8Array };\n\nexport type UpdateRateInstructionDataArgs = {};\n\nexport function getUpdateRateInstructionDataEncoder(): FixedSizeEncoder<UpdateRateInstructionDataArgs> {\n return transformEncoder(\n getStructEncoder([[\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)]]),\n (value) => ({ ...value, discriminator: UPDATE_RATE_DISCRIMINATOR })\n );\n}\n\nexport function getUpdateRateInstructionDataDecoder(): FixedSizeDecoder<UpdateRateInstructionData> {\n return getStructDecoder([[\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)]]);\n}\n\nexport function getUpdateRateInstructionDataCodec(): FixedSizeCodec<\n UpdateRateInstructionDataArgs,\n UpdateRateInstructionData\n> {\n return combineCodec(getUpdateRateInstructionDataEncoder(), getUpdateRateInstructionDataDecoder());\n}\n\nexport type UpdateRateInput<\n TAccountLending extends InstructionAccountInput = InstructionAccountInput,\n TAccountMint extends InstructionAccountInput = InstructionAccountInput,\n TAccountFTokenMint extends InstructionAccountInput = InstructionAccountInput,\n TAccountSupplyTokenReservesLiquidity extends InstructionAccountInput = InstructionAccountInput,\n TAccountRewardsRateModel extends InstructionAccountInput = InstructionAccountInput,\n> = {\n lending: TAccountLending;\n mint: TAccountMint;\n fTokenMint: TAccountFTokenMint;\n supplyTokenReservesLiquidity: TAccountSupplyTokenReservesLiquidity;\n rewardsRateModel: TAccountRewardsRateModel;\n};\n\nexport function getUpdateRateInstruction<\n TAccountLending extends InstructionAccountInput,\n TAccountMint extends InstructionAccountInput,\n TAccountFTokenMint extends InstructionAccountInput,\n TAccountSupplyTokenReservesLiquidity extends InstructionAccountInput,\n TAccountRewardsRateModel extends InstructionAccountInput,\n TProgramAddress extends Address = typeof LENDING_PROGRAM_ADDRESS,\n>(\n input: UpdateRateInput<\n TAccountLending,\n TAccountMint,\n TAccountFTokenMint,\n TAccountSupplyTokenReservesLiquidity,\n TAccountRewardsRateModel\n >,\n config?: { programAddress?: TProgramAddress }\n): UpdateRateInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<TAccountLending, InstructionAccountInputAddress<TAccountLending>>,\n ResolvedInstructionAccountMeta<TAccountMint, InstructionAccountInputAddress<TAccountMint>>,\n ResolvedInstructionAccountMeta<\n TAccountFTokenMint,\n InstructionAccountInputAddress<TAccountFTokenMint>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSupplyTokenReservesLiquidity,\n InstructionAccountInputAddress<TAccountSupplyTokenReservesLiquidity>\n >,\n ResolvedInstructionAccountMeta<\n TAccountRewardsRateModel,\n InstructionAccountInputAddress<TAccountRewardsRateModel>\n >\n> {\n // Program address.\n const programAddress = config?.programAddress ?? LENDING_PROGRAM_ADDRESS;\n\n // Account meta helper.\n const getAccountMeta = getAccountMetaFactory(programAddress, \"programId\");\n\n // Original accounts.\n const originalAccounts = {\n lending: { value: input.lending ?? null, isSigner: false, isWritable: true },\n mint: { value: input.mint ?? null, isSigner: false, isWritable: false },\n fTokenMint: { value: input.fTokenMint ?? null, isSigner: false, isWritable: false },\n supplyTokenReservesLiquidity: {\n value: input.supplyTokenReservesLiquidity ?? null,\n isSigner: false,\n isWritable: false,\n },\n rewardsRateModel: { value: input.rewardsRateModel ?? null, isSigner: false, isWritable: false },\n };\n const accounts = originalAccounts as Record<\n keyof typeof originalAccounts,\n ResolvedInstructionAccount\n >;\n\n return Object.freeze({\n accounts: [\n getAccountMeta(\"lending\", accounts.lending),\n getAccountMeta(\"mint\", accounts.mint),\n getAccountMeta(\"fTokenMint\", accounts.fTokenMint),\n getAccountMeta(\"supplyTokenReservesLiquidity\", accounts.supplyTokenReservesLiquidity),\n getAccountMeta(\"rewardsRateModel\", accounts.rewardsRateModel),\n ],\n data: getUpdateRateInstructionDataEncoder().encode({}),\n programAddress,\n } as UpdateRateInstruction<\n TProgramAddress,\n ResolvedInstructionAccountMeta<\n TAccountLending,\n InstructionAccountInputAddress<TAccountLending>\n >,\n ResolvedInstructionAccountMeta<TAccountMint, InstructionAccountInputAddress<TAccountMint>>,\n ResolvedInstructionAccountMeta<\n TAccountFTokenMint,\n InstructionAccountInputAddress<TAccountFTokenMint>\n >,\n ResolvedInstructionAccountMeta<\n TAccountSupplyTokenReservesLiquidity,\n InstructionAccountInputAddress<TAccountSupplyTokenReservesLiquidity>\n >,\n ResolvedInstructionAccountMeta<\n TAccountRewardsRateModel,\n InstructionAccountInputAddress<TAccountRewardsRateModel>\n >\n >);\n}\n\nexport type ParsedUpdateRateInstruction<\n TProgram extends string = typeof LENDING_PROGRAM_ADDRESS,\n TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],\n> = {\n programAddress: Address<TProgram>;\n accounts: {\n lending: TAccountMetas[0];\n mint: TAccountMetas[1];\n fTokenMint: TAccountMetas[2];\n supplyTokenReservesLiquidity: TAccountMetas[3];\n rewardsRateModel: TAccountMetas[4];\n };\n data: UpdateRateInstructionData;\n};\n\nexport function parseUpdateRateInstruction<\n TProgram extends string,\n TAccountMetas extends readonly AccountMeta[],\n>(\n instruction: Instruction<TProgram> &\n InstructionWithAccounts<TAccountMetas> &\n InstructionWithData<ReadonlyUint8Array>\n): ParsedUpdateRateInstruction<TProgram, TAccountMetas> {\n if (instruction.accounts.length < 5) {\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, {\n actualAccountMetas: instruction.accounts.length,\n expectedAccountMetas: 5,\n });\n }\n let accountIndex = 0;\n const getNextAccount = () => {\n const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;\n accountIndex += 1;\n return accountMeta;\n };\n return {\n programAddress: instruction.programAddress,\n accounts: {\n lending: getNextAccount(),\n mint: getNextAccount(),\n fTokenMint: getNextAccount(),\n supplyTokenReservesLiquidity: getNextAccount(),\n rewardsRateModel: getNextAccount(),\n },\n data: getUpdateRateInstructionDataDecoder().decode(instruction.data),\n };\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const RATE_MODEL_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 94, 3, 203, 219, 107, 137, 4, 162,\n]);\n\nexport function getRateModelDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(RATE_MODEL_DISCRIMINATOR);\n}\n\nexport type RateModel = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n version: number;\n rateAtZero: number;\n kink1Utilization: number;\n rateAtKink1: number;\n rateAtMax: number;\n kink2Utilization: number;\n rateAtKink2: number;\n};\n\nexport type RateModelArgs = {\n mint: Address;\n version: number;\n rateAtZero: number;\n kink1Utilization: number;\n rateAtKink1: number;\n rateAtMax: number;\n kink2Utilization: number;\n rateAtKink2: number;\n};\n\n/** Gets the encoder for {@link RateModelArgs} account data. */\nexport function getRateModelEncoder(): FixedSizeEncoder<RateModelArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"version\", getU8Encoder()],\n [\"rateAtZero\", getU16Encoder()],\n [\"kink1Utilization\", getU16Encoder()],\n [\"rateAtKink1\", getU16Encoder()],\n [\"rateAtMax\", getU16Encoder()],\n [\"kink2Utilization\", getU16Encoder()],\n [\"rateAtKink2\", getU16Encoder()],\n ]),\n (value) => ({ ...value, discriminator: RATE_MODEL_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link RateModel} account data. */\nexport function getRateModelDecoder(): FixedSizeDecoder<RateModel> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"version\", getU8Decoder()],\n [\"rateAtZero\", getU16Decoder()],\n [\"kink1Utilization\", getU16Decoder()],\n [\"rateAtKink1\", getU16Decoder()],\n [\"rateAtMax\", getU16Decoder()],\n [\"kink2Utilization\", getU16Decoder()],\n [\"rateAtKink2\", getU16Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link RateModel} account data. */\nexport function getRateModelCodec(): FixedSizeCodec<RateModelArgs, RateModel> {\n return combineCodec(getRateModelEncoder(), getRateModelDecoder());\n}\n\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<RateModel, TAddress>;\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<RateModel, TAddress>;\nexport function decodeRateModel<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<RateModel, TAddress> | MaybeAccount<RateModel, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getRateModelDecoder());\n}\n\nexport async function fetchRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<RateModel, TAddress>> {\n const maybeAccount = await fetchMaybeRateModel(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeRateModel<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<RateModel, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeRateModel(maybeAccount);\n}\n\nexport async function fetchAllRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<RateModel>[]> {\n const maybeAccounts = await fetchAllMaybeRateModel(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeRateModel(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<RateModel>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeRateModel(maybeAccount));\n}\n\nexport function getRateModelSize(): number {\n return 53;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const TOKEN_RESERVE_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 21, 18, 59, 135, 120, 20, 31, 12,\n]);\n\nexport function getTokenReserveDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(TOKEN_RESERVE_DISCRIMINATOR);\n}\n\nexport type TokenReserve = {\n discriminator: ReadonlyUint8Array;\n mint: Address;\n vault: Address;\n borrowRate: number;\n feeOnInterest: number;\n lastUtilization: number;\n lastUpdateTimestamp: bigint;\n supplyExchangePrice: bigint;\n borrowExchangePrice: bigint;\n maxUtilization: number;\n totalSupplyWithInterest: bigint;\n totalSupplyInterestFree: bigint;\n totalBorrowWithInterest: bigint;\n totalBorrowInterestFree: bigint;\n totalClaimAmount: bigint;\n interactingProtocol: Address;\n interactingTimestamp: bigint;\n interactingBalance: bigint;\n};\n\nexport type TokenReserveArgs = {\n mint: Address;\n vault: Address;\n borrowRate: number;\n feeOnInterest: number;\n lastUtilization: number;\n lastUpdateTimestamp: number | bigint;\n supplyExchangePrice: number | bigint;\n borrowExchangePrice: number | bigint;\n maxUtilization: number;\n totalSupplyWithInterest: number | bigint;\n totalSupplyInterestFree: number | bigint;\n totalBorrowWithInterest: number | bigint;\n totalBorrowInterestFree: number | bigint;\n totalClaimAmount: number | bigint;\n interactingProtocol: Address;\n interactingTimestamp: number | bigint;\n interactingBalance: number | bigint;\n};\n\n/** Gets the encoder for {@link TokenReserveArgs} account data. */\nexport function getTokenReserveEncoder(): FixedSizeEncoder<TokenReserveArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"mint\", getAddressEncoder()],\n [\"vault\", getAddressEncoder()],\n [\"borrowRate\", getU16Encoder()],\n [\"feeOnInterest\", getU16Encoder()],\n [\"lastUtilization\", getU16Encoder()],\n [\"lastUpdateTimestamp\", getU64Encoder()],\n [\"supplyExchangePrice\", getU64Encoder()],\n [\"borrowExchangePrice\", getU64Encoder()],\n [\"maxUtilization\", getU16Encoder()],\n [\"totalSupplyWithInterest\", getU64Encoder()],\n [\"totalSupplyInterestFree\", getU64Encoder()],\n [\"totalBorrowWithInterest\", getU64Encoder()],\n [\"totalBorrowInterestFree\", getU64Encoder()],\n [\"totalClaimAmount\", getU64Encoder()],\n [\"interactingProtocol\", getAddressEncoder()],\n [\"interactingTimestamp\", getU64Encoder()],\n [\"interactingBalance\", getU64Encoder()],\n ]),\n (value) => ({ ...value, discriminator: TOKEN_RESERVE_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link TokenReserve} account data. */\nexport function getTokenReserveDecoder(): FixedSizeDecoder<TokenReserve> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"mint\", getAddressDecoder()],\n [\"vault\", getAddressDecoder()],\n [\"borrowRate\", getU16Decoder()],\n [\"feeOnInterest\", getU16Decoder()],\n [\"lastUtilization\", getU16Decoder()],\n [\"lastUpdateTimestamp\", getU64Decoder()],\n [\"supplyExchangePrice\", getU64Decoder()],\n [\"borrowExchangePrice\", getU64Decoder()],\n [\"maxUtilization\", getU16Decoder()],\n [\"totalSupplyWithInterest\", getU64Decoder()],\n [\"totalSupplyInterestFree\", getU64Decoder()],\n [\"totalBorrowWithInterest\", getU64Decoder()],\n [\"totalBorrowInterestFree\", getU64Decoder()],\n [\"totalClaimAmount\", getU64Decoder()],\n [\"interactingProtocol\", getAddressDecoder()],\n [\"interactingTimestamp\", getU64Decoder()],\n [\"interactingBalance\", getU64Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link TokenReserve} account data. */\nexport function getTokenReserveCodec(): FixedSizeCodec<TokenReserveArgs, TokenReserve> {\n return combineCodec(getTokenReserveEncoder(), getTokenReserveDecoder());\n}\n\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<TokenReserve, TAddress>;\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<TokenReserve, TAddress>;\nexport function decodeTokenReserve<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<TokenReserve, TAddress> | MaybeAccount<TokenReserve, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getTokenReserveDecoder());\n}\n\nexport async function fetchTokenReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<TokenReserve, TAddress>> {\n const maybeAccount = await fetchMaybeTokenReserve(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeTokenReserve<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<TokenReserve, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeTokenReserve(maybeAccount);\n}\n\nexport async function fetchAllTokenReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<TokenReserve>[]> {\n const maybeAccounts = await fetchAllMaybeTokenReserve(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeTokenReserve(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<TokenReserve>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeTokenReserve(maybeAccount));\n}\n\nexport function getTokenReserveSize(): number {\n return 192;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport async function findLiquidityPda(\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([108, 105, 113, 117, 105, 100, 105, 116, 121])),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type RateModelSeeds = {\n mint: Address;\n};\n\nexport async function findRateModelPda(\n seeds: RateModelSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([114, 97, 116, 101, 95, 109, 111, 100, 101, 108])),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type TokenReserveSeeds = {\n mint: Address;\n};\n\nexport async function findTokenReservePda(\n seeds: TokenReserveSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([114, 101, 115, 101, 114, 118, 101])),\n getAddressEncoder().encode(seeds.mint),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type UserSupplyPositionSeeds = {\n supplyMint: Address;\n protocol: Address;\n};\n\nexport async function findUserSupplyPositionPda(\n seeds: UserSupplyPositionSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([\n 117, 115, 101, 114, 95, 115, 117, 112, 112, 108, 121, 95, 112, 111, 115, 105, 116, 105,\n 111, 110,\n ])\n ),\n getAddressEncoder().encode(seeds.supplyMint),\n getAddressEncoder().encode(seeds.protocol),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport { addSelfFetchFunctions, type SelfFetchFunctions } from \"@solana/kit/program-client-core\";\nimport {\n getRateModelCodec,\n getTokenReserveCodec,\n type RateModel,\n type RateModelArgs,\n type TokenReserve,\n type TokenReserveArgs,\n} from \"../accounts\";\nimport {\n findAuthListPda,\n findClaimAccountPda,\n findLiquidityPda,\n findRateModelPda,\n findTokenReservePda,\n findUserBorrowPositionPda,\n findUserSupplyPositionPda,\n} from \"../pdas\";\n\nexport const LIQUIDITY_PROGRAM_ADDRESS =\n \"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\" as Address<\"jupeiUmn818Jg1ekPURTpr4mFo29p46vygyykFJ3wZC\">;\n\nexport enum LiquidityAccount {\n RateModel,\n TokenReserve,\n}\n\nexport function identifyLiquidityAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): LiquidityAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([94, 3, 203, 219, 107, 137, 4, 162])\n ),\n 0\n )\n ) {\n return LiquidityAccount.RateModel;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([21, 18, 59, 135, 120, 20, 31, 12])\n ),\n 0\n )\n ) {\n return LiquidityAccount.TokenReserve;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"liquidity\",\n });\n}\n\nexport type LiquidityPlugin = {\n accounts: LiquidityPluginAccounts;\n pdas: LiquidityPluginPdas;\n identifyAccount: typeof identifyLiquidityAccount;\n};\n\nexport type LiquidityPluginAccounts = {\n rateModel: ReturnType<typeof getRateModelCodec> & SelfFetchFunctions<RateModelArgs, RateModel>;\n tokenReserve: ReturnType<typeof getTokenReserveCodec> &\n SelfFetchFunctions<TokenReserveArgs, TokenReserve>;\n};\n\nexport type LiquidityPluginPdas = {\n claimAccount: typeof findClaimAccountPda;\n liquidity: typeof findLiquidityPda;\n authList: typeof findAuthListPda;\n userSupplyPosition: typeof findUserSupplyPositionPda;\n userBorrowPosition: typeof findUserBorrowPositionPda;\n rateModel: typeof findRateModelPda;\n tokenReserve: typeof findTokenReservePda;\n};\n\nexport type LiquidityPluginRequirements = ClientWithRpc<GetAccountInfoApi & GetMultipleAccountsApi>;\n\nexport function liquidityProgram() {\n return <T extends LiquidityPluginRequirements>(\n client: T\n ): ExtendedClient<T, { liquidity: LiquidityPlugin }> => {\n return extendClient(client, {\n liquidity: <LiquidityPlugin>{\n accounts: {\n rateModel: addSelfFetchFunctions(client, getRateModelCodec()),\n tokenReserve: addSelfFetchFunctions(client, getTokenReserveCodec()),\n },\n pdas: {\n claimAccount: findClaimAccountPda,\n liquidity: findLiquidityPda,\n authList: findAuthListPda,\n userSupplyPosition: findUserSupplyPositionPda,\n userBorrowPosition: findUserBorrowPositionPda,\n rateModel: findRateModelPda,\n tokenReserve: findTokenReservePda,\n },\n identifyAccount: identifyLiquidityAccount,\n },\n });\n };\n}\n","import type { Address, ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type {\n JupLendingRewardsRateModel,\n JupLendingState,\n JupRateModel,\n JupTokenReserve,\n} from \"./types\";\n\nimport {\n getLendingDecoder,\n getLendingRewardsRateModelDecoder,\n LENDING_DISCRIMINATOR,\n LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR,\n} from \"~/generated/jup-lend\";\nimport {\n getRateModelDecoder,\n getTokenReserveDecoder,\n RATE_MODEL_DISCRIMINATOR,\n TOKEN_RESERVE_DISCRIMINATOR,\n} from \"~/generated/jup-lend-liquidity\";\n\nexport { LENDING_PROGRAM_ADDRESS as JUP_LEND_PROGRAM_ADDRESS } from \"~/generated/jup-lend\";\nexport { LIQUIDITY_PROGRAM_ADDRESS as JUP_LIQUIDITY_PROGRAM_ADDRESS } from \"~/generated/jup-lend-liquidity\";\n\n/**\n * Decodes a JupLend `Lending` account at `address`.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupLendingState(address: Address, data: ReadonlyUint8Array): JupLendingState {\n const lending = decodeAccountData(\n data,\n LENDING_DISCRIMINATOR,\n getLendingDecoder(),\n \"JupLend Lending\"\n );\n return {\n pubkey: address,\n mint: lending.mint,\n fTokenMint: lending.fTokenMint,\n lendingId: lending.lendingId,\n decimals: lending.decimals,\n rewardsRateModel: lending.rewardsRateModel,\n liquidityExchangePrice: lending.liquidityExchangePrice,\n tokenExchangePrice: lending.tokenExchangePrice,\n lastUpdateTimestamp: lending.lastUpdateTimestamp,\n tokenReservesLiquidity: lending.tokenReservesLiquidity,\n supplyPositionOnLiquidity: lending.supplyPositionOnLiquidity,\n };\n}\n\n/**\n * Decodes a JupLend liquidity-layer `TokenReserve` account at `address`.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupTokenReserve(address: Address, data: ReadonlyUint8Array): JupTokenReserve {\n const reserve = decodeAccountData(\n data,\n TOKEN_RESERVE_DISCRIMINATOR,\n getTokenReserveDecoder(),\n \"JupLend TokenReserve\"\n );\n return {\n pubkey: address,\n borrowRate: reserve.borrowRate,\n feeOnInterest: reserve.feeOnInterest,\n lastUtilization: reserve.lastUtilization,\n supplyExchangePrice: reserve.supplyExchangePrice,\n borrowExchangePrice: reserve.borrowExchangePrice,\n totalSupplyWithInterest: reserve.totalSupplyWithInterest,\n totalSupplyInterestFree: reserve.totalSupplyInterestFree,\n totalBorrowWithInterest: reserve.totalBorrowWithInterest,\n totalBorrowInterestFree: reserve.totalBorrowInterestFree,\n };\n}\n\n/**\n * Decodes a JupLend liquidity-layer `RateModel` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupRateModel(data: ReadonlyUint8Array): JupRateModel {\n return decodeAccountData(\n data,\n RATE_MODEL_DISCRIMINATOR,\n getRateModelDecoder(),\n \"JupLend RateModel\"\n );\n}\n\n/**\n * Decodes a JupLend `LendingRewardsRateModel` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeJupLendingRewardsRateModel(\n data: ReadonlyUint8Array\n): JupLendingRewardsRateModel {\n return decodeAccountData(\n data,\n LENDING_REWARDS_RATE_MODEL_DISCRIMINATOR,\n getLendingRewardsRateModelDecoder(),\n \"JupLend LendingRewardsRateModel\"\n );\n}\n","import type { Instruction } from \"@solana/kit\";\n\nimport type { JupLendingState } from \"./types\";\n\nimport { getUpdateRateInstruction } from \"~/generated/jup-lend\";\n\n/**\n * Refreshes a JupLend market's exchange prices (permissionless crank). Needed before risk-sensitive\n * flows (liquidation, borrow, non-JupLend withdraw) for every involved JupLend bank in the same\n * transaction; juplend_deposit and juplend_withdraw already update the rate internally.\n */\nexport function makeUpdateJupLendRateIx(lendingState: JupLendingState): Instruction {\n return getUpdateRateInstruction({\n lending: lendingState.pubkey,\n mint: lendingState.mint,\n fTokenMint: lendingState.fTokenMint,\n supplyTokenReservesLiquidity: lendingState.tokenReservesLiquidity,\n rewardsRateModel: lendingState.rewardsRateModel,\n });\n}\n","import { BigNumber } from \"bignumber.js\";\n\nimport {\n JupLendingState,\n JupLendingRewardsRateModel,\n JupTokenReserve,\n JupRateModel,\n} from \"./types\";\n\nimport { aprToApy } from \"~/utils\";\n\n/**\n * Jup-Lend Interest Rate & Exchange Price Utilities\n *\n * Extracted from the compiled @jup-ag/lend SDK (earn/index.mjs).\n * All functions work on pre-fetched state — no RPC calls.\n *\n * Diverges from @jup-ag/lend 0.3.0-beta.1 `getNewExchangePrice`, which neither scales the rewards\n * term by 100 (1e12 → 1e14) nor zeroes rewards that haven't started or have ended; kept as-is\n * pending confirmation against the on-chain program.\n */\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nexport const JUP_EXCHANGE_PRICES_PRECISION = 1_000_000_000_000n; // 1e12\nexport const JUP_SECONDS_PER_YEAR = 31_536_000n;\nexport const JUP_MAX_REWARDS_RATE = 50_000_000_000_000n; // 50 * 1e12 = 50%\n\n// ============================================================================\n// TOTAL ASSETS\n// ============================================================================\n\n/**\n * Calculate total assets for a jup-lend market.\n * Formula: tokenExchangePrice * fTokenTotalSupply / EXCHANGE_PRICES_PRECISION\n *\n * @param lendingState - The on-chain Lending account\n * @param fTokenTotalSupply - Total supply of the fToken (from getTokenSupply)\n * @returns Total assets in underlying token native units\n */\nexport function calculateJupLendTotalAssets(\n lendingState: JupLendingState,\n fTokenTotalSupply: bigint\n): bigint {\n return (lendingState.tokenExchangePrice * fTokenTotalSupply) / JUP_EXCHANGE_PRICES_PRECISION;\n}\n\n// ============================================================================\n// REWARDS RATE\n// ============================================================================\n\nexport interface JupLendRewardsResult {\n rewardsRate: bigint;\n rewardsEnded: boolean;\n rewardsStartTime: bigint;\n}\n\n/**\n * Calculate the rewards rate from a LendingRewardsRateModel.\n * Extracted from compiled SDK's `calculateRewardsRate`.\n *\n * @param rewardsModel - The on-chain LendingRewardsRateModel account\n * @param totalAssets - Total assets in the market (from calculateJupLendTotalAssets)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Rewards rate, whether rewards ended, and start time\n */\nexport function calculateJupLendRewardsRate(\n rewardsModel: JupLendingRewardsRateModel,\n totalAssets: bigint,\n currentTimestamp: bigint\n): JupLendRewardsResult {\n const defaultResult: JupLendRewardsResult = {\n rewardsRate: 0n,\n rewardsEnded: false,\n rewardsStartTime: rewardsModel.startTime,\n };\n\n if (rewardsModel.startTime === 0n || rewardsModel.duration === 0n) {\n return defaultResult;\n }\n\n if (currentTimestamp > rewardsModel.startTime + rewardsModel.duration) {\n return { ...defaultResult, rewardsEnded: true };\n }\n\n if (totalAssets === 0n || totalAssets < rewardsModel.startTvl) {\n return defaultResult;\n }\n\n let rewardsRate = (rewardsModel.yearlyReward * 10_000n) / totalAssets;\n\n if (rewardsRate > JUP_MAX_REWARDS_RATE) {\n rewardsRate = JUP_MAX_REWARDS_RATE;\n }\n\n return {\n rewardsRate,\n rewardsEnded: false,\n rewardsStartTime: rewardsModel.startTime,\n };\n}\n\n// ============================================================================\n// REWARDS RATE FOR EXCHANGE PRICE (1e12 precision)\n// ============================================================================\n\n/**\n * Calculate the rewards rate at 1e12 precision for use in exchange price projection.\n * Mirrors SDK's `getRewardsRate` (earn/index.mjs line 261), NOT `calculateRewardsRate`.\n *\n * This is distinct from `calculateJupLendRewardsRate` which uses 1e4 precision for APR display.\n *\n * @param rewardsModel - The on-chain LendingRewardsRateModel account\n * @param totalAssets - Total assets in the market (from calculateJupLendTotalAssets)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Rate at 1e12 precision and rewards start time\n */\nexport function calculateJupLendRewardsRateForExchangePrice(\n rewardsModel: JupLendingRewardsRateModel,\n totalAssets: bigint,\n currentTimestamp: bigint\n): { rate: bigint; rewardsStartTime: bigint } {\n const defaultResult = { rate: 0n, rewardsStartTime: rewardsModel.startTime };\n\n if (rewardsModel.startTime === 0n || rewardsModel.duration === 0n) {\n return defaultResult;\n }\n\n if (currentTimestamp > rewardsModel.startTime + rewardsModel.duration) {\n return defaultResult;\n }\n\n if (totalAssets === 0n || totalAssets < rewardsModel.startTvl) {\n return defaultResult;\n }\n\n let rate = (rewardsModel.yearlyReward * JUP_EXCHANGE_PRICES_PRECISION) / totalAssets;\n\n if (rate > JUP_MAX_REWARDS_RATE) {\n rate = JUP_MAX_REWARDS_RATE;\n }\n\n return { rate, rewardsStartTime: rewardsModel.startTime };\n}\n\n// ============================================================================\n// EXCHANGE PRICE PROJECTION\n// ============================================================================\n\n/**\n * Project the new token exchange price offline (no RPC calls).\n * Extracted from compiled SDK's `getNewExchangePrice` (earn/index.mjs line 316).\n *\n * This combines:\n * 1. Rewards rate contribution (time-weighted, 1e12 precision via getRewardsRate)\n * 2. Liquidity exchange price delta (scaled to 1e14)\n *\n * Both components are accumulated in 1e14 space before being applied.\n *\n * @param lendingState - The on-chain Lending account\n * @param tokenReserve - The on-chain TokenReserve account (provides current supplyExchangePrice)\n * @param rewardsModel - The on-chain LendingRewardsRateModel (or null if no rewards)\n * @param fTokenTotalSupply - Total supply of the fToken (for totalAssets calculation)\n * @param currentTimestamp - Current unix timestamp (seconds)\n * @returns Projected token exchange price (1e12 precision)\n */\nexport function calculateJupLendNewExchangePrice(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint,\n currentTimestamp: bigint\n): bigint {\n const oldTokenExchangePrice = lendingState.tokenExchangePrice;\n const oldLiquidityExchangePrice = lendingState.liquidityExchangePrice;\n const currentLiquidityExchangePrice = tokenReserve.supplyExchangePrice;\n\n // Rewards component — must use 1e12-precision rate (mirrors SDK getRewardsRate, not calculateRewardsRate)\n let rewardsRate = 0n;\n let rewardsStartTime = lendingState.lastUpdateTimestamp;\n\n if (rewardsModel) {\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const result = calculateJupLendRewardsRateForExchangePrice(\n rewardsModel,\n totalAssets,\n currentTimestamp\n );\n rewardsRate = result.rate;\n rewardsStartTime = result.rewardsStartTime;\n }\n\n let lastUpdateTime = lendingState.lastUpdateTimestamp;\n if (lastUpdateTime < rewardsStartTime) {\n lastUpdateTime = rewardsStartTime;\n }\n\n const secondsElapsed = currentTimestamp - lastUpdateTime;\n\n // Rewards contribution: rate (1e12) * secondsElapsed / SECONDS_PER_YEAR → ~1e12 scale\n // Scaled up to 1e14 to match the liquidity delta component\n let totalReturnPercent = ((rewardsRate * secondsElapsed) / JUP_SECONDS_PER_YEAR) * 100n; // 1e12 → 1e14\n\n // Liquidity exchange price delta contribution (1e14 precision)\n const delta = currentLiquidityExchangePrice - oldLiquidityExchangePrice;\n totalReturnPercent += (delta * 100_000_000_000_000n) / oldLiquidityExchangePrice;\n\n return (\n oldTokenExchangePrice + (oldTokenExchangePrice * totalReturnPercent) / 100_000_000_000_000n\n );\n}\n\n/**\n * Underlying tokens (native units) per fToken at `nowSeconds` (unix seconds): the projected exchange\n * price over its 1e12 precision.\n */\nexport function getJupLendFTokenMultiplier(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint,\n nowSeconds: number\n): BigNumber {\n const exchangePrice = calculateJupLendNewExchangePrice(\n lendingState,\n tokenReserve,\n rewardsModel,\n fTokenTotalSupply,\n BigInt(nowSeconds)\n );\n\n return new BigNumber(exchangePrice.toString()).dividedBy(\n JUP_EXCHANGE_PRICES_PRECISION.toString()\n );\n}\n\n// ============================================================================\n// LIQUIDITY SUPPLY RATE\n// ============================================================================\n\n/**\n * Calculate the liquidity layer supply rate for an asset.\n * Extracted from compiled SDK's `getLiquidityAssetSupplyRate`.\n *\n * Formula: borrowRate * (1 - fee) * borrowWithInterest / supplyWithInterest\n *\n * @param tokenReserve - The on-chain TokenReserve account\n * @returns Supply rate in bps\n */\nexport function calculateJupLendLiquiditySupplyRate(tokenReserve: JupTokenReserve): bigint {\n const borrowRate = BigInt(tokenReserve.borrowRate);\n const fee = BigInt(tokenReserve.feeOnInterest);\n\n if (tokenReserve.totalSupplyWithInterest === 0n) {\n return 0n;\n }\n\n const borrowWithInterestForRate =\n (tokenReserve.totalBorrowWithInterest * tokenReserve.borrowExchangePrice) /\n JUP_EXCHANGE_PRICES_PRECISION;\n\n const supplyWithInterestForRate =\n (tokenReserve.totalSupplyWithInterest * tokenReserve.supplyExchangePrice) /\n JUP_EXCHANGE_PRICES_PRECISION;\n\n if (supplyWithInterestForRate === 0n) {\n return 0n;\n }\n\n return (\n (borrowRate * (10_000n - fee) * borrowWithInterestForRate) /\n (supplyWithInterestForRate * 10_000n)\n );\n}\n\n// ============================================================================\n// COMBINED SUPPLY RATE (APR)\n// ============================================================================\n\n/**\n * Calculate the total supply rate (APR) for a jup-lend market,\n * combining both base liquidity supply rate and rewards rate.\n *\n * Returns a number as a decimal (e.g. 0.05 = 5% APR).\n *\n * @param lendingState - The on-chain Lending account\n * @param tokenReserve - The on-chain TokenReserve account\n * @param rewardsModel - The on-chain LendingRewardsRateModel account (or null if no rewards)\n * @param fTokenTotalSupply - Total supply of the fToken\n * @returns Supply rate as decimal number\n */\nexport function calculateJupLendSupplyRate(\n lendingState: JupLendingState,\n tokenReserve: JupTokenReserve,\n rewardsModel: JupLendingRewardsRateModel | null,\n fTokenTotalSupply: bigint\n): number {\n const supplyRate = calculateJupLendLiquiditySupplyRate(tokenReserve);\n\n // supplyRate is in bps (e.g. 500 = 5%)\n let totalRateBps = Number(supplyRate);\n\n if (rewardsModel) {\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));\n const { rewardsRate } = calculateJupLendRewardsRate(\n rewardsModel,\n totalAssets,\n currentTimestamp\n );\n // rewardsRate is scaled by 1e4 relative to totalAssets\n totalRateBps += Number(rewardsRate);\n }\n\n return totalRateBps / 10_000;\n}\n\n// ============================================================================\n// SUPPLY APY\n// ============================================================================\n\n/**\n * Calculate the supply APY for a jup-lend market (base rate only, no rewards).\n *\n * Uses hourly compounding: (1 + apr/HOURS_PER_YEAR)^HOURS_PER_YEAR - 1\n *\n * @param tokenReserve - The on-chain TokenReserve account\n * @returns Supply APY as decimal (e.g. 0.0512 = 5.12% APY)\n */\nexport function calculateJupLendSupplyAPY(tokenReserve: JupTokenReserve): number {\n const supplyRateBps = calculateJupLendLiquiditySupplyRate(tokenReserve);\n const apr = Number(supplyRateBps) / 1e4;\n return aprToApy(apr);\n}\n\n// ============================================================================\n// BORROW RATE FROM RATE MODEL (PIECEWISE LINEAR)\n// ============================================================================\n\n/**\n * Calculate the borrow rate at a given utilization using the on-chain RateModel.\n *\n * V1 (version=1, single kink):\n * [0, kink1] → linear rateAtZero → rateAtKink1\n * [kink1, 10000] → linear rateAtKink1 → rateAtMax\n *\n * V2 (version=2, dual kink):\n * [0, kink1] → linear rateAtZero → rateAtKink1\n * [kink1, kink2] → linear rateAtKink1 → rateAtKink2\n * [kink2, 10000] → linear rateAtKink2 → rateAtMax\n *\n * @param rateModel - The on-chain RateModel account\n * @param utilizationBps - Utilization in bps (0–10000)\n * @returns Borrow rate in bps\n */\nexport function calculateJupLendBorrowRate(\n rateModel: JupRateModel,\n utilizationBps: number\n): number {\n const u = Math.max(0, Math.min(10000, utilizationBps));\n\n if (rateModel.version === 2) {\n // V2: dual kink\n if (u <= rateModel.kink1Utilization) {\n return linearInterpolate(\n 0,\n rateModel.rateAtZero,\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n u\n );\n } else if (u <= rateModel.kink2Utilization) {\n return linearInterpolate(\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n rateModel.kink2Utilization,\n rateModel.rateAtKink2,\n u\n );\n } else {\n return linearInterpolate(\n rateModel.kink2Utilization,\n rateModel.rateAtKink2,\n 10000,\n rateModel.rateAtMax,\n u\n );\n }\n } else {\n // V1: single kink\n if (u <= rateModel.kink1Utilization) {\n return linearInterpolate(\n 0,\n rateModel.rateAtZero,\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n u\n );\n } else {\n return linearInterpolate(\n rateModel.kink1Utilization,\n rateModel.rateAtKink1,\n 10000,\n rateModel.rateAtMax,\n u\n );\n }\n }\n}\n\n/**\n * Linear interpolation between two points.\n */\nfunction linearInterpolate(x0: number, y0: number, x1: number, y1: number, x: number): number {\n if (x1 === x0) return y0;\n return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0);\n}\n\n// ============================================================================\n// SUPPLY INTEREST RATE CURVE\n// ============================================================================\n\n/**\n * Interest rate curve point for visualization (supply only).\n */\nexport interface JupLendInterestRateCurvePoint {\n utilization: number; // 0-100 percentage\n supplyAPY: number; // percentage\n}\n\n/**\n * Generate a supply interest rate curve for a JupLend reserve using the on-chain RateModel.\n *\n * Uses the piecewise linear borrow rate curve from the RateModel account:\n * borrowAPR(U) = calculateJupLendBorrowRate(rateModel, U * 10000)\n * supplyAPR(U) = borrowAPR(U) * (1 - feeOnInterest / 1e4) * U\n * supplyAPY(U) = aprToApy(supplyAPR(U))\n *\n * @param rateModel - The on-chain RateModel account (from liquidity program)\n * @param feeOnInterest - Fee on interest in bps (from TokenReserve.feeOnInterest)\n * @returns 101 curve points (utilization 0–100%)\n */\nexport function generateJupLendSupplyCurve(\n rateModel: JupRateModel,\n feeOnInterest: number\n): JupLendInterestRateCurvePoint[] {\n const feeMultiplier = 1 - feeOnInterest / 1e4;\n\n return Array.from({ length: 101 }, (_, i) => {\n const utilizationFraction = i / 100; // 0.00 to 1.00\n const utilizationBps = i * 100; // 0 to 10000\n\n const borrowRateBps = calculateJupLendBorrowRate(rateModel, utilizationBps);\n const borrowRateDecimal = borrowRateBps / 1e4;\n\n const supplyAPR = borrowRateDecimal * feeMultiplier * utilizationFraction;\n const supplyAPY = aprToApy(supplyAPR);\n\n return {\n utilization: i, // 0-100\n supplyAPY: supplyAPY * 100, // Convert to percentage\n };\n });\n}\n","import {\n address,\n getAddressEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\nimport { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\n\nimport { findFTokenMintPda, findLendingAdminPda, findLendingPda } from \"~/generated/jup-lend\";\nimport {\n findLiquidityPda,\n findRateModelPda,\n findTokenReservePda,\n findUserSupplyPositionPda,\n} from \"~/generated/jup-lend-liquidity\";\n\n/** JupLend rewards rate model program (no IDL client; only its PDA is needed). */\nexport const JUP_REWARDS_PROGRAM_ADDRESS = address(\"jup7TthsMgcR9Y3L277b8Eo9uboVSmu1utkuXHNUKar\");\n\n/** `LendingRewardsRateModel` PDA of `mint`, owned by the rewards program. */\nexport function deriveJupLendLendingRewardsRateModel(\n mint: Address\n): Promise<ProgramDerivedAddress> {\n return getProgramDerivedAddress({\n programAddress: JUP_REWARDS_PROGRAM_ADDRESS,\n seeds: [\"lending_rewards_rate_model\", getAddressEncoder().encode(mint)],\n });\n}\n\n/** Liquidity-layer rate model PDA of `mint`. */\nexport function deriveJupLendRateModel(mint: Address): Promise<ProgramDerivedAddress> {\n return findRateModelPda({ mint });\n}\n\n/**\n * All JupLend accounts a deposit/withdraw of `mint` needs, derived locally. `tokenProgram` is the\n * mint's token program (for the liquidity vault ATA).\n */\nexport async function getAllDerivedJupLendAccounts(\n mint: Address,\n tokenProgram: Address = TOKEN_PROGRAM_ADDRESS\n) {\n const [[fTokenMint], [liquidity]] = await Promise.all([\n findFTokenMintPda({ mint }),\n findLiquidityPda(),\n ]);\n const [\n [lending],\n [lendingAdmin],\n [supplyTokenReservesLiquidity],\n [rateModel],\n [vault],\n [rewardsRateModel],\n ] = await Promise.all([\n findLendingPda({ mint, fTokenMint }),\n findLendingAdminPda(),\n findTokenReservePda({ mint }),\n findRateModelPda({ mint }),\n findAssociatedTokenPda({ owner: liquidity, tokenProgram, mint }),\n deriveJupLendLendingRewardsRateModel(mint),\n ]);\n const [lendingSupplyPositionOnLiquidity] = await findUserSupplyPositionPda({\n supplyMint: mint,\n protocol: lending,\n });\n\n return {\n fTokenMint,\n lendingAdmin,\n supplyTokenReservesLiquidity,\n lendingSupplyPositionOnLiquidity,\n rateModel,\n vault,\n liquidity,\n rewardsRateModel,\n };\n}\n","import {\n calculateJupLendRewardsRate,\n calculateJupLendTotalAssets,\n JupLendRewardsResult,\n} from \"./interest-rate\";\nimport { JupLendingRewardsRateModel, JupLendingState } from \"./types\";\n\n/**\n * Rewards info of a JupLend market from pre-fetched state.\n * @param fTokenTotalSupply - fToken supply, native units\n */\nexport function getJupLendRewards(\n lendingState: JupLendingState,\n rewardsModel: JupLendingRewardsRateModel,\n fTokenTotalSupply: bigint\n): JupLendRewardsResult {\n if (lendingState.rewardsRateModel === \"11111111111111111111111111111111\") {\n return { rewardsRate: 0n, rewardsEnded: false, rewardsStartTime: 0n };\n }\n\n const totalAssets = calculateJupLendTotalAssets(lendingState, fTokenTotalSupply);\n const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));\n\n return calculateJupLendRewardsRate(rewardsModel, totalAssets, currentTimestamp);\n}\n","import { address } from \"@solana/kit\";\n\nimport {\n JupLendingRewardsRateModel,\n JupLendingRewardsRateModelJSON,\n JupLendingState,\n JupLendingStateJSON,\n JupRateModel,\n JupRateModelJSON,\n JupTokenReserve,\n JupTokenReserveJSON,\n} from \"./types\";\n\n/** Serializes a JupLend lending state to its JSON DTO. */\nexport function jupLendingStateRawToDto(state: JupLendingState): JupLendingStateJSON {\n return {\n pubkey: state.pubkey,\n mint: state.mint,\n fTokenMint: state.fTokenMint,\n lendingId: state.lendingId,\n decimals: state.decimals,\n rewardsRateModel: state.rewardsRateModel,\n liquidityExchangePrice: state.liquidityExchangePrice.toString(),\n tokenExchangePrice: state.tokenExchangePrice.toString(),\n lastUpdateTimestamp: state.lastUpdateTimestamp.toString(),\n tokenReservesLiquidity: state.tokenReservesLiquidity,\n supplyPositionOnLiquidity: state.supplyPositionOnLiquidity,\n };\n}\n\n/**\n * Parses a JupLend lending state DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToJupLendingStateRaw(dto: JupLendingStateJSON): JupLendingState {\n return {\n pubkey: address(dto.pubkey),\n mint: address(dto.mint),\n fTokenMint: address(dto.fTokenMint),\n lendingId: dto.lendingId,\n decimals: dto.decimals,\n rewardsRateModel: address(dto.rewardsRateModel),\n liquidityExchangePrice: BigInt(dto.liquidityExchangePrice),\n tokenExchangePrice: BigInt(dto.tokenExchangePrice),\n lastUpdateTimestamp: BigInt(dto.lastUpdateTimestamp),\n tokenReservesLiquidity: address(dto.tokenReservesLiquidity),\n supplyPositionOnLiquidity: address(dto.supplyPositionOnLiquidity),\n };\n}\n\n/** Serializes a JupLend token reserve to its JSON DTO. */\nexport function jupTokenReserveRawToDto(reserve: JupTokenReserve): JupTokenReserveJSON {\n return {\n pubkey: reserve.pubkey,\n borrowRate: reserve.borrowRate,\n feeOnInterest: reserve.feeOnInterest,\n lastUtilization: reserve.lastUtilization,\n supplyExchangePrice: reserve.supplyExchangePrice.toString(),\n borrowExchangePrice: reserve.borrowExchangePrice.toString(),\n totalSupplyWithInterest: reserve.totalSupplyWithInterest.toString(),\n totalSupplyInterestFree: reserve.totalSupplyInterestFree.toString(),\n totalBorrowWithInterest: reserve.totalBorrowWithInterest.toString(),\n totalBorrowInterestFree: reserve.totalBorrowInterestFree.toString(),\n };\n}\n\n/**\n * Parses a JupLend token reserve DTO.\n * @throws if an address string is invalid\n */\nexport function dtoToJupTokenReserveRaw(dto: JupTokenReserveJSON): JupTokenReserve {\n return {\n pubkey: address(dto.pubkey),\n borrowRate: dto.borrowRate,\n feeOnInterest: dto.feeOnInterest,\n lastUtilization: dto.lastUtilization,\n supplyExchangePrice: BigInt(dto.supplyExchangePrice),\n borrowExchangePrice: BigInt(dto.borrowExchangePrice),\n totalSupplyWithInterest: BigInt(dto.totalSupplyWithInterest),\n totalSupplyInterestFree: BigInt(dto.totalSupplyInterestFree),\n totalBorrowWithInterest: BigInt(dto.totalBorrowWithInterest),\n totalBorrowInterestFree: BigInt(dto.totalBorrowInterestFree),\n };\n}\n\n/** Serializes a JupLend rewards rate model to its JSON DTO. */\nexport function jupLendingRewardsRateModelRawToDto(\n model: JupLendingRewardsRateModel\n): JupLendingRewardsRateModelJSON {\n return {\n startTvl: model.startTvl.toString(),\n duration: model.duration.toString(),\n startTime: model.startTime.toString(),\n yearlyReward: model.yearlyReward.toString(),\n };\n}\n\n/** Parses a JupLend rewards rate model DTO. */\nexport function dtoToJupLendingRewardsRateModelRaw(\n dto: JupLendingRewardsRateModelJSON\n): JupLendingRewardsRateModel {\n return {\n startTvl: BigInt(dto.startTvl),\n duration: BigInt(dto.duration),\n startTime: BigInt(dto.startTime),\n yearlyReward: BigInt(dto.yearlyReward),\n };\n}\n\n/** Serializes a JupLend rate model to its JSON DTO. */\nexport function jupRateModelRawToDto(model: JupRateModel): JupRateModelJSON {\n return {\n version: model.version,\n rateAtZero: model.rateAtZero,\n kink1Utilization: model.kink1Utilization,\n rateAtKink1: model.rateAtKink1,\n rateAtMax: model.rateAtMax,\n kink2Utilization: model.kink2Utilization,\n rateAtKink2: model.rateAtKink2,\n };\n}\n\n/** Parses a JupLend rate model DTO. */\nexport function dtoToJupRateModelRaw(dto: JupRateModelJSON): JupRateModel {\n return {\n version: dto.version,\n rateAtZero: dto.rateAtZero,\n kink1Utilization: dto.kink1Utilization,\n rateAtKink1: dto.rateAtKink1,\n rateAtMax: dto.rateAtMax,\n kink2Utilization: dto.kink2Utilization,\n rateAtKink2: dto.rateAtKink2,\n };\n}\n","import type { GetMultipleAccountsApi, Rpc } from \"@solana/kit\";\nimport { getMintDecoder } from \"@solana-program/token\";\n\nimport {\n decodeJupLendingRewardsRateModel,\n decodeJupLendingState,\n decodeJupRateModel,\n decodeJupTokenReserve,\n} from \"./accounts\";\nimport { deriveJupLendRateModel } from \"./pda\";\nimport {\n jupLendingRewardsRateModelRawToDto,\n jupLendingStateRawToDto,\n jupRateModelRawToDto,\n jupTokenReserveRawToDto,\n} from \"./serialize\";\nimport type { JupLendBankInput, JupLendStates, JupLendStatesJSON } from \"./types\";\n\nimport { DEFAULT_ADDRESS } from \"~/constants\";\nimport { chunkedGetRawMultipleAccountInfoOrderedWithNulls } from \"~/utils\";\n\n/**\n * Fetches each bank's {@link JupLendStates}, keyed by bank address. Banks with a default lending\n * state or a missing lending state, token reserve or fToken mint are left out.\n * @throws if a fetched account isn't the JupLend account it should be\n */\nexport async function fetchJupLendStates(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: JupLendBankInput[]\n): Promise<Record<string, JupLendStates>> {\n const validBanks = banks.filter((bank) => bank.lendingState !== DEFAULT_ADDRESS);\n const accounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n validBanks.map((bank) => bank.lendingState)\n );\n const decoded = validBanks.flatMap((bank, i) => {\n const lending = accounts[i];\n return lending\n ? [\n {\n bankAddress: bank.bankAddress,\n lendingState: decodeJupLendingState(bank.lendingState, lending.data),\n },\n ]\n : [];\n });\n\n const rateModels = await Promise.all(\n decoded.map(async ({ lendingState }) => (await deriveJupLendRateModel(lendingState.mint))[0])\n );\n const venueAccounts = await chunkedGetRawMultipleAccountInfoOrderedWithNulls(\n rpc,\n decoded.flatMap(({ lendingState }, i) => [\n lendingState.tokenReservesLiquidity,\n lendingState.rewardsRateModel,\n lendingState.fTokenMint,\n rateModels[i],\n ])\n );\n\n return Object.fromEntries(\n decoded.flatMap(({ bankAddress, lendingState }, i) => {\n const [tokenReserve, rewardsRateModel, fTokenMint, rateModel] = venueAccounts.slice(\n 4 * i,\n 4 * i + 4\n );\n return tokenReserve && fTokenMint\n ? [\n [\n bankAddress,\n {\n lendingState,\n tokenReserveState: decodeJupTokenReserve(\n lendingState.tokenReservesLiquidity,\n tokenReserve.data\n ),\n rewardsRateModel:\n rewardsRateModel && lendingState.rewardsRateModel !== DEFAULT_ADDRESS\n ? decodeJupLendingRewardsRateModel(rewardsRateModel.data)\n : null,\n rateModel: rateModel ? decodeJupRateModel(rateModel.data) : null,\n fTokenTotalSupply: getMintDecoder().decode(fTokenMint.data).supply,\n },\n ],\n ]\n : [];\n })\n );\n}\n\n/**\n * {@link fetchJupLendStates} in the JSON wire format served by API routes.\n * @throws see {@link fetchJupLendStates}\n */\nexport async function fetchJupLendStatesDto(\n rpc: Rpc<GetMultipleAccountsApi>,\n banks: JupLendBankInput[]\n): Promise<Record<string, JupLendStatesJSON>> {\n const states = await fetchJupLendStates(rpc, banks);\n return Object.fromEntries(\n Object.entries(states).map(([bank, state]) => [\n bank,\n {\n lendingState: jupLendingStateRawToDto(state.lendingState),\n tokenReserveState: jupTokenReserveRawToDto(state.tokenReserveState),\n rewardsRateModel:\n state.rewardsRateModel && jupLendingRewardsRateModelRawToDto(state.rewardsRateModel),\n rateModel: state.rateModel && jupRateModelRawToDto(state.rateModel),\n fTokenTotalSupply: state.fTokenTotalSupply.toString(),\n },\n ])\n );\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const DEPOSIT_POLICY_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 159, 243, 65, 242, 81, 27, 41, 167,\n]);\n\nexport function getDepositPolicyDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(DEPOSIT_POLICY_DISCRIMINATOR);\n}\n\nexport type DepositPolicy = {\n discriminator: ReadonlyUint8Array;\n /** Vault this policy belongs to. */\n lpVault: Address;\n /** Maximum post-deposit NAV in the vault asset's base units. */\n capacityAssets: bigint;\n /** Emergency switch for deposits. Withdrawals do not consult this field. */\n depositsPaused: boolean;\n /** PDA derivation bump. */\n bump: number;\n};\n\nexport type DepositPolicyArgs = {\n /** Vault this policy belongs to. */\n lpVault: Address;\n /** Maximum post-deposit NAV in the vault asset's base units. */\n capacityAssets: number | bigint;\n /** Emergency switch for deposits. Withdrawals do not consult this field. */\n depositsPaused: boolean;\n /** PDA derivation bump. */\n bump: number;\n};\n\n/** Gets the encoder for {@link DepositPolicyArgs} account data. */\nexport function getDepositPolicyEncoder(): FixedSizeEncoder<DepositPolicyArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"lpVault\", getAddressEncoder()],\n [\"capacityAssets\", getU64Encoder()],\n [\"depositsPaused\", getBooleanEncoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: DEPOSIT_POLICY_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link DepositPolicy} account data. */\nexport function getDepositPolicyDecoder(): FixedSizeDecoder<DepositPolicy> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"lpVault\", getAddressDecoder()],\n [\"capacityAssets\", getU64Decoder()],\n [\"depositsPaused\", getBooleanDecoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link DepositPolicy} account data. */\nexport function getDepositPolicyCodec(): FixedSizeCodec<DepositPolicyArgs, DepositPolicy> {\n return combineCodec(getDepositPolicyEncoder(), getDepositPolicyDecoder());\n}\n\nexport function decodeDepositPolicy<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<DepositPolicy, TAddress>;\nexport function decodeDepositPolicy<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<DepositPolicy, TAddress>;\nexport function decodeDepositPolicy<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<DepositPolicy, TAddress> | MaybeAccount<DepositPolicy, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getDepositPolicyDecoder());\n}\n\nexport async function fetchDepositPolicy<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<DepositPolicy, TAddress>> {\n const maybeAccount = await fetchMaybeDepositPolicy(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeDepositPolicy<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<DepositPolicy, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeDepositPolicy(maybeAccount);\n}\n\nexport async function fetchAllDepositPolicy(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<DepositPolicy>[]> {\n const maybeAccounts = await fetchAllMaybeDepositPolicy(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeDepositPolicy(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<DepositPolicy>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeDepositPolicy(maybeAccount));\n}\n\nexport function getDepositPolicySize(): number {\n return 50;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const LP_VAULT_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 189, 45, 167, 23, 91, 118, 105, 190,\n]);\n\nexport function getLpVaultDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(LP_VAULT_DISCRIMINATOR);\n}\n\nexport type LpVault = {\n discriminator: ReadonlyUint8Array;\n /** USDC TokenAccount where users deposit, funds agent operations. */\n assetsAccount: Address;\n /** TokenAccount where shares are held during queued (illiquid) withdrawals. */\n pendingSharesAccount: Address;\n /** Derived mint (created on initialize) that represents LP tokens or shares. */\n sharesMint: Address;\n /** Mint corresponding to the asset, most of the time USDC. */\n assetsMint: Address;\n /** Pubkey authorized to withdraw assets from assets_account and update NAV. */\n fundAuthority: Address;\n /** Current Net Asset Value (total vault value in asset decimals). */\n nav: bigint;\n /**\n * Total shares outstanding (cached for efficiency). May temporarily diverge\n * from shares_mint.supply during the escrow withdrawal flow (between\n * fulfill_withdrawal and complete_withdrawal).\n */\n totalShares: bigint;\n /** Timestamp for when NAV was last updated. */\n navUpdatedAt: bigint;\n /**\n * Maximum NAV staleness for user operations (in seconds).\n * Deposits and withdrawals fail if NAV is older than this.\n */\n navMaxStaleness: bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n vaultName: string;\n /**\n * Total value of pending withdrawals awaiting liquidity.\n * When a withdrawal cannot be fulfilled instantly due to insufficient\n * liquid assets, the value is tracked here. This is approximate — the\n * value recorded at withdrawal time may differ from the value at\n * fulfillment time (recomputed at current NAV). Used for operator\n * visibility only, not for critical calculations.\n */\n pendingWithdrawalValue: bigint;\n /** Shares token account that receives fee shares. Pubkey::default() = disabled. */\n feeRecipient: Address;\n /** Performance fee rate in basis points (2000 = 20%). 0 = disabled. */\n performanceFeeBps: number;\n /** How often scheduled fees are assessed (seconds). E.g., 86400 = 24h. */\n assessmentIntervalSecs: bigint;\n /** Unix timestamp of last fee event (scheduled or withdrawal-triggered). */\n lastAssessmentTimestamp: bigint;\n /** PPS at last fee event, scaled by PRICE_SCALE. High-water mark for fees. */\n pricePerShareAtLastAssessment: bigint;\n /**\n * Optional keeper authority. When set (non-default), this key can call\n * fulfill_withdrawal in addition to fund_authority. Allows the keeper\n * process to use a separate key from the agent/fund_authority.\n * Pubkey::default() = not set (only fund_authority can fulfill).\n */\n keeperAuthority: Address;\n};\n\nexport type LpVaultArgs = {\n /** USDC TokenAccount where users deposit, funds agent operations. */\n assetsAccount: Address;\n /** TokenAccount where shares are held during queued (illiquid) withdrawals. */\n pendingSharesAccount: Address;\n /** Derived mint (created on initialize) that represents LP tokens or shares. */\n sharesMint: Address;\n /** Mint corresponding to the asset, most of the time USDC. */\n assetsMint: Address;\n /** Pubkey authorized to withdraw assets from assets_account and update NAV. */\n fundAuthority: Address;\n /** Current Net Asset Value (total vault value in asset decimals). */\n nav: number | bigint;\n /**\n * Total shares outstanding (cached for efficiency). May temporarily diverge\n * from shares_mint.supply during the escrow withdrawal flow (between\n * fulfill_withdrawal and complete_withdrawal).\n */\n totalShares: number | bigint;\n /** Timestamp for when NAV was last updated. */\n navUpdatedAt: number | bigint;\n /**\n * Maximum NAV staleness for user operations (in seconds).\n * Deposits and withdrawals fail if NAV is older than this.\n */\n navMaxStaleness: number | bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n vaultName: string;\n /**\n * Total value of pending withdrawals awaiting liquidity.\n * When a withdrawal cannot be fulfilled instantly due to insufficient\n * liquid assets, the value is tracked here. This is approximate — the\n * value recorded at withdrawal time may differ from the value at\n * fulfillment time (recomputed at current NAV). Used for operator\n * visibility only, not for critical calculations.\n */\n pendingWithdrawalValue: number | bigint;\n /** Shares token account that receives fee shares. Pubkey::default() = disabled. */\n feeRecipient: Address;\n /** Performance fee rate in basis points (2000 = 20%). 0 = disabled. */\n performanceFeeBps: number;\n /** How often scheduled fees are assessed (seconds). E.g., 86400 = 24h. */\n assessmentIntervalSecs: number | bigint;\n /** Unix timestamp of last fee event (scheduled or withdrawal-triggered). */\n lastAssessmentTimestamp: number | bigint;\n /** PPS at last fee event, scaled by PRICE_SCALE. High-water mark for fees. */\n pricePerShareAtLastAssessment: number | bigint;\n /**\n * Optional keeper authority. When set (non-default), this key can call\n * fulfill_withdrawal in addition to fund_authority. Allows the keeper\n * process to use a separate key from the agent/fund_authority.\n * Pubkey::default() = not set (only fund_authority can fulfill).\n */\n keeperAuthority: Address;\n};\n\n/** Gets the encoder for {@link LpVaultArgs} account data. */\nexport function getLpVaultEncoder(): Encoder<LpVaultArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"assetsAccount\", getAddressEncoder()],\n [\"pendingSharesAccount\", getAddressEncoder()],\n [\"sharesMint\", getAddressEncoder()],\n [\"assetsMint\", getAddressEncoder()],\n [\"fundAuthority\", getAddressEncoder()],\n [\"nav\", getU64Encoder()],\n [\"totalShares\", getU64Encoder()],\n [\"navUpdatedAt\", getI64Encoder()],\n [\"navMaxStaleness\", getU64Encoder()],\n [\"bump\", getU8Encoder()],\n [\"vaultName\", addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n [\"pendingWithdrawalValue\", getU64Encoder()],\n [\"feeRecipient\", getAddressEncoder()],\n [\"performanceFeeBps\", getU16Encoder()],\n [\"assessmentIntervalSecs\", getI64Encoder()],\n [\"lastAssessmentTimestamp\", getI64Encoder()],\n [\"pricePerShareAtLastAssessment\", getU64Encoder()],\n [\"keeperAuthority\", getAddressEncoder()],\n ]),\n (value) => ({ ...value, discriminator: LP_VAULT_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link LpVault} account data. */\nexport function getLpVaultDecoder(): Decoder<LpVault> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"assetsAccount\", getAddressDecoder()],\n [\"pendingSharesAccount\", getAddressDecoder()],\n [\"sharesMint\", getAddressDecoder()],\n [\"assetsMint\", getAddressDecoder()],\n [\"fundAuthority\", getAddressDecoder()],\n [\"nav\", getU64Decoder()],\n [\"totalShares\", getU64Decoder()],\n [\"navUpdatedAt\", getI64Decoder()],\n [\"navMaxStaleness\", getU64Decoder()],\n [\"bump\", getU8Decoder()],\n [\"vaultName\", addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n [\"pendingWithdrawalValue\", getU64Decoder()],\n [\"feeRecipient\", getAddressDecoder()],\n [\"performanceFeeBps\", getU16Decoder()],\n [\"assessmentIntervalSecs\", getI64Decoder()],\n [\"lastAssessmentTimestamp\", getI64Decoder()],\n [\"pricePerShareAtLastAssessment\", getU64Decoder()],\n [\"keeperAuthority\", getAddressDecoder()],\n ]);\n}\n\n/** Gets the codec for {@link LpVault} account data. */\nexport function getLpVaultCodec(): Codec<LpVaultArgs, LpVault> {\n return combineCodec(getLpVaultEncoder(), getLpVaultDecoder());\n}\n\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<LpVault, TAddress>;\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<LpVault, TAddress>;\nexport function decodeLpVault<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<LpVault, TAddress> | MaybeAccount<LpVault, TAddress> {\n return decodeAccount(encodedAccount as MaybeEncodedAccount<TAddress>, getLpVaultDecoder());\n}\n\nexport async function fetchLpVault<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<LpVault, TAddress>> {\n const maybeAccount = await fetchMaybeLpVault(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeLpVault<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<LpVault, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeLpVault(maybeAccount);\n}\n\nexport async function fetchAllLpVault(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<LpVault>[]> {\n const maybeAccounts = await fetchAllMaybeLpVault(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeLpVault(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<LpVault>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeLpVault(maybeAccount));\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU16Decoder,\n getU16Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const WITHDRAWAL_POLICY_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 52, 231, 68, 59, 247, 250, 119, 244,\n]);\n\nexport function getWithdrawalPolicyDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(WITHDRAWAL_POLICY_DISCRIMINATOR);\n}\n\nexport type WithdrawalPolicy = {\n discriminator: ReadonlyUint8Array;\n /** Vault this policy belongs to. */\n lpVault: Address;\n /** Base-asset fee retained in the vault on withdrawal. 30 = 0.30%. */\n withdrawalFeeBps: number;\n /** Max net withdrawal accepted per hour as bps of current NAV. 0 = disabled. */\n hourlyWithdrawalCapBps: number;\n /** Max net withdrawal accepted per day as bps of current NAV. 0 = disabled. */\n dailyWithdrawalCapBps: number;\n /** Net withdrawn assets counted in the current hourly window. */\n hourlyWithdrawnAssets: bigint;\n /** Net withdrawn assets counted in the current daily window. */\n dailyWithdrawnAssets: bigint;\n /** Start timestamp for the current hourly cap window. */\n hourlyWindowStart: bigint;\n /** Start timestamp for the current daily cap window. */\n dailyWindowStart: bigint;\n /** PDA derivation bump. */\n bump: number;\n};\n\nexport type WithdrawalPolicyArgs = {\n /** Vault this policy belongs to. */\n lpVault: Address;\n /** Base-asset fee retained in the vault on withdrawal. 30 = 0.30%. */\n withdrawalFeeBps: number;\n /** Max net withdrawal accepted per hour as bps of current NAV. 0 = disabled. */\n hourlyWithdrawalCapBps: number;\n /** Max net withdrawal accepted per day as bps of current NAV. 0 = disabled. */\n dailyWithdrawalCapBps: number;\n /** Net withdrawn assets counted in the current hourly window. */\n hourlyWithdrawnAssets: number | bigint;\n /** Net withdrawn assets counted in the current daily window. */\n dailyWithdrawnAssets: number | bigint;\n /** Start timestamp for the current hourly cap window. */\n hourlyWindowStart: number | bigint;\n /** Start timestamp for the current daily cap window. */\n dailyWindowStart: number | bigint;\n /** PDA derivation bump. */\n bump: number;\n};\n\n/** Gets the encoder for {@link WithdrawalPolicyArgs} account data. */\nexport function getWithdrawalPolicyEncoder(): FixedSizeEncoder<WithdrawalPolicyArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"lpVault\", getAddressEncoder()],\n [\"withdrawalFeeBps\", getU16Encoder()],\n [\"hourlyWithdrawalCapBps\", getU16Encoder()],\n [\"dailyWithdrawalCapBps\", getU16Encoder()],\n [\"hourlyWithdrawnAssets\", getU64Encoder()],\n [\"dailyWithdrawnAssets\", getU64Encoder()],\n [\"hourlyWindowStart\", getI64Encoder()],\n [\"dailyWindowStart\", getI64Encoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: WITHDRAWAL_POLICY_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link WithdrawalPolicy} account data. */\nexport function getWithdrawalPolicyDecoder(): FixedSizeDecoder<WithdrawalPolicy> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"lpVault\", getAddressDecoder()],\n [\"withdrawalFeeBps\", getU16Decoder()],\n [\"hourlyWithdrawalCapBps\", getU16Decoder()],\n [\"dailyWithdrawalCapBps\", getU16Decoder()],\n [\"hourlyWithdrawnAssets\", getU64Decoder()],\n [\"dailyWithdrawnAssets\", getU64Decoder()],\n [\"hourlyWindowStart\", getI64Decoder()],\n [\"dailyWindowStart\", getI64Decoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link WithdrawalPolicy} account data. */\nexport function getWithdrawalPolicyCodec(): FixedSizeCodec<WithdrawalPolicyArgs, WithdrawalPolicy> {\n return combineCodec(getWithdrawalPolicyEncoder(), getWithdrawalPolicyDecoder());\n}\n\nexport function decodeWithdrawalPolicy<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<WithdrawalPolicy, TAddress>;\nexport function decodeWithdrawalPolicy<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<WithdrawalPolicy, TAddress>;\nexport function decodeWithdrawalPolicy<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<WithdrawalPolicy, TAddress> | MaybeAccount<WithdrawalPolicy, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getWithdrawalPolicyDecoder()\n );\n}\n\nexport async function fetchWithdrawalPolicy<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<WithdrawalPolicy, TAddress>> {\n const maybeAccount = await fetchMaybeWithdrawalPolicy(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeWithdrawalPolicy<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<WithdrawalPolicy, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeWithdrawalPolicy(maybeAccount);\n}\n\nexport async function fetchAllWithdrawalPolicy(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<WithdrawalPolicy>[]> {\n const maybeAccounts = await fetchAllMaybeWithdrawalPolicy(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeWithdrawalPolicy(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<WithdrawalPolicy>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeWithdrawalPolicy(maybeAccount));\n}\n\nexport function getWithdrawalPolicySize(): number {\n return 79;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getStructDecoder,\n getStructEncoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type EncodedAccount,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type FixedSizeCodec,\n type FixedSizeDecoder,\n type FixedSizeEncoder,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\n\nexport const WITHDRAW_RECEIPT_DISCRIMINATOR: ReadonlyUint8Array = new Uint8Array([\n 132, 238, 44, 182, 207, 9, 124, 140,\n]);\n\nexport function getWithdrawReceiptDiscriminatorBytes(): ReadonlyUint8Array {\n return fixEncoderSize(getBytesEncoder(), 8).encode(WITHDRAW_RECEIPT_DISCRIMINATOR);\n}\n\nexport type WithdrawReceipt = {\n discriminator: ReadonlyUint8Array;\n /** User requesting withdrawal. */\n user: Address;\n /** Vault where the user has invested. */\n lpVault: Address;\n /**\n * Shares waiting for liquidity (keeper needs to fulfill these).\n * These shares are held in the escrow_shares_account.\n */\n pendingShares: bigint;\n /**\n * Shares that have been fulfilled and are ready to claim.\n * These shares are also in escrow_shares_account, waiting to be burned on claim.\n */\n claimableShares: bigint;\n /** Asset value ready to claim (held in escrow_assets_account). */\n claimableAssets: bigint;\n /**\n * NAV ordering floor for the whole `pending_shares` aggregate, re-derived on\n * the MOST RECENT addition.\n *\n * Despite the name and the `i64` type this is NOT a wall-clock timestamp of\n * the addition: it stores `observed_nav_updated_at + 1`, i.e. one past the\n * NAV version in force when that addition was queued. It shares the\n * `nav_updated_at` number space, which is why the existing `>=` comparisons\n * in the program and the keeper keep working unchanged.\n *\n * `fulfill_withdrawal` prices all of `pending_shares` at once and requires\n * `nav_updated_at >= oldest_pending_at`, so this must track the newest\n * request, not the first: a first-request-only stamp lets every subsequent\n * addition settle against a NAV that predates it.\n *\n * NOTE: the field name is retained for wire/IDL compatibility — the keeper\n * reads it by name and orders fulfilment on it. Renaming it to\n * `newest_pending_at` is a follow-up that must land with a keeper change.\n *\n * The floor is derived from the NAV VERSION the request observed —\n * `lp_vault.nav_updated_at + 1` — not from the wall clock. Combined with\n * fulfilment's `nav_updated_at >= oldest_pending_at`, that requires a NAV\n * write STRICTLY NEWER than the one in force when the request was queued.\n *\n * KNOWN RESIDUAL — a newer VERSION does not prove a later VALUATION. An\n * `update_nav_checked` prepared BEFORE the request can still land after it:\n * its compare-and-set covers only `(nav, total_shares, nav_updated_at)`, and\n * a fee-free illiquid queue changes none of them. `apply_illiquid_withdrawal`\n * adds only `fee_shares` (zero here) to `total_shares` and moves\n * `pending_withdrawal_value`, which is NOT part of the CAS tuple — the\n * cross-chain path passes `fee_shares = 0` explicitly. So the prepared\n * update still validates, advances the timestamp past the floor, and\n * fulfilment settles against a valuation computed before the request.\n *\n * Two writers, two different bounds:\n *\n * - `update_nav_checked` — bounded by the publisher's prepare-to-publish\n * interval (`NAV_PUBLISH_INTENT_MAX_AGE_MS`, 120s in gamma-vault-agents),\n * because a prepared intent older than that is discarded client-side.\n * - `update_nav` (legacy, `handler`) — **UNBOUNDED**. It validates no\n * expected state and carries no age limit, so a valuation computed\n * arbitrarily long before the request can be published at any later time\n * and will advance `nav_updated_at` past the floor.\n *\n * This residual is still reachable WITHOUT any privileged actor: a holder\n * only has to queue between an honest publisher's prepare and its publish.\n * No compromised key and no operator error is required — only timing inside\n * that window. What the `+1` narrows is the SIZE of the window (from \"any\n * NAV after the first request on the receipt\" to \"the publisher's in-flight\n * interval\"), not the privilege needed to hit it.\n *\n * The legacy entrypoint is already slated for removal (gamma-vault-agents\n * calls only `update_nav_checked`, with no fallback, and the legacy client\n * helper has no callers). Deleting it closes the unbounded half of this\n * residual and should be sequenced with removing the web-server's\n * `/gamma/update-vault-nav` route.\n *\n * Either way this is strictly narrower than the pre-fix behaviour, which\n * accepted any NAV after the FIRST request on the receipt.\n *\n * Closing it requires the queue to invalidate in-flight NAV writes — i.e.\n * extending the CAS tuple with `pending_withdrawal_value` (or a receipt\n * version). That changes `update_nav_checked`'s signature, so it is a\n * coordinated program + IDL + agent + web-server change and an on-chain\n * upgrade; the agent calls `update_nav_checked` with no fallback, so a\n * required new argument breaks it against the deployed program until all\n * four ship together. Deliberately not bundled here.\n *\n * This needs no new state and no change to either comparison:\n * `next_nav_updated_at` already guarantees `nav_updated_at` strictly\n * increases on every NAV write (`max(clock_now, previous + 1)`), so\n * `observed + 1` is always reachable by the next write. It proves only that\n * the version ALREADY OBSERVED cannot settle the request — a stale\n * valuation that becomes the next write still passes, which is exactly the\n * residual above. The keeper's mirrored `>=` check keeps working unchanged.\n *\n * A wall-clock floor left a same-second hole: `Clock::unix_timestamp` is\n * second-resolution and the comparison is `>=`, so a NAV published earlier\n * in the same second as the request compared equal and passed.\n *\n * UPGRADE GATE — receipts already pending at the upgrade carry a LEGACY\n * floor. Accounts survive a program upgrade, and nothing re-stamps a\n * receipt until its next `withdraw`, so a receipt queued under the previous\n * release keeps a wall-clock, first-request-only value that\n * `fulfill_withdrawal` still accepts. Concretely: 1 share queued at T0,\n * NAV published at T1, an unrecorded loss, then 1,000,000 shares added —\n * all pre-upgrade — leaves the receipt at T0, and post-upgrade fulfilment\n * accepts the stale T1 NAV.\n *\n * Publishing a fresh NAV after the upgrade does NOT fix this: any NAV after\n * T0 satisfies a T0 floor, which is the whole defect. The gate is therefore\n * to DRAIN pending receipts before the upgrade, so no legacy floor survives\n * it.\n *\n * A scan alone is NOT sufficient: `withdraw` intake is permissionless, so a\n * user can create a fresh legacy-floor receipt between the scan and the\n * upgrade, and no off-chain maintenance mode can stop a direct transaction.\n *\n * There is no withdrawal pause flag for the native path — `withdrawals_enabled`\n * gates only the cross-chain intake, and zeroing the `WithdrawalPolicy` caps\n * REMOVES the limits rather than applying them. The one enforceable on-chain\n * lever is NAV staleness: `withdraw` begins with `require_fresh_nav`, so once\n * NAV ages past `nav_max_staleness` every new intake reverts with `StaleNav`.\n * `fulfill_withdrawal` requires fresh NAV too, so draining must finish first:\n *\n * 1. drain — fulfil until `pending_shares == 0` on EVERY receipt, with NAV\n * still being published. \"Every receipt\" means an on-chain\n * `getProgramAccounts` scan for `WithdrawReceipt` filtered by\n * `lp_vault`; the off-chain `gamma_pending_withdrawals` table is NOT a\n * valid inventory — it tracks only agent-managed parent-to-child Gamma\n * withdrawals for dedup and NAV enumeration, and omits ordinary user\n * and cross-chain receipts entirely;\n * 2. stop publishing NAV and wait out `nav_max_staleness` (1800s on prod\n * STBL1). New `withdraw` calls now revert on-chain, not by convention;\n * 3. RE-CHECK that every receipt is still at zero — nothing can have been\n * added during step 2;\n * 4. upgrade;\n * 5. resume NAV publication, which re-opens intake.\n *\n * No production pre-verification is claimed here: the scan in step 1 has not\n * been run, and the agent-side table cannot stand in for it. Steps 2 and 3\n * are required regardless, because the count can otherwise change under you.\n */\n oldestPendingAt: bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n};\n\nexport type WithdrawReceiptArgs = {\n /** User requesting withdrawal. */\n user: Address;\n /** Vault where the user has invested. */\n lpVault: Address;\n /**\n * Shares waiting for liquidity (keeper needs to fulfill these).\n * These shares are held in the escrow_shares_account.\n */\n pendingShares: number | bigint;\n /**\n * Shares that have been fulfilled and are ready to claim.\n * These shares are also in escrow_shares_account, waiting to be burned on claim.\n */\n claimableShares: number | bigint;\n /** Asset value ready to claim (held in escrow_assets_account). */\n claimableAssets: number | bigint;\n /**\n * NAV ordering floor for the whole `pending_shares` aggregate, re-derived on\n * the MOST RECENT addition.\n *\n * Despite the name and the `i64` type this is NOT a wall-clock timestamp of\n * the addition: it stores `observed_nav_updated_at + 1`, i.e. one past the\n * NAV version in force when that addition was queued. It shares the\n * `nav_updated_at` number space, which is why the existing `>=` comparisons\n * in the program and the keeper keep working unchanged.\n *\n * `fulfill_withdrawal` prices all of `pending_shares` at once and requires\n * `nav_updated_at >= oldest_pending_at`, so this must track the newest\n * request, not the first: a first-request-only stamp lets every subsequent\n * addition settle against a NAV that predates it.\n *\n * NOTE: the field name is retained for wire/IDL compatibility — the keeper\n * reads it by name and orders fulfilment on it. Renaming it to\n * `newest_pending_at` is a follow-up that must land with a keeper change.\n *\n * The floor is derived from the NAV VERSION the request observed —\n * `lp_vault.nav_updated_at + 1` — not from the wall clock. Combined with\n * fulfilment's `nav_updated_at >= oldest_pending_at`, that requires a NAV\n * write STRICTLY NEWER than the one in force when the request was queued.\n *\n * KNOWN RESIDUAL — a newer VERSION does not prove a later VALUATION. An\n * `update_nav_checked` prepared BEFORE the request can still land after it:\n * its compare-and-set covers only `(nav, total_shares, nav_updated_at)`, and\n * a fee-free illiquid queue changes none of them. `apply_illiquid_withdrawal`\n * adds only `fee_shares` (zero here) to `total_shares` and moves\n * `pending_withdrawal_value`, which is NOT part of the CAS tuple — the\n * cross-chain path passes `fee_shares = 0` explicitly. So the prepared\n * update still validates, advances the timestamp past the floor, and\n * fulfilment settles against a valuation computed before the request.\n *\n * Two writers, two different bounds:\n *\n * - `update_nav_checked` — bounded by the publisher's prepare-to-publish\n * interval (`NAV_PUBLISH_INTENT_MAX_AGE_MS`, 120s in gamma-vault-agents),\n * because a prepared intent older than that is discarded client-side.\n * - `update_nav` (legacy, `handler`) — **UNBOUNDED**. It validates no\n * expected state and carries no age limit, so a valuation computed\n * arbitrarily long before the request can be published at any later time\n * and will advance `nav_updated_at` past the floor.\n *\n * This residual is still reachable WITHOUT any privileged actor: a holder\n * only has to queue between an honest publisher's prepare and its publish.\n * No compromised key and no operator error is required — only timing inside\n * that window. What the `+1` narrows is the SIZE of the window (from \"any\n * NAV after the first request on the receipt\" to \"the publisher's in-flight\n * interval\"), not the privilege needed to hit it.\n *\n * The legacy entrypoint is already slated for removal (gamma-vault-agents\n * calls only `update_nav_checked`, with no fallback, and the legacy client\n * helper has no callers). Deleting it closes the unbounded half of this\n * residual and should be sequenced with removing the web-server's\n * `/gamma/update-vault-nav` route.\n *\n * Either way this is strictly narrower than the pre-fix behaviour, which\n * accepted any NAV after the FIRST request on the receipt.\n *\n * Closing it requires the queue to invalidate in-flight NAV writes — i.e.\n * extending the CAS tuple with `pending_withdrawal_value` (or a receipt\n * version). That changes `update_nav_checked`'s signature, so it is a\n * coordinated program + IDL + agent + web-server change and an on-chain\n * upgrade; the agent calls `update_nav_checked` with no fallback, so a\n * required new argument breaks it against the deployed program until all\n * four ship together. Deliberately not bundled here.\n *\n * This needs no new state and no change to either comparison:\n * `next_nav_updated_at` already guarantees `nav_updated_at` strictly\n * increases on every NAV write (`max(clock_now, previous + 1)`), so\n * `observed + 1` is always reachable by the next write. It proves only that\n * the version ALREADY OBSERVED cannot settle the request — a stale\n * valuation that becomes the next write still passes, which is exactly the\n * residual above. The keeper's mirrored `>=` check keeps working unchanged.\n *\n * A wall-clock floor left a same-second hole: `Clock::unix_timestamp` is\n * second-resolution and the comparison is `>=`, so a NAV published earlier\n * in the same second as the request compared equal and passed.\n *\n * UPGRADE GATE — receipts already pending at the upgrade carry a LEGACY\n * floor. Accounts survive a program upgrade, and nothing re-stamps a\n * receipt until its next `withdraw`, so a receipt queued under the previous\n * release keeps a wall-clock, first-request-only value that\n * `fulfill_withdrawal` still accepts. Concretely: 1 share queued at T0,\n * NAV published at T1, an unrecorded loss, then 1,000,000 shares added —\n * all pre-upgrade — leaves the receipt at T0, and post-upgrade fulfilment\n * accepts the stale T1 NAV.\n *\n * Publishing a fresh NAV after the upgrade does NOT fix this: any NAV after\n * T0 satisfies a T0 floor, which is the whole defect. The gate is therefore\n * to DRAIN pending receipts before the upgrade, so no legacy floor survives\n * it.\n *\n * A scan alone is NOT sufficient: `withdraw` intake is permissionless, so a\n * user can create a fresh legacy-floor receipt between the scan and the\n * upgrade, and no off-chain maintenance mode can stop a direct transaction.\n *\n * There is no withdrawal pause flag for the native path — `withdrawals_enabled`\n * gates only the cross-chain intake, and zeroing the `WithdrawalPolicy` caps\n * REMOVES the limits rather than applying them. The one enforceable on-chain\n * lever is NAV staleness: `withdraw` begins with `require_fresh_nav`, so once\n * NAV ages past `nav_max_staleness` every new intake reverts with `StaleNav`.\n * `fulfill_withdrawal` requires fresh NAV too, so draining must finish first:\n *\n * 1. drain — fulfil until `pending_shares == 0` on EVERY receipt, with NAV\n * still being published. \"Every receipt\" means an on-chain\n * `getProgramAccounts` scan for `WithdrawReceipt` filtered by\n * `lp_vault`; the off-chain `gamma_pending_withdrawals` table is NOT a\n * valid inventory — it tracks only agent-managed parent-to-child Gamma\n * withdrawals for dedup and NAV enumeration, and omits ordinary user\n * and cross-chain receipts entirely;\n * 2. stop publishing NAV and wait out `nav_max_staleness` (1800s on prod\n * STBL1). New `withdraw` calls now revert on-chain, not by convention;\n * 3. RE-CHECK that every receipt is still at zero — nothing can have been\n * added during step 2;\n * 4. upgrade;\n * 5. resume NAV publication, which re-opens intake.\n *\n * No production pre-verification is claimed here: the scan in step 1 has not\n * been run, and the agent-side table cannot stand in for it. Steps 2 and 3\n * are required regardless, because the count can otherwise change under you.\n */\n oldestPendingAt: number | bigint;\n /** PDA derivation bump, stored for CU saving purposes. */\n bump: number;\n};\n\n/** Gets the encoder for {@link WithdrawReceiptArgs} account data. */\nexport function getWithdrawReceiptEncoder(): FixedSizeEncoder<WithdrawReceiptArgs> {\n return transformEncoder(\n getStructEncoder([\n [\"discriminator\", fixEncoderSize(getBytesEncoder(), 8)],\n [\"user\", getAddressEncoder()],\n [\"lpVault\", getAddressEncoder()],\n [\"pendingShares\", getU64Encoder()],\n [\"claimableShares\", getU64Encoder()],\n [\"claimableAssets\", getU64Encoder()],\n [\"oldestPendingAt\", getI64Encoder()],\n [\"bump\", getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: WITHDRAW_RECEIPT_DISCRIMINATOR })\n );\n}\n\n/** Gets the decoder for {@link WithdrawReceipt} account data. */\nexport function getWithdrawReceiptDecoder(): FixedSizeDecoder<WithdrawReceipt> {\n return getStructDecoder([\n [\"discriminator\", fixDecoderSize(getBytesDecoder(), 8)],\n [\"user\", getAddressDecoder()],\n [\"lpVault\", getAddressDecoder()],\n [\"pendingShares\", getU64Decoder()],\n [\"claimableShares\", getU64Decoder()],\n [\"claimableAssets\", getU64Decoder()],\n [\"oldestPendingAt\", getI64Decoder()],\n [\"bump\", getU8Decoder()],\n ]);\n}\n\n/** Gets the codec for {@link WithdrawReceipt} account data. */\nexport function getWithdrawReceiptCodec(): FixedSizeCodec<WithdrawReceiptArgs, WithdrawReceipt> {\n return combineCodec(getWithdrawReceiptEncoder(), getWithdrawReceiptDecoder());\n}\n\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<WithdrawReceipt, TAddress>;\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<WithdrawReceipt, TAddress>;\nexport function decodeWithdrawReceipt<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n): Account<WithdrawReceipt, TAddress> | MaybeAccount<WithdrawReceipt, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getWithdrawReceiptDecoder()\n );\n}\n\nexport async function fetchWithdrawReceipt<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<WithdrawReceipt, TAddress>> {\n const maybeAccount = await fetchMaybeWithdrawReceipt(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeWithdrawReceipt<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<WithdrawReceipt, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeWithdrawReceipt(maybeAccount);\n}\n\nexport async function fetchAllWithdrawReceipt(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<WithdrawReceipt>[]> {\n const maybeAccounts = await fetchAllMaybeWithdrawReceipt(rpc, addresses, config);\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeWithdrawReceipt(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<WithdrawReceipt>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) => decodeWithdrawReceipt(maybeAccount));\n}\n\nexport function getWithdrawReceiptSize(): number {\n return 105;\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type CompleteWithdrawalWithdrawEscrowSeeds = {\n user: Address;\n lpVault: Address;\n};\n\nexport async function findCompleteWithdrawalWithdrawEscrowPda(\n seeds: CompleteWithdrawalWithdrawEscrowSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([119, 105, 116, 104, 100, 114, 97, 119, 95, 101, 115, 99, 114, 111, 119])\n ),\n getAddressEncoder().encode(seeds.user),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type DepositPolicySeeds = {\n lpVault: Address;\n};\n\nexport async function findDepositPolicyPda(\n seeds: DepositPolicySeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([100, 101, 112, 111, 115, 105, 116, 95, 112, 111, 108, 105, 99, 121])\n ),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type WithdrawalPolicySeeds = {\n lpVault: Address;\n};\n\nexport async function findWithdrawalPolicyPda(\n seeds: WithdrawalPolicySeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([\n 119, 105, 116, 104, 100, 114, 97, 119, 97, 108, 95, 112, 111, 108, 105, 99, 121,\n ])\n ),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from \"@solana/kit\";\n\nexport type WithdrawReceiptSeeds = {\n crossChainWithdrawer: Address;\n lpVault: Address;\n};\n\nexport async function findWithdrawReceiptPda(\n seeds: WithdrawReceiptSeeds,\n config: { programAddress?: Address | undefined } = {}\n): Promise<ProgramDerivedAddress> {\n const {\n programAddress = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">,\n } = config;\n return await getProgramDerivedAddress({\n programAddress,\n seeds: [\n getBytesEncoder().encode(\n new Uint8Array([\n 119, 105, 116, 104, 100, 114, 97, 119, 95, 114, 101, 99, 101, 105, 112, 116,\n ])\n ),\n getAddressEncoder().encode(seeds.crossChainWithdrawer),\n getAddressEncoder().encode(seeds.lpVault),\n ],\n });\n}\n","/**\n * This code was AUTOGENERATED using the Codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun Codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n assertIsInstructionWithAccounts,\n containsBytes,\n extendClient,\n fixEncoderSize,\n getBytesEncoder,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT,\n SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION,\n SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE,\n SolanaError,\n type Address,\n type ClientWithRpc,\n type ClientWithTransactionPlanning,\n type ClientWithTransactionSending,\n type ExtendedClient,\n type GetAccountInfoApi,\n type GetMultipleAccountsApi,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from \"@solana/kit\";\nimport {\n addSelfFetchFunctions,\n addSelfPlanAndSendFunctions,\n type SelfFetchFunctions,\n type SelfPlanAndSendFunctions,\n} from \"@solana/kit/program-client-core\";\nimport {\n getDepositPolicyCodec,\n getLpVaultCodec,\n getWithdrawalPolicyCodec,\n getWithdrawReceiptCodec,\n type DepositPolicy,\n type DepositPolicyArgs,\n type LpVault,\n type LpVaultArgs,\n type WithdrawalPolicy,\n type WithdrawalPolicyArgs,\n type WithdrawReceipt,\n type WithdrawReceiptArgs,\n} from \"../accounts\";\nimport {\n getCompleteWithdrawalInstructionAsync,\n getDepositInstructionAsync,\n getWithdrawInstructionAsync,\n parseCompleteWithdrawalInstruction,\n parseDepositInstruction,\n parseWithdrawInstruction,\n type CompleteWithdrawalAsyncInput,\n type DepositAsyncInput,\n type ParsedCompleteWithdrawalInstruction,\n type ParsedDepositInstruction,\n type ParsedWithdrawInstruction,\n type WithdrawAsyncInput,\n} from \"../instructions\";\nimport {\n findAssetsAccountPda,\n findCompleteWithdrawalWithdrawEscrowPda,\n findCompleteWithdrawalWithdrawReceiptPda,\n findCrossChainConfigPda,\n findCrossChainDepositAndBridgeDepositReceiptPda,\n findCrossChainIntentPda,\n findCrossChainSenderPda,\n findCrossChainVaultRoutePda,\n findCrossChainWithdrawerPda,\n findDepositPolicyPda,\n findDepositReceiptPda,\n findGlobalConfigPda,\n findLpVaultPda,\n findNavUpdatePolicyPda,\n findPendingSharesAccountPda,\n findReceiveCrossChainWithdrawalCrossChainIntentPda,\n findSharesMintPda,\n findWithdrawalPolicyPda,\n findWithdrawEscrowPda,\n findWithdrawReceiptPda,\n} from \"../pdas\";\n\nexport const GAMMA_VAULT_PROGRAM_ADDRESS =\n \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\" as Address<\"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\">;\n\nexport enum GammaVaultAccount {\n DepositPolicy,\n LpVault,\n WithdrawReceipt,\n WithdrawalPolicy,\n}\n\nexport function identifyGammaVaultAccount(\n account: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): GammaVaultAccount {\n const data = \"data\" in account ? account.data : account;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([159, 243, 65, 242, 81, 27, 41, 167])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.DepositPolicy;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([189, 45, 167, 23, 91, 118, 105, 190])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.LpVault;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([132, 238, 44, 182, 207, 9, 124, 140])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.WithdrawReceipt;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([52, 231, 68, 59, 247, 250, 119, 244])\n ),\n 0\n )\n ) {\n return GammaVaultAccount.WithdrawalPolicy;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_ACCOUNT, {\n accountData: data,\n programName: \"gammaVault\",\n });\n}\n\nexport enum GammaVaultInstruction {\n CompleteWithdrawal,\n Deposit,\n Withdraw,\n}\n\nexport function identifyGammaVaultInstruction(\n instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array\n): GammaVaultInstruction {\n const data = \"data\" in instruction ? instruction.data : instruction;\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([107, 98, 134, 131, 74, 120, 174, 121])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.CompleteWithdrawal;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([242, 35, 198, 137, 82, 225, 242, 182])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.Deposit;\n }\n if (\n containsBytes(\n data,\n fixEncoderSize(getBytesEncoder(), 8).encode(\n new Uint8Array([183, 18, 70, 156, 148, 109, 161, 34])\n ),\n 0\n )\n ) {\n return GammaVaultInstruction.Withdraw;\n }\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__FAILED_TO_IDENTIFY_INSTRUCTION, {\n instructionData: data,\n programName: \"gammaVault\",\n });\n}\n\nexport type ParsedGammaVaultInstruction<\n TProgram extends string = \"GaMmanX9i4jGmqDZZD2tbD6B2v9p21btenPneMXnTczV\",\n> =\n | ({\n instructionType: GammaVaultInstruction.CompleteWithdrawal;\n } & ParsedCompleteWithdrawalInstruction<TProgram>)\n | ({ instructionType: GammaVaultInstruction.Deposit } & ParsedDepositInstruction<TProgram>)\n | ({ instructionType: GammaVaultInstruction.Withdraw } & ParsedWithdrawInstruction<TProgram>);\n\nexport function parseGammaVaultInstruction<TProgram extends string>(\n instruction: Instruction<TProgram> & InstructionWithData<ReadonlyUint8Array>\n): ParsedGammaVaultInstruction<TProgram> {\n const instructionType = identifyGammaVaultInstruction(instruction);\n switch (instructionType) {\n case GammaVaultInstruction.CompleteWithdrawal: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.CompleteWithdrawal,\n ...parseCompleteWithdrawalInstruction(instruction),\n };\n }\n case GammaVaultInstruction.Deposit: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.Deposit,\n ...parseDepositInstruction(instruction),\n };\n }\n case GammaVaultInstruction.Withdraw: {\n assertIsInstructionWithAccounts(instruction);\n return {\n instructionType: GammaVaultInstruction.Withdraw,\n ...parseWithdrawInstruction(instruction),\n };\n }\n default:\n throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__UNRECOGNIZED_INSTRUCTION_TYPE, {\n instructionType: instructionType as string,\n programName: \"gammaVault\",\n });\n }\n}\n\nexport type GammaVaultPlugin = {\n accounts: GammaVaultPluginAccounts;\n instructions: GammaVaultPluginInstructions;\n pdas: GammaVaultPluginPdas;\n identifyAccount: typeof identifyGammaVaultAccount;\n identifyInstruction: typeof identifyGammaVaultInstruction;\n parseInstruction: typeof parseGammaVaultInstruction;\n};\n\nexport type GammaVaultPluginAccounts = {\n depositPolicy: ReturnType<typeof getDepositPolicyCodec> &\n SelfFetchFunctions<DepositPolicyArgs, DepositPolicy>;\n lpVault: ReturnType<typeof getLpVaultCodec> & SelfFetchFunctions<LpVaultArgs, LpVault>;\n withdrawReceipt: ReturnType<typeof getWithdrawReceiptCodec> &\n SelfFetchFunctions<WithdrawReceiptArgs, WithdrawReceipt>;\n withdrawalPolicy: ReturnType<typeof getWithdrawalPolicyCodec> &\n SelfFetchFunctions<WithdrawalPolicyArgs, WithdrawalPolicy>;\n};\n\nexport type GammaVaultPluginInstructions = {\n completeWithdrawal: (\n input: CompleteWithdrawalAsyncInput\n ) => ReturnType<typeof getCompleteWithdrawalInstructionAsync> & SelfPlanAndSendFunctions;\n deposit: (\n input: DepositAsyncInput\n ) => ReturnType<typeof getDepositInstructionAsync> & SelfPlanAndSendFunctions;\n withdraw: (\n input: WithdrawAsyncInput\n ) => ReturnType<typeof getWithdrawInstructionAsync> & SelfPlanAndSendFunctions;\n};\n\nexport type GammaVaultPluginPdas = {\n crossChainWithdrawer: typeof findCrossChainWithdrawerPda;\n withdrawReceipt: typeof findWithdrawReceiptPda;\n withdrawEscrow: typeof findWithdrawEscrowPda;\n depositReceipt: typeof findDepositReceiptPda;\n completeWithdrawalWithdrawEscrow: typeof findCompleteWithdrawalWithdrawEscrowPda;\n completeWithdrawalWithdrawReceipt: typeof findCompleteWithdrawalWithdrawReceiptPda;\n crossChainConfig: typeof findCrossChainConfigPda;\n crossChainVaultRoute: typeof findCrossChainVaultRoutePda;\n crossChainIntent: typeof findCrossChainIntentPda;\n crossChainSender: typeof findCrossChainSenderPda;\n crossChainDepositAndBridgeDepositReceipt: typeof findCrossChainDepositAndBridgeDepositReceiptPda;\n withdrawalPolicy: typeof findWithdrawalPolicyPda;\n depositPolicy: typeof findDepositPolicyPda;\n globalConfig: typeof findGlobalConfigPda;\n navUpdatePolicy: typeof findNavUpdatePolicyPda;\n lpVault: typeof findLpVaultPda;\n sharesMint: typeof findSharesMintPda;\n assetsAccount: typeof findAssetsAccountPda;\n pendingSharesAccount: typeof findPendingSharesAccountPda;\n receiveCrossChainWithdrawalCrossChainIntent: typeof findReceiveCrossChainWithdrawalCrossChainIntentPda;\n};\n\nexport type GammaVaultPluginRequirements = ClientWithRpc<\n GetAccountInfoApi & GetMultipleAccountsApi\n> &\n ClientWithTransactionPlanning &\n ClientWithTransactionSending;\n\nexport function gammaVaultProgram() {\n return <T extends GammaVaultPluginRequirements>(\n client: T\n ): ExtendedClient<T, { gammaVault: GammaVaultPlugin }> => {\n return extendClient(client, {\n gammaVault: <GammaVaultPlugin>{\n accounts: {\n depositPolicy: addSelfFetchFunctions(client, getDepositPolicyCodec()),\n lpVault: addSelfFetchFunctions(client, getLpVaultCodec()),\n withdrawReceipt: addSelfFetchFunctions(client, getWithdrawReceiptCodec()),\n withdrawalPolicy: addSelfFetchFunctions(client, getWithdrawalPolicyCodec()),\n },\n instructions: {\n completeWithdrawal: (input) =>\n addSelfPlanAndSendFunctions(client, getCompleteWithdrawalInstructionAsync(input)),\n deposit: (input) =>\n addSelfPlanAndSendFunctions(client, getDepositInstructionAsync(input)),\n withdraw: (input) =>\n addSelfPlanAndSendFunctions(client, getWithdrawInstructionAsync(input)),\n },\n pdas: {\n crossChainWithdrawer: findCrossChainWithdrawerPda,\n withdrawReceipt: findWithdrawReceiptPda,\n withdrawEscrow: findWithdrawEscrowPda,\n depositReceipt: findDepositReceiptPda,\n completeWithdrawalWithdrawEscrow: findCompleteWithdrawalWithdrawEscrowPda,\n completeWithdrawalWithdrawReceipt: findCompleteWithdrawalWithdrawReceiptPda,\n crossChainConfig: findCrossChainConfigPda,\n crossChainVaultRoute: findCrossChainVaultRoutePda,\n crossChainIntent: findCrossChainIntentPda,\n crossChainSender: findCrossChainSenderPda,\n crossChainDepositAndBridgeDepositReceipt: findCrossChainDepositAndBridgeDepositReceiptPda,\n withdrawalPolicy: findWithdrawalPolicyPda,\n depositPolicy: findDepositPolicyPda,\n globalConfig: findGlobalConfigPda,\n navUpdatePolicy: findNavUpdatePolicyPda,\n lpVault: findLpVaultPda,\n sharesMint: findSharesMintPda,\n assetsAccount: findAssetsAccountPda,\n pendingSharesAccount: findPendingSharesAccountPda,\n receiveCrossChainWithdrawalCrossChainIntent:\n findReceiveCrossChainWithdrawalCrossChainIntentPda,\n },\n identifyAccount: identifyGammaVaultAccount,\n identifyInstruction: identifyGammaVaultInstruction,\n parseInstruction: parseGammaVaultInstruction,\n },\n });\n };\n}\n","import type { Address, ProgramDerivedAddress, ReadonlyUint8Array } from \"@solana/kit\";\n\nimport { decodeAccountData } from \"../account-data\";\n\nimport type {\n GammaDepositPolicy,\n GammaLpVault,\n GammaWithdrawalPolicy,\n GammaWithdrawReceipt,\n} from \"./types\";\n\nimport {\n DEPOSIT_POLICY_DISCRIMINATOR,\n findCompleteWithdrawalWithdrawEscrowPda,\n findDepositPolicyPda,\n findWithdrawalPolicyPda,\n findWithdrawReceiptPda,\n getDepositPolicyDecoder,\n getLpVaultDecoder,\n getWithdrawalPolicyDecoder,\n getWithdrawReceiptDecoder,\n LP_VAULT_DISCRIMINATOR,\n WITHDRAWAL_POLICY_DISCRIMINATOR,\n WITHDRAW_RECEIPT_DISCRIMINATOR,\n} from \"~/generated/gamma\";\n\nexport { GAMMA_VAULT_PROGRAM_ADDRESS } from \"~/generated/gamma\";\n\n/**\n * Decodes a Gamma `LpVault` account.\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaLpVault(data: ReadonlyUint8Array): GammaLpVault {\n return decodeAccountData(data, LP_VAULT_DISCRIMINATOR, getLpVaultDecoder(), \"Gamma LpVault\");\n}\n\n/**\n * Decodes a Gamma `WithdrawReceipt` account (a user's pending → claimable withdrawal).\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaWithdrawReceipt(data: ReadonlyUint8Array): GammaWithdrawReceipt {\n return decodeAccountData(\n data,\n WITHDRAW_RECEIPT_DISCRIMINATOR,\n getWithdrawReceiptDecoder(),\n \"Gamma WithdrawReceipt\"\n );\n}\n\n/**\n * Decodes a Gamma `DepositPolicy` account (a vault's deposit cap + pause switch).\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaDepositPolicy(data: ReadonlyUint8Array): GammaDepositPolicy {\n return decodeAccountData(\n data,\n DEPOSIT_POLICY_DISCRIMINATOR,\n getDepositPolicyDecoder(),\n \"Gamma DepositPolicy\"\n );\n}\n\n/**\n * Decodes a Gamma `WithdrawalPolicy` account (a vault's withdrawal fee + rolling caps).\n * @throws if the discriminator doesn't match\n */\nexport function decodeGammaWithdrawalPolicy(data: ReadonlyUint8Array): GammaWithdrawalPolicy {\n return decodeAccountData(\n data,\n WITHDRAWAL_POLICY_DISCRIMINATOR,\n getWithdrawalPolicyDecoder(),\n \"Gamma WithdrawalPolicy\"\n );\n}\n\n/** `lpVault`'s deposit policy PDA. */\nexport function deriveGammaDepositPolicy(lpVault: Address): Promise<ProgramDerivedAddress> {\n return findDepositPolicyPda({ lpVault });\n}\n\n/** `lpVault`'s withdrawal policy PDA. */\nexport function deriveGammaWithdrawalPolicy(lpVault: Address): Promise<ProgramDerivedAddress> {\n return findWithdrawalPolicyPda({ lpVault });\n}\n\n/** `user`'s withdraw receipt PDA for `lpVault`. */\nexport function deriveGammaWithdrawReceipt(\n user: Address,\n lpVault: Address\n): Promise<ProgramDerivedAddress> {\n return findWithdrawReceiptPda({ crossChainWithdrawer: user, lpVault });\n}\n\n/** `user`'s withdraw escrow PDA for `lpVault` (owner of the escrow token accounts). */\nexport function deriveGammaWithdrawEscrow(\n user: Address,\n lpVault: Address\n): Promise<ProgramDerivedAddress> {\n return findCompleteWithdrawalWithdrawEscrowPda({ user, lpVault });\n}\n","// Minimal Titan V1 WebSocket client — vendored from @titanexchange/sdk-ts\n// Source: https://github.com/Titan-Pathfinder/titan-sdk-ts (MIT)\n//\n// Differences from upstream:\n// - No compression (negotiates only \"v1.api.titan.ag\" subprotocol)\n// - Uses `ws` package instead of `websocket`\n// - Only implements connect, newSwapQuoteStream, stopStream, close\n\nimport { Encoder, Decoder } from \"@msgpack/msgpack\";\nimport WebSocket from \"ws\";\n\nimport type {\n ClientRequest,\n SwapQuoteRequest,\n ServerMessage,\n ResponseSuccess,\n ResponseError,\n StreamData,\n StreamEnd,\n SwapQuotes,\n QuoteSwapStreamResponse,\n StopStreamResponse,\n} from \"./types\";\n\nconst SUBPROTOCOL = \"v1.api.titan.ag\";\nconst UINT64_MAX = (1n << 64n) - 1n;\n\nfunction toBigInt(value: number | bigint): bigint {\n if (typeof value === \"bigint\") {\n if (value < 0n || value > UINT64_MAX) {\n throw new RangeError(`Amount out of uint64 range: ${value}`);\n }\n return value;\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`Amount must be a whole number, got ${value}`);\n }\n if (value < 0) {\n throw new RangeError(`Amount must be non-negative, got ${value}`);\n }\n return BigInt(value);\n}\n\n// --- Error classes ---\n\nexport class ConnectionClosed extends Error {\n code: number;\n reason: string;\n\n constructor(code: number, reason: string) {\n super(`Client WebSocket closed with code ${code}: ${reason}`);\n this.name = \"ConnectionClosed\";\n Object.setPrototypeOf(this, ConnectionClosed.prototype);\n this.code = code;\n this.reason = reason;\n }\n}\n\nexport class ErrorResponse extends Error {\n response: ResponseError;\n\n constructor(response: ResponseError) {\n super(`Request ${response.requestId} failed with code ${response.code}: ${response.message}`);\n this.name = \"ErrorResponse\";\n Object.setPrototypeOf(this, ErrorResponse.prototype);\n this.response = response;\n }\n}\n\nexport class StreamError extends Error {\n streamId: number;\n errorCode: number;\n errorMessage: string;\n\n constructor(packet: StreamEnd) {\n const code = packet.errorCode ?? 0;\n const message = packet.errorMessage ?? \"\";\n super(`Stream ${packet.id} ended with error code ${code}: ${message}`);\n this.name = \"StreamError\";\n Object.setPrototypeOf(this, StreamError.prototype);\n this.streamId = packet.id;\n this.errorCode = code;\n this.errorMessage = message;\n }\n}\n\n// --- Response handler types ---\n\nexport interface ResponseWithStream<T, D> {\n response: T;\n stream: ReadableStream<D>;\n streamId: number;\n}\n\ntype Resolver<T> = (value: T | PromiseLike<T>) => void;\ntype Rejector = (reason?: unknown) => void;\n\ninterface PendingRequest {\n resolve: Resolver<unknown>;\n reject: Rejector;\n kind: \"NewSwapQuoteStream\" | \"StopStream\";\n}\n\n// --- Codec (msgpack, no compression) ---\n\nconst encoder = new Encoder({ useBigInt64: true });\nconst decoder = new Decoder({ useBigInt64: true });\n\n// --- V1Client ---\n\nexport class V1Client {\n private socket: WebSocket;\n private nextId = 0;\n private _closed = false;\n private _closing = false;\n\n private pending = new Map<number, PendingRequest>();\n private streams = new Map<number, ReadableStreamDefaultController<SwapQuotes>>();\n private streamStopping = new Map<number, boolean>();\n private closeListeners: { resolve: Resolver<void>; reject: Rejector }[] = [];\n\n // --- Static connect ---\n\n static connect(url: string): Promise<V1Client> {\n return new Promise<V1Client>((resolve, reject) => {\n const ws = new WebSocket(url, [SUBPROTOCOL]);\n\n ws.binaryType = \"arraybuffer\";\n\n const onOpen = () => {\n // ws doesn't populate .protocol when using the `ws` library in Node\n // but since we only offer one subprotocol, the server must accept it.\n ws.off(\"error\", onError);\n ws.off(\"close\", onClose);\n resolve(new V1Client(ws));\n };\n const onError = (err: Error) => {\n ws.off(\"open\", onOpen);\n ws.off(\"close\", onClose);\n reject(err);\n };\n // Guard against the socket closing before `open` fires without a\n // preceding `error` (e.g. a clean close during handshake). Without this\n // the promise would hang forever.\n const onClose = (code: number, reason: Buffer) => {\n ws.off(\"open\", onOpen);\n ws.off(\"error\", onError);\n reject(\n new Error(\n `WebSocket closed before open (code=${code}${\n reason.length ? `, reason=${reason.toString()}` : \"\"\n })`\n )\n );\n };\n\n ws.once(\"open\", onOpen);\n ws.once(\"error\", onError);\n ws.once(\"close\", onClose);\n });\n }\n\n // --- Constructor ---\n\n private constructor(socket: WebSocket) {\n this.socket = socket;\n\n this.socket.on(\"message\", (data: WebSocket.RawData) => {\n this.handleMessage(data);\n });\n this.socket.on(\"close\", (code: number, reason: Buffer) => {\n this.handleClose(code, reason.toString());\n });\n this.socket.on(\"error\", (err: Error) => {\n this.handleError(err);\n });\n }\n\n private nextRequestId(): number {\n return this.nextId++;\n }\n\n // --- Public API ---\n\n public get closed(): boolean {\n return this._closed;\n }\n\n public close(): Promise<void> {\n if (this._closed) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n this.closeListeners.push({ resolve, reject });\n if (!this._closing) {\n this._closing = true;\n this.socket.close();\n }\n });\n }\n\n public newSwapQuoteStream(\n params: SwapQuoteRequest\n ): Promise<ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes>> {\n const requestId = this.nextRequestId();\n\n const promise = new Promise<ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes>>(\n (resolve, reject) => {\n this.pending.set(requestId, {\n resolve: resolve as Resolver<unknown>,\n reject,\n kind: \"NewSwapQuoteStream\",\n });\n }\n );\n\n const normalized: SwapQuoteRequest = {\n ...params,\n swap: { ...params.swap, amount: toBigInt(params.swap.amount) },\n };\n\n const message: ClientRequest = {\n id: requestId,\n data: { NewSwapQuoteStream: normalized },\n };\n this.send(message);\n\n return promise;\n }\n\n public stopStream(streamId: number): Promise<StopStreamResponse> {\n const requestId = this.nextRequestId();\n\n const promise = new Promise<StopStreamResponse>((resolve, reject) => {\n this.pending.set(requestId, {\n resolve: resolve as Resolver<unknown>,\n reject,\n kind: \"StopStream\",\n });\n });\n\n const message: ClientRequest = {\n id: requestId,\n data: { StopStream: { id: streamId } },\n };\n this.send(message);\n\n return promise;\n }\n\n // --- Send ---\n\n private send(message: ClientRequest): void {\n try {\n const encoded = encoder.encode(message);\n this.socket.send(encoded);\n } catch (err) {\n const req = this.pending.get(message.id);\n if (req) {\n this.pending.delete(message.id);\n req.reject(err);\n }\n }\n }\n\n // --- Message handling ---\n\n private handleMessage(raw: WebSocket.RawData): void {\n let buf: Uint8Array;\n if (raw instanceof ArrayBuffer) {\n buf = new Uint8Array(raw);\n } else if (Buffer.isBuffer(raw)) {\n buf = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n } else if (Array.isArray(raw)) {\n buf = new Uint8Array(Buffer.concat(raw));\n } else {\n return;\n }\n\n let message: ServerMessage;\n try {\n message = decoder.decode(buf) as ServerMessage;\n } catch {\n this.socket.close(3002, \"failed to decode message\");\n return;\n }\n\n if (\"Response\" in message) {\n this.handleResponse(message.Response);\n } else if (\"Error\" in message) {\n this.handleResponseError(message.Error);\n } else if (\"StreamData\" in message) {\n this.handleStreamData(message.StreamData);\n } else if (\"StreamEnd\" in message) {\n this.handleStreamEnd(message.StreamEnd);\n }\n }\n\n private handleResponse(msg: ResponseSuccess): void {\n const req = this.pending.get(msg.requestId);\n if (!req) return;\n this.pending.delete(msg.requestId);\n\n if (\"NewSwapQuoteStream\" in msg.data && req.kind === \"NewSwapQuoteStream\") {\n const streamInfo = msg.stream;\n if (!streamInfo) {\n req.reject(new Error(\"No stream associated with NewSwapQuoteStream response\"));\n return;\n }\n const stream = new ReadableStream<SwapQuotes>({\n start: (controller) => {\n this.streams.set(streamInfo.id, controller);\n },\n cancel: () => {\n return this.cancelStream(streamInfo.id);\n },\n });\n const result: ResponseWithStream<QuoteSwapStreamResponse, SwapQuotes> = {\n response: msg.data.NewSwapQuoteStream,\n stream,\n streamId: streamInfo.id,\n };\n req.resolve(result);\n } else if (\"StreamStopped\" in msg.data && req.kind === \"StopStream\") {\n req.resolve(msg.data.StreamStopped);\n } else {\n req.reject(new Error(`Unexpected response type for ${req.kind}`));\n }\n }\n\n private handleResponseError(error: ResponseError): void {\n const req = this.pending.get(error.requestId);\n if (!req) return;\n this.pending.delete(error.requestId);\n req.reject(new ErrorResponse(error));\n }\n\n private handleStreamData(packet: StreamData): void {\n const controller = this.streams.get(packet.id);\n if (!controller) return;\n if (packet.payload.SwapQuotes !== undefined) {\n controller.enqueue(packet.payload.SwapQuotes);\n }\n }\n\n private handleStreamEnd(packet: StreamEnd): void {\n const controller = this.streams.get(packet.id);\n if (!controller) return;\n this.streams.delete(packet.id);\n this.streamStopping.delete(packet.id);\n\n if (packet.errorCode !== undefined) {\n controller.error(new StreamError(packet));\n } else {\n controller.close();\n }\n }\n\n private async cancelStream(streamId: number): Promise<void> {\n if (this.streamStopping.get(streamId) || !this.streams.has(streamId)) return;\n this.streamStopping.set(streamId, true);\n await this.stopStream(streamId);\n }\n\n // --- Connection lifecycle ---\n\n private rejectAll(error: Error): void {\n for (const req of this.pending.values()) {\n req.reject(error);\n }\n this.pending.clear();\n for (const controller of this.streams.values()) {\n controller.error(error);\n }\n this.streams.clear();\n this.streamStopping.clear();\n }\n\n private handleClose(code: number, reason: string): void {\n this._closed = true;\n this.rejectAll(new ConnectionClosed(code, reason));\n for (const listener of this.closeListeners) {\n listener.resolve();\n }\n this.closeListeners = [];\n }\n\n private handleError(err: Error): void {\n this.rejectAll(err);\n this.socket.close(3002);\n }\n}\n","// Vendored Titan protocol types — cherry-picked from @titanexchange/sdk-ts\n// Source: https://github.com/Titan-Pathfinder/titan-sdk-ts (MIT)\n\n// --- Common types ---\n\n/** A Solana account public key, encoded as 32 bytes by msgpack. */\nexport type Pubkey = Uint8Array;\n\n/** Solana account metadata for an instruction. */\nexport interface AccountMeta {\n /** Public key for the account. */\n p: Pubkey;\n /** Whether the account is a signer. */\n s: boolean;\n /** Whether the account is writable. */\n w: boolean;\n}\n\n/** A single instruction to be executed as part of a transaction. */\nexport interface Instruction {\n /** Program id. */\n p: Pubkey;\n /** Account metadata. */\n a: AccountMeta[];\n /** Instruction data. */\n d: Uint8Array;\n}\n\n/** An address lookup table referenced by a transaction template (key + inner addresses). */\nexport interface TransactionTemplateLut {\n /** ALT account address. */\n p: Pubkey;\n /** Addresses stored inside the ALT, in order. */\n a: Pubkey[];\n}\n\n/**\n * Footprint of the instructions/ALTs surrounding the swap, so the router sizes\n * routes to fit alongside them. Wire format uses single-letter fields: `i`\n * instructions, `a` ALTs, `m` extra account metas. See the gateway helper\n * `buildTitanTemplate`. Over the WebSocket this is sent as a native msgpack\n * object (no base64) — unlike the gateway GET there is no URL-length limit, so\n * large ALTs are fine.\n */\nexport interface TransactionTemplate {\n i: Instruction[];\n a: TransactionTemplateLut[];\n m: AccountMeta[];\n /** Transaction-level compute budget; required with `transactionFormat: 1`, ignored for v0. */\n c?: TransactionConfigParams;\n}\n\n/** Compute budget a v1 transaction carries in its message; omitted fields use the runtime default. */\nexport interface TransactionConfigParams {\n priorityFee?: number;\n computeUnitLimit?: number;\n loadedAccountsDataSizeLimit?: number;\n}\n\nexport enum SwapMode {\n ExactIn = \"ExactIn\",\n ExactOut = \"ExactOut\",\n}\n\n// --- Client request types ---\n\nexport type Uint64 = number | bigint;\n\nexport interface ClientRequest {\n id: number;\n data: RequestData;\n}\n\nexport type RequestData =\n | { NewSwapQuoteStream: SwapQuoteRequest }\n | { StopStream: StopStreamRequest };\n\nexport interface SwapQuoteRequest {\n swap: SwapParams;\n transaction: TransactionParams;\n update?: QuoteUpdateParams;\n}\n\nexport interface SwapParams {\n inputMint: Pubkey;\n outputMint: Pubkey;\n amount: Uint64;\n swapMode?: SwapMode;\n slippageBps?: number;\n dexes?: string[];\n excludeDexes?: string[];\n /**\n * Exclude the server-configured \"vote account\" venues from routing. Those venues touch validator\n * vote accounts, which Jito refuses to bundle — so a swap that routes through them can't land inside\n * our flashloan/double-hop Jito bundles. Set `true` for bundled flows. Available since Titan v1.6.\n */\n noVoteAccounts?: boolean;\n onlyDirectRoutes?: boolean;\n addSizeConstraint?: boolean;\n sizeConstraint?: number;\n providers?: string[];\n /** Limit total number of accounts used by routes. Default: 256. Available since v1.1. */\n accountsLimitTotal?: number;\n /** Limit writable accounts used by routes. Default: 64. Available since v1.1. */\n accountsLimitWritable?: number;\n /**\n * Reserve room for the surrounding (non-swap) instructions + ALTs so the\n * router sizes routes to fit. Mutually exclusive with `sizeConstraint` /\n * `accountsLimitTotal` / `accountsLimitWritable`. Available since v1.2.\n */\n transactionTemplate?: TransactionTemplate;\n}\n\nexport interface TransactionParams {\n userPublicKey: Pubkey;\n closeInputTokenAccount?: boolean;\n createOutputTokenAccount?: boolean;\n feeAccount?: Pubkey;\n feeBps?: number;\n feeFromInputMint?: boolean;\n outputAccount?: Pubkey;\n titanSwapVersion?: SwapVersion;\n /**\n * `true` leaves a wSOL output as wrapped SOL (the wSOL SPL token) instead of\n * unwrapping it to native lamports. Default `false`. Only has an effect when\n * `outputMint == wSOL`; ignored otherwise. Requires `titanSwapVersion=3`.\n */\n outputWsol?: boolean;\n /**\n * Transaction format routes are sized for: `0` (default) a v0 transaction of 1232 bytes, `1` a\n * v1 transaction of 4096 bytes without ALTs, which needs the template's `c` and\n * `titanSwapVersion=3`.\n */\n transactionFormat?: 0 | 1;\n}\n\nexport enum SwapVersion {\n V2 = 2,\n V3 = 3,\n}\n\nexport interface QuoteUpdateParams {\n intervalMs?: Uint64;\n num_quotes: number;\n}\n\nexport interface StopStreamRequest {\n id: number;\n}\n\n// --- Server message types ---\n\nexport type ServerMessage =\n | { Response: ResponseSuccess }\n | { Error: ResponseError }\n | { StreamData: StreamData }\n | { StreamEnd: StreamEnd };\n\nexport type ResponseData =\n | { NewSwapQuoteStream: QuoteSwapStreamResponse }\n | { StreamStopped: StopStreamResponse };\n\nexport interface StreamStart {\n id: number;\n dataType: string;\n}\n\nexport interface ResponseSuccess {\n requestId: number;\n data: ResponseData;\n stream?: StreamStart;\n}\n\nexport interface ResponseError {\n requestId: number;\n code: number;\n message: string;\n}\n\nexport type StreamDataPayload = { SwapQuotes: SwapQuotes };\n\nexport interface StreamData {\n id: number;\n seq: number;\n payload: StreamDataPayload;\n}\n\nexport interface StreamEnd {\n id: number;\n errorCode?: number;\n errorMessage?: string;\n}\n\nexport interface QuoteSwapStreamResponse {\n intervalMs: number;\n}\n\nexport interface StopStreamResponse {\n id: number;\n}\n\n// --- Quote / Route types ---\n\nexport interface SwapQuotes {\n id: string;\n inputMint: Uint8Array;\n outputMint: Uint8Array;\n swapMode: SwapMode;\n amount: number;\n quotes: { [key: string]: SwapRoute };\n /** Present when DART is enabled; names the route Titan recommends. */\n metadata?: { ExpectedWinner?: string };\n}\n\nexport interface SwapRoute {\n inAmount: number;\n outAmount: number;\n slippageBps: number;\n platformFee?: PlatformFee;\n steps: RoutePlanStep[];\n instructions: Instruction[];\n addressLookupTables: Pubkey[];\n contextSlot?: number;\n timeTaken?: number;\n expiresAtMs?: number;\n expiresAfterSlot?: number;\n computeUnits?: number;\n computeUnitsSafe?: number;\n transaction?: Uint8Array;\n referenceId?: string;\n}\n\nexport interface PlatformFee {\n amount: number;\n fee_bps: number;\n}\n\nexport interface RoutePlanStep {\n ammKey: Uint8Array;\n label: string;\n inputMint: Uint8Array;\n outputMint: Uint8Array;\n inAmount: number;\n outAmount: number;\n allocPpb: number;\n feeMint?: Uint8Array;\n feeAmount?: number;\n contextSlot?: number;\n}\n","// Shared Titan proxy response helpers — used by both SDK and web app\n// to deserialize, select, and build results from the HTTP proxy's\n// base64-serialized responses.\n\nimport {\n AccountRole,\n assertAccountDecoded,\n fetchJsonParsedAccounts,\n getAddressDecoder,\n getBase64Encoder,\n upgradeRoleToSigner,\n upgradeRoleToWritable,\n type Address,\n type AddressesByLookupTableAddress,\n type GetMultipleAccountsApi,\n type Instruction,\n type Rpc,\n} from \"@solana/kit\";\n\n// --- Serialized (base64) types from the HTTP proxy ---\n\nexport interface SerializedInstruction {\n p: string; // base64 program id\n a: { p: string; s: boolean; w: boolean }[]; // base64 accounts\n d: string; // base64 data\n}\n\nexport interface SerializedSwapRoute {\n inAmount: number;\n outAmount: number;\n slippageBps: number;\n platformFee?: { amount: number; fee_bps: number };\n instructions: SerializedInstruction[];\n addressLookupTables: string[]; // base64 encoded pubkeys\n contextSlot?: number;\n timeTaken?: number;\n}\n\nexport interface TitanProxySwapQuoteResponse {\n quotes: { [providerId: string]: SerializedSwapRoute };\n inputMint: string; // base64\n outputMint: string; // base64\n swapMode: string;\n amount: number;\n}\n\nexport interface TitanProxyExactOutResponse {\n inAmount: number;\n outAmount: number;\n otherAmountThreshold: string;\n slippageBps: number;\n}\n\n// --- Deserialization ---\n\n/**\n * Titan's router stamps a read-only `jitodontfront…` MEV-guard account onto the\n * swap instruction. Jito refuses to bundle any transaction that touches a `jito*`\n * marker, so we drop it to keep the swap landable inside a Jito bundle (our\n * flashloan swaps are bundled).\n */\nexport const isJitoDontFront = (address: Address) => address.startsWith(\"jitodontfront\");\n\n/** Kit account role for Titan's `s` (signer) / `w` (writable) flags. */\nexport function titanAccountRole(isSigner: boolean, isWritable: boolean): AccountRole {\n const role = isWritable ? upgradeRoleToWritable(AccountRole.READONLY) : AccountRole.READONLY;\n return isSigner ? upgradeRoleToSigner(role) : role;\n}\n\n/** Deserializes a base64 HTTP-proxy instruction, dropping the `jitodontfront` marker account. */\nexport function deserializeSerializedInstruction(ix: SerializedInstruction): Instruction {\n const fromBase64 = (value: string) =>\n getAddressDecoder().decode(getBase64Encoder().encode(value));\n return {\n programAddress: fromBase64(ix.p),\n accounts: ix.a\n .map((account) => ({\n address: fromBase64(account.p),\n role: titanAccountRole(account.s, account.w),\n }))\n .filter((account) => !isJitoDontFront(account.address)),\n data: getBase64Encoder().encode(ix.d),\n };\n}\n\n// --- Route selection ---\n\nexport function selectBestRoute<T extends { inAmount: number; outAmount: number }>(\n quotes: { [id: string]: T },\n swapMode: \"ExactIn\" | \"ExactOut\"\n): T | null {\n const routes = Object.values(quotes);\n if (routes.length === 0) return null;\n return routes.reduce((best, route) => {\n if (swapMode === \"ExactIn\") {\n return route.outAmount > best.outAmount ? route : best;\n } else {\n return route.inAmount < best.inAmount ? route : best;\n }\n });\n}\n\n// --- Quote result builder ---\n\nexport interface TitanSwapQuoteResult {\n inAmount: string;\n outAmount: string;\n otherAmountThreshold: string;\n slippageBps: number;\n platformFee?: { amount: string; feeBps: number };\n contextSlot?: number;\n timeTaken?: number;\n}\n\nexport function buildSwapQuoteResult(\n route: {\n inAmount: number | bigint;\n outAmount: number | bigint;\n slippageBps: number;\n platformFee?: { amount: number | bigint; fee_bps: number };\n contextSlot?: number;\n timeTaken?: number;\n },\n swapMode: \"ExactIn\" | \"ExactOut\"\n): TitanSwapQuoteResult {\n const slippageBps = route.slippageBps;\n // The WebSocket/protobuf path decodes int64 amounts as BigInt; token amounts fit safely in a\n // JS number, so coerce for the slippage float math (BigInt × number throws).\n const outAmount = Number(route.outAmount);\n const inAmount = Number(route.inAmount);\n\n let otherAmountThreshold: string;\n if (swapMode === \"ExactIn\") {\n otherAmountThreshold = String(Math.floor(outAmount * (1 - slippageBps / 10000)));\n } else {\n otherAmountThreshold = String(Math.ceil(inAmount * (1 + slippageBps / 10000)));\n }\n\n return {\n inAmount: String(route.inAmount),\n outAmount: String(route.outAmount),\n otherAmountThreshold,\n slippageBps,\n platformFee: route.platformFee\n ? {\n amount: String(route.platformFee.amount),\n feeBps: route.platformFee.fee_bps,\n }\n : undefined,\n contextSlot: route.contextSlot,\n timeTaken: route.timeTaken,\n };\n}\n\n// --- LUT resolution ---\n\n/** Fetches the addresses of the given lookup tables; missing tables are omitted. */\nexport async function resolveLookupTables(\n rpc: Rpc<GetMultipleAccountsApi>,\n lookupTables: Address[]\n): Promise<AddressesByLookupTableAddress> {\n if (lookupTables.length === 0) return {};\n const accounts = await fetchJsonParsedAccounts<{ addresses: Address[] }[]>(rpc, lookupTables);\n const addressesByLookupTable: AddressesByLookupTableAddress = {};\n for (const account of accounts) {\n if (!account.exists) continue;\n assertAccountDecoded(account);\n addressesByLookupTable[account.address] = account.data.addresses;\n }\n return addressesByLookupTable;\n}\n","// Titan Swap V3 gateway (REST) helpers.\n//\n// Unlike the legacy HTTP proxy path (which posts JSON to an app-side proxy that\n// translates to/from msgpack), this talks to the Titan gateway directly using\n// the msgpack wire protocol. It is meant to run server-side where the Titan API\n// key is available. V3 (`titanSwapVersion: 3`) + `transactionTemplate` let the\n// router size routes against the footprint of the rest of the transaction.\n//\n// Docs: developer-doc/swap-api/guides/transaction-template\n// developer-doc/swap-api/reference/gateway/gateway-quote-swap\n\nimport { Encoder, decode } from \"@msgpack/msgpack\";\nimport {\n getAddressDecoder,\n getAddressEncoder,\n getBase64Decoder,\n isSignerRole,\n isWritableRole,\n type AccountMeta,\n type Address,\n type AddressesByLookupTableAddress,\n type Instruction,\n} from \"@solana/kit\";\n\nimport { isJitoDontFront, titanAccountRole } from \"./helpers\";\nimport type { Instruction as TitanWireInstruction, SwapRoute } from \"./types\";\n\nconst msgpackEncoder = new Encoder({ useBigInt64: true });\n\n// --- Transaction template (wire format) ---\n//\n// Single-letter field names, raw bytes for pubkeys + instruction data. See the\n// \"Transaction Template\" guide. `i` = instructions sharing the tx, `a` = ALTs\n// already referenced (order is load-bearing), `m` = extra account metas.\n\nexport interface TitanTemplateLut {\n /** ALT account address (32 raw bytes). */\n p: Uint8Array;\n /** Addresses stored inside the ALT, in order (32 raw bytes each). */\n a: Uint8Array[];\n}\n\nexport interface TitanTransactionTemplate {\n i: TitanWireInstruction[];\n a: TitanTemplateLut[];\n m: { p: Uint8Array; s: boolean; w: boolean }[];\n}\n\nconst addressBytes = (address: Address) => Uint8Array.from(getAddressEncoder().encode(address));\n\nconst accountMetaToTitanWire = (account: AccountMeta) => ({\n p: addressBytes(account.address),\n s: isSignerRole(account.role),\n w: isWritableRole(account.role),\n});\n\n/**\n * Build a Titan `transactionTemplate` from the surrounding (non-swap) footprint.\n * ALT order is preserved — insert the tables in the order the final message will use.\n */\nexport function buildTitanTemplate(footprint: {\n instructions: Instruction[];\n luts: AddressesByLookupTableAddress;\n extraAccountMetas?: AccountMeta[];\n}): TitanTransactionTemplate {\n return {\n i: footprint.instructions.map((ix) => ({\n p: addressBytes(ix.programAddress),\n a: (ix.accounts ?? []).map(accountMetaToTitanWire),\n d: Uint8Array.from(ix.data ?? []),\n })),\n a: Object.entries(footprint.luts).map(([lookupTable, addresses]) => ({\n p: addressBytes(lookupTable as Address),\n a: addresses.map(addressBytes),\n })),\n m: (footprint.extraAccountMetas ?? []).map(accountMetaToTitanWire),\n };\n}\n\n/** msgpack-encode then base64 a template for the gateway query string. */\nexport function encodeTitanTemplate(template: TitanTransactionTemplate): string {\n return getBase64Decoder().decode(msgpackEncoder.encode(template));\n}\n\n// --- Gateway quote/swap (V3) ---\n\nexport interface TitanGatewayQuoteParams {\n /** Gateway base path, e.g. `https://<host>/api/v1`. `/quote/swap` is appended. */\n basePath: string;\n apiKey?: string;\n headers?: Record<string, string>;\n\n inputMint: string;\n outputMint: string;\n amount: number;\n userPublicKey: string;\n outputAccount: string;\n slippageBps?: number;\n swapMode?: \"ExactIn\" | \"ExactOut\";\n dexes?: string[];\n excludeDexes?: string[];\n onlyDirectRoutes?: boolean;\n /** Allowlist of quote providers by id. The gateway has no exclude-list, so to\n * drop a provider (e.g. Titan-DART) we list the ones we want. */\n providers?: string[];\n\n /** msgpack+base64 template. Mutually exclusive with the size/account limits\n * below. Note: sent as a query-string value, so a template that embeds large\n * ALTs can exceed the gateway's URI limit (414) — prefer the numeric limits\n * for flashloan footprints that reference big lookup tables. */\n transactionTemplate?: string;\n\n /** Numeric sizing (small query params; safe for LUT-heavy footprints). */\n addSizeConstraint?: boolean;\n sizeConstraint?: number;\n accountsLimitTotal?: number;\n accountsLimitWritable?: number;\n\n feeBps?: number;\n feeAccount?: string;\n}\n\nexport interface TitanGatewayQuoteResponse {\n quotes: { [id: string]: SwapRoute };\n metadata?: { ExpectedWinner?: string };\n}\n\n/**\n * Fetch a V3 quote/swap from the Titan gateway and return the best route.\n * Honors the gateway's `ExpectedWinner` when present, otherwise falls back to\n * `selectBestRoute` semantics (max out for ExactIn, min in for ExactOut).\n */\nexport async function fetchTitanQuoteSwapV3(\n params: TitanGatewayQuoteParams\n): Promise<{ route: SwapRoute; raw: TitanGatewayQuoteResponse }> {\n const {\n basePath,\n apiKey,\n headers,\n inputMint,\n outputMint,\n amount,\n userPublicKey,\n outputAccount,\n slippageBps,\n swapMode,\n dexes,\n excludeDexes,\n onlyDirectRoutes,\n providers,\n transactionTemplate,\n addSizeConstraint,\n sizeConstraint,\n accountsLimitTotal,\n accountsLimitWritable,\n feeBps,\n feeAccount,\n } = params;\n\n const query = new URLSearchParams({\n inputMint,\n outputMint,\n amount: String(amount),\n userPublicKey,\n outputAccount,\n titanSwapVersion: \"3\",\n simulate: \"false\",\n });\n if (slippageBps !== undefined) query.set(\"slippageBps\", String(slippageBps));\n if (swapMode) query.set(\"swapMode\", swapMode);\n if (dexes?.length) query.set(\"dexes\", dexes.join(\",\"));\n if (excludeDexes?.length) query.set(\"excludeDexes\", excludeDexes.join(\",\"));\n if (providers?.length) query.set(\"providers\", providers.join(\",\"));\n if (onlyDirectRoutes) query.set(\"onlyDirectRoutes\", \"true\");\n if (transactionTemplate) {\n query.set(\"transactionTemplate\", transactionTemplate);\n } else {\n // Numeric sizing (mutually exclusive with the template).\n if (addSizeConstraint) query.set(\"addSizeConstraint\", \"true\");\n if (sizeConstraint !== undefined) query.set(\"sizeConstraint\", String(sizeConstraint));\n if (accountsLimitTotal !== undefined) {\n query.set(\"accountsLimitTotal\", String(accountsLimitTotal));\n }\n if (accountsLimitWritable !== undefined) {\n query.set(\"accountsLimitWritable\", String(accountsLimitWritable));\n }\n }\n if (feeBps !== undefined && feeAccount) {\n query.set(\"feeBps\", String(feeBps));\n query.set(\"feeAccount\", feeAccount);\n }\n\n const response = await fetch(`${basePath}/quote/swap?${query.toString()}`, {\n method: \"GET\",\n headers: {\n Accept: \"application/vnd.msgpack\",\n ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n ...(headers ?? {}),\n },\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Titan gateway error (${response.status}): ${text || response.statusText}`);\n }\n\n // The gateway occasionally returns a truncated / non-msgpack body (e.g. an\n // empty \"no route\" response); decode it defensively so callers get a clean\n // error instead of an opaque msgpack RangeError.\n let raw: TitanGatewayQuoteResponse;\n try {\n raw = decode(new Uint8Array(await response.arrayBuffer())) as TitanGatewayQuoteResponse;\n } catch {\n throw new Error(\n `Titan gateway returned an undecodable response for ${inputMint} -> ${outputMint}`\n );\n }\n\n const route = selectGatewayRoute(raw, swapMode ?? \"ExactIn\");\n if (!route) {\n throw new Error(`No Titan V3 route found for ${inputMint} -> ${outputMint}`);\n }\n return { route, raw };\n}\n\n/**\n * A route is only usable if it quotes a real amount. Titan occasionally returns\n * a single `Titan-DART` (RFQ / private-swap) route that quotes `outAmount: 0` —\n * DART settles via a separate auction/signature and isn't composable inside a\n * flashloan, so we treat zero-amount routes as non-viable.\n */\nfunction isViableRoute(route: SwapRoute, swapMode: \"ExactIn\" | \"ExactOut\"): boolean {\n return swapMode === \"ExactIn\" ? route.outAmount > 0 : route.inAmount > 0;\n}\n\n/**\n * Pick the best usable route from a quotes map, honoring Titan's\n * `ExpectedWinner` when present and skipping non-viable (zero-amount) routes.\n * Shared by the gateway REST path and the WebSocket adapter.\n */\nexport function selectGatewayRoute(\n raw: TitanGatewayQuoteResponse,\n swapMode: \"ExactIn\" | \"ExactOut\"\n): SwapRoute | null {\n const viable = Object.values(raw.quotes ?? {}).filter((r) => isViableRoute(r, swapMode));\n if (viable.length === 0) return null;\n\n // Honor Titan's recommended winner only when it is itself a viable route.\n const winnerId = raw.metadata?.ExpectedWinner;\n if (winnerId) {\n const winner = raw.quotes[winnerId];\n if (winner && isViableRoute(winner, swapMode)) return winner;\n }\n\n return viable.reduce((best, route) =>\n swapMode === \"ExactIn\"\n ? route.outAmount > best.outAmount\n ? route\n : best\n : route.inAmount < best.inAmount\n ? route\n : best\n );\n}\n\n/** Deserialize a Titan wire instruction (raw bytes), dropping the `jitodontfront` marker account. */\nexport function deserializeTitanWireInstruction(ix: TitanWireInstruction): Instruction {\n return {\n programAddress: getAddressDecoder().decode(ix.p),\n accounts: ix.a\n .map((account) => ({\n address: getAddressDecoder().decode(account.p),\n role: titanAccountRole(account.s, account.w),\n }))\n .filter((account) => !isJitoDontFront(account.address)),\n data: Uint8Array.from(ix.d),\n };\n}\n"]}