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

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/README.md CHANGED
@@ -63,9 +63,15 @@ from its shares account and farm stake, a Lend 'max' from the obligation
63
63
  (debt with the reserve's accrued interest), and the reserve the API names
64
64
  must be this market's and lend that token. An API figure that disagrees —
65
65
  a `tokensPerShare` more than 1 % off, a reported deposit or debt that is not
66
- the obligation's, any negative figure — is refused, never used. Reads
67
- (`getVault`, `getPosition`, APY, TVL) stay the API's; mint decimals are read
68
- when the account has an RPC, else taken from a table of Kamino's listed mints.
66
+ the obligation's (the API's per-token legs, or the cTokens and scaled debt in
67
+ its raw obligation `state`, valued at the reserves' on-chain rates), any
68
+ negative figure — is refused, never used. A Lend market's `getPosition` reads
69
+ the wallet's obligations from the chain too: the API only names them (each
70
+ must be the wallet's on this market; the vanilla one is read even when the
71
+ API leaves it out), and every leg is what it redeems for, or owes, at its
72
+ reserve's on-chain rate. Other reads (`getVault`, a vault's `getPosition`,
73
+ APY, TVL, LTVs, USD values) stay the API's; mint decimals are read when the
74
+ account has an RPC, else taken from a table of Kamino's listed mints.
69
75
 
70
76
  ## Usage
71
77
 
@@ -95,7 +101,7 @@ const market = new KaminoMarketProtocolSolana(account) // Main Market
95
101
  await market.getReserves() // symbol, mint, supply / borrow APY (%), max LTV, TVL, utilization
96
102
  await market.supply({ token: USDC, amount: 5_000_000n }) // collateral on the wallet's obligation
97
103
  await market.borrow({ token: USDC, amount: 1_000_000n })
98
- await market.getPosition() // { obligations, supplied: {mint: units}, borrowed }
104
+ await market.getPosition() // { obligations, supplied: {mint: units}, borrowed } — from the chain
99
105
  await market.repay({ token: USDC, amount: 'max' })
100
106
  await market.withdraw({ token: USDC, amount: 'max' })
101
107
  ```
@@ -118,9 +124,13 @@ reserves) resolves to the deepest one by supplied value; pin another with
118
124
  ## Verify
119
125
 
120
126
  `pnpm test` (fixtures copied from live API responses). `pnpm verify:live
121
- [address]` reads markets, reserves and vaults from the API, then builds a vault
122
- deposit and a Lend deposit for the address and runs both through the guard as
123
- a read-only account (no keys, no writes).
127
+ [address] [rpcUrl] [lendAddress]` reads markets, reserves and vaults from the
128
+ API, then builds a vault deposit and a Lend deposit for the address, and a Lend
129
+ withdraw for a wallet with USDC supplied on the main market, and runs each
130
+ through the guard as a read-only account (no keys, no writes); that wallet's
131
+ `getPosition` must match its obligation on chain. A holder whose USDC account
132
+ is frozen is named and refused before anything is built; one without USDC
133
+ skips the deposits and still runs the withdraw.
124
134
 
125
135
  Program ids: Kamino Lend `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD`, kVault
126
136
  `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd`, Farms
package/dist/index.cjs CHANGED
@@ -44,12 +44,14 @@ __export(src_exports, {
44
44
  WITHDRAW_ALL: () => WITHDRAW_ALL,
45
45
  WSOL_MINT: () => WSOL_MINT,
46
46
  associatedTokenAddress: () => associatedTokenAddress,
47
+ debtLegNow: () => debtLegNow,
47
48
  debtNow: () => debtNow,
48
49
  decodeFarmUser: () => decodeFarmUser,
49
50
  decodeObligation: () => decodeObligation,
50
51
  decodeReserve: () => decodeReserve,
51
52
  decodeVault: () => decodeVault,
52
53
  default: () => KaminoVaultProtocolSolana,
54
+ depositLegLiquidity: () => depositLegLiquidity,
53
55
  depositedLiquidity: () => depositedLiquidity,
54
56
  divWadUp: () => divWadUp,
55
57
  farmUserState: () => farmUserState,
@@ -149,6 +151,35 @@ var pct = (x) => x === null || x === void 0 ? 0 : Number(x) * 100;
149
151
  var num = (x, d = 0) => x === null || x === void 0 || x === "" ? d : Number(x);
150
152
  var big = (x) => x === null || x === void 0 ? 0n : BigInt(String(x).split(".")[0]);
151
153
  var str = (x) => x === null || x === void 0 ? "0" : String(x);
154
+ var DEFAULT_KEY = "11111111111111111111111111111111";
155
+ function uint(x, what, bits) {
156
+ let v;
157
+ if (typeof x === "number" && Number.isSafeInteger(x) && x >= 0) v = BigInt(x);
158
+ else if (typeof x === "string" && x.length <= 40 && /^\d+$/.test(x)) v = BigInt(x);
159
+ 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}.`);
160
+ return v;
161
+ }
162
+ function u256Limbs(x, what) {
163
+ const limbs = x?.value;
164
+ if (!Array.isArray(limbs) || limbs.length !== 4) throw new KaminoError(`Kamino reported ${what} without its four limbs.`);
165
+ return limbs.reduce((sum, l, i) => sum + (uint(l, `a limb of ${what}`, 64) << BigInt(64 * i)), 0n);
166
+ }
167
+ function obligationState(x) {
168
+ if (!x || typeof x !== "object") return null;
169
+ const s = x;
170
+ if (!Array.isArray(s.deposits) && !Array.isArray(s.borrows)) return null;
171
+ const slots = (v, key2) => (Array.isArray(v) ? v : []).filter((l) => !!l && typeof l === "object" && String(l[key2] ?? DEFAULT_KEY) !== DEFAULT_KEY);
172
+ return {
173
+ owner: String(s.owner ?? ""),
174
+ lendingMarket: String(s.lendingMarket ?? ""),
175
+ deposits: slots(s.deposits, "depositReserve").map((l) => ({ reserve: String(l.depositReserve), ctokens: uint(l.depositedAmount, "a deposit's depositedAmount", 64) })),
176
+ borrows: slots(s.borrows, "borrowReserve").map((l) => ({
177
+ reserve: String(l.borrowReserve),
178
+ borrowedSf: uint(l.borrowedAmountSf, "a borrow's borrowedAmountSf", 128),
179
+ cumulativeBorrowRate: u256Limbs(l.cumulativeBorrowRateBsf, "a borrow's cumulativeBorrowRateBsf")
180
+ }))
181
+ };
182
+ }
152
183
  var KaminoApi = class {
153
184
  /** `timeoutMs` bounds each call (default 15 s): a silent API must not hang a read or a write's build. */
154
185
  constructor(endpoint = KAMINO_API, fetchImpl = fetch, timeoutMs = 15e3) {
@@ -288,16 +319,20 @@ var KaminoApi = class {
288
319
  valueUsd: str(l.tokenValue ?? l.valueUsd)
289
320
  }));
290
321
  const coll = info.collateral ?? {}, debt = info.debt ?? {};
322
+ const stats = row.refreshedStats ?? {}, st = row.state ?? {};
323
+ const deposited = num(stats.userTotalDeposit);
324
+ const maxLtv = stats.borrowLimit !== void 0 && deposited > 0 ? num(stats.borrowLimit) / deposited : info.maxLtv === null || info.maxLtv === void 0 ? null : num(info.maxLtv);
291
325
  return {
292
326
  obligation: String(row.obligationAddress ?? row.loanId ?? row.obligation ?? row.address ?? ""),
293
327
  market: String(row.marketId ?? market),
294
328
  user: String(row.user ?? ""),
295
- elevationGroup: num(row.elevationGroup),
329
+ elevationGroup: num(st.elevationGroup ?? row.elevationGroup),
296
330
  deposits: legs(coll.deposits ?? row.deposits),
297
331
  borrows: legs(debt.borrows ?? row.borrows),
298
- currentLtv: num(info.currentLtv),
299
- maxLtv: info.maxLtv === null || info.maxLtv === void 0 ? null : num(info.maxLtv),
300
- liquidationLtv: num(info.liquidationLtv),
332
+ state: obligationState(row.state),
333
+ currentLtv: num(stats.loanToValue ?? info.currentLtv),
334
+ maxLtv,
335
+ liquidationLtv: num(stats.liquidationLtv ?? info.liquidationLtv),
301
336
  raw: row
302
337
  };
303
338
  }
@@ -534,7 +569,7 @@ var import_base = require("@scure/base");
534
569
  var SF = 1n << 60n;
535
570
  var FARM_STAKE_SCALE = 10n ** 18n;
536
571
  var CHAIN_TOLERANCE_BPS = 100n;
537
- var DEFAULT_KEY = "11111111111111111111111111111111";
572
+ var DEFAULT_KEY2 = "11111111111111111111111111111111";
538
573
  var KINDS = {
539
574
  VaultState: { program: KVAULT_PROGRAM, disc: "e4c452a562d2eb98", size: 62552 },
540
575
  Reserve: { program: KLEND_PROGRAM, disc: "2bf2ccca1af73b7f", size: 8624 },
@@ -564,7 +599,7 @@ function decodeVault(address, acc) {
564
599
  for (let i = 0; i < 25; i++) {
565
600
  const o = 312 + i * 2160;
566
601
  const reserve = key(d, o);
567
- if (reserve !== DEFAULT_KEY) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
602
+ if (reserve !== DEFAULT_KEY2) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
568
603
  }
569
604
  const farm = key(d, 58600);
570
605
  return {
@@ -579,7 +614,7 @@ function decodeVault(address, acc) {
579
614
  allocations,
580
615
  minDeposit: u64(d, 58408),
581
616
  minWithdraw: u64(d, 58416),
582
- farm: farm === DEFAULT_KEY ? null : farm
617
+ farm: farm === DEFAULT_KEY2 ? null : farm
583
618
  };
584
619
  }
585
620
  function decodeReserve(address, acc) {
@@ -610,23 +645,27 @@ function decodeObligation(address, acc) {
610
645
  for (let i = 0; i < 8; i++) {
611
646
  const o = 96 + i * 136;
612
647
  const reserve = key(d, o);
613
- if (reserve !== DEFAULT_KEY) deposits.push({ reserve, ctokens: u64(d, o + 32) });
648
+ if (reserve !== DEFAULT_KEY2) deposits.push({ reserve, ctokens: u64(d, o + 32) });
614
649
  }
615
650
  for (let i = 0; i < 5; i++) {
616
651
  const o = 1208 + i * 200;
617
652
  const reserve = key(d, o);
618
- if (reserve !== DEFAULT_KEY) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
653
+ if (reserve !== DEFAULT_KEY2) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
619
654
  }
620
655
  return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
621
656
  }
657
+ function depositLegLiquidity(r, ctokens) {
658
+ return collateralToLiquiditySf(r, ctokens) / SF;
659
+ }
660
+ function debtLegNow(r, leg) {
661
+ const sf = leg.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > leg.cumulativeBorrowRate ? leg.borrowedSf * r.cumulativeBorrowRate / leg.cumulativeBorrowRate : leg.borrowedSf;
662
+ return (sf + SF - 1n) / SF;
663
+ }
622
664
  function depositedLiquidity(o, r, reserve) {
623
- return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + collateralToLiquiditySf(r, x.ctokens) / SF, 0n);
665
+ return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + depositLegLiquidity(r, x.ctokens), 0n);
624
666
  }
625
667
  function debtNow(o, r, reserve) {
626
- return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => {
627
- const sf = x.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > x.cumulativeBorrowRate ? x.borrowedSf * r.cumulativeBorrowRate / x.cumulativeBorrowRate : x.borrowedSf;
628
- return sum + (sf + SF - 1n) / SF;
629
- }, 0n);
668
+ return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + debtLegNow(r, x), 0n);
630
669
  }
631
670
  function decodeFarmUser(address, acc) {
632
671
  const d = bytesOf("UserState", address, acc);
@@ -1033,6 +1072,7 @@ function symbolOf(v) {
1033
1072
  }
1034
1073
 
1035
1074
  // src/market.ts
1075
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
1036
1076
  var KaminoMarketProtocolSolana = class extends KaminoBase {
1037
1077
  market;
1038
1078
  firstDepositAllowance;
@@ -1040,7 +1080,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1040
1080
  constructor(account, config = {}) {
1041
1081
  super(account, config);
1042
1082
  this.market = config?.market ?? MAIN_MARKET;
1043
- if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
1083
+ if (!ADDRESS.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
1044
1084
  this.firstDepositAllowance = config?.firstDepositAllowanceLamports === void 0 ? DEFAULT_FIRST_DEPOSIT_ALLOWANCE : BigInt(config.firstDepositAllowanceLamports);
1045
1085
  }
1046
1086
  /** Reserves with rates, cached for a minute. */
@@ -1078,17 +1118,63 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1078
1118
  if (candidates.length === 0) throw new KaminoError(`Market ${this.market} has no reserve for ${mint}.`);
1079
1119
  return candidates[0];
1080
1120
  }
1081
- /** Obligations and per-mint totals. */
1121
+ /**
1122
+ * Obligations and per-mint totals, read from the chain (watch 2026-11-04: the live API now answers
1123
+ * `deposits: {}` / `borrows: {}` and keeps the legs in its raw `state`, so its figures said "no
1124
+ * position" for wallets with millions supplied). The API only names the wallet's obligations; each
1125
+ * is read from the chain and must be the wallet's on this market, and the wallet's vanilla obligation
1126
+ * is read even when the API leaves it out. A listed obligation that no longer exists is closed.
1127
+ * Amounts are what each leg redeems for, or owes, at its reserve's on-chain rate.
1128
+ */
1082
1129
  async getPosition() {
1083
1130
  const me = await this.me();
1084
- const obligations = await this.api.getUserObligations(this.market, me);
1131
+ const rows = await this.api.getUserObligations(this.market, me);
1132
+ const vanilla = vanillaObligation(me, this.market, KLEND_PROGRAM);
1133
+ const addresses = [.../* @__PURE__ */ new Set([...rows.map((r) => r.obligation).filter((a) => ADDRESS.test(a)), vanilla])];
1134
+ const accounts = await this.readChain(addresses);
1135
+ const onChain = [];
1136
+ addresses.forEach((address, i) => {
1137
+ const acc = accounts[i];
1138
+ if (!acc) return;
1139
+ const o = decodeObligation(address, acc);
1140
+ if (o.owner !== me || o.lendingMarket !== this.market) throw new KaminoError(`Obligation ${address} is not ${me}'s on market ${this.market}.`);
1141
+ onChain.push([address, o]);
1142
+ });
1143
+ const reserves = await this.chainReserves(onChain.flatMap(([, o]) => [...o.deposits, ...o.borrows].map((l) => l.reserve)));
1144
+ const symbols = onChain.length ? new Map((await this.getReserves().catch(() => [])).map((r) => [r.reserve, r.symbol])) : /* @__PURE__ */ new Map();
1085
1145
  const supplied = {}, borrowed = {};
1086
- for (const o of obligations) {
1087
- for (const d of o.deposits) if (d.mint) supplied[d.mint] = (supplied[d.mint] ?? 0n) + fromDecimalString(d.amount, await this.decimals(d.mint));
1088
- for (const b of o.borrows) if (b.mint) borrowed[b.mint] = (borrowed[b.mint] ?? 0n) + fromDecimalString(b.amount, await this.decimals(b.mint));
1089
- }
1146
+ const obligations = onChain.map(([address, o]) => {
1147
+ const row = rows.find((r) => r.obligation === address);
1148
+ const leg = (reserve, amount, side, totals) => {
1149
+ const r = reserves.get(reserve);
1150
+ totals[r.mint] = (totals[r.mint] ?? 0n) + amount;
1151
+ const priced = row?.[side].filter((l) => l.mint === r.mint) ?? [];
1152
+ const alone = o[side].filter((l) => reserves.get(l.reserve).mint === r.mint).length === 1;
1153
+ 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 };
1154
+ };
1155
+ const deposits = o.deposits.map((d) => leg(d.reserve, depositLegLiquidity(reserves.get(d.reserve), d.ctokens), "deposits", supplied));
1156
+ const borrows = o.borrows.map((b) => leg(b.reserve, debtLegNow(reserves.get(b.reserve), b), "borrows", borrowed));
1157
+ const base = row ?? { obligation: address, market: this.market, user: me, elevationGroup: 0, deposits: [], borrows: [], state: null, currentLtv: 0, maxLtv: null, liquidationLtv: 0, raw: null };
1158
+ return { ...base, deposits, borrows };
1159
+ });
1090
1160
  return { obligations, supplied, borrowed };
1091
1161
  }
1162
+ /**
1163
+ * Reserves of this market from the chain, keyed by address: each must be a klend Reserve on this
1164
+ * market. `known` (already read) is reused and filled in.
1165
+ */
1166
+ async chainReserves(addresses, known = /* @__PURE__ */ new Map()) {
1167
+ const missing = [...new Set(addresses)].filter((a) => !known.has(a));
1168
+ if (missing.length) {
1169
+ const accs = await this.readChain(missing);
1170
+ missing.forEach((a, i) => {
1171
+ const r = decodeReserve(a, accs[i] ?? null);
1172
+ if (r.lendingMarket !== this.market) throw new KaminoError(`Reserve ${a} belongs to market ${r.lendingMarket} on chain, not ${this.market}.`);
1173
+ known.set(a, r);
1174
+ });
1175
+ }
1176
+ return known;
1177
+ }
1092
1178
  /**
1093
1179
  * The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
1094
1180
  * the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
@@ -1133,28 +1219,39 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
1133
1219
  const o = c.obligation;
1134
1220
  const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
1135
1221
  if (amount <= 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
1136
- const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals);
1222
+ const known = /* @__PURE__ */ new Map([[reserve, c.reserve]]);
1223
+ const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals, known);
1137
1224
  if (reported !== void 0) {
1138
- const legs = side === "supplied" ? o.deposits : o.borrows;
1139
- const others = [...new Set(legs.map((l) => l.reserve).filter((r) => r !== reserve))];
1140
- let perMint = amount;
1141
- if (others.length) {
1142
- const accs = await this.readChain(others);
1143
- others.forEach((r, i) => {
1144
- const rc = decodeReserve(r, accs[i] ?? null);
1145
- if (rc.mint === mint) perMint += side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r);
1146
- });
1147
- }
1225
+ const perMint = await this.perMint(side, o, mint, known);
1148
1226
  if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
1149
1227
  }
1150
1228
  return amount;
1151
1229
  }
1152
- /** The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. */
1153
- async reported(side, me, mint, obligation, decimals) {
1230
+ /** What the legs hold in, or owe of, `mint` across every reserve they name, at the reserves' on-chain rates. */
1231
+ async perMint(side, o, mint, known) {
1232
+ const legs = side === "supplied" ? o.deposits : o.borrows;
1233
+ const reserves = await this.chainReserves(legs.map((l) => l.reserve), known);
1234
+ return [...new Set(legs.map((l) => l.reserve))].reduce((sum, r) => {
1235
+ const rc = reserves.get(r);
1236
+ return rc.mint !== mint ? sum : sum + (side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r));
1237
+ }, 0n);
1238
+ }
1239
+ /**
1240
+ * The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. Its
1241
+ * decorated per-token legs count when it gives them; the live API (2026-10-28 on) leaves them empty and
1242
+ * keeps the account's legs in the row's raw `state` (cTokens, scaled debt), which are valued at the
1243
+ * reserves' on-chain rates, so a `state` that is not the chain's obligation is refused all the same.
1244
+ */
1245
+ async reported(side, me, mint, obligation, decimals, known) {
1154
1246
  const row = (await this.api.getUserObligations(this.market, me)).find((x) => x.obligation === obligation);
1155
- const legs = (side === "supplied" ? row?.deposits : row?.borrows)?.filter((l) => l.mint === mint) ?? [];
1156
- if (!legs.length) return void 0;
1157
- return legs.reduce((sum, l) => sum + fromDecimalString(l.amount, decimals), 0n);
1247
+ if (!row) return void 0;
1248
+ const legs = (side === "supplied" ? row.deposits : row.borrows).filter((l) => l.mint === mint);
1249
+ if (legs.length) return legs.reduce((sum, l) => sum + fromDecimalString(l.amount, decimals), 0n);
1250
+ if (!row.state) return void 0;
1251
+ const stateLegs = side === "supplied" ? row.state.deposits : row.state.borrows;
1252
+ const reserves = await this.chainReserves(stateLegs.map((l) => l.reserve), known);
1253
+ if (!stateLegs.some((l) => reserves.get(l.reserve).mint === mint)) return void 0;
1254
+ return this.perMint(side, row.state, mint, known);
1158
1255
  }
1159
1256
  async quoteSupply(o) {
1160
1257
  const me = await this.me();