@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/README.md +17 -7
- package/dist/index.cjs +151 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +130 -78
- package/dist/index.d.ts +130 -78
- package/dist/index.js +151 -39
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
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
|
|
67
|
-
|
|
68
|
-
|
|
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
|
|
122
|
-
deposit and a Lend deposit for the address and
|
|
123
|
-
a
|
|
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
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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
|
|
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 !==
|
|
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 ===
|
|
617
|
+
farm: farm === DEFAULT_KEY2 ? null : farm
|
|
583
618
|
};
|
|
584
619
|
}
|
|
585
620
|
function decodeReserve(address, acc) {
|
|
@@ -599,29 +634,38 @@ function collateralToLiquiditySf(r, ctokens) {
|
|
|
599
634
|
if (r.collateralSupply === 0n || r.totalLiquiditySf === 0n) return ctokens * SF;
|
|
600
635
|
return ctokens * r.totalLiquiditySf / r.collateralSupply;
|
|
601
636
|
}
|
|
637
|
+
function oneCtokenLiquidityUp(r) {
|
|
638
|
+
const sf = r.collateralSupply === 0n || r.totalLiquiditySf === 0n ? SF : (r.totalLiquiditySf + r.collateralSupply - 1n) / r.collateralSupply;
|
|
639
|
+
const units = (sf + SF - 1n) / SF;
|
|
640
|
+
return units > 0n ? units : 1n;
|
|
641
|
+
}
|
|
602
642
|
function decodeObligation(address, acc) {
|
|
603
643
|
const d = bytesOf("Obligation", address, acc);
|
|
604
644
|
const deposits = [], borrows = [];
|
|
605
645
|
for (let i = 0; i < 8; i++) {
|
|
606
646
|
const o = 96 + i * 136;
|
|
607
647
|
const reserve = key(d, o);
|
|
608
|
-
if (reserve !==
|
|
648
|
+
if (reserve !== DEFAULT_KEY2) deposits.push({ reserve, ctokens: u64(d, o + 32) });
|
|
609
649
|
}
|
|
610
650
|
for (let i = 0; i < 5; i++) {
|
|
611
651
|
const o = 1208 + i * 200;
|
|
612
652
|
const reserve = key(d, o);
|
|
613
|
-
if (reserve !==
|
|
653
|
+
if (reserve !== DEFAULT_KEY2) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
|
|
614
654
|
}
|
|
615
655
|
return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
|
|
616
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
|
+
}
|
|
617
664
|
function depositedLiquidity(o, r, reserve) {
|
|
618
|
-
return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum +
|
|
665
|
+
return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + depositLegLiquidity(r, x.ctokens), 0n);
|
|
619
666
|
}
|
|
620
667
|
function debtNow(o, r, reserve) {
|
|
621
|
-
return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) =>
|
|
622
|
-
const sf = x.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > x.cumulativeBorrowRate ? x.borrowedSf * r.cumulativeBorrowRate / x.cumulativeBorrowRate : x.borrowedSf;
|
|
623
|
-
return sum + (sf + SF - 1n) / SF;
|
|
624
|
-
}, 0n);
|
|
668
|
+
return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + debtLegNow(r, x), 0n);
|
|
625
669
|
}
|
|
626
670
|
function decodeFarmUser(address, acc) {
|
|
627
671
|
const d = bytesOf("UserState", address, acc);
|
|
@@ -1028,6 +1072,7 @@ function symbolOf(v) {
|
|
|
1028
1072
|
}
|
|
1029
1073
|
|
|
1030
1074
|
// src/market.ts
|
|
1075
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
1031
1076
|
var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
1032
1077
|
market;
|
|
1033
1078
|
firstDepositAllowance;
|
|
@@ -1035,7 +1080,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
1035
1080
|
constructor(account, config = {}) {
|
|
1036
1081
|
super(account, config);
|
|
1037
1082
|
this.market = config?.market ?? MAIN_MARKET;
|
|
1038
|
-
if (
|
|
1083
|
+
if (!ADDRESS.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
|
|
1039
1084
|
this.firstDepositAllowance = config?.firstDepositAllowanceLamports === void 0 ? DEFAULT_FIRST_DEPOSIT_ALLOWANCE : BigInt(config.firstDepositAllowanceLamports);
|
|
1040
1085
|
}
|
|
1041
1086
|
/** Reserves with rates, cached for a minute. */
|
|
@@ -1073,17 +1118,63 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
1073
1118
|
if (candidates.length === 0) throw new KaminoError(`Market ${this.market} has no reserve for ${mint}.`);
|
|
1074
1119
|
return candidates[0];
|
|
1075
1120
|
}
|
|
1076
|
-
/**
|
|
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
|
+
*/
|
|
1077
1129
|
async getPosition() {
|
|
1078
1130
|
const me = await this.me();
|
|
1079
|
-
const
|
|
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();
|
|
1080
1145
|
const supplied = {}, borrowed = {};
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
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
|
+
});
|
|
1085
1160
|
return { obligations, supplied, borrowed };
|
|
1086
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
|
+
}
|
|
1087
1178
|
/**
|
|
1088
1179
|
* The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
|
|
1089
1180
|
* the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
|
|
@@ -1128,28 +1219,39 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
1128
1219
|
const o = c.obligation;
|
|
1129
1220
|
const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
|
|
1130
1221
|
if (amount <= 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
|
|
1131
|
-
const
|
|
1222
|
+
const known = /* @__PURE__ */ new Map([[reserve, c.reserve]]);
|
|
1223
|
+
const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals, known);
|
|
1132
1224
|
if (reported !== void 0) {
|
|
1133
|
-
const
|
|
1134
|
-
const others = [...new Set(legs.map((l) => l.reserve).filter((r) => r !== reserve))];
|
|
1135
|
-
let perMint = amount;
|
|
1136
|
-
if (others.length) {
|
|
1137
|
-
const accs = await this.readChain(others);
|
|
1138
|
-
others.forEach((r, i) => {
|
|
1139
|
-
const rc = decodeReserve(r, accs[i] ?? null);
|
|
1140
|
-
if (rc.mint === mint) perMint += side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r);
|
|
1141
|
-
});
|
|
1142
|
-
}
|
|
1225
|
+
const perMint = await this.perMint(side, o, mint, known);
|
|
1143
1226
|
if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
|
|
1144
1227
|
}
|
|
1145
1228
|
return amount;
|
|
1146
1229
|
}
|
|
1147
|
-
/**
|
|
1148
|
-
async
|
|
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) {
|
|
1149
1246
|
const row = (await this.api.getUserObligations(this.market, me)).find((x) => x.obligation === obligation);
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
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);
|
|
1153
1255
|
}
|
|
1154
1256
|
async quoteSupply(o) {
|
|
1155
1257
|
const me = await this.me();
|
|
@@ -1165,11 +1267,21 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
1165
1267
|
const base64 = await this.build("deposit", me, p);
|
|
1166
1268
|
return this.sendBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules, "supply");
|
|
1167
1269
|
}
|
|
1270
|
+
/**
|
|
1271
|
+
* A withdrawal pays out about what was asked: at least the amount less the slippage tolerance, at
|
|
1272
|
+
* most the amount plus that tolerance (interest accrued before the block, on a 'max'), one cToken's
|
|
1273
|
+
* worth at the reserve's on-chain rate (klend redeems whole cTokens) and a unit of rounding. A bigger
|
|
1274
|
+
* payout is collateral the user did not choose to take out of the obligation.
|
|
1275
|
+
*/
|
|
1276
|
+
withdrawExpectation(mint, p) {
|
|
1277
|
+
const max = p.amount + (p.amount - lessBps(p.amount, this.slippageBps)) + oneCtokenLiquidityUp(p.chain.reserve) + 1n;
|
|
1278
|
+
return this.receiveExpectation(mint, p.amount, 0n, max);
|
|
1279
|
+
}
|
|
1168
1280
|
async quoteWithdraw(o) {
|
|
1169
1281
|
const me = await this.me();
|
|
1170
1282
|
const p = await this.prepare("withdraw", me, o.token, o.amount);
|
|
1171
1283
|
const base64 = await this.build("withdraw", me, p);
|
|
1172
|
-
const expect = this.
|
|
1284
|
+
const expect = this.withdrawExpectation(o.token, p);
|
|
1173
1285
|
const { fee } = await this.quoteBuilt(base64, expect, p.rules);
|
|
1174
1286
|
return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
1175
1287
|
}
|
|
@@ -1178,7 +1290,7 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
1178
1290
|
const me = await this.me();
|
|
1179
1291
|
const p = await this.prepare("withdraw", me, o.token, o.amount);
|
|
1180
1292
|
const base64 = await this.build("withdraw", me, p);
|
|
1181
|
-
return this.sendBuilt(base64, this.
|
|
1293
|
+
return this.sendBuilt(base64, this.withdrawExpectation(o.token, p), p.rules, "withdraw");
|
|
1182
1294
|
}
|
|
1183
1295
|
/** A borrow pays out at most what was asked: a bigger one is debt the user did not choose. */
|
|
1184
1296
|
borrowExpectation(mint, amount) {
|