@anywalletkit/protocol-lending-kamino-solana 0.2.2 → 0.3.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 +33 -13
- package/dist/index.cjs +464 -100
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +213 -21
- package/dist/index.d.ts +213 -21
- package/dist/index.js +461 -97
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -20,18 +20,29 @@ function toAmount(amount) {
|
|
|
20
20
|
if (value <= 0n) throw new KaminoError("'amount' should be greater than zero.");
|
|
21
21
|
return value;
|
|
22
22
|
}
|
|
23
|
+
var MAX_DECIMALS = 255;
|
|
24
|
+
var MAX_EXPONENT = 400;
|
|
25
|
+
var MAX_DIGITS = 1e3;
|
|
26
|
+
function checkDecimals(decimals) {
|
|
27
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_DECIMALS) throw new KaminoError(`Decimals must be an integer from 0 to ${MAX_DECIMALS}, not ${decimals}.`);
|
|
28
|
+
}
|
|
23
29
|
function toDecimalString(amount, decimals) {
|
|
30
|
+
checkDecimals(decimals);
|
|
24
31
|
const s = amount.toString().padStart(decimals + 1, "0");
|
|
25
32
|
const whole = s.slice(0, s.length - decimals), frac = s.slice(s.length - decimals).replace(/0+$/, "");
|
|
26
33
|
return frac ? `${whole}.${frac}` : whole;
|
|
27
34
|
}
|
|
28
35
|
function fromDecimalString(value, decimals) {
|
|
36
|
+
checkDecimals(decimals);
|
|
29
37
|
const s = String(value).trim();
|
|
30
|
-
|
|
31
|
-
if (
|
|
32
|
-
|
|
38
|
+
if (s.length > MAX_DIGITS) throw new KaminoError(`Kamino reported a figure of ${s.length} characters; no amount or rate is that long.`);
|
|
39
|
+
if (/^[-+]/.test(s)) throw new KaminoError(`Kamino reported a signed figure (${s.slice(0, 40)}); every amount and rate it reports is positive.`);
|
|
40
|
+
const m = /^(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
|
|
41
|
+
if (!m) throw new KaminoError(`Not a decimal number: ${s.slice(0, 40)}`);
|
|
42
|
+
let [, whole = "", frac = "", exp] = m;
|
|
33
43
|
if (exp) {
|
|
34
44
|
const e = Number(exp);
|
|
45
|
+
if (!(Math.abs(e) <= MAX_EXPONENT)) throw new KaminoError(`Kamino reported a figure with exponent ${exp.slice(0, 40)}; more than ${MAX_EXPONENT} either way is no amount or rate.`);
|
|
35
46
|
const digits = whole + frac;
|
|
36
47
|
let point = whole.length + e;
|
|
37
48
|
if (point <= 0) {
|
|
@@ -45,9 +56,9 @@ function fromDecimalString(value, decimals) {
|
|
|
45
56
|
frac = digits.slice(point);
|
|
46
57
|
}
|
|
47
58
|
}
|
|
48
|
-
const scaled = (whole || "0") + (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
49
|
-
|
|
50
|
-
return
|
|
59
|
+
const scaled = ((whole || "0") + (frac + "0".repeat(decimals)).slice(0, decimals)).replace(/^0+(?=\d)/, "");
|
|
60
|
+
if (scaled.length > MAX_DIGITS) throw new KaminoError(`Kamino reported a figure of ${scaled.length} digits in base units; no amount or rate is that large.`);
|
|
61
|
+
return BigInt(scaled);
|
|
51
62
|
}
|
|
52
63
|
var WAD = 10n ** 18n;
|
|
53
64
|
var toWad = (value) => fromDecimalString(value, 18);
|
|
@@ -55,6 +66,9 @@ var mulWad = (a, wad) => a * wad / WAD;
|
|
|
55
66
|
var divWadUp = (a, wad) => wad === 0n ? 0n : (a * WAD + wad - 1n) / wad;
|
|
56
67
|
var lessBps = (amount, bps) => amount * BigInt(1e4 - bps) / 10000n;
|
|
57
68
|
|
|
69
|
+
// src/base.ts
|
|
70
|
+
import { LendingProtocol } from "@anywalletkit/core";
|
|
71
|
+
|
|
58
72
|
// src/api.ts
|
|
59
73
|
var KAMINO_API = "https://api.kamino.finance";
|
|
60
74
|
var MAIN_MARKET = "7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF";
|
|
@@ -203,7 +217,7 @@ var KaminoApi = class {
|
|
|
203
217
|
}));
|
|
204
218
|
const coll = info.collateral ?? {}, debt = info.debt ?? {};
|
|
205
219
|
return {
|
|
206
|
-
obligation: String(row.loanId ?? row.obligation ?? row.address ?? ""),
|
|
220
|
+
obligation: String(row.obligationAddress ?? row.loanId ?? row.obligation ?? row.address ?? ""),
|
|
207
221
|
market: String(row.marketId ?? market),
|
|
208
222
|
user: String(row.user ?? ""),
|
|
209
223
|
elevationGroup: num(row.elevationGroup),
|
|
@@ -231,7 +245,7 @@ var KaminoApi = class {
|
|
|
231
245
|
buildVaultDeposit(p) {
|
|
232
246
|
return this.ktx("/ktx/kvault/deposit", strip(p));
|
|
233
247
|
}
|
|
234
|
-
/** Base64 unsigned v0 transaction: redeem `amount` SHARES (decimal)
|
|
248
|
+
/** Base64 unsigned v0 transaction: redeem `amount` SHARES (decimal). */
|
|
235
249
|
buildVaultWithdraw(p) {
|
|
236
250
|
return this.ktx("/ktx/kvault/withdraw", strip(p));
|
|
237
251
|
}
|
|
@@ -252,9 +266,6 @@ function strip(o) {
|
|
|
252
266
|
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
|
|
253
267
|
}
|
|
254
268
|
|
|
255
|
-
// src/base.ts
|
|
256
|
-
import { LendingProtocol } from "@anywalletkit/core";
|
|
257
|
-
|
|
258
269
|
// src/programs.ts
|
|
259
270
|
var KLEND_PROGRAM = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD";
|
|
260
271
|
var KVAULT_PROGRAM = "KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd";
|
|
@@ -311,8 +322,8 @@ var INSTRUCTION_NAMES = Object.freeze({
|
|
|
311
322
|
function instructionName(programId, data) {
|
|
312
323
|
const table = INSTRUCTION_NAMES[programId];
|
|
313
324
|
if (!table || data.length < 8) return void 0;
|
|
314
|
-
const
|
|
315
|
-
return table[
|
|
325
|
+
const hex2 = Array.from(data.subarray(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
326
|
+
return table[hex2];
|
|
316
327
|
}
|
|
317
328
|
|
|
318
329
|
// src/base.ts
|
|
@@ -399,31 +410,45 @@ var KaminoBase = class extends LendingProtocol {
|
|
|
399
410
|
}
|
|
400
411
|
return p;
|
|
401
412
|
}
|
|
402
|
-
guard(expect) {
|
|
403
|
-
|
|
413
|
+
guard(expect, instructions) {
|
|
414
|
+
if (!instructions.length) throw new KaminoError("A Kamino transaction is checked against the instructions its operation takes; none were given.");
|
|
415
|
+
return { programAllowlist: KAMINO_PROGRAM_ALLOWLIST, instructions, expect };
|
|
416
|
+
}
|
|
417
|
+
/** Accounts from the chain through the wallet's RPC, in the order asked (null where none exists). */
|
|
418
|
+
async readChain(addresses) {
|
|
419
|
+
const s = this.surface();
|
|
420
|
+
if (typeof s.getAccountInfos !== "function") throw new KaminoError("Kamino checks the API against the chain: it needs a @anywalletkit/wallet-solana account (getAccountInfos).");
|
|
421
|
+
const out = await s.getAccountInfos(addresses);
|
|
422
|
+
if (!Array.isArray(out) || out.length !== addresses.length) throw new KaminoError("The account returned a different number of accounts than asked.");
|
|
423
|
+
return out;
|
|
404
424
|
}
|
|
405
425
|
/** The wallet sends `amount` of `mint` (SOL counts on the lamport side) and may lose rent on top. */
|
|
406
426
|
spendExpectation(mint, amount, extraLamports = 0n) {
|
|
427
|
+
if (amount <= 0n) throw new KaminoError(`Refusing a transaction that spends ${amount} of ${mint}: the amount must be positive.`);
|
|
407
428
|
const rent = this.rentAllowance + extraLamports;
|
|
408
429
|
return mint === WSOL_MINT ? { maxLamportsOut: amount + rent } : { maxLamportsOut: rent, maxTokenOut: { mint, amount } };
|
|
409
430
|
}
|
|
410
|
-
/**
|
|
411
|
-
|
|
431
|
+
/**
|
|
432
|
+
* The wallet must receive at least `expected × (1 − slippage)` of `mint` (and at most `max`, when
|
|
433
|
+
* given); rent is the only SOL it may lose.
|
|
434
|
+
*/
|
|
435
|
+
receiveExpectation(mint, expected, extraLamports = 0n, max) {
|
|
436
|
+
if (expected <= 0n) throw new KaminoError(`Refusing a transaction that should pay out ${expected} of ${mint}: the amount must be positive.`);
|
|
412
437
|
const min = expected * BigInt(1e4 - this.slippageBps) / 10000n;
|
|
413
|
-
return { maxLamportsOut: this.rentAllowance + extraLamports, tokenIn: { mint, minAmount: min } };
|
|
438
|
+
return { maxLamportsOut: this.rentAllowance + extraLamports, tokenIn: { mint, minAmount: min, ...max !== void 0 ? { maxAmount: max } : {} } };
|
|
414
439
|
}
|
|
415
440
|
/** Simulate the built transaction through the account's guard and return its fee; nothing is signed. */
|
|
416
|
-
async quoteBuilt(base64, expect) {
|
|
441
|
+
async quoteBuilt(base64, expect, instructions) {
|
|
417
442
|
const s = this.surface();
|
|
418
443
|
if (typeof s.checkSerialized !== "function") throw new KaminoError("Quoting a Kamino transaction needs a @anywalletkit/wallet-solana account (checkSerialized).");
|
|
419
|
-
const check = await s.checkSerialized(base64, this.guard(expect));
|
|
444
|
+
const check = await s.checkSerialized(base64, this.guard(expect, instructions));
|
|
420
445
|
return { fee: BigInt(check.quote.fee) };
|
|
421
446
|
}
|
|
422
447
|
/** Guard, sign and broadcast the built transaction; the account refuses before signing if the proof fails. */
|
|
423
|
-
async sendBuilt(base64, expect, method) {
|
|
448
|
+
async sendBuilt(base64, expect, instructions, method) {
|
|
424
449
|
const account = this.requireSigningAccount(`${method}(options)`);
|
|
425
450
|
if (typeof account.sendSerialized !== "function") throw new KaminoError(`${method}() needs a @anywalletkit/wallet-solana account (sendSerialized).`);
|
|
426
|
-
const sent = await account.sendSerialized(base64, this.guard(expect));
|
|
451
|
+
const sent = await account.sendSerialized(base64, this.guard(expect, instructions));
|
|
427
452
|
if (!sent?.hash) throw new KaminoError("The account returned no transaction signature.");
|
|
428
453
|
return { hash: sent.hash, fee: BigInt(sent.fee ?? 0) };
|
|
429
454
|
}
|
|
@@ -432,13 +457,134 @@ var KaminoBase = class extends LendingProtocol {
|
|
|
432
457
|
}
|
|
433
458
|
};
|
|
434
459
|
|
|
460
|
+
// src/chain.ts
|
|
461
|
+
import { base58 } from "@scure/base";
|
|
462
|
+
var SF = 1n << 60n;
|
|
463
|
+
var FARM_STAKE_SCALE = 10n ** 18n;
|
|
464
|
+
var CHAIN_TOLERANCE_BPS = 100n;
|
|
465
|
+
var DEFAULT_KEY = "11111111111111111111111111111111";
|
|
466
|
+
var KINDS = {
|
|
467
|
+
VaultState: { program: KVAULT_PROGRAM, disc: "e4c452a562d2eb98", size: 62552 },
|
|
468
|
+
Reserve: { program: KLEND_PROGRAM, disc: "2bf2ccca1af73b7f", size: 8624 },
|
|
469
|
+
Obligation: { program: KLEND_PROGRAM, disc: "a8ce8d6a584caca7", size: 3344 },
|
|
470
|
+
UserState: { program: FARMS_PROGRAM, disc: "48b155f94ca7ba7e", size: 920 }
|
|
471
|
+
};
|
|
472
|
+
var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
473
|
+
var u64 = (d, o) => new DataView(d.buffer, d.byteOffset, d.byteLength).getBigUint64(o, true);
|
|
474
|
+
var u128 = (d, o) => u64(d, o) + (u64(d, o + 8) << 64n);
|
|
475
|
+
var u256 = (d, o) => u128(d, o) + (u128(d, o + 16) << 128n);
|
|
476
|
+
var key = (d, o) => base58.encode(d.subarray(o, o + 32));
|
|
477
|
+
function decimalsAt(d, o, what) {
|
|
478
|
+
const v = u64(d, o);
|
|
479
|
+
if (v > 255n) throw new KaminoError(`${what} records ${v} decimals; a mint has at most 255.`);
|
|
480
|
+
return Number(v.toString());
|
|
481
|
+
}
|
|
482
|
+
function bytesOf(kind, address, acc) {
|
|
483
|
+
const k = KINDS[kind];
|
|
484
|
+
if (!acc) throw new KaminoError(`${kind} ${address} does not exist on chain.`);
|
|
485
|
+
if (acc.owner !== k.program) throw new KaminoError(`${address} is not a Kamino ${kind}: it belongs to ${acc.owner}.`);
|
|
486
|
+
if (acc.data.length < k.size || hex(acc.data.subarray(0, 8)) !== k.disc) throw new KaminoError(`${address} is not a Kamino ${kind} account.`);
|
|
487
|
+
return acc.data;
|
|
488
|
+
}
|
|
489
|
+
function decodeVault(address, acc) {
|
|
490
|
+
const d = bytesOf("VaultState", address, acc);
|
|
491
|
+
const allocations = [];
|
|
492
|
+
for (let i = 0; i < 25; i++) {
|
|
493
|
+
const o = 312 + i * 2160;
|
|
494
|
+
const reserve = key(d, o);
|
|
495
|
+
if (reserve !== DEFAULT_KEY) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
|
|
496
|
+
}
|
|
497
|
+
const farm = key(d, 58600);
|
|
498
|
+
return {
|
|
499
|
+
tokenMint: key(d, 80),
|
|
500
|
+
tokenDecimals: decimalsAt(d, 112, `Vault ${address}`),
|
|
501
|
+
tokenProgram: key(d, 152),
|
|
502
|
+
sharesMint: key(d, 184),
|
|
503
|
+
sharesDecimals: decimalsAt(d, 216, `Vault ${address}`),
|
|
504
|
+
tokenAvailable: u64(d, 224),
|
|
505
|
+
sharesIssued: u64(d, 232),
|
|
506
|
+
pendingFeesSf: u128(d, 296),
|
|
507
|
+
allocations,
|
|
508
|
+
minDeposit: u64(d, 58408),
|
|
509
|
+
minWithdraw: u64(d, 58416),
|
|
510
|
+
farm: farm === DEFAULT_KEY ? null : farm
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
function decodeReserve(address, acc) {
|
|
514
|
+
const d = bytesOf("Reserve", address, acc);
|
|
515
|
+
const total = u64(d, 224) * SF + u128(d, 232) - u128(d, 344) - u128(d, 360) - u128(d, 376);
|
|
516
|
+
return {
|
|
517
|
+
lendingMarket: key(d, 32),
|
|
518
|
+
mint: key(d, 128),
|
|
519
|
+
decimals: decimalsAt(d, 272, `Reserve ${address}`),
|
|
520
|
+
tokenProgram: key(d, 408),
|
|
521
|
+
totalLiquiditySf: total > 0n ? total : 0n,
|
|
522
|
+
collateralSupply: u64(d, 2592),
|
|
523
|
+
cumulativeBorrowRate: u256(d, 296)
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function collateralToLiquiditySf(r, ctokens) {
|
|
527
|
+
if (r.collateralSupply === 0n || r.totalLiquiditySf === 0n) return ctokens * SF;
|
|
528
|
+
return ctokens * r.totalLiquiditySf / r.collateralSupply;
|
|
529
|
+
}
|
|
530
|
+
function decodeObligation(address, acc) {
|
|
531
|
+
const d = bytesOf("Obligation", address, acc);
|
|
532
|
+
const deposits = [], borrows = [];
|
|
533
|
+
for (let i = 0; i < 8; i++) {
|
|
534
|
+
const o = 96 + i * 136;
|
|
535
|
+
const reserve = key(d, o);
|
|
536
|
+
if (reserve !== DEFAULT_KEY) deposits.push({ reserve, ctokens: u64(d, o + 32) });
|
|
537
|
+
}
|
|
538
|
+
for (let i = 0; i < 5; i++) {
|
|
539
|
+
const o = 1208 + i * 200;
|
|
540
|
+
const reserve = key(d, o);
|
|
541
|
+
if (reserve !== DEFAULT_KEY) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
|
|
542
|
+
}
|
|
543
|
+
return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
|
|
544
|
+
}
|
|
545
|
+
function depositedLiquidity(o, r, reserve) {
|
|
546
|
+
return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + collateralToLiquiditySf(r, x.ctokens) / SF, 0n);
|
|
547
|
+
}
|
|
548
|
+
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);
|
|
553
|
+
}
|
|
554
|
+
function decodeFarmUser(address, acc) {
|
|
555
|
+
const d = bytesOf("UserState", address, acc);
|
|
556
|
+
return { farm: key(d, 16), owner: key(d, 48), staked: u128(d, 408) / FARM_STAKE_SCALE };
|
|
557
|
+
}
|
|
558
|
+
function tokenAmount(acc, mint, owner) {
|
|
559
|
+
if (!acc || acc.owner !== TOKEN_PROGRAM && acc.owner !== TOKEN_2022_PROGRAM || acc.data.length < 165) return 0n;
|
|
560
|
+
if (key(acc.data, 0) !== mint || key(acc.data, 32) !== owner) return 0n;
|
|
561
|
+
return u64(acc.data, 64);
|
|
562
|
+
}
|
|
563
|
+
function vaultTokensPerShareWad(v, reserves) {
|
|
564
|
+
let aumSf = v.tokenAvailable * SF;
|
|
565
|
+
for (const a of v.allocations) {
|
|
566
|
+
if (a.ctokens === 0n) continue;
|
|
567
|
+
const r = reserves.get(a.reserve);
|
|
568
|
+
if (!r) throw new KaminoError(`The vault's reserve ${a.reserve} was not read.`);
|
|
569
|
+
aumSf += collateralToLiquiditySf(r, a.ctokens);
|
|
570
|
+
}
|
|
571
|
+
aumSf -= v.pendingFeesSf;
|
|
572
|
+
if (v.sharesIssued === 0n) return WAD;
|
|
573
|
+
if (aumSf <= 0n) throw new KaminoError("The vault holds nothing against its shares on chain.");
|
|
574
|
+
return aumSf * 10n ** BigInt(v.sharesDecimals) * WAD / (v.sharesIssued * SF * 10n ** BigInt(v.tokenDecimals));
|
|
575
|
+
}
|
|
576
|
+
function withinTolerance(a, b) {
|
|
577
|
+
const diff = a > b ? a - b : b - a;
|
|
578
|
+
return diff * 10000n <= b * CHAIN_TOLERANCE_BPS;
|
|
579
|
+
}
|
|
580
|
+
|
|
435
581
|
// src/pda.ts
|
|
436
582
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
437
583
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
438
|
-
import { base58 } from "@scure/base";
|
|
584
|
+
import { base58 as base582 } from "@scure/base";
|
|
439
585
|
var PDA_MARKER = new TextEncoder().encode("ProgramDerivedAddress");
|
|
440
586
|
function findProgramAddress(seeds, programId) {
|
|
441
|
-
const program =
|
|
587
|
+
const program = base582.decode(programId);
|
|
442
588
|
for (let bump = 255; bump >= 0; bump--) {
|
|
443
589
|
const parts = [...seeds, Uint8Array.of(bump), program, PDA_MARKER];
|
|
444
590
|
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
@@ -451,17 +597,116 @@ function findProgramAddress(seeds, programId) {
|
|
|
451
597
|
try {
|
|
452
598
|
ed25519.Point.fromBytes(hash);
|
|
453
599
|
} catch {
|
|
454
|
-
return
|
|
600
|
+
return base582.encode(hash);
|
|
455
601
|
}
|
|
456
602
|
}
|
|
457
603
|
throw new Error("No program address found for these seeds.");
|
|
458
604
|
}
|
|
459
605
|
function vanillaObligation(user, market, klendProgram = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD") {
|
|
460
606
|
const zero = new Uint8Array(32);
|
|
461
|
-
return findProgramAddress([Uint8Array.of(0), Uint8Array.of(0),
|
|
607
|
+
return findProgramAddress([Uint8Array.of(0), Uint8Array.of(0), base582.decode(user), base582.decode(market), zero, zero], klendProgram);
|
|
462
608
|
}
|
|
463
609
|
function vaultSharesMint(vault, kvaultProgram) {
|
|
464
|
-
return findProgramAddress([new TextEncoder().encode("shares"),
|
|
610
|
+
return findProgramAddress([new TextEncoder().encode("shares"), base582.decode(vault)], kvaultProgram);
|
|
611
|
+
}
|
|
612
|
+
function associatedTokenAddress(owner, mint, tokenProgram) {
|
|
613
|
+
return findProgramAddress([base582.decode(owner), base582.decode(tokenProgram), base582.decode(mint)], "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
|
|
614
|
+
}
|
|
615
|
+
function farmUserState(farm, owner, farmsProgram = "FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr") {
|
|
616
|
+
return findProgramAddress([new TextEncoder().encode("user"), base582.decode(farm), base582.decode(owner)], farmsProgram);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// src/policy.ts
|
|
620
|
+
var IX = Object.freeze({
|
|
621
|
+
initUserMetadata: "75a9b045c5170fa2",
|
|
622
|
+
initObligation: "fb0ae74c1b0b9f60",
|
|
623
|
+
initObligationFarmsForReserve: "883f0fbad398a8a4",
|
|
624
|
+
refreshReserve: "02da8aeb4fc91966",
|
|
625
|
+
refreshObligation: "218493e497c04859",
|
|
626
|
+
refreshObligationFarmsForReserve: "8c90fd150a4af803",
|
|
627
|
+
requestElevationGroup: "2477fb8122f00793",
|
|
628
|
+
depositV2: "d8e0bf1bcc9766af",
|
|
629
|
+
withdrawV2: "eb34779895c51407",
|
|
630
|
+
borrowV2: "a1808ff5abc7c206",
|
|
631
|
+
repayV2: "74aed54cb435d290",
|
|
632
|
+
vaultDeposit: "f223c68952e1f2b6",
|
|
633
|
+
vaultWithdraw: "b712469c946da122",
|
|
634
|
+
vaultWithdrawFromAvailable: "1383709baadc2239",
|
|
635
|
+
farmInitializeUser: "6f11b9fa3c7a26fe",
|
|
636
|
+
farmStake: "ceb0ca12c8d1b36c",
|
|
637
|
+
farmUnstake: "5a5f6b2acd7c32e1",
|
|
638
|
+
farmWithdrawUnstaked: "2466bb31dc248443"
|
|
639
|
+
});
|
|
640
|
+
function plumbing(me, wsolAta) {
|
|
641
|
+
return [
|
|
642
|
+
{ program: COMPUTE_BUDGET_PROGRAM },
|
|
643
|
+
{ program: MEMO_PROGRAM },
|
|
644
|
+
// Create / CreateIdempotent: payer and owner are the wallet.
|
|
645
|
+
{ program: ASSOCIATED_TOKEN_PROGRAM, data: "", dataLength: 0, accounts: { 0: me, 2: me } },
|
|
646
|
+
{ program: ASSOCIATED_TOKEN_PROGRAM, data: "01", dataLength: 1, accounts: { 0: me, 2: me } },
|
|
647
|
+
// System Transfer into the wallet's wSOL account, SyncNative on it, and closing it back to the wallet.
|
|
648
|
+
{ program: SYSTEM_PROGRAM, data: "02000000", dataLength: 12, accounts: { 0: me, 1: wsolAta } },
|
|
649
|
+
{ program: TOKEN_PROGRAM, data: "11", dataLength: 1, accounts: { 0: wsolAta } },
|
|
650
|
+
{ program: TOKEN_PROGRAM, data: "09", dataLength: 1, accounts: { 0: wsolAta, 1: me, 2: me } }
|
|
651
|
+
];
|
|
652
|
+
}
|
|
653
|
+
function marketRules(op, a) {
|
|
654
|
+
const { me, market, obligation, reserve, mint, ata } = a;
|
|
655
|
+
const owner = { 0: me, 1: obligation, 2: market };
|
|
656
|
+
const rules = [
|
|
657
|
+
...plumbing(me, a.wsolAta),
|
|
658
|
+
{ program: KLEND_PROGRAM, data: IX.refreshReserve, dataLength: 8, accounts: { 1: market } },
|
|
659
|
+
{ program: KLEND_PROGRAM, data: IX.refreshObligation, dataLength: 8, accounts: { 0: market, 1: obligation } },
|
|
660
|
+
{ program: KLEND_PROGRAM, data: IX.refreshObligationFarmsForReserve, dataLength: 9, accounts: { 1: obligation, 6: market } },
|
|
661
|
+
{ program: KLEND_PROGRAM, data: IX.initObligationFarmsForReserve, dataLength: 9, accounts: { 0: me, 1: me, 2: obligation, 7: market } }
|
|
662
|
+
];
|
|
663
|
+
if (op === "deposit") {
|
|
664
|
+
rules.push(
|
|
665
|
+
// A first deposit: user metadata, the vanilla obligation (tag 0, id 0) and the user's lookup table, all paid by the wallet.
|
|
666
|
+
{ program: KLEND_PROGRAM, data: IX.initUserMetadata, dataLength: 40, accounts: { 0: me, 1: me } },
|
|
667
|
+
{ program: KLEND_PROGRAM, data: `${IX.initObligation}0000`, dataLength: 10, accounts: { 0: me, 1: me, 2: obligation, 3: market } },
|
|
668
|
+
{ program: ADDRESS_LOOKUP_TABLE_PROGRAM, data: "00000000", dataLength: 13, accounts: { 1: me, 2: me } },
|
|
669
|
+
{ program: ADDRESS_LOOKUP_TABLE_PROGRAM, data: "02000000", accounts: { 1: me } },
|
|
670
|
+
{ program: KLEND_PROGRAM, data: IX.depositV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 9: ata } }
|
|
671
|
+
);
|
|
672
|
+
} else if (op === "withdraw") {
|
|
673
|
+
rules.push({ program: KLEND_PROGRAM, data: IX.withdrawV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 9: ata } });
|
|
674
|
+
} else if (op === "borrow") {
|
|
675
|
+
rules.push(
|
|
676
|
+
{ program: KLEND_PROGRAM, data: IX.requestElevationGroup, dataLength: 9, accounts: owner },
|
|
677
|
+
{ program: KLEND_PROGRAM, data: IX.borrowV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 8: ata } }
|
|
678
|
+
);
|
|
679
|
+
} else {
|
|
680
|
+
rules.push({ program: KLEND_PROGRAM, data: IX.repayV2, dataLength: 16, accounts: { ...owner, 3: reserve, 4: mint, 6: ata } });
|
|
681
|
+
}
|
|
682
|
+
return rules;
|
|
683
|
+
}
|
|
684
|
+
function vaultRules(op, a, opts) {
|
|
685
|
+
const { me, vault, mint, sharesMint, tokenAta, sharesAtas, farm } = a;
|
|
686
|
+
const rules = plumbing(me, a.wsolAta);
|
|
687
|
+
if (op === "deposit") {
|
|
688
|
+
rules.push({ program: KVAULT_PROGRAM, data: IX.vaultDeposit, dataLength: 16, accounts: { 0: me, 1: vault, 3: mint, 5: sharesMint, 6: tokenAta, 7: sharesAtas } });
|
|
689
|
+
if (opts.stake && farm) {
|
|
690
|
+
rules.push(
|
|
691
|
+
{ program: FARMS_PROGRAM, data: IX.farmInitializeUser, dataLength: 8, accounts: { 0: me, 1: me, 2: me, 3: me, 4: farm.userState, 5: farm.farm } },
|
|
692
|
+
{ program: FARMS_PROGRAM, data: IX.farmStake, dataLength: 16, accounts: { 0: me, 1: farm.userState, 2: farm.farm, 4: sharesAtas, 5: sharesMint } }
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
} else {
|
|
696
|
+
const redeem = { 0: me, 1: vault, 5: tokenAta, 6: mint, 7: sharesAtas, 8: sharesMint };
|
|
697
|
+
rules.push(
|
|
698
|
+
{ program: KVAULT_PROGRAM, data: IX.vaultWithdrawFromAvailable, dataLength: 16, accounts: redeem },
|
|
699
|
+
{ program: KVAULT_PROGRAM, data: IX.vaultWithdraw, dataLength: 16, accounts: redeem },
|
|
700
|
+
...sharesAtas.slice(0, 2).map((ata, i) => ({ program: i === 0 ? TOKEN_PROGRAM : TOKEN_2022_PROGRAM, data: "09", dataLength: 1, accounts: { 0: ata, 1: me, 2: me } }))
|
|
701
|
+
);
|
|
702
|
+
if (farm) {
|
|
703
|
+
rules.push(
|
|
704
|
+
{ program: FARMS_PROGRAM, data: IX.farmUnstake, dataLength: 24, accounts: { 0: me, 1: farm.userState, 2: farm.farm } },
|
|
705
|
+
{ program: FARMS_PROGRAM, data: IX.farmWithdrawUnstaked, dataLength: 8, accounts: { 0: me, 1: farm.userState, 2: farm.farm, 3: sharesAtas } }
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return rules;
|
|
465
710
|
}
|
|
466
711
|
|
|
467
712
|
// src/vault.ts
|
|
@@ -557,15 +802,71 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
|
|
|
557
802
|
assetsToShares(assets, v, tokensPerShareWad) {
|
|
558
803
|
return rescale(divWadUp(assets, tokensPerShareWad), v.tokenMintDecimals, v.sharesMintDecimals);
|
|
559
804
|
}
|
|
805
|
+
/**
|
|
806
|
+
* What a write's bounds are computed from, read from the chain (scan 2026-10-27 modules, F2/F11/F12):
|
|
807
|
+
* the vault's state and the reserves it invests in give the share price, the wallet's shares
|
|
808
|
+
* account and farm state its position. The API must describe the same vault — mints, decimals —
|
|
809
|
+
* and quote a `tokensPerShare` within 1% of the chain's; a lying rate is refused, never used.
|
|
810
|
+
*/
|
|
811
|
+
async onChain(me, v, m) {
|
|
812
|
+
const refuse = (what) => {
|
|
813
|
+
throw new KaminoError(`Kamino's answer for vault ${this.vault} does not match the chain: ${what}.`);
|
|
814
|
+
};
|
|
815
|
+
const state = decodeVault(this.vault, (await this.readChain([this.vault]))[0] ?? null);
|
|
816
|
+
if (state.tokenMint !== v.tokenMint || state.sharesMint !== v.sharesMint) refuse(`mints ${v.tokenMint} / ${v.sharesMint} are ${state.tokenMint} / ${state.sharesMint} on chain`);
|
|
817
|
+
if (state.tokenDecimals !== v.tokenMintDecimals || state.sharesDecimals !== v.sharesMintDecimals) refuse(`decimals ${v.tokenMintDecimals} / ${v.sharesMintDecimals} are ${state.tokenDecimals} / ${state.sharesDecimals} on chain`);
|
|
818
|
+
const invested = state.allocations.filter((a) => a.ctokens > 0n).map((a) => a.reserve);
|
|
819
|
+
const sharesAtas = [associatedTokenAddress(me, state.sharesMint, TOKEN_PROGRAM), associatedTokenAddress(me, state.sharesMint, TOKEN_2022_PROGRAM)];
|
|
820
|
+
const userState = state.farm ? farmUserState(state.farm, me) : null;
|
|
821
|
+
const accs = await this.readChain([...invested, ...sharesAtas, ...userState ? [userState] : []]);
|
|
822
|
+
const reserves = /* @__PURE__ */ new Map();
|
|
823
|
+
invested.forEach((r, i) => {
|
|
824
|
+
const reserve = decodeReserve(r, accs[i] ?? null);
|
|
825
|
+
if (reserve.mint !== state.tokenMint) refuse(`its reserve ${r} lends ${reserve.mint}`);
|
|
826
|
+
reserves.set(r, reserve);
|
|
827
|
+
});
|
|
828
|
+
const tokensPerShareWad = vaultTokensPerShareWad(state, reserves);
|
|
829
|
+
const quoted = toWad(m.tokensPerShare);
|
|
830
|
+
if (quoted <= 0n) refuse(`tokensPerShare ${m.tokensPerShare} is not positive`);
|
|
831
|
+
if (!withinTolerance(quoted, tokensPerShareWad)) refuse(`tokensPerShare ${m.tokensPerShare} is ${toDecimalString(tokensPerShareWad, 18)} on chain`);
|
|
832
|
+
const unstaked = sharesAtas.reduce((sum, a, i) => sum + tokenAmount(accs[invested.length + i] ?? null, state.sharesMint, me), 0n);
|
|
833
|
+
const farmAcc = userState ? accs[invested.length + 2] ?? null : null;
|
|
834
|
+
const stake = userState && farmAcc ? decodeFarmUser(userState, farmAcc) : null;
|
|
835
|
+
const staked = stake && stake.owner === me && stake.farm === state.farm ? stake.staked : 0n;
|
|
836
|
+
return {
|
|
837
|
+
state,
|
|
838
|
+
tokensPerShareWad,
|
|
839
|
+
sharesAtas,
|
|
840
|
+
tokenAta: associatedTokenAddress(me, state.tokenMint, state.tokenProgram),
|
|
841
|
+
farm: state.farm && userState ? { farm: state.farm, userState } : null,
|
|
842
|
+
unstaked,
|
|
843
|
+
staked
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
rules(op, me, c) {
|
|
847
|
+
return vaultRules(op, {
|
|
848
|
+
me,
|
|
849
|
+
vault: this.vault,
|
|
850
|
+
mint: c.state.tokenMint,
|
|
851
|
+
sharesMint: c.state.sharesMint,
|
|
852
|
+
tokenAta: c.tokenAta,
|
|
853
|
+
sharesAtas: c.sharesAtas,
|
|
854
|
+
farm: c.farm,
|
|
855
|
+
wsolAta: associatedTokenAddress(me, WSOL_MINT, TOKEN_PROGRAM)
|
|
856
|
+
}, { stake: !this.skipFarm });
|
|
857
|
+
}
|
|
560
858
|
async plan(o, me) {
|
|
561
859
|
const amount = toAmount(o.amount);
|
|
562
860
|
const token = o.token ?? this._config.asset;
|
|
563
861
|
if (token === void 0) throw new KaminoError(`Name the asset to deposit: pass 'token' or set 'asset' in the vault config.`);
|
|
564
862
|
const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
|
|
565
863
|
if (token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} takes ${symbolOf(v)} (${v.tokenMint}), not ${token}.`);
|
|
566
|
-
|
|
864
|
+
const c = await this.onChain(me, v, m);
|
|
865
|
+
if (amount < c.state.minDeposit) throw new KaminoError(`Deposit below the vault minimum: ${amount} < ${c.state.minDeposit} base units.`);
|
|
866
|
+
const expectedShares = this.assetsToShares(amount, v, c.tokensPerShareWad);
|
|
867
|
+
if (expectedShares <= 0n) throw new KaminoError(`A deposit of ${amount} base units buys no shares of vault ${this.vault}.`);
|
|
567
868
|
const base64 = await this.api.buildVaultDeposit({ wallet: me, kvault: this.vault, amount: toDecimalString(amount, v.tokenMintDecimals), skipFarm: this.skipFarm, memo: this.memo() });
|
|
568
|
-
return { base64, v, amount, expectedShares: this.
|
|
869
|
+
return { base64, v, amount, expectedShares, rules: this.rules("deposit", me, c) };
|
|
569
870
|
}
|
|
570
871
|
supplyExpectation(v, amount, expectedShares) {
|
|
571
872
|
const e = this.spendExpectation(v.tokenMint, amount);
|
|
@@ -573,35 +874,37 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
|
|
|
573
874
|
}
|
|
574
875
|
async quoteSupply(o) {
|
|
575
876
|
const me = await this.me();
|
|
576
|
-
const { base64, v, amount, expectedShares } = await this.plan(o, me);
|
|
577
|
-
const { fee } = await this.quoteBuilt(base64, this.supplyExpectation(v, amount, expectedShares));
|
|
877
|
+
const { base64, v, amount, expectedShares, rules } = await this.plan(o, me);
|
|
878
|
+
const { fee } = await this.quoteBuilt(base64, this.supplyExpectation(v, amount, expectedShares), rules);
|
|
578
879
|
return { fee, expectedShares };
|
|
579
880
|
}
|
|
580
881
|
async supply(o) {
|
|
581
882
|
this.requireSigningAccount("supply(options)");
|
|
582
883
|
const me = await this.me();
|
|
583
|
-
const { base64, v, amount, expectedShares } = await this.plan(o, me);
|
|
584
|
-
return this.sendBuilt(base64, this.supplyExpectation(v, amount, expectedShares), "supply");
|
|
884
|
+
const { base64, v, amount, expectedShares, rules } = await this.plan(o, me);
|
|
885
|
+
return this.sendBuilt(base64, this.supplyExpectation(v, amount, expectedShares), rules, "supply");
|
|
585
886
|
}
|
|
586
887
|
async planWithdraw(o, me) {
|
|
587
|
-
const [v, m
|
|
888
|
+
const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
|
|
588
889
|
if (o.token && o.token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} pays out ${symbolOf(v)} (${v.tokenMint}), not ${o.token}.`);
|
|
589
|
-
|
|
590
|
-
const
|
|
890
|
+
const c = await this.onChain(me, v, m);
|
|
891
|
+
const held = c.unstaked + c.staked;
|
|
892
|
+
if (held === 0n) throw new KaminoError(`No position in vault ${this.vault} for ${me}.`);
|
|
893
|
+
const tps = c.tokensPerShareWad;
|
|
591
894
|
let shares, amountArg;
|
|
592
895
|
if (o.amount === "max") {
|
|
593
|
-
shares =
|
|
594
|
-
amountArg =
|
|
896
|
+
shares = held;
|
|
897
|
+
amountArg = toDecimalString(held, v.sharesMintDecimals);
|
|
595
898
|
} else {
|
|
596
899
|
const assets = toAmount(o.amount);
|
|
597
900
|
shares = this.assetsToShares(assets, v, tps);
|
|
598
|
-
if (shares >
|
|
901
|
+
if (shares > held) throw new KaminoError(`Withdrawal exceeds the position: ${assets} asset units need ${shares} shares, the wallet holds ${held}.`);
|
|
599
902
|
amountArg = toDecimalString(shares, v.sharesMintDecimals);
|
|
600
903
|
}
|
|
601
904
|
const expectedAssets = this.sharesToAssets(shares, v, tps);
|
|
602
|
-
if (expectedAssets <
|
|
905
|
+
if (expectedAssets < c.state.minWithdraw) throw new KaminoError(`Withdrawal below the vault minimum: ${expectedAssets} < ${c.state.minWithdraw} base units.`);
|
|
603
906
|
const base64 = await this.api.buildVaultWithdraw({ wallet: me, kvault: this.vault, amount: amountArg, memo: this.memo() });
|
|
604
|
-
return { base64, v, shares, expectedAssets };
|
|
907
|
+
return { base64, v, shares, expectedAssets, rules: this.rules("withdraw", me, c) };
|
|
605
908
|
}
|
|
606
909
|
/**
|
|
607
910
|
* The asset comes in (within slippage), and the shares being redeemed may leave the wallet's
|
|
@@ -613,16 +916,16 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
|
|
|
613
916
|
}
|
|
614
917
|
async quoteWithdraw(o) {
|
|
615
918
|
const me = await this.me();
|
|
616
|
-
const { base64, v, shares, expectedAssets } = await this.planWithdraw(o, me);
|
|
919
|
+
const { base64, v, shares, expectedAssets, rules } = await this.planWithdraw(o, me);
|
|
617
920
|
const expect = this.withdrawExpectation(v, shares, expectedAssets);
|
|
618
|
-
const { fee } = await this.quoteBuilt(base64, expect);
|
|
921
|
+
const { fee } = await this.quoteBuilt(base64, expect, rules);
|
|
619
922
|
return { fee, shares, expectedAssets, minAssets: expect.tokenIn.minAmount };
|
|
620
923
|
}
|
|
621
924
|
async withdraw(o) {
|
|
622
925
|
this.requireSigningAccount("withdraw(options)");
|
|
623
926
|
const me = await this.me();
|
|
624
|
-
const { base64, v, shares, expectedAssets } = await this.planWithdraw(o, me);
|
|
625
|
-
return this.sendBuilt(base64, this.withdrawExpectation(v, shares, expectedAssets), "withdraw");
|
|
927
|
+
const { base64, v, shares, expectedAssets, rules } = await this.planWithdraw(o, me);
|
|
928
|
+
return this.sendBuilt(base64, this.withdrawExpectation(v, shares, expectedAssets), rules, "withdraw");
|
|
626
929
|
}
|
|
627
930
|
async borrow() {
|
|
628
931
|
throw new NotImplementedError("borrow(options) \u2014 an Earn vault does not lend to its depositors; use KaminoMarketProtocolSolana.");
|
|
@@ -709,99 +1012,148 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
|
709
1012
|
}
|
|
710
1013
|
return { obligations, supplied, borrowed };
|
|
711
1014
|
}
|
|
712
|
-
|
|
1015
|
+
/**
|
|
1016
|
+
* The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
|
|
1017
|
+
* the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
|
|
1018
|
+
* instruction rules pin the operation to that obligation, reserve and the wallet's token account.
|
|
1019
|
+
*/
|
|
1020
|
+
async prepare(kind, me, mint, amount) {
|
|
713
1021
|
const reserve = await this.resolveReserve(mint);
|
|
714
|
-
const
|
|
715
|
-
const
|
|
716
|
-
|
|
1022
|
+
const obligationAddress = vanillaObligation(me, this.market, KLEND_PROGRAM);
|
|
1023
|
+
const [r, o] = await this.readChain([reserve.reserve, obligationAddress]);
|
|
1024
|
+
const onChain = decodeReserve(reserve.reserve, r ?? null);
|
|
1025
|
+
if (onChain.lendingMarket !== this.market) throw new KaminoError(`Reserve ${reserve.reserve} belongs to market ${onChain.lendingMarket} on chain, not ${this.market}.`);
|
|
1026
|
+
if (onChain.mint !== mint) throw new KaminoError(`Reserve ${reserve.reserve} lends ${onChain.mint} on chain, not ${mint}.`);
|
|
1027
|
+
const obligation = o ? decodeObligation(obligationAddress, o) : null;
|
|
1028
|
+
if (obligation && (obligation.owner !== me || obligation.lendingMarket !== this.market)) throw new KaminoError(`Obligation ${obligationAddress} is not ${me}'s on market ${this.market}.`);
|
|
1029
|
+
const chain = { reserve: onChain, obligation, obligationAddress };
|
|
1030
|
+
const value = amount === "max" ? await this.resolveMax(kind === "withdraw" ? "supplied" : "borrowed", me, mint, reserve.reserve, chain) : toAmount(amount);
|
|
1031
|
+
const rules = marketRules(kind, {
|
|
1032
|
+
me,
|
|
1033
|
+
market: this.market,
|
|
1034
|
+
obligation: obligationAddress,
|
|
1035
|
+
reserve: reserve.reserve,
|
|
1036
|
+
mint,
|
|
1037
|
+
ata: associatedTokenAddress(me, mint, onChain.tokenProgram),
|
|
1038
|
+
wsolAta: associatedTokenAddress(me, WSOL_MINT, TOKEN_PROGRAM)
|
|
1039
|
+
});
|
|
1040
|
+
return { reserve, chain, amount: value, rules };
|
|
1041
|
+
}
|
|
1042
|
+
build(kind, me, p) {
|
|
1043
|
+
const params = { wallet: me, market: this.market, reserve: p.reserve.reserve, amount: toDecimalString(p.amount, p.chain.reserve.decimals), memo: this.memo() };
|
|
1044
|
+
return kind === "deposit" ? this.api.buildLendDeposit(params) : kind === "withdraw" ? this.api.buildLendWithdraw(params) : kind === "borrow" ? this.api.buildLendBorrow(params) : this.api.buildLendRepay(params);
|
|
1045
|
+
}
|
|
1046
|
+
/** A wallet without its vanilla obligation here (on chain) pays the rent of one on its first deposit. */
|
|
1047
|
+
firstDepositExtra(p) {
|
|
1048
|
+
return p.chain.obligation ? 0n : this.firstDepositAllowance;
|
|
717
1049
|
}
|
|
718
1050
|
/**
|
|
719
|
-
*
|
|
720
|
-
*
|
|
721
|
-
*
|
|
1051
|
+
* 'max' from the chain: what the vanilla obligation holds in, or owes to, this reserve (debt with the
|
|
1052
|
+
* interest the reserve has accrued). When the API reports a figure for that obligation it must agree
|
|
1053
|
+
* within 1%: an inflated debt or a negative deposit is refused (scan 2026-10-27 modules, F6/F10).
|
|
722
1054
|
*/
|
|
723
|
-
async
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1055
|
+
async resolveMax(side, me, mint, reserve, c) {
|
|
1056
|
+
const o = c.obligation;
|
|
1057
|
+
const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
|
|
1058
|
+
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);
|
|
1060
|
+
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
|
+
}
|
|
1071
|
+
if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
|
|
729
1072
|
}
|
|
730
|
-
|
|
731
|
-
return obligations.some((o) => o.obligation === vanilla) ? 0n : this.firstDepositAllowance;
|
|
1073
|
+
return amount;
|
|
732
1074
|
}
|
|
733
|
-
/**
|
|
734
|
-
async
|
|
735
|
-
|
|
736
|
-
const
|
|
737
|
-
if (
|
|
738
|
-
return
|
|
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) {
|
|
1077
|
+
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);
|
|
739
1081
|
}
|
|
740
1082
|
async quoteSupply(o) {
|
|
741
1083
|
const me = await this.me();
|
|
742
|
-
const
|
|
743
|
-
const
|
|
744
|
-
const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, amount,
|
|
745
|
-
return { fee, reserve: reserve.reserve };
|
|
1084
|
+
const p = await this.prepare("deposit", me, o.token, o.amount);
|
|
1085
|
+
const base64 = await this.build("deposit", me, p);
|
|
1086
|
+
const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules);
|
|
1087
|
+
return { fee, reserve: p.reserve.reserve };
|
|
746
1088
|
}
|
|
747
1089
|
async supply(o) {
|
|
748
1090
|
this.requireSigningAccount("supply(options)");
|
|
749
1091
|
const me = await this.me();
|
|
750
|
-
const
|
|
751
|
-
const
|
|
752
|
-
return this.sendBuilt(base64, this.spendExpectation(o.token, amount,
|
|
1092
|
+
const p = await this.prepare("deposit", me, o.token, o.amount);
|
|
1093
|
+
const base64 = await this.build("deposit", me, p);
|
|
1094
|
+
return this.sendBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules, "supply");
|
|
753
1095
|
}
|
|
754
1096
|
async quoteWithdraw(o) {
|
|
755
1097
|
const me = await this.me();
|
|
756
|
-
const
|
|
757
|
-
const
|
|
758
|
-
const expect = this.receiveExpectation(o.token, amount);
|
|
759
|
-
const { fee } = await this.quoteBuilt(base64, expect);
|
|
760
|
-
return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
1098
|
+
const p = await this.prepare("withdraw", me, o.token, o.amount);
|
|
1099
|
+
const base64 = await this.build("withdraw", me, p);
|
|
1100
|
+
const expect = this.receiveExpectation(o.token, p.amount);
|
|
1101
|
+
const { fee } = await this.quoteBuilt(base64, expect, p.rules);
|
|
1102
|
+
return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
761
1103
|
}
|
|
762
1104
|
async withdraw(o) {
|
|
763
1105
|
this.requireSigningAccount("withdraw(options)");
|
|
764
1106
|
const me = await this.me();
|
|
765
|
-
const
|
|
766
|
-
const
|
|
767
|
-
return this.sendBuilt(base64, this.receiveExpectation(o.token, amount), "withdraw");
|
|
1107
|
+
const p = await this.prepare("withdraw", me, o.token, o.amount);
|
|
1108
|
+
const base64 = await this.build("withdraw", me, p);
|
|
1109
|
+
return this.sendBuilt(base64, this.receiveExpectation(o.token, p.amount), p.rules, "withdraw");
|
|
1110
|
+
}
|
|
1111
|
+
/** A borrow pays out at most what was asked: a bigger one is debt the user did not choose. */
|
|
1112
|
+
borrowExpectation(mint, amount) {
|
|
1113
|
+
return this.receiveExpectation(mint, amount, 0n, amount);
|
|
768
1114
|
}
|
|
769
1115
|
async quoteBorrow(o) {
|
|
770
1116
|
const me = await this.me();
|
|
771
|
-
const
|
|
772
|
-
const
|
|
773
|
-
const expect = this.
|
|
774
|
-
const { fee } = await this.quoteBuilt(base64, expect);
|
|
775
|
-
return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
1117
|
+
const p = await this.prepare("borrow", me, o.token, o.amount);
|
|
1118
|
+
const base64 = await this.build("borrow", me, p);
|
|
1119
|
+
const expect = this.borrowExpectation(o.token, p.amount);
|
|
1120
|
+
const { fee } = await this.quoteBuilt(base64, expect, p.rules);
|
|
1121
|
+
return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
776
1122
|
}
|
|
777
1123
|
async borrow(o) {
|
|
778
1124
|
this.requireSigningAccount("borrow(options)");
|
|
779
1125
|
const me = await this.me();
|
|
780
|
-
const
|
|
781
|
-
const
|
|
782
|
-
return this.sendBuilt(base64, this.
|
|
1126
|
+
const p = await this.prepare("borrow", me, o.token, o.amount);
|
|
1127
|
+
const base64 = await this.build("borrow", me, p);
|
|
1128
|
+
return this.sendBuilt(base64, this.borrowExpectation(o.token, p.amount), p.rules, "borrow");
|
|
1129
|
+
}
|
|
1130
|
+
/** Interest accrues between the quote and the block: allow the slippage tolerance on top of the debt read. */
|
|
1131
|
+
repayExpectation(mint, amount) {
|
|
1132
|
+
return this.spendExpectation(mint, amount + (amount - lessBps(amount, this.slippageBps)));
|
|
783
1133
|
}
|
|
784
1134
|
async quoteRepay(o) {
|
|
785
1135
|
const me = await this.me();
|
|
786
|
-
const
|
|
787
|
-
const
|
|
788
|
-
const { fee } = await this.quoteBuilt(base64, this.
|
|
789
|
-
return { fee, reserve: reserve.reserve };
|
|
1136
|
+
const p = await this.prepare("repay", me, o.token, o.amount);
|
|
1137
|
+
const base64 = await this.build("repay", me, p);
|
|
1138
|
+
const { fee } = await this.quoteBuilt(base64, this.repayExpectation(o.token, p.amount), p.rules);
|
|
1139
|
+
return { fee, reserve: p.reserve.reserve };
|
|
790
1140
|
}
|
|
791
1141
|
async repay(o) {
|
|
792
1142
|
this.requireSigningAccount("repay(options)");
|
|
793
1143
|
const me = await this.me();
|
|
794
|
-
const
|
|
795
|
-
const
|
|
796
|
-
return this.sendBuilt(base64, this.
|
|
1144
|
+
const p = await this.prepare("repay", me, o.token, o.amount);
|
|
1145
|
+
const base64 = await this.build("repay", me, p);
|
|
1146
|
+
return this.sendBuilt(base64, this.repayExpectation(o.token, p.amount), p.rules, "repay");
|
|
797
1147
|
}
|
|
798
1148
|
};
|
|
799
1149
|
export {
|
|
800
1150
|
ADDRESS_LOOKUP_TABLE_PROGRAM,
|
|
1151
|
+
CHAIN_TOLERANCE_BPS,
|
|
801
1152
|
DEFAULT_FIRST_DEPOSIT_ALLOWANCE,
|
|
802
1153
|
DEFAULT_RENT_ALLOWANCE,
|
|
803
1154
|
FARMS_PROGRAM,
|
|
804
1155
|
INSTRUCTION_NAMES,
|
|
1156
|
+
IX,
|
|
805
1157
|
KAMINO_API,
|
|
806
1158
|
KAMINO_PROGRAM_ALLOWLIST,
|
|
807
1159
|
KLEND_PROGRAM,
|
|
@@ -818,17 +1170,29 @@ export {
|
|
|
818
1170
|
WAD,
|
|
819
1171
|
WITHDRAW_ALL,
|
|
820
1172
|
WSOL_MINT,
|
|
1173
|
+
associatedTokenAddress,
|
|
1174
|
+
debtNow,
|
|
1175
|
+
decodeFarmUser,
|
|
1176
|
+
decodeObligation,
|
|
1177
|
+
decodeReserve,
|
|
1178
|
+
decodeVault,
|
|
821
1179
|
KaminoVaultProtocolSolana as default,
|
|
1180
|
+
depositedLiquidity,
|
|
822
1181
|
divWadUp,
|
|
1182
|
+
farmUserState,
|
|
823
1183
|
findProgramAddress,
|
|
824
1184
|
fromDecimalString,
|
|
825
1185
|
instructionName,
|
|
826
1186
|
lessBps,
|
|
1187
|
+
marketRules,
|
|
827
1188
|
mulWad,
|
|
1189
|
+
plumbing,
|
|
828
1190
|
toAmount,
|
|
829
1191
|
toDecimalString,
|
|
830
1192
|
toWad,
|
|
831
1193
|
vanillaObligation,
|
|
832
|
-
|
|
1194
|
+
vaultRules,
|
|
1195
|
+
vaultSharesMint,
|
|
1196
|
+
vaultTokensPerShareWad
|
|
833
1197
|
};
|
|
834
1198
|
//# sourceMappingURL=index.js.map
|