@kamino-finance/klend-sdk 2.10.17 → 2.10.18

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.
@@ -553,6 +553,15 @@ class KaminoObligation {
553
553
  originationFeeRate = originationFeeRate.div(originationFeeRate.add(new decimal_js_1.default(1)));
554
554
  const borrowFee = maxBorrowAmount.mul(originationFeeRate);
555
555
  maxBorrowAmount = maxBorrowAmount.sub(borrowFee);
556
+ const utilizationRatioLimit = reserve.state.config.utilizationLimitBlockBorrowingAbove / 100;
557
+ const currentUtilizationRatio = reserve.calculateUtilizationRatio();
558
+ if (utilizationRatioLimit > 0 && currentUtilizationRatio > utilizationRatioLimit) {
559
+ return new decimal_js_1.default(0);
560
+ }
561
+ else if (utilizationRatioLimit > 0 && currentUtilizationRatio < utilizationRatioLimit) {
562
+ const maxBorrowBasedOnUtilization = new decimal_js_1.default(utilizationRatioLimit - currentUtilizationRatio).mul(reserve.getTotalSupply());
563
+ maxBorrowAmount = decimal_js_1.default.min(maxBorrowAmount, maxBorrowBasedOnUtilization);
564
+ }
556
565
  return decimal_js_1.default.max(new decimal_js_1.default(0), maxBorrowAmount);
557
566
  }
558
567
  getMaxWithdrawAmount(market, tokenMint, slot) {
@@ -586,7 +595,7 @@ class KaminoObligation {
586
595
  maxWithdrawValue = this.refreshedStats.borrowLimit
587
596
  .sub(this.refreshedStats.userTotalBorrowBorrowFactorAdjusted)
588
597
  .div(reserveMaxLtv)
589
- .mul(0.995); // remove 0.5% to prevent going over max ltv
598
+ .mul(0.999); // remove 0.1% to prevent going over max ltv
590
599
  }
591
600
  const maxWithdrawAmount = maxWithdrawValue.div(reserve.getOracleMarketPrice()).mul(reserve.getMintFactor());
592
601
  const reserveAvailableLiquidity = reserve.getLiquidityAvailableAmount();
@@ -1 +1 @@
1
- {"version":3,"file":"obligation.js","sourceRoot":"","sources":["../../src/classes/obligation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,4DAAiC;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C,MAAM,CAAC,aAAa,CAAE,CAAC;gBACxE,MAAM,oBAAoB,GAAG,OAAO,CAAC,gCAAgC,CAAC,IAAI,CAAC,CAAC;gBAC5E,qBAAqB,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;aAClE;SACF;IACH,CAAC;IAED,MAAM,CAAC,yBAAyB,CAAC,OAAsB,EAAE,cAAsB;QAC7E,IAAI,cAAc,KAAK,CAAC,EAAE;YACxB,OAAO,IAAI,oBAAO,CAAC,CAAC,CAAC,CAAC;SACvB;QACD,OAAO,IAAI,oBAAO,CAAC,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1D,CAAC;CACF;AAjgCD,4CAigCC","sourcesContent":["/* eslint-disable max-classes-per-file */\nimport { PublicKey } from '@solana/web3.js';\nimport Decimal from 'decimal.js';\nimport { KaminoReserve } from './reserve';\nimport { Obligation } from '../idl_codegen/accounts';\nimport { KaminoMarket } from './market';\nimport BN from 'bn.js';\nimport { Fraction } from './fraction';\nimport { ObligationCollateral, ObligationLiquidity } from '../idl_codegen/types';\nimport { positiveOrZero, valueOrZero } from './utils';\nimport { isNotNullPubkey, PubkeyHashMap } from '../utils';\nimport { ActionType } from './action';\n\nexport type Position = {\n reserveAddress: PublicKey;\n mintAddress: PublicKey;\n amount: Decimal;\n marketValueRefreshed: Decimal;\n};\n\nexport type ObligationStats = {\n userTotalDeposit: Decimal;\n userTotalBorrow: Decimal;\n userTotalBorrowBorrowFactorAdjusted: Decimal;\n borrowLimit: Decimal;\n borrowLiquidationLimit: Decimal;\n borrowUtilization: Decimal;\n netAccountValue: Decimal;\n loanToValue: Decimal;\n liquidationLtv: Decimal;\n leverage: Decimal;\n potentialElevationGroupUpdate: Array<number>;\n};\n\ninterface BorrowStats {\n borrows: Map<PublicKey, Position>;\n userTotalBorrow: Decimal;\n userTotalBorrowBorrowFactorAdjusted: Decimal;\n positions: number;\n}\n\nexport class KaminoObligation {\n obligationAddress: PublicKey;\n\n state: Obligation;\n\n /**\n * Deposits stored in a map of reserve address to position\n */\n deposits: Map<PublicKey, Position>;\n\n /**\n * Borrows stored in a map of reserve address to position\n */\n borrows: Map<PublicKey, Position>;\n\n refreshedStats: ObligationStats;\n\n obligationTag: number;\n\n /**\n * Initialise a new Obligation from the deserialized state\n * @param market\n * @param obligationAddress\n * @param obligation\n * @param collateralExchangeRates - rates from the market by reserve address, will be calculated if not provided\n * @param cumulativeBorrowRates - rates from the market by reserve address, will be calculated if not provided\n */\n constructor(\n market: KaminoMarket,\n obligationAddress: PublicKey,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>\n ) {\n this.obligationAddress = obligationAddress;\n this.state = obligation;\n const { borrows, deposits, refreshedStats } = this.calculatePositions(\n market,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n this.deposits = deposits;\n this.borrows = borrows;\n this.refreshedStats = refreshedStats;\n this.obligationTag = obligation.tag.toNumber();\n }\n\n static async load(kaminoMarket: KaminoMarket, obligationAddress: PublicKey): Promise<KaminoObligation | null> {\n const res = await kaminoMarket.getConnection().getAccountInfoAndContext(obligationAddress);\n if (res.value === null) {\n return null;\n }\n const accInfo = res.value;\n if (!accInfo.owner.equals(kaminoMarket.programId)) {\n throw new Error(\"account doesn't belong to this program\");\n }\n const obligation = Obligation.decode(accInfo.data);\n\n if (obligation === null) {\n return null;\n }\n const { collateralExchangeRates, cumulativeBorrowRates } = KaminoObligation.getRatesForObligation(\n kaminoMarket,\n obligation,\n res.context.slot\n );\n return new KaminoObligation(\n kaminoMarket,\n obligationAddress,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n }\n\n static async loadAll(\n kaminoMarket: KaminoMarket,\n obligationAddresses: PublicKey[],\n slot?: number\n ): Promise<(KaminoObligation | null)[]> {\n let currentSlot = slot;\n let obligations: (Obligation | null)[];\n if (!currentSlot) {\n [currentSlot, obligations] = await Promise.all([\n kaminoMarket.getConnection().getSlot(),\n Obligation.fetchMultiple(kaminoMarket.getConnection(), obligationAddresses, kaminoMarket.programId),\n ]);\n } else {\n obligations = await Obligation.fetchMultiple(\n kaminoMarket.getConnection(),\n obligationAddresses,\n kaminoMarket.programId\n );\n }\n const cumulativeBorrowRates = new PubkeyHashMap<PublicKey, Decimal>();\n const collateralExchangeRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (const obligation of obligations) {\n if (obligation !== null) {\n KaminoObligation.addRatesForObligation(\n kaminoMarket,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates,\n currentSlot\n );\n }\n }\n\n return obligations.map((obligation, i) => {\n if (obligation === null) {\n return null;\n }\n return new KaminoObligation(\n kaminoMarket,\n obligationAddresses[i],\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n });\n }\n\n /**\n * @returns the obligation borrows as a list\n */\n getBorrows(): Array<Position> {\n return [...this.borrows.values()];\n }\n\n /**\n * @returns the obligation borrows as a list\n */\n getDeposits(): Array<Position> {\n return [...this.deposits.values()];\n }\n\n /**\n * @returns the total deposited value of the obligation (sum of all deposits)\n */\n getDepositedValue(): Decimal {\n return new Fraction(this.state.depositedValueSf).toDecimal();\n }\n\n /**\n * @returns the total borrowed value of the obligation (sum of all borrows -- no borrow factor)\n */\n getBorrowedMarketValue(): Decimal {\n return new Fraction(this.state.borrowedAssetsMarketValueSf).toDecimal();\n }\n\n /**\n * @returns the total borrowed value of the obligation (sum of all borrows -- with borrow factor weighting)\n */\n getBorrowedMarketValueBFAdjusted(): Decimal {\n return new Fraction(this.state.borrowFactorAdjustedDebtValueSf).toDecimal();\n }\n\n /**\n * @returns total borrow power of the obligation, relative to max LTV of each asset's reserve\n */\n getAllowedBorrowValue(): Decimal {\n return new Fraction(this.state.allowedBorrowValueSf).toDecimal();\n }\n\n /**\n * @returns the borrow value at which the obligation gets liquidatable\n * (relative to the liquidation threshold of each asset's reserve)\n */\n getUnhealthyBorrowValue(): Decimal {\n return new Fraction(this.state.unhealthyBorrowValueSf).toDecimal();\n }\n\n /**\n *\n * @returns Market value of the deposit in the specified obligation collateral/deposit asset (USD)\n */\n getDepositMarketValue(deposit: ObligationCollateral): Decimal {\n return new Fraction(deposit.marketValueSf).toDecimal();\n }\n\n getBorrowByReserve(reserve: PublicKey): Position | undefined {\n return this.borrows.get(reserve);\n }\n\n getDepositByReserve(reserve: PublicKey): Position | undefined {\n return this.deposits.get(reserve);\n }\n\n getBorrowByMint(mint: PublicKey): Position | undefined {\n for (const value of this.borrows.values()) {\n if (value.mintAddress.equals(mint)) {\n return value;\n }\n }\n return undefined;\n }\n\n getDepositByMint(mint: PublicKey): Position | undefined {\n for (const value of this.deposits.values()) {\n if (value.mintAddress.equals(mint)) {\n return value;\n }\n }\n return undefined;\n }\n\n /**\n *\n * @returns Market value of the borrow in the specified obligation liquidity/borrow asset (USD) (no borrow factor weighting)\n */\n getBorrowMarketValue(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.marketValueSf).toDecimal();\n }\n\n /**\n *\n * @returns Market value of the borrow in the specified obligation liquidity/borrow asset (USD) (with borrow factor weighting)\n */\n getBorrowMarketValueBFAdjusted(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.borrowFactorAdjustedMarketValueSf).toDecimal();\n }\n\n /**\n * Calculate the current ratio of borrowed value to deposited value\n */\n loanToValue(): Decimal {\n if (this.refreshedStats.userTotalDeposit.eq(0)) {\n return new Decimal(0);\n }\n return this.refreshedStats.userTotalBorrowBorrowFactorAdjusted.div(this.refreshedStats.userTotalDeposit);\n }\n\n /**\n * @returns the total number of positions (deposits + borrows)\n */\n getNumberOfPositions(): number {\n return this.deposits.size + this.borrows.size;\n }\n\n getNetAccountValue(): Decimal {\n return this.refreshedStats.netAccountValue;\n }\n\n /**\n * @returns the potential elevation groups the obligation qualifies for\n */\n getElevationGroups(kaminoMarket: KaminoMarket): Array<number> {\n const reserves = new PubkeyHashMap<PublicKey, KaminoReserve>();\n for (const deposit of this.state.deposits.values()) {\n if (isNotNullPubkey(deposit.depositReserve) && !reserves.has(deposit.depositReserve)) {\n reserves.set(deposit.depositReserve, kaminoMarket.getReserveByAddress(deposit.depositReserve)!);\n }\n }\n for (const borrow of this.state.borrows.values()) {\n if (isNotNullPubkey(borrow.borrowReserve) && !reserves.has(borrow.borrowReserve)) {\n reserves.set(borrow.borrowReserve, kaminoMarket.getReserveByAddress(borrow.borrowReserve)!);\n }\n }\n return KaminoObligation.getElevationGroupsForReserves([...reserves.values()]);\n }\n\n static getElevationGroupsForReserves(reserves: Array<KaminoReserve>): Array<number> {\n const elevationGroupsCounts = new Map<number, number>();\n for (const reserve of reserves) {\n for (const elevationGroup of reserve.state.config.elevationGroups) {\n if (elevationGroup !== 0) {\n const count = elevationGroupsCounts.get(elevationGroup);\n if (count) {\n elevationGroupsCounts.set(elevationGroup, count + 1);\n } else {\n elevationGroupsCounts.set(elevationGroup, 1);\n }\n }\n }\n }\n const activeElevationGroups = new Array<number>();\n for (const [group, count] of elevationGroupsCounts.entries()) {\n if (count === reserves.length) {\n activeElevationGroups.push(group);\n }\n }\n return activeElevationGroups;\n }\n\n calculateSimulatedBorrow(\n oldStats: ObligationStats,\n oldBorrows: Map<PublicKey, Position>,\n borrowAmount: Decimal,\n mint: PublicKey,\n reserves: Map<PublicKey, KaminoReserve>\n ): {\n stats: ObligationStats;\n borrows: Map<PublicKey, Position>;\n } {\n const newStats = { ...oldStats };\n const newBorrows = new PubkeyHashMap<PublicKey, Position>([...oldBorrows.entries()]);\n let borrowPosition: Position | undefined = undefined;\n for (const oldBorrow of oldBorrows.values()) {\n if (oldBorrow.mintAddress.equals(mint)) {\n borrowPosition = { ...oldBorrow };\n }\n }\n let reserve: KaminoReserve | undefined = undefined;\n for (const kaminoReserve of reserves.values()) {\n if (kaminoReserve.getLiquidityMint().equals(mint)) {\n reserve = kaminoReserve;\n }\n }\n\n if (!reserve) {\n throw new Error(`No reserve found for mint ${mint}`);\n }\n\n if (!borrowPosition) {\n borrowPosition = {\n reserveAddress: reserve!.address,\n mintAddress: mint,\n amount: new Decimal(0),\n marketValueRefreshed: new Decimal(0),\n };\n }\n\n if (!reserve.state.config.elevationGroups.includes(this.state.elevationGroup)) {\n throw new Error(\n `User would have to downgrade the elevation group in order to be able to borrow from this reserve`\n );\n }\n\n const borrowFactor =\n this.state.elevationGroup !== 0 ? new Decimal(1) : new Decimal(reserve.stats.borrowFactor).div(100);\n\n const borrowValueUSD = borrowAmount.mul(reserve.getOracleMarketPrice()).dividedBy(reserve.getMintFactor());\n\n const borrowValueBorrowFactorAdjustedUSD = borrowValueUSD.mul(borrowFactor);\n\n newStats.userTotalBorrow = positiveOrZero(newStats.userTotalBorrow.plus(borrowValueUSD));\n newStats.userTotalBorrowBorrowFactorAdjusted = positiveOrZero(\n newStats.userTotalBorrowBorrowFactorAdjusted.plus(borrowValueBorrowFactorAdjustedUSD)\n );\n\n borrowPosition.amount = positiveOrZero(borrowPosition.amount.plus(borrowAmount));\n borrowPosition.mintAddress = mint;\n borrowPosition.marketValueRefreshed = positiveOrZero(borrowPosition.marketValueRefreshed.plus(borrowValueUSD));\n\n newBorrows.set(borrowPosition.reserveAddress, borrowPosition);\n return {\n borrows: newBorrows,\n stats: newStats,\n };\n }\n\n calculateSimulatedDeposit(\n oldStats: ObligationStats,\n oldDeposits: Map<PublicKey, Position>,\n amount: Decimal,\n mint: PublicKey,\n reserves: Map<PublicKey, KaminoReserve>,\n market: KaminoMarket\n ): {\n stats: ObligationStats;\n deposits: Map<PublicKey, Position>;\n } {\n const newStats = { ...oldStats };\n const newDeposits = new PubkeyHashMap<PublicKey, Position>([...oldDeposits.entries()]);\n\n let depositPosition: Position | undefined = undefined;\n for (const oldDeposit of oldDeposits.values()) {\n if (oldDeposit.mintAddress.equals(mint)) {\n depositPosition = { ...oldDeposit };\n }\n }\n let reserve: KaminoReserve | undefined = undefined;\n for (const kaminoReserve of reserves.values()) {\n if (kaminoReserve.getLiquidityMint().equals(mint)) {\n reserve = kaminoReserve;\n }\n }\n if (!reserve) {\n throw new Error(`No reserve found for mint ${mint}`);\n }\n\n if (!depositPosition) {\n depositPosition = {\n reserveAddress: reserve!.address,\n mintAddress: mint,\n amount: new Decimal(0),\n marketValueRefreshed: new Decimal(0),\n };\n }\n\n let loanToValue = reserve.stats.loanToValuePct;\n let liqThreshold = reserve.stats.liquidationThreshold;\n\n if (this.state.elevationGroup !== 0) {\n loanToValue = market.getElevationGroup(this.state.elevationGroup).ltvPct / 100;\n liqThreshold = market.getElevationGroup(this.state.elevationGroup).liquidationThresholdPct / 100;\n }\n\n if (!reserve.state.config.elevationGroups.includes(this.state.elevationGroup)) {\n throw new Error(\n `User would have to downgrade the elevation group in order to be able to deposit in this reserve`\n );\n }\n\n const supplyAmount = amount; //.mul(reserve.getCollateralExchangeRate()).floor();\n const supplyAmountMultiplierUSD = supplyAmount\n .mul(reserve.getOracleMarketPrice())\n .dividedBy('1'.concat(Array(reserve.stats.decimals + 1).join('0')));\n\n newStats.userTotalDeposit = positiveOrZero(newStats.userTotalDeposit.plus(supplyAmountMultiplierUSD));\n newStats.borrowLimit = positiveOrZero(newStats.borrowLimit.plus(supplyAmountMultiplierUSD.mul(loanToValue)));\n newStats.borrowLiquidationLimit = positiveOrZero(\n newStats.borrowLiquidationLimit.plus(supplyAmountMultiplierUSD.mul(liqThreshold))\n );\n newStats.liquidationLtv = valueOrZero(newStats.borrowLiquidationLimit.div(newStats.userTotalDeposit));\n\n depositPosition.amount = positiveOrZero(depositPosition.amount.plus(amount));\n depositPosition.mintAddress = mint;\n depositPosition.marketValueRefreshed = positiveOrZero(\n depositPosition.marketValueRefreshed.plus(\n supplyAmount.mul(reserve.getOracleMarketPrice()).dividedBy(reserve.getMintFactor())\n )\n );\n\n newDeposits.set(depositPosition.reserveAddress, depositPosition);\n\n return {\n deposits: newDeposits,\n stats: newStats,\n };\n }\n\n /**\n * Calculate the newly modified stats of the obligation\n */\n // TODO: Elevation group problems\n // TODO: Shall we set up position limits?\n getSimulatedObligationStats(\n amount: Decimal,\n action: ActionType,\n mint: PublicKey,\n market: KaminoMarket,\n reserves: Map<PublicKey, KaminoReserve>\n ): {\n stats: ObligationStats;\n deposits: Map<PublicKey, Position>;\n borrows: Map<PublicKey, Position>;\n } {\n let newStats = { ...this.refreshedStats };\n let newDeposits: Map<PublicKey, Position> = new PubkeyHashMap<PublicKey, Position>([...this.deposits.entries()]);\n let newBorrows: Map<PublicKey, Position> = new PubkeyHashMap<PublicKey, Position>([...this.borrows.entries()]);\n\n switch (action) {\n case 'deposit': {\n const { stats, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n\n newStats = stats;\n newDeposits = deposits;\n\n break;\n }\n case 'borrow': {\n const { stats, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n amount,\n mint,\n reserves\n );\n newStats = stats;\n newBorrows = borrows;\n break;\n }\n case 'repay': {\n const { stats, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n new Decimal(amount).neg(),\n mint,\n reserves\n );\n newStats = stats;\n newBorrows = borrows;\n break;\n }\n\n case 'withdraw': {\n const { stats, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n new Decimal(amount).neg(),\n mint,\n reserves,\n market\n );\n newStats = stats;\n newDeposits = deposits;\n break;\n }\n case 'depositAndBorrow': {\n const { stats: statsAfterDeposit, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n const { stats, borrows } = this.calculateSimulatedBorrow(\n statsAfterDeposit,\n this.borrows,\n amount,\n mint,\n reserves\n );\n\n newStats = stats;\n newDeposits = deposits;\n newBorrows = borrows;\n break;\n }\n case 'repayAndWithdraw': {\n const { stats: statsAfterRepay, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n new Decimal(amount).neg(),\n mint,\n reserves\n );\n const { stats: statsAfterWithdraw, deposits } = this.calculateSimulatedDeposit(\n statsAfterRepay,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n newStats = statsAfterWithdraw;\n newDeposits = deposits;\n newBorrows = borrows;\n break;\n }\n default: {\n throw Error(`Invalid action type ${action} for getSimulatedObligationStats`);\n }\n }\n newStats.netAccountValue = newStats.userTotalDeposit.minus(newStats.userTotalBorrow);\n newStats.loanToValue = valueOrZero(\n newStats.userTotalBorrowBorrowFactorAdjusted.dividedBy(newStats.userTotalDeposit)\n );\n newStats.leverage = valueOrZero(newStats.userTotalDeposit.dividedBy(newStats.netAccountValue));\n\n return {\n stats: newStats,\n deposits: newDeposits,\n borrows: newBorrows,\n };\n }\n\n estimateObligationInterestRate = (\n reserve: KaminoReserve,\n borrow: ObligationLiquidity,\n currentSlot: number\n ): Decimal => {\n const estimatedCumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(currentSlot);\n\n const currentCumulativeBorrowRate = KaminoObligation.getCumulativeBorrowRate(borrow);\n\n if (estimatedCumulativeBorrowRate.gt(currentCumulativeBorrowRate)) {\n return estimatedCumulativeBorrowRate.div(currentCumulativeBorrowRate);\n }\n\n return new Decimal(0);\n };\n\n private calculateDeposits(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n getPx: (reserve: KaminoReserve) => Decimal\n ): {\n deposits: Map<PublicKey, Position>;\n userTotalDeposit: Decimal;\n borrowLimit: Decimal;\n liquidationLtv: Decimal;\n borrowLiquidationLimit: Decimal;\n } {\n return KaminoObligation.calculateObligationDeposits(market, obligation, collateralExchangeRates, getPx);\n }\n\n private calculateBorrows(\n market: KaminoMarket,\n obligation: Obligation,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n getPx: (reserve: KaminoReserve) => Decimal\n ): BorrowStats {\n return KaminoObligation.calculateObligationBorrows(market, obligation, cumulativeBorrowRates, getPx);\n }\n\n private calculatePositions(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>\n ): {\n borrows: Map<PublicKey, Position>;\n deposits: Map<PublicKey, Position>;\n refreshedStats: ObligationStats;\n } {\n const commonElevationGroups = this.getElevationGroups(market);\n\n const getOraclePx = (reserve: KaminoReserve) => reserve.getOracleMarketPrice();\n const depositStatsOraclePrice = this.calculateDeposits(market, obligation, collateralExchangeRates, getOraclePx);\n\n const borrowStatsOraclePrice = this.calculateBorrows(market, obligation, cumulativeBorrowRates, getOraclePx);\n\n const netAccountValueScopeRefreshed = depositStatsOraclePrice.userTotalDeposit.minus(\n borrowStatsOraclePrice.userTotalBorrow\n );\n\n return {\n deposits: depositStatsOraclePrice.deposits,\n borrows: borrowStatsOraclePrice.borrows,\n refreshedStats: {\n borrowLimit: depositStatsOraclePrice.borrowLimit,\n borrowLiquidationLimit: depositStatsOraclePrice.borrowLiquidationLimit,\n userTotalBorrow: borrowStatsOraclePrice.userTotalBorrow,\n userTotalBorrowBorrowFactorAdjusted: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted,\n userTotalDeposit: depositStatsOraclePrice.userTotalDeposit,\n liquidationLtv: depositStatsOraclePrice.liquidationLtv,\n borrowUtilization: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted.dividedBy(\n depositStatsOraclePrice.borrowLimit\n ),\n netAccountValue: netAccountValueScopeRefreshed,\n leverage: depositStatsOraclePrice.userTotalDeposit.dividedBy(netAccountValueScopeRefreshed),\n loanToValue: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted.dividedBy(\n depositStatsOraclePrice.userTotalDeposit\n ),\n potentialElevationGroupUpdate: commonElevationGroups,\n },\n };\n }\n\n public static calculateObligationDeposits(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal> | null,\n getPx: (reserve: KaminoReserve) => Decimal\n ): {\n deposits: Map<PublicKey, Position>;\n userTotalDeposit: Decimal;\n userTotalCollateralDeposit: Decimal;\n borrowLimit: Decimal;\n liquidationLtv: Decimal;\n borrowLiquidationLimit: Decimal;\n } {\n let userTotalDeposit = new Decimal(0);\n let userTotalCollateralDeposit = new Decimal(0);\n let borrowLimit = new Decimal(0);\n let borrowLiquidationLimit = new Decimal(0);\n\n const deposits = new PubkeyHashMap<PublicKey, Position>();\n for (let i = 0; i < obligation.deposits.length; i++) {\n if (!isNotNullPubkey(obligation.deposits[i].depositReserve)) {\n continue;\n }\n const deposit = obligation.deposits[i];\n const reserve = market.getReserveByAddress(deposit.depositReserve);\n if (!reserve) {\n throw new Error(\n `Obligation contains a deposit belonging to reserve: ${deposit.depositReserve} but the reserve was not found on the market. Deposit amount: ${deposit.depositedAmount}`\n );\n }\n let loanToValue = reserve.stats.loanToValuePct;\n let liqThreshold = reserve.stats.liquidationThreshold;\n\n if (obligation.elevationGroup !== 0) {\n loanToValue = market.state.elevationGroups[obligation.elevationGroup - 1].ltvPct / 100;\n liqThreshold = market.state.elevationGroups[obligation.elevationGroup - 1].liquidationThresholdPct / 100;\n }\n\n let exchangeRate;\n if (collateralExchangeRates !== null) {\n exchangeRate = collateralExchangeRates.get(reserve.address)!;\n } else {\n exchangeRate = reserve.getCollateralExchangeRate();\n }\n const supplyAmount = new Decimal(deposit.depositedAmount.toString()).div(exchangeRate);\n\n const depositValueUsd = supplyAmount.mul(getPx(reserve)).div(reserve.getMintFactor());\n\n userTotalDeposit = userTotalDeposit.add(depositValueUsd);\n\n if (loanToValue !== 0) {\n userTotalCollateralDeposit = userTotalCollateralDeposit.add(depositValueUsd);\n }\n\n borrowLimit = borrowLimit.add(depositValueUsd.mul(loanToValue));\n borrowLiquidationLimit = borrowLiquidationLimit.add(depositValueUsd.mul(liqThreshold));\n\n const position: Position = {\n reserveAddress: reserve.address,\n mintAddress: reserve.getLiquidityMint(),\n amount: supplyAmount,\n marketValueRefreshed: depositValueUsd,\n };\n deposits.set(reserve.address, position);\n }\n\n return {\n deposits,\n userTotalDeposit,\n userTotalCollateralDeposit,\n borrowLimit,\n liquidationLtv: valueOrZero(borrowLiquidationLimit.div(userTotalDeposit)),\n borrowLiquidationLimit,\n };\n }\n\n public static calculateObligationBorrows(\n market: KaminoMarket,\n obligation: Obligation,\n cumulativeBorrowRates: Map<PublicKey, Decimal> | null,\n getPx: (reserve: KaminoReserve) => Decimal\n ): BorrowStats {\n let userTotalBorrow = new Decimal(0);\n let userTotalBorrowBorrowFactorAdjusted = new Decimal(0);\n let positions = 0;\n\n const borrows = new PubkeyHashMap<PublicKey, Position>();\n for (let i = 0; i < obligation.borrows.length; i++) {\n if (!isNotNullPubkey(obligation.borrows[i].borrowReserve)) {\n continue;\n }\n const borrow = obligation.borrows[i];\n const reserve = market.getReserveByAddress(borrow.borrowReserve);\n if (!reserve) {\n throw new Error(\n `Obligation contains a borrow belonging to reserve: ${\n borrow.borrowReserve\n } but the reserve was not found on the market. Borrow amount: ${KaminoObligation.getBorrowAmount(borrow)}`\n );\n }\n\n const obligationCumulativeBorrowRate = KaminoObligation.getCumulativeBorrowRate(borrow);\n let cumulativeBorrowRate;\n if (cumulativeBorrowRates !== null) {\n cumulativeBorrowRate = cumulativeBorrowRates.get(reserve.address)!;\n } else {\n cumulativeBorrowRate = reserve.getCumulativeBorrowRate();\n }\n\n const borrowAmount = KaminoObligation.getBorrowAmount(borrow)\n .mul(cumulativeBorrowRate)\n .dividedBy(obligationCumulativeBorrowRate);\n\n const borrowValueUsd = borrowAmount.mul(getPx(reserve)).dividedBy(reserve.getMintFactor());\n\n const borrowFactor = KaminoObligation.getBorrowFactorForReserve(reserve, obligation.elevationGroup);\n const borrowValueBorrowFactorAdjustedUsd = borrowValueUsd.mul(borrowFactor);\n\n if (!borrowAmount.eq(new Decimal('0'))) {\n positions += 1;\n }\n\n userTotalBorrow = userTotalBorrow.plus(borrowValueUsd);\n userTotalBorrowBorrowFactorAdjusted = userTotalBorrowBorrowFactorAdjusted.plus(\n borrowValueBorrowFactorAdjustedUsd\n );\n\n const position: Position = {\n reserveAddress: reserve.address,\n mintAddress: reserve.getLiquidityMint(),\n amount: borrowAmount,\n marketValueRefreshed: borrowValueUsd,\n };\n borrows.set(reserve.address, position);\n }\n\n return {\n borrows,\n userTotalBorrow,\n userTotalBorrowBorrowFactorAdjusted,\n positions,\n };\n }\n\n getMaxBorrowAmount(market: KaminoMarket, tokenMint: PublicKey, slot: number): Decimal {\n const reserve = market.getReserveByMint(tokenMint);\n\n if (!reserve) {\n throw new Error('Reserve not found');\n }\n\n const elevationGroupActivated =\n reserve.state.config.elevationGroups.includes(this.state.elevationGroup) && this.state.elevationGroup !== 0;\n\n const reserveBorrowFactor = reserve.getBorrowFactor();\n const borrowFactor = elevationGroupActivated ? new Decimal(1) : reserveBorrowFactor;\n\n const maxObligationBorrowPower = this.refreshedStats.borrowLimit // adjusted available amount\n .minus(this.refreshedStats.userTotalBorrowBorrowFactorAdjusted)\n .div(borrowFactor)\n .div(reserve.getOracleMarketPrice())\n .mul(reserve.getMintFactor());\n const reserveAvailableAmount = reserve.getLiquidityAvailableAmount();\n let reserveBorrowCapRemained = reserve.stats.reserveBorrowLimit.sub(reserve.getBorrowedAmount());\n\n reserveBorrowCapRemained =\n reserve.state.config.disableUsageAsCollOutsideEmode === 1 && !elevationGroupActivated\n ? new Decimal(0)\n : reserveBorrowCapRemained;\n\n let maxBorrowAmount = Decimal.min(maxObligationBorrowPower, reserveAvailableAmount, reserveBorrowCapRemained);\n\n const debtWithdrawalCap = reserve.getDebtWithdrawalCapCapacity().sub(reserve.getDebtWithdrawalCapCurrent(slot));\n maxBorrowAmount = reserve.getDebtWithdrawalCapCapacity().gt(0)\n ? Decimal.min(maxBorrowAmount, debtWithdrawalCap)\n : maxBorrowAmount;\n\n let originationFeeRate = reserve.getBorrowFee();\n\n // Inclusive fee rate\n originationFeeRate = originationFeeRate.div(originationFeeRate.add(new Decimal(1)));\n const borrowFee = maxBorrowAmount.mul(originationFeeRate);\n\n maxBorrowAmount = maxBorrowAmount.sub(borrowFee);\n\n return Decimal.max(new Decimal(0), maxBorrowAmount);\n }\n\n getMaxWithdrawAmount(market: KaminoMarket, tokenMint: PublicKey, slot: number): Decimal {\n const reserve = market.getReserveByMint(tokenMint);\n\n if (!reserve) {\n throw new Error('Reserve not found');\n }\n\n const userDepositPosition = this.getDepositByReserve(reserve.address);\n\n if (!userDepositPosition) {\n throw new Error('Deposit reserve not found');\n }\n\n const userDepositPositionAmount = userDepositPosition.amount;\n\n if (this.refreshedStats.userTotalBorrowBorrowFactorAdjusted.equals(new Decimal(0))) {\n return new Decimal(userDepositPositionAmount);\n }\n\n const elevationGroupActivated =\n reserve.state.config.elevationGroups.includes(this.state.elevationGroup) && this.state.elevationGroup !== 0;\n\n const reserveMaxLtv = elevationGroupActivated\n ? market.getElevationGroup(this.state.elevationGroup).ltvPct / 100\n : reserve.stats.loanToValuePct;\n\n // bf adjusted debt value > allowed_borrow_value\n if (this.refreshedStats.userTotalBorrowBorrowFactorAdjusted >= this.refreshedStats.borrowLimit) {\n return new Decimal(0);\n }\n\n let maxWithdrawValue;\n if (reserveMaxLtv === 0) {\n maxWithdrawValue = userDepositPositionAmount;\n } else {\n // borrowLimit / userTotalDeposit = maxLtv\n // maxWithdrawValue = userTotalDeposit - userTotalBorrow / maxLtv\n maxWithdrawValue = this.refreshedStats.borrowLimit\n .sub(this.refreshedStats.userTotalBorrowBorrowFactorAdjusted)\n .div(reserveMaxLtv)\n .mul(0.995); // remove 0.5% to prevent going over max ltv\n }\n\n const maxWithdrawAmount = maxWithdrawValue.div(reserve.getOracleMarketPrice()).mul(reserve.getMintFactor());\n const reserveAvailableLiquidity = reserve.getLiquidityAvailableAmount();\n\n const withdrawalCapRemained = reserve\n .getDepositWithdrawalCapCapacity()\n .sub(reserve.getDepositWithdrawalCapCurrent(slot));\n return Decimal.max(\n 0,\n Decimal.min(userDepositPositionAmount, maxWithdrawAmount, reserveAvailableLiquidity, withdrawalCapRemained)\n );\n }\n\n /**\n *\n * @returns Total borrowed amount for the specified obligation liquidity/borrow asset\n */\n static getBorrowAmount(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.borrowedAmountSf).toDecimal();\n }\n\n /**\n *\n * @returns Cumulative borrow rate for the specified obligation liquidity/borrow asset\n */\n static getCumulativeBorrowRate(borrow: ObligationLiquidity): Decimal {\n let accSf = new BN(0);\n for (const value of borrow.cumulativeBorrowRateBsf.value.reverse()) {\n accSf = accSf.add(value);\n accSf.shrn(64);\n }\n return new Fraction(accSf).toDecimal();\n }\n\n public static getRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n slot: number\n ): {\n collateralExchangeRates: Map<PublicKey, Decimal>;\n cumulativeBorrowRates: Map<PublicKey, Decimal>;\n } {\n const collateralExchangeRates = KaminoObligation.getCollateralExchangeRatesForObligation(\n kaminoMarket,\n obligation,\n slot\n );\n const cumulativeBorrowRates = KaminoObligation.getCumulativeBorrowRatesForObligation(\n kaminoMarket,\n obligation,\n slot\n );\n\n return {\n collateralExchangeRates,\n cumulativeBorrowRates,\n };\n }\n\n public static addRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n slot: number\n ): void {\n KaminoObligation.addCollateralExchangeRatesForObligation(kaminoMarket, collateralExchangeRates, obligation, slot);\n KaminoObligation.addCumulativeBorrowRatesForObligation(kaminoMarket, cumulativeBorrowRates, obligation, slot);\n }\n\n static getCollateralExchangeRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n slot: number\n ): Map<PublicKey, Decimal> {\n const collateralExchangeRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (let i = 0; i < obligation.deposits.length; i++) {\n const deposit = obligation.deposits[i];\n if (isNotNullPubkey(deposit.depositReserve) && !collateralExchangeRates.has(deposit.depositReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(deposit.depositReserve)!;\n const collateralExchangeRate = reserve.getEstimatedCollateralExchangeRate(\n slot,\n kaminoMarket.state.referralFeeBps\n );\n collateralExchangeRates.set(reserve.address, collateralExchangeRate);\n }\n }\n return collateralExchangeRates;\n }\n\n static addCollateralExchangeRatesForObligation(\n kaminoMarket: KaminoMarket,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n obligation: Obligation,\n slot: number\n ) {\n for (let i = 0; i < obligation.deposits.length; i++) {\n const deposit = obligation.deposits[i];\n if (isNotNullPubkey(deposit.depositReserve) && !collateralExchangeRates.has(deposit.depositReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(deposit.depositReserve)!;\n const collateralExchangeRate = reserve.getEstimatedCollateralExchangeRate(\n slot,\n kaminoMarket.state.referralFeeBps\n );\n collateralExchangeRates.set(reserve.address, collateralExchangeRate);\n }\n }\n }\n\n static getCumulativeBorrowRatesForObligation(kaminoMarket: KaminoMarket, obligation: Obligation, slot: number) {\n const cumulativeBorrowRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (let i = 0; i < obligation.borrows.length; i++) {\n const borrow = obligation.borrows[i];\n if (isNotNullPubkey(borrow.borrowReserve) && !cumulativeBorrowRates.has(borrow.borrowReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(borrow.borrowReserve)!;\n const cumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(slot);\n cumulativeBorrowRates.set(reserve.address, cumulativeBorrowRate);\n }\n }\n return cumulativeBorrowRates;\n }\n\n static addCumulativeBorrowRatesForObligation(\n kaminoMarket: KaminoMarket,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n obligation: Obligation,\n slot: number\n ) {\n for (let i = 0; i < obligation.borrows.length; i++) {\n const borrow = obligation.borrows[i];\n if (isNotNullPubkey(borrow.borrowReserve) && !cumulativeBorrowRates.has(borrow.borrowReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(borrow.borrowReserve)!;\n const cumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(slot);\n cumulativeBorrowRates.set(reserve.address, cumulativeBorrowRate);\n }\n }\n }\n\n static getBorrowFactorForReserve(reserve: KaminoReserve, elevationGroup: number): Decimal {\n if (elevationGroup !== 0) {\n return new Decimal(1);\n }\n return new Decimal(reserve.stats.borrowFactor).div(100);\n }\n}\n"]}
1
+ {"version":3,"file":"obligation.js","sourceRoot":"","sources":["../../src/classes/obligation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,4DAAiC;AAEjC,sDAAqD;AAErD,kDAAuB;AACvB,yCAAsC;AAEtC,mCAAsD;AACtD,oCAA0D;AA+B1D,MAAa,gBAAgB;IAmB3B;;;;;;;OAOG;IACH,YACE,MAAoB,EACpB,iBAA4B,EAC5B,UAAsB,EACtB,uBAAgD,EAChD,qBAA8C;QAuhBhD,mCAA8B,GAAG,CAC/B,OAAsB,EACtB,MAA2B,EAC3B,WAAmB,EACV,EAAE;YACX,MAAM,6BAA6B,GAAG,OAAO,CAAC,gCAAgC,CAAC,WAAW,CAAC,CAAC;YAE5F,MAAM,2BAA2B,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;YAErF,IAAI,6BAA6B,CAAC,EAAE,CAAC,2BAA2B,CAAC,EAAE;gBACjE,OAAO,6BAA6B,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;aACvE;YAED,OAAO,IAAI,oBAAO,CAAC,CAAC,CAAC,CAAC;QACxB,CAAC,CAAC;QAniBA,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC;QACxB,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC,kBAAkB,CACnE,MAAM,EACN,UAAU,EACV,uBAAuB,EACvB,qBAAqB,CACtB,CAAC;QACF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,c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,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1D,CAAC;CACF;AA7gCD,4CA6gCC","sourcesContent":["/* eslint-disable max-classes-per-file */\nimport { PublicKey } from '@solana/web3.js';\nimport Decimal from 'decimal.js';\nimport { KaminoReserve } from './reserve';\nimport { Obligation } from '../idl_codegen/accounts';\nimport { KaminoMarket } from './market';\nimport BN from 'bn.js';\nimport { Fraction } from './fraction';\nimport { ObligationCollateral, ObligationLiquidity } from '../idl_codegen/types';\nimport { positiveOrZero, valueOrZero } from './utils';\nimport { isNotNullPubkey, PubkeyHashMap } from '../utils';\nimport { ActionType } from './action';\n\nexport type Position = {\n reserveAddress: PublicKey;\n mintAddress: PublicKey;\n amount: Decimal;\n marketValueRefreshed: Decimal;\n};\n\nexport type ObligationStats = {\n userTotalDeposit: Decimal;\n userTotalBorrow: Decimal;\n userTotalBorrowBorrowFactorAdjusted: Decimal;\n borrowLimit: Decimal;\n borrowLiquidationLimit: Decimal;\n borrowUtilization: Decimal;\n netAccountValue: Decimal;\n loanToValue: Decimal;\n liquidationLtv: Decimal;\n leverage: Decimal;\n potentialElevationGroupUpdate: Array<number>;\n};\n\ninterface BorrowStats {\n borrows: Map<PublicKey, Position>;\n userTotalBorrow: Decimal;\n userTotalBorrowBorrowFactorAdjusted: Decimal;\n positions: number;\n}\n\nexport class KaminoObligation {\n obligationAddress: PublicKey;\n\n state: Obligation;\n\n /**\n * Deposits stored in a map of reserve address to position\n */\n deposits: Map<PublicKey, Position>;\n\n /**\n * Borrows stored in a map of reserve address to position\n */\n borrows: Map<PublicKey, Position>;\n\n refreshedStats: ObligationStats;\n\n obligationTag: number;\n\n /**\n * Initialise a new Obligation from the deserialized state\n * @param market\n * @param obligationAddress\n * @param obligation\n * @param collateralExchangeRates - rates from the market by reserve address, will be calculated if not provided\n * @param cumulativeBorrowRates - rates from the market by reserve address, will be calculated if not provided\n */\n constructor(\n market: KaminoMarket,\n obligationAddress: PublicKey,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>\n ) {\n this.obligationAddress = obligationAddress;\n this.state = obligation;\n const { borrows, deposits, refreshedStats } = this.calculatePositions(\n market,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n this.deposits = deposits;\n this.borrows = borrows;\n this.refreshedStats = refreshedStats;\n this.obligationTag = obligation.tag.toNumber();\n }\n\n static async load(kaminoMarket: KaminoMarket, obligationAddress: PublicKey): Promise<KaminoObligation | null> {\n const res = await kaminoMarket.getConnection().getAccountInfoAndContext(obligationAddress);\n if (res.value === null) {\n return null;\n }\n const accInfo = res.value;\n if (!accInfo.owner.equals(kaminoMarket.programId)) {\n throw new Error(\"account doesn't belong to this program\");\n }\n const obligation = Obligation.decode(accInfo.data);\n\n if (obligation === null) {\n return null;\n }\n const { collateralExchangeRates, cumulativeBorrowRates } = KaminoObligation.getRatesForObligation(\n kaminoMarket,\n obligation,\n res.context.slot\n );\n return new KaminoObligation(\n kaminoMarket,\n obligationAddress,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n }\n\n static async loadAll(\n kaminoMarket: KaminoMarket,\n obligationAddresses: PublicKey[],\n slot?: number\n ): Promise<(KaminoObligation | null)[]> {\n let currentSlot = slot;\n let obligations: (Obligation | null)[];\n if (!currentSlot) {\n [currentSlot, obligations] = await Promise.all([\n kaminoMarket.getConnection().getSlot(),\n Obligation.fetchMultiple(kaminoMarket.getConnection(), obligationAddresses, kaminoMarket.programId),\n ]);\n } else {\n obligations = await Obligation.fetchMultiple(\n kaminoMarket.getConnection(),\n obligationAddresses,\n kaminoMarket.programId\n );\n }\n const cumulativeBorrowRates = new PubkeyHashMap<PublicKey, Decimal>();\n const collateralExchangeRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (const obligation of obligations) {\n if (obligation !== null) {\n KaminoObligation.addRatesForObligation(\n kaminoMarket,\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates,\n currentSlot\n );\n }\n }\n\n return obligations.map((obligation, i) => {\n if (obligation === null) {\n return null;\n }\n return new KaminoObligation(\n kaminoMarket,\n obligationAddresses[i],\n obligation,\n collateralExchangeRates,\n cumulativeBorrowRates\n );\n });\n }\n\n /**\n * @returns the obligation borrows as a list\n */\n getBorrows(): Array<Position> {\n return [...this.borrows.values()];\n }\n\n /**\n * @returns the obligation borrows as a list\n */\n getDeposits(): Array<Position> {\n return [...this.deposits.values()];\n }\n\n /**\n * @returns the total deposited value of the obligation (sum of all deposits)\n */\n getDepositedValue(): Decimal {\n return new Fraction(this.state.depositedValueSf).toDecimal();\n }\n\n /**\n * @returns the total borrowed value of the obligation (sum of all borrows -- no borrow factor)\n */\n getBorrowedMarketValue(): Decimal {\n return new Fraction(this.state.borrowedAssetsMarketValueSf).toDecimal();\n }\n\n /**\n * @returns the total borrowed value of the obligation (sum of all borrows -- with borrow factor weighting)\n */\n getBorrowedMarketValueBFAdjusted(): Decimal {\n return new Fraction(this.state.borrowFactorAdjustedDebtValueSf).toDecimal();\n }\n\n /**\n * @returns total borrow power of the obligation, relative to max LTV of each asset's reserve\n */\n getAllowedBorrowValue(): Decimal {\n return new Fraction(this.state.allowedBorrowValueSf).toDecimal();\n }\n\n /**\n * @returns the borrow value at which the obligation gets liquidatable\n * (relative to the liquidation threshold of each asset's reserve)\n */\n getUnhealthyBorrowValue(): Decimal {\n return new Fraction(this.state.unhealthyBorrowValueSf).toDecimal();\n }\n\n /**\n *\n * @returns Market value of the deposit in the specified obligation collateral/deposit asset (USD)\n */\n getDepositMarketValue(deposit: ObligationCollateral): Decimal {\n return new Fraction(deposit.marketValueSf).toDecimal();\n }\n\n getBorrowByReserve(reserve: PublicKey): Position | undefined {\n return this.borrows.get(reserve);\n }\n\n getDepositByReserve(reserve: PublicKey): Position | undefined {\n return this.deposits.get(reserve);\n }\n\n getBorrowByMint(mint: PublicKey): Position | undefined {\n for (const value of this.borrows.values()) {\n if (value.mintAddress.equals(mint)) {\n return value;\n }\n }\n return undefined;\n }\n\n getDepositByMint(mint: PublicKey): Position | undefined {\n for (const value of this.deposits.values()) {\n if (value.mintAddress.equals(mint)) {\n return value;\n }\n }\n return undefined;\n }\n\n /**\n *\n * @returns Market value of the borrow in the specified obligation liquidity/borrow asset (USD) (no borrow factor weighting)\n */\n getBorrowMarketValue(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.marketValueSf).toDecimal();\n }\n\n /**\n *\n * @returns Market value of the borrow in the specified obligation liquidity/borrow asset (USD) (with borrow factor weighting)\n */\n getBorrowMarketValueBFAdjusted(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.borrowFactorAdjustedMarketValueSf).toDecimal();\n }\n\n /**\n * Calculate the current ratio of borrowed value to deposited value\n */\n loanToValue(): Decimal {\n if (this.refreshedStats.userTotalDeposit.eq(0)) {\n return new Decimal(0);\n }\n return this.refreshedStats.userTotalBorrowBorrowFactorAdjusted.div(this.refreshedStats.userTotalDeposit);\n }\n\n /**\n * @returns the total number of positions (deposits + borrows)\n */\n getNumberOfPositions(): number {\n return this.deposits.size + this.borrows.size;\n }\n\n getNetAccountValue(): Decimal {\n return this.refreshedStats.netAccountValue;\n }\n\n /**\n * @returns the potential elevation groups the obligation qualifies for\n */\n getElevationGroups(kaminoMarket: KaminoMarket): Array<number> {\n const reserves = new PubkeyHashMap<PublicKey, KaminoReserve>();\n for (const deposit of this.state.deposits.values()) {\n if (isNotNullPubkey(deposit.depositReserve) && !reserves.has(deposit.depositReserve)) {\n reserves.set(deposit.depositReserve, kaminoMarket.getReserveByAddress(deposit.depositReserve)!);\n }\n }\n for (const borrow of this.state.borrows.values()) {\n if (isNotNullPubkey(borrow.borrowReserve) && !reserves.has(borrow.borrowReserve)) {\n reserves.set(borrow.borrowReserve, kaminoMarket.getReserveByAddress(borrow.borrowReserve)!);\n }\n }\n return KaminoObligation.getElevationGroupsForReserves([...reserves.values()]);\n }\n\n static getElevationGroupsForReserves(reserves: Array<KaminoReserve>): Array<number> {\n const elevationGroupsCounts = new Map<number, number>();\n for (const reserve of reserves) {\n for (const elevationGroup of reserve.state.config.elevationGroups) {\n if (elevationGroup !== 0) {\n const count = elevationGroupsCounts.get(elevationGroup);\n if (count) {\n elevationGroupsCounts.set(elevationGroup, count + 1);\n } else {\n elevationGroupsCounts.set(elevationGroup, 1);\n }\n }\n }\n }\n const activeElevationGroups = new Array<number>();\n for (const [group, count] of elevationGroupsCounts.entries()) {\n if (count === reserves.length) {\n activeElevationGroups.push(group);\n }\n }\n return activeElevationGroups;\n }\n\n calculateSimulatedBorrow(\n oldStats: ObligationStats,\n oldBorrows: Map<PublicKey, Position>,\n borrowAmount: Decimal,\n mint: PublicKey,\n reserves: Map<PublicKey, KaminoReserve>\n ): {\n stats: ObligationStats;\n borrows: Map<PublicKey, Position>;\n } {\n const newStats = { ...oldStats };\n const newBorrows = new PubkeyHashMap<PublicKey, Position>([...oldBorrows.entries()]);\n let borrowPosition: Position | undefined = undefined;\n for (const oldBorrow of oldBorrows.values()) {\n if (oldBorrow.mintAddress.equals(mint)) {\n borrowPosition = { ...oldBorrow };\n }\n }\n let reserve: KaminoReserve | undefined = undefined;\n for (const kaminoReserve of reserves.values()) {\n if (kaminoReserve.getLiquidityMint().equals(mint)) {\n reserve = kaminoReserve;\n }\n }\n\n if (!reserve) {\n throw new Error(`No reserve found for mint ${mint}`);\n }\n\n if (!borrowPosition) {\n borrowPosition = {\n reserveAddress: reserve!.address,\n mintAddress: mint,\n amount: new Decimal(0),\n marketValueRefreshed: new Decimal(0),\n };\n }\n\n if (!reserve.state.config.elevationGroups.includes(this.state.elevationGroup)) {\n throw new Error(\n `User would have to downgrade the elevation group in order to be able to borrow from this reserve`\n );\n }\n\n const borrowFactor =\n this.state.elevationGroup !== 0 ? new Decimal(1) : new Decimal(reserve.stats.borrowFactor).div(100);\n\n const borrowValueUSD = borrowAmount.mul(reserve.getOracleMarketPrice()).dividedBy(reserve.getMintFactor());\n\n const borrowValueBorrowFactorAdjustedUSD = borrowValueUSD.mul(borrowFactor);\n\n newStats.userTotalBorrow = positiveOrZero(newStats.userTotalBorrow.plus(borrowValueUSD));\n newStats.userTotalBorrowBorrowFactorAdjusted = positiveOrZero(\n newStats.userTotalBorrowBorrowFactorAdjusted.plus(borrowValueBorrowFactorAdjustedUSD)\n );\n\n borrowPosition.amount = positiveOrZero(borrowPosition.amount.plus(borrowAmount));\n borrowPosition.mintAddress = mint;\n borrowPosition.marketValueRefreshed = positiveOrZero(borrowPosition.marketValueRefreshed.plus(borrowValueUSD));\n\n newBorrows.set(borrowPosition.reserveAddress, borrowPosition);\n return {\n borrows: newBorrows,\n stats: newStats,\n };\n }\n\n calculateSimulatedDeposit(\n oldStats: ObligationStats,\n oldDeposits: Map<PublicKey, Position>,\n amount: Decimal,\n mint: PublicKey,\n reserves: Map<PublicKey, KaminoReserve>,\n market: KaminoMarket\n ): {\n stats: ObligationStats;\n deposits: Map<PublicKey, Position>;\n } {\n const newStats = { ...oldStats };\n const newDeposits = new PubkeyHashMap<PublicKey, Position>([...oldDeposits.entries()]);\n\n let depositPosition: Position | undefined = undefined;\n for (const oldDeposit of oldDeposits.values()) {\n if (oldDeposit.mintAddress.equals(mint)) {\n depositPosition = { ...oldDeposit };\n }\n }\n let reserve: KaminoReserve | undefined = undefined;\n for (const kaminoReserve of reserves.values()) {\n if (kaminoReserve.getLiquidityMint().equals(mint)) {\n reserve = kaminoReserve;\n }\n }\n if (!reserve) {\n throw new Error(`No reserve found for mint ${mint}`);\n }\n\n if (!depositPosition) {\n depositPosition = {\n reserveAddress: reserve!.address,\n mintAddress: mint,\n amount: new Decimal(0),\n marketValueRefreshed: new Decimal(0),\n };\n }\n\n let loanToValue = reserve.stats.loanToValuePct;\n let liqThreshold = reserve.stats.liquidationThreshold;\n\n if (this.state.elevationGroup !== 0) {\n loanToValue = market.getElevationGroup(this.state.elevationGroup).ltvPct / 100;\n liqThreshold = market.getElevationGroup(this.state.elevationGroup).liquidationThresholdPct / 100;\n }\n\n if (!reserve.state.config.elevationGroups.includes(this.state.elevationGroup)) {\n throw new Error(\n `User would have to downgrade the elevation group in order to be able to deposit in this reserve`\n );\n }\n\n const supplyAmount = amount; //.mul(reserve.getCollateralExchangeRate()).floor();\n const supplyAmountMultiplierUSD = supplyAmount\n .mul(reserve.getOracleMarketPrice())\n .dividedBy('1'.concat(Array(reserve.stats.decimals + 1).join('0')));\n\n newStats.userTotalDeposit = positiveOrZero(newStats.userTotalDeposit.plus(supplyAmountMultiplierUSD));\n newStats.borrowLimit = positiveOrZero(newStats.borrowLimit.plus(supplyAmountMultiplierUSD.mul(loanToValue)));\n newStats.borrowLiquidationLimit = positiveOrZero(\n newStats.borrowLiquidationLimit.plus(supplyAmountMultiplierUSD.mul(liqThreshold))\n );\n newStats.liquidationLtv = valueOrZero(newStats.borrowLiquidationLimit.div(newStats.userTotalDeposit));\n\n depositPosition.amount = positiveOrZero(depositPosition.amount.plus(amount));\n depositPosition.mintAddress = mint;\n depositPosition.marketValueRefreshed = positiveOrZero(\n depositPosition.marketValueRefreshed.plus(\n supplyAmount.mul(reserve.getOracleMarketPrice()).dividedBy(reserve.getMintFactor())\n )\n );\n\n newDeposits.set(depositPosition.reserveAddress, depositPosition);\n\n return {\n deposits: newDeposits,\n stats: newStats,\n };\n }\n\n /**\n * Calculate the newly modified stats of the obligation\n */\n // TODO: Elevation group problems\n // TODO: Shall we set up position limits?\n getSimulatedObligationStats(\n amount: Decimal,\n action: ActionType,\n mint: PublicKey,\n market: KaminoMarket,\n reserves: Map<PublicKey, KaminoReserve>\n ): {\n stats: ObligationStats;\n deposits: Map<PublicKey, Position>;\n borrows: Map<PublicKey, Position>;\n } {\n let newStats = { ...this.refreshedStats };\n let newDeposits: Map<PublicKey, Position> = new PubkeyHashMap<PublicKey, Position>([...this.deposits.entries()]);\n let newBorrows: Map<PublicKey, Position> = new PubkeyHashMap<PublicKey, Position>([...this.borrows.entries()]);\n\n switch (action) {\n case 'deposit': {\n const { stats, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n\n newStats = stats;\n newDeposits = deposits;\n\n break;\n }\n case 'borrow': {\n const { stats, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n amount,\n mint,\n reserves\n );\n newStats = stats;\n newBorrows = borrows;\n break;\n }\n case 'repay': {\n const { stats, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n new Decimal(amount).neg(),\n mint,\n reserves\n );\n newStats = stats;\n newBorrows = borrows;\n break;\n }\n\n case 'withdraw': {\n const { stats, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n new Decimal(amount).neg(),\n mint,\n reserves,\n market\n );\n newStats = stats;\n newDeposits = deposits;\n break;\n }\n case 'depositAndBorrow': {\n const { stats: statsAfterDeposit, deposits } = this.calculateSimulatedDeposit(\n this.refreshedStats,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n const { stats, borrows } = this.calculateSimulatedBorrow(\n statsAfterDeposit,\n this.borrows,\n amount,\n mint,\n reserves\n );\n\n newStats = stats;\n newDeposits = deposits;\n newBorrows = borrows;\n break;\n }\n case 'repayAndWithdraw': {\n const { stats: statsAfterRepay, borrows } = this.calculateSimulatedBorrow(\n this.refreshedStats,\n this.borrows,\n new Decimal(amount).neg(),\n mint,\n reserves\n );\n const { stats: statsAfterWithdraw, deposits } = this.calculateSimulatedDeposit(\n statsAfterRepay,\n this.deposits,\n amount,\n mint,\n reserves,\n market\n );\n newStats = statsAfterWithdraw;\n newDeposits = deposits;\n newBorrows = borrows;\n break;\n }\n default: {\n throw Error(`Invalid action type ${action} for getSimulatedObligationStats`);\n }\n }\n newStats.netAccountValue = newStats.userTotalDeposit.minus(newStats.userTotalBorrow);\n newStats.loanToValue = valueOrZero(\n newStats.userTotalBorrowBorrowFactorAdjusted.dividedBy(newStats.userTotalDeposit)\n );\n newStats.leverage = valueOrZero(newStats.userTotalDeposit.dividedBy(newStats.netAccountValue));\n\n return {\n stats: newStats,\n deposits: newDeposits,\n borrows: newBorrows,\n };\n }\n\n estimateObligationInterestRate = (\n reserve: KaminoReserve,\n borrow: ObligationLiquidity,\n currentSlot: number\n ): Decimal => {\n const estimatedCumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(currentSlot);\n\n const currentCumulativeBorrowRate = KaminoObligation.getCumulativeBorrowRate(borrow);\n\n if (estimatedCumulativeBorrowRate.gt(currentCumulativeBorrowRate)) {\n return estimatedCumulativeBorrowRate.div(currentCumulativeBorrowRate);\n }\n\n return new Decimal(0);\n };\n\n private calculateDeposits(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n getPx: (reserve: KaminoReserve) => Decimal\n ): {\n deposits: Map<PublicKey, Position>;\n userTotalDeposit: Decimal;\n borrowLimit: Decimal;\n liquidationLtv: Decimal;\n borrowLiquidationLimit: Decimal;\n } {\n return KaminoObligation.calculateObligationDeposits(market, obligation, collateralExchangeRates, getPx);\n }\n\n private calculateBorrows(\n market: KaminoMarket,\n obligation: Obligation,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n getPx: (reserve: KaminoReserve) => Decimal\n ): BorrowStats {\n return KaminoObligation.calculateObligationBorrows(market, obligation, cumulativeBorrowRates, getPx);\n }\n\n private calculatePositions(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>\n ): {\n borrows: Map<PublicKey, Position>;\n deposits: Map<PublicKey, Position>;\n refreshedStats: ObligationStats;\n } {\n const commonElevationGroups = this.getElevationGroups(market);\n\n const getOraclePx = (reserve: KaminoReserve) => reserve.getOracleMarketPrice();\n const depositStatsOraclePrice = this.calculateDeposits(market, obligation, collateralExchangeRates, getOraclePx);\n\n const borrowStatsOraclePrice = this.calculateBorrows(market, obligation, cumulativeBorrowRates, getOraclePx);\n\n const netAccountValueScopeRefreshed = depositStatsOraclePrice.userTotalDeposit.minus(\n borrowStatsOraclePrice.userTotalBorrow\n );\n\n return {\n deposits: depositStatsOraclePrice.deposits,\n borrows: borrowStatsOraclePrice.borrows,\n refreshedStats: {\n borrowLimit: depositStatsOraclePrice.borrowLimit,\n borrowLiquidationLimit: depositStatsOraclePrice.borrowLiquidationLimit,\n userTotalBorrow: borrowStatsOraclePrice.userTotalBorrow,\n userTotalBorrowBorrowFactorAdjusted: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted,\n userTotalDeposit: depositStatsOraclePrice.userTotalDeposit,\n liquidationLtv: depositStatsOraclePrice.liquidationLtv,\n borrowUtilization: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted.dividedBy(\n depositStatsOraclePrice.borrowLimit\n ),\n netAccountValue: netAccountValueScopeRefreshed,\n leverage: depositStatsOraclePrice.userTotalDeposit.dividedBy(netAccountValueScopeRefreshed),\n loanToValue: borrowStatsOraclePrice.userTotalBorrowBorrowFactorAdjusted.dividedBy(\n depositStatsOraclePrice.userTotalDeposit\n ),\n potentialElevationGroupUpdate: commonElevationGroups,\n },\n };\n }\n\n public static calculateObligationDeposits(\n market: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal> | null,\n getPx: (reserve: KaminoReserve) => Decimal\n ): {\n deposits: Map<PublicKey, Position>;\n userTotalDeposit: Decimal;\n userTotalCollateralDeposit: Decimal;\n borrowLimit: Decimal;\n liquidationLtv: Decimal;\n borrowLiquidationLimit: Decimal;\n } {\n let userTotalDeposit = new Decimal(0);\n let userTotalCollateralDeposit = new Decimal(0);\n let borrowLimit = new Decimal(0);\n let borrowLiquidationLimit = new Decimal(0);\n\n const deposits = new PubkeyHashMap<PublicKey, Position>();\n for (let i = 0; i < obligation.deposits.length; i++) {\n if (!isNotNullPubkey(obligation.deposits[i].depositReserve)) {\n continue;\n }\n const deposit = obligation.deposits[i];\n const reserve = market.getReserveByAddress(deposit.depositReserve);\n if (!reserve) {\n throw new Error(\n `Obligation contains a deposit belonging to reserve: ${deposit.depositReserve} but the reserve was not found on the market. Deposit amount: ${deposit.depositedAmount}`\n );\n }\n let loanToValue = reserve.stats.loanToValuePct;\n let liqThreshold = reserve.stats.liquidationThreshold;\n\n if (obligation.elevationGroup !== 0) {\n loanToValue = market.state.elevationGroups[obligation.elevationGroup - 1].ltvPct / 100;\n liqThreshold = market.state.elevationGroups[obligation.elevationGroup - 1].liquidationThresholdPct / 100;\n }\n\n let exchangeRate;\n if (collateralExchangeRates !== null) {\n exchangeRate = collateralExchangeRates.get(reserve.address)!;\n } else {\n exchangeRate = reserve.getCollateralExchangeRate();\n }\n const supplyAmount = new Decimal(deposit.depositedAmount.toString()).div(exchangeRate);\n\n const depositValueUsd = supplyAmount.mul(getPx(reserve)).div(reserve.getMintFactor());\n\n userTotalDeposit = userTotalDeposit.add(depositValueUsd);\n\n if (loanToValue !== 0) {\n userTotalCollateralDeposit = userTotalCollateralDeposit.add(depositValueUsd);\n }\n\n borrowLimit = borrowLimit.add(depositValueUsd.mul(loanToValue));\n borrowLiquidationLimit = borrowLiquidationLimit.add(depositValueUsd.mul(liqThreshold));\n\n const position: Position = {\n reserveAddress: reserve.address,\n mintAddress: reserve.getLiquidityMint(),\n amount: supplyAmount,\n marketValueRefreshed: depositValueUsd,\n };\n deposits.set(reserve.address, position);\n }\n\n return {\n deposits,\n userTotalDeposit,\n userTotalCollateralDeposit,\n borrowLimit,\n liquidationLtv: valueOrZero(borrowLiquidationLimit.div(userTotalDeposit)),\n borrowLiquidationLimit,\n };\n }\n\n public static calculateObligationBorrows(\n market: KaminoMarket,\n obligation: Obligation,\n cumulativeBorrowRates: Map<PublicKey, Decimal> | null,\n getPx: (reserve: KaminoReserve) => Decimal\n ): BorrowStats {\n let userTotalBorrow = new Decimal(0);\n let userTotalBorrowBorrowFactorAdjusted = new Decimal(0);\n let positions = 0;\n\n const borrows = new PubkeyHashMap<PublicKey, Position>();\n for (let i = 0; i < obligation.borrows.length; i++) {\n if (!isNotNullPubkey(obligation.borrows[i].borrowReserve)) {\n continue;\n }\n const borrow = obligation.borrows[i];\n const reserve = market.getReserveByAddress(borrow.borrowReserve);\n if (!reserve) {\n throw new Error(\n `Obligation contains a borrow belonging to reserve: ${\n borrow.borrowReserve\n } but the reserve was not found on the market. Borrow amount: ${KaminoObligation.getBorrowAmount(borrow)}`\n );\n }\n\n const obligationCumulativeBorrowRate = KaminoObligation.getCumulativeBorrowRate(borrow);\n let cumulativeBorrowRate;\n if (cumulativeBorrowRates !== null) {\n cumulativeBorrowRate = cumulativeBorrowRates.get(reserve.address)!;\n } else {\n cumulativeBorrowRate = reserve.getCumulativeBorrowRate();\n }\n\n const borrowAmount = KaminoObligation.getBorrowAmount(borrow)\n .mul(cumulativeBorrowRate)\n .dividedBy(obligationCumulativeBorrowRate);\n\n const borrowValueUsd = borrowAmount.mul(getPx(reserve)).dividedBy(reserve.getMintFactor());\n\n const borrowFactor = KaminoObligation.getBorrowFactorForReserve(reserve, obligation.elevationGroup);\n const borrowValueBorrowFactorAdjustedUsd = borrowValueUsd.mul(borrowFactor);\n\n if (!borrowAmount.eq(new Decimal('0'))) {\n positions += 1;\n }\n\n userTotalBorrow = userTotalBorrow.plus(borrowValueUsd);\n userTotalBorrowBorrowFactorAdjusted = userTotalBorrowBorrowFactorAdjusted.plus(\n borrowValueBorrowFactorAdjustedUsd\n );\n\n const position: Position = {\n reserveAddress: reserve.address,\n mintAddress: reserve.getLiquidityMint(),\n amount: borrowAmount,\n marketValueRefreshed: borrowValueUsd,\n };\n borrows.set(reserve.address, position);\n }\n\n return {\n borrows,\n userTotalBorrow,\n userTotalBorrowBorrowFactorAdjusted,\n positions,\n };\n }\n\n getMaxBorrowAmount(market: KaminoMarket, tokenMint: PublicKey, slot: number): Decimal {\n const reserve = market.getReserveByMint(tokenMint);\n\n if (!reserve) {\n throw new Error('Reserve not found');\n }\n\n const elevationGroupActivated =\n reserve.state.config.elevationGroups.includes(this.state.elevationGroup) && this.state.elevationGroup !== 0;\n\n const reserveBorrowFactor = reserve.getBorrowFactor();\n const borrowFactor = elevationGroupActivated ? new Decimal(1) : reserveBorrowFactor;\n\n const maxObligationBorrowPower = this.refreshedStats.borrowLimit // adjusted available amount\n .minus(this.refreshedStats.userTotalBorrowBorrowFactorAdjusted)\n .div(borrowFactor)\n .div(reserve.getOracleMarketPrice())\n .mul(reserve.getMintFactor());\n const reserveAvailableAmount = reserve.getLiquidityAvailableAmount();\n let reserveBorrowCapRemained = reserve.stats.reserveBorrowLimit.sub(reserve.getBorrowedAmount());\n\n reserveBorrowCapRemained =\n reserve.state.config.disableUsageAsCollOutsideEmode === 1 && !elevationGroupActivated\n ? new Decimal(0)\n : reserveBorrowCapRemained;\n\n let maxBorrowAmount = Decimal.min(maxObligationBorrowPower, reserveAvailableAmount, reserveBorrowCapRemained);\n\n const debtWithdrawalCap = reserve.getDebtWithdrawalCapCapacity().sub(reserve.getDebtWithdrawalCapCurrent(slot));\n maxBorrowAmount = reserve.getDebtWithdrawalCapCapacity().gt(0)\n ? Decimal.min(maxBorrowAmount, debtWithdrawalCap)\n : maxBorrowAmount;\n\n let originationFeeRate = reserve.getBorrowFee();\n\n // Inclusive fee rate\n originationFeeRate = originationFeeRate.div(originationFeeRate.add(new Decimal(1)));\n const borrowFee = maxBorrowAmount.mul(originationFeeRate);\n\n maxBorrowAmount = maxBorrowAmount.sub(borrowFee);\n\n const utilizationRatioLimit = reserve.state.config.utilizationLimitBlockBorrowingAbove / 100;\n const currentUtilizationRatio = reserve.calculateUtilizationRatio();\n\n if (utilizationRatioLimit > 0 && currentUtilizationRatio > utilizationRatioLimit) {\n return new Decimal(0);\n } else if (utilizationRatioLimit > 0 && currentUtilizationRatio < utilizationRatioLimit) {\n const maxBorrowBasedOnUtilization = new Decimal(utilizationRatioLimit - currentUtilizationRatio).mul(\n reserve.getTotalSupply()\n );\n maxBorrowAmount = Decimal.min(maxBorrowAmount, maxBorrowBasedOnUtilization);\n }\n\n return Decimal.max(new Decimal(0), maxBorrowAmount);\n }\n\n getMaxWithdrawAmount(market: KaminoMarket, tokenMint: PublicKey, slot: number): Decimal {\n const reserve = market.getReserveByMint(tokenMint);\n\n if (!reserve) {\n throw new Error('Reserve not found');\n }\n\n const userDepositPosition = this.getDepositByReserve(reserve.address);\n\n if (!userDepositPosition) {\n throw new Error('Deposit reserve not found');\n }\n\n const userDepositPositionAmount = userDepositPosition.amount;\n\n if (this.refreshedStats.userTotalBorrowBorrowFactorAdjusted.equals(new Decimal(0))) {\n return new Decimal(userDepositPositionAmount);\n }\n\n const elevationGroupActivated =\n reserve.state.config.elevationGroups.includes(this.state.elevationGroup) && this.state.elevationGroup !== 0;\n\n const reserveMaxLtv = elevationGroupActivated\n ? market.getElevationGroup(this.state.elevationGroup).ltvPct / 100\n : reserve.stats.loanToValuePct;\n\n // bf adjusted debt value > allowed_borrow_value\n if (this.refreshedStats.userTotalBorrowBorrowFactorAdjusted >= this.refreshedStats.borrowLimit) {\n return new Decimal(0);\n }\n\n let maxWithdrawValue;\n if (reserveMaxLtv === 0) {\n maxWithdrawValue = userDepositPositionAmount;\n } else {\n // borrowLimit / userTotalDeposit = maxLtv\n // maxWithdrawValue = userTotalDeposit - userTotalBorrow / maxLtv\n maxWithdrawValue = this.refreshedStats.borrowLimit\n .sub(this.refreshedStats.userTotalBorrowBorrowFactorAdjusted)\n .div(reserveMaxLtv)\n .mul(0.999); // remove 0.1% to prevent going over max ltv\n }\n\n const maxWithdrawAmount = maxWithdrawValue.div(reserve.getOracleMarketPrice()).mul(reserve.getMintFactor());\n const reserveAvailableLiquidity = reserve.getLiquidityAvailableAmount();\n\n const withdrawalCapRemained = reserve\n .getDepositWithdrawalCapCapacity()\n .sub(reserve.getDepositWithdrawalCapCurrent(slot));\n return Decimal.max(\n 0,\n Decimal.min(userDepositPositionAmount, maxWithdrawAmount, reserveAvailableLiquidity, withdrawalCapRemained)\n );\n }\n\n /**\n *\n * @returns Total borrowed amount for the specified obligation liquidity/borrow asset\n */\n static getBorrowAmount(borrow: ObligationLiquidity): Decimal {\n return new Fraction(borrow.borrowedAmountSf).toDecimal();\n }\n\n /**\n *\n * @returns Cumulative borrow rate for the specified obligation liquidity/borrow asset\n */\n static getCumulativeBorrowRate(borrow: ObligationLiquidity): Decimal {\n let accSf = new BN(0);\n for (const value of borrow.cumulativeBorrowRateBsf.value.reverse()) {\n accSf = accSf.add(value);\n accSf.shrn(64);\n }\n return new Fraction(accSf).toDecimal();\n }\n\n public static getRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n slot: number\n ): {\n collateralExchangeRates: Map<PublicKey, Decimal>;\n cumulativeBorrowRates: Map<PublicKey, Decimal>;\n } {\n const collateralExchangeRates = KaminoObligation.getCollateralExchangeRatesForObligation(\n kaminoMarket,\n obligation,\n slot\n );\n const cumulativeBorrowRates = KaminoObligation.getCumulativeBorrowRatesForObligation(\n kaminoMarket,\n obligation,\n slot\n );\n\n return {\n collateralExchangeRates,\n cumulativeBorrowRates,\n };\n }\n\n public static addRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n slot: number\n ): void {\n KaminoObligation.addCollateralExchangeRatesForObligation(kaminoMarket, collateralExchangeRates, obligation, slot);\n KaminoObligation.addCumulativeBorrowRatesForObligation(kaminoMarket, cumulativeBorrowRates, obligation, slot);\n }\n\n static getCollateralExchangeRatesForObligation(\n kaminoMarket: KaminoMarket,\n obligation: Obligation,\n slot: number\n ): Map<PublicKey, Decimal> {\n const collateralExchangeRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (let i = 0; i < obligation.deposits.length; i++) {\n const deposit = obligation.deposits[i];\n if (isNotNullPubkey(deposit.depositReserve) && !collateralExchangeRates.has(deposit.depositReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(deposit.depositReserve)!;\n const collateralExchangeRate = reserve.getEstimatedCollateralExchangeRate(\n slot,\n kaminoMarket.state.referralFeeBps\n );\n collateralExchangeRates.set(reserve.address, collateralExchangeRate);\n }\n }\n return collateralExchangeRates;\n }\n\n static addCollateralExchangeRatesForObligation(\n kaminoMarket: KaminoMarket,\n collateralExchangeRates: Map<PublicKey, Decimal>,\n obligation: Obligation,\n slot: number\n ) {\n for (let i = 0; i < obligation.deposits.length; i++) {\n const deposit = obligation.deposits[i];\n if (isNotNullPubkey(deposit.depositReserve) && !collateralExchangeRates.has(deposit.depositReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(deposit.depositReserve)!;\n const collateralExchangeRate = reserve.getEstimatedCollateralExchangeRate(\n slot,\n kaminoMarket.state.referralFeeBps\n );\n collateralExchangeRates.set(reserve.address, collateralExchangeRate);\n }\n }\n }\n\n static getCumulativeBorrowRatesForObligation(kaminoMarket: KaminoMarket, obligation: Obligation, slot: number) {\n const cumulativeBorrowRates = new PubkeyHashMap<PublicKey, Decimal>();\n for (let i = 0; i < obligation.borrows.length; i++) {\n const borrow = obligation.borrows[i];\n if (isNotNullPubkey(borrow.borrowReserve) && !cumulativeBorrowRates.has(borrow.borrowReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(borrow.borrowReserve)!;\n const cumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(slot);\n cumulativeBorrowRates.set(reserve.address, cumulativeBorrowRate);\n }\n }\n return cumulativeBorrowRates;\n }\n\n static addCumulativeBorrowRatesForObligation(\n kaminoMarket: KaminoMarket,\n cumulativeBorrowRates: Map<PublicKey, Decimal>,\n obligation: Obligation,\n slot: number\n ) {\n for (let i = 0; i < obligation.borrows.length; i++) {\n const borrow = obligation.borrows[i];\n if (isNotNullPubkey(borrow.borrowReserve) && !cumulativeBorrowRates.has(borrow.borrowReserve)) {\n const reserve = kaminoMarket.getReserveByAddress(borrow.borrowReserve)!;\n const cumulativeBorrowRate = reserve.getEstimatedCumulativeBorrowRate(slot);\n cumulativeBorrowRates.set(reserve.address, cumulativeBorrowRate);\n }\n }\n }\n\n static getBorrowFactorForReserve(reserve: KaminoReserve, elevationGroup: number): Decimal {\n if (elevationGroup !== 0) {\n return new Decimal(1);\n }\n return new Decimal(reserve.stats.borrowFactor).div(100);\n }\n}\n"]}
package/dist/idl.json CHANGED
@@ -2575,6 +2575,12 @@
2575
2575
  },
2576
2576
  {
2577
2577
  "name": "UpdateDisableUsageAsCollateralOutsideEmode"
2578
+ },
2579
+ {
2580
+ "name": "UpdateBlockBorrowingAboveUtilization"
2581
+ },
2582
+ {
2583
+ "name": "UpdateBlockPriceUsage"
2578
2584
  }
2579
2585
  ]
2580
2586
  }
@@ -3212,12 +3218,16 @@
3212
3218
  "name": "disableUsageAsCollOutsideEmode",
3213
3219
  "type": "u8"
3214
3220
  },
3221
+ {
3222
+ "name": "utilizationLimitBlockBorrowingAbove",
3223
+ "type": "u8"
3224
+ },
3215
3225
  {
3216
3226
  "name": "reserved1",
3217
3227
  "type": {
3218
3228
  "array": [
3219
3229
  "u8",
3220
- 3
3230
+ 2
3221
3231
  ]
3222
3232
  }
3223
3233
  }
@@ -3637,12 +3647,25 @@
3637
3647
  "defined": "PythConfiguration"
3638
3648
  }
3639
3649
  },
3650
+ {
3651
+ "name": "blockPriceUsage",
3652
+ "type": "u8"
3653
+ },
3654
+ {
3655
+ "name": "reserved",
3656
+ "type": {
3657
+ "array": [
3658
+ "u8",
3659
+ 7
3660
+ ]
3661
+ }
3662
+ },
3640
3663
  {
3641
3664
  "name": "padding",
3642
3665
  "type": {
3643
3666
  "array": [
3644
3667
  "u64",
3645
- 20
3668
+ 19
3646
3669
  ]
3647
3670
  }
3648
3671
  }
@@ -4175,6 +4198,11 @@
4175
4198
  "code": 6097,
4176
4199
  "name": "ReserveAccountingMismatch",
4177
4200
  "msg": "Reserve internal state accounting has been unexpectedly modified"
4201
+ },
4202
+ {
4203
+ "code": 6098,
4204
+ "name": "BorrowingAboveUtilizationRateDisabled",
4205
+ "msg": "Borrowing above set utilization rate is disabled"
4178
4206
  }
4179
4207
  ]
4180
4208
  }
@@ -1,4 +1,4 @@
1
- export type CustomError = InvalidMarketAuthority | InvalidMarketOwner | InvalidAccountOwner | InvalidAmount | InvalidConfig | InvalidSigner | InvalidAccountInput | MathOverflow | InsufficientLiquidity | ReserveStale | WithdrawTooSmall | WithdrawTooLarge | BorrowTooSmall | BorrowTooLarge | RepayTooSmall | LiquidationTooSmall | ObligationHealthy | ObligationStale | ObligationReserveLimit | InvalidObligationOwner | ObligationDepositsEmpty | ObligationBorrowsEmpty | ObligationDepositsZero | ObligationBorrowsZero | InvalidObligationCollateral | InvalidObligationLiquidity | ObligationCollateralEmpty | ObligationLiquidityEmpty | NegativeInterestRate | InvalidOracleConfig | InsufficientProtocolFeesToRedeem | FlashBorrowCpi | NoFlashRepayFound | InvalidFlashRepay | FlashRepayCpi | MultipleFlashBorrows | FlashLoansDisabled | SwitchboardV2Error | CouldNotDeserializeScope | PriceTooOld | PriceTooDivergentFromTwap | InvalidTwapPrice | GlobalEmergencyMode | InvalidFlag | PriceNotValid | PriceIsBiggerThanHeuristic | PriceIsLowerThanHeuristic | PriceIsZero | PriceConfidenceTooWide | IntegerOverflow | NoFarmForReserve | IncorrectInstructionInPosition | NoPriceFound | InvalidTwapConfig | InvalidPythPriceAccount | InvalidSwitchboardAccount | InvalidScopePriceAccount | ObligationCollateralLtvZero | InvalidObligationSeedsValue | InvalidObligationId | InvalidBorrowRateCurvePoint | InvalidUtilizationRate | CannotSocializeObligationWithCollateral | ObligationEmpty | WithdrawalCapReached | LastTimestampGreaterThanCurrent | LiquidationSlippageError | IsolatedAssetTierViolation | InconsistentElevationGroup | InvalidElevationGroup | InvalidElevationGroupConfig | UnhealthyElevationGroupLtv | ElevationGroupNewLoansDisabled | ReserveDeprecated | ReferrerAccountNotInitialized | ReferrerAccountMintMissmatch | ReferrerAccountWrongAddress | ReferrerAccountReferrerMissmatch | ReferrerAccountMissing | InsufficientReferralFeesToRedeem | CpiDisabled | ShortUrlNotAsciiAlphanumeric | ReserveObsolete | ElevationGroupAlreadyActivated | ObligationInDeprecatedReserve | ReferrerStateOwnerMismatch | UserMetadataOwnerAlreadySet | CollateralNonLiquidatable | BorrowingDisabled | BorrowLimitExceeded | DepositLimitExceeded | BorrowingDisabledOutsideElevationGroup | NetValueRemainingTooSmall | WorseLTVBlocked | LiabilitiesBiggerThanAssets | ReserveTokenBalanceMismatch | ReserveVaultBalanceMismatch | ReserveAccountingMismatch;
1
+ export type CustomError = InvalidMarketAuthority | InvalidMarketOwner | InvalidAccountOwner | InvalidAmount | InvalidConfig | InvalidSigner | InvalidAccountInput | MathOverflow | InsufficientLiquidity | ReserveStale | WithdrawTooSmall | WithdrawTooLarge | BorrowTooSmall | BorrowTooLarge | RepayTooSmall | LiquidationTooSmall | ObligationHealthy | ObligationStale | ObligationReserveLimit | InvalidObligationOwner | ObligationDepositsEmpty | ObligationBorrowsEmpty | ObligationDepositsZero | ObligationBorrowsZero | InvalidObligationCollateral | InvalidObligationLiquidity | ObligationCollateralEmpty | ObligationLiquidityEmpty | NegativeInterestRate | InvalidOracleConfig | InsufficientProtocolFeesToRedeem | FlashBorrowCpi | NoFlashRepayFound | InvalidFlashRepay | FlashRepayCpi | MultipleFlashBorrows | FlashLoansDisabled | SwitchboardV2Error | CouldNotDeserializeScope | PriceTooOld | PriceTooDivergentFromTwap | InvalidTwapPrice | GlobalEmergencyMode | InvalidFlag | PriceNotValid | PriceIsBiggerThanHeuristic | PriceIsLowerThanHeuristic | PriceIsZero | PriceConfidenceTooWide | IntegerOverflow | NoFarmForReserve | IncorrectInstructionInPosition | NoPriceFound | InvalidTwapConfig | InvalidPythPriceAccount | InvalidSwitchboardAccount | InvalidScopePriceAccount | ObligationCollateralLtvZero | InvalidObligationSeedsValue | InvalidObligationId | InvalidBorrowRateCurvePoint | InvalidUtilizationRate | CannotSocializeObligationWithCollateral | ObligationEmpty | WithdrawalCapReached | LastTimestampGreaterThanCurrent | LiquidationSlippageError | IsolatedAssetTierViolation | InconsistentElevationGroup | InvalidElevationGroup | InvalidElevationGroupConfig | UnhealthyElevationGroupLtv | ElevationGroupNewLoansDisabled | ReserveDeprecated | ReferrerAccountNotInitialized | ReferrerAccountMintMissmatch | ReferrerAccountWrongAddress | ReferrerAccountReferrerMissmatch | ReferrerAccountMissing | InsufficientReferralFeesToRedeem | CpiDisabled | ShortUrlNotAsciiAlphanumeric | ReserveObsolete | ElevationGroupAlreadyActivated | ObligationInDeprecatedReserve | ReferrerStateOwnerMismatch | UserMetadataOwnerAlreadySet | CollateralNonLiquidatable | BorrowingDisabled | BorrowLimitExceeded | DepositLimitExceeded | BorrowingDisabledOutsideElevationGroup | NetValueRemainingTooSmall | WorseLTVBlocked | LiabilitiesBiggerThanAssets | ReserveTokenBalanceMismatch | ReserveVaultBalanceMismatch | ReserveAccountingMismatch | BorrowingAboveUtilizationRateDisabled;
2
2
  export declare class InvalidMarketAuthority extends Error {
3
3
  readonly logs?: string[] | undefined;
4
4
  static readonly code = 6000;
@@ -783,4 +783,12 @@ export declare class ReserveAccountingMismatch extends Error {
783
783
  readonly msg = "Reserve internal state accounting has been unexpectedly modified";
784
784
  constructor(logs?: string[] | undefined);
785
785
  }
786
+ export declare class BorrowingAboveUtilizationRateDisabled extends Error {
787
+ readonly logs?: string[] | undefined;
788
+ static readonly code = 6098;
789
+ readonly code = 6098;
790
+ readonly name = "BorrowingAboveUtilizationRateDisabled";
791
+ readonly msg = "Borrowing above set utilization rate is disabled";
792
+ constructor(logs?: string[] | undefined);
793
+ }
786
794
  export declare function fromCode(code: number, logs?: string[]): CustomError | null;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.IntegerOverflow = exports.PriceConfidenceTooWide = exports.PriceIsZero = exports.PriceIsLowerThanHeuristic = exports.PriceIsBiggerThanHeuristic = exports.PriceNotValid = exports.InvalidFlag = exports.GlobalEmergencyMode = exports.InvalidTwapPrice = exports.PriceTooDivergentFromTwap = exports.PriceTooOld = exports.CouldNotDeserializeScope = exports.SwitchboardV2Error = exports.FlashLoansDisabled = exports.MultipleFlashBorrows = exports.FlashRepayCpi = exports.InvalidFlashRepay = exports.NoFlashRepayFound = exports.FlashBorrowCpi = exports.InsufficientProtocolFeesToRedeem = exports.InvalidOracleConfig = exports.NegativeInterestRate = exports.ObligationLiquidityEmpty = exports.ObligationCollateralEmpty = exports.InvalidObligationLiquidity = exports.InvalidObligationCollateral = exports.ObligationBorrowsZero = exports.ObligationDepositsZero = exports.ObligationBorrowsEmpty = exports.ObligationDepositsEmpty = exports.InvalidObligationOwner = exports.ObligationReserveLimit = exports.ObligationStale = exports.ObligationHealthy = exports.LiquidationTooSmall = exports.RepayTooSmall = exports.BorrowTooLarge = exports.BorrowTooSmall = exports.WithdrawTooLarge = exports.WithdrawTooSmall = exports.ReserveStale = exports.InsufficientLiquidity = exports.MathOverflow = exports.InvalidAccountInput = exports.InvalidSigner = exports.InvalidConfig = exports.InvalidAmount = exports.InvalidAccountOwner = exports.InvalidMarketOwner = exports.InvalidMarketAuthority = void 0;
4
- exports.fromCode = exports.ReserveAccountingMismatch = exports.ReserveVaultBalanceMismatch = exports.ReserveTokenBalanceMismatch = exports.LiabilitiesBiggerThanAssets = exports.WorseLTVBlocked = exports.NetValueRemainingTooSmall = exports.BorrowingDisabledOutsideElevationGroup = exports.DepositLimitExceeded = exports.BorrowLimitExceeded = exports.BorrowingDisabled = exports.CollateralNonLiquidatable = exports.UserMetadataOwnerAlreadySet = exports.ReferrerStateOwnerMismatch = exports.ObligationInDeprecatedReserve = exports.ElevationGroupAlreadyActivated = exports.ReserveObsolete = exports.ShortUrlNotAsciiAlphanumeric = exports.CpiDisabled = exports.InsufficientReferralFeesToRedeem = exports.ReferrerAccountMissing = exports.ReferrerAccountReferrerMissmatch = exports.ReferrerAccountWrongAddress = exports.ReferrerAccountMintMissmatch = exports.ReferrerAccountNotInitialized = exports.ReserveDeprecated = exports.ElevationGroupNewLoansDisabled = exports.UnhealthyElevationGroupLtv = exports.InvalidElevationGroupConfig = exports.InvalidElevationGroup = exports.InconsistentElevationGroup = exports.IsolatedAssetTierViolation = exports.LiquidationSlippageError = exports.LastTimestampGreaterThanCurrent = exports.WithdrawalCapReached = exports.ObligationEmpty = exports.CannotSocializeObligationWithCollateral = exports.InvalidUtilizationRate = exports.InvalidBorrowRateCurvePoint = exports.InvalidObligationId = exports.InvalidObligationSeedsValue = exports.ObligationCollateralLtvZero = exports.InvalidScopePriceAccount = exports.InvalidSwitchboardAccount = exports.InvalidPythPriceAccount = exports.InvalidTwapConfig = exports.NoPriceFound = exports.IncorrectInstructionInPosition = exports.NoFarmForReserve = void 0;
4
+ exports.fromCode = exports.BorrowingAboveUtilizationRateDisabled = exports.ReserveAccountingMismatch = exports.ReserveVaultBalanceMismatch = exports.ReserveTokenBalanceMismatch = exports.LiabilitiesBiggerThanAssets = exports.WorseLTVBlocked = exports.NetValueRemainingTooSmall = exports.BorrowingDisabledOutsideElevationGroup = exports.DepositLimitExceeded = exports.BorrowLimitExceeded = exports.BorrowingDisabled = exports.CollateralNonLiquidatable = exports.UserMetadataOwnerAlreadySet = exports.ReferrerStateOwnerMismatch = exports.ObligationInDeprecatedReserve = exports.ElevationGroupAlreadyActivated = exports.ReserveObsolete = exports.ShortUrlNotAsciiAlphanumeric = exports.CpiDisabled = exports.InsufficientReferralFeesToRedeem = exports.ReferrerAccountMissing = exports.ReferrerAccountReferrerMissmatch = exports.ReferrerAccountWrongAddress = exports.ReferrerAccountMintMissmatch = exports.ReferrerAccountNotInitialized = exports.ReserveDeprecated = exports.ElevationGroupNewLoansDisabled = exports.UnhealthyElevationGroupLtv = exports.InvalidElevationGroupConfig = exports.InvalidElevationGroup = exports.InconsistentElevationGroup = exports.IsolatedAssetTierViolation = exports.LiquidationSlippageError = exports.LastTimestampGreaterThanCurrent = exports.WithdrawalCapReached = exports.ObligationEmpty = exports.CannotSocializeObligationWithCollateral = exports.InvalidUtilizationRate = exports.InvalidBorrowRateCurvePoint = exports.InvalidObligationId = exports.InvalidObligationSeedsValue = exports.ObligationCollateralLtvZero = exports.InvalidScopePriceAccount = exports.InvalidSwitchboardAccount = exports.InvalidPythPriceAccount = exports.InvalidTwapConfig = exports.NoPriceFound = exports.IncorrectInstructionInPosition = exports.NoFarmForReserve = void 0;
5
5
  class InvalidMarketAuthority extends Error {
6
6
  constructor(logs) {
7
7
  super("6000: Market authority is invalid");
@@ -1080,6 +1080,17 @@ class ReserveAccountingMismatch extends Error {
1080
1080
  }
1081
1081
  exports.ReserveAccountingMismatch = ReserveAccountingMismatch;
1082
1082
  ReserveAccountingMismatch.code = 6097;
1083
+ class BorrowingAboveUtilizationRateDisabled extends Error {
1084
+ constructor(logs) {
1085
+ super("6098: Borrowing above set utilization rate is disabled");
1086
+ this.logs = logs;
1087
+ this.code = 6098;
1088
+ this.name = "BorrowingAboveUtilizationRateDisabled";
1089
+ this.msg = "Borrowing above set utilization rate is disabled";
1090
+ }
1091
+ }
1092
+ exports.BorrowingAboveUtilizationRateDisabled = BorrowingAboveUtilizationRateDisabled;
1093
+ BorrowingAboveUtilizationRateDisabled.code = 6098;
1083
1094
  function fromCode(code, logs) {
1084
1095
  switch (code) {
1085
1096
  case 6000:
@@ -1278,6 +1289,8 @@ function fromCode(code, logs) {
1278
1289
  return new ReserveVaultBalanceMismatch(logs);
1279
1290
  case 6097:
1280
1291
  return new ReserveAccountingMismatch(logs);
1292
+ case 6098:
1293
+ return new BorrowingAboveUtilizationRateDisabled(logs);
1281
1294
  }
1282
1295
  return null;
1283
1296
  }