@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.cjs CHANGED
@@ -9,9 +9,9 @@ var __export = (target, all) => {
9
9
  };
10
10
  var __copyProps = (to, from, except, desc) => {
11
11
  if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
12
+ for (let key2 of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
14
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
15
15
  }
16
16
  return to;
17
17
  };
@@ -21,10 +21,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  ADDRESS_LOOKUP_TABLE_PROGRAM: () => ADDRESS_LOOKUP_TABLE_PROGRAM,
24
+ CHAIN_TOLERANCE_BPS: () => CHAIN_TOLERANCE_BPS,
24
25
  DEFAULT_FIRST_DEPOSIT_ALLOWANCE: () => DEFAULT_FIRST_DEPOSIT_ALLOWANCE,
25
26
  DEFAULT_RENT_ALLOWANCE: () => DEFAULT_RENT_ALLOWANCE,
26
27
  FARMS_PROGRAM: () => FARMS_PROGRAM,
27
28
  INSTRUCTION_NAMES: () => INSTRUCTION_NAMES,
29
+ IX: () => IX,
28
30
  KAMINO_API: () => KAMINO_API,
29
31
  KAMINO_PROGRAM_ALLOWLIST: () => KAMINO_PROGRAM_ALLOWLIST,
30
32
  KLEND_PROGRAM: () => KLEND_PROGRAM,
@@ -41,18 +43,30 @@ __export(src_exports, {
41
43
  WAD: () => WAD,
42
44
  WITHDRAW_ALL: () => WITHDRAW_ALL,
43
45
  WSOL_MINT: () => WSOL_MINT,
46
+ associatedTokenAddress: () => associatedTokenAddress,
47
+ debtNow: () => debtNow,
48
+ decodeFarmUser: () => decodeFarmUser,
49
+ decodeObligation: () => decodeObligation,
50
+ decodeReserve: () => decodeReserve,
51
+ decodeVault: () => decodeVault,
44
52
  default: () => KaminoVaultProtocolSolana,
53
+ depositedLiquidity: () => depositedLiquidity,
45
54
  divWadUp: () => divWadUp,
55
+ farmUserState: () => farmUserState,
46
56
  findProgramAddress: () => findProgramAddress,
47
57
  fromDecimalString: () => fromDecimalString,
48
58
  instructionName: () => instructionName,
49
59
  lessBps: () => lessBps,
60
+ marketRules: () => marketRules,
50
61
  mulWad: () => mulWad,
62
+ plumbing: () => plumbing,
51
63
  toAmount: () => toAmount,
52
64
  toDecimalString: () => toDecimalString,
53
65
  toWad: () => toWad,
54
66
  vanillaObligation: () => vanillaObligation,
55
- vaultSharesMint: () => vaultSharesMint
67
+ vaultRules: () => vaultRules,
68
+ vaultSharesMint: () => vaultSharesMint,
69
+ vaultTokensPerShareWad: () => vaultTokensPerShareWad
56
70
  });
57
71
  module.exports = __toCommonJS(src_exports);
58
72
 
@@ -85,9 +99,10 @@ function toDecimalString(amount, decimals) {
85
99
  }
86
100
  function fromDecimalString(value, decimals) {
87
101
  const s = String(value).trim();
88
- const m = /^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
89
- if (!m) throw new KaminoError(`Not a decimal number: ${s}`);
90
- let [, sign, whole = "", frac = "", exp] = m;
102
+ if (/^[-+]/.test(s)) throw new KaminoError(`Kamino reported a signed figure (${s.slice(0, 40)}); every amount and rate it reports is positive.`);
103
+ const m = /^(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
104
+ if (!m) throw new KaminoError(`Not a decimal number: ${s.slice(0, 40)}`);
105
+ let [, whole = "", frac = "", exp] = m;
91
106
  if (exp) {
92
107
  const e = Number(exp);
93
108
  const digits = whole + frac;
@@ -104,8 +119,7 @@ function fromDecimalString(value, decimals) {
104
119
  }
105
120
  }
106
121
  const scaled = (whole || "0") + (frac + "0".repeat(decimals)).slice(0, decimals);
107
- const out = BigInt(scaled.replace(/^0+(?=\d)/, ""));
108
- return sign ? -out : out;
122
+ return BigInt(scaled.replace(/^0+(?=\d)/, ""));
109
123
  }
110
124
  var WAD = 10n ** 18n;
111
125
  var toWad = (value) => fromDecimalString(value, 18);
@@ -113,6 +127,9 @@ var mulWad = (a, wad) => a * wad / WAD;
113
127
  var divWadUp = (a, wad) => wad === 0n ? 0n : (a * WAD + wad - 1n) / wad;
114
128
  var lessBps = (amount, bps) => amount * BigInt(1e4 - bps) / 10000n;
115
129
 
130
+ // src/base.ts
131
+ var import_core = require("@anywalletkit/core");
132
+
116
133
  // src/api.ts
117
134
  var KAMINO_API = "https://api.kamino.finance";
118
135
  var MAIN_MARKET = "7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF";
@@ -261,7 +278,7 @@ var KaminoApi = class {
261
278
  }));
262
279
  const coll = info.collateral ?? {}, debt = info.debt ?? {};
263
280
  return {
264
- obligation: String(row.loanId ?? row.obligation ?? row.address ?? ""),
281
+ obligation: String(row.obligationAddress ?? row.loanId ?? row.obligation ?? row.address ?? ""),
265
282
  market: String(row.marketId ?? market),
266
283
  user: String(row.user ?? ""),
267
284
  elevationGroup: num(row.elevationGroup),
@@ -289,7 +306,7 @@ var KaminoApi = class {
289
306
  buildVaultDeposit(p) {
290
307
  return this.ktx("/ktx/kvault/deposit", strip(p));
291
308
  }
292
- /** Base64 unsigned v0 transaction: redeem `amount` SHARES (decimal) — {@link WITHDRAW_ALL} for every share. */
309
+ /** Base64 unsigned v0 transaction: redeem `amount` SHARES (decimal). */
293
310
  buildVaultWithdraw(p) {
294
311
  return this.ktx("/ktx/kvault/withdraw", strip(p));
295
312
  }
@@ -310,9 +327,6 @@ function strip(o) {
310
327
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
311
328
  }
312
329
 
313
- // src/base.ts
314
- var import_core = require("@anywalletkit/core");
315
-
316
330
  // src/programs.ts
317
331
  var KLEND_PROGRAM = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD";
318
332
  var KVAULT_PROGRAM = "KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd";
@@ -369,8 +383,8 @@ var INSTRUCTION_NAMES = Object.freeze({
369
383
  function instructionName(programId, data) {
370
384
  const table = INSTRUCTION_NAMES[programId];
371
385
  if (!table || data.length < 8) return void 0;
372
- const hex = Array.from(data.subarray(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
373
- return table[hex];
386
+ const hex2 = Array.from(data.subarray(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
387
+ return table[hex2];
374
388
  }
375
389
 
376
390
  // src/base.ts
@@ -457,31 +471,45 @@ var KaminoBase = class extends import_core.LendingProtocol {
457
471
  }
458
472
  return p;
459
473
  }
460
- guard(expect) {
461
- return { programAllowlist: KAMINO_PROGRAM_ALLOWLIST, expect };
474
+ guard(expect, instructions) {
475
+ if (!instructions.length) throw new KaminoError("A Kamino transaction is checked against the instructions its operation takes; none were given.");
476
+ return { programAllowlist: KAMINO_PROGRAM_ALLOWLIST, instructions, expect };
477
+ }
478
+ /** Accounts from the chain through the wallet's RPC, in the order asked (null where none exists). */
479
+ async readChain(addresses) {
480
+ const s = this.surface();
481
+ if (typeof s.getAccountInfos !== "function") throw new KaminoError("Kamino checks the API against the chain: it needs a @anywalletkit/wallet-solana account (getAccountInfos).");
482
+ const out = await s.getAccountInfos(addresses);
483
+ if (!Array.isArray(out) || out.length !== addresses.length) throw new KaminoError("The account returned a different number of accounts than asked.");
484
+ return out;
462
485
  }
463
486
  /** The wallet sends `amount` of `mint` (SOL counts on the lamport side) and may lose rent on top. */
464
487
  spendExpectation(mint, amount, extraLamports = 0n) {
488
+ if (amount <= 0n) throw new KaminoError(`Refusing a transaction that spends ${amount} of ${mint}: the amount must be positive.`);
465
489
  const rent = this.rentAllowance + extraLamports;
466
490
  return mint === WSOL_MINT ? { maxLamportsOut: amount + rent } : { maxLamportsOut: rent, maxTokenOut: { mint, amount } };
467
491
  }
468
- /** The wallet must receive at least `expected × (1 − slippage)` of `mint`; rent is the only SOL it may lose. */
469
- receiveExpectation(mint, expected, extraLamports = 0n) {
492
+ /**
493
+ * The wallet must receive at least `expected × (1 − slippage)` of `mint` (and at most `max`, when
494
+ * given); rent is the only SOL it may lose.
495
+ */
496
+ receiveExpectation(mint, expected, extraLamports = 0n, max) {
497
+ if (expected <= 0n) throw new KaminoError(`Refusing a transaction that should pay out ${expected} of ${mint}: the amount must be positive.`);
470
498
  const min = expected * BigInt(1e4 - this.slippageBps) / 10000n;
471
- return { maxLamportsOut: this.rentAllowance + extraLamports, tokenIn: { mint, minAmount: min } };
499
+ return { maxLamportsOut: this.rentAllowance + extraLamports, tokenIn: { mint, minAmount: min, ...max !== void 0 ? { maxAmount: max } : {} } };
472
500
  }
473
501
  /** Simulate the built transaction through the account's guard and return its fee; nothing is signed. */
474
- async quoteBuilt(base64, expect) {
502
+ async quoteBuilt(base64, expect, instructions) {
475
503
  const s = this.surface();
476
504
  if (typeof s.checkSerialized !== "function") throw new KaminoError("Quoting a Kamino transaction needs a @anywalletkit/wallet-solana account (checkSerialized).");
477
- const check = await s.checkSerialized(base64, this.guard(expect));
505
+ const check = await s.checkSerialized(base64, this.guard(expect, instructions));
478
506
  return { fee: BigInt(check.quote.fee) };
479
507
  }
480
508
  /** Guard, sign and broadcast the built transaction; the account refuses before signing if the proof fails. */
481
- async sendBuilt(base64, expect, method) {
509
+ async sendBuilt(base64, expect, instructions, method) {
482
510
  const account = this.requireSigningAccount(`${method}(options)`);
483
511
  if (typeof account.sendSerialized !== "function") throw new KaminoError(`${method}() needs a @anywalletkit/wallet-solana account (sendSerialized).`);
484
- const sent = await account.sendSerialized(base64, this.guard(expect));
512
+ const sent = await account.sendSerialized(base64, this.guard(expect, instructions));
485
513
  if (!sent?.hash) throw new KaminoError("The account returned no transaction signature.");
486
514
  return { hash: sent.hash, fee: BigInt(sent.fee ?? 0) };
487
515
  }
@@ -490,13 +518,134 @@ var KaminoBase = class extends import_core.LendingProtocol {
490
518
  }
491
519
  };
492
520
 
521
+ // src/chain.ts
522
+ var import_base = require("@scure/base");
523
+ var SF = 1n << 60n;
524
+ var FARM_STAKE_SCALE = 10n ** 18n;
525
+ var CHAIN_TOLERANCE_BPS = 100n;
526
+ var DEFAULT_KEY = "11111111111111111111111111111111";
527
+ var KINDS = {
528
+ VaultState: { program: KVAULT_PROGRAM, disc: "e4c452a562d2eb98", size: 62552 },
529
+ Reserve: { program: KLEND_PROGRAM, disc: "2bf2ccca1af73b7f", size: 8624 },
530
+ Obligation: { program: KLEND_PROGRAM, disc: "a8ce8d6a584caca7", size: 3344 },
531
+ UserState: { program: FARMS_PROGRAM, disc: "48b155f94ca7ba7e", size: 920 }
532
+ };
533
+ var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
534
+ var u64 = (d, o) => new DataView(d.buffer, d.byteOffset, d.byteLength).getBigUint64(o, true);
535
+ var u128 = (d, o) => u64(d, o) + (u64(d, o + 8) << 64n);
536
+ var u256 = (d, o) => u128(d, o) + (u128(d, o + 16) << 128n);
537
+ var key = (d, o) => import_base.base58.encode(d.subarray(o, o + 32));
538
+ function decimalsAt(d, o, what) {
539
+ const v = u64(d, o);
540
+ if (v > 255n) throw new KaminoError(`${what} records ${v} decimals; a mint has at most 255.`);
541
+ return Number(v.toString());
542
+ }
543
+ function bytesOf(kind, address, acc) {
544
+ const k = KINDS[kind];
545
+ if (!acc) throw new KaminoError(`${kind} ${address} does not exist on chain.`);
546
+ if (acc.owner !== k.program) throw new KaminoError(`${address} is not a Kamino ${kind}: it belongs to ${acc.owner}.`);
547
+ if (acc.data.length < k.size || hex(acc.data.subarray(0, 8)) !== k.disc) throw new KaminoError(`${address} is not a Kamino ${kind} account.`);
548
+ return acc.data;
549
+ }
550
+ function decodeVault(address, acc) {
551
+ const d = bytesOf("VaultState", address, acc);
552
+ const allocations = [];
553
+ for (let i = 0; i < 25; i++) {
554
+ const o = 312 + i * 2160;
555
+ const reserve = key(d, o);
556
+ if (reserve !== DEFAULT_KEY) allocations.push({ reserve, ctokens: u64(d, o + 1104) });
557
+ }
558
+ const farm = key(d, 58600);
559
+ return {
560
+ tokenMint: key(d, 80),
561
+ tokenDecimals: decimalsAt(d, 112, `Vault ${address}`),
562
+ tokenProgram: key(d, 152),
563
+ sharesMint: key(d, 184),
564
+ sharesDecimals: decimalsAt(d, 216, `Vault ${address}`),
565
+ tokenAvailable: u64(d, 224),
566
+ sharesIssued: u64(d, 232),
567
+ pendingFeesSf: u128(d, 296),
568
+ allocations,
569
+ minDeposit: u64(d, 58408),
570
+ minWithdraw: u64(d, 58416),
571
+ farm: farm === DEFAULT_KEY ? null : farm
572
+ };
573
+ }
574
+ function decodeReserve(address, acc) {
575
+ const d = bytesOf("Reserve", address, acc);
576
+ const total = u64(d, 224) * SF + u128(d, 232) - u128(d, 344) - u128(d, 360) - u128(d, 376);
577
+ return {
578
+ lendingMarket: key(d, 32),
579
+ mint: key(d, 128),
580
+ decimals: decimalsAt(d, 272, `Reserve ${address}`),
581
+ tokenProgram: key(d, 408),
582
+ totalLiquiditySf: total > 0n ? total : 0n,
583
+ collateralSupply: u64(d, 2592),
584
+ cumulativeBorrowRate: u256(d, 296)
585
+ };
586
+ }
587
+ function collateralToLiquiditySf(r, ctokens) {
588
+ if (r.collateralSupply === 0n || r.totalLiquiditySf === 0n) return ctokens * SF;
589
+ return ctokens * r.totalLiquiditySf / r.collateralSupply;
590
+ }
591
+ function decodeObligation(address, acc) {
592
+ const d = bytesOf("Obligation", address, acc);
593
+ const deposits = [], borrows = [];
594
+ for (let i = 0; i < 8; i++) {
595
+ const o = 96 + i * 136;
596
+ const reserve = key(d, o);
597
+ if (reserve !== DEFAULT_KEY) deposits.push({ reserve, ctokens: u64(d, o + 32) });
598
+ }
599
+ for (let i = 0; i < 5; i++) {
600
+ const o = 1208 + i * 200;
601
+ const reserve = key(d, o);
602
+ if (reserve !== DEFAULT_KEY) borrows.push({ reserve, cumulativeBorrowRate: u256(d, o + 32), borrowedSf: u128(d, o + 88) });
603
+ }
604
+ return { lendingMarket: key(d, 32), owner: key(d, 64), deposits, borrows };
605
+ }
606
+ function depositedLiquidity(o, r, reserve) {
607
+ return o.deposits.filter((x) => x.reserve === reserve).reduce((sum, x) => sum + collateralToLiquiditySf(r, x.ctokens) / SF, 0n);
608
+ }
609
+ function debtNow(o, r, reserve) {
610
+ return o.borrows.filter((x) => x.reserve === reserve).reduce((sum, x) => {
611
+ const sf = x.cumulativeBorrowRate > 0n && r.cumulativeBorrowRate > x.cumulativeBorrowRate ? x.borrowedSf * r.cumulativeBorrowRate / x.cumulativeBorrowRate : x.borrowedSf;
612
+ return sum + (sf + SF - 1n) / SF;
613
+ }, 0n);
614
+ }
615
+ function decodeFarmUser(address, acc) {
616
+ const d = bytesOf("UserState", address, acc);
617
+ return { farm: key(d, 16), owner: key(d, 48), staked: u128(d, 408) / FARM_STAKE_SCALE };
618
+ }
619
+ function tokenAmount(acc, mint, owner) {
620
+ if (!acc || acc.owner !== TOKEN_PROGRAM && acc.owner !== TOKEN_2022_PROGRAM || acc.data.length < 165) return 0n;
621
+ if (key(acc.data, 0) !== mint || key(acc.data, 32) !== owner) return 0n;
622
+ return u64(acc.data, 64);
623
+ }
624
+ function vaultTokensPerShareWad(v, reserves) {
625
+ let aumSf = v.tokenAvailable * SF;
626
+ for (const a of v.allocations) {
627
+ if (a.ctokens === 0n) continue;
628
+ const r = reserves.get(a.reserve);
629
+ if (!r) throw new KaminoError(`The vault's reserve ${a.reserve} was not read.`);
630
+ aumSf += collateralToLiquiditySf(r, a.ctokens);
631
+ }
632
+ aumSf -= v.pendingFeesSf;
633
+ if (v.sharesIssued === 0n) return WAD;
634
+ if (aumSf <= 0n) throw new KaminoError("The vault holds nothing against its shares on chain.");
635
+ return aumSf * 10n ** BigInt(v.sharesDecimals) * WAD / (v.sharesIssued * SF * 10n ** BigInt(v.tokenDecimals));
636
+ }
637
+ function withinTolerance(a, b) {
638
+ const diff = a > b ? a - b : b - a;
639
+ return diff * 10000n <= b * CHAIN_TOLERANCE_BPS;
640
+ }
641
+
493
642
  // src/pda.ts
494
643
  var import_ed25519 = require("@noble/curves/ed25519.js");
495
644
  var import_sha2 = require("@noble/hashes/sha2.js");
496
- var import_base = require("@scure/base");
645
+ var import_base2 = require("@scure/base");
497
646
  var PDA_MARKER = new TextEncoder().encode("ProgramDerivedAddress");
498
647
  function findProgramAddress(seeds, programId) {
499
- const program = import_base.base58.decode(programId);
648
+ const program = import_base2.base58.decode(programId);
500
649
  for (let bump = 255; bump >= 0; bump--) {
501
650
  const parts = [...seeds, Uint8Array.of(bump), program, PDA_MARKER];
502
651
  const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
@@ -509,17 +658,115 @@ function findProgramAddress(seeds, programId) {
509
658
  try {
510
659
  import_ed25519.ed25519.Point.fromBytes(hash);
511
660
  } catch {
512
- return import_base.base58.encode(hash);
661
+ return import_base2.base58.encode(hash);
513
662
  }
514
663
  }
515
664
  throw new Error("No program address found for these seeds.");
516
665
  }
517
666
  function vanillaObligation(user, market, klendProgram = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD") {
518
667
  const zero = new Uint8Array(32);
519
- return findProgramAddress([Uint8Array.of(0), Uint8Array.of(0), import_base.base58.decode(user), import_base.base58.decode(market), zero, zero], klendProgram);
668
+ return findProgramAddress([Uint8Array.of(0), Uint8Array.of(0), import_base2.base58.decode(user), import_base2.base58.decode(market), zero, zero], klendProgram);
520
669
  }
521
670
  function vaultSharesMint(vault, kvaultProgram) {
522
- return findProgramAddress([new TextEncoder().encode("shares"), import_base.base58.decode(vault)], kvaultProgram);
671
+ return findProgramAddress([new TextEncoder().encode("shares"), import_base2.base58.decode(vault)], kvaultProgram);
672
+ }
673
+ function associatedTokenAddress(owner, mint, tokenProgram) {
674
+ return findProgramAddress([import_base2.base58.decode(owner), import_base2.base58.decode(tokenProgram), import_base2.base58.decode(mint)], "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
675
+ }
676
+ function farmUserState(farm, owner, farmsProgram = "FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr") {
677
+ return findProgramAddress([new TextEncoder().encode("user"), import_base2.base58.decode(farm), import_base2.base58.decode(owner)], farmsProgram);
678
+ }
679
+
680
+ // src/policy.ts
681
+ var IX = Object.freeze({
682
+ initUserMetadata: "75a9b045c5170fa2",
683
+ initObligation: "fb0ae74c1b0b9f60",
684
+ initObligationFarmsForReserve: "883f0fbad398a8a4",
685
+ refreshReserve: "02da8aeb4fc91966",
686
+ refreshObligation: "218493e497c04859",
687
+ refreshObligationFarmsForReserve: "8c90fd150a4af803",
688
+ requestElevationGroup: "2477fb8122f00793",
689
+ depositV2: "d8e0bf1bcc9766af",
690
+ withdrawV2: "eb34779895c51407",
691
+ borrowV2: "a1808ff5abc7c206",
692
+ repayV2: "74aed54cb435d290",
693
+ vaultDeposit: "f223c68952e1f2b6",
694
+ vaultWithdraw: "b712469c946da122",
695
+ vaultWithdrawFromAvailable: "1383709baadc2239",
696
+ farmInitializeUser: "6f11b9fa3c7a26fe",
697
+ farmStake: "ceb0ca12c8d1b36c",
698
+ farmUnstake: "5a5f6b2acd7c32e1",
699
+ farmWithdrawUnstaked: "2466bb31dc248443"
700
+ });
701
+ function plumbing(me, wsolAta) {
702
+ return [
703
+ { program: COMPUTE_BUDGET_PROGRAM },
704
+ { program: MEMO_PROGRAM },
705
+ // Create / CreateIdempotent: payer and owner are the wallet.
706
+ { program: ASSOCIATED_TOKEN_PROGRAM, data: "", dataLength: 0, accounts: { 0: me, 2: me } },
707
+ { program: ASSOCIATED_TOKEN_PROGRAM, data: "01", dataLength: 1, accounts: { 0: me, 2: me } },
708
+ // System Transfer into the wallet's wSOL account, SyncNative on it, and closing it back to the wallet.
709
+ { program: SYSTEM_PROGRAM, data: "02000000", dataLength: 12, accounts: { 0: me, 1: wsolAta } },
710
+ { program: TOKEN_PROGRAM, data: "11", dataLength: 1, accounts: { 0: wsolAta } },
711
+ { program: TOKEN_PROGRAM, data: "09", dataLength: 1, accounts: { 0: wsolAta, 1: me, 2: me } }
712
+ ];
713
+ }
714
+ function marketRules(op, a) {
715
+ const { me, market, obligation, reserve, mint, ata } = a;
716
+ const owner = { 0: me, 1: obligation, 2: market };
717
+ const rules = [
718
+ ...plumbing(me, a.wsolAta),
719
+ { program: KLEND_PROGRAM, data: IX.refreshReserve, dataLength: 8, accounts: { 1: market } },
720
+ { program: KLEND_PROGRAM, data: IX.refreshObligation, dataLength: 8, accounts: { 0: market, 1: obligation } },
721
+ { program: KLEND_PROGRAM, data: IX.refreshObligationFarmsForReserve, dataLength: 9, accounts: { 1: obligation, 6: market } },
722
+ { program: KLEND_PROGRAM, data: IX.initObligationFarmsForReserve, dataLength: 9, accounts: { 0: me, 1: me, 2: obligation, 7: market } }
723
+ ];
724
+ if (op === "deposit") {
725
+ rules.push(
726
+ // A first deposit: user metadata, the vanilla obligation (tag 0, id 0) and the user's lookup table, all paid by the wallet.
727
+ { program: KLEND_PROGRAM, data: IX.initUserMetadata, dataLength: 40, accounts: { 0: me, 1: me } },
728
+ { program: KLEND_PROGRAM, data: `${IX.initObligation}0000`, dataLength: 10, accounts: { 0: me, 1: me, 2: obligation, 3: market } },
729
+ { program: ADDRESS_LOOKUP_TABLE_PROGRAM, data: "00000000", dataLength: 13, accounts: { 1: me, 2: me } },
730
+ { program: ADDRESS_LOOKUP_TABLE_PROGRAM, data: "02000000", accounts: { 1: me } },
731
+ { program: KLEND_PROGRAM, data: IX.depositV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 9: ata } }
732
+ );
733
+ } else if (op === "withdraw") {
734
+ rules.push({ program: KLEND_PROGRAM, data: IX.withdrawV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 9: ata } });
735
+ } else if (op === "borrow") {
736
+ rules.push(
737
+ { program: KLEND_PROGRAM, data: IX.requestElevationGroup, dataLength: 9, accounts: owner },
738
+ { program: KLEND_PROGRAM, data: IX.borrowV2, dataLength: 16, accounts: { ...owner, 4: reserve, 5: mint, 8: ata } }
739
+ );
740
+ } else {
741
+ rules.push({ program: KLEND_PROGRAM, data: IX.repayV2, dataLength: 16, accounts: { ...owner, 3: reserve, 4: mint, 6: ata } });
742
+ }
743
+ return rules;
744
+ }
745
+ function vaultRules(op, a, opts) {
746
+ const { me, vault, mint, sharesMint, tokenAta, sharesAtas, farm } = a;
747
+ const rules = plumbing(me, a.wsolAta);
748
+ if (op === "deposit") {
749
+ rules.push({ program: KVAULT_PROGRAM, data: IX.vaultDeposit, dataLength: 16, accounts: { 0: me, 1: vault, 3: mint, 5: sharesMint, 6: tokenAta, 7: sharesAtas } });
750
+ if (opts.stake && farm) {
751
+ rules.push(
752
+ { program: FARMS_PROGRAM, data: IX.farmInitializeUser, dataLength: 8, accounts: { 0: me, 1: me, 2: me, 3: me, 4: farm.userState, 5: farm.farm } },
753
+ { program: FARMS_PROGRAM, data: IX.farmStake, dataLength: 16, accounts: { 0: me, 1: farm.userState, 2: farm.farm, 4: sharesAtas, 5: sharesMint } }
754
+ );
755
+ }
756
+ } else {
757
+ const redeem = { 0: me, 1: vault, 5: tokenAta, 6: mint, 7: sharesAtas, 8: sharesMint };
758
+ rules.push(
759
+ { program: KVAULT_PROGRAM, data: IX.vaultWithdrawFromAvailable, dataLength: 16, accounts: redeem },
760
+ { program: KVAULT_PROGRAM, data: IX.vaultWithdraw, dataLength: 16, accounts: redeem }
761
+ );
762
+ if (farm) {
763
+ rules.push(
764
+ { program: FARMS_PROGRAM, data: IX.farmUnstake, dataLength: 24, accounts: { 0: me, 1: farm.userState, 2: farm.farm } },
765
+ { program: FARMS_PROGRAM, data: IX.farmWithdrawUnstaked, dataLength: 8, accounts: { 0: me, 1: farm.userState, 2: farm.farm, 3: sharesAtas } }
766
+ );
767
+ }
768
+ }
769
+ return rules;
523
770
  }
524
771
 
525
772
  // src/vault.ts
@@ -615,15 +862,71 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
615
862
  assetsToShares(assets, v, tokensPerShareWad) {
616
863
  return rescale(divWadUp(assets, tokensPerShareWad), v.tokenMintDecimals, v.sharesMintDecimals);
617
864
  }
865
+ /**
866
+ * What a write's bounds are computed from, read from the chain (scan 2026-10-27 modules, F2/F11/F12):
867
+ * the vault's state and the reserves it invests in give the share price, the wallet's shares
868
+ * account and farm state its position. The API must describe the same vault — mints, decimals —
869
+ * and quote a `tokensPerShare` within 1% of the chain's; a lying rate is refused, never used.
870
+ */
871
+ async onChain(me, v, m) {
872
+ const refuse = (what) => {
873
+ throw new KaminoError(`Kamino's answer for vault ${this.vault} does not match the chain: ${what}.`);
874
+ };
875
+ const state = decodeVault(this.vault, (await this.readChain([this.vault]))[0] ?? null);
876
+ if (state.tokenMint !== v.tokenMint || state.sharesMint !== v.sharesMint) refuse(`mints ${v.tokenMint} / ${v.sharesMint} are ${state.tokenMint} / ${state.sharesMint} on chain`);
877
+ if (state.tokenDecimals !== v.tokenMintDecimals || state.sharesDecimals !== v.sharesMintDecimals) refuse(`decimals ${v.tokenMintDecimals} / ${v.sharesMintDecimals} are ${state.tokenDecimals} / ${state.sharesDecimals} on chain`);
878
+ const invested = state.allocations.filter((a) => a.ctokens > 0n).map((a) => a.reserve);
879
+ const sharesAtas = [associatedTokenAddress(me, state.sharesMint, TOKEN_PROGRAM), associatedTokenAddress(me, state.sharesMint, TOKEN_2022_PROGRAM)];
880
+ const userState = state.farm ? farmUserState(state.farm, me) : null;
881
+ const accs = await this.readChain([...invested, ...sharesAtas, ...userState ? [userState] : []]);
882
+ const reserves = /* @__PURE__ */ new Map();
883
+ invested.forEach((r, i) => {
884
+ const reserve = decodeReserve(r, accs[i] ?? null);
885
+ if (reserve.mint !== state.tokenMint) refuse(`its reserve ${r} lends ${reserve.mint}`);
886
+ reserves.set(r, reserve);
887
+ });
888
+ const tokensPerShareWad = vaultTokensPerShareWad(state, reserves);
889
+ const quoted = toWad(m.tokensPerShare);
890
+ if (quoted <= 0n) refuse(`tokensPerShare ${m.tokensPerShare} is not positive`);
891
+ if (!withinTolerance(quoted, tokensPerShareWad)) refuse(`tokensPerShare ${m.tokensPerShare} is ${toDecimalString(tokensPerShareWad, 18)} on chain`);
892
+ const unstaked = sharesAtas.reduce((sum, a, i) => sum + tokenAmount(accs[invested.length + i] ?? null, state.sharesMint, me), 0n);
893
+ const farmAcc = userState ? accs[invested.length + 2] ?? null : null;
894
+ const stake = userState && farmAcc ? decodeFarmUser(userState, farmAcc) : null;
895
+ const staked = stake && stake.owner === me && stake.farm === state.farm ? stake.staked : 0n;
896
+ return {
897
+ state,
898
+ tokensPerShareWad,
899
+ sharesAtas,
900
+ tokenAta: associatedTokenAddress(me, state.tokenMint, state.tokenProgram),
901
+ farm: state.farm && userState ? { farm: state.farm, userState } : null,
902
+ unstaked,
903
+ staked
904
+ };
905
+ }
906
+ rules(op, me, c) {
907
+ return vaultRules(op, {
908
+ me,
909
+ vault: this.vault,
910
+ mint: c.state.tokenMint,
911
+ sharesMint: c.state.sharesMint,
912
+ tokenAta: c.tokenAta,
913
+ sharesAtas: c.sharesAtas,
914
+ farm: c.farm,
915
+ wsolAta: associatedTokenAddress(me, WSOL_MINT, TOKEN_PROGRAM)
916
+ }, { stake: !this.skipFarm });
917
+ }
618
918
  async plan(o, me) {
619
919
  const amount = toAmount(o.amount);
620
920
  const token = o.token ?? this._config.asset;
621
921
  if (token === void 0) throw new KaminoError(`Name the asset to deposit: pass 'token' or set 'asset' in the vault config.`);
622
922
  const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
623
923
  if (token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} takes ${symbolOf(v)} (${v.tokenMint}), not ${token}.`);
624
- if (amount < v.minDepositAmount) throw new KaminoError(`Deposit below the vault minimum: ${amount} < ${v.minDepositAmount} base units.`);
924
+ const c = await this.onChain(me, v, m);
925
+ if (amount < c.state.minDeposit) throw new KaminoError(`Deposit below the vault minimum: ${amount} < ${c.state.minDeposit} base units.`);
926
+ const expectedShares = this.assetsToShares(amount, v, c.tokensPerShareWad);
927
+ if (expectedShares <= 0n) throw new KaminoError(`A deposit of ${amount} base units buys no shares of vault ${this.vault}.`);
625
928
  const base64 = await this.api.buildVaultDeposit({ wallet: me, kvault: this.vault, amount: toDecimalString(amount, v.tokenMintDecimals), skipFarm: this.skipFarm, memo: this.memo() });
626
- return { base64, v, amount, expectedShares: this.assetsToShares(amount, v, toWad(m.tokensPerShare)) };
929
+ return { base64, v, amount, expectedShares, rules: this.rules("deposit", me, c) };
627
930
  }
628
931
  supplyExpectation(v, amount, expectedShares) {
629
932
  const e = this.spendExpectation(v.tokenMint, amount);
@@ -631,35 +934,37 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
631
934
  }
632
935
  async quoteSupply(o) {
633
936
  const me = await this.me();
634
- const { base64, v, amount, expectedShares } = await this.plan(o, me);
635
- const { fee } = await this.quoteBuilt(base64, this.supplyExpectation(v, amount, expectedShares));
937
+ const { base64, v, amount, expectedShares, rules } = await this.plan(o, me);
938
+ const { fee } = await this.quoteBuilt(base64, this.supplyExpectation(v, amount, expectedShares), rules);
636
939
  return { fee, expectedShares };
637
940
  }
638
941
  async supply(o) {
639
942
  this.requireSigningAccount("supply(options)");
640
943
  const me = await this.me();
641
- const { base64, v, amount, expectedShares } = await this.plan(o, me);
642
- return this.sendBuilt(base64, this.supplyExpectation(v, amount, expectedShares), "supply");
944
+ const { base64, v, amount, expectedShares, rules } = await this.plan(o, me);
945
+ return this.sendBuilt(base64, this.supplyExpectation(v, amount, expectedShares), rules, "supply");
643
946
  }
644
947
  async planWithdraw(o, me) {
645
- const [v, m, position] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault), this.getPosition()]);
948
+ const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
646
949
  if (o.token && o.token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} pays out ${symbolOf(v)} (${v.tokenMint}), not ${o.token}.`);
647
- if (position.shares === 0n) throw new KaminoError(`No position in vault ${this.vault} for ${me}.`);
648
- const tps = toWad(m.tokensPerShare);
950
+ const c = await this.onChain(me, v, m);
951
+ const held = c.unstaked + c.staked;
952
+ if (held === 0n) throw new KaminoError(`No position in vault ${this.vault} for ${me}.`);
953
+ const tps = c.tokensPerShareWad;
649
954
  let shares, amountArg;
650
955
  if (o.amount === "max") {
651
- shares = position.shares;
652
- amountArg = WITHDRAW_ALL;
956
+ shares = held;
957
+ amountArg = toDecimalString(held, v.sharesMintDecimals);
653
958
  } else {
654
959
  const assets = toAmount(o.amount);
655
960
  shares = this.assetsToShares(assets, v, tps);
656
- if (shares > position.shares) throw new KaminoError(`Withdrawal exceeds the position: ${assets} asset units need ${shares} shares, the wallet holds ${position.shares}.`);
961
+ if (shares > held) throw new KaminoError(`Withdrawal exceeds the position: ${assets} asset units need ${shares} shares, the wallet holds ${held}.`);
657
962
  amountArg = toDecimalString(shares, v.sharesMintDecimals);
658
963
  }
659
964
  const expectedAssets = this.sharesToAssets(shares, v, tps);
660
- if (expectedAssets < v.minWithdrawAmount) throw new KaminoError(`Withdrawal below the vault minimum: ${expectedAssets} < ${v.minWithdrawAmount} base units.`);
965
+ if (expectedAssets < c.state.minWithdraw) throw new KaminoError(`Withdrawal below the vault minimum: ${expectedAssets} < ${c.state.minWithdraw} base units.`);
661
966
  const base64 = await this.api.buildVaultWithdraw({ wallet: me, kvault: this.vault, amount: amountArg, memo: this.memo() });
662
- return { base64, v, shares, expectedAssets };
967
+ return { base64, v, shares, expectedAssets, rules: this.rules("withdraw", me, c) };
663
968
  }
664
969
  /**
665
970
  * The asset comes in (within slippage), and the shares being redeemed may leave the wallet's
@@ -671,16 +976,16 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
671
976
  }
672
977
  async quoteWithdraw(o) {
673
978
  const me = await this.me();
674
- const { base64, v, shares, expectedAssets } = await this.planWithdraw(o, me);
979
+ const { base64, v, shares, expectedAssets, rules } = await this.planWithdraw(o, me);
675
980
  const expect = this.withdrawExpectation(v, shares, expectedAssets);
676
- const { fee } = await this.quoteBuilt(base64, expect);
981
+ const { fee } = await this.quoteBuilt(base64, expect, rules);
677
982
  return { fee, shares, expectedAssets, minAssets: expect.tokenIn.minAmount };
678
983
  }
679
984
  async withdraw(o) {
680
985
  this.requireSigningAccount("withdraw(options)");
681
986
  const me = await this.me();
682
- const { base64, v, shares, expectedAssets } = await this.planWithdraw(o, me);
683
- return this.sendBuilt(base64, this.withdrawExpectation(v, shares, expectedAssets), "withdraw");
987
+ const { base64, v, shares, expectedAssets, rules } = await this.planWithdraw(o, me);
988
+ return this.sendBuilt(base64, this.withdrawExpectation(v, shares, expectedAssets), rules, "withdraw");
684
989
  }
685
990
  async borrow() {
686
991
  throw new import_core2.NotImplementedError("borrow(options) \u2014 an Earn vault does not lend to its depositors; use KaminoMarketProtocolSolana.");
@@ -767,91 +1072,138 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
767
1072
  }
768
1073
  return { obligations, supplied, borrowed };
769
1074
  }
770
- async lend(kind, me, mint, amount) {
1075
+ /**
1076
+ * The reserve and the wallet's vanilla obligation from the chain (scan 2026-10-27 modules, F1/F6/F10):
1077
+ * the reserve must be this market's and lend the token, 'max' comes from the obligation, and the
1078
+ * instruction rules pin the operation to that obligation, reserve and the wallet's token account.
1079
+ */
1080
+ async prepare(kind, me, mint, amount) {
771
1081
  const reserve = await this.resolveReserve(mint);
772
- const p = { wallet: me, market: this.market, reserve: reserve.reserve, amount: toDecimalString(amount, await this.decimals(mint)), memo: this.memo() };
773
- 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);
774
- return { base64, reserve };
1082
+ const obligationAddress = vanillaObligation(me, this.market, KLEND_PROGRAM);
1083
+ const [r, o] = await this.readChain([reserve.reserve, obligationAddress]);
1084
+ const onChain = decodeReserve(reserve.reserve, r ?? null);
1085
+ if (onChain.lendingMarket !== this.market) throw new KaminoError(`Reserve ${reserve.reserve} belongs to market ${onChain.lendingMarket} on chain, not ${this.market}.`);
1086
+ if (onChain.mint !== mint) throw new KaminoError(`Reserve ${reserve.reserve} lends ${onChain.mint} on chain, not ${mint}.`);
1087
+ const obligation = o ? decodeObligation(obligationAddress, o) : null;
1088
+ if (obligation && (obligation.owner !== me || obligation.lendingMarket !== this.market)) throw new KaminoError(`Obligation ${obligationAddress} is not ${me}'s on market ${this.market}.`);
1089
+ const chain = { reserve: onChain, obligation, obligationAddress };
1090
+ const value = amount === "max" ? await this.resolveMax(kind === "withdraw" ? "supplied" : "borrowed", me, mint, reserve.reserve, chain) : toAmount(amount);
1091
+ const rules = marketRules(kind, {
1092
+ me,
1093
+ market: this.market,
1094
+ obligation: obligationAddress,
1095
+ reserve: reserve.reserve,
1096
+ mint,
1097
+ ata: associatedTokenAddress(me, mint, onChain.tokenProgram),
1098
+ wsolAta: associatedTokenAddress(me, WSOL_MINT, TOKEN_PROGRAM)
1099
+ });
1100
+ return { reserve, chain, amount: value, rules };
1101
+ }
1102
+ build(kind, me, p) {
1103
+ const params = { wallet: me, market: this.market, reserve: p.reserve.reserve, amount: toDecimalString(p.amount, p.chain.reserve.decimals), memo: this.memo() };
1104
+ return kind === "deposit" ? this.api.buildLendDeposit(params) : kind === "withdraw" ? this.api.buildLendWithdraw(params) : kind === "borrow" ? this.api.buildLendBorrow(params) : this.api.buildLendRepay(params);
1105
+ }
1106
+ /** A wallet without its vanilla obligation here (on chain) pays the rent of one on its first deposit. */
1107
+ firstDepositExtra(p) {
1108
+ return p.chain.obligation ? 0n : this.firstDepositAllowance;
775
1109
  }
776
1110
  /**
777
- * A wallet without its vanilla obligation here pays the rent of one on its first deposit. Only
778
- * that obligation counts (a Multiply one does not hold a plain deposit), and an API failure is a
779
- * refusal: guessing "first deposit" would widen what the transaction may spend.
1111
+ * 'max' from the chain: what the vanilla obligation holds in, or owes to, this reserve (debt with the
1112
+ * interest the reserve has accrued). When the API reports a figure for that obligation it must agree
1113
+ * within 1%: an inflated debt or a negative deposit is refused (scan 2026-10-27 modules, F6/F10).
780
1114
  */
781
- async firstDepositExtra(me) {
782
- let obligations;
783
- try {
784
- obligations = await this.api.getUserObligations(this.market, me);
785
- } catch (e) {
786
- 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.`);
1115
+ async resolveMax(side, me, mint, reserve, c) {
1116
+ const o = c.obligation;
1117
+ const amount = !o ? 0n : side === "supplied" ? depositedLiquidity(o, c.reserve, reserve) : debtNow(o, c.reserve, reserve);
1118
+ if (amount <= 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
1119
+ const reported = await this.reported(side, me, mint, c.obligationAddress, c.reserve.decimals);
1120
+ if (reported !== void 0) {
1121
+ const legs = side === "supplied" ? o.deposits : o.borrows;
1122
+ const others = [...new Set(legs.map((l) => l.reserve).filter((r) => r !== reserve))];
1123
+ let perMint = amount;
1124
+ if (others.length) {
1125
+ const accs = await this.readChain(others);
1126
+ others.forEach((r, i) => {
1127
+ const rc = decodeReserve(r, accs[i] ?? null);
1128
+ if (rc.mint === mint) perMint += side === "supplied" ? depositedLiquidity(o, rc, r) : debtNow(o, rc, r);
1129
+ });
1130
+ }
1131
+ if (!withinTolerance(reported, perMint)) throw new KaminoError(`Kamino reports ${reported} base units ${side} in ${mint}; obligation ${c.obligationAddress} has ${perMint} on chain.`);
787
1132
  }
788
- const vanilla = vanillaObligation(me, this.market, KLEND_PROGRAM);
789
- return obligations.some((o) => o.obligation === vanilla) ? 0n : this.firstDepositAllowance;
1133
+ return amount;
790
1134
  }
791
- /** Resolve 'max' against the position's supplied / borrowed total for the mint. */
792
- async resolveMax(amount, mint, side) {
793
- if (amount !== "max") return toAmount(amount);
794
- const total = (await this.getPosition())[side][mint] ?? 0n;
795
- if (total === 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
796
- return total;
1135
+ /** The API's figure for one leg of the wallet's vanilla obligation; undefined when it reports none. */
1136
+ async reported(side, me, mint, obligation, decimals) {
1137
+ const row = (await this.api.getUserObligations(this.market, me)).find((x) => x.obligation === obligation);
1138
+ const legs = (side === "supplied" ? row?.deposits : row?.borrows)?.filter((l) => l.mint === mint) ?? [];
1139
+ if (!legs.length) return void 0;
1140
+ return legs.reduce((sum, l) => sum + fromDecimalString(l.amount, decimals), 0n);
797
1141
  }
798
1142
  async quoteSupply(o) {
799
1143
  const me = await this.me();
800
- const amount = toAmount(o.amount);
801
- const [{ base64, reserve }, extra] = await Promise.all([this.lend("deposit", me, o.token, amount), this.firstDepositExtra(me)]);
802
- const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, amount, extra));
803
- return { fee, reserve: reserve.reserve };
1144
+ const p = await this.prepare("deposit", me, o.token, o.amount);
1145
+ const base64 = await this.build("deposit", me, p);
1146
+ const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules);
1147
+ return { fee, reserve: p.reserve.reserve };
804
1148
  }
805
1149
  async supply(o) {
806
1150
  this.requireSigningAccount("supply(options)");
807
1151
  const me = await this.me();
808
- const amount = toAmount(o.amount);
809
- const [{ base64 }, extra] = await Promise.all([this.lend("deposit", me, o.token, amount), this.firstDepositExtra(me)]);
810
- return this.sendBuilt(base64, this.spendExpectation(o.token, amount, extra), "supply");
1152
+ const p = await this.prepare("deposit", me, o.token, o.amount);
1153
+ const base64 = await this.build("deposit", me, p);
1154
+ return this.sendBuilt(base64, this.spendExpectation(o.token, p.amount, this.firstDepositExtra(p)), p.rules, "supply");
811
1155
  }
812
1156
  async quoteWithdraw(o) {
813
1157
  const me = await this.me();
814
- const amount = await this.resolveMax(o.amount, o.token, "supplied");
815
- const { base64, reserve } = await this.lend("withdraw", me, o.token, amount);
816
- const expect = this.receiveExpectation(o.token, amount);
817
- const { fee } = await this.quoteBuilt(base64, expect);
818
- return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
1158
+ const p = await this.prepare("withdraw", me, o.token, o.amount);
1159
+ const base64 = await this.build("withdraw", me, p);
1160
+ const expect = this.receiveExpectation(o.token, p.amount);
1161
+ const { fee } = await this.quoteBuilt(base64, expect, p.rules);
1162
+ return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
819
1163
  }
820
1164
  async withdraw(o) {
821
1165
  this.requireSigningAccount("withdraw(options)");
822
1166
  const me = await this.me();
823
- const amount = await this.resolveMax(o.amount, o.token, "supplied");
824
- const { base64 } = await this.lend("withdraw", me, o.token, amount);
825
- return this.sendBuilt(base64, this.receiveExpectation(o.token, amount), "withdraw");
1167
+ const p = await this.prepare("withdraw", me, o.token, o.amount);
1168
+ const base64 = await this.build("withdraw", me, p);
1169
+ return this.sendBuilt(base64, this.receiveExpectation(o.token, p.amount), p.rules, "withdraw");
1170
+ }
1171
+ /** A borrow pays out at most what was asked: a bigger one is debt the user did not choose. */
1172
+ borrowExpectation(mint, amount) {
1173
+ return this.receiveExpectation(mint, amount, 0n, amount);
826
1174
  }
827
1175
  async quoteBorrow(o) {
828
1176
  const me = await this.me();
829
- const amount = toAmount(o.amount);
830
- const { base64, reserve } = await this.lend("borrow", me, o.token, amount);
831
- const expect = this.receiveExpectation(o.token, amount);
832
- const { fee } = await this.quoteBuilt(base64, expect);
833
- return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
1177
+ const p = await this.prepare("borrow", me, o.token, o.amount);
1178
+ const base64 = await this.build("borrow", me, p);
1179
+ const expect = this.borrowExpectation(o.token, p.amount);
1180
+ const { fee } = await this.quoteBuilt(base64, expect, p.rules);
1181
+ return { fee, reserve: p.reserve.reserve, minReceived: expect.tokenIn.minAmount };
834
1182
  }
835
1183
  async borrow(o) {
836
1184
  this.requireSigningAccount("borrow(options)");
837
1185
  const me = await this.me();
838
- const amount = toAmount(o.amount);
839
- const { base64 } = await this.lend("borrow", me, o.token, amount);
840
- return this.sendBuilt(base64, this.receiveExpectation(o.token, amount), "borrow");
1186
+ const p = await this.prepare("borrow", me, o.token, o.amount);
1187
+ const base64 = await this.build("borrow", me, p);
1188
+ return this.sendBuilt(base64, this.borrowExpectation(o.token, p.amount), p.rules, "borrow");
1189
+ }
1190
+ /** Interest accrues between the quote and the block: allow the slippage tolerance on top of the debt read. */
1191
+ repayExpectation(mint, amount) {
1192
+ return this.spendExpectation(mint, amount + (amount - lessBps(amount, this.slippageBps)));
841
1193
  }
842
1194
  async quoteRepay(o) {
843
1195
  const me = await this.me();
844
- const amount = await this.resolveMax(o.amount, o.token, "borrowed");
845
- const { base64, reserve } = await this.lend("repay", me, o.token, amount);
846
- const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, amount + (amount - lessBps(amount, this.slippageBps))));
847
- return { fee, reserve: reserve.reserve };
1196
+ const p = await this.prepare("repay", me, o.token, o.amount);
1197
+ const base64 = await this.build("repay", me, p);
1198
+ const { fee } = await this.quoteBuilt(base64, this.repayExpectation(o.token, p.amount), p.rules);
1199
+ return { fee, reserve: p.reserve.reserve };
848
1200
  }
849
1201
  async repay(o) {
850
1202
  this.requireSigningAccount("repay(options)");
851
1203
  const me = await this.me();
852
- const amount = await this.resolveMax(o.amount, o.token, "borrowed");
853
- const { base64 } = await this.lend("repay", me, o.token, amount);
854
- return this.sendBuilt(base64, this.spendExpectation(o.token, amount + (amount - lessBps(amount, this.slippageBps))), "repay");
1204
+ const p = await this.prepare("repay", me, o.token, o.amount);
1205
+ const base64 = await this.build("repay", me, p);
1206
+ return this.sendBuilt(base64, this.repayExpectation(o.token, p.amount), p.rules, "repay");
855
1207
  }
856
1208
  };
857
1209
  //# sourceMappingURL=index.cjs.map