@anywalletkit/protocol-lending-kamino-solana 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -77,6 +77,35 @@ var pct = (x) => x === null || x === void 0 ? 0 : Number(x) * 100;
77
77
  var num = (x, d = 0) => x === null || x === void 0 || x === "" ? d : Number(x);
78
78
  var big = (x) => x === null || x === void 0 ? 0n : BigInt(String(x).split(".")[0]);
79
79
  var str = (x) => x === null || x === void 0 ? "0" : String(x);
80
+ var DEFAULT_KEY = "11111111111111111111111111111111";
81
+ function uint(x, what, bits) {
82
+ let v;
83
+ if (typeof x === "number" && Number.isSafeInteger(x) && x >= 0) v = BigInt(x);
84
+ else if (typeof x === "string" && x.length <= 40 && /^\d+$/.test(x)) v = BigInt(x);
85
+ if (v === void 0 || v >= 1n << BigInt(bits)) throw new KaminoError(`Kamino reported ${what} as ${String(x).slice(0, 40)}; it is a u${bits}.`);
86
+ return v;
87
+ }
88
+ function u256Limbs(x, what) {
89
+ const limbs = x?.value;
90
+ if (!Array.isArray(limbs) || limbs.length !== 4) throw new KaminoError(`Kamino reported ${what} without its four limbs.`);
91
+ return limbs.reduce((sum, l, i) => sum + (uint(l, `a limb of ${what}`, 64) << BigInt(64 * i)), 0n);
92
+ }
93
+ function obligationState(x) {
94
+ if (!x || typeof x !== "object") return null;
95
+ const s = x;
96
+ if (!Array.isArray(s.deposits) && !Array.isArray(s.borrows)) return null;
97
+ const slots = (v, key2) => (Array.isArray(v) ? v : []).filter((l) => !!l && typeof l === "object" && String(l[key2] ?? DEFAULT_KEY) !== DEFAULT_KEY);
98
+ return {
99
+ owner: String(s.owner ?? ""),
100
+ lendingMarket: String(s.lendingMarket ?? ""),
101
+ deposits: slots(s.deposits, "depositReserve").map((l) => ({ reserve: String(l.depositReserve), ctokens: uint(l.depositedAmount, "a deposit's depositedAmount", 64) })),
102
+ borrows: slots(s.borrows, "borrowReserve").map((l) => ({
103
+ reserve: String(l.borrowReserve),
104
+ borrowedSf: uint(l.borrowedAmountSf, "a borrow's borrowedAmountSf", 128),
105
+ cumulativeBorrowRate: u256Limbs(l.cumulativeBorrowRateBsf, "a borrow's cumulativeBorrowRateBsf")
106
+ }))
107
+ };
108
+ }
80
109
  var KaminoApi = class {
81
110
  /** `timeoutMs` bounds each call (default 15 s): a silent API must not hang a read or a write's build. */
82
111
  constructor(endpoint = KAMINO_API, fetchImpl = fetch, timeoutMs = 15e3) {
@@ -216,16 +245,20 @@ var KaminoApi = class {
216
245
  valueUsd: str(l.tokenValue ?? l.valueUsd)
217
246
  }));
218
247
  const coll = info.collateral ?? {}, debt = info.debt ?? {};
248
+ const stats = row.refreshedStats ?? {}, st = row.state ?? {};
249
+ const deposited = num(stats.userTotalDeposit);
250
+ const maxLtv = stats.borrowLimit !== void 0 && deposited > 0 ? num(stats.borrowLimit) / deposited : info.maxLtv === null || info.maxLtv === void 0 ? null : num(info.maxLtv);
219
251
  return {
220
252
  obligation: String(row.obligationAddress ?? row.loanId ?? row.obligation ?? row.address ?? ""),
221
253
  market: String(row.marketId ?? market),
222
254
  user: String(row.user ?? ""),
223
- elevationGroup: num(row.elevationGroup),
255
+ elevationGroup: num(st.elevationGroup ?? row.elevationGroup),
224
256
  deposits: legs(coll.deposits ?? row.deposits),
225
257
  borrows: legs(debt.borrows ?? row.borrows),
226
- currentLtv: num(info.currentLtv),
227
- maxLtv: info.maxLtv === null || info.maxLtv === void 0 ? null : num(info.maxLtv),
228
- liquidationLtv: num(info.liquidationLtv),
258
+ state: obligationState(row.state),
259
+ currentLtv: num(stats.loanToValue ?? info.currentLtv),
260
+ maxLtv,
261
+ liquidationLtv: num(stats.liquidationLtv ?? info.liquidationLtv),
229
262
  raw: row
230
263
  };
231
264
  }
@@ -462,7 +495,7 @@ import { base58 } from "@scure/base";
462
495
  var SF = 1n << 60n;
463
496
  var FARM_STAKE_SCALE = 10n ** 18n;
464
497
  var CHAIN_TOLERANCE_BPS = 100n;
465
- var DEFAULT_KEY = "11111111111111111111111111111111";
498
+ var DEFAULT_KEY2 = "11111111111111111111111111111111";
466
499
  var KINDS = {
467
500
  VaultState: { program: KVAULT_PROGRAM, disc: "e4c452a562d2eb98", size: 62552 },
468
501
  Reserve: { program: KLEND_PROGRAM, disc: "2bf2ccca1af73b7f", size: 8624 },
@@ -492,7 +525,7 @@ function decodeVault(address, acc) {
492
525
  for (let i = 0; i < 25; i++) {
493
526
  const o = 312 + i * 2160;
494
527
  const reserve = key(d, o);
495
- if (reserve !== DEFAULT_KEY) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
528
+ if (reserve !== DEFAULT_KEY2) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
496
529
  }
497
530
  const farm = key(d, 58600);
498
531
  return {
@@ -507,7 +540,7 @@ function decodeVault(address, acc) {
507
540
  allocations,
508
541
  minDeposit: u64(d, 58408),
509
542
  minWithdraw: u64(d, 58416),
510
- farm: farm === DEFAULT_KEY ? null : farm
543
+ farm: farm === DEFAULT_KEY2 ? null : farm
511
544
  };
512
545
  }
513
546
  function decodeReserve(address, acc) {
@@ -538,23 +571,27 @@ function decodeObligation(address, acc) {
538
571
  for (let i = 0; i < 8; i++) {
539
572
  const o = 96 + i * 136;
540
573
  const reserve = key(d, o);
541
- if (reserve !== DEFAULT_KEY) deposits.push({ reserve, ctokens: u64(d, o + 32) });
574
+ if (reserve !== DEFAULT_KEY2) deposits.push({ reserve, ctokens: u64(d, o + 32) });
542
575
  }
543
576
  for (let i = 0; i < 5; i++) {
544
577
  const o = 1208 + i * 200;
545
578
  const reserve = key(d, o);
546
- if (reserve !== DEFAULT_KEY) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
579
+ if (reserve !== DEFAULT_KEY2) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
547
580
  }
548
581
  return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
549
582
  }
583
+ function depositLegLiquidity(r, ctokens) {
584
+ return collateralToLiquiditySf(r, ctokens) / SF;
585
+ }
586
+ function debtLegNow(r, leg) {
587
+ const sf = leg.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > leg.cumulativeBorrowRate ? leg.borrowedSf * r.cumulativeBorrowRate / leg.cumulativeBorrowRate : leg.borrowedSf;
588
+ return (sf + SF - 1n) / SF;
589
+ }
550
590
  function depositedLiquidity(o, r, reserve) {
551
- return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + collateralToLiquiditySf(r, x.ctokens) / SF, 0n);
591
+ return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + depositLegLiquidity(r, x.ctokens), 0n);
552
592
  }
553
593
  function debtNow(o, r, reserve) {
554
- return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => {
555
- const sf = x.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > x.cumulativeBorrowRate ? x.borrowedSf * r.cumulativeBorrowRate / x.cumulativeBorrowRate : x.borrowedSf;
556
- return sum + (sf + SF - 1n) / SF;
557
- }, 0n);
594
+ return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + debtLegNow(r, x), 0n);
558
595
  }
559
596
  function decodeFarmUser(address, acc) {
560
597
  const d = bytesOf("UserState", address, acc);
@@ -961,6 +998,7 @@ function symbolOf(v) {
961
998
  }
962
999
 
963
1000
  // src/market.ts
1001
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
964
1002
  var KaminoMarketProtocolSolana = class extends KaminoBase {
965
1003
  market;
966
1004
  firstDepositAllowance;
@@ -968,7 +1006,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
968
1006
  constructor(account, config = {}) {
969
1007
  super(account, config);
970
1008
  this.market = config?.market ?? MAIN_MARKET;
971
- if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
1009
+ if (!ADDRESS.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
972
1010
  this.firstDepositAllowance = config?.firstDepositAllowanceLamports === void 0 ? DEFAULT_FIRST_DEPOSIT_ALLOWANCE : BigInt(config.firstDepositAllowanceLamports);
973
1011
  }
974
1012
  /** Reserves with rates, cached for a minute. */
@@ -1006,17 +1044,63 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1006
1044
  if (candidates.length === 0) throw new KaminoError(`Market ${this.market} has no reserve for ${mint}.`);
1007
1045
  return candidates[0];
1008
1046
  }
1009
- /** Obligations and per-mint totals. */
1047
+ /**
1048
+ * Obligations and per-mint totals, read from the chain (watch 2026-11-04: the live API now answers
1049
+ * `deposits: {}` / `borrows: {}` and keeps the legs in its raw `state`, so its figures said "no
1050
+ * position" for wallets with millions supplied). The API only names the wallet's obligations; each
1051
+ * is read from the chain and must be the wallet's on this market, and the wallet's vanilla obligation
1052
+ * is read even when the API leaves it out. A listed obligation that no longer exists is closed.
1053
+ * Amounts are what each leg redeems for, or owes, at its reserve's on-chain rate.
1054
+ */
1010
1055
  async getPosition() {
1011
1056
  const me = await this.me();
1012
- const obligations = await this.api.getUserObligations(this.market, me);
1057
+ const rows = await this.api.getUserObligations(this.market, me);
1058
+ const vanilla = vanillaObligation(me, this.market, KLEND_PROGRAM);
1059
+ const addresses = [.../* @__PURE__ */ new Set([...rows.map((r) => r.obligation).filter((a) => ADDRESS.test(a)), vanilla])];
1060
+ const accounts = await this.readChain(addresses);
1061
+ const onChain = [];
1062
+ addresses.forEach((address, i) => {
1063
+ const acc = accounts[i];
1064
+ if (!acc) return;
1065
+ const o = decodeObligation(address, acc);
1066
+ if (o.owner !== me || o.lendingMarket !== this.market) throw new KaminoError(`Obligation ${address} is not ${me}'s on market ${this.market}.`);
1067
+ onChain.push([address, o]);
1068
+ });
1069
+ const reserves = await this.chainReserves(onChain.flatMap(([, o]) => [...o.deposits, ...o.borrows].map((l) => l.reserve)));
1070
+ const symbols = onChain.length ? new Map((await this.getReserves().catch(() => [])).map((r) => [r.reserve, r.symbol])) : /* @__PURE__ */ new Map();
1013
1071
  const supplied = {}, borrowed = {};
1014
- for (const o of obligations) {
1015
- for (const d of o.deposits) if (d.mint) supplied[d.mint] = (supplied[d.mint] ?? 0n) + fromDecimalString(d.amount, await this.decimals(d.mint));
1016
- for (const b of o.borrows) if (b.mint) borrowed[b.mint] = (borrowed[b.mint] ?? 0n) + fromDecimalString(b.amount, await this.decimals(b.mint));
1017
- }
1072
+ const obligations = onChain.map(([address, o]) => {
1073
+ const row = rows.find((r) => r.obligation === address);
1074
+ const leg = (reserve, amount, side, totals) => {
1075
+ const r = reserves.get(reserve);
1076
+ totals[r.mint] = (totals[r.mint] ?? 0n) + amount;
1077
+ const priced = row?.[side].filter((l) => l.mint === r.mint) ?? [];
1078
+ const alone = o[side].filter((l) => reserves.get(l.reserve).mint === r.mint).length === 1;
1079
+ return { mint: r.mint, symbol: symbols.get(reserve) ?? priced[0]?.symbol ?? "", amount: toDecimalString(amount, r.decimals), valueUsd: alone && priced.length === 1 ? priced[0].valueUsd : "", reserve };
1080
+ };
1081
+ const deposits = o.deposits.map((d) => leg(d.reserve, depositLegLiquidity(reserves.get(d.reserve), d.ctokens), "deposits", supplied));
1082
+ const borrows = o.borrows.map((b) => leg(b.reserve, debtLegNow(reserves.get(b.reserve), b), "borrows", borrowed));
1083
+ const base = row ?? { obligation: address, market: this.market, user: me, elevationGroup: 0, deposits: [], borrows: [], state: null, currentLtv: 0, maxLtv: null, liquidationLtv: 0, raw: null };
1084
+ return { ...base, deposits, borrows };
1085
+ });
1018
1086
  return { obligations, supplied, borrowed };
1019
1087
  }
1088
+ /**
1089
+ * Reserves of this market from the chain, keyed by address: each must be a klend Reserve on this
1090
+ * market. `known` (already read) is reused and filled in.
1091
+ */
1092
+ async chainReserves(addresses, known = /* @__PURE__ */ new Map()) {
1093
+ const missing = [...new Set(addresses)].filter((a) => !known.has(a));
1094
+ if (missing.length) {
1095
+ const accs = await this.readChain(missing);
1096
+ missing.forEach((a, i) => {
1097
+ const r = decodeReserve(a, accs[i] ?? null);
1098
+ if (r.lendingMarket !== this.market) throw new KaminoError(`Reserve ${a} belongs to market ${r.lendingMarket} on chain, not ${this.market}.`);
1099
+ known.set(a, r);
1100
+ });
1101
+ }
1102
+ return known;
1103
+ }
1020
1104
  /**
1021
1105
  * The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
1022
1106
  * the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
@@ -1061,28 +1145,39 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1061
1145
  const o = c.obligation;
1062
1146
  const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
1063
1147
  if (amount <= 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
1064
- const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals);
1148
+ const known = /* @__PURE__ */ new Map([[reserve, c.reserve]]);
1149
+ const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals, known);
1065
1150
  if (reported !== void 0) {
1066
- const legs = side === "supplied" ? o.deposits : o.borrows;
1067
- const others = [...new Set(legs.map((l) => l.reserve).filter((r) => r !== reserve))];
1068
- let perMint = amount;
1069
- if (others.length) {
1070
- const accs = await this.readChain(others);
1071
- others.forEach((r, i) => {
1072
- const rc = decodeReserve(r, accs[i] ?? null);
1073
- if (rc.mint === mint) perMint += side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r);
1074
- });
1075
- }
1151
+ const perMint = await this.perMint(side, o, mint, known);
1076
1152
  if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
1077
1153
  }
1078
1154
  return amount;
1079
1155
  }
1080
- /** The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. */
1081
- async reported(side, me, mint, obligation, decimals) {
1156
+ /** What the legs hold in, or owe of, `mint` across every reserve they name, at the reserves' on-chain rates. */
1157
+ async perMint(side, o, mint, known) {
1158
+ const legs = side === "supplied" ? o.deposits : o.borrows;
1159
+ const reserves = await this.chainReserves(legs.map((l) => l.reserve), known);
1160
+ return [...new Set(legs.map((l) => l.reserve))].reduce((sum, r) => {
1161
+ const rc = reserves.get(r);
1162
+ return rc.mint !== mint ? sum : sum + (side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r));
1163
+ }, 0n);
1164
+ }
1165
+ /**
1166
+ * The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. Its
1167
+ * decorated per-token legs count when it gives them; the live API (2026-10-28 on) leaves them empty and
1168
+ * keeps the account's legs in the row's raw `state` (cTokens, scaled debt), which are valued at the
1169
+ * reserves' on-chain rates, so a `state` that is not the chain's obligation is refused all the same.
1170
+ */
1171
+ async reported(side, me, mint, obligation, decimals, known) {
1082
1172
  const row = (await this.api.getUserObligations(this.market, me)).find((x) => x.obligation === obligation);
1083
- const legs = (side === "supplied" ? row?.deposits : row?.borrows)?.filter((l) => l.mint === mint) ?? [];
1084
- if (!legs.length) return void 0;
1085
- return legs.reduce((sum, l) => sum + fromDecimalString(l.amount, decimals), 0n);
1173
+ if (!row) return void 0;
1174
+ const legs = (side === "supplied" ? row.deposits : row.borrows).filter((l) => l.mint === mint);
1175
+ if (legs.length) return legs.reduce((sum, l) => sum + fromDecimalString(l.amount, decimals), 0n);
1176
+ if (!row.state) return void 0;
1177
+ const stateLegs = side === "supplied" ? row.state.deposits : row.state.borrows;
1178
+ const reserves = await this.chainReserves(stateLegs.map((l) => l.reserve), known);
1179
+ if (!stateLegs.some((l) => reserves.get(l.reserve).mint === mint)) return void 0;
1180
+ return this.perMint(side, row.state, mint, known);
1086
1181
  }
1087
1182
  async quoteSupply(o) {
1088
1183
  const me = await this.me();
@@ -1186,12 +1281,14 @@ export {
1186
1281
  WITHDRAW_ALL,
1187
1282
  WSOL_MINT,
1188
1283
  associatedTokenAddress,
1284
+ debtLegNow,
1189
1285
  debtNow,
1190
1286
  decodeFarmUser,
1191
1287
  decodeObligation,
1192
1288
  decodeReserve,
1193
1289
  decodeVault,
1194
1290
  KaminoVaultProtocolSolana as default,
1291
+ depositLegLiquidity,
1195
1292
  depositedLiquidity,
1196
1293
  divWadUp,
1197
1294
  farmUserState,