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