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