@kestrelfi/lyc-sdk 1.0.1 → 1.0.3

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.
Files changed (738) hide show
  1. package/README.md +32 -0
  2. package/dist/carry-XU3WUD22.mjs +20 -0
  3. package/dist/carry-XU3WUD22.mjs.map +1 -0
  4. package/dist/chunk-2T23QQCX.mjs +3707 -0
  5. package/dist/chunk-2T23QQCX.mjs.map +1 -0
  6. package/dist/chunk-GOW6CARW.mjs +3969 -0
  7. package/dist/chunk-GOW6CARW.mjs.map +1 -0
  8. package/dist/chunk-ZPXXY3QV.mjs +9330 -0
  9. package/dist/chunk-ZPXXY3QV.mjs.map +1 -0
  10. package/dist/{sdks/long-yield-carry/src/idl/long_yield_carry.d.ts → core-DP6wfpME.d.mts} +3242 -84
  11. package/dist/core-DP6wfpME.d.ts +10485 -0
  12. package/dist/core.d.mts +8 -0
  13. package/dist/core.d.ts +8 -0
  14. package/dist/core.js +12348 -0
  15. package/dist/core.js.map +1 -0
  16. package/dist/core.mjs +72 -0
  17. package/dist/core.mjs.map +1 -0
  18. package/dist/index.d.mts +2537 -0
  19. package/dist/index.d.ts +2537 -0
  20. package/dist/index.js +23884 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/index.mjs +5898 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/package.json +56 -10
  25. package/.env.example +0 -11
  26. package/dist/sdks/long-yield-carry/scripts/asyncBurn.d.ts +0 -1
  27. package/dist/sdks/long-yield-carry/scripts/asyncBurn.js +0 -117
  28. package/dist/sdks/long-yield-carry/scripts/burnToken.d.ts +0 -1
  29. package/dist/sdks/long-yield-carry/scripts/burnToken.js +0 -98
  30. package/dist/sdks/long-yield-carry/scripts/claimIncentives.d.ts +0 -1
  31. package/dist/sdks/long-yield-carry/scripts/claimIncentives.js +0 -108
  32. package/dist/sdks/long-yield-carry/scripts/closeCpiPlans.d.ts +0 -1
  33. package/dist/sdks/long-yield-carry/scripts/closeCpiPlans.js +0 -93
  34. package/dist/sdks/long-yield-carry/scripts/collectInterest.d.ts +0 -1
  35. package/dist/sdks/long-yield-carry/scripts/collectInterest.js +0 -164
  36. package/dist/sdks/long-yield-carry/scripts/collectProtocolFees.d.ts +0 -1
  37. package/dist/sdks/long-yield-carry/scripts/collectProtocolFees.js +0 -120
  38. package/dist/sdks/long-yield-carry/scripts/computeOptimalAllocations.d.ts +0 -1
  39. package/dist/sdks/long-yield-carry/scripts/computeOptimalAllocations.js +0 -84
  40. package/dist/sdks/long-yield-carry/scripts/createToken.d.ts +0 -1
  41. package/dist/sdks/long-yield-carry/scripts/createToken.js +0 -76
  42. package/dist/sdks/long-yield-carry/scripts/createTokenLendingPosition.d.ts +0 -1
  43. package/dist/sdks/long-yield-carry/scripts/createTokenLendingPosition.js +0 -157
  44. package/dist/sdks/long-yield-carry/scripts/createYieldingBank.d.ts +0 -1
  45. package/dist/sdks/long-yield-carry/scripts/createYieldingBank.js +0 -69
  46. package/dist/sdks/long-yield-carry/scripts/decreaseCarryPositions.d.ts +0 -1
  47. package/dist/sdks/long-yield-carry/scripts/decreaseCarryPositions.js +0 -247
  48. package/dist/sdks/long-yield-carry/scripts/depositUnlentCollateral.d.ts +0 -1
  49. package/dist/sdks/long-yield-carry/scripts/depositUnlentCollateral.js +0 -90
  50. package/dist/sdks/long-yield-carry/scripts/emergency/deleverageAll.d.ts +0 -1
  51. package/dist/sdks/long-yield-carry/scripts/emergency/deleverageAll.js +0 -202
  52. package/dist/sdks/long-yield-carry/scripts/emergency/triggerCircuitBreaker.d.ts +0 -1
  53. package/dist/sdks/long-yield-carry/scripts/emergency/triggerCircuitBreaker.js +0 -68
  54. package/dist/sdks/long-yield-carry/scripts/env.d.ts +0 -1
  55. package/dist/sdks/long-yield-carry/scripts/env.js +0 -8
  56. package/dist/sdks/long-yield-carry/scripts/findTxs.d.ts +0 -1
  57. package/dist/sdks/long-yield-carry/scripts/findTxs.js +0 -143
  58. package/dist/sdks/long-yield-carry/scripts/increaseCarryPositions.d.ts +0 -1
  59. package/dist/sdks/long-yield-carry/scripts/increaseCarryPositions.js +0 -112
  60. package/dist/sdks/long-yield-carry/scripts/inspect/format.d.ts +0 -13
  61. package/dist/sdks/long-yield-carry/scripts/inspect/format.js +0 -363
  62. package/dist/sdks/long-yield-carry/scripts/inspect.d.ts +0 -1
  63. package/dist/sdks/long-yield-carry/scripts/inspect.js +0 -108
  64. package/dist/sdks/long-yield-carry/scripts/localUtils.d.ts +0 -53
  65. package/dist/sdks/long-yield-carry/scripts/localUtils.js +0 -191
  66. package/dist/sdks/long-yield-carry/scripts/mintToken.d.ts +0 -1
  67. package/dist/sdks/long-yield-carry/scripts/mintToken.js +0 -103
  68. package/dist/sdks/long-yield-carry/scripts/processAsyncBurns.d.ts +0 -1
  69. package/dist/sdks/long-yield-carry/scripts/processAsyncBurns.js +0 -76
  70. package/dist/sdks/long-yield-carry/scripts/rebalanceToken.d.ts +0 -1
  71. package/dist/sdks/long-yield-carry/scripts/rebalanceToken.js +0 -210
  72. package/dist/sdks/long-yield-carry/scripts/rebalanceYieldingBank.d.ts +0 -1
  73. package/dist/sdks/long-yield-carry/scripts/rebalanceYieldingBank.js +0 -149
  74. package/dist/sdks/long-yield-carry/scripts/recollateralizeLoss.d.ts +0 -1
  75. package/dist/sdks/long-yield-carry/scripts/recollateralizeLoss.js +0 -64
  76. package/dist/sdks/long-yield-carry/scripts/refresh.d.ts +0 -1
  77. package/dist/sdks/long-yield-carry/scripts/refresh.js +0 -101
  78. package/dist/sdks/long-yield-carry/scripts/updateFees.d.ts +0 -1
  79. package/dist/sdks/long-yield-carry/scripts/updateFees.js +0 -369
  80. package/dist/sdks/long-yield-carry/scripts/updateGeneralLut.d.ts +0 -1
  81. package/dist/sdks/long-yield-carry/scripts/updateGeneralLut.js +0 -27
  82. package/dist/sdks/long-yield-carry/scripts/updateLendingPositionConfig.d.ts +0 -1
  83. package/dist/sdks/long-yield-carry/scripts/updateLendingPositionConfig.js +0 -127
  84. package/dist/sdks/long-yield-carry/scripts/updateTokenLuts.d.ts +0 -1
  85. package/dist/sdks/long-yield-carry/scripts/updateTokenLuts.js +0 -27
  86. package/dist/sdks/long-yield-carry/scripts/updateTokenMetadata.d.ts +0 -1
  87. package/dist/sdks/long-yield-carry/scripts/updateTokenMetadata.js +0 -194
  88. package/dist/sdks/long-yield-carry/scripts/updateYieldingBankConfig.d.ts +0 -1
  89. package/dist/sdks/long-yield-carry/scripts/updateYieldingBankConfig.js +0 -84
  90. package/dist/sdks/long-yield-carry/scripts/withdrawUnlentCollateral.d.ts +0 -1
  91. package/dist/sdks/long-yield-carry/scripts/withdrawUnlentCollateral.js +0 -140
  92. package/dist/sdks/long-yield-carry/src/client/account.d.ts +0 -152
  93. package/dist/sdks/long-yield-carry/src/client/account.js +0 -349
  94. package/dist/sdks/long-yield-carry/src/client/builders/args.d.ts +0 -299
  95. package/dist/sdks/long-yield-carry/src/client/builders/args.js +0 -2
  96. package/dist/sdks/long-yield-carry/src/client/builders/asyncBurnBuilder.d.ts +0 -20
  97. package/dist/sdks/long-yield-carry/src/client/builders/asyncBurnBuilder.js +0 -212
  98. package/dist/sdks/long-yield-carry/src/client/builders/base.d.ts +0 -77
  99. package/dist/sdks/long-yield-carry/src/client/builders/base.js +0 -191
  100. package/dist/sdks/long-yield-carry/src/client/builders/burnTokenBuilder.d.ts +0 -18
  101. package/dist/sdks/long-yield-carry/src/client/builders/burnTokenBuilder.js +0 -165
  102. package/dist/sdks/long-yield-carry/src/client/builders/claimIncentivesBuilder.d.ts +0 -9
  103. package/dist/sdks/long-yield-carry/src/client/builders/claimIncentivesBuilder.js +0 -135
  104. package/dist/sdks/long-yield-carry/src/client/builders/collectFeesBuilder.d.ts +0 -14
  105. package/dist/sdks/long-yield-carry/src/client/builders/collectFeesBuilder.js +0 -50
  106. package/dist/sdks/long-yield-carry/src/client/builders/collectInterestBuilder.d.ts +0 -8
  107. package/dist/sdks/long-yield-carry/src/client/builders/collectInterestBuilder.js +0 -86
  108. package/dist/sdks/long-yield-carry/src/client/builders/createCpiPlanBuilder.d.ts +0 -6
  109. package/dist/sdks/long-yield-carry/src/client/builders/createCpiPlanBuilder.js +0 -22
  110. package/dist/sdks/long-yield-carry/src/client/builders/createTokenBuilder.d.ts +0 -7
  111. package/dist/sdks/long-yield-carry/src/client/builders/createTokenBuilder.js +0 -64
  112. package/dist/sdks/long-yield-carry/src/client/builders/createTokenLendingPositionBuilder.d.ts +0 -10
  113. package/dist/sdks/long-yield-carry/src/client/builders/createTokenLendingPositionBuilder.js +0 -138
  114. package/dist/sdks/long-yield-carry/src/client/builders/createYieldingBankAllocationBuilder.d.ts +0 -7
  115. package/dist/sdks/long-yield-carry/src/client/builders/createYieldingBankAllocationBuilder.js +0 -29
  116. package/dist/sdks/long-yield-carry/src/client/builders/createYieldingBankBuilder.d.ts +0 -7
  117. package/dist/sdks/long-yield-carry/src/client/builders/createYieldingBankBuilder.js +0 -39
  118. package/dist/sdks/long-yield-carry/src/client/builders/decreaseCarryPositionBuilder.d.ts +0 -30
  119. package/dist/sdks/long-yield-carry/src/client/builders/decreaseCarryPositionBuilder.js +0 -99
  120. package/dist/sdks/long-yield-carry/src/client/builders/depositUnlentCollateralBuilder.d.ts +0 -8
  121. package/dist/sdks/long-yield-carry/src/client/builders/depositUnlentCollateralBuilder.js +0 -64
  122. package/dist/sdks/long-yield-carry/src/client/builders/increaseCarryPositionBuilder.d.ts +0 -8
  123. package/dist/sdks/long-yield-carry/src/client/builders/increaseCarryPositionBuilder.js +0 -73
  124. package/dist/sdks/long-yield-carry/src/client/builders/index.d.ts +0 -28
  125. package/dist/sdks/long-yield-carry/src/client/builders/index.js +0 -62
  126. package/dist/sdks/long-yield-carry/src/client/builders/mintTokenBuilder.d.ts +0 -8
  127. package/dist/sdks/long-yield-carry/src/client/builders/mintTokenBuilder.js +0 -95
  128. package/dist/sdks/long-yield-carry/src/client/builders/rebalanceTokenBuilder.d.ts +0 -11
  129. package/dist/sdks/long-yield-carry/src/client/builders/rebalanceTokenBuilder.js +0 -255
  130. package/dist/sdks/long-yield-carry/src/client/builders/rebalanceYieldingBankBuilder.d.ts +0 -8
  131. package/dist/sdks/long-yield-carry/src/client/builders/rebalanceYieldingBankBuilder.js +0 -75
  132. package/dist/sdks/long-yield-carry/src/client/builders/recollateralizeLossBuilder.d.ts +0 -12
  133. package/dist/sdks/long-yield-carry/src/client/builders/recollateralizeLossBuilder.js +0 -220
  134. package/dist/sdks/long-yield-carry/src/client/builders/refreshTokenStateBuilder.d.ts +0 -9
  135. package/dist/sdks/long-yield-carry/src/client/builders/refreshTokenStateBuilder.js +0 -112
  136. package/dist/sdks/long-yield-carry/src/client/builders/refreshTokensBuilder.d.ts +0 -9
  137. package/dist/sdks/long-yield-carry/src/client/builders/refreshTokensBuilder.js +0 -59
  138. package/dist/sdks/long-yield-carry/src/client/builders/refreshYieldingBankBuilder.d.ts +0 -8
  139. package/dist/sdks/long-yield-carry/src/client/builders/refreshYieldingBankBuilder.js +0 -29
  140. package/dist/sdks/long-yield-carry/src/client/builders/resetTokenBurnRateLimitBuilder.d.ts +0 -7
  141. package/dist/sdks/long-yield-carry/src/client/builders/resetTokenBurnRateLimitBuilder.js +0 -19
  142. package/dist/sdks/long-yield-carry/src/client/builders/setTokenCircuitBreakerBuilder.d.ts +0 -11
  143. package/dist/sdks/long-yield-carry/src/client/builders/setTokenCircuitBreakerBuilder.js +0 -31
  144. package/dist/sdks/long-yield-carry/src/client/builders/setYieldingBankCircuitBreakerBuilder.d.ts +0 -8
  145. package/dist/sdks/long-yield-carry/src/client/builders/setYieldingBankCircuitBreakerBuilder.js +0 -28
  146. package/dist/sdks/long-yield-carry/src/client/builders/updateLendingPositionConfigBuilder.d.ts +0 -10
  147. package/dist/sdks/long-yield-carry/src/client/builders/updateLendingPositionConfigBuilder.js +0 -30
  148. package/dist/sdks/long-yield-carry/src/client/builders/updateTokenConfigurationBuilder.d.ts +0 -11
  149. package/dist/sdks/long-yield-carry/src/client/builders/updateTokenConfigurationBuilder.js +0 -47
  150. package/dist/sdks/long-yield-carry/src/client/builders/updateTokenMetadataBuilder.d.ts +0 -7
  151. package/dist/sdks/long-yield-carry/src/client/builders/updateTokenMetadataBuilder.js +0 -24
  152. package/dist/sdks/long-yield-carry/src/client/builders/updateYieldingBankConfigBuilder.d.ts +0 -10
  153. package/dist/sdks/long-yield-carry/src/client/builders/updateYieldingBankConfigBuilder.js +0 -31
  154. package/dist/sdks/long-yield-carry/src/client/builders/utils.d.ts +0 -4
  155. package/dist/sdks/long-yield-carry/src/client/builders/utils.js +0 -20
  156. package/dist/sdks/long-yield-carry/src/client/client.d.ts +0 -115
  157. package/dist/sdks/long-yield-carry/src/client/client.js +0 -166
  158. package/dist/sdks/long-yield-carry/src/client/externalLiquidityResolver.d.ts +0 -13
  159. package/dist/sdks/long-yield-carry/src/client/externalLiquidityResolver.js +0 -34
  160. package/dist/sdks/long-yield-carry/src/client/index.d.ts +0 -10
  161. package/dist/sdks/long-yield-carry/src/client/index.js +0 -33
  162. package/dist/sdks/long-yield-carry/src/client/lendingPlatformClients.d.ts +0 -19
  163. package/dist/sdks/long-yield-carry/src/client/lendingPlatformClients.js +0 -33
  164. package/dist/sdks/long-yield-carry/src/client/pda.d.ts +0 -33
  165. package/dist/sdks/long-yield-carry/src/client/pda.js +0 -79
  166. package/dist/sdks/long-yield-carry/src/client/plans/collectInterest.d.ts +0 -24
  167. package/dist/sdks/long-yield-carry/src/client/plans/collectInterest.js +0 -150
  168. package/dist/sdks/long-yield-carry/src/client/plans/decreaseCarryPosition.d.ts +0 -12
  169. package/dist/sdks/long-yield-carry/src/client/plans/decreaseCarryPosition.js +0 -140
  170. package/dist/sdks/long-yield-carry/src/client/routes/collectInterest.d.ts +0 -13
  171. package/dist/sdks/long-yield-carry/src/client/routes/collectInterest.js +0 -39
  172. package/dist/sdks/long-yield-carry/src/client/transaction.d.ts +0 -41
  173. package/dist/sdks/long-yield-carry/src/client/transaction.js +0 -55
  174. package/dist/sdks/long-yield-carry/src/client/types/builders.d.ts +0 -18
  175. package/dist/sdks/long-yield-carry/src/client/types/builders.js +0 -2
  176. package/dist/sdks/long-yield-carry/src/client/types/enums.d.ts +0 -22
  177. package/dist/sdks/long-yield-carry/src/client/types/enums.js +0 -48
  178. package/dist/sdks/long-yield-carry/src/client/types/general.d.ts +0 -98
  179. package/dist/sdks/long-yield-carry/src/client/types/general.js +0 -2
  180. package/dist/sdks/long-yield-carry/src/client/types/index.d.ts +0 -6
  181. package/dist/sdks/long-yield-carry/src/client/types/index.js +0 -22
  182. package/dist/sdks/long-yield-carry/src/client/types/ix.d.ts +0 -352
  183. package/dist/sdks/long-yield-carry/src/client/types/ix.js +0 -2
  184. package/dist/sdks/long-yield-carry/src/client/types/planTypes/collectInterest.d.ts +0 -91
  185. package/dist/sdks/long-yield-carry/src/client/types/planTypes/collectInterest.js +0 -2
  186. package/dist/sdks/long-yield-carry/src/client/types/planTypes/common.d.ts +0 -28
  187. package/dist/sdks/long-yield-carry/src/client/types/planTypes/common.js +0 -2
  188. package/dist/sdks/long-yield-carry/src/client/types/planTypes/decreaseCarryPosition.d.ts +0 -128
  189. package/dist/sdks/long-yield-carry/src/client/types/planTypes/decreaseCarryPosition.js +0 -2
  190. package/dist/sdks/long-yield-carry/src/client/types/planTypes/index.d.ts +0 -3
  191. package/dist/sdks/long-yield-carry/src/client/types/planTypes/index.js +0 -19
  192. package/dist/sdks/long-yield-carry/src/client/types/tx.d.ts +0 -339
  193. package/dist/sdks/long-yield-carry/src/client/types/tx.js +0 -2
  194. package/dist/sdks/long-yield-carry/src/constants/configs/allocations.d.ts +0 -3
  195. package/dist/sdks/long-yield-carry/src/constants/configs/allocations.js +0 -23
  196. package/dist/sdks/long-yield-carry/src/constants/configs/carryTradePresets.d.ts +0 -58
  197. package/dist/sdks/long-yield-carry/src/constants/configs/carryTradePresets.js +0 -116
  198. package/dist/sdks/long-yield-carry/src/constants/configs/index.d.ts +0 -2
  199. package/dist/sdks/long-yield-carry/src/constants/configs/index.js +0 -18
  200. package/dist/sdks/long-yield-carry/src/constants/general.d.ts +0 -70
  201. package/dist/sdks/long-yield-carry/src/constants/general.js +0 -107
  202. package/dist/sdks/long-yield-carry/src/constants/index.d.ts +0 -3
  203. package/dist/sdks/long-yield-carry/src/constants/index.js +0 -19
  204. package/dist/sdks/long-yield-carry/src/constants/lycTokenMetadata.d.ts +0 -36
  205. package/dist/sdks/long-yield-carry/src/constants/lycTokenMetadata.js +0 -41
  206. package/dist/sdks/long-yield-carry/src/decoders/decodeTransaction.d.ts +0 -86
  207. package/dist/sdks/long-yield-carry/src/decoders/decodeTransaction.js +0 -230
  208. package/dist/sdks/long-yield-carry/src/decoders/discriminators.d.ts +0 -8
  209. package/dist/sdks/long-yield-carry/src/decoders/discriminators.js +0 -11
  210. package/dist/sdks/long-yield-carry/src/decoders/idlAccounts.d.ts +0 -29
  211. package/dist/sdks/long-yield-carry/src/decoders/idlAccounts.js +0 -57
  212. package/dist/sdks/long-yield-carry/src/decoders/index.d.ts +0 -6
  213. package/dist/sdks/long-yield-carry/src/decoders/index.js +0 -14
  214. package/dist/sdks/long-yield-carry/src/decoders/innerCpis.d.ts +0 -68
  215. package/dist/sdks/long-yield-carry/src/decoders/innerCpis.js +0 -225
  216. package/dist/sdks/long-yield-carry/src/decoders/lycInstructionNames.d.ts +0 -6
  217. package/dist/sdks/long-yield-carry/src/decoders/lycInstructionNames.js +0 -73
  218. package/dist/sdks/long-yield-carry/src/decoders/programIds.d.ts +0 -4
  219. package/dist/sdks/long-yield-carry/src/decoders/programIds.js +0 -11
  220. package/dist/sdks/long-yield-carry/src/decoders/solana.d.ts +0 -7
  221. package/dist/sdks/long-yield-carry/src/decoders/solana.js +0 -30
  222. package/dist/sdks/long-yield-carry/src/decoders/transactionPayload.d.ts +0 -41
  223. package/dist/sdks/long-yield-carry/src/decoders/transactionPayload.js +0 -6
  224. package/dist/sdks/long-yield-carry/src/decoders/types.d.ts +0 -58
  225. package/dist/sdks/long-yield-carry/src/decoders/types.js +0 -2
  226. package/dist/sdks/long-yield-carry/src/errors.d.ts +0 -69
  227. package/dist/sdks/long-yield-carry/src/errors.js +0 -183
  228. package/dist/sdks/long-yield-carry/src/idl/long_yield_carry.js +0 -7323
  229. package/dist/sdks/long-yield-carry/src/index.d.ts +0 -10
  230. package/dist/sdks/long-yield-carry/src/index.js +0 -25
  231. package/dist/sdks/long-yield-carry/src/metrics/index.d.ts +0 -1
  232. package/dist/sdks/long-yield-carry/src/metrics/index.js +0 -17
  233. package/dist/sdks/long-yield-carry/src/metrics/protocolMetrics.d.ts +0 -276
  234. package/dist/sdks/long-yield-carry/src/metrics/protocolMetrics.js +0 -547
  235. package/dist/sdks/long-yield-carry/src/models/index.d.ts +0 -3
  236. package/dist/sdks/long-yield-carry/src/models/index.js +0 -7
  237. package/dist/sdks/long-yield-carry/src/models/lycToken.d.ts +0 -156
  238. package/dist/sdks/long-yield-carry/src/models/lycToken.js +0 -288
  239. package/dist/sdks/long-yield-carry/src/models/yieldingBank.d.ts +0 -52
  240. package/dist/sdks/long-yield-carry/src/models/yieldingBank.js +0 -109
  241. package/dist/sdks/long-yield-carry/src/services/allocation/allocationService.d.ts +0 -106
  242. package/dist/sdks/long-yield-carry/src/services/allocation/allocationService.js +0 -589
  243. package/dist/sdks/long-yield-carry/src/services/allocation/index.d.ts +0 -2
  244. package/dist/sdks/long-yield-carry/src/services/allocation/index.js +0 -18
  245. package/dist/sdks/long-yield-carry/src/services/allocation/types.d.ts +0 -25
  246. package/dist/sdks/long-yield-carry/src/services/allocation/types.js +0 -2
  247. package/dist/sdks/long-yield-carry/src/services/carry/carryAllocationConfig.d.ts +0 -103
  248. package/dist/sdks/long-yield-carry/src/services/carry/carryAllocationConfig.js +0 -146
  249. package/dist/sdks/long-yield-carry/src/services/carry/index.d.ts +0 -2
  250. package/dist/sdks/long-yield-carry/src/services/carry/index.js +0 -18
  251. package/dist/sdks/long-yield-carry/src/services/carry/lycLendingPositionManager.d.ts +0 -39
  252. package/dist/sdks/long-yield-carry/src/services/carry/lycLendingPositionManager.js +0 -100
  253. package/dist/sdks/long-yield-carry/src/services/index.d.ts +0 -5
  254. package/dist/sdks/long-yield-carry/src/services/index.js +0 -21
  255. package/dist/sdks/long-yield-carry/src/services/lendingPosition/index.d.ts +0 -2
  256. package/dist/sdks/long-yield-carry/src/services/lendingPosition/index.js +0 -5
  257. package/dist/sdks/long-yield-carry/src/services/lendingPosition/lendingPositionService.d.ts +0 -88
  258. package/dist/sdks/long-yield-carry/src/services/lendingPosition/lendingPositionService.js +0 -229
  259. package/dist/sdks/long-yield-carry/src/services/rebalance/index.d.ts +0 -2
  260. package/dist/sdks/long-yield-carry/src/services/rebalance/index.js +0 -18
  261. package/dist/sdks/long-yield-carry/src/services/rebalance/token/index.d.ts +0 -1
  262. package/dist/sdks/long-yield-carry/src/services/rebalance/token/index.js +0 -17
  263. package/dist/sdks/long-yield-carry/src/services/rebalance/token/tokenRebalanceService.d.ts +0 -51
  264. package/dist/sdks/long-yield-carry/src/services/rebalance/token/tokenRebalanceService.js +0 -99
  265. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/index.d.ts +0 -3
  266. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/index.js +0 -21
  267. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/planner.d.ts +0 -68
  268. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/planner.js +0 -181
  269. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/strategy.d.ts +0 -26
  270. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/strategy.js +0 -26
  271. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/types.d.ts +0 -40
  272. package/dist/sdks/long-yield-carry/src/services/rebalance/yieldingBank/types.js +0 -2
  273. package/dist/sdks/long-yield-carry/src/services/redemption/index.d.ts +0 -2
  274. package/dist/sdks/long-yield-carry/src/services/redemption/index.js +0 -5
  275. package/dist/sdks/long-yield-carry/src/services/redemption/redemptionService.d.ts +0 -139
  276. package/dist/sdks/long-yield-carry/src/services/redemption/redemptionService.js +0 -532
  277. package/dist/sdks/long-yield-carry/src/types/enriched.d.ts +0 -168
  278. package/dist/sdks/long-yield-carry/src/types/enriched.js +0 -2
  279. package/dist/sdks/long-yield-carry/src/types/index.d.ts +0 -1
  280. package/dist/sdks/long-yield-carry/src/types/index.js +0 -17
  281. package/dist/sdks/long-yield-carry/src/utils/cache.d.ts +0 -4
  282. package/dist/sdks/long-yield-carry/src/utils/cache.js +0 -10
  283. package/dist/sdks/long-yield-carry/src/utils/data.d.ts +0 -12
  284. package/dist/sdks/long-yield-carry/src/utils/data.js +0 -59
  285. package/dist/sdks/long-yield-carry/src/utils/enrichment.d.ts +0 -5
  286. package/dist/sdks/long-yield-carry/src/utils/enrichment.js +0 -244
  287. package/dist/sdks/long-yield-carry/src/utils/feeDripMetrics.d.ts +0 -36
  288. package/dist/sdks/long-yield-carry/src/utils/feeDripMetrics.js +0 -93
  289. package/dist/sdks/long-yield-carry/src/utils/general.d.ts +0 -28
  290. package/dist/sdks/long-yield-carry/src/utils/general.js +0 -47
  291. package/dist/sdks/long-yield-carry/src/utils/index.d.ts +0 -13
  292. package/dist/sdks/long-yield-carry/src/utils/index.js +0 -29
  293. package/dist/sdks/long-yield-carry/src/utils/ix.d.ts +0 -83
  294. package/dist/sdks/long-yield-carry/src/utils/ix.js +0 -165
  295. package/dist/sdks/long-yield-carry/src/utils/lendingPosition.d.ts +0 -68
  296. package/dist/sdks/long-yield-carry/src/utils/lendingPosition.js +0 -105
  297. package/dist/sdks/long-yield-carry/src/utils/lookupTables.d.ts +0 -55
  298. package/dist/sdks/long-yield-carry/src/utils/lookupTables.js +0 -216
  299. package/dist/sdks/long-yield-carry/src/utils/lycData.d.ts +0 -66
  300. package/dist/sdks/long-yield-carry/src/utils/lycData.js +0 -211
  301. package/dist/sdks/long-yield-carry/src/utils/timelock.d.ts +0 -19
  302. package/dist/sdks/long-yield-carry/src/utils/timelock.js +0 -37
  303. package/dist/sdks/long-yield-carry/src/utils/tokenFeeMath.d.ts +0 -11
  304. package/dist/sdks/long-yield-carry/src/utils/tokenFeeMath.js +0 -24
  305. package/dist/sdks/long-yield-carry/src/utils/transactions.d.ts +0 -20
  306. package/dist/sdks/long-yield-carry/src/utils/transactions.js +0 -72
  307. package/dist/sdks/long-yield-carry/src/utils/yieldingBank.d.ts +0 -24
  308. package/dist/sdks/long-yield-carry/src/utils/yieldingBank.js +0 -36
  309. package/dist/shared/common/src/constants/accountMetas.d.ts +0 -3
  310. package/dist/shared/common/src/constants/accountMetas.js +0 -9
  311. package/dist/shared/common/src/constants/general.d.ts +0 -21
  312. package/dist/shared/common/src/constants/general.js +0 -30
  313. package/dist/shared/common/src/constants/generated/cpi.d.ts +0 -23
  314. package/dist/shared/common/src/constants/generated/cpi.js +0 -28
  315. package/dist/shared/common/src/constants/generated/index.d.ts +0 -1
  316. package/dist/shared/common/src/constants/generated/index.js +0 -17
  317. package/dist/shared/common/src/constants/index.d.ts +0 -3
  318. package/dist/shared/common/src/constants/index.js +0 -19
  319. package/dist/shared/common/src/index.d.ts +0 -4
  320. package/dist/shared/common/src/index.js +0 -20
  321. package/dist/shared/common/src/services/baseAccountClient.d.ts +0 -22
  322. package/dist/shared/common/src/services/baseAccountClient.js +0 -38
  323. package/dist/shared/common/src/services/baseIxBuilderService.d.ts +0 -27
  324. package/dist/shared/common/src/services/baseIxBuilderService.js +0 -48
  325. package/dist/shared/common/src/services/dataCache.d.ts +0 -41
  326. package/dist/shared/common/src/services/dataCache.js +0 -130
  327. package/dist/shared/common/src/services/index.d.ts +0 -8
  328. package/dist/shared/common/src/services/index.js +0 -24
  329. package/dist/shared/common/src/services/lutManager.d.ts +0 -31
  330. package/dist/shared/common/src/services/lutManager.js +0 -133
  331. package/dist/shared/common/src/services/mints/defaults.d.ts +0 -2
  332. package/dist/shared/common/src/services/mints/defaults.js +0 -152
  333. package/dist/shared/common/src/services/mints/index.d.ts +0 -4
  334. package/dist/shared/common/src/services/mints/index.js +0 -20
  335. package/dist/shared/common/src/services/mints/registry.d.ts +0 -70
  336. package/dist/shared/common/src/services/mints/registry.js +0 -117
  337. package/dist/shared/common/src/services/mints/symbols.d.ts +0 -6
  338. package/dist/shared/common/src/services/mints/symbols.js +0 -13
  339. package/dist/shared/common/src/services/mints/types.d.ts +0 -30
  340. package/dist/shared/common/src/services/mints/types.js +0 -2
  341. package/dist/shared/common/src/services/swap/index.d.ts +0 -4
  342. package/dist/shared/common/src/services/swap/index.js +0 -20
  343. package/dist/shared/common/src/services/swap/routableSwapClient.d.ts +0 -36
  344. package/dist/shared/common/src/services/swap/routableSwapClient.js +0 -2
  345. package/dist/shared/common/src/services/swap/swapClientBase.d.ts +0 -45
  346. package/dist/shared/common/src/services/swap/swapClientBase.js +0 -2
  347. package/dist/shared/common/src/services/swap/swapRouting.d.ts +0 -13
  348. package/dist/shared/common/src/services/swap/swapRouting.js +0 -28
  349. package/dist/shared/common/src/services/swap/types.d.ts +0 -77
  350. package/dist/shared/common/src/services/swap/types.js +0 -2
  351. package/dist/shared/common/src/services/token/index.d.ts +0 -2
  352. package/dist/shared/common/src/services/token/index.js +0 -18
  353. package/dist/shared/common/src/services/token/tokenProtocolClientBase.d.ts +0 -51
  354. package/dist/shared/common/src/services/token/tokenProtocolClientBase.js +0 -2
  355. package/dist/shared/common/src/services/token/types.d.ts +0 -19
  356. package/dist/shared/common/src/services/token/types.js +0 -2
  357. package/dist/shared/common/src/services/transactionSender.d.ts +0 -24
  358. package/dist/shared/common/src/services/transactionSender.js +0 -30
  359. package/dist/shared/common/src/types/cpi.d.ts +0 -34
  360. package/dist/shared/common/src/types/cpi.js +0 -8
  361. package/dist/shared/common/src/types/enums.d.ts +0 -59
  362. package/dist/shared/common/src/types/enums.js +0 -122
  363. package/dist/shared/common/src/types/general.d.ts +0 -38
  364. package/dist/shared/common/src/types/general.js +0 -2
  365. package/dist/shared/common/src/types/index.d.ts +0 -4
  366. package/dist/shared/common/src/types/index.js +0 -20
  367. package/dist/shared/common/src/types/solana.d.ts +0 -24
  368. package/dist/shared/common/src/types/solana.js +0 -2
  369. package/dist/shared/common/src/utils/accounts/index.d.ts +0 -5
  370. package/dist/shared/common/src/utils/accounts/index.js +0 -21
  371. package/dist/shared/common/src/utils/accounts/meta.d.ts +0 -21
  372. package/dist/shared/common/src/utils/accounts/meta.js +0 -27
  373. package/dist/shared/common/src/utils/accounts/pda.d.ts +0 -2
  374. package/dist/shared/common/src/utils/accounts/pda.js +0 -17
  375. package/dist/shared/common/src/utils/accounts/roles.d.ts +0 -26
  376. package/dist/shared/common/src/utils/accounts/roles.js +0 -54
  377. package/dist/shared/common/src/utils/accounts/rpc.d.ts +0 -8
  378. package/dist/shared/common/src/utils/accounts/rpc.js +0 -30
  379. package/dist/shared/common/src/utils/accounts/splBalances.d.ts +0 -15
  380. package/dist/shared/common/src/utils/accounts/splBalances.js +0 -52
  381. package/dist/shared/common/src/utils/anchor.d.ts +0 -17
  382. package/dist/shared/common/src/utils/anchor.js +0 -29
  383. package/dist/shared/common/src/utils/asyncConcurrency.d.ts +0 -5
  384. package/dist/shared/common/src/utils/asyncConcurrency.js +0 -28
  385. package/dist/shared/common/src/utils/compat.d.ts +0 -46
  386. package/dist/shared/common/src/utils/compat.js +0 -72
  387. package/dist/shared/common/src/utils/cpi/args.d.ts +0 -69
  388. package/dist/shared/common/src/utils/cpi/args.js +0 -100
  389. package/dist/shared/common/src/utils/cpi/index.d.ts +0 -2
  390. package/dist/shared/common/src/utils/cpi/index.js +0 -18
  391. package/dist/shared/common/src/utils/cpi/refs.d.ts +0 -122
  392. package/dist/shared/common/src/utils/cpi/refs.js +0 -234
  393. package/dist/shared/common/src/utils/data.d.ts +0 -20
  394. package/dist/shared/common/src/utils/data.js +0 -27
  395. package/dist/shared/common/src/utils/general.d.ts +0 -24
  396. package/dist/shared/common/src/utils/general.js +0 -95
  397. package/dist/shared/common/src/utils/index.d.ts +0 -22
  398. package/dist/shared/common/src/utils/index.js +0 -38
  399. package/dist/shared/common/src/utils/instruction.d.ts +0 -74
  400. package/dist/shared/common/src/utils/instruction.js +0 -147
  401. package/dist/shared/common/src/utils/jito.d.ts +0 -113
  402. package/dist/shared/common/src/utils/jito.js +0 -178
  403. package/dist/shared/common/src/utils/json.d.ts +0 -5
  404. package/dist/shared/common/src/utils/json.js +0 -25
  405. package/dist/shared/common/src/utils/jsonRpcFetch.d.ts +0 -21
  406. package/dist/shared/common/src/utils/jsonRpcFetch.js +0 -134
  407. package/dist/shared/common/src/utils/metadata.d.ts +0 -107
  408. package/dist/shared/common/src/utils/metadata.js +0 -194
  409. package/dist/shared/common/src/utils/numbers.d.ts +0 -72
  410. package/dist/shared/common/src/utils/numbers.js +0 -193
  411. package/dist/shared/common/src/utils/priorityFee.d.ts +0 -18
  412. package/dist/shared/common/src/utils/priorityFee.js +0 -63
  413. package/dist/shared/common/src/utils/retry.d.ts +0 -20
  414. package/dist/shared/common/src/utils/retry.js +0 -69
  415. package/dist/shared/common/src/utils/rpc.d.ts +0 -40
  416. package/dist/shared/common/src/utils/rpc.js +0 -130
  417. package/dist/shared/common/src/utils/solana.d.ts +0 -23
  418. package/dist/shared/common/src/utils/solana.js +0 -61
  419. package/dist/shared/common/src/utils/timeSeries.d.ts +0 -18
  420. package/dist/shared/common/src/utils/timeSeries.js +0 -40
  421. package/dist/shared/common/src/utils/token.d.ts +0 -33
  422. package/dist/shared/common/src/utils/token.js +0 -82
  423. package/dist/shared/common/src/utils/transaction.d.ts +0 -154
  424. package/dist/shared/common/src/utils/transaction.js +0 -585
  425. package/dist/shared/common/src/utils/transactionSplitter.d.ts +0 -85
  426. package/dist/shared/common/src/utils/transactionSplitter.js +0 -127
  427. package/dist/shared/common/src/utils/txAccountCoverage.d.ts +0 -49
  428. package/dist/shared/common/src/utils/txAccountCoverage.js +0 -122
  429. package/dist/shared/jupiter-helpers/src/api.d.ts +0 -59
  430. package/dist/shared/jupiter-helpers/src/api.js +0 -130
  431. package/dist/shared/jupiter-helpers/src/client.d.ts +0 -79
  432. package/dist/shared/jupiter-helpers/src/client.js +0 -173
  433. package/dist/shared/jupiter-helpers/src/constants.d.ts +0 -35
  434. package/dist/shared/jupiter-helpers/src/constants.js +0 -38
  435. package/dist/shared/jupiter-helpers/src/extract.d.ts +0 -30
  436. package/dist/shared/jupiter-helpers/src/extract.js +0 -57
  437. package/dist/shared/jupiter-helpers/src/index.d.ts +0 -5
  438. package/dist/shared/jupiter-helpers/src/index.js +0 -21
  439. package/dist/shared/jupiter-helpers/src/routePreInstructions.d.ts +0 -19
  440. package/dist/shared/jupiter-helpers/src/routePreInstructions.js +0 -61
  441. package/dist/shared/jupiter-helpers/src/sizeExactInForMinOutput.d.ts +0 -70
  442. package/dist/shared/jupiter-helpers/src/sizeExactInForMinOutput.js +0 -95
  443. package/dist/shared/jupiter-helpers/src/types.d.ts +0 -66
  444. package/dist/shared/jupiter-helpers/src/types.js +0 -2
  445. package/dist/shared/lending-platforms/src/constants/cache.d.ts +0 -8
  446. package/dist/shared/lending-platforms/src/constants/cache.js +0 -11
  447. package/dist/shared/lending-platforms/src/constants/index.d.ts +0 -3
  448. package/dist/shared/lending-platforms/src/constants/index.js +0 -19
  449. package/dist/shared/lending-platforms/src/constants/kamino.d.ts +0 -7
  450. package/dist/shared/lending-platforms/src/constants/kamino.js +0 -83
  451. package/dist/shared/lending-platforms/src/constants/lendingPosition.d.ts +0 -7
  452. package/dist/shared/lending-platforms/src/constants/lendingPosition.js +0 -10
  453. package/dist/shared/lending-platforms/src/data/accounts/index.d.ts +0 -2
  454. package/dist/shared/lending-platforms/src/data/accounts/index.js +0 -18
  455. package/dist/shared/lending-platforms/src/data/accounts/kamino.d.ts +0 -42
  456. package/dist/shared/lending-platforms/src/data/accounts/kamino.js +0 -104
  457. package/dist/shared/lending-platforms/src/data/accounts/lpAccountsBase.d.ts +0 -7
  458. package/dist/shared/lending-platforms/src/data/accounts/lpAccountsBase.js +0 -9
  459. package/dist/shared/lending-platforms/src/data/incentive/incentiveBase.d.ts +0 -35
  460. package/dist/shared/lending-platforms/src/data/incentive/incentiveBase.js +0 -26
  461. package/dist/shared/lending-platforms/src/data/incentive/index.d.ts +0 -2
  462. package/dist/shared/lending-platforms/src/data/incentive/index.js +0 -18
  463. package/dist/shared/lending-platforms/src/data/incentive/kamino.d.ts +0 -55
  464. package/dist/shared/lending-platforms/src/data/incentive/kamino.js +0 -101
  465. package/dist/shared/lending-platforms/src/data/index.d.ts +0 -6
  466. package/dist/shared/lending-platforms/src/data/index.js +0 -22
  467. package/dist/shared/lending-platforms/src/data/instructions/index.d.ts +0 -3
  468. package/dist/shared/lending-platforms/src/data/instructions/index.js +0 -19
  469. package/dist/shared/lending-platforms/src/data/instructions/kamino.d.ts +0 -55
  470. package/dist/shared/lending-platforms/src/data/instructions/kamino.js +0 -630
  471. package/dist/shared/lending-platforms/src/data/instructions/lpInstructionsBase.d.ts +0 -175
  472. package/dist/shared/lending-platforms/src/data/instructions/lpInstructionsBase.js +0 -192
  473. package/dist/shared/lending-platforms/src/data/instructions/types.d.ts +0 -7
  474. package/dist/shared/lending-platforms/src/data/instructions/types.js +0 -2
  475. package/dist/shared/lending-platforms/src/data/platform/index.d.ts +0 -2
  476. package/dist/shared/lending-platforms/src/data/platform/index.js +0 -18
  477. package/dist/shared/lending-platforms/src/data/platform/kamino.d.ts +0 -59
  478. package/dist/shared/lending-platforms/src/data/platform/kamino.js +0 -206
  479. package/dist/shared/lending-platforms/src/data/platform/lpDataBase.d.ts +0 -35
  480. package/dist/shared/lending-platforms/src/data/platform/lpDataBase.js +0 -31
  481. package/dist/shared/lending-platforms/src/data/reserve/index.d.ts +0 -2
  482. package/dist/shared/lending-platforms/src/data/reserve/index.js +0 -18
  483. package/dist/shared/lending-platforms/src/data/reserve/kamino.d.ts +0 -45
  484. package/dist/shared/lending-platforms/src/data/reserve/kamino.js +0 -141
  485. package/dist/shared/lending-platforms/src/data/reserve/reserveBase.d.ts +0 -114
  486. package/dist/shared/lending-platforms/src/data/reserve/reserveBase.js +0 -125
  487. package/dist/shared/lending-platforms/src/data/userPosition/index.d.ts +0 -2
  488. package/dist/shared/lending-platforms/src/data/userPosition/index.js +0 -18
  489. package/dist/shared/lending-platforms/src/data/userPosition/kamino.d.ts +0 -15
  490. package/dist/shared/lending-platforms/src/data/userPosition/kamino.js +0 -45
  491. package/dist/shared/lending-platforms/src/data/userPosition/userPositionBase.d.ts +0 -50
  492. package/dist/shared/lending-platforms/src/data/userPosition/userPositionBase.js +0 -63
  493. package/dist/shared/lending-platforms/src/index.d.ts +0 -5
  494. package/dist/shared/lending-platforms/src/index.js +0 -21
  495. package/dist/shared/lending-platforms/src/services/client/index.d.ts +0 -2
  496. package/dist/shared/lending-platforms/src/services/client/index.js +0 -18
  497. package/dist/shared/lending-platforms/src/services/client/kamino.d.ts +0 -53
  498. package/dist/shared/lending-platforms/src/services/client/kamino.js +0 -142
  499. package/dist/shared/lending-platforms/src/services/client/lpClientBase.d.ts +0 -66
  500. package/dist/shared/lending-platforms/src/services/client/lpClientBase.js +0 -19
  501. package/dist/shared/lending-platforms/src/services/flashLoan/flashLoanBase.d.ts +0 -49
  502. package/dist/shared/lending-platforms/src/services/flashLoan/flashLoanBase.js +0 -16
  503. package/dist/shared/lending-platforms/src/services/flashLoan/index.d.ts +0 -2
  504. package/dist/shared/lending-platforms/src/services/flashLoan/index.js +0 -18
  505. package/dist/shared/lending-platforms/src/services/flashLoan/kamino.d.ts +0 -11
  506. package/dist/shared/lending-platforms/src/services/flashLoan/kamino.js +0 -85
  507. package/dist/shared/lending-platforms/src/services/index.d.ts +0 -5
  508. package/dist/shared/lending-platforms/src/services/index.js +0 -21
  509. package/dist/shared/lending-platforms/src/services/lendingPosition/index.d.ts +0 -2
  510. package/dist/shared/lending-platforms/src/services/lendingPosition/index.js +0 -18
  511. package/dist/shared/lending-platforms/src/services/lendingPosition/lendingPositionManager.d.ts +0 -117
  512. package/dist/shared/lending-platforms/src/services/lendingPosition/lendingPositionManager.js +0 -342
  513. package/dist/shared/lending-platforms/src/services/lendingPosition/types.d.ts +0 -40
  514. package/dist/shared/lending-platforms/src/services/lendingPosition/types.js +0 -2
  515. package/dist/shared/lending-platforms/src/services/leverage/index.d.ts +0 -2
  516. package/dist/shared/lending-platforms/src/services/leverage/index.js +0 -18
  517. package/dist/shared/lending-platforms/src/services/leverage/leverageService.d.ts +0 -104
  518. package/dist/shared/lending-platforms/src/services/leverage/leverageService.js +0 -437
  519. package/dist/shared/lending-platforms/src/services/leverage/types.d.ts +0 -261
  520. package/dist/shared/lending-platforms/src/services/leverage/types.js +0 -2
  521. package/dist/shared/lending-platforms/src/services/reservesManager.d.ts +0 -53
  522. package/dist/shared/lending-platforms/src/services/reservesManager.js +0 -112
  523. package/dist/shared/lending-platforms/src/types/general.d.ts +0 -37
  524. package/dist/shared/lending-platforms/src/types/general.js +0 -8
  525. package/dist/shared/lending-platforms/src/types/index.d.ts +0 -2
  526. package/dist/shared/lending-platforms/src/types/index.js +0 -18
  527. package/dist/shared/lending-platforms/src/types/kamino.d.ts +0 -10
  528. package/dist/shared/lending-platforms/src/types/kamino.js +0 -2
  529. package/dist/shared/lending-platforms/src/utils/accounts.d.ts +0 -16
  530. package/dist/shared/lending-platforms/src/utils/accounts.js +0 -36
  531. package/dist/shared/lending-platforms/src/utils/cache.d.ts +0 -3
  532. package/dist/shared/lending-platforms/src/utils/cache.js +0 -11
  533. package/dist/shared/lending-platforms/src/utils/index.d.ts +0 -6
  534. package/dist/shared/lending-platforms/src/utils/index.js +0 -22
  535. package/dist/shared/lending-platforms/src/utils/kamino.d.ts +0 -87
  536. package/dist/shared/lending-platforms/src/utils/kamino.js +0 -190
  537. package/dist/shared/lending-platforms/src/utils/lendingPlatform.d.ts +0 -6
  538. package/dist/shared/lending-platforms/src/utils/lendingPlatform.js +0 -16
  539. package/dist/shared/lending-platforms/src/utils/math.d.ts +0 -47
  540. package/dist/shared/lending-platforms/src/utils/math.js +0 -123
  541. package/dist/shared/lending-platforms/src/utils/scope.d.ts +0 -38
  542. package/dist/shared/lending-platforms/src/utils/scope.js +0 -144
  543. package/dist/shared/oracle-service/src/constants/index.d.ts +0 -3
  544. package/dist/shared/oracle-service/src/constants/index.js +0 -19
  545. package/dist/shared/oracle-service/src/constants/pyth.d.ts +0 -7
  546. package/dist/shared/oracle-service/src/constants/pyth.js +0 -71
  547. package/dist/shared/oracle-service/src/constants/splStake.d.ts +0 -2
  548. package/dist/shared/oracle-service/src/constants/splStake.js +0 -6
  549. package/dist/shared/oracle-service/src/constants/switchboard.d.ts +0 -7
  550. package/dist/shared/oracle-service/src/constants/switchboard.js +0 -10
  551. package/dist/shared/oracle-service/src/feeds/custom.d.ts +0 -30
  552. package/dist/shared/oracle-service/src/feeds/custom.js +0 -56
  553. package/dist/shared/oracle-service/src/feeds/jupiter.d.ts +0 -7
  554. package/dist/shared/oracle-service/src/feeds/jupiter.js +0 -43
  555. package/dist/shared/oracle-service/src/feeds/priceBase.d.ts +0 -13
  556. package/dist/shared/oracle-service/src/feeds/priceBase.js +0 -25
  557. package/dist/shared/oracle-service/src/feeds/pyth.d.ts +0 -8
  558. package/dist/shared/oracle-service/src/feeds/pyth.js +0 -59
  559. package/dist/shared/oracle-service/src/feeds/splStake.d.ts +0 -26
  560. package/dist/shared/oracle-service/src/feeds/splStake.js +0 -99
  561. package/dist/shared/oracle-service/src/feeds/switchboard.d.ts +0 -6
  562. package/dist/shared/oracle-service/src/feeds/switchboard.js +0 -11
  563. package/dist/shared/oracle-service/src/index.d.ts +0 -5
  564. package/dist/shared/oracle-service/src/index.js +0 -26
  565. package/dist/shared/oracle-service/src/oracle.d.ts +0 -22
  566. package/dist/shared/oracle-service/src/oracle.js +0 -104
  567. package/dist/shared/oracle-service/src/types.d.ts +0 -4
  568. package/dist/shared/oracle-service/src/types.js +0 -2
  569. package/dist/shared/oracle-service/src/utils/general.d.ts +0 -20
  570. package/dist/shared/oracle-service/src/utils/general.js +0 -65
  571. package/dist/shared/oracle-service/src/utils/index.d.ts +0 -1
  572. package/dist/shared/oracle-service/src/utils/index.js +0 -17
  573. package/dist/shared/perena-helpers/src/accounts.d.ts +0 -7
  574. package/dist/shared/perena-helpers/src/accounts.js +0 -12
  575. package/dist/shared/perena-helpers/src/client.d.ts +0 -299
  576. package/dist/shared/perena-helpers/src/client.js +0 -680
  577. package/dist/shared/perena-helpers/src/constants.d.ts +0 -5
  578. package/dist/shared/perena-helpers/src/constants.js +0 -8
  579. package/dist/shared/perena-helpers/src/cpi/burn.d.ts +0 -27
  580. package/dist/shared/perena-helpers/src/cpi/burn.js +0 -22
  581. package/dist/shared/perena-helpers/src/cpi/index.d.ts +0 -3
  582. package/dist/shared/perena-helpers/src/cpi/index.js +0 -19
  583. package/dist/shared/perena-helpers/src/cpi/mint.d.ts +0 -27
  584. package/dist/shared/perena-helpers/src/cpi/mint.js +0 -22
  585. package/dist/shared/perena-helpers/src/cpi/requestUnstake.d.ts +0 -19
  586. package/dist/shared/perena-helpers/src/cpi/requestUnstake.js +0 -16
  587. package/dist/shared/perena-helpers/src/index.d.ts +0 -5
  588. package/dist/shared/perena-helpers/src/index.js +0 -21
  589. package/dist/shared/perena-helpers/src/utils.d.ts +0 -9
  590. package/dist/shared/perena-helpers/src/utils.js +0 -54
  591. package/dist/shared/swap-aggregator/src/aggSwapClient.d.ts +0 -71
  592. package/dist/shared/swap-aggregator/src/aggSwapClient.js +0 -103
  593. package/dist/shared/swap-aggregator/src/index.d.ts +0 -1
  594. package/dist/shared/swap-aggregator/src/index.js +0 -17
  595. package/docs/launchingToken.md +0 -57
  596. package/scripts/asyncBurn.ts +0 -155
  597. package/scripts/burnToken.ts +0 -120
  598. package/scripts/claimIncentives.ts +0 -125
  599. package/scripts/closeCpiPlans.ts +0 -113
  600. package/scripts/collectInterest.ts +0 -194
  601. package/scripts/collectProtocolFees.ts +0 -144
  602. package/scripts/computeOptimalAllocations.ts +0 -117
  603. package/scripts/createToken.ts +0 -100
  604. package/scripts/createTokenLendingPosition.ts +0 -204
  605. package/scripts/createYieldingBank.ts +0 -91
  606. package/scripts/decreaseCarryPositions.ts +0 -359
  607. package/scripts/depositUnlentCollateral.ts +0 -106
  608. package/scripts/emergency/deleverageAll.ts +0 -287
  609. package/scripts/emergency/triggerCircuitBreaker.ts +0 -87
  610. package/scripts/env.ts +0 -4
  611. package/scripts/findTxs.ts +0 -169
  612. package/scripts/increaseCarryPositions.ts +0 -134
  613. package/scripts/inspect/format.ts +0 -576
  614. package/scripts/inspect.ts +0 -147
  615. package/scripts/localUtils.ts +0 -249
  616. package/scripts/mintToken.ts +0 -126
  617. package/scripts/processAsyncBurns.ts +0 -89
  618. package/scripts/rebalanceToken.ts +0 -269
  619. package/scripts/rebalanceYieldingBank.ts +0 -183
  620. package/scripts/recollateralizeLoss.ts +0 -79
  621. package/scripts/refresh.ts +0 -156
  622. package/scripts/updateFees.ts +0 -486
  623. package/scripts/updateGeneralLut.ts +0 -36
  624. package/scripts/updateLendingPositionConfig.ts +0 -172
  625. package/scripts/updateTokenLuts.ts +0 -36
  626. package/scripts/updateTokenMetadata.ts +0 -199
  627. package/scripts/updateYieldingBankConfig.ts +0 -100
  628. package/scripts/withdrawUnlentCollateral.ts +0 -178
  629. package/src/client/account.ts +0 -503
  630. package/src/client/builders/args.ts +0 -381
  631. package/src/client/builders/asyncBurnBuilder.ts +0 -305
  632. package/src/client/builders/base.ts +0 -303
  633. package/src/client/builders/burnTokenBuilder.ts +0 -258
  634. package/src/client/builders/claimIncentivesBuilder.ts +0 -211
  635. package/src/client/builders/collectFeesBuilder.ts +0 -52
  636. package/src/client/builders/collectInterestBuilder.ts +0 -165
  637. package/src/client/builders/createCpiPlanBuilder.ts +0 -21
  638. package/src/client/builders/createTokenBuilder.ts +0 -73
  639. package/src/client/builders/createTokenLendingPositionBuilder.ts +0 -219
  640. package/src/client/builders/createYieldingBankAllocationBuilder.ts +0 -32
  641. package/src/client/builders/createYieldingBankBuilder.ts +0 -39
  642. package/src/client/builders/decreaseCarryPositionBuilder.ts +0 -162
  643. package/src/client/builders/depositUnlentCollateralBuilder.ts +0 -95
  644. package/src/client/builders/increaseCarryPositionBuilder.ts +0 -105
  645. package/src/client/builders/index.ts +0 -37
  646. package/src/client/builders/mintTokenBuilder.ts +0 -137
  647. package/src/client/builders/rebalanceTokenBuilder.ts +0 -356
  648. package/src/client/builders/rebalanceYieldingBankBuilder.ts +0 -109
  649. package/src/client/builders/recollateralizeLossBuilder.ts +0 -367
  650. package/src/client/builders/refreshTokenStateBuilder.ts +0 -153
  651. package/src/client/builders/refreshTokensBuilder.ts +0 -82
  652. package/src/client/builders/refreshYieldingBankBuilder.ts +0 -42
  653. package/src/client/builders/resetTokenBurnRateLimitBuilder.ts +0 -21
  654. package/src/client/builders/setTokenCircuitBreakerBuilder.ts +0 -40
  655. package/src/client/builders/setYieldingBankCircuitBreakerBuilder.ts +0 -37
  656. package/src/client/builders/updateLendingPositionConfigBuilder.ts +0 -33
  657. package/src/client/builders/updateTokenConfigurationBuilder.ts +0 -50
  658. package/src/client/builders/updateTokenMetadataBuilder.ts +0 -24
  659. package/src/client/builders/updateYieldingBankConfigBuilder.ts +0 -32
  660. package/src/client/builders/utils.ts +0 -26
  661. package/src/client/client.ts +0 -264
  662. package/src/client/externalLiquidityResolver.ts +0 -54
  663. package/src/client/index.ts +0 -20
  664. package/src/client/lendingPlatformClients.ts +0 -50
  665. package/src/client/pda.ts +0 -102
  666. package/src/client/plans/collectInterest.ts +0 -207
  667. package/src/client/plans/decreaseCarryPosition.ts +0 -226
  668. package/src/client/routes/collectInterest.ts +0 -56
  669. package/src/client/transaction.ts +0 -106
  670. package/src/client/types/builders.ts +0 -19
  671. package/src/client/types/enums.ts +0 -47
  672. package/src/client/types/general.ts +0 -117
  673. package/src/client/types/index.ts +0 -6
  674. package/src/client/types/ix.ts +0 -452
  675. package/src/client/types/planTypes/collectInterest.ts +0 -97
  676. package/src/client/types/planTypes/common.ts +0 -31
  677. package/src/client/types/planTypes/decreaseCarryPosition.ts +0 -134
  678. package/src/client/types/planTypes/index.ts +0 -3
  679. package/src/client/types/tx.ts +0 -409
  680. package/src/constants/configs/allocations.ts +0 -30
  681. package/src/constants/configs/carryTradePresets.ts +0 -164
  682. package/src/constants/configs/index.ts +0 -2
  683. package/src/constants/general.ts +0 -141
  684. package/src/constants/index.ts +0 -3
  685. package/src/constants/lycTokenMetadata.ts +0 -52
  686. package/src/decoders/decodeTransaction.ts +0 -319
  687. package/src/decoders/discriminators.ts +0 -10
  688. package/src/decoders/idlAccounts.ts +0 -75
  689. package/src/decoders/index.ts +0 -15
  690. package/src/decoders/innerCpis.ts +0 -262
  691. package/src/decoders/lycInstructionNames.ts +0 -73
  692. package/src/decoders/programIds.ts +0 -12
  693. package/src/decoders/solana.ts +0 -25
  694. package/src/decoders/transactionPayload.ts +0 -41
  695. package/src/decoders/types.ts +0 -60
  696. package/src/errors.ts +0 -195
  697. package/src/idl/long_yield_carry.ts +0 -14648
  698. package/src/index.ts +0 -10
  699. package/src/metrics/index.ts +0 -1
  700. package/src/metrics/protocolMetrics.ts +0 -976
  701. package/src/models/index.ts +0 -9
  702. package/src/models/lycToken.ts +0 -380
  703. package/src/models/yieldingBank.ts +0 -127
  704. package/src/services/allocation/allocationService.ts +0 -823
  705. package/src/services/allocation/index.ts +0 -2
  706. package/src/services/allocation/types.ts +0 -27
  707. package/src/services/carry/carryAllocationConfig.ts +0 -266
  708. package/src/services/carry/index.ts +0 -2
  709. package/src/services/carry/lycLendingPositionManager.ts +0 -167
  710. package/src/services/index.ts +0 -5
  711. package/src/services/lendingPosition/index.ts +0 -5
  712. package/src/services/lendingPosition/lendingPositionService.ts +0 -328
  713. package/src/services/rebalance/index.ts +0 -2
  714. package/src/services/rebalance/token/index.ts +0 -1
  715. package/src/services/rebalance/token/tokenRebalanceService.ts +0 -142
  716. package/src/services/rebalance/yieldingBank/index.ts +0 -3
  717. package/src/services/rebalance/yieldingBank/planner.ts +0 -215
  718. package/src/services/rebalance/yieldingBank/strategy.ts +0 -41
  719. package/src/services/rebalance/yieldingBank/types.ts +0 -41
  720. package/src/services/redemption/index.ts +0 -9
  721. package/src/services/redemption/redemptionService.ts +0 -758
  722. package/src/types/enriched.ts +0 -187
  723. package/src/types/index.ts +0 -1
  724. package/src/utils/cache.ts +0 -12
  725. package/src/utils/data.ts +0 -65
  726. package/src/utils/enrichment.ts +0 -330
  727. package/src/utils/feeDripMetrics.ts +0 -146
  728. package/src/utils/general.ts +0 -54
  729. package/src/utils/index.ts +0 -13
  730. package/src/utils/ix.ts +0 -227
  731. package/src/utils/lendingPosition.ts +0 -221
  732. package/src/utils/lookupTables.ts +0 -309
  733. package/src/utils/lycData.ts +0 -321
  734. package/src/utils/timelock.ts +0 -63
  735. package/src/utils/tokenFeeMath.ts +0 -25
  736. package/src/utils/transactions.ts +0 -109
  737. package/src/utils/yieldingBank.ts +0 -38
  738. package/tsconfig.json +0 -11
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../shared/lending-platforms/src/services/client/kamino.ts","../../../shared/lending-platforms/src/services/client/lpClientBase.ts","../../../shared/lending-platforms/src/data/platform/kamino.ts","../../../shared/lending-platforms/src/constants/cache.ts","../../../shared/lending-platforms/src/data/platform/lpDataBase.ts","../../../shared/lending-platforms/src/constants/kamino.ts","../../../shared/lending-platforms/src/constants/lendingPosition.ts","../../../shared/lending-platforms/src/utils/accounts.ts","../../../shared/lending-platforms/src/utils/cache.ts","../../../shared/lending-platforms/src/utils/kamino.ts","../../../shared/lending-platforms/src/utils/math.ts","../../../shared/lending-platforms/src/utils/scope.ts","../../../shared/lending-platforms/src/data/reserve/kamino.ts","../../../shared/lending-platforms/src/data/incentive/incentiveBase.ts","../../../shared/lending-platforms/src/data/incentive/kamino.ts","../../../shared/lending-platforms/src/data/reserve/reserveBase.ts","../../../shared/lending-platforms/src/data/userPosition/kamino.ts","../../../shared/lending-platforms/src/data/userPosition/userPositionBase.ts","../../../shared/lending-platforms/src/data/instructions/kamino.ts","../../../shared/lending-platforms/src/data/instructions/lpInstructionsBase.ts","../../../shared/lending-platforms/src/data/accounts/kamino.ts","../../../shared/lending-platforms/src/data/accounts/lpAccountsBase.ts","../../../shared/lending-platforms/src/services/flashLoan/kamino.ts","../../../shared/lending-platforms/src/services/flashLoan/flashLoanBase.ts","../../../shared/lending-platforms/src/services/leverage/leverageService.ts","../../../shared/jupiter-helpers/src/constants.ts","../../../shared/jupiter-helpers/src/api.ts","../../../shared/jupiter-helpers/src/extract.ts","../../../shared/jupiter-helpers/src/routePreInstructions.ts","../../../shared/jupiter-helpers/src/client.ts","../../../shared/jupiter-helpers/src/sizeExactInForMinOutput.ts","../../../shared/lending-platforms/src/services/lendingPosition/lendingPositionManager.ts","../../../shared/lending-platforms/src/services/reservesManager.ts","../src/constants/configs/carryTradePresets.ts","../src/services/carry/carryAllocationConfig.ts","../src/services/carry/lycLendingPositionManager.ts"],"sourcesContent":["import { Address } from \"@solana/kit\";\nimport { BN } from \"@anchor-lang/core\";\nimport { Obligation } from \"@kamino-finance/klend-sdk\";\nimport { getRpcUrl, ENVIRONMENT, U64_MAX_BN } from \"common\";\nimport { LendingPlatformClientBase } from \"./lpClientBase\";\nimport { KaminoData, KaminoUserPositionData } from \"../../data\";\nimport { KaminoAccounts } from \"../../data/accounts\";\nimport { KaminoInstructions } from \"../../data/instructions\";\nimport { KaminoFlashLoan } from \"../flashLoan/kamino\";\nimport type { OutstandingIncentive } from \"../../types\";\n\n/**\n * Client for interacting with Kamino Lend protocol.\n * Provides access to data, accounts, and instruction builders for lending operations.\n */\nexport class KaminoClient extends LendingPlatformClientBase<KaminoData> {\n accounts: KaminoAccounts;\n ix: KaminoInstructions;\n\n constructor(rpcUrl: string = getRpcUrl(ENVIRONMENT), rpcUrls: string[] = [rpcUrl]) {\n super(rpcUrl, rpcUrls);\n this.data = new KaminoData(rpcUrl, undefined, rpcUrls);\n this.accounts = new KaminoAccounts(this.data);\n this.ix = new KaminoInstructions(this.rpc, rpcUrl, this.data, this.accounts);\n }\n\n async refreshData(pools: Address[]) {\n this.data.clearCache();\n await this.data.load(pools);\n }\n\n getFlashLoan(): KaminoFlashLoan {\n return new KaminoFlashLoan(this.data);\n }\n\n /**\n * Kamino's `RepayObligationLiquidityV2` interprets `u64::MAX` as \"repay\n * the obligation's full debt for this reserve\" — letting the on-chain\n * handler clear interest-accrual dust between the off-chain quote and\n * settlement. The flash-borrow over-borrows by a slippage buffer to fund\n * this; the post-repay surplus is swept into the yielding bank.\n */\n override getRepayAllSentinel(): BN {\n return U64_MAX_BN;\n }\n\n async getAvailableUserAccountId(\n pool: Address,\n user: Address,\n excludeUserAccounts: readonly Address[] = []\n ): Promise<number> {\n const positions = await this.data.fetchAllUserPositionsForUserInPool(pool, user);\n const positionsByAddress = new Map(positions.map((position) => [position.address, position]));\n const excludeSet = new Set(excludeUserAccounts);\n\n for (let userAccountId = 0; ; userAccountId++) {\n const userAccount = await this.accounts.getUserAccountAddress(pool, user, userAccountId);\n if (excludeSet.has(userAccount)) {\n continue;\n }\n const existingPosition = positionsByAddress.get(userAccount);\n\n if (!existingPosition || this.isInactiveUserAccount(existingPosition)) {\n return userAccountId;\n }\n }\n }\n\n /**\n * Returns claimable rewards across all kamino farms tied to this obligation:\n *\n * - **Obligation farms** (klend reserve `farmCollateral`/`farmDebt`):\n * UserState.owner = obligation owner (the lyc-token PDA),\n * UserState.delegatee = the obligation itself.\n * - **Direct/extra farms** (e.g. paired-reserve incentives): the lyc-token\n * PDA stakes directly in the farms program.\n * UserState.owner = UserState.delegatee = lyc-token PDA.\n *\n * The farms SDK filters UserStates by memcmp against `owner` (offset 48),\n * so we query by the obligation's owner and then accept any UserState whose\n * `delegatee` is either the obligation or the owner itself. In both cases\n * `userFarm.userStateAddress` is the correct UserState account for the\n * `HarvestReward` CPI; deriving via `obligationFarmStatePda` would be wrong\n * for direct farms (different seed scheme).\n */\n async getOutstandingIncentives(\n userAccount: Address,\n minUiAmount = 0,\n log?: (msg: string) => void\n ): Promise<OutstandingIncentive[]> {\n const obligationOwner = await this.fetchObligationOwner(userAccount);\n if (!obligationOwner) {\n log?.(` [getOutstandingIncentives] no obligation owner found for ${userAccount}`);\n return [];\n }\n const allOwnerFarms = await this.data.fetchUserActiveIncentives(obligationOwner);\n log?.(\n ` [getOutstandingIncentives] found ${allOwnerFarms.length} farm(s) owned by ${obligationOwner.slice(0, 6)}…`\n );\n const userFarms = allOwnerFarms.filter(\n (uf) => uf.userState.delegatee === userAccount || uf.userState.delegatee === obligationOwner\n );\n const filteredOut = allOwnerFarms.length - userFarms.length;\n if (filteredOut > 0) {\n log?.(\n ` [getOutstandingIncentives] ${filteredOut} farm(s) skipped — delegatee matched neither userAccount (${userAccount.slice(0, 6)}…) nor owner`\n );\n }\n if (userFarms.length === 0) {\n log?.(` [getOutstandingIncentives] no matching farms for userAccount`);\n return [];\n }\n\n // Reward token decimals live on the FarmState, not on the pending-reward\n // entry, so fetch the (cached) farm states to convert raw balances to UI\n // units for the dust filter.\n const farmStates = await this.data.fetchFarms(userFarms.map((uf) => uf.farm));\n const decimalsByFarmAndMint = new Map<string, number>();\n farmStates.forEach((farmState, i) => {\n const farm = userFarms[i].farm;\n for (const rewardInfo of farmState.rewardInfos) {\n decimalsByFarmAndMint.set(\n `${farm}:${rewardInfo.token.mint}`,\n rewardInfo.token.decimals.toNumber()\n );\n }\n });\n\n const incentives: OutstandingIncentive[] = [];\n\n for (const userFarm of userFarms) {\n log?.(\n ` [getOutstandingIncentives] farm ${userFarm.farm.slice(0, 6)}… userFarm ${userFarm.userStateAddress.slice(0, 6)}… delegatee ${userFarm.userState.delegatee.slice(0, 6)}… ${userFarm.pendingRewards.length} pending reward(s)`\n );\n for (const reward of userFarm.pendingRewards) {\n const amount = reward.cumulatedPendingRewards.toNumber();\n const decimals =\n decimalsByFarmAndMint.get(`${userFarm.farm}:${reward.rewardTokenMint}`) ?? 0;\n const uiAmount = amount / 10 ** decimals;\n if (amount <= 0) {\n log?.(` reward ${reward.rewardTokenMint.slice(0, 6)}… — skipped (amount=0)`);\n continue;\n }\n if (uiAmount < minUiAmount) {\n log?.(\n ` reward ${reward.rewardTokenMint.slice(0, 6)}… — skipped (uiAmount=${uiAmount.toFixed(4)} < minUiAmount=${minUiAmount})`\n );\n continue;\n }\n log?.(\n ` reward ${reward.rewardTokenMint.slice(0, 6)}… — claimable uiAmount=${uiAmount.toFixed(4)}`\n );\n incentives.push({\n mint: reward.rewardTokenMint,\n amount,\n decimals,\n uiAmount,\n claimAccounts: {\n farm: userFarm.farm,\n userFarm: userFarm.userStateAddress,\n },\n });\n }\n }\n\n return incentives;\n }\n\n /**\n * Reads the klend obligation account and returns its `owner` field (the\n * authority that opened the obligation — for LYC this is the lyc-token PDA).\n * Returns null when the account doesn't exist on-chain (stale protocolUserAcc).\n */\n private async fetchObligationOwner(userAccount: Address): Promise<Address | null> {\n const obligation = await Obligation.fetch(this.rpc, userAccount);\n return obligation ? (obligation.owner as Address) : null;\n }\n\n private isInactiveUserAccount(position: KaminoUserPositionData): boolean {\n return [...position.deposits, ...position.borrows].every((entry) => entry.amount.isZero());\n }\n}\n","import { Address, Rpc, SolanaRpcApi } from \"@solana/kit\";\nimport { BN } from \"@anchor-lang/core\";\nimport { createRpcWithFailover, TransactionCacheInvalidation } from \"common\";\nimport { LendingPlatformData, LpAccountsBase, LpInstructionsBase } from \"../../data\";\nimport type { FlashLoanBase } from \"../flashLoan/flashLoanBase\";\nimport type { OutstandingIncentive } from \"../../types\";\n\n/**\n * A platform-agnostic lending client — the base class instantiated against\n * any concrete `LendingPlatformData` subclass. Use this when a function\n * doesn't care about the underlying platform (Kamino, Marginfi, etc.) and\n * just needs to call the shared abstract surface.\n */\nexport type AnyLendingPlatformClient = LendingPlatformClientBase<LendingPlatformData>;\n\n/**\n * Abstract base class for lending platform clients.\n * Provides a unified interface for interacting with different lending protocols.\n *\n * @typeParam T - The platform-specific data class extending LendingPlatformData\n */\nexport abstract class LendingPlatformClientBase<T extends LendingPlatformData> {\n public rpc!: Rpc<SolanaRpcApi>;\n public data!: T;\n public abstract accounts: LpAccountsBase<T>;\n public abstract ix: LpInstructionsBase<T>;\n\n constructor(rpcUrl: string, rpcUrls: string[] = [rpcUrl]) {\n this.rpc = createRpcWithFailover(rpcUrls);\n }\n\n applyPostSuccessCacheInvalidations(invalidations: TransactionCacheInvalidation[]) {\n this.ix.applyPostSuccessCacheInvalidations(invalidations);\n }\n\n /** Refreshes cached platform data for the specified pools */\n abstract refreshData(pools: Address[]): Promise<void>;\n\n /**\n * Returns this platform's flash-loan client. Implementations should throw\n * if the platform doesn't expose a flash-loan facility.\n */\n abstract getFlashLoan(): FlashLoanBase<T>;\n\n /**\n * Returns the platform-specific \"repay full obligation debt\" sentinel for\n * the repay CPI's amount field, or `null` if the platform has no such\n * sentinel and callers must compute the exact debt amount themselves.\n * Used by `rebalance_token` on full-position moves to clear obligation\n * debt exactly without leaving interest-accrual dust.\n */\n abstract getRepayAllSentinel(): BN | null;\n\n /**\n * Returns the first user-account ID that can be used in `pool` for `user`.\n *\n * Implementations may reuse an existing inactive account or return the first\n * never-before-used ID, depending on the platform's account model.\n *\n * `excludeUserAccounts`, when provided, lists protocol user-account\n * addresses that must NOT be returned even if they look reusable on-chain\n * (e.g. zero deposits + zero borrows). Callers managing multiple\n * higher-level positions over the same `(pool, user)` pair use this to\n * ensure each position gets its own distinct user account, even when\n * sibling positions are temporarily inactive on-chain.\n */\n abstract getAvailableUserAccountId(\n pool: Address,\n user: Address,\n excludeUserAccounts?: readonly Address[]\n ): Promise<number>;\n\n /**\n * Returns the protocol user account's currently claimable rewards, excluding\n * zero balances. Entries may include claim metadata required by the platform\n * to harvest that specific reward.\n *\n * `minUiAmount` filters out dust: rewards whose UI-denominated balance is\n * below this threshold are omitted, so callers don't pay transaction fees to\n * harvest economically negligible amounts. Defaults to `0` (no filtering).\n */\n abstract getOutstandingIncentives(\n userAccount: Address,\n minUiAmount?: number,\n log?: (msg: string) => void\n ): Promise<OutstandingIncentive[]>;\n}\n","import { type Address } from \"@solana/kit\";\nimport {\n KaminoMarket,\n KaminoObligation,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n PROGRAM_ID,\n DEFAULT_PUBLIC_KEY,\n KaminoReserve,\n KlendPrices,\n VanillaObligation,\n userMetadataPda,\n} from \"@kamino-finance/klend-sdk\";\nimport { Scope } from \"@kamino-finance/scope-sdk\";\nimport { Farms, FarmState, UserFarm } from \"@kamino-finance/farms-sdk\";\nimport { LendingPlatformData } from \"./lpDataBase\";\nimport { KaminoReserveData, KaminoUserPositionData, KaminoIncentiveDataArgs } from \"..\";\nimport { KAMINO_FARMS_PROGRAM_ID } from \"../../constants\";\nimport { LendingPlatform } from \"../../types\";\nimport { fetchExtraFarms } from \"../../utils\";\nimport { OraclePrices } from \"@kamino-finance/scope-sdk/dist/@codegen/scope/accounts\";\nimport { CacheTtlConfig, currentUnixSeconds } from \"common\";\nimport Decimal from \"decimal.js\";\n\n/** Cache configuration for Kamino data with optional market-specific TTL */\nexport interface KaminoCacheConfig extends CacheTtlConfig {\n marketsTtlMs?: number;\n}\n\n/** Internal type for tracking farm addresses and their type (collateral vs debt) */\ninterface FarmEntry {\n address: Address;\n isDebtFarm: boolean;\n}\n\n/**\n * Data provider for Kamino Lend protocol.\n * Handles fetching and caching of markets, reserves, obligations, farms, and prices.\n * Supports both standard reserve farms and \"extra\" farms (paired collateral/debt incentives).\n */\nexport class KaminoData extends LendingPlatformData {\n farms!: Farms;\n private scope!: Scope;\n\n constructor(rpcUrl: string, cacheConfig?: KaminoCacheConfig, rpcUrls: string[] = [rpcUrl]) {\n const ttlConfig: CacheTtlConfig = {\n defaultTtlMs: 90_000,\n categoryTtlMs: {\n ...cacheConfig?.categoryTtlMs,\n markets: 60_000 * 5,\n farms: 60_000 * 5,\n extraFarms: Number.MAX_SAFE_INTEGER,\n scopeOraclePrices: 30_000,\n scopeConfig: 60_000 * 5,\n },\n };\n super(rpcUrl, ttlConfig, rpcUrls);\n this.farms = new Farms(this.rpc, KAMINO_FARMS_PROGRAM_ID);\n this.scope = new Scope(\"mainnet-beta\", this.rpc as any);\n }\n\n platform(): LendingPlatform {\n return LendingPlatform.Kamino;\n }\n\n /**\n * Warms the market cache for the requested pools. Single-pool calls reuse the\n * normal lazy fetch path; multi-pool calls use Kamino's batched loader.\n */\n async load(pools: Address[]): Promise<void> {\n if (pools.length === 0) return;\n\n if (pools.length === 1) {\n await this.fetchMarket(pools[0]);\n return;\n }\n\n const { data: markets, fromCache } = await this.cache.getDataBatch<KaminoMarket>(\n async () => {\n const marketsData = await KaminoMarket.loadMultiple(\n this.rpc,\n pools,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n PROGRAM_ID,\n true\n );\n return pools.map((pool) => marketsData.get(pool) ?? null);\n },\n this.poolCatKey,\n pools\n );\n\n if (!fromCache) {\n await Promise.all(markets.map(async (market) => await market.loadReserves()));\n }\n }\n\n /** Fetches a market by address, loading from cache if available */\n async fetchMarket(market: Address): Promise<KaminoMarket> {\n const { data, fromCache } = await this.cache.getDataOrThrow<KaminoMarket>(\n async () =>\n await KaminoMarket.load(\n this.rpc,\n market,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n PROGRAM_ID,\n true\n ),\n this.poolCatKey,\n market\n );\n if (!fromCache) {\n await data.loadReserves();\n }\n return data;\n }\n\n /** Fetches all oracle prices for assets in the specified market */\n async fetchPrices(pool: Address) {\n const market = await this.fetchMarket(pool);\n const { data } = await this.cache.getDataOrThrow<KlendPrices>(\n async () => await market.getAllPrices(),\n \"prices\",\n \"queryAll\"\n );\n return data;\n }\n\n /** Fetches an obligation (user position) by address */\n async fetchObligation(\n market: KaminoMarket,\n obligation: Address\n ): Promise<KaminoObligation | null> {\n const { data } = await this.cache.getData<KaminoObligation>(\n async () => await market.getObligationByAddress(obligation),\n this.userAccountCatKey,\n obligation,\n { cacheNull: false }\n );\n return data;\n }\n\n /** Batch fetches farm states by their addresses */\n async fetchFarms(farms: Address[]) {\n const { data } = await this.cache.getDataBatch<FarmState>(\n async () => (await this.farms.getAllFarmStatesByPubkeys(farms)).map((x) => x.farmState),\n \"userFarms\",\n farms\n );\n return data;\n }\n\n private async fetchExtraFarms() {\n const { data } = await this.cache.getDataOrThrow(\n async () => await fetchExtraFarms(),\n \"extraFarms\",\n \"mainnet-beta\"\n );\n return data;\n }\n\n /**\n * Collects all farm incentives for a reserve, including both standard\n * collateral/debt farms and extra paired farms from Kamino CDN config.\n */\n private async fetchFarmsForReserve(\n pool: Address,\n reserve: Address\n ): Promise<KaminoIncentiveDataArgs[]> {\n const market = await this.fetchMarket(pool);\n const reserveData = market.getReserveByAddress(reserve);\n if (!reserveData) {\n throw new Error(`Unable to find reserve ${reserve}`);\n }\n\n const farms: FarmEntry[] = [];\n\n const farmCollateral = reserveData.state.farmCollateral;\n const farmDebt = reserveData.state.farmDebt;\n\n if (farmCollateral && farmCollateral !== DEFAULT_PUBLIC_KEY) {\n farms.push({ address: farmCollateral, isDebtFarm: false });\n }\n if (farmDebt && farmDebt !== DEFAULT_PUBLIC_KEY) {\n farms.push({ address: farmDebt, isDebtFarm: true });\n }\n\n const extraFarmsData = (await this.fetchExtraFarms()).filter(\n (x) => x.collReserve === reserve || x.debtReserve === reserve\n );\n const extraFarmEntries: FarmEntry[] = extraFarmsData.map((x) => ({\n address: x.farm,\n isDebtFarm: x.debtReserve === reserve,\n }));\n\n const allFarmEntries = [...farms, ...extraFarmEntries];\n const allFarmAddresses = allFarmEntries.map((f) => f.address);\n\n if (!allFarmAddresses.length) {\n return [];\n }\n\n const farmStates = await this.fetchFarms(allFarmAddresses);\n const result: KaminoIncentiveDataArgs[] = [];\n\n farmStates.forEach((farmState, i) => {\n const farmEntry = allFarmEntries[i];\n const isExtraFarm = i >= farms.length;\n const extraFarmIndex = i - farms.length;\n\n farmState.rewardInfos.forEach((rewardInfo, rewardIndex) => {\n if (rewardInfo.rewardsVault === DEFAULT_PUBLIC_KEY) {\n return;\n }\n\n result.push({\n data: {\n key: farmEntry.address,\n farmState,\n },\n rewardIndex,\n requiresPairReserve: isExtraFarm ? extraFarmsData[extraFarmIndex].debtReserve : undefined,\n isDebtFarm: farmEntry.isDebtFarm,\n });\n });\n });\n\n return result;\n }\n\n async fetchUserActiveIncentives(user: Address, specificFarm?: Address) {\n let { data } = await this.cache.getDataOrThrow<UserFarm[]>(\n async () => {\n return Array.from(\n (\n await this.farms.getAllFarmsForUserMultiState(user, new Decimal(currentUnixSeconds()))\n ).values()\n ).flat();\n },\n \"userFarms\",\n user\n );\n\n if (specificFarm) {\n data = data.filter((x) => x.farm === specificFarm);\n }\n\n return data;\n }\n\n async maybeFetchUserPositionInPool(\n pool: Address,\n userPosition: Address\n ): Promise<KaminoUserPositionData | null> {\n const market = await this.fetchMarket(pool);\n const obligation = await this.fetchObligation(market, userPosition);\n return obligation ? KaminoUserPositionData.loadData(obligation) : null;\n }\n\n async fetchUserPositionsInPool(\n pool: Address,\n userPositions: Address[]\n ): Promise<KaminoUserPositionData[]> {\n const market = await this.fetchMarket(pool);\n const { data } = await this.cache.getDataBatch<KaminoObligation>(\n async () => await market.getMultipleObligationsByAddress(userPositions),\n this.userAccountCatKey,\n userPositions\n );\n return data.map((obligation) => KaminoUserPositionData.loadData(obligation));\n }\n\n async fetchAllUserPositionsForUserInPool(\n pool: Address,\n user: Address\n ): Promise<KaminoUserPositionData[]> {\n const market = await this.fetchMarket(pool);\n const { data } = await this.cache.getDataOrThrow<KaminoObligation[]>(\n async () => await market.getAllUserObligations(user, \"confirmed\"),\n \"obligationsBatch\",\n user\n );\n return data.map((obligation) => KaminoUserPositionData.loadData(obligation));\n }\n\n async fetchReserve(pool: Address, reserve: Address): Promise<KaminoReserveData> {\n const market = await this.fetchMarket(pool);\n const reserveData = market.getReserveByAddress(reserve);\n if (!reserveData) {\n throw new Error(`Unable to find reserve ${reserve}`);\n }\n return this.mapReserve(market, reserveData);\n }\n\n async fetchReserveByMint(pool: Address, mint: Address): Promise<KaminoReserveData> {\n const market = await this.fetchMarket(pool);\n const reserveData = market.getReserveByMint(mint);\n if (!reserveData) {\n throw new Error(`Unable to find reserve by mint ${mint}`);\n }\n return this.mapReserve(market, reserveData);\n }\n\n private async mapReserve(\n market: KaminoMarket,\n reserve: KaminoReserve\n ): Promise<KaminoReserveData> {\n return KaminoReserveData.loadData(\n market,\n reserve,\n await this.fetchFarmsForReserve(market.address, reserve.address),\n await this.fetchPrices(market.address),\n await this.getSlot()\n );\n }\n\n /**\n * Fetches and caches the Scope OraclePrices account for a given price feed.\n * @returns The deserialized OraclePrices, or null if the account doesn't exist\n */\n async fetchScopeOraclePrices(priceFeed: Address): Promise<OraclePrices | null> {\n const { data } = await this.cache.getData<OraclePrices>(\n async () => await this.scope.getSingleOraclePrices({ prices: priceFeed }),\n \"scopeOraclePrices\",\n priceFeed\n );\n return data;\n }\n\n /**\n * Resolves and caches the Scope Configuration account address for a given OraclePrices account.\n * The first call per price feed does a getProgramAccounts lookup; subsequent calls use cache.\n */\n async fetchScopeConfigAddress(priceFeed: Address): Promise<Address> {\n const { data } = await this.cache.getDataOrThrow<Address>(\n async () => {\n const [configAddr] = await this.scope.getSingleFeedConfiguration({\n prices: priceFeed,\n });\n return configAddr;\n },\n \"scopeConfig\",\n priceFeed\n );\n return data;\n }\n}\n","/**\n * `DataCache` category keys for `LendingPlatformData` and platform implementations.\n * Prefer `data.poolCatKey` / `data.reserveCatKey` / `data.userAccountCatKey` when you have a data\n * instance so subclasses stay consistent; import these constants for static references or other packages.\n */\nexport const LENDING_PLATFORM_DATA_CACHE_CATEGORY_POOL = \"pool\";\nexport const LENDING_PLATFORM_DATA_CACHE_CATEGORY_RESERVE = \"reserve\";\nexport const LENDING_PLATFORM_DATA_CACHE_CATEGORY_USER_ACCOUNT = \"userAccount\";\n","import { type Address, type Rpc, type SolanaRpcApi } from \"@solana/kit\";\nimport { ReserveBase, UserPositionBase } from \"..\";\nimport { createRpcWithFailover, DataCache, CacheTtlConfig, getSlot } from \"common\";\nimport { LendingPlatform } from \"../../types\";\nimport {\n LENDING_PLATFORM_DATA_CACHE_CATEGORY_POOL,\n LENDING_PLATFORM_DATA_CACHE_CATEGORY_RESERVE,\n LENDING_PLATFORM_DATA_CACHE_CATEGORY_USER_ACCOUNT,\n} from \"../../constants/cache\";\n\n/**\n * Abstract base class for fetching and caching lending platform data.\n * Provides a unified interface for accessing markets, reserves, and user positions\n * across different lending protocols with built-in TTL-based caching.\n */\nexport abstract class LendingPlatformData {\n protected rpc!: Rpc<SolanaRpcApi>;\n protected cache!: DataCache;\n\n public poolCatKey = LENDING_PLATFORM_DATA_CACHE_CATEGORY_POOL;\n public reserveCatKey = LENDING_PLATFORM_DATA_CACHE_CATEGORY_RESERVE;\n public userAccountCatKey = LENDING_PLATFORM_DATA_CACHE_CATEGORY_USER_ACCOUNT;\n\n constructor(rpcUrl: string, cacheTtlConfig?: CacheTtlConfig, rpcUrls: string[] = [rpcUrl]) {\n this.rpc = createRpcWithFailover(rpcUrls);\n this.cache = new DataCache(cacheTtlConfig);\n }\n\n /** Returns the platform identifier for this data provider */\n abstract platform(): LendingPlatform;\n\n /** Loads and caches data for the specified lending pools/markets */\n abstract load(pools: Address[]): Promise<void>;\n\n clearCache() {\n this.cache.clearAllCache();\n }\n\n clearCacheEntry(category: string, id: string) {\n this.cache.clearCacheEntry(category, id);\n }\n\n /** Returns the current slot, cached to reduce RPC calls */\n async getSlot() {\n const { data } = await this.cache.getDataOrThrow<bigint>(\n async () => await getSlot(this.rpc),\n \"slot\",\n \"slot\"\n );\n return data;\n }\n\n /** Fetches a single user position by address if it exists */\n abstract maybeFetchUserPositionInPool(\n pool: Address,\n userPosition: Address\n ): Promise<UserPositionBase | null>;\n\n /** Fetches multiple user positions by their addresses */\n abstract fetchUserPositionsInPool(\n pool: Address,\n userPositions: Address[]\n ): Promise<UserPositionBase[]>;\n\n /** Fetches all positions owned by a user in a specific pool */\n abstract fetchAllUserPositionsForUserInPool(\n pool: Address,\n user: Address\n ): Promise<UserPositionBase[]>;\n\n /** Fetches reserve data by reserve address */\n abstract fetchReserve(pool: Address, reserve: Address): Promise<ReserveBase | null>;\n\n /** Fetches reserve data by the underlying token mint */\n abstract fetchReserveByMint(pool: Address, mint: Address): Promise<ReserveBase | null>;\n}\n","import { address } from \"@solana/kit\";\nimport { LendingPlatformAccounts } from \"../types\";\n\nexport const KAMINO_FARMS_PROGRAM_ID = address(\"FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr\");\nexport const KAMINO_SCOPE_PROGRAM_ID = address(\"HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ\");\n\nexport const KAMINO_MAIN_MARKET = address(\"7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF\");\nexport const SOL_RESERVE = address(\"d4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q\");\nexport const USDC_RESERVE = address(\"D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59\");\n\nexport const KAMINO_ACCOUNTS: LendingPlatformAccounts = {\n [KAMINO_MAIN_MARKET]: [\n {\n address: SOL_RESERVE,\n mintSymbol: \"SOL\",\n },\n {\n address: address(\"37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK\"),\n mintSymbol: \"cbBTC\",\n },\n {\n address: address(\"febGYTnFX4GbSGoFHFeJXUHgNaK53fB23uDins9Jp1E\"),\n mintSymbol: \"wETH\",\n },\n {\n address: address(\"DGQZWCY17gGtBUgdaFs1VreJWsodkjFxndPsskwFKGpp\"),\n mintSymbol: \"JupSOL\",\n },\n {\n address: address(\"CkgQnPbuHHwSv2mNdAKH79TKSqC6jsyttK9yh4MPH6z3\"),\n mintSymbol: \"dfdvSOL\",\n },\n {\n address: USDC_RESERVE,\n mintSymbol: \"USDC\",\n },\n {\n address: address(\"2gc9Dm1eB6UgVYFBUN9bWks6Kes9PbWSaPaa9DqyvEiN\"),\n mintSymbol: \"PYUSD\",\n },\n {\n address: address(\"ApQkX32ULJUzszZDe986aobLDLMNDoGQK8tRm6oD6SsA\"),\n mintSymbol: \"CASH\",\n },\n {\n address: address(\"ESCkPWKHmgNE7Msf77n9yzqJd5kQVWWGy3o5Mgxhvavp\"),\n mintSymbol: \"USDG\",\n },\n {\n address: address(\"BHUi32TrEsfN2U821G4FprKrR4hTeK4LCWtA3BFetuqA\"),\n mintSymbol: \"USDS\",\n },\n {\n address: address(\"H3t6qZ1JkguCNTi9uzVKqQ7dvt2cum4XiXWom6Gn5e5S\"),\n mintSymbol: \"USDT\",\n },\n ],\n /// xStocks Market\n [address(\"5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua\")]: [\n {\n address: address(\"2jerdAXR8r2B6z3P7P6VgSiePQX7wqcpbEqdDbm8mgeB\"),\n mintSymbol: \"QQQx\",\n },\n {\n address: address(\"UvXjBuC7YZYaGB9Rn1PpBD1GySmjzunXgE8Zev9ua8d\"),\n mintSymbol: \"SPYx\",\n },\n {\n address: address(\"97zoywd8mPZsGTg8q1wdD2Wgkdrs2tqusp1Qqcxbyj7E\"),\n mintSymbol: \"USDC\",\n },\n ],\n // Bitcoin Market\n // [address(\"GMqmFygF5iSm5nkckYU6tieggFcR42SyjkkhK5rswFRs\")]: [\n // {\n // address: address(\"2Xd86oYAuhiKtQMVJBuWvJYxrSippreb46PmehGszpPQ\"),\n // mintSymbol: \"wBTC\"\n // },\n // {\n // address: address(\"9FRZvAsjDJ6WM8BJ2S45h9PoDCLAq8DNY9zZDX7MyGzT\"),\n // mintSymbol: \"USDC\"\n // }\n // ]\n};\n","/** Maximum value for `targetUtilizationRateBps` (100% LTV utilization). */\nexport const MAX_TARGET_UTILIZATION_RATE_BPS = 10_000;\n\n/**\n * Maximum unwind-trigger utilization: `target + maxDeviationAbove`.\n * Mirrors `MAX_LENDING_POSITION_UPPER_UTIL_BPS` in the on-chain program.\n */\nexport const MAX_LENDING_POSITION_UPPER_UTIL_BPS = 10_500;\n","import type { Address } from \"@solana/kit\";\nimport { KAMINO_ACCOUNTS } from \"../constants\";\n\n/**\n * Returns all lending pool addresses that list a reserve matching the\n * given mint symbol (case-insensitive).\n *\n * Useful for resolving which pool(s) a collateral token is eligible for\n * when the caller hasn't specified a pool explicitly.\n */\nexport function getEligiblePools(mintSymbol: string): Address[] {\n const needle = mintSymbol.toUpperCase();\n const pools: Address[] = [];\n\n for (const pool of Object.keys(KAMINO_ACCOUNTS)) {\n const reserves = KAMINO_ACCOUNTS[pool as Address];\n if (reserves.some((r) => r.mintSymbol.toUpperCase() === needle)) {\n pools.push(pool as Address);\n }\n }\n\n return pools;\n}\n\n/**\n * Returns all mint symbols listed in a given lending pool.\n *\n * Callers can cross-reference with the common mint registry's `assetType`\n * to filter for stablecoins, LSTs, etc.\n */\nexport function getBorrowableMintsForPool(pool: Address): string[] {\n const reserves = KAMINO_ACCOUNTS[pool];\n if (!reserves) {\n throw new Error(`getBorrowableMintsForPool: unknown pool ${pool}`);\n }\n return reserves.map((r) => r.mintSymbol);\n}\n","import { type Address } from \"@solana/kit\";\nimport { type TransactionCacheInvalidation } from \"common\";\nimport { LENDING_PLATFORM_DATA_CACHE_CATEGORY_USER_ACCOUNT } from \"../constants/cache\";\n\nexport function getLendingUserAccountCacheInvalidation(\n userAccount: Address\n): TransactionCacheInvalidation {\n return {\n client: \"kamino\",\n category: LENDING_PLATFORM_DATA_CACHE_CATEGORY_USER_ACCOUNT,\n id: userAccount,\n };\n}\n","import {\n calculateCurrentRewardPerToken,\n RewardInfo,\n SECONDS_IN_A_DAY,\n} from \"@kamino-finance/farms-sdk\";\nimport { BN } from \"@anchor-lang/core\";\nimport { LendingMarket, PROGRAM_ID } from \"@kamino-finance/klend-sdk\";\nimport { Address } from \"@solana/kit\";\nimport {\n createRpcWithRetry,\n currentUnixSeconds,\n DAYS_PER_YEAR,\n fetchWithRetry,\n fromUiAmount,\n mints,\n toUiAmount,\n} from \"common\";\nimport Decimal from \"decimal.js\";\nimport { KaminoReserveData } from \"../data\";\nimport { KaminoExtraFarmData } from \"../types\";\n\ninterface KaminoResources {\n \"mainnet-beta\": { extraFarms: KaminoExtraFarmData[] };\n}\n\n/**\n * Fetches extra farm configurations from Kamino's CDN.\n */\nexport async function fetchExtraFarms(): Promise<KaminoExtraFarmData[]> {\n const cdnRes = await fetchWithRetry(\"https://cdn.kamino.finance/resources.json\");\n const allResources = (await cdnRes.json()) as KaminoResources;\n return allResources[\"mainnet-beta\"][\"extraFarms\"];\n}\n\n/**\n * Fetches all Kamino lending markets from on-chain program accounts.\n * @returns Array of market objects with address, name, and decoded state\n */\nexport async function getAllKaminoMarkets(rpcUrl: string) {\n const rpc = createRpcWithRetry(rpcUrl);\n\n const accounts = await rpc\n .getProgramAccounts(PROGRAM_ID, {\n filters: [\n {\n dataSize: BigInt(LendingMarket.layout.span + 8), // +8 for discriminator\n },\n ],\n encoding: \"base64\",\n })\n .send();\n\n return accounts.map((account) => {\n const market = LendingMarket.decode(Buffer.from(account.account.data[0], \"base64\"));\n const name = Buffer.from(market.name).toString(\"utf8\").replace(/\\0/g, \"\");\n return {\n address: account.pubkey,\n name,\n state: market,\n };\n });\n}\n\n/**\n * Calculates the APY for a farm reward based on current reward emissions and total staked amount.\n * Converts daily reward rate to annualized percentage yield using compound interest formula.\n *\n * @param reserveMint - The mint address of the reserve's underlying token\n * @param rewardInfo - Farm reward configuration containing emission rate and token info\n * @param totalStakedRaw - Total amount staked in the farm (raw units as string)\n * @param stakedTokenDecimals - Decimal places for the staked token\n * @param exchangeRate - Exchange rate between staked shares and underlying tokens\n * @param rewardMintPrice - USD price of the reward token (used for non-stablecoin rewards)\n * @param requiresPairReserve - If the Kamino incentive requires a pair reserve in order to be eligible\n * @returns Annualized percentage yield as a decimal (e.g., 0.05 = 5% APY)\n */\nexport function calculateRewardAPY(\n reserveMint: Address,\n rewardInfo: RewardInfo,\n totalStakedRaw: string,\n stakedTokenDecimals: number,\n exchangeRate: number,\n rewardMintPrice: number,\n requiresPairReserve: boolean\n): number {\n let totalStaked = new Decimal(toUiAmount(BigInt(totalStakedRaw), stakedTokenDecimals));\n if (!requiresPairReserve) {\n totalStaked = totalStaked.div(exchangeRate);\n }\n if (totalStaked.isZero()) return 0;\n\n const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(\n rewardInfo,\n new Decimal(currentUnixSeconds())\n );\n\n if (!rewardPerTokenPerSecond) return 0;\n\n const divisor = new Decimal(10)\n .pow(new Decimal(rewardInfo.rewardsPerSecondDecimals.toString()))\n .mul(new Decimal(10).pow(new Decimal(rewardInfo.token.decimals.toString())));\n\n const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor);\n let dailyRewards = adjustedRewardPerToken.mul(SECONDS_IN_A_DAY);\n\n if (\n mints.get(rewardInfo.token.mint)?.assetType !== \"Stablecoin\" &&\n rewardInfo.token.mint !== reserveMint\n ) {\n dailyRewards = dailyRewards.mul(new Decimal(rewardMintPrice));\n }\n\n const dailyRate = dailyRewards.div(totalStaked);\n const apy = Decimal.pow(dailyRate.plus(1), DAYS_PER_YEAR).minus(1);\n\n return apy.toNumber();\n}\n\n/**\n * Converts a liquidity (underlying token) amount to collateral (cToken) amount\n * using the reserve's estimated exchange rate.\n *\n * Kamino's withdraw V2 instruction expects the amount in cTokens, so this\n * conversion is needed when the caller specifies a liquidity amount to withdraw.\n *\n * @param reserveData - The reserve to use for the exchange rate\n * @param liquidityBaseUnits - Amount in liquidity base units (e.g., USDC smallest unit)\n * @returns Amount in collateral base units (cTokens), floored to avoid overdrawing\n */\nexport function liquidityToCollateral(\n reserveData: KaminoReserveData,\n liquidityBaseUnits: number\n): number {\n const exchangeRate = reserveData.rawData\n .getEstimatedCollateralExchangeRate(reserveData.slot, 0)\n .toNumber();\n return Math.floor(liquidityBaseUnits * exchangeRate);\n}\n\n/**\n * Converts a collateral (cToken) amount back to liquidity base units using the\n * same estimated exchange rate as Kamino's reserve math.\n *\n * @param reserveData - The reserve to use for the exchange rate\n * @param collateralBaseUnits - Amount in collateral base units (cTokens)\n * @returns Amount in liquidity base units, floored to preserve withdraw safety\n */\nexport function collateralToLiquidity(\n reserveData: KaminoReserveData,\n collateralBaseUnits: number\n): number {\n const exchangeRate = reserveData.rawData\n .getEstimatedCollateralExchangeRate(reserveData.slot, 0)\n .toNumber();\n return Math.floor(collateralBaseUnits / exchangeRate);\n}\n\n/**\n * Normalizes a requested liquidity withdraw amount to the actual liquidity that\n * Kamino can redeem after converting through collateral shares.\n *\n * Kamino withdraws collateral shares, not raw liquidity. Because the liquidity\n * -> collateral conversion floors, a requested liquidity amount may redeem\n * slightly less liquidity in practice. Round-tripping through collateral shares\n * lets callers pre-snap to the realizable liquidity amount.\n *\n * @param reserveData - Source reserve used for the withdraw\n * @param liquidityBaseUnits - Requested liquidity amount in base units\n * @returns Realizable liquidity amount after liquidity -> collateral -> liquidity\n */\nexport function normalizeLiquidityWithdrawAmount(\n reserveData: KaminoReserveData,\n liquidityBaseUnits: BN | number\n): BN {\n const requestedBaseUnits =\n typeof liquidityBaseUnits === \"number\" ? liquidityBaseUnits : liquidityBaseUnits.toNumber();\n const collateralBaseUnits = liquidityToCollateral(reserveData, requestedBaseUnits);\n return new BN(collateralToLiquidity(reserveData, collateralBaseUnits));\n}\n\n/**\n * Smallest liquidity (underlying) base-unit withdraw request such that, after Kamino's\n * liquidity→collateral→liquidity rounding ({@link normalizeLiquidityWithdrawAmount}),\n * the **realized** liquidity is still at least `minLiquidityOut`.\n *\n * Used for `burn_token` withdraw CPI sizing: the on-chain program credits `unlent_amount`\n * from the actual token balance delta; if the requested withdraw floors below the burn's\n * `collateral_to_user`, the instruction fails with `InsufficientUnlentCollateral`.\n */\nexport function minLiquidityWithdrawForPayout(\n reserveData: KaminoReserveData,\n minLiquidityOut: BN\n): BN {\n const min = new BN(minLiquidityOut.toString());\n\n if (normalizeLiquidityWithdrawAmount(reserveData, min).gte(min)) {\n return min;\n }\n\n let hi = min.clone();\n let expanded = false;\n for (let i = 0; i < 64; i++) {\n hi = hi.muln(2);\n if (normalizeLiquidityWithdrawAmount(reserveData, hi).gte(min)) {\n expanded = true;\n break;\n }\n }\n if (!expanded) {\n throw new Error(\n `minLiquidityWithdrawForPayout: could not bracket min out ${minLiquidityOut.toString()}`\n );\n }\n\n let loBn = min.clone();\n let hiBn = hi.clone();\n while (loBn.lt(hiBn)) {\n const mid = loBn.add(hiBn).shrn(1);\n const realized = normalizeLiquidityWithdrawAmount(reserveData, mid);\n if (realized.gte(min)) {\n hiBn = mid;\n } else {\n loBn = mid.addn(1);\n }\n }\n return loBn;\n}\n\n/**\n * Normalizes a requested UI liquidity withdraw amount to the realizable UI\n * liquidity amount after Kamino rounds through collateral shares.\n *\n * @param reserveData - Source reserve used for the withdraw\n * @param uiAmount - Requested liquidity amount in UI units\n * @returns Realizable liquidity amount in UI units\n */\nexport function normalizeLiquidityWithdrawUiAmount(\n reserveData: KaminoReserveData,\n uiAmount: number\n): number {\n const requestedBaseUnits = fromUiAmount(uiAmount, reserveData.mint.mintDecimals);\n const normalizedBaseUnits = normalizeLiquidityWithdrawAmount(reserveData, requestedBaseUnits);\n return toUiAmount(normalizedBaseUnits, reserveData.mint.mintDecimals);\n}\n","/**\n * LTV utilization math (same definition as `ReservesManager.calcLtvUtilizationRateBps` /\n * Kamino `borrowedValueUsd / borrowLimit`):\n *\n * ```\n * ltvUtilization = debtUsd / (collateralUsd × maxLtv)\n * ```\n *\n * **Assumptions:** debt USD fixed; only collateral USD moves. Liquidation uses a one-collateral sketch\n * (`debt ≤ collateral × liquidationThreshold`). Real obligations are multi-asset.\n */\n\nfunction clampUnitInterval(x: number): number {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n return x;\n}\n\nfunction assertLtv(ltv: number): void {\n if (!(ltv > 0) || ltv > 1) {\n throw new RangeError(\"ltv must be in (0, 1] (e.g. 0.8 for 80% max LTV)\");\n }\n}\n\nfunction assertLiquidationThreshold(t: number): void {\n if (!(t > 0) || t > 1) {\n throw new RangeError(\"liquidationThreshold must be in (0, 1] (e.g. 0.85)\");\n }\n}\n\nfunction maxLtvUtilBeforeCollUsdMultiplierInternal(params: {\n collateralUsdMultiplier: number;\n ltv: number;\n targetMaxBorrowUtilizationAfter?: number;\n liquidationThreshold?: number;\n}): number {\n const {\n collateralUsdMultiplier: mult,\n ltv,\n liquidationThreshold,\n targetMaxBorrowUtilizationAfter = 1,\n } = params;\n\n assertLtv(ltv);\n if (!(mult > 0)) {\n throw new RangeError(\"collateralUsdMultiplier must be positive\");\n }\n\n if (liquidationThreshold !== undefined) {\n assertLiquidationThreshold(liquidationThreshold);\n return clampUnitInterval((mult * liquidationThreshold) / ltv);\n }\n\n if (!(targetMaxBorrowUtilizationAfter > 0) || targetMaxBorrowUtilizationAfter > 1) {\n throw new RangeError(\n \"targetMaxBorrowUtilizationAfter must be in (0, 1] (1 = 100% of borrow limit)\"\n );\n }\n\n return clampUnitInterval(mult * targetMaxBorrowUtilizationAfter);\n}\n\n/**\n * If collateral drops X% (positive `drawdownPercent`), what **current** LTV utilization (decimal) stays\n * within the constraint? With `liquidationThreshold`, caps so that after the drop the sketch stays solvent:\n * `target ≤ (1 − drawdown/100) × liquidationThreshold / maxLtv`.\n *\n * Without `liquidationThreshold`, caps so post-drop utilization ≤ `targetMaxBorrowUtilizationAfter` (default 1).\n */\nexport function maxLtvUtilBeforeCollDrawdown(params: {\n drawdownPercent: number;\n ltv: number;\n targetMaxBorrowUtilizationAfter?: number;\n liquidationThreshold?: number;\n}): number {\n if (!(params.drawdownPercent >= 0)) {\n throw new RangeError(\"drawdownPercent must be non-negative (e.g. 30 for a 30% drop)\");\n }\n const collateralUsdMultiplier = 1 - params.drawdownPercent / 100;\n if (!(collateralUsdMultiplier > 0)) {\n throw new RangeError(\n \"drawdownPercent must be less than 100 so collateral USD remains positive\"\n );\n }\n return maxLtvUtilBeforeCollUsdMultiplierInternal({\n collateralUsdMultiplier,\n ltv: params.ltv,\n targetMaxBorrowUtilizationAfter: params.targetMaxBorrowUtilizationAfter,\n liquidationThreshold: params.liquidationThreshold,\n });\n}\n\n/**\n * LTV utilization after collateral **USD** moves by `collateralPricePctChg`, with debt USD unchanged.\n *\n * `collateralPricePctChg`: signed percent on collateral price, e.g. `10` = +10% rally, `-30` = −30% crash.\n * Formula: `newUtil = currentUtil / (1 + collateralPricePctChg/100)`.\n */\nexport function ltvUtilAfterCollateralPricePctChg(\n currentLtvUtilization: number,\n collateralPricePctChg: number\n): number {\n if (!(currentLtvUtilization >= 0) || currentLtvUtilization > 1) {\n throw new RangeError(\"currentLtvUtilization must be in [0, 1]\");\n }\n const mult = 1 + collateralPricePctChg / 100;\n if (!(mult > 0)) {\n throw new RangeError(\n \"collateralPricePctChg must be greater than -100 so collateral USD stays positive\"\n );\n }\n return currentLtvUtilization / mult;\n}\n\n/**\n * If you sit at **target** utilization and collateral **rallies** `rallyPercentPositive` (e.g. `25` = +25%),\n * utilization falls. This returns how far **below** target it lands — the width of `maxDeviationBelowTarget`\n * that lines up with that rally for carry-style triggers.\n *\n * Equivalent to: `target − ltvUtilAfterCollateralPricePctChg(target, rallyPercentPositive)`.\n */\nexport function ltvUtilDeltaBelowTargForRallyPct(\n targetLtvUtilization: number,\n rallyPercentPositive: number\n): number {\n if (!(targetLtvUtilization > 0) || targetLtvUtilization > 1) {\n throw new RangeError(\"targetLtvUtilization must be in (0, 1]\");\n }\n if (!Number.isFinite(rallyPercentPositive) || rallyPercentPositive <= 0) {\n throw new RangeError(\"rallyPercentPositive must be finite and positive\");\n }\n const after = ltvUtilAfterCollateralPricePctChg(targetLtvUtilization, rallyPercentPositive);\n return targetLtvUtilization - after;\n}\n\n/**\n * If you sit at **target** utilization and collateral **falls** `dropPercentPositive` (e.g. `20` = −20%),\n * utilization rises. This returns how far **above** target it lands — the width of `maxDeviationAboveTarget`\n * that lines up with that drop for carry-style triggers.\n *\n * Equivalent to: `ltvUtilAfterCollateralPricePctChg(target, -dropPercentPositive) − target`.\n */\nexport function ltvUtilDeltaAboveTargForDropPct(\n targetLtvUtilization: number,\n dropPercentPositive: number\n): number {\n if (!(targetLtvUtilization > 0) || targetLtvUtilization > 1) {\n throw new RangeError(\"targetLtvUtilization must be in (0, 1]\");\n }\n if (\n !Number.isFinite(dropPercentPositive) ||\n dropPercentPositive <= 0 ||\n dropPercentPositive >= 100\n ) {\n throw new RangeError(\"dropPercentPositive must be in (0, 100)\");\n }\n const after = ltvUtilAfterCollateralPricePctChg(targetLtvUtilization, -dropPercentPositive);\n return after - targetLtvUtilization;\n}\n","import { Scope } from \"@kamino-finance/scope-sdk\";\nimport { OraclePrices } from \"@kamino-finance/scope-sdk/dist/@codegen/scope/accounts\";\nimport { Address, Rpc, SolanaRpcApi } from \"@solana/kit\";\nimport { currentUnixSeconds, DEFAULT_PUBLIC_KEY } from \"common\";\nimport { KaminoReserveData } from \"../data/reserve/kamino\";\n\ntype OracleMappings = {\n refPrice: number[];\n priceTypes: number[];\n priceInfoAccounts: Address[];\n generic: number[][];\n};\n\nconst ORACLE_TYPE_MOST_RECENT_OF = 28;\nconst ORACLE_TYPE_CAPPED_FLOORED = 33;\nconst MOST_RECENT_OF_UNUSED = 512;\n\n/**\n * Recursively collects a token and all its Scope dependency tokens.\n *\n * Handles three dependency mechanisms:\n * - `refPrice`: ScopeTwap and similar read from a single reference index\n * - `generic` (MostRecentOf): stores up to 4 source token indices as u16 LE\n * - `generic` (CappedFloored): stores sourceEntry, capEntry, floorEntry\n */\nexport function collectTokenDependencies(\n token: number,\n mappings: OracleMappings,\n result: Set<number>,\n depth = 0\n): void {\n if (result.has(token) || depth > 5) return;\n\n const isValidDep = (dep: number) =>\n dep !== undefined &&\n dep !== token &&\n dep < mappings.priceInfoAccounts.length &&\n mappings.priceInfoAccounts[dep] !== DEFAULT_PUBLIC_KEY;\n\n const recurse = (dep: number) => collectTokenDependencies(dep, mappings, result, depth + 1);\n\n if (mappings.priceTypes[token] === ORACLE_TYPE_MOST_RECENT_OF) {\n const raw = mappings.generic[token];\n if (raw?.length >= 8) {\n for (let i = 0; i < 4; i++) {\n const src = raw[i * 2] | (raw[i * 2 + 1] << 8);\n if (src !== MOST_RECENT_OF_UNUSED && isValidDep(src)) {\n recurse(src);\n }\n }\n }\n } else if (mappings.priceTypes[token] === ORACLE_TYPE_CAPPED_FLOORED) {\n const raw = mappings.generic[token];\n if (raw?.length >= 7) {\n const sourceEntry = raw[0] | (raw[1] << 8);\n if (isValidDep(sourceEntry)) recurse(sourceEntry);\n\n // borsh Option<u16>: 1-byte tag (0=None,1=Some) + u16 value\n if (raw[2] === 1) {\n const capEntry = raw[3] | (raw[4] << 8);\n if (isValidDep(capEntry)) recurse(capEntry);\n }\n const floorOffset = raw[2] === 1 ? 5 : 3;\n if (raw[floorOffset] === 1) {\n const floorEntry = raw[floorOffset + 1] | (raw[floorOffset + 2] << 8);\n if (isValidDep(floorEntry)) recurse(floorEntry);\n }\n }\n }\n\n const dep = mappings.refPrice[token];\n if (isValidDep(dep)) {\n recurse(dep);\n }\n\n result.add(token);\n}\n\n/**\n * Checks if a reserve's Scope price chain has any stale entries by comparing\n * each entry's `unixTimestamp` against the reserve's configured max price age.\n * @param reserveData - The reserve to check\n * @param oraclePrices - The fetched Scope OraclePrices account\n * @param bufferSeconds - Lookahead buffer (same semantics as KaminoReserveData.requiresRefresh)\n */\nexport function isScopePriceStale(\n reserveData: KaminoReserveData,\n oraclePrices: OraclePrices,\n bufferSeconds = 10\n): boolean {\n const SCOPE_CHAIN_END = 65535; // U16_MAX — terminates the price chain\n const tokenInfo = reserveData.rawData.state.config.tokenInfo;\n const { priceChain, twapChain } = tokenInfo.scopeConfiguration;\n const isTwapEnabled = tokenInfo.maxTwapDivergenceBps.toNumber() > 0;\n\n const now = currentUnixSeconds();\n\n const isChainStale = (chain: number[], maxAge: number) => {\n for (const index of chain) {\n if (index === SCOPE_CHAIN_END) break;\n const datedPrice = oraclePrices.prices[index];\n if (!datedPrice || now - datedPrice.unixTimestamp.toNumber() > maxAge - bufferSeconds) {\n return true;\n }\n }\n return false;\n };\n\n const spotMaxAge = tokenInfo.maxAgePriceSeconds.toNumber();\n if (isChainStale(priceChain, spotMaxAge)) return true;\n\n if (isTwapEnabled) {\n const twapMaxAge = tokenInfo.maxAgeTwapSeconds.toNumber();\n if (isChainStale(twapChain, twapMaxAge)) return true;\n }\n\n return false;\n}\n\nconst ORACLE_TYPE_PYTH_PULL = 21;\nconst ORACLE_TYPE_PYTH_PULL_EMA = 22;\nconst SCOPE_CHAIN_END = 65535;\n\n/**\n * Returns the external PythPull / PythPullEMA oracle accounts from the Scope\n * dependency tree for the given Kamino reserves. These are the accounts whose\n * data Scope reads during RefreshPriceList — streaming them on a localnet fork\n * keeps Scope prices fresh.\n *\n * Only Pyth accounts are returned. Switchboard and other oracle types are\n * intentionally excluded because their on-chain data format can produce corrupt\n * values when streamed through Surfpool's account mirroring.\n */\nexport async function getScopePythAccounts(\n rpc: Rpc<SolanaRpcApi>,\n reserves: KaminoReserveData[]\n): Promise<Address[]> {\n const scope = new Scope(\"mainnet-beta\", rpc as any);\n const accounts = new Set<string>();\n\n for (const reserve of reserves) {\n const scopeFeed = reserve.getOracleAccounts().scope;\n if (!scopeFeed) continue;\n\n const [configAddr] = await scope.getSingleFeedConfiguration({ prices: scopeFeed });\n const mappings = await scope.getOracleMappings({ config: configAddr });\n\n const { priceChain, twapChain } = reserve.rawData.state.config.tokenInfo.scopeConfiguration;\n const chainTokens = new Set<number>();\n for (const chain of [priceChain, twapChain]) {\n for (const index of chain) {\n if (index === SCOPE_CHAIN_END) break;\n chainTokens.add(index);\n }\n }\n\n const allTokens = new Set<number>();\n for (const token of chainTokens) {\n collectTokenDependencies(token, mappings, allTokens);\n }\n\n for (const token of allTokens) {\n const type = mappings.priceTypes[token];\n if (type === ORACLE_TYPE_PYTH_PULL || type === ORACLE_TYPE_PYTH_PULL_EMA) {\n const account = mappings.priceInfoAccounts[token];\n if (account && account !== DEFAULT_PUBLIC_KEY) {\n accounts.add(account);\n }\n }\n }\n }\n\n return [...accounts] as Address[];\n}\n","import { Address } from \"@solana/kit\";\nimport {\n isNotNullPubkey,\n KaminoMarket,\n KaminoReserve,\n KlendPrices,\n} from \"@kamino-finance/klend-sdk\";\nimport Decimal from \"decimal.js\";\nimport { currentUnixSeconds, fromUiAmount, fromWeb3Pk, toUiAmount } from \"common\";\nimport { ReserveBase } from \"./reserveBase\";\nimport { KaminoIncentiveData, KaminoIncentiveDataArgs } from \"../incentive\";\nimport { PositionBalanceChange } from \"../../types\";\n\n/** Supported oracle types for Kamino price feeds */\nexport type OracleType = \"pythPrice\" | \"switchboardPrice\" | \"switchboardTwap\" | \"scope\";\n\nexport type ReserveOracleAccounts = Record<OracleType, Address | undefined>;\n\n/**\n * Kamino-specific reserve data implementation.\n * Wraps KaminoReserve with normalized accessors and oracle account resolution.\n */\nexport class KaminoReserveData extends ReserveBase {\n public rawData!: KaminoReserve;\n slot!: bigint;\n\n /**\n * Creates a KaminoReserveData instance from raw SDK types.\n * Extracts and normalizes configuration, rates, limits, and incentives.\n */\n static loadData(\n market: KaminoMarket,\n reserve: KaminoReserve,\n reserveFarms: KaminoIncentiveDataArgs[],\n prices: KlendPrices,\n slot: bigint\n ): KaminoReserveData {\n const stats = reserve.stats;\n const state = reserve.state;\n const config = state.config;\n\n const mintDecimals = reserve.getMintDecimals();\n const price = reserve.getOracleMarketPrice().toNumber();\n\n const allElevationGroups = config.elevationGroups\n .map((id) => market.getElevationGroup(id))\n .filter(\n (group) =>\n group !== undefined &&\n group.debtReserve !== reserve.address &&\n group.maxReservesAsCollateral === 1\n );\n\n const data = new KaminoReserveData(\n reserve.address,\n {\n mint: reserve.getLiquidityMint(),\n mintDecimals,\n mintTokenProgram: reserve.getLiquidityTokenProgram(),\n price,\n },\n {\n ltvPct: stats.loanToValue,\n liquidationThresholdPct: stats.liquidationThreshold,\n borrowFeePct: reserve.getBorrowFee().toNumber(),\n flashLoanFeePct: reserve.getFlashLoanFee().toNumber(),\n emodes: allElevationGroups.map((x) => ({\n id: x.id,\n debtReserve: x.debtReserve,\n ltvPct: x.ltvPct,\n liquidationThresholdPct: x.liquidationThresholdPct,\n })),\n },\n {\n totalAmount: reserve.getDepositTvl().toNumber() / price,\n limit: toUiAmount(config.depositLimit, mintDecimals),\n apy: reserve.totalSupplyAPY(slot),\n },\n {\n totalAmount: reserve.getBorrowTvl().toNumber() / price,\n limit: toUiAmount(config.borrowLimit, mintDecimals),\n apy: reserve.totalBorrowAPY(slot),\n },\n {\n utilizationRatePct: reserve.calculateUtilizationRatio(),\n availableLiquidity: toUiAmount(\n BigInt(reserve.getLiquidityAvailableAmount().toFixed(0)),\n mintDecimals\n ),\n },\n reserveFarms\n .map((x) => KaminoIncentiveData.loadData(x, reserve, prices, slot))\n .filter((x) => x.active() || [state.farmCollateral, state.farmDebt].includes(x.address))\n );\n\n data.rawData = reserve;\n data.slot = slot;\n\n return data;\n }\n\n /** Checks if TWAP price validation is enabled for this reserve */\n protected isTwapEnabled() {\n return this.rawData.state.config.tokenInfo.maxTwapDivergenceBps.toNumber() > 0;\n }\n\n /**\n * Determines if the reserve's on-chain price data is stale and needs refreshing.\n */\n requiresRefresh() {\n return true;\n }\n\n /**\n * Returns all configured oracle account addresses for this reserve.\n * Only includes accounts that are actually enabled.\n */\n getOracleAccounts(): ReserveOracleAccounts {\n const tokenInfo = this.rawData.state.config.tokenInfo;\n\n const pythAccount = tokenInfo.pythConfiguration.price;\n const switchboardPrice = tokenInfo.switchboardConfiguration.priceAggregator;\n const switchboardTwap = tokenInfo.switchboardConfiguration.twapAggregator;\n const scope = tokenInfo.scopeConfiguration.priceFeed;\n\n const pythEnabled = isNotNullPubkey(pythAccount);\n const switchboardEnabled = isNotNullPubkey(switchboardPrice);\n const switchboardTwapEnabled =\n switchboardEnabled && this.isTwapEnabled() && isNotNullPubkey(switchboardTwap);\n const scopeEnabled = isNotNullPubkey(scope);\n\n return {\n pythPrice: pythEnabled ? pythAccount : undefined,\n switchboardPrice: switchboardEnabled ? switchboardPrice : undefined,\n switchboardTwap: switchboardTwapEnabled ? switchboardTwap : undefined,\n scope: scopeEnabled ? scope : undefined,\n };\n }\n\n /**\n * Simulates the supply APY after a position balance change.\n * Uses the SDK's calcSimulatedSupplyAPR which accounts for utilization changes.\n */\n simulateNewSupplyAPY(args: PositionBalanceChange, usingDebtReserve?: Address): number {\n const collateralChange = args.collateralChange ?? 0;\n if (!collateralChange) {\n return this.supplyAPY(usingDebtReserve);\n }\n\n const simulatedAPR = this.rawData.calcSimulatedSupplyAPR(\n new Decimal(fromUiAmount(collateralChange, this.mint.mintDecimals).toNumber()),\n collateralChange > 0 ? \"deposit\" : \"withdraw\",\n this.slot,\n 0\n );\n\n return simulatedAPR + this.simulateNewEligbleIncentivesAPY(args, \"supply\", usingDebtReserve);\n }\n\n /**\n * Simulates the borrow APY after a position balance change.\n * Uses the SDK's calcSimulatedBorrowAPR which accounts for utilization changes.\n */\n simulateNewBorrowAPY(args: PositionBalanceChange, usingSupplyReserve?: Address): number {\n const debtChange = args.debtChange ?? 0;\n if (!debtChange) {\n return this.borrowAPY(usingSupplyReserve);\n }\n\n const simulatedAPR = this.rawData.calcSimulatedBorrowAPR(\n new Decimal(fromUiAmount(debtChange, this.mint.mintDecimals).toNumber()),\n debtChange > 0 ? \"borrow\" : \"repay\",\n this.slot,\n 0\n );\n\n return simulatedAPR - this.simulateNewEligbleIncentivesAPY(args, \"borrow\", usingSupplyReserve);\n }\n\n canWithdraw(amount: number): boolean {\n const capCapacity = this.rawData.getDepositWithdrawalCapCapacity();\n const capCurrent = this.rawData.getDepositWithdrawalCapCurrent(this.slot);\n return this.hasCapacity(amount, capCapacity, capCurrent);\n }\n\n canBorrow(amount: number): boolean {\n const capCapacity = this.rawData.getDebtWithdrawalCapCapacity();\n const capCurrent = this.rawData.getDebtWithdrawalCapCurrent(this.slot);\n return amount <= this.borrows.limit && this.hasCapacity(amount, capCapacity, capCurrent);\n }\n\n private hasCapacity(amount: number, capCapacity: Decimal, capCurrent: Decimal) {\n if (!capCapacity.isZero()) {\n const remainingCap = toUiAmount(\n BigInt(capCapacity.minus(capCurrent).toFixed(0)),\n this.mint.mintDecimals\n );\n if (amount > remainingCap) {\n return false;\n }\n }\n return true;\n }\n}\n","import { Address } from \"@solana/kit\";\nimport { PositionBalanceChange } from \"../../types\";\n\n/**\n * Categorizes when an incentive reward applies:\n * - LendingOnly: Only for lending\n * - BorrowingOnly: Only for borroweing\n * - Pair: Requires both collateral and debt in specific reserves\n */\nexport enum IncentiveType {\n LendingOnly = \"Lending\",\n BorrowingOnly = \"Borrowing\",\n Pair = \"Pair\",\n}\n\ninterface IncentiveConfig {\n rewardMint: Address;\n incentiveType: IncentiveType;\n /** If set, this incentive only applies when paired with this reserve */\n requiresPairReserve?: Address;\n}\n\n/**\n * Abstract base class for token reward incentives on lending reserves.\n * Incentives can apply to deposits, borrows, or paired positions.\n */\nexport abstract class TokenIncentiveBase {\n constructor(\n public address: Address,\n public config: IncentiveConfig\n ) {}\n\n /** Returns true if the incentive is currently active and emitting rewards */\n abstract active(): boolean;\n\n /** Returns the current APY from this incentive */\n abstract apy(): number;\n\n /** Simulates the APY after a hypothetical position change after changing total collateral deposits or debt borrows */\n abstract simulateNewAPY(args: PositionBalanceChange): number;\n}\n","import { Address } from \"@solana/kit\";\nimport Decimal from \"decimal.js\";\nimport { BN } from \"@anchor-lang/core\";\nimport { IncentiveType, TokenIncentiveBase } from \"./incentiveBase\";\nimport {\n FarmAndKey,\n FarmState,\n RewardInfo,\n calculateCurrentRewardPerToken,\n} from \"@kamino-finance/farms-sdk\";\nimport { currentUnixSeconds } from \"common\";\nimport { PositionBalanceChange } from \"../../types\";\nimport { calculateRewardAPY } from \"../../utils\";\nimport { KaminoReserve, KlendPrices } from \"@kamino-finance/klend-sdk\";\n\n/** Arguments for constructing a KaminoIncentiveData instance */\nexport interface KaminoIncentiveDataArgs {\n data: FarmAndKey;\n /** Index of the reward within the farm's rewardInfos array */\n rewardIndex: number;\n /** If set, this incentive requires a paired position with this reserve */\n requiresPairReserve?: Address;\n /** True if this is a debt farm (rewards borrowers), false for collateral farm */\n isDebtFarm: boolean;\n}\n\n/**\n * Kamino-specific incentive data for farm rewards.\n * Handles both collateral farms (reward lenders) and debt farms (reward borrowers),\n * as well as paired incentives that require specific collateral/debt combinations.\n */\nexport class KaminoIncentiveData extends TokenIncentiveBase {\n public rawReserve!: KaminoReserve;\n public rawFarm!: FarmState;\n public rewardInfo!: RewardInfo;\n public isDebtFarm!: boolean;\n\n private exchangeRate!: number;\n private rewardMintPrice!: number;\n\n /**\n * Creates a KaminoIncentiveData instance from farm and reserve data.\n * Determines the incentive type and calculates current exchange rates.\n */\n static loadData(\n args: KaminoIncentiveDataArgs,\n reserve: KaminoReserve,\n prices: KlendPrices,\n slot: bigint\n ): KaminoIncentiveData {\n const {\n data: { key, farmState },\n rewardIndex,\n requiresPairReserve,\n isDebtFarm,\n } = args;\n\n const rewardInfo = farmState.rewardInfos[rewardIndex];\n\n const data = new KaminoIncentiveData(key, {\n rewardMint: rewardInfo.token.mint,\n incentiveType: isDebtFarm\n ? IncentiveType.BorrowingOnly\n : requiresPairReserve\n ? IncentiveType.Pair\n : IncentiveType.LendingOnly,\n requiresPairReserve,\n });\n data.rawReserve = reserve;\n data.rawFarm = farmState;\n data.rewardInfo = farmState.rewardInfos[rewardIndex];\n data.isDebtFarm = isDebtFarm;\n\n const collateralExchangeRate = reserve.getEstimatedCollateralExchangeRate(slot, 0).toNumber();\n const debtExchangeRate = reserve.getEstimatedCumulativeBorrowRate(slot, 0).toNumber();\n data.exchangeRate = isDebtFarm ? debtExchangeRate : collateralExchangeRate;\n\n const rewardMint = rewardInfo.token.mint;\n const scope = prices.scope.spot[rewardMint];\n const pyth = prices.pyth.spot[rewardMint];\n const swb = prices.switchboard.spot[rewardMint];\n\n // TODO: need to fetch the price if kamino doesn't provide it\n data.rewardMintPrice = scope\n ? scope.price.toNumber()\n : pyth\n ? pyth.price.toNumber()\n : swb\n ? swb.price.toNumber()\n : 0;\n\n return data;\n }\n\n /**\n * Checks if the incentive is currently active.\n * An incentive is active if rewards are available, the schedule has started,\n * and there is a non-zero emission rate.\n */\n active(): boolean {\n const rewardsAvailable = this.rewardInfo.rewardsAvailable.gtn(0);\n const hasStarted =\n this.rewardInfo.rewardScheduleCurve.points[0].tsStart.toNumber() < currentUnixSeconds();\n const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(\n this.rewardInfo,\n new Decimal(currentUnixSeconds())\n );\n\n return rewardsAvailable && hasStarted && rewardPerTokenPerSecond > 0;\n }\n\n /** Calculates the current APY based on total staked amount and reward emission rate */\n apy(): number {\n const { totalStaked, stakedTokenDecimals } = this.getStakedTokenData();\n return calculateRewardAPY(\n this.rawReserve.getLiquidityMint(),\n this.rewardInfo,\n totalStaked.toString(),\n stakedTokenDecimals,\n this.exchangeRate,\n this.rewardMintPrice,\n Boolean(this.config.requiresPairReserve)\n );\n }\n\n /**\n * Simulates the APY after a hypothetical position change.\n * Useful for calculating expected rewards before executing a transaction.\n */\n simulateNewAPY(args: PositionBalanceChange): number {\n const changeInUnderlying = this.isDebtFarm\n ? (args.debtChange ?? 0)\n : (args.collateralChange ?? 0);\n\n if (changeInUnderlying === 0) {\n return this.apy();\n }\n\n const { totalStaked, stakedTokenDecimals } = this.getStakedTokenData();\n const changeInShares = changeInUnderlying / this.exchangeRate;\n const changeInSharesRaw = new BN(\n Math.round(changeInShares * Math.pow(10, stakedTokenDecimals))\n );\n const newTotalStakedRaw = new BN(totalStaked.toString()).add(changeInSharesRaw);\n\n return calculateRewardAPY(\n this.rawReserve.getLiquidityMint(),\n this.rewardInfo,\n newTotalStakedRaw.toString(),\n stakedTokenDecimals,\n this.exchangeRate,\n this.rewardMintPrice,\n Boolean(this.config.requiresPairReserve)\n );\n }\n\n /**\n * Returns staking metrics for APY calculation.\n * Falls back to reserve decimals if farm token decimals are not set.\n */\n protected getStakedTokenData() {\n return {\n totalStaked: this.rawFarm.totalStakedAmount,\n stakedTokenDecimals:\n this.rawFarm.token.decimals.toNumber() ||\n (this.config.requiresPairReserve ? 6 : this.rawReserve.getMintDecimals()),\n };\n }\n}\n","import type { Address } from \"@solana/kit\";\nimport { PRICE_STALENESS_SECONDS, sum } from \"common\";\nimport { IncentiveType, TokenIncentiveBase } from \"../incentive\";\nimport { PositionBalanceChange } from \"../../types\";\n\ntype IncentiveSide = \"supply\" | \"borrow\";\n\n/** Token mint information for a reserve's underlying asset */\ninterface ReserveMint {\n mint: Address;\n mintDecimals: number;\n mintTokenProgram: Address;\n price?: number;\n emaPrice?: number;\n}\n\n/** Risk and fee parameters for a reserve */\ninterface ReserveConfig {\n ltvPct: number;\n liquidationThresholdPct: number;\n borrowFeePct: number;\n flashLoanFeePct: number;\n /** E-mode configurations for enhanced LTV with specific debt reserves */\n emodes?: EmodeConfig[];\n}\n\n/** Aggregated metrics for deposit/borrow activity */\ninterface ReserveInteractionInfo {\n /** In UI amounts, e.g. 1.234 */\n totalAmount: number;\n /** In UI amounts, e.g. 1.234 */\n limit: number;\n apy: number;\n}\n\ninterface ReserveState {\n utilizationRatePct: number;\n availableLiquidity: number;\n}\n\n/** E-mode (efficiency mode) configuration for enhanced collateral ratios */\ninterface EmodeConfig {\n id?: number;\n debtReserve?: Address;\n ltvPct: number;\n liquidationThresholdPct: number;\n}\n\n/**\n * Abstract base class representing a lending reserve (asset pool).\n * Contains normalized data about deposits, borrows, rates, and incentives.\n */\nexport abstract class ReserveBase {\n private createdAt = Date.now();\n\n constructor(\n public address: Address,\n public mint: ReserveMint,\n public config: ReserveConfig,\n public deposits: ReserveInteractionInfo,\n public borrows: ReserveInteractionInfo,\n private state: ReserveState,\n public incentives?: TokenIncentiveBase[]\n ) {}\n\n private normalizeLtvPct(ltvPct: number): number {\n return ltvPct <= 1 ? ltvPct : ltvPct / 100;\n }\n\n /** Returns the cached price, or undefined if stale */\n get mintPrice(): number | undefined {\n if (this.mint.price === undefined) {\n return undefined;\n }\n const ageMs = Date.now() - this.createdAt;\n if (ageMs > PRICE_STALENESS_SECONDS * 1000) {\n return undefined;\n }\n return this.mint.price;\n }\n\n /** Returns the cached EMA price, or undefined if stale/missing */\n get mintEmaPrice(): number | undefined {\n if (this.mint.emaPrice === undefined) {\n return undefined;\n }\n const ageMs = Date.now() - this.createdAt;\n if (ageMs > PRICE_STALENESS_SECONDS * 1000) {\n return undefined;\n }\n return this.mint.emaPrice;\n }\n\n /** Returns oracle account addresses used for price feeds */\n abstract getOracleAccounts(): Record<string, Address | undefined>;\n\n /**\n * Returns the reserve LTV in decimal form, where `0.5 = 50%`.\n */\n get ltvPct(): number {\n return this.normalizeLtvPct(this.config.ltvPct);\n }\n\n /**\n * Returns e-mode configs with `ltvPct` normalized to decimal form, where\n * `0.5 = 50%`.\n */\n get emodes(): EmodeConfig[] | undefined {\n return this.config.emodes?.map((emode) => ({\n ...emode,\n ltvPct: this.normalizeLtvPct(emode.ltvPct),\n }));\n }\n\n utilizationRatePct(): number {\n return this.state.utilizationRatePct;\n }\n\n /** Returns borrowable liquidity, accounting for both available balance and borrow limits, in UI amount (e.g. 1.234) */\n liquidityAvailable(): number {\n return Math.min(this.state.availableLiquidity, this.borrows.limit - this.borrows.totalAmount);\n }\n\n /**\n * Returns the total supply APY including base rate and eligible supply-side\n * incentives (types `LendingOnly` and `Pair`). Borrow-side incentives are\n * excluded here — they reward borrowers, not lenders.\n * @param usingDebtReserve - When specified, includes paired incentives requiring this debt reserve\n */\n supplyAPY(usingDebtReserve?: Address) {\n return this.deposits.apy + this.sumEligibleIncentivesAPY(\"supply\", usingDebtReserve);\n }\n\n /** Simulates supply APY after a position change */\n abstract simulateNewSupplyAPY(args: PositionBalanceChange, usingDebtReserve?: Address): number;\n\n /**\n * Returns the effective borrow APY (base rate minus eligible borrow-side\n * incentive rebates, i.e. `BorrowingOnly`). Lender-side incentives are\n * excluded — they are paid to lenders and do not offset borrower cost.\n * @param usingSupplyReserve - When specified, includes paired incentives requiring this collateral\n */\n borrowAPY(usingSupplyReserve?: Address) {\n return this.borrows.apy - this.sumEligibleIncentivesAPY(\"borrow\", usingSupplyReserve);\n }\n\n /** Simulates borrow APY after a position change */\n abstract simulateNewBorrowAPY(args: PositionBalanceChange, usingSupplyReserve?: Address): number;\n\n /** Sums APY from incentives eligible for the given side and paired reserve */\n protected sumEligibleIncentivesAPY(side: IncentiveSide, usingPairReserve?: Address) {\n return sum(this.getEligibleIncentives(side, usingPairReserve).map((x) => x.apy()));\n }\n\n /** Sums the new simulated APY from incentives eligible for the given side and paired reserve */\n protected simulateNewEligbleIncentivesAPY(\n args: PositionBalanceChange,\n side: IncentiveSide,\n usingPairReserve?: Address\n ) {\n return sum(\n this.getEligibleIncentives(side, usingPairReserve).map((x) => x.simulateNewAPY(args))\n );\n }\n\n /**\n * Filters incentives eligible for the given side (supply vs borrow) and\n * paired reserve.\n *\n * Side filter:\n * - `supply`: `LendingOnly` and `Pair` (collateral-farm incentives,\n * optionally gated on a specific debt reserve).\n * - `borrow`: `BorrowingOnly` (debt-farm incentives, optionally gated on a\n * specific collateral reserve via `requiresPairReserve`).\n *\n * Pair filter: incentives with `requiresPairReserve` only apply when that\n * reserve matches the caller's pair.\n */\n protected getEligibleIncentives(\n side: IncentiveSide,\n usingPairReserve?: Address\n ): TokenIncentiveBase[] {\n return (this.incentives ?? []).filter((x) => {\n const sideMatches =\n side === \"borrow\"\n ? x.config.incentiveType === IncentiveType.BorrowingOnly\n : x.config.incentiveType !== IncentiveType.BorrowingOnly;\n if (!sideMatches) return false;\n return !x.config.requiresPairReserve || x.config.requiresPairReserve === usingPairReserve;\n });\n }\n\n canDeposit(amount: number): boolean {\n return amount <= this.deposits.limit;\n }\n\n abstract canWithdraw(amount: number): boolean;\n\n canBorrow(amount: number) {\n return amount <= this.borrows.limit;\n }\n}\n","import { BN } from \"@anchor-lang/core\";\nimport { KaminoObligation } from \"@kamino-finance/klend-sdk\";\nimport { PositionInfo, UserPositionBase } from \"./userPositionBase\";\n\n/**\n * Kamino-specific user position data.\n * Extracts deposit/borrow positions and health metrics from a KaminoObligation.\n */\nexport class KaminoUserPositionData extends UserPositionBase {\n public rawData!: KaminoObligation;\n\n /** Creates a KaminoUserPositionData from a raw KaminoObligation */\n static loadData(obligation: KaminoObligation): KaminoUserPositionData {\n const deposits: PositionInfo[] = [];\n obligation.deposits.forEach((deposit, mint) => {\n deposits.push({\n reserve: deposit.reserveAddress,\n mint,\n amount: new BN(deposit.amount.toFixed(0)),\n valueUsd: deposit.marketValueRefreshed.toNumber(),\n });\n });\n\n const borrows: PositionInfo[] = [];\n obligation.borrows.forEach((borrow, mint) => {\n borrows.push({\n reserve: borrow.reserveAddress,\n mint,\n amount: new BN(borrow.amount.toFixed(0)),\n valueUsd: borrow.marketValueRefreshed.toNumber(),\n });\n });\n\n const borrowedValueUsd = obligation.refreshedStats.userTotalBorrow.toNumber();\n const borrowLimitUsd = obligation.refreshedStats.borrowLimit.toNumber();\n const utilizationRate = borrowLimitUsd > 0 ? borrowedValueUsd / borrowLimitUsd : 0;\n\n const data = new KaminoUserPositionData(\n obligation.obligationAddress,\n utilizationRate,\n deposits,\n borrows,\n undefined,\n undefined,\n borrowLimitUsd\n );\n\n data.rawData = obligation;\n\n return data;\n }\n\n /**\n * Determines if the obligation needs a refresh_obligation instruction.\n */\n requiresRefresh(): boolean {\n return true;\n }\n}\n","import type { Address } from \"@solana/kit\";\nimport { BN } from \"@anchor-lang/core\";\nimport { fromUiAmount, toUiAmount } from \"common\";\n\n/** Represents a single asset position (deposit or borrow) within an obligation */\nexport interface PositionInfo {\n reserve: Address;\n mint: Address;\n amount: BN;\n valueUsd: number;\n}\n\n/**\n * Base class representing a user's lending position.\n * Contains aggregated data about deposits, borrows, and health metrics.\n */\nexport class UserPositionBase {\n constructor(\n public address: Address,\n /** Current utilization as a ratio of borrowed value to borrow limit (0-1) */\n public utilizationRate: number,\n public deposits: PositionInfo[],\n public borrows: PositionInfo[],\n /** Loan-to-value ratio (if applicable based on elevation group) */\n public ltv?: number,\n /** Liquidation threshold percentage (if applicable) */\n public liquidationThreshold?: number,\n /**\n * Obligation-level max borrow capacity in USD (`borrowedUsd / utilizationRate`).\n * Each platform loader must set this from that protocol's position health model.\n */\n public borrowLimitUsd?: number\n ) {}\n\n /** Aggregate borrowed USD for headroom; prefers per-borrow breakdown when present. */\n private userPositionBorrowedValueUsd(): number {\n const fromBorrows = this.borrows.reduce((sum, borrow) => sum + borrow.valueUsd, 0);\n if (fromBorrows > 0) {\n return fromBorrows;\n }\n if (this.borrowLimitUsd !== undefined && this.utilizationRate > 0) {\n return this.borrowLimitUsd * this.utilizationRate;\n }\n return 0;\n }\n\n /**\n * Max additional debt UI amount before the platform rejects the borrow.\n * Uses obligation `borrowLimitUsd − borrowedUsd`, floored to base units with a\n * one-unit buffer so simulation-time refresh cannot overshoot. Returns `undefined`\n * when `borrowLimitUsd` was not set by the platform loader.\n */\n getMaxAdditionalBorrowUiAmount(debtPriceUsd: number, debtDecimals: number): number | undefined {\n if (this.borrowLimitUsd === undefined) {\n return undefined;\n }\n\n const borrowedValueUsd = this.userPositionBorrowedValueUsd();\n const headroomUsd = Math.max(0, this.borrowLimitUsd - borrowedValueUsd);\n if (headroomUsd <= 0 || !(debtPriceUsd > 0)) {\n return 0;\n }\n\n const headroomUi = headroomUsd / debtPriceUsd;\n const maxBaseUnits = fromUiAmount(headroomUi, debtDecimals);\n const safeBaseUnits = BN.max(maxBaseUnits.subn(1), new BN(0));\n return toUiAmount(safeBaseUnits, debtDecimals);\n }\n}\n","import { BN } from \"@anchor-lang/core\";\nimport { address, Address, getAddressEncoder, Instruction, Rpc, SolanaRpcApi } from \"@solana/kit\";\nimport { Scope } from \"@kamino-finance/scope-sdk\";\nimport {\n DEFAULT_PUBLIC_KEY,\n lendingMarketAuthPda,\n PROGRAM_ID,\n userMetadataPda,\n VanillaObligation,\n} from \"@kamino-finance/klend-sdk\";\nimport {\n accountExists,\n CpiData,\n CpiTypes,\n dedupeOrderedAddresses,\n getAtaAddress,\n IX_SYSVAR_META,\n LOCALNET_URL,\n mints,\n numToU64Bytes,\n RENT_SYSVAR_META,\n SYSTEM_PROGRAM_META,\n toCustomAccountMeta,\n U64_MAX_BN,\n} from \"common\";\nimport {\n LendingOperationParams,\n LpInstructionsBase,\n RepayOperationParams,\n SplitLpOperationCpiData,\n} from \"./lpInstructionsBase\";\nimport { RefreshPrerequisiteTarget } from \"./types\";\nimport { TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { getTreasuryVaultPDA } from \"@kamino-finance/farms-sdk\";\nimport { KAMINO_FARMS_PROGRAM_ID } from \"../../constants\";\nimport { KaminoData } from \"../platform\";\nimport { collectTokenDependencies, liquidityToCollateral } from \"../../utils\";\nimport { KaminoAccounts } from \"../accounts\";\n\n/**\n * Instruction builder for Kamino Lend protocol.\n * Provides methods to build CPI account metas for lending operations.\n */\nexport class KaminoInstructions extends LpInstructionsBase<KaminoData> {\n declare accounts: KaminoAccounts;\n programId = PROGRAM_ID;\n lookupTable = address(\"bzdjSeDDPEdsGpK73oevQ87x4Sm6QRsnzupPLQEaFFN\");\n\n constructor(rpc: Rpc<SolanaRpcApi>, rpcUrl: string, data: KaminoData, accounts: KaminoAccounts) {\n super(rpc, rpcUrl, data, accounts);\n }\n\n clearTransactionCache(txId?: string) {\n super.clearTransactionCache(txId);\n }\n\n // ================ CPI Data ================\n\n private getUserAccountCacheInvalidations(userAccount: Address) {\n return [\n this.getCacheInvalidation({\n category: this.data.userAccountCatKey,\n id: userAccount,\n }),\n ];\n }\n\n private async getInitUserMetadataCpiData(\n user: Address,\n payer: Address,\n userLookupTable?: Address\n ): Promise<CpiData | undefined> {\n const [userMetadataAddress] = await userMetadataPda(user, this.programId);\n if (await accountExists(this.rpc, userMetadataAddress)) return;\n\n return this.getCpiData(\n CpiTypes.K_INIT_USER_METADATA,\n [\n toCustomAccountMeta(user, false, undefined, true),\n toCustomAccountMeta(payer, true, undefined, true),\n toCustomAccountMeta(userMetadataAddress, true),\n this.emptyAccountMeta(),\n RENT_SYSVAR_META,\n SYSTEM_PROGRAM_META,\n ],\n new Uint8Array(getAddressEncoder().encode(userLookupTable ?? DEFAULT_PUBLIC_KEY))\n );\n }\n\n override async getInitLendingPositionCpiData(params: {\n pool: Address;\n user: Address;\n payer: Address;\n userAccountId: number;\n collateralReserve: Address;\n debtReserve: Address;\n }): Promise<SplitLpOperationCpiData> {\n const userInit = await this.getInitUserAccountCpiData(\n params.pool,\n params.user,\n params.payer,\n params.userAccountId\n );\n const obligation = await this.accounts.getUserAccountAddress(\n params.pool,\n params.user,\n params.userAccountId\n );\n\n const farmCpis: CpiData[] = [];\n const farmTargets: Array<[Address, \"collateral\" | \"debt\"]> = [\n [params.collateralReserve, \"collateral\"],\n [params.debtReserve, \"debt\"],\n ];\n for (const [reserve, mode] of farmTargets) {\n const reserveData = await this.data.fetchReserve(params.pool, reserve);\n const reserveFarm =\n mode === \"collateral\"\n ? reserveData.rawData.state.farmCollateral\n : reserveData.rawData.state.farmDebt;\n if (!reserveFarm || reserveFarm === DEFAULT_PUBLIC_KEY) continue;\n\n const farmAccounts = await this.accounts.getFarmAccounts(\n params.pool,\n reserve,\n obligation,\n mode\n );\n if (await accountExists(this.rpc, farmAccounts.userFarm.address)) continue;\n\n farmCpis.push(\n await this.getInitObligationFarmsForReserveCpiData(\n params.user,\n params.payer,\n obligation,\n params.pool,\n reserve,\n mode\n )\n );\n }\n\n return this.createSplitOperationCpiData(userInit.prerequisiteCpis, [\n ...userInit.cpis,\n ...farmCpis,\n ]);\n }\n\n async getInitUserAccountCpiData(\n pool: Address,\n user: Address,\n payer: Address,\n id: number,\n userLookupTable?: Address\n ): Promise<SplitLpOperationCpiData> {\n const market = await this.data.fetchMarket(pool);\n const obligationPda = await this.accounts.getUserAccountAddress(pool, user, id);\n const userMetadataAddress = await this.accounts.getUserMetadataAddress(user);\n const tag = VanillaObligation.tag;\n\n const initMetadataCpi = await this.getInitUserMetadataCpiData(user, payer, userLookupTable);\n const obligationAlreadyInit = await accountExists(this.rpc, obligationPda);\n return this.createSplitOperationCpiData(\n [],\n [\n ...(initMetadataCpi ? [initMetadataCpi] : []),\n ...(obligationAlreadyInit\n ? []\n : [\n this.getCpiData(\n CpiTypes.K_INIT_OBLIGATION,\n [\n toCustomAccountMeta(user),\n toCustomAccountMeta(payer, true),\n toCustomAccountMeta(obligationPda, true),\n toCustomAccountMeta(market.address),\n toCustomAccountMeta(DEFAULT_PUBLIC_KEY),\n toCustomAccountMeta(DEFAULT_PUBLIC_KEY),\n toCustomAccountMeta(userMetadataAddress),\n RENT_SYSVAR_META,\n SYSTEM_PROGRAM_META,\n ],\n new Uint8Array([tag, id])\n ),\n ]),\n ]\n );\n }\n\n private async getInitObligationFarmsForReserveCpiData(\n user: Address,\n payer: Address,\n obligation: Address,\n pool: Address,\n reserve: Address,\n farmMode: \"collateral\" | \"debt\"\n ): Promise<CpiData> {\n const farmAccounts = await this.accounts.getFarmAccounts(pool, reserve, obligation, farmMode);\n return this.getCpiData(\n CpiTypes.K_INIT_USER_FARM,\n [\n toCustomAccountMeta(payer, true),\n toCustomAccountMeta(user),\n toCustomAccountMeta(obligation, true),\n toCustomAccountMeta((await lendingMarketAuthPda(pool))[0]),\n toCustomAccountMeta(reserve, true),\n farmAccounts.farm,\n farmAccounts.userFarm,\n toCustomAccountMeta(pool),\n toCustomAccountMeta(KAMINO_FARMS_PROGRAM_ID),\n RENT_SYSVAR_META,\n SYSTEM_PROGRAM_META,\n ],\n new Uint8Array([farmMode === \"collateral\" ? 0 : 1])\n );\n }\n\n /**\n * Returns CPI accounts for refreshing a reserve's state.\n * Includes the market, reserve, and all configured oracle accounts.\n */\n private async getRefreshReserveCpiData(pool: Address, reserve: Address): Promise<CpiData> {\n const reserveData = await this.data.fetchReserve(pool, reserve);\n const oracleAccounts = reserveData.getOracleAccounts();\n return this.getCpiData(\n CpiTypes.K_REFRESH_RESERVE,\n [\n toCustomAccountMeta(reserve, true),\n toCustomAccountMeta(pool),\n ...Object.values(oracleAccounts).map((x) =>\n x === undefined ? this.emptyAccountMeta() : toCustomAccountMeta(x)\n ),\n ],\n new Uint8Array()\n );\n }\n\n private async getRefreshObligationCpiData(\n txId: string,\n pool: Address,\n obligation: Address\n ): Promise<CpiData> {\n const obligationData = await this.data.maybeFetchUserPositionInPool(pool, obligation);\n\n const cached = this.getTxUserAccountReserves(txId, obligation);\n // Drop debt reserves the caller has flagged as fully repaid earlier in\n // the same tx (via `markObligationDebtCleared`). The on-chain obligation\n // will no longer list them by the time this RefreshObligation runs;\n // including them here would trip Kamino's account-count check\n // (`expected_remaining_accounts != actual_remaining_accounts`,\n // InvalidAccountInput / klend 6006).\n const cleared = this.getTxObligationClearedDebt(txId, obligation);\n const collateralReserves = [\n ...new Set([...(obligationData?.deposits.map((x) => x.reserve) ?? []), ...cached.collateral]),\n ];\n // Drop any debt reserves a prior CPI in this tx already cleared via the\n // repay-all sentinel — at execution time the obligation no longer carries\n // that borrow, and klend rejects the mismatched accounts count\n // (`InvalidAccountInput`, error 6006).\n const debtReserves = [\n ...new Set([...(obligationData?.borrows.map((x) => x.reserve) ?? []), ...cached.debt]),\n ].filter((r) => !cleared.has(r));\n\n return this.getCpiData(\n CpiTypes.K_REFRESH_OBLIGATION,\n [\n toCustomAccountMeta(pool),\n toCustomAccountMeta(obligation, true),\n ...collateralReserves.map((x) => toCustomAccountMeta(x)),\n ...debtReserves.map((x) => toCustomAccountMeta(x)),\n ],\n new Uint8Array()\n );\n }\n\n private getRefreshObligationCpiDataFromReserves({\n pool,\n userAccount,\n collateralReserves,\n debtReserves,\n }: RefreshPrerequisiteTarget): CpiData {\n return this.getCpiData(\n CpiTypes.K_REFRESH_OBLIGATION,\n [\n toCustomAccountMeta(pool),\n toCustomAccountMeta(userAccount, true),\n ...dedupeOrderedAddresses(collateralReserves).map((x) => toCustomAccountMeta(x)),\n ...dedupeOrderedAddresses(debtReserves).map((x) => toCustomAccountMeta(x)),\n ],\n new Uint8Array()\n );\n }\n\n override async getPrerequisiteCpisForRefresh(\n targets: RefreshPrerequisiteTarget[]\n ): Promise<CpiData[]> {\n const reserveRefreshes: Array<{ pool: Address; reserve: Address }> = [];\n const seenReserveRefreshes = new Set<string>();\n const obligationRefreshes = new Map<string, RefreshPrerequisiteTarget>();\n\n for (const target of targets) {\n for (const reserve of dedupeOrderedAddresses([\n ...target.collateralReserves,\n ...target.debtReserves,\n ])) {\n const reserveRefreshKey = `${target.pool}:${reserve}`;\n if (seenReserveRefreshes.has(reserveRefreshKey)) {\n continue;\n }\n seenReserveRefreshes.add(reserveRefreshKey);\n reserveRefreshes.push({ pool: target.pool, reserve });\n }\n\n if (target.userAccount === DEFAULT_PUBLIC_KEY) {\n continue;\n }\n\n const obligationKey = `${target.pool}:${target.userAccount}`;\n if (obligationRefreshes.has(obligationKey)) {\n continue;\n }\n obligationRefreshes.set(obligationKey, {\n pool: target.pool,\n userAccount: target.userAccount,\n collateralReserves: dedupeOrderedAddresses(target.collateralReserves),\n debtReserves: dedupeOrderedAddresses(target.debtReserves),\n });\n }\n\n const prerequisiteCpis: CpiData[] = [];\n for (const { pool, reserve } of reserveRefreshes) {\n prerequisiteCpis.push(await this.getRefreshReserveCpiData(pool, reserve));\n }\n\n for (const obligationRefresh of obligationRefreshes.values()) {\n let obligationData = null;\n try {\n obligationData = await this.data.maybeFetchUserPositionInPool(\n obligationRefresh.pool,\n obligationRefresh.userAccount\n );\n } catch {\n obligationData = null;\n }\n\n if (!obligationData) {\n continue;\n }\n\n prerequisiteCpis.push(\n this.getRefreshObligationCpiDataFromReserves({\n pool: obligationRefresh.pool,\n userAccount: obligationRefresh.userAccount,\n collateralReserves: obligationData.deposits.map((deposit) => deposit.reserve),\n debtReserves: obligationData.borrows.map((borrow) => borrow.reserve),\n })\n );\n }\n\n return prerequisiteCpis;\n }\n\n private async getRefreshUserFarmCpiData(\n signer: Address,\n pool: Address,\n reserve: Address,\n obligation: Address,\n userFarm: Address,\n farm: Address,\n mode: \"collateral\" | \"debt\"\n ): Promise<CpiData> {\n const details = await this.accounts.reserveInteractionDetails(\n signer,\n pool,\n reserve,\n obligation\n );\n return this.getCpiData(\n CpiTypes.K_REFRESH_USER_FARM,\n [\n details.signer,\n details.obligation!,\n details.lendingMarketAuthority,\n details.reserve,\n toCustomAccountMeta(farm, true),\n toCustomAccountMeta(userFarm, true),\n details.lendingMarket,\n details.farmsProgram,\n RENT_SYSVAR_META,\n SYSTEM_PROGRAM_META,\n ],\n new Uint8Array([mode === \"collateral\" ? 0 : 1])\n );\n }\n\n /**\n * Checks if refresh CPIs are needed for the given reserve and obligation.\n * Also registers all involved reserves in the txReserves cache for getPreInstructions.\n *\n * The instruction `reserve` (collateral vs debt) is also listed on the obligation;\n * `dedupeOrderedAddresses` ensures one RefreshReserve CPI per reserve pubkey.\n */\n private async getRefreshCpisIfNeeded(\n txId: string,\n pool: Address,\n reserve: Address,\n obligation: Address\n ): Promise<CpiData[]> {\n const cpis: CpiData[] = [];\n const cached = this.getTxUserAccountReserves(txId, obligation);\n\n const refreshReserve = async (reserveAddr: Address) => {\n cpis.push(await this.getRefreshReserveCpiData(pool, reserveAddr));\n this.registerTxReserve(txId, pool, reserveAddr);\n };\n\n const obligationData = await this.data.maybeFetchUserPositionInPool(pool, obligation);\n\n if (obligationData) {\n const needsFullObligationRefresh =\n obligationData.requiresRefresh() || cached.collateral.length > 0 || cached.debt.length > 0;\n\n if (needsFullObligationRefresh) {\n const additional = [\n ...obligationData.deposits.map((d) => d.reserve),\n ...obligationData.borrows.map((b) => b.reserve),\n ...cached.collateral,\n ...cached.debt,\n ];\n for (const addr of dedupeOrderedAddresses([reserve, ...additional])) {\n await refreshReserve(addr);\n }\n cpis.push(await this.getRefreshObligationCpiData(txId, pool, obligation));\n } else {\n await refreshReserve(reserve);\n }\n } else {\n const additional = [...new Set([...cached.collateral, ...cached.debt])];\n for (const addr of dedupeOrderedAddresses([reserve, ...additional])) {\n await refreshReserve(addr);\n }\n cpis.push(await this.getRefreshObligationCpiData(txId, pool, obligation));\n }\n\n return cpis;\n }\n\n async getPreInstructions(txId: string): Promise<Instruction[]> {\n const reserveEntries = this.txReserves.get(txId);\n if (!reserveEntries) return [];\n\n const SCOPE_CHAIN_END = 65535;\n\n // Collect scope feed -> token indices, then merge feeds that share the\n // same Scope Configuration into a single RefreshPriceList instruction.\n // Scope's on-chain handler rejects a RefreshPriceList that is preceded by\n // non-Scope instructions, so emitting multiple ixs only works when they\n // are consecutive with nothing in between — grouping by config avoids the\n // problem entirely.\n const scopeFeeds = new Map<string, Set<number>>();\n\n if (reserveEntries) {\n for (const [reserve, { pool }] of reserveEntries) {\n const reserveData = await this.data.fetchReserve(pool, reserve as Address);\n if (!reserveData.requiresRefresh()) continue;\n\n const scopeFeed = reserveData.getOracleAccounts().scope;\n if (!scopeFeed) continue;\n\n if (!scopeFeeds.has(scopeFeed)) {\n scopeFeeds.set(scopeFeed, new Set());\n }\n const tokens = scopeFeeds.get(scopeFeed)!;\n\n const { priceChain, twapChain } =\n reserveData.rawData.state.config.tokenInfo.scopeConfiguration;\n for (const chain of [priceChain, twapChain]) {\n for (const index of chain) {\n if (index === SCOPE_CHAIN_END) break;\n tokens.add(index);\n }\n }\n }\n }\n\n // Resolve each feed's config, then merge token indices by config address.\n // Scope's on-chain handler rejects a RefreshPriceList that is preceded by\n // a RefreshPriceList from a different Configuration account, so we can only\n // emit one instruction per transaction. On deployed environments crankers\n // keep prices fresh, so skipping additional configs is safe.\n const configTokens = new Map<string, Set<number>>();\n for (const [feed, chainTokens] of scopeFeeds) {\n const configAddr = await this.data.fetchScopeConfigAddress(feed as Address);\n if (!configTokens.has(configAddr)) {\n configTokens.set(configAddr, new Set());\n }\n const merged = configTokens.get(configAddr)!;\n for (const t of chainTokens) merged.add(t);\n }\n\n const scope = new Scope(\"mainnet-beta\", this.rpc);\n const isLocalnet = this.rpcUrl === LOCALNET_URL;\n\n // Take only the first config to avoid the cross-config Scope rejection.\n const [firstEntry] = configTokens;\n if (!firstEntry) return [];\n const [configAddr, chainTokens] = firstEntry;\n\n let tokens: number[];\n if (isLocalnet) {\n // On localnet there are no crankers keeping Scope prices fresh, so we\n // must resolve the full dependency graph (CappedFloored sources, etc.)\n // and refresh in topological order.\n const mappings = await scope.getOracleMappings({ config: address(configAddr) });\n const allTokens = new Set<number>();\n for (const token of chainTokens) {\n collectTokenDependencies(token, mappings, allTokens);\n }\n tokens = [...allTokens];\n } else {\n tokens = [...chainTokens];\n }\n\n const ix = await scope.refreshPriceListIx({ config: address(configAddr) }, tokens);\n return ix ? [ix] : [];\n }\n\n async getClaimIncentiveCpiData(\n user: Address,\n payer: Address,\n pool: Address,\n reserve: Address,\n obligation: Address,\n farm: Address,\n userFarm: Address,\n mint: Address\n ): Promise<CpiData[]> {\n const tokenProgram = mints.get(mint)?.tokenProgram ?? TOKEN_PROGRAM_ADDRESS;\n const reserveData = await this.data.fetchReserve(pool, reserve);\n\n const [farmState] = await this.data.fetchFarms([farm]);\n\n const rewardIndex = farmState.rewardInfos.findIndex((r) => r.token.mint === mint);\n if (rewardIndex === -1) {\n throw new Error(`Reward mint ${mint} not found on farm ${farm}`);\n }\n\n const rewardInfo = farmState.rewardInfos[rewardIndex];\n const treasuryVault = await getTreasuryVaultPDA(\n KAMINO_FARMS_PROGRAM_ID,\n farmState.globalConfig,\n mint\n );\n const scopePrices =\n farmState.scopePrices === DEFAULT_PUBLIC_KEY\n ? KAMINO_FARMS_PROGRAM_ID\n : farmState.scopePrices;\n\n const mode =\n reserveData.rawData.state.farmCollateral === farm\n ? \"collateral\"\n : reserveData.rawData.state.farmDebt === farm\n ? \"debt\"\n : undefined;\n const refreshIx = mode\n ? await this.getRefreshUserFarmCpiData(user, pool, reserve, obligation, userFarm, farm, mode)\n : undefined;\n\n // Kfarms HarvestReward requires `owner` (account[0]) to equal\n // `UserState.owner`, which for both klend obligation farms and direct/extra\n // farms is the lyc-token PDA — `user` here. The CPI dispatcher signs for it\n // via `invoke_signed` with the token PDA seeds. Passing the manager fails\n // with HarvestingNotPermissionlessPayerMismatch (0x17b2).\n return [\n ...(refreshIx ? [refreshIx] : []),\n this.getCpiData(\n CpiTypes.K_HARVEST_REWARD,\n [\n toCustomAccountMeta(user, true),\n toCustomAccountMeta(userFarm, true),\n toCustomAccountMeta(farm, true),\n toCustomAccountMeta(farmState.globalConfig),\n toCustomAccountMeta(mint),\n toCustomAccountMeta(await getAtaAddress(mint, user, tokenProgram), true, {\n owner: user,\n mint,\n tokenProgram,\n }),\n toCustomAccountMeta(rewardInfo.rewardsVault, true),\n toCustomAccountMeta(treasuryVault, true),\n toCustomAccountMeta(farmState.farmVaultsAuthority),\n toCustomAccountMeta(scopePrices),\n toCustomAccountMeta(tokenProgram),\n ],\n numToU64Bytes(rewardIndex),\n KAMINO_FARMS_PROGRAM_ID\n ),\n ];\n }\n\n async getRequestElevationGroupCpiData(\n elevationGroup: number,\n user: Address,\n obligation: Address,\n pool: Address,\n txId: string\n ): Promise<CpiData> {\n // Kamino's request_elevation_group handler validates the trailing\n // remaining accounts against the obligation's *current* deposit + borrow\n // reserves — the same `expected_remaining_accounts != actual_remaining_accounts`\n // count check that RefreshObligation enforces (see\n // `getRefreshObligationCpiData`); a mismatch throws InvalidAccountInput\n // (klend 6006). Passing only the three fixed accounts (as we used to)\n // works for an empty obligation but fails the moment it holds a deposit\n // — e.g. the flash-rebalance destination, which has the just-moved\n // collateral deposited before this elevation request runs.\n //\n // Mirror the refresh path: append the obligation's collateral then debt\n // reserves, combining on-chain state with reserves registered earlier in\n // this same tx (the destination deposit isn't reflected on-chain yet at\n // build time). Kamino marks these WRITABLE.\n const obligationData = await this.data.maybeFetchUserPositionInPool(pool, obligation);\n const cached = this.getTxUserAccountReserves(txId, obligation);\n const cleared = this.getTxObligationClearedDebt(txId, obligation);\n const collateralReserves = [\n ...new Set([...(obligationData?.deposits.map((x) => x.reserve) ?? []), ...cached.collateral]),\n ];\n const debtReserves = [\n ...new Set([...(obligationData?.borrows.map((x) => x.reserve) ?? []), ...cached.debt]),\n ].filter((r) => !cleared.has(r));\n\n return this.getCpiData(\n CpiTypes.K_REQUEST_ELEVATION_GROUP,\n [\n toCustomAccountMeta(user),\n toCustomAccountMeta(obligation, true),\n toCustomAccountMeta(pool),\n ...collateralReserves.map((x) => toCustomAccountMeta(x, true)),\n ...debtReserves.map((x) => toCustomAccountMeta(x, true)),\n ],\n new Uint8Array([elevationGroup])\n );\n }\n\n async getInitAndDepositCpiData(\n params: LendingOperationParams,\n userAccountId: number\n ): Promise<SplitLpOperationCpiData> {\n const initCpis: CpiData[] = [];\n\n if (!(await accountExists(this.rpc, params.userAccount))) {\n initCpis.push(\n ...(\n await this.getInitUserAccountCpiData(\n params.pool,\n params.user,\n params.payer,\n userAccountId\n )\n ).allCpis,\n await this.getRefreshObligationCpiData(params.txId, params.pool, params.userAccount)\n );\n }\n\n const reserveData = await this.data.fetchReserve(params.pool, params.reserve);\n const farmCollateral = reserveData.rawData.state.farmCollateral;\n if (farmCollateral && farmCollateral !== DEFAULT_PUBLIC_KEY) {\n const farmAccounts = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"collateral\"\n );\n if (!(await accountExists(this.rpc, farmAccounts.userFarm.address))) {\n initCpis.push(\n await this.getInitObligationFarmsForReserveCpiData(\n params.user,\n params.payer,\n params.userAccount,\n params.pool,\n params.reserve,\n \"collateral\"\n )\n );\n }\n }\n\n const depositCpis = await this.getDepositCpiData(params);\n return this.createSplitOperationCpiData(\n [...initCpis, ...depositCpis.prerequisiteCpis],\n depositCpis.cpis\n );\n }\n\n async getInitBorrowPositionCpiData(\n params: LendingOperationParams,\n collReserve: Address\n ): Promise<SplitLpOperationCpiData> {\n const initCpis: CpiData[] = [];\n\n const reserveData = await this.data.fetchReserve(params.pool, params.reserve);\n const farmDebt = reserveData.rawData.state.farmDebt;\n if (farmDebt && farmDebt !== DEFAULT_PUBLIC_KEY) {\n const farmAccounts = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"debt\"\n );\n if (!(await accountExists(this.rpc, farmAccounts.userFarm.address))) {\n initCpis.push(\n await this.getInitObligationFarmsForReserveCpiData(\n params.user,\n params.payer,\n params.userAccount,\n params.pool,\n params.reserve,\n \"debt\"\n )\n );\n }\n }\n\n const debtReserveData = await this.data.fetchReserve(params.pool, params.reserve);\n const market = await this.data.fetchMarket(params.pool);\n const requestedBorrowBaseUnits =\n params.baseUnitAmount && params.baseUnitAmount !== \"all\"\n ? params.baseUnitAmount\n : typeof params.uiAmount === \"number\"\n ? new BN(Math.floor(params.uiAmount * Math.pow(10, debtReserveData.mint.mintDecimals)))\n : undefined;\n\n const collReserveData = await this.data.fetchReserve(params.pool, collReserve);\n const availableElevationGroups = collReserveData.config.emodes?.filter(\n (x) => x.debtReserve === params.reserve\n );\n if (availableElevationGroups?.length) {\n // Greedily prefer the highest-LTV e-mode group, but only enter one that\n // actually has borrow capacity for this debt+collateral pair right now.\n // Kamino rejects entry into a group whose debt cap is exhausted or\n // disabled (ElevationGroupBorrowLimitExceeded, klend 6101); the cap lives\n // on the collateral reserve, indexed per group. `getLiquidityAvailable…`\n // folds the emode cap together with the reserve's global / utilization /\n // daily caps and returns 0 for a maxed/zeroed group. When none qualify we\n // fall back to no e-mode (group 0) — LYC sizing uses the base (non-emode)\n // LTV, so the borrow always fits there.\n const sortedGroups = [...availableElevationGroups]\n .filter((g) => g.id !== undefined)\n .sort((a, b) => b.ltvPct - a.ltvPct);\n\n let selectedGroup: number | undefined;\n for (const group of sortedGroups) {\n const [available] = debtReserveData.rawData.getLiquidityAvailableForDebtReserveGivenCaps(\n market,\n [group.id!],\n [collReserve]\n );\n const hasCapacity = requestedBorrowBaseUnits\n ? available.gte(requestedBorrowBaseUnits.toString())\n : available.gt(0);\n if (hasCapacity) {\n selectedGroup = group.id!;\n break;\n }\n }\n\n if (selectedGroup !== undefined) {\n // RequestElevationGroup requires the obligation to be refreshed in the\n // current slot (klend ObligationStale / 6017). A preceding CPI in this\n // group — e.g. the destination collateral deposit in a flash rebalance —\n // dirties the obligation, so refresh it (and its reserves) immediately\n // before the elevation request. Refreshing against `collReserve` scopes\n // the RefreshObligation to the obligation's current deposits; the borrow\n // below emits its own refresh afterward, re-freshening the obligation\n // that RequestElevationGroup itself leaves stale.\n initCpis.push(\n ...(await this.getRefreshCpisIfNeeded(\n params.txId,\n params.pool,\n collReserve,\n params.userAccount\n ))\n );\n initCpis.push(\n await this.getRequestElevationGroupCpiData(\n selectedGroup,\n params.user,\n params.userAccount,\n params.pool,\n params.txId\n )\n );\n }\n }\n\n const borrowCpis = await this.getBorrowCpiData(params);\n return this.createSplitOperationCpiData(\n [...initCpis, ...borrowCpis.prerequisiteCpis],\n borrowCpis.cpis\n );\n }\n\n async getDepositCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData> {\n const refreshCpis = await this.getRefreshCpisIfNeeded(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount\n );\n const details = await this.accounts.reserveInteractionDetails(\n params.user,\n params.pool,\n params.reserve,\n params.userAccount,\n typeof params.uiAmount === \"number\" ? params.uiAmount : undefined,\n params.baseUnitAmount instanceof BN ? params.baseUnitAmount : undefined\n );\n const farms = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"collateral\"\n );\n\n this.registerTxReserve(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount,\n \"collateral\"\n );\n\n return this.createSplitOperationCpiData(refreshCpis, [\n this.getCpiData(\n CpiTypes.K_DEPOSIT,\n [\n details.signer,\n details.obligation!,\n details.lendingMarket,\n details.lendingMarketAuthority,\n details.reserve,\n details.reserveLiquidityMint,\n details.reserveLiquiditySupply,\n details.reserveCollateralMint,\n details.reserveCollateralSupply,\n details.userLiquidityTa,\n this.emptyAccountMeta(),\n details.collateralMintTokenProgram,\n details.liquidityMintTokenProgram,\n IX_SYSVAR_META,\n farms.userFarm,\n farms.farm,\n details.farmsProgram,\n ],\n details.baseUnitAmount ? numToU64Bytes(details.baseUnitAmount) : undefined,\n undefined,\n this.getUserAccountCacheInvalidations(params.userAccount)\n ),\n ]);\n }\n\n async getWithdrawCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData> {\n const refreshCpis = await this.getRefreshCpisIfNeeded(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount\n );\n const withdrawAll = params.uiAmount === \"all\" || params.baseUnitAmount === \"all\";\n const details = await this.accounts.reserveInteractionDetails(\n params.user,\n params.pool,\n params.reserve,\n params.userAccount,\n typeof params.uiAmount === \"number\" ? params.uiAmount : undefined,\n params.baseUnitAmount instanceof BN ? params.baseUnitAmount : undefined\n );\n const farms = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"collateral\"\n );\n\n let collateralBytes: Uint8Array | undefined;\n if (withdrawAll) {\n // Kamino's `WithdrawObligationCollateralAndRedeemReserveCollateralV2`\n // treats `collateral_amount = u64::MAX` as \"withdraw the obligation's\n // entire deposit on this reserve\" — clears dust regardless of off-chain\n // cToken/liquidity rate drift.\n collateralBytes = numToU64Bytes(U64_MAX_BN);\n } else if (details.baseUnitAmount) {\n const reserveData = await this.data.fetchReserve(params.pool, params.reserve);\n // +1 cToken so the on-chain redemption always realizes at least the\n // requested liquidity amount despite the floor in the exchange rate\n // conversion and minor rate drift between fetch and execution.\n const collateralAmount =\n liquidityToCollateral(reserveData, details.baseUnitAmount.toNumber()) + 1;\n collateralBytes = numToU64Bytes(collateralAmount);\n }\n\n this.registerTxReserve(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount,\n \"collateral\"\n );\n\n return this.createSplitOperationCpiData(refreshCpis, [\n this.getCpiData(\n CpiTypes.K_WITHDRAW,\n [\n details.signer,\n details.obligation!,\n details.lendingMarket,\n details.lendingMarketAuthority,\n details.reserve,\n details.reserveLiquidityMint,\n details.reserveCollateralSupply,\n details.reserveCollateralMint,\n details.reserveLiquiditySupply,\n details.userLiquidityTa,\n this.emptyAccountMeta(),\n details.collateralMintTokenProgram,\n details.liquidityMintTokenProgram,\n IX_SYSVAR_META,\n farms.userFarm,\n farms.farm,\n details.farmsProgram,\n ],\n collateralBytes,\n undefined,\n this.getUserAccountCacheInvalidations(params.userAccount)\n ),\n ]);\n }\n\n async getBorrowCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData> {\n const refreshCpis = await this.getRefreshCpisIfNeeded(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount\n );\n const details = await this.accounts.reserveInteractionDetails(\n params.user,\n params.pool,\n params.reserve,\n params.userAccount,\n typeof params.uiAmount === \"number\" ? params.uiAmount : undefined\n );\n const farms = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"debt\"\n );\n\n this.registerTxReserve(params.txId, params.pool, params.reserve, params.userAccount, \"debt\");\n return this.createSplitOperationCpiData(refreshCpis, [\n this.getCpiData(\n CpiTypes.K_BORROW,\n [\n details.signer,\n details.obligation!,\n details.lendingMarket,\n details.lendingMarketAuthority,\n details.reserve,\n details.reserveLiquidityMint,\n details.reserveLiquiditySupply,\n details.reserveFeeVault,\n details.userLiquidityTa,\n this.emptyAccountMeta(),\n details.liquidityMintTokenProgram,\n IX_SYSVAR_META,\n farms.userFarm,\n farms.farm,\n details.farmsProgram,\n ],\n details.baseUnitAmount ? numToU64Bytes(details.baseUnitAmount) : undefined,\n undefined,\n this.getUserAccountCacheInvalidations(params.userAccount)\n ),\n ]);\n }\n\n async getRepayCpiData(params: RepayOperationParams): Promise<SplitLpOperationCpiData> {\n this.registerTxReserve(params.txId, params.pool, params.reserve, params.userAccount, \"debt\");\n const refreshCpis = await this.getRefreshCpisIfNeeded(\n params.txId,\n params.pool,\n params.reserve,\n params.userAccount\n );\n const details = await this.accounts.reserveInteractionDetails(\n params.user,\n params.pool,\n params.reserve,\n params.userAccount,\n typeof params.uiAmount === \"number\" ? params.uiAmount : undefined\n );\n const farms = await this.accounts.getFarmAccounts(\n params.pool,\n params.reserve,\n params.userAccount,\n \"debt\"\n );\n\n // \"all\" never carries a repay amount — full repayment goes through `full`\n // (U64_MAX); a non-BN amount falls back to the derived reserve amount.\n const repayAmountBytes = params.full\n ? numToU64Bytes(U64_MAX_BN)\n : params.baseUnitAmount instanceof BN\n ? numToU64Bytes(params.baseUnitAmount)\n : details.baseUnitAmount\n ? numToU64Bytes(details.baseUnitAmount)\n : undefined;\n\n return this.createSplitOperationCpiData(refreshCpis, [\n this.getCpiData(\n CpiTypes.K_REPAY,\n [\n details.signer,\n details.obligation!,\n details.lendingMarket,\n details.reserve,\n details.reserveLiquidityMint,\n details.reserveLiquiditySupply,\n details.userLiquidityTa,\n details.liquidityMintTokenProgram,\n IX_SYSVAR_META,\n farms.userFarm,\n farms.farm,\n details.lendingMarketAuthority,\n details.farmsProgram,\n ],\n repayAmountBytes,\n undefined,\n this.getUserAccountCacheInvalidations(params.userAccount)\n ),\n ]);\n }\n}\n","import { BN } from \"@anchor-lang/core\";\nimport { Address, Instruction, Rpc, SolanaRpcApi } from \"@solana/kit\";\nimport { LendingPlatformData } from \"../platform\";\nimport {\n CpiData,\n CustomAccountMeta,\n toCustomAccountMeta,\n TransactionCacheInvalidation,\n} from \"common\";\nimport { LpAccountsBase } from \"../accounts\";\nimport { RefreshPrerequisiteTarget } from \"./types\";\n\n/** Parameters for deposit, withdraw, and borrow operations */\nexport interface LendingOperationParams {\n user: Address;\n payer: Address;\n pool: Address;\n reserve: Address;\n userAccount: Address;\n /**\n * UI-unit amount, or `\"all\"` (withdraw-only) to encode the platform's\n * \"withdraw all\" sentinel (Kamino: `u64::MAX` collateral amount) so the\n * obligation's deposit is fully drained on-chain — no dust left behind\n * from off-chain cToken/liquidity rate drift.\n *\n * If neither this nor {@link baseUnitAmount} is provided, the amount is\n * implied to be derived in the program.\n */\n uiAmount?: number | \"all\";\n /**\n * Exact liquidity base units for the operation (e.g. lamports for SOL). Prefer over\n * {@link uiAmount} when float round-trips would undershoot on-chain requirements.\n * Pass `\"all\"` (withdraw-only) for the same sentinel semantics as {@link uiAmount}.\n */\n baseUnitAmount?: BN | \"all\";\n txId: string;\n}\n\n/** Parameters for repay operations, with option for full repayment */\nexport interface RepayOperationParams extends LendingOperationParams {\n /** Repay amount in UI units. The withdraw-only `\"all\"` sentinel is not valid here. */\n uiAmount?: number;\n /** Exact repay amount in liquidity base units. */\n baseUnitAmount?: BN;\n /** When true, repays the entire debt balance regardless of `amount` */\n full?: boolean;\n}\n\n/** CPI data split into instruction-level prerequisite CPIs and main operation CPIs. */\nexport interface SplitLpOperationCpiData {\n prerequisiteCpis: CpiData[];\n cpis: CpiData[];\n allCpis: CpiData[];\n}\n\n/** Split CPI data plus flattened post-success cache invalidations from all nested CPIs. */\nexport interface LendingOperationCpiBundle extends SplitLpOperationCpiData {\n postSuccessCacheInvalidations: TransactionCacheInvalidation[];\n}\n\n/** Whether a reserve is used as collateral or debt for a user account */\nexport type ReserveRole = \"collateral\" | \"debt\";\n\n/** Tracks a reserve's pool and which user accounts reference it (with roles) */\nexport interface TxReserveInfo {\n pool: Address;\n userAccounts: Map<string, Set<ReserveRole>>;\n}\n\n/**\n * Abstract base class for lending platform instruction builders.\n * Provides a unified interface for building CPI data for different lending protocols.\n * Each platform implementation provides the account metas needed to construct CPI calls.\n *\n * @typeParam T - The platform-specific data class extending LendingPlatformData\n */\nexport abstract class LpInstructionsBase<T extends LendingPlatformData> {\n rpc: Rpc<SolanaRpcApi>;\n rpcUrl: string;\n data: T;\n public abstract programId: Address;\n public abstract lookupTable: Address;\n public accounts: LpAccountsBase<T>;\n\n /** Tracks which reserves (and their pools/roles) are involved in each transaction */\n protected txReserves = new Map<string, Map<string, TxReserveInfo>>();\n\n /**\n * Per-txId per-obligation set of debt reserves that the caller has flagged\n * as being fully repaid earlier in the same transaction. Subsequent\n * `RefreshObligation` builds for that obligation must NOT include these\n * reserves in the borrow accounts list — by execution time the borrow row\n * has been removed from the obligation, and Kamino's `handler_refresh_obligation`\n * checks the passed account count against the live obligation state and\n * fails with `InvalidAccountInput` (klend error 6006) on a mismatch.\n *\n * Set via {@link markObligationDebtCleared}, read via {@link getTxObligationClearedDebt}.\n */\n protected txClearedDebt = new Map<string, Map<string, Set<string>>>();\n\n constructor(rpc: Rpc<SolanaRpcApi>, rpcUrl: string, data: T, accounts: LpAccountsBase<T>) {\n this.rpc = rpc;\n this.rpcUrl = rpcUrl;\n this.data = data;\n this.accounts = accounts;\n }\n\n emptyAccountMeta() {\n return toCustomAccountMeta(this.programId);\n }\n\n clearCacheEntry(category: string, id: string) {\n this.data.clearCacheEntry(category, id);\n }\n\n protected getCacheInvalidation(invalidation: {\n category: string;\n id: Address;\n }): TransactionCacheInvalidation {\n return {\n client: \"kamino\",\n ...invalidation,\n };\n }\n\n applyPostSuccessCacheInvalidations(invalidations: TransactionCacheInvalidation[]) {\n for (const invalidation of invalidations) {\n if (invalidation.client !== \"kamino\") {\n continue;\n }\n this.clearCacheEntry(invalidation.category, invalidation.id);\n }\n }\n\n protected getCpiData(\n cpiType: number,\n accounts: CustomAccountMeta[],\n data?: Uint8Array,\n programId?: Address,\n postSuccessCacheInvalidations?: TransactionCacheInvalidation[]\n ): CpiData {\n return {\n programId: programId ?? this.programId,\n cpiType,\n data,\n accounts,\n lookupTables: [this.lookupTable],\n postSuccessCacheInvalidations,\n };\n }\n\n protected createSplitOperationCpiData(\n prerequisiteCpis: CpiData[],\n cpis: CpiData[]\n ): SplitLpOperationCpiData {\n return {\n prerequisiteCpis,\n cpis,\n allCpis: [...prerequisiteCpis, ...cpis],\n };\n }\n\n protected buildLendingOperationCpiBundle(\n cpiData: SplitLpOperationCpiData\n ): LendingOperationCpiBundle {\n return {\n prerequisiteCpis: cpiData.prerequisiteCpis,\n cpis: cpiData.cpis,\n allCpis: [...cpiData.prerequisiteCpis, ...cpiData.cpis],\n postSuccessCacheInvalidations: [...cpiData.prerequisiteCpis, ...cpiData.cpis].flatMap(\n (cpi) => cpi.postSuccessCacheInvalidations ?? []\n ),\n };\n }\n\n async getInitAndDepositCpiBundle(\n params: LendingOperationParams,\n userAccountId: number\n ): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(\n await this.getInitAndDepositCpiData(params, userAccountId)\n );\n }\n\n async getInitBorrowPositionCpiBundle(\n params: LendingOperationParams,\n collReserve: Address\n ): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(\n await this.getInitBorrowPositionCpiData(params, collReserve)\n );\n }\n\n async getDepositCpiBundle(params: LendingOperationParams): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(await this.getDepositCpiData(params));\n }\n\n async getWithdrawCpiBundle(params: LendingOperationParams): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(await this.getWithdrawCpiData(params));\n }\n\n async getBorrowCpiBundle(params: LendingOperationParams): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(await this.getBorrowCpiData(params));\n }\n\n async getRepayCpiBundle(params: RepayOperationParams): Promise<LendingOperationCpiBundle> {\n return this.buildLendingOperationCpiBundle(await this.getRepayCpiData(params));\n }\n\n /**\n * Registers a reserve as being used in a transaction.\n * When userAccount and role are provided, also tracks the collateral/debt role\n * for that specific user account.\n */\n protected registerTxReserve(\n txId: string,\n pool: Address,\n reserve: Address,\n userAccount?: Address,\n role?: ReserveRole\n ) {\n if (!this.txReserves.has(txId)) {\n this.txReserves.set(txId, new Map());\n }\n const txMap = this.txReserves.get(txId)!;\n if (!txMap.has(reserve)) {\n txMap.set(reserve, { pool, userAccounts: new Map() });\n }\n if (userAccount && role) {\n const entry = txMap.get(reserve)!;\n if (!entry.userAccounts.has(userAccount)) {\n entry.userAccounts.set(userAccount, new Set());\n }\n entry.userAccounts.get(userAccount)!.add(role);\n }\n }\n\n /**\n * Returns the collateral and debt reserves registered in the tx cache\n * for a specific user account (obligation).\n */\n protected getTxUserAccountReserves(\n txId: string,\n userAccount: Address\n ): { collateral: Address[]; debt: Address[] } {\n const collateral: Address[] = [];\n const debt: Address[] = [];\n const txMap = this.txReserves.get(txId);\n if (!txMap) return { collateral, debt };\n for (const [reserve, info] of txMap) {\n const roles = info.userAccounts.get(userAccount);\n if (roles?.has(\"collateral\")) collateral.push(reserve as Address);\n if (roles?.has(\"debt\")) debt.push(reserve as Address);\n }\n return { collateral, debt };\n }\n\n /**\n * Mark that `reserve` will be fully repaid for `userAccount` earlier in the\n * `txId` flow, so subsequent obligation-refresh builders drop it from the\n * borrow accounts they emit. Call after building a \"repay all\" CPI; it has\n * no effect on the repay itself.\n */\n markObligationDebtCleared(txId: string, userAccount: Address, reserve: Address) {\n if (!this.txClearedDebt.has(txId)) {\n this.txClearedDebt.set(txId, new Map());\n }\n const obligationMap = this.txClearedDebt.get(txId)!;\n if (!obligationMap.has(userAccount)) {\n obligationMap.set(userAccount, new Set());\n }\n obligationMap.get(userAccount)!.add(reserve);\n }\n\n /** Returns the set of debt reserves marked cleared for `(txId, userAccount)`. */\n protected getTxObligationClearedDebt(txId: string, userAccount: Address): Set<Address> {\n return (this.txClearedDebt.get(txId)?.get(userAccount) ?? new Set()) as Set<Address>;\n }\n\n /**\n * Clears the transaction cache for a given transaction or all transactions.\n * Call after finishing building a transaction to free memory.\n */\n clearTransactionCache(txId?: string) {\n if (txId) {\n this.txReserves.delete(txId);\n this.txClearedDebt.delete(txId);\n } else {\n this.txReserves.clear();\n this.txClearedDebt.clear();\n }\n }\n\n /**\n * Returns standalone instructions that must be executed at the top level\n * BEFORE the the main CPIs. Should be called after all CPI methods for this\n * txId have been invoked.\n */\n abstract getPreInstructions(txId: string): Promise<Instruction[]>;\n\n /**\n * Returns prerequisite CPIs needed before reading refreshed account state for\n * a batch of lending positions outside a normal deposit/withdraw/borrow/repay\n * flow.\n */\n async getPrerequisiteCpisForRefresh(_targets: RefreshPrerequisiteTarget[]): Promise<CpiData[]> {\n return [];\n }\n\n /** Returns CPI data for initializing a user's lending account */\n abstract getInitUserAccountCpiData(\n pool: Address,\n user: Address,\n feePayer: Address,\n id: number\n ): Promise<SplitLpOperationCpiData>;\n\n /**\n * Returns CPI data for initializing a lending position end-to-end: the user\n * account itself plus any per-reserve accessory accounts (e.g. Kamino\n * obligation farm user states for the collateral and debt reserves). Called\n * at position-creation time so subsequent deposit/borrow flows don't need\n * to init these inline.\n *\n * Default: delegates to {@link getInitUserAccountCpiData}. Platforms with\n * per-reserve accessory accounts override this to add their inits.\n */\n async getInitLendingPositionCpiData(params: {\n pool: Address;\n user: Address;\n payer: Address;\n userAccountId: number;\n collateralReserve: Address;\n debtReserve: Address;\n }): Promise<SplitLpOperationCpiData> {\n return this.getInitUserAccountCpiData(\n params.pool,\n params.user,\n params.payer,\n params.userAccountId\n );\n }\n\n /** Returns CPI data for initializing user account, incentive account (if necessary) and depositing */\n abstract getInitAndDepositCpiData(\n params: LendingOperationParams,\n userAccountId: number\n ): Promise<SplitLpOperationCpiData>;\n\n /** Returns CPI data for initializing a new borrow position */\n abstract getInitBorrowPositionCpiData(\n params: LendingOperationParams,\n collReserve: Address\n ): Promise<SplitLpOperationCpiData>;\n\n /** Returns deposit CPI data split into optional prerequisite CPIs and main CPIs. */\n abstract getDepositCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData>;\n\n /** Returns withdraw CPI data split into optional prerequisite CPIs and main CPIs. */\n abstract getWithdrawCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData>;\n\n /** Returns borrow CPI data split into optional prerequisite CPIs and main CPIs. */\n abstract getBorrowCpiData(params: LendingOperationParams): Promise<SplitLpOperationCpiData>;\n\n /** Returns repay CPI data split into optional prerequisite CPIs and main CPIs. */\n abstract getRepayCpiData(params: RepayOperationParams): Promise<SplitLpOperationCpiData>;\n}\n","import { BN } from \"@anchor-lang/core\";\nimport { Address } from \"@solana/kit\";\nimport { KaminoData } from \"../platform\";\nimport {\n DEFAULT_PUBLIC_KEY,\n lendingMarketAuthPda,\n obligationFarmStatePda,\n PROGRAM_ID,\n userMetadataPda,\n VanillaObligation,\n} from \"@kamino-finance/klend-sdk\";\nimport { getAtaAddress, fromUiAmount, toCustomAccountMeta } from \"common\";\nimport { AssociatedTokenSeeds, TOKEN_PROGRAM_ADDRESS } from \"@solana-program/token\";\nimport { KAMINO_FARMS_PROGRAM_ID } from \"../../constants\";\nimport { LpAccountsBase } from \"./lpAccountsBase\";\n\nexport class KaminoAccounts extends LpAccountsBase<KaminoData> {\n async getUserAccountAddress(pool: Address, user: Address, id: number): Promise<Address> {\n const market = await this.data.fetchMarket(pool);\n const obligationType = new VanillaObligation(market.programId, id);\n return await obligationType.toPda(pool, user);\n }\n\n async getUserMetadataAddress(user: Address) {\n return (await userMetadataPda(user, PROGRAM_ID))[0];\n }\n\n /**\n * Gets the obligation farm accounts for a reserve.\n */\n async getFarmAccounts(\n pool: Address,\n reserve: Address,\n obligation: Address,\n farmMode: \"collateral\" | \"debt\"\n ) {\n const emptyFarms = {\n userFarm: toCustomAccountMeta(PROGRAM_ID),\n farm: toCustomAccountMeta(PROGRAM_ID),\n };\n\n const reserveData = await this.data.fetchReserve(pool, reserve);\n if (!reserveData) {\n return emptyFarms;\n }\n\n const farmAddress =\n farmMode === \"collateral\"\n ? reserveData.rawData.state.farmCollateral\n : reserveData.rawData.state.farmDebt;\n\n if (!farmAddress || farmAddress === DEFAULT_PUBLIC_KEY) {\n return emptyFarms;\n }\n\n const obligationFarmUserState = await obligationFarmStatePda(farmAddress, obligation);\n return {\n userFarm: toCustomAccountMeta(obligationFarmUserState, true),\n farm: toCustomAccountMeta(farmAddress, true),\n };\n }\n\n /**\n * Returns the obligationFarmUserState PDA addresses for all active farms\n * (collateral and debt) on a reserve. The farm addresses themselves live on\n * the Kamino LUTs; only the user-specific state needs the per-token LUT.\n */\n async getUserFarmAddresses(\n pool: Address,\n reserve: Address,\n obligation: Address\n ): Promise<Address[]> {\n const addresses: Address[] = [];\n for (const mode of [\"collateral\", \"debt\"] as const) {\n const { farm, userFarm } = await this.getFarmAccounts(pool, reserve, obligation, mode);\n if (farm.address !== PROGRAM_ID) {\n addresses.push(userFarm.address);\n }\n }\n return addresses;\n }\n\n /**\n * Get all relevant account metas needed for interacting with the Kamino lending market.\n */\n async reserveInteractionDetails(\n user: Address,\n pool: Address,\n reserve: Address,\n obligation?: Address,\n amount?: number,\n baseUnitAmountOverride?: BN\n ) {\n const reserveData = await this.data.fetchReserve(pool, reserve);\n const liquidityMint = reserveData.mint.mint;\n const liquidityMintTokenProgram = reserveData.mint.mintTokenProgram;\n\n const collateralMint = reserveData.rawData.state.collateral.mintPubkey;\n const collateralMintTokenProgram = TOKEN_PROGRAM_ADDRESS;\n\n const userLiquidityTaSeeds: AssociatedTokenSeeds = {\n mint: liquidityMint,\n owner: user,\n tokenProgram: liquidityMintTokenProgram,\n };\n const userLiquidityTa = await getAtaAddress(liquidityMint, user, liquidityMintTokenProgram);\n\n const userCollateralTaSeeds: AssociatedTokenSeeds = {\n mint: collateralMint,\n owner: user,\n tokenProgram: collateralMintTokenProgram,\n };\n const userCollateralTa = await getAtaAddress(collateralMint, user, collateralMintTokenProgram);\n\n const reserveLiquiditySupply = reserveData.rawData.state.liquidity.supplyVault;\n const reserveCollateralSupply = reserveData.rawData.state.collateral.supplyVault;\n\n return {\n baseUnitAmount:\n baseUnitAmountOverride !== undefined\n ? baseUnitAmountOverride\n : amount !== undefined\n ? fromUiAmount(amount, reserveData.mint.mintDecimals)\n : undefined,\n signer: toCustomAccountMeta(user, true),\n obligation: obligation ? toCustomAccountMeta(obligation, true) : undefined,\n reserve: toCustomAccountMeta(reserve, true),\n reserveFeeVault: toCustomAccountMeta(reserveData.rawData.state.liquidity.feeVault, true),\n reserveLiquidityMint: toCustomAccountMeta(liquidityMint),\n reserveLiquiditySupply: toCustomAccountMeta(reserveLiquiditySupply, true),\n reserveCollateralMint: toCustomAccountMeta(collateralMint, true),\n reserveCollateralSupply: toCustomAccountMeta(reserveCollateralSupply, true),\n lendingMarket: toCustomAccountMeta(pool),\n lendingMarketAuthority: toCustomAccountMeta((await lendingMarketAuthPda(pool))[0]),\n userLiquidityTa: toCustomAccountMeta(userLiquidityTa, true, userLiquidityTaSeeds),\n userCollateralTa: toCustomAccountMeta(userCollateralTa, true, userCollateralTaSeeds),\n liquidityMintTokenProgram: toCustomAccountMeta(liquidityMintTokenProgram),\n collateralMintTokenProgram: toCustomAccountMeta(collateralMintTokenProgram),\n farmsProgram: toCustomAccountMeta(KAMINO_FARMS_PROGRAM_ID),\n };\n }\n}\n","import { Address } from \"@solana/kit\";\nimport { LendingPlatformData } from \"../platform\";\n\nexport abstract class LpAccountsBase<T extends LendingPlatformData> {\n data!: T;\n\n constructor(data: T) {\n this.data = data;\n }\n\n abstract getUserAccountAddress(pool: Address, user: Address, id: number): Promise<Address>;\n}\n","import { BN } from \"@anchor-lang/core\";\nimport Decimal from \"decimal.js\";\nimport { type Address, type Instruction, none } from \"@solana/kit\";\nimport {\n getBorrowFlashLoanInstruction,\n getRepayFlashLoanInstruction,\n lendingMarketAuthPda,\n PROGRAM_ID,\n} from \"@kamino-finance/klend-sdk\";\nimport { createSignerFromAddress, getAtaAddress, mints } from \"common\";\nimport { KaminoData } from \"../../data/platform\";\nimport { KaminoReserveData } from \"../../data/reserve\";\nimport { FlashBorrowParams, FlashLoanBase, FlashRepayParams } from \"./flashLoanBase\";\n\n/**\n * Drop the `signer` field from any account meta, leaving the address + role\n * intact. The Kamino codegen attaches a placeholder `NoopSigner` to the\n * `userTransferAuthority` meta to satisfy its TS types; if we keep it, Kit's\n * dedup conflicts with the real fee-payer `KeyPairSigner` whenever the\n * placeholder address matches the fee payer (or appears twice — borrow +\n * repay — in the same tx). Stripping it lets `addSignersToTransactionMessage`\n * re-attach the real signer at compile time.\n */\nfunction stripAccountSigners(ix: Instruction): Instruction {\n if (!ix.accounts) return ix;\n return {\n ...ix,\n accounts: ix.accounts.map((account) => {\n if (!(\"signer\" in account)) return account;\n const { signer: _signer, ...rest } = account as { signer: unknown } & typeof account;\n return rest;\n }),\n };\n}\n\nexport class KaminoFlashLoan extends FlashLoanBase<KaminoData> {\n async getFlashBorrowIx(params: FlashBorrowParams): Promise<Instruction> {\n const { reserve, lendingMarketAuthority, destinationAta } =\n await this.resolveSharedAccounts(params);\n\n return stripAccountSigners(\n getBorrowFlashLoanInstruction({\n userTransferAuthority: createSignerFromAddress(params.user),\n lendingMarketAuthority,\n lendingMarketAddress: params.pool,\n reserve: reserve.rawData,\n amountLamports: new Decimal(params.amountBaseUnits.toString()),\n destinationAta,\n referrerAccount: none(),\n referrerTokenState: none(),\n programId: PROGRAM_ID,\n })\n );\n }\n\n async getAvailableFlashBorrowAmount(pool: Address, reserve: Address): Promise<BN> {\n const reserveData = await this.data.fetchReserve(pool, reserve);\n return new BN(reserveData.rawData.getLiquidityAvailableAmount().toFixed(0));\n }\n\n async getFlashLoanFeeRate(pool: Address, reserve: Address): Promise<number> {\n const reserveData = await this.data.fetchReserve(pool, reserve);\n return reserveData.config.flashLoanFeePct;\n }\n\n async getFlashRepayIx(params: FlashRepayParams): Promise<Instruction> {\n const { reserve, lendingMarketAuthority, destinationAta } =\n await this.resolveSharedAccounts(params);\n\n return stripAccountSigners(\n getRepayFlashLoanInstruction({\n borrowIxIndex: params.borrowIxIndex,\n userTransferAuthority: createSignerFromAddress(params.user),\n lendingMarketAuthority,\n lendingMarketAddress: params.pool,\n reserve: reserve.rawData,\n amountLamports: new Decimal(params.amountBaseUnits.toString()),\n userSourceLiquidity: params.userSourceLiquidity ?? destinationAta,\n referrerAccount: none(),\n referrerTokenState: none(),\n programId: PROGRAM_ID,\n })\n );\n }\n\n private async resolveSharedAccounts(params: FlashBorrowParams): Promise<{\n reserve: KaminoReserveData;\n lendingMarketAuthority: Address;\n destinationAta: Address;\n }> {\n const reserve = await this.data.fetchReserve(params.pool, params.reserve);\n const [lendingMarketAuthority] = await lendingMarketAuthPda(params.pool);\n\n const liquidityMint = reserve.mint.mint;\n const tokenProgram = mints.get(liquidityMint)?.tokenProgram;\n if (!tokenProgram) {\n throw new Error(`Unsupported liquidity mint for flash loan: ${liquidityMint}`);\n }\n\n const destinationAta =\n params.destinationAta ?? (await getAtaAddress(liquidityMint, params.user, tokenProgram));\n\n return { reserve, lendingMarketAuthority, destinationAta };\n }\n}\n","import { BN } from \"@anchor-lang/core\";\nimport type { Address, Instruction } from \"@solana/kit\";\nimport { LendingPlatformData } from \"../../data/platform\";\n\n/** Parameters for building a flash-borrow instruction. */\nexport interface FlashBorrowParams {\n /** Authority that signs the transfer of the borrowed liquidity. */\n user: Address;\n pool: Address;\n reserve: Address;\n /** Amount to borrow, in the reserve liquidity mint's base units. */\n amountBaseUnits: BN;\n /** Destination ATA for the borrowed liquidity. Defaults to `user`'s ATA for the mint. */\n destinationAta?: Address;\n}\n\n/** Parameters for building a flash-repay instruction, paired with a prior flash-borrow. */\nexport interface FlashRepayParams extends FlashBorrowParams {\n /** Top-level transaction index of the matching flash-borrow instruction. */\n borrowIxIndex: number;\n /** Source ATA for the repay. Defaults to the destination ATA used on the flash-borrow. */\n userSourceLiquidity?: Address;\n}\n\n/**\n * Abstract base for lending-platform flash-loan instruction builders.\n * Flash loans are composed of a top-level borrow and repay pair that must live\n * in the same transaction; the repay references the borrow by instruction index.\n *\n * @typeParam T - The platform-specific data class extending LendingPlatformData\n */\nexport abstract class FlashLoanBase<T extends LendingPlatformData> {\n data!: T;\n\n constructor(data: T) {\n this.data = data;\n }\n\n /** Builds the top-level flash-borrow instruction. */\n abstract getFlashBorrowIx(params: FlashBorrowParams): Promise<Instruction>;\n\n /**\n * Builds the top-level flash-repay instruction. Must be paired with a\n * flash-borrow at `borrowIxIndex` in the same transaction.\n */\n abstract getFlashRepayIx(params: FlashRepayParams): Promise<Instruction>;\n\n /**\n * Returns the maximum amount that can be flash-borrowed from `reserve`, in\n * the reserve liquidity mint's base units.\n */\n abstract getAvailableFlashBorrowAmount(pool: Address, reserve: Address): Promise<BN>;\n\n /**\n * Returns `reserve`'s flash-loan fee rate as a fraction of the borrowed\n * amount (e.g. `0.003` for 0.3%).\n */\n abstract getFlashLoanFeeRate(pool: Address, reserve: Address): Promise<number>;\n}\n","import { BN } from \"@anchor-lang/core\";\nimport type { Instruction } from \"@solana/kit\";\nimport { applyFeeCeil, type CpiData, fromUiAmount, getAtaAddress, toUiAmount } from \"common\";\nimport { sizeExactInForMinOutput } from \"jupiter-helpers\";\nimport { LendingPositionManager } from \"../lendingPosition/lendingPositionManager\";\nimport { ReservesManager } from \"../reservesManager\";\nimport type {\n DecreaseLeverageParams,\n DecreaseLeverageResult,\n FlashRebalanceContext,\n FlashRebalanceParams,\n FlashRebalanceResult,\n IncreaseLeverageParams,\n IncreaseLeverageResult,\n LeverageContext,\n LeverageSwapContext,\n} from \"./types\";\n\nconst DECREASE_LEVERAGE_SWAP_BUFFER_BPS = 5;\nconst DECREASE_LEVERAGE_SWAP_SLIPPAGE_BPS = 40;\nconst DECREASE_LEVERAGE_SWAP_MAX_ACCOUNTS = 30;\nconst FLASH_REBALANCE_SWAP_MAX_ACCOUNTS = 25;\n\n/**\n * Thrown by {@link LeverageService.buildFlashRebalance} when the quoted\n * destination-debt → source-debt swap breaches a caller-set bound. The quote's\n * total below-par gap is split into two components, each bounded separately:\n *\n * - `executionCostBps` — quote rate vs the oracle-fair cross rate: route fees\n * + price impact. Permanently lost value.\n * - `marketBasisBps` — oracle-fair cross rate vs 1:1: genuine USD price\n * difference between the two stables. Charged to the token's carry-vs-debt\n * difference by the $1-pinned books at conversion time, but reverses on\n * unwind if the basis persists.\n *\n * `reason` names which bound was breached; both measured components are\n * always populated for logging/telemetry.\n */\nexport class FlashRebalanceSwapCostExceededError extends Error {\n constructor(\n readonly reason: \"execution-cost\" | \"market-basis\",\n readonly executionCostBps: number,\n readonly marketBasisBps: number,\n readonly limitBps: number,\n readonly inputAmount: bigint,\n readonly outputAmount: bigint\n ) {\n super(\n `LeverageService.buildFlashRebalance: swap ${reason} exceeds ${limitBps} bps ` +\n `(execution cost ${executionCostBps.toFixed(2)} bps, market basis ${marketBasisBps.toFixed(2)} bps, ` +\n `in=${inputAmount} out=${outputAmount})`\n );\n this.name = \"FlashRebalanceSwapCostExceededError\";\n }\n}\n\n/**\n * Stateless service that sizes and builds lending-protocol CPIs for leverage\n * changes on a collateral/debt reserve pair.\n *\n * Inputs are generic lending-platform types (reserves, LP client, position\n * identifiers). No program-specific types.\n *\n * - **Increase leverage** → calculates borrow amount to reach target, builds\n * borrow CPIs.\n * - **Decrease leverage** → calculates repay amount to reach target, builds\n * repay CPIs, and assembles swap + repay CPI groups when the debt token must\n * be obtained via swap.\n */\nexport class LeverageService {\n /**\n * Calculate the borrow amount needed to reach the target utilization rate,\n * then build the borrow CPIs.\n */\n static async buildIncreaseLeverage(\n ctx: LeverageContext,\n params: IncreaseLeverageParams\n ): Promise<IncreaseLeverageResult> {\n const reserves = new ReservesManager(ctx.supplyReserve, ctx.debtReserve, ctx.environment);\n const mode = params.mode ?? \"debtOnly\";\n\n const debtAdjustmentUsd = await reserves.calcDebtAdjustmentUsd(\n params.currentSupplyUiAmount,\n params.currentDebtUiAmount,\n params.targetUtilizationRateBps,\n { positionChangeMode: mode }\n );\n\n const prices = await reserves.prices();\n const borrowUiAmount = Math.abs(debtAdjustmentUsd / prices.debt.realtimePrice);\n const borrowBaseUnits = fromUiAmount(borrowUiAmount, ctx.debtReserve.mint.mintDecimals);\n\n const { prerequisiteCpis, cpis, postSuccessCacheInvalidations } =\n await ctx.lendingIx.getBorrowCpiBundle({\n user: ctx.user,\n payer: ctx.payer,\n pool: ctx.pool,\n reserve: ctx.debtReserve.address,\n userAccount: ctx.userAccount,\n uiAmount: borrowUiAmount,\n txId: ctx.txId,\n });\n\n const preInstructions = await ctx.lendingIx.getPreInstructions(ctx.txId);\n\n return {\n borrowUiAmount,\n borrowBaseUnits,\n prerequisiteCpis,\n borrowCpis: cpis,\n preInstructions,\n postSuccessCacheInvalidations,\n };\n }\n\n /**\n * Calculate the repay amount needed to reach the target utilization rate,\n * build the repay CPIs, and assemble CPI groups with an optional swap\n * prepended when the caller's debt-token balance is insufficient.\n *\n * The returned `repayUiAmount` is always non-negative. When the position is\n * already at or below the target, the amount is zero and the CPI list is\n * sized for a zero repay.\n */\n static async buildDecreaseLeverage(\n ctx: LeverageContext,\n params: DecreaseLeverageParams\n ): Promise<DecreaseLeverageResult> {\n const reserves = new ReservesManager(ctx.supplyReserve, ctx.debtReserve, ctx.environment);\n const mode = params.mode ?? \"debtOnly\";\n\n const debtAdjustmentUsd = await reserves.calcDebtAdjustmentUsd(\n params.currentSupplyUiAmount,\n params.currentDebtUiAmount,\n params.targetUtilizationRateBps,\n { positionChangeMode: mode }\n );\n\n const prices = await reserves.prices();\n const debtDecimals = ctx.debtReserve.mint.mintDecimals;\n const repayUiAmount = Math.abs(debtAdjustmentUsd / prices.debt.realtimePrice);\n const calculatedRepayBaseUnits = fromUiAmount(repayUiAmount, debtDecimals);\n const repayBaseUnits = params.repayBaseUnitsOverride ?? calculatedRepayBaseUnits;\n\n // The repay CPI is always built without an embedded amount. On-chain, the\n // handler sources the final amount from `params.repay_amount` (manager /\n // non-swap path) or from the post-swap balance delta (swap path), then\n // forwards it to the repay CPI via `invoke_amount_cpi` (Skip sentinel).\n // Embedding the amount here would leak build-time estimates into a slot\n // that must reflect runtime state.\n //\n // Full deleverages pass `repayBaseUnitsOverride` so the Kamino CPI and SPL\n // transfer both use refreshed obligation debt instead of stale accounting.\n const { prerequisiteCpis, cpis } = await ctx.lendingIx.getRepayCpiData({\n user: ctx.user,\n payer: ctx.payer,\n pool: ctx.pool,\n reserve: ctx.debtReserve.address,\n userAccount: ctx.userAccount,\n txId: ctx.txId,\n ...(params.repayBaseUnitsOverride ? { baseUnitAmount: repayBaseUnits } : {}),\n });\n\n const preInstructions = await ctx.lendingIx.getPreInstructions(ctx.txId);\n\n const swapRequired = params.swapContext !== undefined;\n const assembledCpis = await this.assembleDecreaseLeverageCpis(\n repayBaseUnits,\n cpis,\n params.swapContext\n );\n\n return {\n repayUiAmount,\n repayBaseUnits,\n prerequisiteCpis,\n repayCpis: cpis,\n cpiDataGroups: assembledCpis.cpiDataGroups,\n swapRequired,\n preInstructions: [...preInstructions, ...assembledCpis.preInstructions],\n };\n }\n\n /**\n * Assemble repay CPI groups, prepending a swap group whenever the bank is\n * configured to source the debt mint via a swap. The on-chain handler\n * decides whether to actually invoke the swap (via `perform_swap`) based on\n * runtime balances; building it unconditionally keeps the tx resilient when\n * the bank's debt-token balance changes between build and send.\n */\n private static async assembleDecreaseLeverageCpis(\n repayBaseUnits: BN,\n repayCpis: CpiData[],\n swapContext?: LeverageSwapContext\n ): Promise<{ cpiDataGroups: CpiData[][]; preInstructions: Instruction[] }> {\n if (!swapContext) {\n return { cpiDataGroups: [repayCpis], preInstructions: [] };\n }\n\n // Quote the swap for the full repay amount rather than\n // `repay - debtHeld`, so the swap can cover the repay on its own if the\n // bank's debt-token balance has dropped since tx build time.\n const swapCpiData = await this.quoteDebtTopUpSwap(swapContext, repayBaseUnits);\n\n return {\n cpiDataGroups: [[swapCpiData], repayCpis],\n preInstructions: swapCpiData.preInstructions ?? [],\n };\n }\n\n /**\n * Quote a swap that converts a source asset into the debt mint,\n * covering at least `shortfall` base units.\n */\n private static async quoteDebtTopUpSwap(\n ctx: LeverageSwapContext,\n shortfall: BN\n ): Promise<CpiData> {\n const need = BigInt(shortfall.toString());\n if (need <= 0n) {\n throw new Error(\"LeverageService.quoteDebtTopUpSwap: shortfall must be positive\");\n }\n if (ctx.sourceBalanceBaseUnits <= 0n) {\n throw new Error(\"LeverageService.quoteDebtTopUpSwap: source balance is zero\");\n }\n\n const { quote } = await sizeExactInForMinOutput(ctx.swap, {\n inputMint: ctx.sourceMint,\n outputMint: ctx.debtMint,\n minOutputAmount: need,\n maxInputAmount: ctx.sourceBalanceBaseUnits,\n slippageBps: ctx.slippageBps ?? DECREASE_LEVERAGE_SWAP_SLIPPAGE_BPS,\n safetyBufferBps: DECREASE_LEVERAGE_SWAP_BUFFER_BPS,\n maxAccounts: DECREASE_LEVERAGE_SWAP_MAX_ACCOUNTS,\n excludeDexes: ctx.excludeDexes,\n });\n\n return ctx.swap.getSwapCpiData(quote, ctx.swapTarget, { payer: ctx.payer });\n }\n\n /**\n * Build a flash-loan-wrapped rebalance that moves collateral between two\n * lending positions without decreasing any carry positions.\n *\n * The flow assembled here (inside a single transaction):\n * 1. Top-level: flash-borrow source debt mint into the user's ATA.\n * 2. CPI: repay flash-borrowed amount on source → frees collateral.\n * 3. CPI: withdraw `collateralUiAmount` from source.\n * 4. CPI: deposit that collateral on destination.\n * 5. CPI: borrow destination debt mint (sized slightly above the swap\n * input needed to produce the flash repay, so post-slippage output\n * still covers it).\n * 6. CPI: exact-in swap destination debt → source debt; the entire borrow\n * is consumed and worst-case output is at least the flash repay amount.\n * 7. Top-level: flash-repay source debt mint.\n *\n * The exact-in over-borrow leaves a small **source-debt** excess in the\n * token PDA's ATA after the swap; the on-chain handler sweeps this excess\n * into the yielding bank before the top-level flash repay so exactly\n * `flashRepayAmountBaseUnits` remains for the repay.\n */\n static async buildFlashRebalance(\n ctx: FlashRebalanceContext,\n params: FlashRebalanceParams\n ): Promise<FlashRebalanceResult> {\n if (ctx.source.debtReserve.mint.mint === ctx.destination.debtReserve.mint.mint) {\n throw new Error(\n \"LeverageService.buildFlashRebalance: source and destination debt mints must differ\"\n );\n }\n const sourceDebtMint = ctx.source.debtReserve.address;\n const sourceDebtLiqMint = ctx.source.debtReserve.mint.mint;\n const sourceDebtDecimals = ctx.source.debtReserve.mint.mintDecimals;\n const destDebtLiqMint = ctx.destination.debtReserve.mint.mint;\n const destDebtDecimals = ctx.destination.debtReserve.mint.mintDecimals;\n\n const sourceRepayBaseUnits = await this.calcSourceRepayForWithdraw(ctx, params);\n if (sourceRepayBaseUnits.lten(0)) {\n throw new Error(\n \"LeverageService.buildFlashRebalance: source repay amount must be positive — use the simple rebalance path when no flash loan is needed\"\n );\n }\n const sourceRepayUiAmount = toUiAmount(sourceRepayBaseUnits, sourceDebtDecimals);\n\n const flashFeeRate = await ctx.flashLoan.getFlashLoanFeeRate(ctx.source.pool, sourceDebtMint);\n // For `withdrawAll`, the rebalance-token builder sends Kamino's\n // `u64::MAX` repay sentinel — Kamino computes the obligation's\n // *refreshed* debt at execution time, which exceeds the off-chain\n // principal snapshot by any unrealized interest accrual. Over-borrow by\n // 5 bps so the ATA always covers the refreshed debt; the surplus is\n // swept into the yielding bank by the rebalance handler's dust path.\n //\n // For partial rebalances the builder sends `flashBorrowAmount` as the\n // explicit repay amount — the on-chain repay matches the ATA balance\n // exactly, so no buffer is needed (over-borrowing would just bloat the\n // dust sweep and pay an unnecessary flash fee).\n const SOURCE_REPAY_OVERBORROW_BPS = 5n;\n const sourceRepayBigInt = BigInt(sourceRepayBaseUnits.toString());\n const flashBorrowBigInt = params.withdrawAll\n ? sourceRepayBigInt + (sourceRepayBigInt * SOURCE_REPAY_OVERBORROW_BPS) / 10_000n\n : sourceRepayBigInt;\n const flashFeeBigInt = applyFeeCeil(flashBorrowBigInt, flashFeeRate);\n const flashRepayBigInt = flashBorrowBigInt + flashFeeBigInt;\n const flashBorrowAmountBaseUnits = new BN(flashBorrowBigInt.toString());\n const flashFeeBaseUnits = new BN(flashFeeBigInt.toString());\n const flashRepayAmountBaseUnits = new BN(flashRepayBigInt.toString());\n\n const reserveBorrowCapacityBaseUnits = BigInt(\n fromUiAmount(\n ctx.destination.debtReserve.borrows.limit - ctx.destination.debtReserve.borrows.totalAmount,\n destDebtDecimals\n ).toString()\n );\n // Borrow capacity is calculated from current destination collateral only —\n // supply never moves in a debt-only rebalance.\n const utilizationBorrowCapacityBaseUnits = await this.calcDestinationBorrowCapacityForDeposit(\n ctx,\n { ...params, collateralUiAmount: 0 }\n );\n const maxDestinationBorrowBaseUnits = [\n params.maxDestinationBorrowBaseUnits,\n reserveBorrowCapacityBaseUnits,\n utilizationBorrowCapacityBaseUnits,\n ]\n .filter((amount): amount is bigint => amount !== undefined)\n .reduce((min, amount) => (amount < min ? amount : min));\n if (maxDestinationBorrowBaseUnits <= 0n) {\n throw new Error(\n \"LeverageService.buildFlashRebalance: destination reserve has no available borrow capacity\"\n );\n }\n // ExactIn-sized swap: routes through the dense ExactIn graph instead of\n // the sparser ExactOut graph (which often returns NO_ROUTES_FOUND on\n // Jupiter). We over-borrow slightly so the worst-case post-slippage\n // output still covers `flashRepayBigInt`; the post-swap source-debt\n // excess is swept on-chain into the yielding bank.\n const { quote: swapQuote } = await sizeExactInForMinOutput(ctx.swap, {\n inputMint: destDebtLiqMint,\n outputMint: sourceDebtLiqMint,\n minOutputAmount: flashRepayBigInt,\n maxInputAmount: maxDestinationBorrowBaseUnits,\n slippageBps: params.swapSlippageBps ?? 15,\n safetyBufferBps: params.swapBufferBps ?? 5,\n maxAccounts: FLASH_REBALANCE_SWAP_MAX_ACCOUNTS,\n });\n\n // Split the quote's below-par gap into market basis (oracle-fair cross\n // rate vs 1:1) and execution cost (quote vs that fair rate — route fees\n // + price impact), and bound each independently. The $1-pinned on-chain\n // books charge the *whole* gap to the token at conversion time, but only\n // the execution component is permanently lost; the basis component is\n // mark-to-market that reverses on unwind if the basis persists.\n if (params.maxSwapCostBps !== undefined || params.maxMarketBasisBps !== undefined) {\n const [sourcePrices, destPrices] = await Promise.all([\n new ReservesManager(\n ctx.source.supplyReserve,\n ctx.source.debtReserve,\n ctx.environment\n ).prices(),\n new ReservesManager(\n ctx.destination.supplyReserve,\n ctx.destination.debtReserve,\n ctx.environment\n ).prices(),\n ]);\n const fairOutPerIn = destPrices.debt.realtimePrice / sourcePrices.debt.realtimePrice;\n if (!Number.isFinite(fairOutPerIn) || fairOutPerIn <= 0) {\n throw new Error(\n `LeverageService.buildFlashRebalance: invalid oracle prices for swap cost check ` +\n `(source=${sourcePrices.debt.realtimePrice} dest=${destPrices.debt.realtimePrice})`\n );\n }\n const inUi = Number(swapQuote.inputAmount) / Math.pow(10, destDebtDecimals);\n const outUi = Number(swapQuote.outputAmount) / Math.pow(10, sourceDebtDecimals);\n const executionCostBps = (1 - outUi / inUi / fairOutPerIn) * 10_000;\n const marketBasisBps = (1 - fairOutPerIn) * 10_000;\n if (params.maxSwapCostBps !== undefined && executionCostBps > params.maxSwapCostBps) {\n throw new FlashRebalanceSwapCostExceededError(\n \"execution-cost\",\n executionCostBps,\n marketBasisBps,\n params.maxSwapCostBps,\n swapQuote.inputAmount,\n swapQuote.outputAmount\n );\n }\n if (\n params.maxMarketBasisBps !== undefined &&\n Math.abs(marketBasisBps) > params.maxMarketBasisBps\n ) {\n throw new FlashRebalanceSwapCostExceededError(\n \"market-basis\",\n executionCostBps,\n marketBasisBps,\n params.maxMarketBasisBps,\n swapQuote.inputAmount,\n swapQuote.outputAmount\n );\n }\n }\n\n const swapCpi = await ctx.swap.getSwapCpiData(swapQuote, ctx.user, { payer: ctx.payer });\n const destinationBorrowBaseUnits = new BN(swapQuote.inputAmount.toString());\n const destinationBorrowUiAmount = toUiAmount(destinationBorrowBaseUnits, destDebtDecimals);\n\n // Build the CPI bundles serially in execution order. The LP instruction\n // clients track reserve registrations per-obligation-per-txId; each\n // bundle's `getRefreshCpisIfNeeded` sees the cached reserves registered\n // by earlier calls on the same obligation. Running these in parallel\n // (Promise.all) would interleave non-deterministically and could cause\n // the later op's refresh to miss a reserve.\n //\n // Repay is built with NO uiAmount → the CPI data is a Skip sentinel.\n // On-chain, the rebalance_token handler fills the amount from\n // `flash_cpis.repay_amount` via `invoke_amount_cpi`, keeping the repay\n // amount authoritative from one top-level param instead of embedded in\n // a CPI we can't easily update after a quote refresh.\n const sourceRepay = await ctx.source.lendingIx.getRepayCpiData({\n user: ctx.user,\n payer: ctx.payer,\n pool: ctx.source.pool,\n reserve: sourceDebtMint,\n userAccount: ctx.source.userAccount,\n txId: ctx.txId,\n });\n\n // For a full repay the source debt row is removed from the obligation before\n // the destination borrow's RefreshObligation runs. Flag it now so that CPI's\n // accounts are built with 0 borrows; otherwise klend rejects the mismatched\n // account count with InvalidAccountInput (error 6006).\n // Partial rebalances leave the debt row intact — do not mark.\n if (params.withdrawAll) {\n ctx.source.lendingIx.markObligationDebtCleared(\n ctx.txId,\n ctx.source.userAccount,\n sourceDebtMint\n );\n }\n\n const destBorrow = await ctx.destination.lendingIx.getInitBorrowPositionCpiBundle(\n {\n user: ctx.user,\n payer: ctx.payer,\n pool: ctx.destination.pool,\n reserve: ctx.destination.debtReserve.address,\n userAccount: ctx.destination.userAccount,\n uiAmount: destinationBorrowUiAmount,\n txId: ctx.txId,\n },\n ctx.destination.supplyReserve.address\n );\n\n // The flash borrow/repay use the payer (a real top-level signer) as\n // `userTransferAuthority` because `ctx.user` (the obligation owner) is\n // typically a PDA and can't sign at the top level. The borrowed liquidity\n // still flows into the obligation owner's source-debt ATA — Kamino\n // requires the borrow's `userDestinationLiquidity` to equal the repay's\n // `userSourceLiquidity`, so both reference the same ATA. The on-chain\n // rebalance handler grants the payer SPL Approve over that ATA at the\n // end so the top-level flash repay's transfer can settle via delegation.\n const userSourceDebtAta = await getAtaAddress(\n sourceDebtLiqMint,\n ctx.user,\n ctx.source.debtReserve.mint.mintTokenProgram\n );\n\n const flashBorrowIx = await ctx.flashLoan.getFlashBorrowIx({\n user: ctx.payer,\n pool: ctx.source.pool,\n reserve: sourceDebtMint,\n amountBaseUnits: flashBorrowAmountBaseUnits,\n destinationAta: userSourceDebtAta,\n });\n\n const sourceIx = ctx.source.lendingIx;\n const destIx = ctx.destination.lendingIx;\n const sourcePreInstructions = await sourceIx.getPreInstructions(ctx.txId);\n const lendingPreInstructions =\n sourceIx === destIx\n ? sourcePreInstructions\n : [...sourcePreInstructions, ...(await destIx.getPreInstructions(ctx.txId))];\n\n // Lending-platform pre-instructions must come first (they prepare reserve\n // state the inner CPIs depend on). Swap-driven pre-instructions\n // (e.g. createATA for intermediate-mint hops in a Jupiter route) ride\n // immediately after — both must precede the host's other ATA setup so\n // they're in scope by the time the rebalance CPI dispatches the swap.\n const swapPreInstructions = swapCpi.preInstructions ?? [];\n const preInstructions = [...lendingPreInstructions, ...swapPreInstructions];\n\n const postSuccessCacheInvalidations = [\n ...destBorrow.postSuccessCacheInvalidations,\n ...(swapCpi.postSuccessCacheInvalidations ?? []),\n ];\n\n return {\n flashBorrowAmountBaseUnits,\n flashRepayAmountBaseUnits,\n flashFeeBaseUnits,\n sourceRepayUiAmount,\n destinationBorrowUiAmount,\n flashBorrowIx,\n sourceRepayCpis: [...sourceRepay.prerequisiteCpis, ...sourceRepay.cpis],\n destinationBorrowCpis: [...destBorrow.prerequisiteCpis, ...destBorrow.cpis],\n swapCpis: [swapCpi],\n preInstructions,\n postSuccessCacheInvalidations,\n };\n }\n\n /**\n * Build the top-level flash-repay instruction for a previously-built flash\n * rebalance, given the final transaction index of its `flashBorrowIx`.\n *\n * Split from {@link buildFlashRebalance} because `borrowIxIndex` depends on\n * the caller's full tx layout (pre-instructions + heap frame + ATA creations\n * + flash-borrow position), which in turn depends on the ATA list derived\n * from the plan's `remainingAccounts` — a chicken-and-egg the caller resolves\n * by assembling the preamble before calling this.\n */\n static async buildFlashRepayIx(\n ctx: FlashRebalanceContext,\n plan: Pick<FlashRebalanceResult, \"flashBorrowAmountBaseUnits\">,\n borrowIxIndex: number\n ): Promise<Instruction> {\n // The payer (top-level signer) authorizes the repay. Kamino enforces\n // that the borrow's `userDestinationLiquidity` matches the repay's\n // `userSourceLiquidity` — both must reference the obligation-owner's\n // source-debt ATA — so we explicitly route the repay through that ATA\n // rather than letting it default to the payer's. The on-chain\n // rebalance handler grants the payer SPL Approve over this ATA before\n // returning, so the top-level repay's transfer settles via delegation.\n const userSourceDebtAta = await getAtaAddress(\n ctx.source.debtReserve.mint.mint,\n ctx.user,\n ctx.source.debtReserve.mint.mintTokenProgram\n );\n return ctx.flashLoan.getFlashRepayIx({\n user: ctx.payer,\n pool: ctx.source.pool,\n reserve: ctx.source.debtReserve.address,\n amountBaseUnits: plan.flashBorrowAmountBaseUnits,\n borrowIxIndex,\n userSourceLiquidity: userSourceDebtAta,\n });\n }\n\n private static async calcSourceRepayForWithdraw(\n ctx: FlashRebalanceContext,\n params: FlashRebalanceParams\n ): Promise<BN> {\n const manager = new LendingPositionManager(\n ctx.source.lendingIx.data,\n ctx.source.pool,\n ctx.source.userAccount,\n ctx.source.supplyReserve,\n ctx.source.debtReserve,\n ctx.environment\n );\n if (params.withdrawAll) {\n const { debtUiAmount } = await manager.getLendingPositionAmounts();\n return fromUiAmount(debtUiAmount, ctx.source.debtReserve.mint.mintDecimals);\n }\n\n const debtChangeUi = await manager.calcDebtChangeAmountForCollateralWithdrawal(\n params.collateralUiAmount,\n params.sourceTargetUtilizationRateBps\n );\n // `calcDebtChangeAmountForCollateralWithdrawal` returns a signed UI delta:\n // negative → repay, positive → (under-leveraged) borrow. The flash path is\n // only relevant for the repay case.\n const repayUi = Math.max(0, -debtChangeUi);\n return fromUiAmount(repayUi, ctx.source.debtReserve.mint.mintDecimals);\n }\n\n private static async calcDestinationBorrowCapacityForDeposit(\n ctx: FlashRebalanceContext,\n params: FlashRebalanceParams\n ): Promise<bigint | undefined> {\n if (params.destinationMaxUtilizationRateBps === undefined) {\n return undefined;\n }\n\n const manager = new LendingPositionManager(\n ctx.destination.lendingIx.data,\n ctx.destination.pool,\n ctx.destination.userAccount,\n ctx.destination.supplyReserve,\n ctx.destination.debtReserve,\n ctx.environment\n );\n const current = await manager.getLendingPositionAmounts();\n const reserves = new ReservesManager(\n ctx.destination.supplyReserve,\n ctx.destination.debtReserve,\n ctx.environment\n );\n const debtAdjustmentUsd = await reserves.calcDebtAdjustmentUsd(\n current.supplyUiAmount + params.collateralUiAmount,\n current.debtUiAmount,\n params.destinationMaxUtilizationRateBps,\n { positionChangeMode: \"debtOnly\" }\n );\n const prices = await reserves.prices();\n if (debtAdjustmentUsd <= 0) {\n return 0n;\n }\n\n const debtUiAmount = debtAdjustmentUsd / prices.debt.realtimePrice;\n return BigInt(\n fromUiAmount(debtUiAmount, ctx.destination.debtReserve.mint.mintDecimals).toString()\n );\n }\n}\n","import { address, type Address } from \"@solana/kit\";\n\n/**\n * Jupiter V6 Aggregator Program ID\n */\nexport const JUPITER_V6_PROGRAM_ID: Address = address(\n \"JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4\"\n);\n\n/**\n * Jupiter API base URL\n */\nexport const JUPITER_API_URL = \"https://lite-api.jup.ag\";\n\n/**\n * Default slippage in basis points (5%)\n */\nexport const DEFAULT_SLIPPAGE_BPS = 500;\n\n/**\n * Local/Surfpool max account budget for swap instructions.\n * Lower values improve compatibility with local validators.\n */\nexport const LOCAL_TEST_MAX_ACCOUNTS = 20;\n\n/**\n * DEXes to exclude in local/Surfpool tests.\n * Production/testnet deployments should not apply this list by default.\n */\nexport const LOCAL_TEST_EXCLUDED_DEXES = [\"GoonFi\", \"HumidiFi\", \"TesseraV\", \"1DEX\", \"Aquifer\"];\n\n/**\n * Venues excluded from ALL Jupiter quotes, in every environment. These\n * proprietary market-maker venues rotate their vault token accounts\n * off-chain, so quoted routes intermittently fail at execution with\n * \"Token account ... has wrong owner\". Not applied when a `dexes`\n * whitelist is set (the whitelist takes full control of routing).\n *\n * TODO(2026-07-06): Riptide was excluded after repeated wrong-owner failures\n * on PYUSD routes. It often quotes the best stable-pair price, so revisit\n * later and give it another chance if their account rotation has stabilized.\n */\nexport const ALWAYS_EXCLUDED_DEXES = [\"Riptide\"];\n","import type { Address, Transaction } from \"@solana/kit\";\nimport { getBase64Encoder, getTransactionDecoder } from \"@solana/kit\";\nimport { createJupiterApiClient } from \"@jup-ag/api\";\nimport type { QuoteResponse } from \"@jup-ag/api\";\nimport { JUPITER_API_URL, DEFAULT_SLIPPAGE_BPS, ALWAYS_EXCLUDED_DEXES } from \"./constants\";\nimport type { JupiterQuoteParams, JupiterSwapParams } from \"./types\";\n\n/**\n * Get a Jupiter swap quote.\n *\n * @param params - Quote parameters\n * @returns Quote response from Jupiter API\n *\n * @example\n * ```typescript\n * const quote = await getJupiterQuote({\n * inputMint: address(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"),\n * outputMint: address(\"So11111111111111111111111111111111111111112\"),\n * amount: 1000_000, // 1 USDC (6 decimals)\n * });\n * ```\n */\nexport async function getJupiterQuote(params: JupiterQuoteParams): Promise<QuoteResponse> {\n const jupiterApi = createJupiterApiClient({ basePath: JUPITER_API_URL });\n\n const amount = typeof params.amount === \"bigint\" ? Number(params.amount) : params.amount;\n const request = {\n inputMint: params.inputMint,\n outputMint: params.outputMint,\n amount,\n slippageBps: params.slippageBps ?? DEFAULT_SLIPPAGE_BPS,\n swapMode: params.swapMode,\n maxAccounts: params.maxAccounts,\n dexes: params.dexes,\n // When `dexes` is set it acts as a whitelist and `excludeDexes` is irrelevant.\n // Otherwise the caller's exclusions are merged with the global list.\n excludeDexes: params.dexes\n ? undefined\n : [...new Set([...ALWAYS_EXCLUDED_DEXES, ...(params.excludeDexes ?? [])])],\n onlyDirectRoutes: params.onlyDirectRoutes,\n };\n\n try {\n return await jupiterApi.quoteGet(request);\n } catch (err) {\n throw await enrichJupiterHttpError(err, request);\n }\n}\n\n/**\n * The OpenAPI client throws `ResponseError` with a generic message; the real reason\n * is usually in the HTTP body (e.g. no route, validation).\n */\nasync function enrichJupiterHttpError(\n err: unknown,\n request: Parameters<ReturnType<typeof createJupiterApiClient>[\"quoteGet\"]>[0]\n): Promise<Error> {\n if (!(err instanceof Error) || !(\"response\" in err)) {\n return err instanceof Error ? err : new Error(String(err));\n }\n const res = (err as { response?: Response }).response;\n if (!res || res.ok || typeof res.text !== \"function\") {\n return err;\n }\n let body = \"\";\n try {\n body = (await res.text()).slice(0, 2000);\n } catch {\n body = \"<failed to read response body>\";\n }\n return new Error(\n `Jupiter quoteGet http=${res.status} ${res.statusText} request=${JSON.stringify(request)} body=${body} (was: ${err.message})`\n );\n}\n\n/**\n * Build a Jupiter swap transaction from a quote.\n *\n * @param params - Swap parameters including quote and user public key\n * @returns Kit Transaction ready for signing or instruction extraction\n *\n * @example\n * ```typescript\n * const quote = await getJupiterQuote({ ... });\n * const tx = await buildJupiterSwapTransaction({\n * quote,\n * userPublicKey: myPdaAddress, // Can be a PDA for CPI\n * });\n * ```\n */\nexport async function buildJupiterSwapTransaction(params: JupiterSwapParams): Promise<Transaction> {\n const jupiterApi = createJupiterApiClient({ basePath: JUPITER_API_URL });\n\n const swapResult = await jupiterApi.swapPost({\n swapRequest: {\n quoteResponse: params.quote,\n userPublicKey: params.userPublicKey,\n wrapAndUnwrapSol: params.wrapAndUnwrapSol ?? false, // Default false for CPI\n dynamicComputeUnitLimit: params.dynamicComputeUnitLimit ?? true,\n },\n });\n\n // Jupiter returns a base64-encoded serialized transaction\n // In Kit, \"encoder\" converts string -> bytes, \"decoder\" converts bytes -> string\n const base64Encoder = getBase64Encoder();\n const transactionBytes = base64Encoder.encode(swapResult.swapTransaction);\n\n const transactionDecoder = getTransactionDecoder();\n return transactionDecoder.decode(transactionBytes);\n}\n\n/**\n * Convenience function to get quote and build transaction in one call.\n *\n * @param quoteParams - Quote parameters\n * @param userPublicKey - Address that will execute the swap\n * @param swapOptions - Additional swap options\n * @returns Quote response and Kit transaction\n *\n * @example\n * ```typescript\n * const { quote, transaction } = await getJupiterSwapTransaction(\n * {\n * inputMint: address(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"),\n * outputMint: address(\"So11111111111111111111111111111111111111112\"),\n * amount: 1000_000,\n * },\n * myPdaAddress\n * );\n * ```\n */\nexport async function getJupiterSwapTransaction(\n quoteParams: JupiterQuoteParams,\n userPublicKey: Address,\n swapOptions?: Omit<JupiterSwapParams, \"quote\" | \"userPublicKey\">\n): Promise<{ quote: QuoteResponse; transaction: Transaction }> {\n const quote = await getJupiterQuote(quoteParams);\n const transaction = await buildJupiterSwapTransaction({\n quote,\n userPublicKey,\n ...swapOptions,\n });\n\n return { quote, transaction };\n}\n","import type { Address, Instruction, Rpc, SolanaRpcApi, Transaction } from \"@solana/kit\";\nimport {\n decompileTransactionMessageFetchingLookupTables,\n getCompiledTransactionMessageDecoder,\n} from \"@solana/kit\";\nimport { CustomAccountMeta } from \"common\";\nimport { JUPITER_V6_PROGRAM_ID } from \"./constants\";\nimport type { ExtractedJupiterInstruction } from \"./types\";\n\n/**\n * Extract Jupiter instruction data and accounts from a Kit transaction.\n *\n * This function decompiles a Jupiter swap transaction, resolves any address lookup tables,\n * and extracts the instruction data and account metas needed for CPI calls.\n *\n * @param transaction - The Kit Transaction from Jupiter API\n * @param rpc - Solana RPC client to resolve lookup tables\n * @param jupiterProgramId - Jupiter program ID (default: JUPITER_V6_PROGRAM_ID)\n * @returns Jupiter instruction data and account metas with writability info\n * @throws Error if Jupiter instruction is not found in transaction\n *\n * @example\n * ```typescript\n * // Get transaction from Jupiter API\n * const jupiterTx = await buildJupiterSwapTransaction({ quote, userPublicKey });\n *\n * // Extract instruction for CPI\n * const { data, accounts } = await extractJupiterInstruction(jupiterTx, rpc);\n *\n * // Use in your program\n * await program.methods\n * .executeSwap({ jupiterSwapData: Array.from(data) })\n * .remainingAccounts(accounts)\n * .rpc();\n * ```\n */\nexport async function extractJupiterInstruction(\n transaction: Transaction,\n rpc: Rpc<SolanaRpcApi>,\n jupiterProgramId: Address = JUPITER_V6_PROGRAM_ID\n): Promise<ExtractedJupiterInstruction> {\n // Decode the message bytes to a CompiledTransactionMessage\n const messageDecoder = getCompiledTransactionMessageDecoder();\n const compiledMessage = messageDecoder.decode(transaction.messageBytes);\n\n // Extract lookup table addresses from the compiled message before decompiling\n const lookupTables: Address[] = (\n \"addressTableLookups\" in compiledMessage ? (compiledMessage.addressTableLookups ?? []) : []\n ).map((lookup) => lookup.lookupTableAddress);\n\n // Decompile the transaction message, fetching any lookup tables needed\n const decompiledMessage = await decompileTransactionMessageFetchingLookupTables(\n compiledMessage,\n rpc\n );\n\n // Find the Jupiter instruction\n const jupiterIx = decompiledMessage.instructions.find(\n (ix: Instruction) => ix.programAddress === jupiterProgramId\n );\n\n if (!jupiterIx) {\n throw new Error(\"Jupiter instruction not found in transaction\");\n }\n\n // Convert instruction accounts to AccountMeta format\n const accounts: CustomAccountMeta[] = (jupiterIx.accounts ?? []).map(\n (account: CustomAccountMeta) => ({\n address: account.address,\n role: account.role,\n })\n );\n\n // Return instruction data, accounts, and lookup tables\n return {\n data: new Uint8Array(jupiterIx.data ?? []),\n accounts,\n lookupTables,\n };\n}\n","import type { Address, Instruction, Rpc, SolanaRpcApi } from \"@solana/kit\";\nimport type { QuoteResponse } from \"@jup-ag/api\";\nimport { getCreateAtaIxIfNeeded, mints, type TransactionCacheInvalidation } from \"common\";\n\nexport interface JupiterRoutePreInstructionsResult {\n instructions: Instruction[];\n postSuccessCacheInvalidations: TransactionCacheInvalidation[];\n}\n\n/**\n * Build idempotent createATA instructions for every intermediate-mint touched\n * by a Jupiter route that the swap authority (`user`) doesn't already have an\n * ATA for. Input/output mints are excluded — the caller is expected to have\n * already provisioned those (e.g. flash-borrow lands the input balance in\n * the user's destDebt ATA).\n *\n * Token programs are resolved via the {@link mints} registry first; unknown\n * mints fall back to an RPC `getMultipleAccounts` lookup that reads each\n * mint's `owner` (the SPL Token vs Token-2022 program).\n */\nexport async function getJupiterRoutePreInstructions(\n rpc: Rpc<SolanaRpcApi>,\n quote: QuoteResponse,\n user: Address,\n payer: Address\n): Promise<JupiterRoutePreInstructionsResult> {\n const intermediate = new Set<Address>();\n for (const step of quote.routePlan ?? []) {\n intermediate.add(step.swapInfo.inputMint as Address);\n intermediate.add(step.swapInfo.outputMint as Address);\n }\n intermediate.delete(quote.inputMint as Address);\n intermediate.delete(quote.outputMint as Address);\n if (!intermediate.size) {\n return { instructions: [], postSuccessCacheInvalidations: [] };\n }\n\n const tokenProgramByMint = new Map<Address, Address>();\n const unknown: Address[] = [];\n for (const mint of intermediate) {\n const info = mints.get(mint);\n if (info) {\n tokenProgramByMint.set(mint, info.tokenProgram);\n } else {\n unknown.push(mint);\n }\n }\n\n if (unknown.length) {\n const resp = await (\n rpc as Rpc<SolanaRpcApi> & {\n getMultipleAccounts: (\n addrs: Address[],\n config: { encoding: \"base64\" }\n ) => { send(): Promise<{ value: Array<{ owner: Address } | null> }> };\n }\n )\n .getMultipleAccounts(unknown, { encoding: \"base64\" })\n .send();\n for (let i = 0; i < unknown.length; i += 1) {\n const acct = resp.value[i];\n if (!acct) {\n throw new Error(\n `getJupiterRoutePreInstructions: route mint ${unknown[i]} not found on-chain`\n );\n }\n tokenProgramByMint.set(unknown[i], acct.owner);\n }\n }\n\n const instructions: Instruction[] = [];\n const postSuccessCacheInvalidations: TransactionCacheInvalidation[] = [];\n for (const mint of intermediate) {\n const tokenProgram = tokenProgramByMint.get(mint)!;\n const result = await getCreateAtaIxIfNeeded(rpc, payer, mint, user, tokenProgram);\n if (result.instruction) {\n instructions.push(result.instruction);\n postSuccessCacheInvalidations.push(...result.postSuccessCacheInvalidations);\n }\n }\n\n return { instructions, postSuccessCacheInvalidations };\n}\n","import { type Address, type Instruction, type Rpc, type SolanaRpcApi } from \"@solana/kit\";\nimport type { QuoteResponse } from \"@jup-ag/api\";\nimport { getJupiterQuote, buildJupiterSwapTransaction } from \"./api\";\nimport { extractJupiterInstruction } from \"./extract\";\nimport { getJupiterRoutePreInstructions } from \"./routePreInstructions\";\nimport { JUPITER_V6_PROGRAM_ID } from \"./constants\";\nimport type { JupiterSwapClientConfig } from \"./types\";\nimport {\n CpiTypes,\n CpiData,\n RoutableSwapClient,\n SwapQuoteParams,\n SwapQuote,\n SwapQuoteCoveringMinOutputParams,\n SwapInstructionOptions,\n} from \"common\";\n\n/** Jupiter-specific swap quote with typed rawQuote */\nexport type JupiterSwapQuote = SwapQuote<QuoteResponse>;\n\n/**\n * Jupiter swap client implementing RoutableSwapClient (see `common`).\n *\n * Provides a simplified API for getting quotes and building swap instructions\n * from Jupiter aggregator for use in CPI calls.\n *\n * @example\n * ```typescript\n * const client = new JupiterSwapClient(rpc);\n *\n * // Get a quote\n * const quote = await client.getQuote({\n * inputMint: USDC_MINT,\n * outputMint: WSOL_MINT,\n * amount: 10_000_000, // 10 USDC\n * slippageBps: 500, // 5%\n * });\n *\n * // Build instruction for CPI\n * const { data, accounts, programId } = await client.getSwapCpiData(\n * quote,\n * swapAuthorityPda\n * );\n *\n * // Use in your Anchor program\n * await program.methods\n * .executeSwap(Buffer.from(data))\n * .remainingAccounts(accounts.map(toWeb3AccountMeta))\n * .rpc();\n * ```\n */\nexport class JupiterSwapClient implements RoutableSwapClient<QuoteResponse> {\n /**\n * Empty lists mean any route for aggregate routing (Jupiter quotes arbitrary\n * pairs via the API).\n */\n readonly inputMints: readonly Address[] = [];\n readonly outputMints: readonly Address[] = [];\n readonly routeAnchorMints: readonly Address[] = [];\n\n /**\n * Creates a new Jupiter swap client.\n *\n * @param rpc - Solana RPC client for resolving address lookup tables\n * @param config - Optional default quote policy applied to every Jupiter quote\n */\n constructor(\n private rpc: Rpc<SolanaRpcApi>,\n private readonly config: JupiterSwapClientConfig = {}\n ) {}\n\n /**\n * Get a swap quote from Jupiter.\n *\n * @param params - Quote parameters\n * @returns Normalized swap quote with Jupiter's QuoteResponse as rawQuote\n */\n async getQuote(params: SwapQuoteParams): Promise<JupiterSwapQuote> {\n const excludeDexes = params.excludeDexes?.length\n ? [...new Set([...(this.config.quoteDefaults?.excludeDexes ?? []), ...params.excludeDexes])]\n : undefined;\n const rawQuote = await getJupiterQuote({\n ...(this.config.quoteDefaults ?? {}),\n inputMint: params.inputMint,\n outputMint: params.outputMint,\n amount: params.amount,\n slippageBps: params.slippageBps,\n ...(params.maxAccounts !== undefined ? { maxAccounts: params.maxAccounts } : {}),\n ...(params.onlyDirectRoutes !== undefined\n ? { onlyDirectRoutes: params.onlyDirectRoutes }\n : {}),\n ...(excludeDexes ? { excludeDexes } : {}),\n });\n\n return {\n inputMint: params.inputMint,\n outputMint: params.outputMint,\n inputAmount: BigInt(rawQuote.inAmount),\n outputAmount: BigInt(rawQuote.outAmount),\n priceImpactPct: Number(rawQuote.priceImpactPct ?? 0),\n rawQuote,\n };\n }\n\n /**\n * Use Jupiter `ExactOut` quoting: desired output is `minOutputAmount`; reject if implied\n * input exceeds `maxInputAmount`.\n */\n async getQuoteCoveringMinOutput(\n params: SwapQuoteCoveringMinOutputParams\n ): Promise<JupiterSwapQuote> {\n const need = params.minOutputAmount;\n if (need <= BigInt(0)) {\n throw new Error(\"getQuoteCoveringMinOutput: minOutputAmount must be positive\");\n }\n const maxIn = params.maxInputAmount;\n if (maxIn <= BigInt(0)) {\n throw new Error(\"getQuoteCoveringMinOutput: maxInputAmount must be positive\");\n }\n if (need > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(\"getQuoteCoveringMinOutput: minOutputAmount exceeds Number.MAX_SAFE_INTEGER\");\n }\n\n const rawQuote = await getJupiterQuote({\n ...(this.config.quoteDefaults ?? {}),\n inputMint: params.inputMint,\n outputMint: params.outputMint,\n amount: Number(need),\n slippageBps: params.slippageBps,\n swapMode: \"ExactOut\",\n });\n\n const inAmt = BigInt(rawQuote.inAmount);\n const outAmt = BigInt(rawQuote.outAmount);\n if (inAmt > maxIn) {\n throw new Error(\n \"Jupiter getQuoteCoveringMinOutput: exact-out route needs more input than maxInputAmount\"\n );\n }\n if (outAmt < need) {\n throw new Error(\"Jupiter getQuoteCoveringMinOutput: quoted output is below minOutputAmount\");\n }\n\n return {\n inputMint: params.inputMint,\n outputMint: params.outputMint,\n inputAmount: inAmt,\n outputAmount: outAmt,\n priceImpactPct: Number(rawQuote.priceImpactPct ?? 0),\n rawQuote,\n };\n }\n\n /**\n * Build Jupiter swap instruction for CPI.\n *\n * This fetches a swap transaction from Jupiter API, decompiles it,\n * and extracts the instruction data and accounts needed for CPI.\n *\n * @param quote - Quote from getQuote()\n * @param userPublicKey - Address executing the swap (typically a PDA)\n * @param options - Swap options\n * @returns Instruction data, accounts, and Jupiter program ID\n */\n async getSwapCpiData(\n quote: JupiterSwapQuote,\n userPublicKey: Address,\n options?: SwapInstructionOptions\n ): Promise<CpiData> {\n const transaction = await buildJupiterSwapTransaction({\n quote: quote.rawQuote,\n userPublicKey,\n wrapAndUnwrapSol: options?.wrapAndUnwrapSol ?? false,\n });\n\n const { data, accounts, lookupTables } = await extractJupiterInstruction(transaction, this.rpc);\n\n // When a `payer` is supplied we provision intermediate-mint ATAs for\n // multi-hop routes; the swap authority `userPublicKey` is typically a PDA\n // and can't pay the rent itself. With no payer we skip pre-instructions\n // (single-hop routes don't need them; multi-hop routes will then fail\n // at the CPI if intermediate ATAs are missing).\n let preInstructions: Instruction[] | undefined;\n let preInvalidations: NonNullable<CpiData[\"postSuccessCacheInvalidations\"]> | undefined;\n if (options?.payer) {\n const result = await getJupiterRoutePreInstructions(\n this.rpc,\n quote.rawQuote,\n userPublicKey,\n options.payer\n );\n if (result.instructions.length) {\n preInstructions = result.instructions;\n preInvalidations = result.postSuccessCacheInvalidations;\n }\n }\n\n return {\n cpiType: CpiTypes.JUPITER_SWAP,\n data,\n accounts,\n programId: JUPITER_V6_PROGRAM_ID,\n lookupTables,\n ...(preInstructions ? { preInstructions } : {}),\n ...(preInvalidations ? { postSuccessCacheInvalidations: preInvalidations } : {}),\n };\n }\n}\n","import type { Address } from \"@solana/kit\";\nimport type { SwapClient, SwapQuote } from \"common\";\n\nexport class ExactInQuoteExceedsMaxInputError extends Error {\n constructor(\n readonly inputAmount: bigint,\n readonly maxInputAmount: bigint\n ) {\n super(\n `sizeExactInForMinOutput: sized input (${inputAmount}) exceeds maxInputAmount (${maxInputAmount})`\n );\n this.name = \"ExactInQuoteExceedsMaxInputError\";\n }\n}\n\nexport interface SizeExactInForMinOutputParams {\n /** Input mint of the swap. */\n inputMint: Address;\n /** Output mint of the swap. */\n outputMint: Address;\n /** Minimum acceptable output amount (smallest units of `outputMint`). */\n minOutputAmount: bigint;\n /**\n * Maximum input amount the caller is willing to spend (smallest units of\n * `inputMint`). Throws if the sized input would exceed this.\n */\n maxInputAmount: bigint;\n /** Slippage tolerance applied by the swap, in basis points (e.g. 50 = 0.5%). */\n slippageBps: number;\n /**\n * Extra bps of headroom added on top of slippage when sizing the input.\n * The worst-case post-slippage output is pushed above `minOutputAmount`\n * by this much. Defaults to 0 (size to bare minimum).\n */\n safetyBufferBps?: number;\n /**\n * If true, restrict the quotes to direct routes (no intermediate hops).\n * Useful for CPI flows where intermediate-mint ATAs (e.g. WSOL) wouldn't\n * exist for a PDA caller. Defaults to false.\n */\n onlyDirectRoutes?: boolean;\n /** Optional route account budget forwarded to backends that support it. */\n maxAccounts?: number;\n /** DEX labels to exclude from routing, forwarded to backends that support it. */\n excludeDexes?: string[];\n}\n\nexport interface SizeExactInForMinOutputResult<TRawQuote = unknown> {\n /** ExactIn quote sized so the worst-case output covers `minOutputAmount`. */\n quote: SwapQuote<TRawQuote>;\n /** The sized input amount in `inputMint` base units (== `quote.inputAmount`). */\n inputAmount: bigint;\n /** The minimum output the caller can rely on after applying slippage. */\n worstCaseOutputAmount: bigint;\n}\n\n/**\n * Size an ExactIn swap so its **worst-case post-slippage output** covers\n * `minOutputAmount`.\n *\n * The ExactIn route graph is denser than ExactOut on most aggregators\n * (Jupiter included), so this is preferred when ExactOut hits\n * `NO_ROUTES_FOUND`. The trade-off: you over-spend input by the slippage\n * buffer; the unused output excess is the caller's to handle (e.g. sweep\n * to a sink account).\n *\n * Strategy:\n * 1. Probe quote at `minOutputAmount` input — gives us the route's\n * spot rate (`probeOut / probeIn`).\n * 2. Solve for the input `I` such that\n * `I × probeOut/probeIn × (1 − slippageBps/10000) ≥ minOutputAmount × (1 + safetyBufferBps/10000)`.\n * 3. Real ExactIn quote at the sized input.\n * 4. Verify the real quote's worst-case output still covers\n * `minOutputAmount` — guards against price impact at the larger size\n * diverging from the probe's spot rate.\n *\n * Throws if `inputAmount` exceeds `maxInputAmount`, if `slippageBps` is\n * out of range, or if the verification in step 4 fails.\n */\nexport async function sizeExactInForMinOutput<TRawQuote = unknown>(\n swap: SwapClient<TRawQuote>,\n params: SizeExactInForMinOutputParams\n): Promise<SizeExactInForMinOutputResult<TRawQuote>> {\n const {\n inputMint,\n outputMint,\n minOutputAmount,\n maxInputAmount,\n slippageBps,\n safetyBufferBps = 0,\n onlyDirectRoutes,\n maxAccounts,\n excludeDexes,\n } = params;\n\n if (minOutputAmount <= 0n) {\n throw new Error(\"sizeExactInForMinOutput: minOutputAmount must be positive\");\n }\n if (maxInputAmount <= 0n) {\n throw new Error(\"sizeExactInForMinOutput: maxInputAmount must be positive\");\n }\n if (slippageBps < 0 || slippageBps >= 10_000) {\n throw new Error(\"sizeExactInForMinOutput: slippageBps must be in [0, 10000)\");\n }\n if (safetyBufferBps < 0) {\n throw new Error(\"sizeExactInForMinOutput: safetyBufferBps must be non-negative\");\n }\n if (minOutputAmount > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(\"sizeExactInForMinOutput: minOutputAmount exceeds Number.MAX_SAFE_INTEGER\");\n }\n\n const probeQuote = await swap.getQuote({\n inputMint,\n outputMint,\n amount: Number(minOutputAmount),\n slippageBps,\n onlyDirectRoutes,\n maxAccounts,\n excludeDexes,\n });\n if (probeQuote.outputAmount <= 0n || probeQuote.inputAmount <= 0n) {\n throw new Error(\"sizeExactInForMinOutput: probe quote returned non-positive amounts\");\n }\n\n // I = ceil(minOutput × probeIn × (10000 + safetyBufferBps) /\n // (probeOut × (10000 - slippageBps)))\n const slippageBpsBig = BigInt(slippageBps);\n const safetyBpsBig = BigInt(safetyBufferBps);\n const sizingNumer = minOutputAmount * probeQuote.inputAmount * (10_000n + safetyBpsBig);\n const sizingDenom = probeQuote.outputAmount * (10_000n - slippageBpsBig);\n const inputAmount = (sizingNumer + sizingDenom - 1n) / sizingDenom;\n\n if (inputAmount > maxInputAmount) {\n throw new ExactInQuoteExceedsMaxInputError(inputAmount, maxInputAmount);\n }\n if (inputAmount > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(\"sizeExactInForMinOutput: sized input exceeds Number.MAX_SAFE_INTEGER\");\n }\n\n const quote = await swap.getQuote({\n inputMint,\n outputMint,\n amount: Number(inputAmount),\n slippageBps,\n onlyDirectRoutes,\n maxAccounts,\n excludeDexes,\n });\n\n const worstCaseOutputAmount = (quote.outputAmount * (10_000n - slippageBpsBig)) / 10_000n;\n if (worstCaseOutputAmount < minOutputAmount) {\n throw new Error(\n `sizeExactInForMinOutput: real-quote worst-case output (${worstCaseOutputAmount}) ` +\n `does not cover minOutputAmount (${minOutputAmount}) — likely price impact at sized input ` +\n `diverged from probe spot rate; raise safetyBufferBps`\n );\n }\n\n return { quote, inputAmount, worstCaseOutputAmount };\n}\n","import { BN } from \"@anchor-lang/core\";\nimport { type Address } from \"@solana/kit\";\nimport { fromUiAmount, toUiAmount, type Environment } from \"common\";\nimport type { PriceResult } from \"oracle-service\";\nimport { LendingPlatformData } from \"../../data/platform/lpDataBase\";\nimport { ReserveBase } from \"../../data/reserve/reserveBase\";\nimport { UserPositionBase } from \"../../data/userPosition/userPositionBase\";\nimport { MAX_LENDING_POSITION_UPPER_UTIL_BPS } from \"../../constants/lendingPosition\";\nimport { ReservesManager, type ReservesPrices } from \"../reservesManager\";\nimport type {\n CollateralPriceTriggerBand,\n CollateralPriceTriggerLevel,\n LendingPositionInspectMetrics,\n LendingPositionSelectedPrice,\n LendingPositionState,\n LendingPositionUtilizationPrices,\n LendingPositionUtilizationRatesBps,\n} from \"./types\";\n\n/**\n * Manages a leveraged lending position (collateral/debt pair): sizing decisions,\n * threshold triggers, and realtime/EMA-priced state. Wraps a {@link ReservesManager}.\n *\n * Generic across protocols — the constructor takes pool + user-account addresses\n * directly. SDK-specific subclasses may add convenience wrappers that derive\n * targets from their own on-chain config.\n */\nexport class LendingPositionManager {\n readonly reservesManager: ReservesManager;\n\n constructor(\n readonly lpData: LendingPlatformData,\n readonly pool: Address,\n readonly userAccount: Address,\n collateralReserve: ReserveBase,\n debtReserve: ReserveBase,\n environment?: Environment\n ) {\n this.reservesManager = new ReservesManager(collateralReserve, debtReserve, environment);\n }\n\n /**\n * Calculates the UI debt amount change needed to reach the target LTV utilization\n * rate. Positive values indicate borrowing; negative values indicate repaying.\n */\n async calcDebtChangeAmount(targetUtilizationRateBps: number): Promise<number> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return 0;\n\n return this.calcDebtChangeAmountFromState(state, targetUtilizationRateBps);\n }\n\n /**\n * Fetch current supply and debt position amounts in UI units.\n */\n async getLendingPositionAmounts(): Promise<{\n supplyUiAmount: number;\n debtUiAmount: number;\n }> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return { supplyUiAmount: 0, debtUiAmount: 0 };\n\n const supplyPrice = state.prices.supply.realtimePrice;\n const debtPrice = state.prices.debt.realtimePrice;\n\n return {\n supplyUiAmount: supplyPrice > 0 ? state.supplyUsd / supplyPrice : 0,\n debtUiAmount: debtPrice > 0 ? state.debtUsd / debtPrice : 0,\n };\n }\n\n /**\n * Calculates the utilization rate the source position must reach before a\n * collateral withdrawal so that, after the withdrawal, the position lands at\n * the desired target utilization rate.\n *\n * Units:\n * - current supply USD = supplied collateral before withdrawal\n * - withdrawn USD = collateral requested for the rebalance move\n * - post-withdraw target = desired utilization after collateral leaves the LP\n *\n * Formula:\n * pre_withdraw_target = post_withdraw_target * (current_supply - withdrawn) / current_supply\n *\n * The result is floored to stay conservatively at or below the requested\n * post-withdraw target once integer basis-point rounding is applied.\n */\n async calcPreWithdrawalTargetUtilizationRateBps(\n withdrawUiCollateralAmount: number,\n postWithdrawalTargetUtilizationRateBps: number\n ): Promise<number> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return 0;\n\n return this.calcPreWithdrawalTargetUtilizationRateBpsFromState(\n state,\n withdrawUiCollateralAmount,\n postWithdrawalTargetUtilizationRateBps\n );\n }\n\n /**\n * Calculates the UI debt amount change needed before a collateral withdrawal\n * so that the position lands at the desired utilization rate after the\n * withdrawal completes.\n */\n async calcDebtChangeAmountForCollateralWithdrawal(\n withdrawUiCollateralAmount: number,\n postWithdrawalTargetUtilizationRateBps: number\n ): Promise<number> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return 0;\n\n const preWithdrawalTargetUtilizationRateBps =\n this.calcPreWithdrawalTargetUtilizationRateBpsFromState(\n state,\n withdrawUiCollateralAmount,\n postWithdrawalTargetUtilizationRateBps\n );\n\n return this.calcDebtChangeAmountFromState(state, preWithdrawalTargetUtilizationRateBps);\n }\n\n /**\n * Calculates the utilization rate after withdrawing collateral while leaving\n * debt unchanged.\n */\n async calcPostWithdrawalUtilizationRateBps(withdrawUiCollateralAmount: number): Promise<number> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return 0;\n\n return this.calcPostWithdrawalUtilizationRateBpsFromState(state, withdrawUiCollateralAmount);\n }\n\n /**\n * For burn-token liquidity management: checks that a withdrawal of\n * `collateralWithdrawalUiAmount` (collateral mint UI units) leaves strictly\n * positive supplied collateral, matching the pre-withdraw math used in\n * {@link calcPreWithdrawalTargetUtilizationRateBps}.\n *\n * Returns realtime LTV utilization in basis points when eligible; null when the\n * obligation is missing, has no supply, prices are invalid, or the withdrawal\n * would consume the full (or more than the full) collateral position.\n */\n async getBurnUnwindEligibility(\n collateralWithdrawalUiAmount: number\n ): Promise<{ utilizationRateBps: number } | null> {\n if (!(collateralWithdrawalUiAmount > 0)) {\n return null;\n }\n const state = await this.getPositionState(\"realtime\");\n if (!state) {\n return null;\n }\n const collateralPrice = state.prices.supply.realtimePrice;\n if (!(collateralPrice > 0)) {\n return null;\n }\n const withdrawnCollateralUsd = collateralWithdrawalUiAmount * collateralPrice;\n if (!(withdrawnCollateralUsd < state.supplyUsd)) {\n return null;\n }\n const utilizationRateBps = this.reservesManager.calcLtvUtilizationRateBps(\n state.supplyUsd,\n state.debtUsd\n );\n return { utilizationRateBps };\n }\n\n /**\n * Returns the collateral price levels that would place the position exactly on\n * its lower and upper utilization trigger bands.\n *\n * The lower-band trigger uses EMA pricing (to mirror boost-trigger semantics),\n * while the upper-band trigger uses realtime pricing (to mirror unwind-trigger\n * semantics).\n */\n async getCollateralPriceTriggerBand(params: {\n lowerTargetUtilizationRateBps: number;\n upperTargetUtilizationRateBps: number;\n }): Promise<CollateralPriceTriggerBand> {\n const [lower, upper] = await Promise.all([\n this.getCollateralPriceTriggerLevel(\"ema\", params.lowerTargetUtilizationRateBps),\n this.getCollateralPriceTriggerLevel(\"realtime\", params.upperTargetUtilizationRateBps),\n ]);\n\n return { lower, upper };\n }\n\n async getUtilizationRatesBps(): Promise<LendingPositionUtilizationRatesBps | null> {\n const [realtimeState, emaState] = await Promise.all([\n this.getPositionState(\"realtime\"),\n this.getPositionState(\"ema\"),\n ]);\n if (!realtimeState || !emaState) {\n return null;\n }\n\n return {\n realtime: this.reservesManager.calcLtvUtilizationRateBps(\n realtimeState.supplyUsd,\n realtimeState.debtUsd\n ),\n ema: this.reservesManager.calcLtvUtilizationRateBps(emaState.supplyUsd, emaState.debtUsd),\n };\n }\n\n async getUtilizationPrices(): Promise<LendingPositionUtilizationPrices | null> {\n const [realtimeState, emaState] = await Promise.all([\n this.getPositionState(\"realtime\"),\n this.getPositionState(\"ema\"),\n ]);\n if (!realtimeState || !emaState) {\n return null;\n }\n\n return {\n realtime: {\n collateral: this.selectPrice(realtimeState.prices.supply, \"realtime\"),\n debt: this.selectPrice(realtimeState.prices.debt, \"realtime\"),\n },\n ema: {\n collateral: this.selectPrice(emaState.prices.supply, \"ema\"),\n debt: this.selectPrice(emaState.prices.debt, \"ema\"),\n },\n };\n }\n\n async getInspectMetrics(params: {\n lowerTargetUtilizationRateBps: number;\n upperTargetUtilizationRateBps: number;\n }): Promise<LendingPositionInspectMetrics | null> {\n const [utilizationRateBps, utilizationPrices, triggerBand] = await Promise.all([\n this.getUtilizationRatesBps(),\n this.getUtilizationPrices(),\n this.getCollateralPriceTriggerBand(params),\n ]);\n if (!utilizationRateBps || !utilizationPrices) {\n return null;\n }\n\n return { utilizationRateBps, utilizationPrices, triggerBand };\n }\n\n protected async getPositionState(mode: \"realtime\" | \"ema\"): Promise<LendingPositionState | null> {\n const position = await this.lpData.maybeFetchUserPositionInPool(this.pool, this.userAccount);\n if (!position) return null;\n\n const prices = await this.reservesManager.prices();\n const { supplyUsd, debtUsd } = this.calcPositionSupplyDebtUsd(position, prices, mode);\n return { prices, supplyUsd, debtUsd };\n }\n\n private calcPositionSupplyDebtUsd(\n position: UserPositionBase,\n prices: ReservesPrices,\n mode: \"realtime\" | \"ema\"\n ): { supplyUsd: number; debtUsd: number } {\n const { supplyReserve, debtReserve } = this.reservesManager;\n\n const deposit = position.deposits.find((d) => d.reserve === supplyReserve.address);\n const borrow = position.borrows.find((b) => b.reserve === debtReserve.address);\n\n const supplyAmount = deposit ? toUiAmount(deposit.amount, supplyReserve.mint.mintDecimals) : 0;\n const debtAmount = borrow ? toUiAmount(borrow.amount, debtReserve.mint.mintDecimals) : 0;\n\n return {\n supplyUsd: supplyAmount * this.selectPrice(prices.supply, mode).value,\n debtUsd: debtAmount * this.selectPrice(prices.debt, mode).value,\n };\n }\n\n private selectPrice(price: PriceResult, mode: \"realtime\" | \"ema\"): LendingPositionSelectedPrice {\n if (mode === \"realtime\") {\n return { value: price.realtimePrice, source: \"realtime\" };\n }\n\n if (price.emaPrice != null) {\n return { value: price.emaPrice, source: \"ema\" };\n }\n\n return { value: price.realtimePrice, source: \"ema_fallback_realtime\" };\n }\n\n private async getCollateralPriceTriggerLevel(\n mode: \"realtime\" | \"ema\",\n targetUtilizationRateBps: number\n ): Promise<CollateralPriceTriggerLevel | undefined> {\n this.assertValidTriggerBandUtilizationRateBps(\n targetUtilizationRateBps,\n \"targetUtilizationRateBps\"\n );\n if (targetUtilizationRateBps === 0) {\n return undefined;\n }\n\n const state = await this.getPositionState(mode);\n if (!state) {\n return undefined;\n }\n\n const currentCollateralPrice =\n mode === \"ema\"\n ? (state.prices.supply.emaPrice ?? state.prices.supply.realtimePrice)\n : state.prices.supply.realtimePrice;\n\n if (currentCollateralPrice <= 0 || state.debtUsd < 0 || this.reservesManager.maxLtv <= 0) {\n return undefined;\n }\n\n const uiSupplyAmount = state.supplyUsd / currentCollateralPrice;\n if (uiSupplyAmount <= 0) {\n return undefined;\n }\n\n const triggerCollateralPrice = this.calcCollateralPriceForTargetUtilization(\n state.debtUsd,\n uiSupplyAmount,\n targetUtilizationRateBps\n );\n\n if (!Number.isFinite(triggerCollateralPrice) || triggerCollateralPrice < 0) {\n return undefined;\n }\n\n return {\n currentCollateralPrice,\n triggerCollateralPrice,\n targetUtilizationRateBps,\n priceMode: mode,\n priceChangePct:\n ((triggerCollateralPrice - currentCollateralPrice) / currentCollateralPrice) * 100,\n };\n }\n\n /**\n * Solve for collateral price at a target utilization:\n * utilization = debtUsd / (collateralAmount * collateralPrice * maxLtv).\n */\n private calcCollateralPriceForTargetUtilization(\n debtUsd: number,\n uiSupplyAmount: number,\n targetUtilizationRateBps: number\n ): number {\n const targetUtilizationRate = targetUtilizationRateBps / 10_000;\n return debtUsd / (uiSupplyAmount * this.reservesManager.maxLtv * targetUtilizationRate);\n }\n\n private async calcDebtChangeAmountFromState(\n state: LendingPositionState,\n targetUtilizationRateBps: number\n ): Promise<number> {\n this.assertValidUtilizationRateBps(targetUtilizationRateBps, \"targetUtilizationRateBps\");\n\n if (state.prices.debt.realtimePrice <= 0) {\n throw new Error(\"Debt reserve realtime price must be positive\");\n }\n if (state.prices.supply.realtimePrice <= 0) {\n throw new Error(\"Collateral reserve realtime price must be positive\");\n }\n\n const debtAdjustmentUsd = await this.reservesManager.calcDebtAdjustmentUsd(\n state.supplyUsd / state.prices.supply.realtimePrice,\n state.debtUsd / state.prices.debt.realtimePrice,\n targetUtilizationRateBps,\n { positionChangeMode: \"debtOnly\" }\n );\n\n const debtChangeUiAmount = debtAdjustmentUsd / state.prices.debt.realtimePrice;\n const debtDecimals = this.reservesManager.debtReserve.mint.mintDecimals;\n\n let quantizedUiAmount = this.quantizeDebtChangeUiAmount(debtChangeUiAmount, debtDecimals);\n if (quantizedUiAmount > 0) {\n quantizedUiAmount = await this.capPositiveBorrowToProtocolHeadroom(quantizedUiAmount, state);\n }\n\n return debtChangeUiAmount < 0 ? -quantizedUiAmount : quantizedUiAmount;\n }\n\n /**\n * Quantize to the debt mint's base-unit precision. Borrows floor; repays round\n * away from zero so deleveraging does not undershoot.\n */\n private quantizeDebtChangeUiAmount(debtChangeUiAmount: number, debtDecimals: number): number {\n if (debtChangeUiAmount === 0) return 0;\n\n const absUi = Math.abs(debtChangeUiAmount);\n\n if (debtChangeUiAmount > 0) {\n if (!(absUi > 0)) return 0;\n const flooredBaseUnits = new BN(Math.floor(absUi * Math.pow(10, debtDecimals)));\n return toUiAmount(flooredBaseUnits, debtDecimals);\n }\n\n const roundedAmount = fromUiAmount(absUi, debtDecimals);\n let repayUi = toUiAmount(roundedAmount, debtDecimals);\n if (repayUi < absUi) {\n repayUi = toUiAmount(roundedAmount.addn(1), debtDecimals);\n }\n return repayUi;\n }\n\n /** Cap positive borrows to obligation headroom when the platform exposes it. */\n private async capPositiveBorrowToProtocolHeadroom(\n requestedUiAmount: number,\n state: LendingPositionState\n ): Promise<number> {\n const debtDecimals = this.reservesManager.debtReserve.mint.mintDecimals;\n const position = await this.lpData.maybeFetchUserPositionInPool(this.pool, this.userAccount);\n if (!position) {\n return requestedUiAmount;\n }\n\n const maxUi = position.getMaxAdditionalBorrowUiAmount(\n state.prices.debt.realtimePrice,\n debtDecimals\n );\n if (maxUi === undefined) {\n return requestedUiAmount;\n }\n return Math.min(requestedUiAmount, maxUi);\n }\n\n private calcPreWithdrawalTargetUtilizationRateBpsFromState(\n state: LendingPositionState,\n withdrawUiCollateralAmount: number,\n postWithdrawalTargetUtilizationRateBps: number\n ): number {\n if (withdrawUiCollateralAmount <= 0) {\n throw new Error(\"withdrawUiCollateralAmount must be greater than zero\");\n }\n this.assertValidUtilizationRateBps(\n postWithdrawalTargetUtilizationRateBps,\n \"postWithdrawalTargetUtilizationRateBps\"\n );\n\n const collateralPrice = state.prices.supply.realtimePrice;\n if (collateralPrice <= 0) {\n throw new Error(\"Collateral reserve realtime price must be positive\");\n }\n\n const withdrawnCollateralUsd = withdrawUiCollateralAmount * collateralPrice;\n if (withdrawnCollateralUsd >= state.supplyUsd) {\n throw new Error(\"withdrawUiCollateralAmount exceeds the current supplied collateral\");\n }\n\n const preWithdrawalTargetUtilizationRateBps = Math.floor(\n (postWithdrawalTargetUtilizationRateBps * (state.supplyUsd - withdrawnCollateralUsd)) /\n state.supplyUsd\n );\n\n return Math.max(\n 0,\n Math.min(postWithdrawalTargetUtilizationRateBps, preWithdrawalTargetUtilizationRateBps)\n );\n }\n\n private calcPostWithdrawalUtilizationRateBpsFromState(\n state: LendingPositionState,\n withdrawUiCollateralAmount: number\n ): number {\n if (withdrawUiCollateralAmount <= 0) {\n throw new Error(\"withdrawUiCollateralAmount must be greater than zero\");\n }\n\n const collateralPrice = state.prices.supply.realtimePrice;\n if (collateralPrice <= 0) {\n throw new Error(\"Collateral reserve realtime price must be positive\");\n }\n\n const withdrawnCollateralUsd = withdrawUiCollateralAmount * collateralPrice;\n if (withdrawnCollateralUsd >= state.supplyUsd) {\n throw new Error(\"withdrawUiCollateralAmount exceeds the current supplied collateral\");\n }\n\n return this.reservesManager.calcLtvUtilizationRateBps(\n state.supplyUsd - withdrawnCollateralUsd,\n state.debtUsd\n );\n }\n\n protected assertValidUtilizationRateBps(value: number, field: string) {\n if (!Number.isFinite(value) || value < 0 || value > 10_000) {\n throw new Error(`${field} must be between 0 and 10000`);\n }\n }\n\n /**\n * Unwind/boost trigger bands may exceed 100% LTV utilization (up to 10_500 bps\n * on-chain). Debt-sizing paths still use {@link assertValidUtilizationRateBps}.\n */\n protected assertValidTriggerBandUtilizationRateBps(value: number, field: string) {\n if (!Number.isFinite(value) || value < 0 || value > MAX_LENDING_POSITION_UPPER_UTIL_BPS) {\n throw new Error(`${field} must be between 0 and ${MAX_LENDING_POSITION_UPPER_UTIL_BPS}`);\n }\n }\n}\n","import type { Address } from \"@solana/kit\";\nimport { DataCache, type Environment } from \"common\";\nimport { oracle, PriceResult } from \"oracle-service\";\nimport { ReserveBase } from \"../data\";\nimport { PositionBalanceChange } from \"../types\";\n\nexport interface ReservesPrices {\n supply: PriceResult;\n debt: PriceResult;\n}\n\nexport interface DebtAdjustmentOptions {\n /**\n * How the position changes when debt is adjusted.\n * `levered` models a loop / flash-loan rebalance where borrowed funds also\n * increase supplied collateral.\n * `debtOnly` models changes such as carry-position borrows where only debt\n * changes and supplied collateral stays constant.\n */\n positionChangeMode?: \"levered\" | \"debtOnly\";\n}\n\n/**\n * Manages a supply/debt reserve pair and provides calculations\n * for APY, simulations, and debt adjustments.\n */\nexport class ReservesManager {\n private cache = new DataCache();\n\n constructor(\n public supplyReserve: ReserveBase,\n public debtReserve: ReserveBase,\n private environment?: Environment\n ) {}\n\n /** Max LTV ratio (0-1), using e-mode override when the pair qualifies */\n get maxLtv(): number {\n const emode = this.supplyReserve.emodes?.find(\n (e) => e.debtReserve === this.debtReserve.address\n );\n return emode?.ltvPct ?? this.supplyReserve.ltvPct;\n }\n\n /**\n * Returns supply and debt token prices.\n * Uses reserve-embedded prices when available, otherwise fetches from oracle and caches the result.\n */\n async prices(): Promise<ReservesPrices> {\n const { data } = await this.cache.getDataOrThrow(\n async () => {\n const supplyRealtimePrice = this.supplyReserve.mintPrice;\n const debtRealtimePrice = this.debtReserve.mintPrice;\n const supplyEmaPrice = this.supplyReserve.mintEmaPrice;\n const debtEmaPrice = this.debtReserve.mintEmaPrice;\n\n const realtimeMintsToFetch = [\n ...(supplyRealtimePrice === undefined ? [this.supplyReserve.mint.mint] : []),\n ...(debtRealtimePrice === undefined ? [this.debtReserve.mint.mint] : []),\n ];\n const emaMintsToFetch = [\n ...(supplyEmaPrice === undefined ? [this.supplyReserve.mint.mint] : []),\n ...(debtEmaPrice === undefined ? [this.debtReserve.mint.mint] : []),\n ];\n\n const [realtime, ema] = await Promise.all([\n realtimeMintsToFetch.length\n ? oracle.fetchPrices(realtimeMintsToFetch, \"realtime\", undefined, this.environment)\n : ({} as Record<Address, number>),\n emaMintsToFetch.length\n ? oracle.fetchPrices(emaMintsToFetch, \"ema\", undefined, this.environment)\n : ({} as Record<Address, number>),\n ]);\n\n return {\n supply: {\n realtimePrice: supplyRealtimePrice ?? realtime[this.supplyReserve.mint.mint],\n emaPrice: supplyEmaPrice ?? ema[this.supplyReserve.mint.mint],\n },\n debt: {\n realtimePrice: debtRealtimePrice ?? realtime[this.debtReserve.mint.mint],\n emaPrice: debtEmaPrice ?? ema[this.debtReserve.mint.mint],\n },\n };\n },\n \"prices\",\n `${this.supplyReserve.mint.mint}:${this.debtReserve.mint.mint}`\n );\n return data;\n }\n\n /**\n * Net APY for the lending & borrowing position.\n * Accounts for eligible incentives based on the paired reserve relationship.\n */\n get netAPY(): number {\n return this.supplyReserve.supplyAPY(this.debtReserve.address) - this.debtReserve.borrowAPY();\n }\n\n /**\n * Simulates net APY after hypothetical position changes.\n * Accounts for eligible incentives based on the paired reserve relationship.\n */\n simulateNetAPY(args: PositionBalanceChange[]): number {\n return (\n this.supplyReserve.simulateNewSupplyAPY(\n args.find((x) => Boolean(x.collateralChange)) ?? { collateralChange: 0 },\n this.debtReserve.address\n ) -\n this.debtReserve.simulateNewBorrowAPY(\n args.find((x) => Boolean(x.debtChange)) ?? { debtChange: 0 }\n )\n );\n }\n\n /** Current LTV utilization rate in basis points (0-10000) given USD position values */\n calcLtvUtilizationRateBps(supplyUsd: number, debtUsd: number): number {\n if (supplyUsd <= 0) return 0;\n return (debtUsd / (supplyUsd * this.maxLtv)) * 10_000;\n }\n\n /**\n * Calculates the USD debt adjustment needed to reach a target LTV utilization rate.\n * Positive result = boost (increase leverage), negative = deleverage.\n */\n async calcDebtAdjustmentUsd(\n uiSupplyAmount: number,\n uiDebtAmount: number,\n targetLtvUtilizationRateBps: number,\n options: DebtAdjustmentOptions = {}\n ): Promise<number> {\n const { supply: supplyPrice, debt: debtPrice } = await this.prices();\n let supplyUsd = uiSupplyAmount * supplyPrice.realtimePrice;\n let debtUsd = uiDebtAmount * debtPrice.realtimePrice;\n\n const maxLtv = this.maxLtv;\n const targetUtilizationRate = targetLtvUtilizationRateBps / 10_000;\n const flFee = this.debtReserve.config.flashLoanFeePct / 100;\n const lpBorrowFee = this.debtReserve.config.borrowFeePct / 100;\n const positionChangeMode = options.positionChangeMode ?? \"levered\";\n\n const currentLtvUtilizationRate = supplyUsd > 0 ? debtUsd / (supplyUsd * maxLtv) : 0;\n const isBoost = currentLtvUtilizationRate < targetUtilizationRate;\n\n if (isBoost) {\n supplyUsd = uiSupplyAmount * (supplyPrice.emaPrice ?? supplyPrice.realtimePrice);\n debtUsd = uiDebtAmount * (debtPrice.emaPrice ?? debtPrice.realtimePrice);\n }\n\n if (positionChangeMode === \"debtOnly\") {\n const targetDebtDeltaUsd = targetUtilizationRate * maxLtv * supplyUsd - debtUsd;\n return isBoost ? targetDebtDeltaUsd / (1.0 + lpBorrowFee) : targetDebtDeltaUsd;\n }\n\n return isBoost\n ? (targetUtilizationRate * maxLtv * supplyUsd - debtUsd) /\n (1.0 + lpBorrowFee + flFee - targetUtilizationRate * maxLtv)\n : (targetUtilizationRate * maxLtv * supplyUsd - debtUsd) /\n (1.0 - targetUtilizationRate * maxLtv * (1.0 + flFee));\n }\n}\n","/**\n * Per-asset carry trade price-band presets, split by volatility regime.\n *\n * Each preset defines three drawdown / rally buffers that control how aggressively a\n * lending position is utilized relative to its liquidation line:\n *\n * - `drawdownPctFromTargetToLiq` — collateral drawdown (%) that separates the **target**\n * utilization from the liquidation line. Larger = more conservative target.\n * - `drawdownPctFromUnwindToLiq` — collateral drawdown (%) that separates the **unwind\n * trigger** from the liquidation line. Smaller than target (closer to liquidation).\n * - `maxPriceChangeUpPercent` — max collateral **rally** (%) before the boost trigger fires,\n * prompting the position to borrow more and return to target.\n *\n * ## Usage\n *\n * Select the appropriate asset preset and volatility regime, then pass it to\n * `LycLendingPositionManager.getLendingAllocationConfigFromPriceBands(preset)`, which combines\n * the price-band params with pair-specific `maxLtv` and `liquidationThreshold` to produce\n * a `CarryLendingAllocationConfig` (target utilization + deviation bands in bps). The\n * resulting config is used to update the on-chain `LendingPositionConfig`, adapting the\n * position's risk envelope to the current market regime.\n *\n * ## Asset tiers (tightest → widest buffers)\n *\n * BTC → ETH → SOL → large-cap alts → small-cap alts\n *\n * Higher-volatility assets use wider buffers to avoid unnecessary unwinds during normal\n * price swings, while lower-volatility assets can afford tighter bands for better capital\n * efficiency.\n */\nimport type { CarryPriceBandPreset } from \"../../services/carry/carryAllocationConfig\";\n\nexport const VOLATILITY_REGIMES = [\"lowVol\", \"highVol\"] as const;\nexport type VolatilityRegime = (typeof VOLATILITY_REGIMES)[number];\n\nexport function isVolatilityRegime(s: string): s is VolatilityRegime {\n return VOLATILITY_REGIMES.includes(s as VolatilityRegime);\n}\n\nexport type CarryVolatilityPresets = {\n lowVol: CarryPriceBandPreset;\n highVol: CarryPriceBandPreset;\n};\n\nexport interface AssetPresetEntry {\n presets: CarryVolatilityPresets;\n defaultRegime: VolatilityRegime;\n}\n\nexport const STOCK_INDEX_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 8,\n drawdownPctFromUnwindToLiq: 5,\n maxPriceChangeUpPercent: 2,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 11,\n drawdownPctFromUnwindToLiq: 7,\n maxPriceChangeUpPercent: 3,\n },\n};\n\nexport const BTC_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 12,\n drawdownPctFromUnwindToLiq: 8,\n maxPriceChangeUpPercent: 6,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 14,\n drawdownPctFromUnwindToLiq: 10,\n maxPriceChangeUpPercent: 8,\n },\n};\n\nexport const ETH_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 14,\n drawdownPctFromUnwindToLiq: 10,\n maxPriceChangeUpPercent: 7,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 17,\n drawdownPctFromUnwindToLiq: 12,\n maxPriceChangeUpPercent: 10,\n },\n};\n\nexport const SOL_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 16,\n drawdownPctFromUnwindToLiq: 12,\n maxPriceChangeUpPercent: 8,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 19,\n drawdownPctFromUnwindToLiq: 14,\n maxPriceChangeUpPercent: 11,\n },\n};\n\nexport const LST_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 19,\n drawdownPctFromUnwindToLiq: 10,\n maxPriceChangeUpPercent: 8,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 22,\n drawdownPctFromUnwindToLiq: 12,\n maxPriceChangeUpPercent: 11,\n },\n};\n\nexport const LARGE_CAP_ALT_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 22,\n drawdownPctFromUnwindToLiq: 16,\n maxPriceChangeUpPercent: 8,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 25,\n drawdownPctFromUnwindToLiq: 18,\n maxPriceChangeUpPercent: 10,\n },\n};\n\nexport const SMALL_CAP_ALT_CARRY_PRESETS: CarryVolatilityPresets = {\n lowVol: {\n drawdownPctFromTargetToLiq: 26,\n drawdownPctFromUnwindToLiq: 22,\n maxPriceChangeUpPercent: 10,\n },\n highVol: {\n drawdownPctFromTargetToLiq: 29,\n drawdownPctFromUnwindToLiq: 24,\n maxPriceChangeUpPercent: 12,\n },\n};\n\n/**\n * Maps collateral symbol (upper-cased) to its carry trade preset tier and\n * default volatility regime. Used by scripts and backend services to resolve\n * the correct price-band parameters when creating or reconfiguring lending\n * positions.\n */\nexport const ASSET_PRESETS: Record<string, AssetPresetEntry> = {\n WBTC: { presets: BTC_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n CBBTC: { presets: BTC_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n WETH: { presets: ETH_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n SOL: { presets: SOL_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n JUPSOL: { presets: LST_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n JITOSOL: { presets: LST_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n DFDVSOL: { presets: LST_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n SPYX: { presets: STOCK_INDEX_PRESETS, defaultRegime: \"lowVol\" },\n QQQX: { presets: STOCK_INDEX_PRESETS, defaultRegime: \"lowVol\" },\n LARGE_CAP: { presets: LARGE_CAP_ALT_CARRY_PRESETS, defaultRegime: \"lowVol\" },\n SMALL_CAP: { presets: SMALL_CAP_ALT_CARRY_PRESETS, defaultRegime: \"highVol\" },\n};\n\n/** Looks up the carry preset entry for a collateral symbol (case-insensitive). */\nexport function resolvePresets(collateralSymbol: string): AssetPresetEntry | undefined {\n return ASSET_PRESETS[collateralSymbol.toUpperCase()];\n}\n","import {\n ltvUtilDeltaBelowTargForRallyPct,\n maxLtvUtilBeforeCollDrawdown,\n ReservesManager,\n type ReserveBase,\n} from \"lending-platforms\";\nimport { mints } from \"common\";\nimport type { Address } from \"@solana/kit\";\nimport { resolvePresets, type VolatilityRegime } from \"../../constants/configs/carryTradePresets\";\n\n/** Maximum value for `targetUtilizationRateBps` (100% in basis points). */\nexport const MAX_TARGET_UTILIZATION_RATE_BPS = 10_000;\n\n/**\n * Maximum allowed value of `targetUtilizationRateBps + maxDeviationAboveTargetUtilBps`.\n * Mirrors `MAX_LENDING_POSITION_UPPER_UTIL_BPS` in the on-chain program.\n */\nexport const MAX_LENDING_POSITION_UPPER_UTIL_BPS = 10_500;\n\n/**\n * Floor for `maxDeviationAboveTargetUtilBps` in preset-based computation.\n *\n * When the raw target is high enough that the unwind-trigger gap would be\n * smaller than this, `computeCarryLendingAllocationConfig` pulls the target\n * down so the above-deviation is at least this wide. This prevents\n * near-zero unwind bands that would trigger constant rebalances.\n */\nexport const MIN_DEVIATION_ABOVE_TARGET_UTIL_BPS = 200;\n\n/**\n * On-chain lending position tuning (see `LendingPositionConfig` in `long_yield_carry`).\n */\nexport type CarryLendingAllocationConfig = {\n targetUtilizationRateBps: number;\n maxDeviationAboveTargetUtilBps: number;\n maxDeviationBelowTargetUtilBps: number;\n};\n\nexport type ComputeCarryLendingAllocationConfigParams = {\n /**\n * Collateral drawdown buffer between the **target** utilization and liquidation (positive percent,\n * e.g. `25` for 25%). At target utilization, a collateral drop of this size reaches the liquidation\n * line: `target = (1 − drawdownPctFromTargetToLiq/100) × liquidationThreshold / maxLtv`.\n *\n * Must be greater than `drawdownPctFromUnwindToLiq` (the target sits further from liquidation than\n * the unwind trigger).\n */\n drawdownPctFromTargetToLiq: number;\n /**\n * Collateral drawdown buffer between the **unwind trigger** and liquidation (positive percent,\n * e.g. `10` for 10%). At the unwind trigger (`target + maxDeviationAbove`), a collateral drop of\n * this size reaches the liquidation line:\n * `unwindTrigger = (1 − drawdownPctFromUnwindToLiq/100) × liquidationThreshold / maxLtv`.\n *\n * Must be less than `drawdownPctFromTargetToLiq`.\n */\n drawdownPctFromUnwindToLiq: number;\n /**\n * Max collateral **appreciation** (positive percent, e.g. `25` for +25%). If you start exactly at\n * target utilization and collateral rallies this much (debt USD fixed), utilization reaches the\n * **boost** trigger: `target − maxDeviationBelow`.\n */\n maxPriceChangeUpPercent: number;\n /** Effective max LTV for the pair (decimal `0.8` = 80%), e.g. `ReservesManager.maxLtv`. */\n maxLtv: number;\n /** Collateral liquidation threshold (decimal `0.85` = 85%), from reserve config. */\n liquidationThreshold: number;\n};\n\n/** The price-band params without pair-specific LTV / liquidation fields. */\nexport type CarryPriceBandPreset = Omit<\n ComputeCarryLendingAllocationConfigParams,\n \"maxLtv\" | \"liquidationThreshold\"\n>;\n\n/**\n * Clamps a lending position config so it satisfies the on-chain constraints in\n * `require_valid_lending_position_config_bps`:\n *\n * - `targetUtilizationRateBps` is clamped to `[1, MAX_TARGET_UTILIZATION_RATE_BPS]`\n * - `maxDeviationAboveTargetUtilBps` is clamped so `target + above ≤ MAX_LENDING_POSITION_UPPER_UTIL_BPS`\n *\n * Throws only for inputs that indicate a bug (non-integer, negative deviation, target ≤ maxDevBelow).\n */\nexport function clampLendingPositionConfigBps(\n config: CarryLendingAllocationConfig\n): CarryLendingAllocationConfig {\n let { targetUtilizationRateBps, maxDeviationAboveTargetUtilBps, maxDeviationBelowTargetUtilBps } =\n config;\n\n if (!Number.isInteger(targetUtilizationRateBps) || targetUtilizationRateBps <= 0) {\n throw new Error(\"targetUtilizationRateBps must be a positive integer\");\n }\n for (const [name, v] of [\n [\"maxDeviationAboveTargetUtilBps\", maxDeviationAboveTargetUtilBps],\n [\"maxDeviationBelowTargetUtilBps\", maxDeviationBelowTargetUtilBps],\n ] as const) {\n if (!Number.isInteger(v) || v < 0) {\n throw new Error(`${name} must be a non-negative integer`);\n }\n }\n\n targetUtilizationRateBps = Math.min(targetUtilizationRateBps, MAX_TARGET_UTILIZATION_RATE_BPS);\n maxDeviationAboveTargetUtilBps = Math.min(\n maxDeviationAboveTargetUtilBps,\n MAX_LENDING_POSITION_UPPER_UTIL_BPS - targetUtilizationRateBps\n );\n\n if (targetUtilizationRateBps <= maxDeviationBelowTargetUtilBps) {\n throw new Error(\"targetUtilizationRateBps must be greater than maxDeviationBelowTargetUtilBps\");\n }\n\n return {\n targetUtilizationRateBps,\n maxDeviationAboveTargetUtilBps,\n maxDeviationBelowTargetUtilBps,\n };\n}\n\n/**\n * Builds `targetUtilizationRateBps` and deviation bands from drawdown-to-liquidation buffers.\n *\n * **Model:** debt USD fixed; only collateral USD moves. Both the target and the unwind trigger are\n * defined by how much collateral drawdown separates them from the liquidation line\n * (`liquidationThreshold / maxLtv`). The boost trigger (below target) is set by a rally percentage.\n *\n * `maxDeviationAbove = unwindTriggerBps − targetBps` (derived, not from a price-change input).\n */\nexport function computeCarryLendingAllocationConfig(\n params: ComputeCarryLendingAllocationConfigParams\n): CarryLendingAllocationConfig {\n const {\n drawdownPctFromTargetToLiq,\n drawdownPctFromUnwindToLiq,\n maxPriceChangeUpPercent,\n maxLtv,\n liquidationThreshold,\n } = params;\n\n if (\n !Number.isFinite(drawdownPctFromTargetToLiq) ||\n drawdownPctFromTargetToLiq <= 0 ||\n drawdownPctFromTargetToLiq >= 100\n ) {\n throw new RangeError(\"drawdownPctFromTargetToLiq must be in (0, 100)\");\n }\n if (\n !Number.isFinite(drawdownPctFromUnwindToLiq) ||\n drawdownPctFromUnwindToLiq < 0 ||\n drawdownPctFromUnwindToLiq >= 100\n ) {\n throw new RangeError(\"drawdownPctFromUnwindToLiq must be in [0, 100)\");\n }\n if (drawdownPctFromUnwindToLiq >= drawdownPctFromTargetToLiq) {\n throw new RangeError(\n \"drawdownPctFromUnwindToLiq must be less than drawdownPctFromTargetToLiq (unwind trigger is closer to liquidation than target)\"\n );\n }\n if (!Number.isFinite(maxPriceChangeUpPercent) || maxPriceChangeUpPercent <= 0) {\n throw new RangeError(\"maxPriceChangeUpPercent must be finite and positive\");\n }\n\n const targetDecimal = maxLtvUtilBeforeCollDrawdown({\n drawdownPercent: drawdownPctFromTargetToLiq,\n ltv: maxLtv,\n liquidationThreshold,\n });\n\n let targetUtilizationRateBps = Math.min(\n Math.floor(targetDecimal * 10_000),\n MAX_TARGET_UTILIZATION_RATE_BPS\n );\n if (targetUtilizationRateBps <= 0) {\n throw new RangeError(\n \"Computed target utilization rounds to zero; reduce drawdownPctFromTargetToLiq or check maxLtv / liquidationThreshold\"\n );\n }\n\n const unwindTriggerDecimal = maxLtvUtilBeforeCollDrawdown({\n drawdownPercent: drawdownPctFromUnwindToLiq,\n ltv: maxLtv,\n liquidationThreshold,\n });\n const unwindTriggerBps = Math.floor(unwindTriggerDecimal * 10_000);\n let maxDeviationAboveTargetUtilBps = Math.min(\n unwindTriggerBps - targetUtilizationRateBps,\n MAX_LENDING_POSITION_UPPER_UTIL_BPS - targetUtilizationRateBps\n );\n\n // If the above-deviation is below the minimum (e.g. because the target was\n // clamped to MAX_TARGET_UTILIZATION_RATE_BPS), pull the target down so the\n // unwind band is at least MIN_DEVIATION_ABOVE_TARGET_UTIL_BPS wide.\n if (maxDeviationAboveTargetUtilBps < MIN_DEVIATION_ABOVE_TARGET_UTIL_BPS) {\n maxDeviationAboveTargetUtilBps = MIN_DEVIATION_ABOVE_TARGET_UTIL_BPS;\n targetUtilizationRateBps = Math.min(\n targetUtilizationRateBps,\n MAX_LENDING_POSITION_UPPER_UTIL_BPS - MIN_DEVIATION_ABOVE_TARGET_UTIL_BPS\n );\n }\n\n const t = targetUtilizationRateBps / 10_000;\n const maxBelowDecimal = ltvUtilDeltaBelowTargForRallyPct(t, maxPriceChangeUpPercent);\n const maxDeviationBelowTargetUtilBps = Math.floor(maxBelowDecimal * 10_000);\n\n return clampLendingPositionConfigBps({\n targetUtilizationRateBps,\n maxDeviationAboveTargetUtilBps,\n maxDeviationBelowTargetUtilBps,\n });\n}\n\n// =============================================================================\n// High-level preset resolution\n// =============================================================================\n\nexport interface ComputeConfigForCollateralArgs {\n /** Collateral mint address — used to look up the symbol from the mint registry. */\n collateralMint: Address;\n /** Collateral reserve — used to read `liquidationThresholdPct`. */\n collateralReserve: ReserveBase;\n /** Debt reserve — paired with collateral to determine `maxLtv` (including e-mode). */\n debtReserve: ReserveBase;\n /**\n * Override the volatility regime. When omitted, uses the asset's\n * `defaultRegime` from `ASSET_PRESETS`.\n */\n regime?: VolatilityRegime;\n}\n\n/**\n * Resolves the carry trade price-band preset for a collateral mint and\n * computes the lending position config (target utilization + deviation bands)\n * using the reserve pair's `maxLtv` and `liquidationThreshold`.\n *\n * Uses {@link ReservesManager} to derive `maxLtv` (including e-mode overrides)\n * and normalizes `liquidationThresholdPct` to a decimal.\n *\n * Throws if the collateral mint symbol is not in `ASSET_PRESETS`.\n */\nexport function computeConfigForCollateral(\n args: ComputeConfigForCollateralArgs\n): CarryLendingAllocationConfig {\n const { collateralMint, collateralReserve, debtReserve } = args;\n\n const mintInfo = mints.get(collateralMint);\n const symbol = mintInfo?.symbol ?? String(collateralMint);\n const entry = resolvePresets(symbol);\n if (!entry) {\n throw new Error(\n `computeConfigForCollateral: no carry preset found for collateral \"${symbol}\" (${collateralMint})`\n );\n }\n\n const regime = args.regime ?? entry.defaultRegime;\n const preset = entry.presets[regime];\n\n const rm = new ReservesManager(collateralReserve, debtReserve);\n const pct = collateralReserve.config.liquidationThresholdPct;\n const liquidationThreshold = pct <= 1 ? pct : pct / 100;\n\n return computeCarryLendingAllocationConfig({\n ...preset,\n maxLtv: rm.maxLtv,\n liquidationThreshold,\n });\n}\n","import { fromWeb3Pk, type Environment } from \"common\";\nimport {\n LendingPlatformData,\n LendingPositionManager,\n ReserveBase,\n type CollateralPriceTriggerBand,\n type LendingPositionInspectMetrics,\n} from \"lending-platforms\";\nimport { TokenLendingPositionData } from \"../../models/lycToken\";\nimport {\n computeCarryLendingAllocationConfig,\n type CarryLendingAllocationConfig,\n type CarryPriceBandPreset,\n} from \"./carryAllocationConfig\";\n\n/**\n * LYC-flavoured {@link LendingPositionManager}: adds carry-specific sizing\n * signals ({@link shouldIncreaseCarryPosition}, {@link shouldDecreaseCarryPosition})\n * and defaults utilization targets from the on-chain `LendingPositionConfig`.\n */\nexport class LycLendingPositionManager extends LendingPositionManager {\n constructor(\n lpData: LendingPlatformData,\n readonly lendingPosition: TokenLendingPositionData,\n collateralReserve: ReserveBase,\n debtReserve: ReserveBase,\n environment?: Environment\n ) {\n super(\n lpData,\n fromWeb3Pk(lendingPosition.pool),\n fromWeb3Pk(lendingPosition.protocolUserAcc),\n collateralReserve,\n debtReserve,\n environment\n );\n }\n\n static async create(\n lpData: LendingPlatformData,\n lendingPosition: TokenLendingPositionData,\n environment?: Environment\n ): Promise<LycLendingPositionManager> {\n const pool = fromWeb3Pk(lendingPosition.pool);\n const [collateralReserve, debtReserve] = await Promise.all([\n lpData.fetchReserve(pool, fromWeb3Pk(lendingPosition.collateralReserve)),\n lpData.fetchReserve(pool, fromWeb3Pk(lendingPosition.debtReserve)),\n ]);\n if (!collateralReserve || !debtReserve) {\n throw new Error(\"Failed to fetch reserves\");\n }\n return new LycLendingPositionManager(\n lpData,\n lendingPosition,\n collateralReserve,\n debtReserve,\n environment\n );\n }\n\n /**\n * Derives `targetUtilizationRateBps` and carry trigger deviations from drawdown-to-liquidation\n * buffers and a rally percentage, using this pair's {@link ReservesManager.maxLtv} and the\n * collateral reserve's **base** `liquidationThresholdPct` (normalized to a decimal).\n *\n * For custom `maxLtv` / `liquidationThreshold` (e.g. e-mode liquidation threshold), call\n * {@link computeCarryLendingAllocationConfig} directly.\n */\n getLendingAllocationConfigFromPriceBands(\n params: CarryPriceBandPreset\n ): CarryLendingAllocationConfig {\n const pct = this.reservesManager.supplyReserve.config.liquidationThresholdPct;\n const liquidationThreshold = pct <= 1 ? pct : pct / 100;\n return computeCarryLendingAllocationConfig({\n ...params,\n maxLtv: this.reservesManager.maxLtv,\n liquidationThreshold,\n });\n }\n\n /**\n * Returns true when the current LTV utilization (valued at EMA prices) has\n * fallen far enough below the target that the position should be boosted.\n */\n async shouldIncreaseCarryPosition(): Promise<boolean> {\n const state = await this.getPositionState(\"ema\");\n if (!state) return false;\n\n const { supplyUsd, debtUsd } = state;\n if (supplyUsd <= 0) return false;\n\n const currentUtilBps = this.reservesManager.calcLtvUtilizationRateBps(supplyUsd, debtUsd);\n return (\n currentUtilBps <=\n this.lendingPosition.config.targetUtilizationRateBps -\n this.lendingPosition.config.maxDeviationBelowTargetUtilBps\n );\n }\n\n /**\n * Returns true when the current LTV utilization (valued at realtime prices) has\n * risen far enough above the target that the position should be unwound.\n */\n async shouldDecreaseCarryPosition(): Promise<boolean> {\n const state = await this.getPositionState(\"realtime\");\n if (!state) return false;\n\n const { supplyUsd, debtUsd } = state;\n const currentUtilBps = this.reservesManager.calcLtvUtilizationRateBps(supplyUsd, debtUsd);\n return (\n currentUtilBps >=\n this.lendingPosition.config.targetUtilizationRateBps +\n this.lendingPosition.config.maxDeviationAboveTargetUtilBps\n );\n }\n\n override async calcDebtChangeAmount(\n targetUtilizationRateBps: number = this.lendingPosition.config.targetUtilizationRateBps\n ): Promise<number> {\n return super.calcDebtChangeAmount(targetUtilizationRateBps);\n }\n\n override async calcPreWithdrawalTargetUtilizationRateBps(\n withdrawUiCollateralAmount: number,\n postWithdrawalTargetUtilizationRateBps: number = this.lendingPosition.config\n .targetUtilizationRateBps\n ): Promise<number> {\n return super.calcPreWithdrawalTargetUtilizationRateBps(\n withdrawUiCollateralAmount,\n postWithdrawalTargetUtilizationRateBps\n );\n }\n\n override async calcDebtChangeAmountForCollateralWithdrawal(\n withdrawUiCollateralAmount: number,\n postWithdrawalTargetUtilizationRateBps: number = this.lendingPosition.config\n .targetUtilizationRateBps\n ): Promise<number> {\n return super.calcDebtChangeAmountForCollateralWithdrawal(\n withdrawUiCollateralAmount,\n postWithdrawalTargetUtilizationRateBps\n );\n }\n\n override async getCollateralPriceTriggerBand(): Promise<CollateralPriceTriggerBand> {\n return super.getCollateralPriceTriggerBand(this.configTriggerBandBps());\n }\n\n override async getInspectMetrics(): Promise<LendingPositionInspectMetrics | null> {\n return super.getInspectMetrics(this.configTriggerBandBps());\n }\n\n private configTriggerBandBps(): {\n lowerTargetUtilizationRateBps: number;\n upperTargetUtilizationRateBps: number;\n } {\n const {\n targetUtilizationRateBps,\n maxDeviationBelowTargetUtilBps,\n maxDeviationAboveTargetUtilBps,\n } = this.lendingPosition.config;\n return {\n lowerTargetUtilizationRateBps: targetUtilizationRateBps - maxDeviationBelowTargetUtilBps,\n upperTargetUtilizationRateBps: targetUtilizationRateBps + maxDeviationAboveTargetUtilBps,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,kBAAkB;;;ACmBpB,IAAe,4BAAf,MAAwE;AAAA,EAM7E,YAAY,QAAgB,UAAoB,CAAC,MAAM,GAAG;AACxD,SAAK,MAAM,sBAAsB,OAAO;AAAA,EAC1C;AAAA,EAEA,mCAAmC,eAA+C;AAChF,SAAK,GAAG,mCAAmC,aAAa;AAAA,EAC1D;AAqDF;;;ACrFA;AAAA,EACE;AAAA,EAEA;AAAA,EACA,cAAAA;AAAA,EACA,sBAAAC;AAAA,OAKK;AACP,SAAS,SAAAC,cAAa;AACtB,SAAS,aAAkC;;;ACRpC,IAAM,4CAA4C;AAClD,IAAM,+CAA+C;AACrD,IAAM,oDAAoD;;;ACQ1D,IAAe,sBAAf,MAAmC;AAAA,EAQxC,YAAY,QAAgB,gBAAiC,UAAoB,CAA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AM_ID","DEFAULT_PUBLIC_KEY","Scope","dep","Decimal","Scope","PROGRAM_ID","DEFAULT_PUBLIC_KEY","Decimal","address","Decimal","BN","calculateCurrentRewardPerToken","calculateCurrentRewardPerToken","Decimal","BN","address","Decimal","BN","BN","address","sum","BN","BN","BN","address","Scope","DEFAULT_PUBLIC_KEY","PROGRAM_ID","userMetadataPda","VanillaObligation","PROGRAM_ID","address","userMetadataPda","DEFAULT_PUBLIC_KEY","VanillaObligation","tokens","chainTokens","configAddr","Scope","BN","DEFAULT_PUBLIC_KEY","lendingMarketAuthPda","PROGRAM_ID","userMetadataPda","VanillaObligation","TOKEN_PROGRAM_ADDRESS","VanillaObligation","userMetadataPda","PROGRAM_ID","DEFAULT_PUBLIC_KEY","TOKEN_PROGRAM_ADDRESS","lendingMarketAuthPda","BN","Decimal","lendingMarketAuthPda","PROGRAM_ID","Decimal","PROGRAM_ID","BN","lendingMarketAuthPda","BN","address","BN","BN","BN","MAX_LENDING_POSITION_UPPER_UTIL_BPS"]}