@anywalletkit/protocol-lending-kamino-solana 0.3.1 → 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) {
@@ -527,29 +560,38 @@ function collateralToLiquiditySf(r, ctokens) {
527
560
  if (r.collateralSupply === 0n || r.totalLiquiditySf === 0n) return ctokens * SF;
528
561
  return ctokens * r.totalLiquiditySf / r.collateralSupply;
529
562
  }
563
+ function oneCtokenLiquidityUp(r) {
564
+ const sf = r.collateralSupply === 0n || r.totalLiquiditySf === 0n ? SF : (r.totalLiquiditySf + r.collateralSupply - 1n) / r.collateralSupply;
565
+ const units = (sf + SF - 1n) / SF;
566
+ return units > 0n ? units : 1n;
567
+ }
530
568
  function decodeObligation(address, acc) {
531
569
  const d = bytesOf("Obligation", address, acc);
532
570
  const deposits = [], borrows = [];
533
571
  for (let i = 0; i < 8; i++) {
534
572
  const o = 96 + i * 136;
535
573
  const reserve = key(d, o);
536
- 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) });
537
575
  }
538
576
  for (let i = 0; i < 5; i++) {
539
577
  const o = 1208 + i * 200;
540
578
  const reserve = key(d, o);
541
- 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) });
542
580
  }
543
581
  return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
544
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
+ }
545
590
  function depositedLiquidity(o, r, reserve) {
546
- 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);
547
592
  }
548
593
  function debtNow(o, r, reserve) {
549
- return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => {
550
- const sf = x.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > x.cumulativeBorrowRate ? x.borrowedSf * r.cumulativeBorrowRate / x.cumulativeBorrowRate : x.borrowedSf;
551
- return sum + (sf + SF - 1n) / SF;
552
- }, 0n);
594
+ return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + debtLegNow(r, x), 0n);
553
595
  }
554
596
  function decodeFarmUser(address, acc) {
555
597
  const d = bytesOf("UserState", address, acc);
@@ -956,6 +998,7 @@ function symbolOf(v) {
956
998
  }
957
999
 
958
1000
  // src/market.ts
1001
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
959
1002
  var KaminoMarketProtocolSolana = class extends KaminoBase {
960
1003
  market;
961
1004
  firstDepositAllowance;
@@ -963,7 +1006,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
963
1006
  constructor(account, config = {}) {
964
1007
  super(account, config);
965
1008
  this.market = config?.market ?? MAIN_MARKET;
966
- 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.");
967
1010
  this.firstDepositAllowance = config?.firstDepositAllowanceLamports === void 0 ? DEFAULT_FIRST_DEPOSIT_ALLOWANCE : BigInt(config.firstDepositAllowanceLamports);
968
1011
  }
969
1012
  /** Reserves with rates, cached for a minute. */
@@ -1001,17 +1044,63 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1001
1044
  if (candidates.length === 0) throw new KaminoError(`Market ${this.market} has no reserve for ${mint}.`);
1002
1045
  return candidates[0];
1003
1046
  }
1004
- /** 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
+ */
1005
1055
  async getPosition() {
1006
1056
  const me = await this.me();
1007
- 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();
1008
1071
  const supplied = {}, borrowed = {};
1009
- for (const o of obligations) {
1010
- for (const d of o.deposits) if (d.mint) supplied[d.mint] = (supplied[d.mint] ?? 0n) + fromDecimalString(d.amount, await this.decimals(d.mint));
1011
- for (const b of o.borrows) if (b.mint) borrowed[b.mint] = (borrowed[b.mint] ?? 0n) + fromDecimalString(b.amount, await this.decimals(b.mint));
1012
- }
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
+ });
1013
1086
  return { obligations, supplied, borrowed };
1014
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
+ }
1015
1104
  /**
1016
1105
  * The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
1017
1106
  * the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
@@ -1056,28 +1145,39 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1056
1145
  const o = c.obligation;
1057
1146
  const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
1058
1147
  if (amount <= 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
1059
- 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);
1060
1150
  if (reported !== void 0) {
1061
- const legs = side === "supplied" ? o.deposits : o.borrows;
1062
- const others = [...new Set(legs.map((l) => l.reserve).filter((r) => r !== reserve))];
1063
- let perMint = amount;
1064
- if (others.length) {
1065
- const accs = await this.readChain(others);
1066
- others.forEach((r, i) => {
1067
- const rc = decodeReserve(r, accs[i] ?? null);
1068
- if (rc.mint === mint) perMint += side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r);
1069
- });
1070
- }
1151
+ const perMint = await this.perMint(side, o, mint, known);
1071
1152
  if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
1072
1153
  }
1073
1154
  return amount;
1074
1155
  }
1075
- /** The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. */
1076
- 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) {
1077
1172
  const row = (await this.api.getUserObligations(this.market, me)).find((x) => x.obligation === obligation);
1078
- const legs = (side === "supplied" ? row?.deposits : row?.borrows)?.filter((l) => l.mint === mint) ?? [];
1079
- if (!legs.length) return void 0;
1080
- 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);
1081
1181
  }
1082
1182
  async quoteSupply(o) {
1083
1183
  const me = await this.me();
@@ -1093,11 +1193,21 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1093
1193
  const base64 = await this.build("deposit", me, p);
1094
1194
  return this.sendBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules, "supply");
1095
1195
  }
1196
+ /**
1197
+ * A withdrawal pays out about what was asked: at least the amount less the slippage tolerance, at
1198
+ * most the amount plus that tolerance (interest accrued before the block, on a 'max'), one cToken's
1199
+ * worth at the reserve's on-chain rate (klend redeems whole cTokens) and a unit of rounding. A bigger
1200
+ * payout is collateral the user did not choose to take out of the obligation.
1201
+ */
1202
+ withdrawExpectation(mint, p) {
1203
+ const max = p.amount + (p.amount - lessBps(p.amount, this.slippageBps)) + oneCtokenLiquidityUp(p.chain.reserve) + 1n;
1204
+ return this.receiveExpectation(mint, p.amount, 0n, max);
1205
+ }
1096
1206
  async quoteWithdraw(o) {
1097
1207
  const me = await this.me();
1098
1208
  const p = await this.prepare("withdraw", me, o.token, o.amount);
1099
1209
  const base64 = await this.build("withdraw", me, p);
1100
- const expect = this.receiveExpectation(o.token, p.amount);
1210
+ const expect = this.withdrawExpectation(o.token, p);
1101
1211
  const { fee } = await this.quoteBuilt(base64, expect, p.rules);
1102
1212
  return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
1103
1213
  }
@@ -1106,7 +1216,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1106
1216
  const me = await this.me();
1107
1217
  const p = await this.prepare("withdraw", me, o.token, o.amount);
1108
1218
  const base64 = await this.build("withdraw", me, p);
1109
- return this.sendBuilt(base64, this.receiveExpectation(o.token, p.amount), p.rules, "withdraw");
1219
+ return this.sendBuilt(base64, this.withdrawExpectation(o.token, p), p.rules, "withdraw");
1110
1220
  }
1111
1221
  /** A borrow pays out at most what was asked: a bigger one is debt the user did not choose. */
1112
1222
  borrowExpectation(mint, amount) {
@@ -1171,12 +1281,14 @@ export {
1171
1281
  WITHDRAW_ALL,
1172
1282
  WSOL_MINT,
1173
1283
  associatedTokenAddress,
1284
+ debtLegNow,
1174
1285
  debtNow,
1175
1286
  decodeFarmUser,
1176
1287
  decodeObligation,
1177
1288
  decodeReserve,
1178
1289
  decodeVault,
1179
1290
  KaminoVaultProtocolSolana as default,
1291
+ depositLegLiquidity,
1180
1292
  depositedLiquidity,
1181
1293
  divWadUp,
1182
1294
  farmUserState,