@anywalletkit/protocol-lending-kamino-solana 0.1.6 → 0.2.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.d.cts CHANGED
@@ -135,7 +135,9 @@ interface KtxLend {
135
135
  declare class KaminoApi {
136
136
  private readonly endpoint;
137
137
  private readonly fetchImpl;
138
- constructor(endpoint?: string, fetchImpl?: typeof fetch);
138
+ private readonly timeoutMs;
139
+ /** `timeoutMs` bounds each call (default 15 s): a silent API must not hang a read or a write's build. */
140
+ constructor(endpoint?: string, fetchImpl?: typeof fetch, timeoutMs?: number);
139
141
  private request;
140
142
  /** Every Kamino Lend market (Main Market first). */
141
143
  listMarkets(): Promise<ApiMarket[]>;
@@ -176,6 +178,8 @@ interface KaminoBaseConfig {
176
178
  api?: string | KaminoApi;
177
179
  /** fetch implementation for the API (default global fetch). */
178
180
  fetch?: typeof fetch;
181
+ /** Per-call timeout for the API, in ms (default 15 000). Ignored when `api` is a prepared client. */
182
+ timeoutMs?: number;
179
183
  /** Tolerance on what the wallet must receive on withdrawals / borrows, in basis points (default 50). */
180
184
  slippageBps?: number;
181
185
  /** SOL the transaction may spend on rent and fees beyond the amount (default 0.01 SOL). */
@@ -247,8 +251,17 @@ declare abstract class KaminoBase<TConfig extends KaminoBaseConfig> extends Lend
247
251
  interface KaminoVaultConfig extends KaminoBaseConfig {
248
252
  /** The Earn vault (kVault) address. */
249
253
  vault: string;
250
- /** Keep the shares in the wallet instead of staking them in the vault farm (default false — staked, as the Kamino app does). */
254
+ /**
255
+ * Keep the shares in the wallet (default true). The guard then proves the shares arrive. With
256
+ * `false` they are staked in the vault farm, as the Kamino app does: they never reach the wallet,
257
+ * so the guard can only bound what leaves it, and the deposit's destination relies on the API.
258
+ */
251
259
  skipFarm?: boolean;
260
+ /**
261
+ * The mint the vault takes and pays out. The API's answer must name it; `supply` needs it here or
262
+ * as its `token`, so a changed API answer cannot make the wallet deposit another asset.
263
+ */
264
+ asset?: string;
252
265
  }
253
266
  interface KaminoVaultSupplyOptions extends Omit<SupplyOptions, 'token'> {
254
267
  token?: string;
@@ -311,7 +324,7 @@ interface VaultWithdrawQuote extends LendingQuote {
311
324
  }
312
325
  /**
313
326
  * A Kamino Earn vault (kVault) as a `LendingProtocol`: `supply` deposits the
314
- * vault's asset for shares (staked in the vault farm unless `skipFarm`),
327
+ * vault's asset for shares (kept in the wallet; staked in the vault farm with `skipFarm: false`),
315
328
  * `withdraw` redeems shares for the asset; `borrow` / `repay` reject, a vault
316
329
  * does not lend to its depositors.
317
330
  *
@@ -325,8 +338,16 @@ declare class KaminoVaultProtocolSolana extends KaminoBase<KaminoVaultConfig> {
325
338
  readonly vault: string;
326
339
  private _vault;
327
340
  constructor(account: IWalletAccountReadOnly | IWalletAccount, config: KaminoVaultConfig);
328
- /** The vault's static state (cached per instance). */
341
+ /** Shares stay in the wallet unless the app opts into the farm (round 3 review: only then can the guard prove them). */
342
+ private get skipFarm();
343
+ /**
344
+ * The vault's static state (cached per instance), checked against what the API cannot choose: it is
345
+ * this vault, on the kVault program, its shares mint is the one the program derives for it, and it
346
+ * takes the configured asset. Mint decimals come from the chain when the account can read them
347
+ * (round 3, H7: a changed `sharesMint` turned the withdraw guard into a pass for any token).
348
+ */
329
349
  protected state(): Promise<ApiVault>;
350
+ private verified;
330
351
  private info;
331
352
  /** The vault as the API describes it: asset, shares, rate, fees, TVL. */
332
353
  getVault(): Promise<VaultInfo>;
@@ -415,7 +436,11 @@ declare class KaminoMarketProtocolSolana extends KaminoBase<KaminoMarketConfig>
415
436
  /** Obligations and per-mint totals. */
416
437
  getPosition(): Promise<MarketPosition>;
417
438
  private lend;
418
- /** A wallet without an obligation here pays the rent of one on its first deposit. */
439
+ /**
440
+ * A wallet without its vanilla obligation here pays the rent of one on its first deposit. Only
441
+ * that obligation counts (a Multiply one does not hold a plain deposit), and an API failure is a
442
+ * refusal: guessing "first deposit" would widen what the transaction may spend.
443
+ */
419
444
  private firstDepositExtra;
420
445
  /** Resolve 'max' against the position's supplied / borrowed total for the mint. */
421
446
  private resolveMax;
@@ -448,4 +473,15 @@ declare const INSTRUCTION_NAMES: Readonly<Record<string, Readonly<Record<string,
448
473
  /** The instruction a Kamino program call is, from its data; undefined when unknown. */
449
474
  declare function instructionName(programId: string, data: Uint8Array): string | undefined;
450
475
 
451
- export { ADDRESS_LOOKUP_TABLE_PROGRAM, type AmountOption, type ApiLoanLeg, type ApiMarket, type ApiObligation, type ApiReserve, type ApiVault, type ApiVaultAllocation, type ApiVaultMetrics, type ApiVaultPosition, DEFAULT_FIRST_DEPOSIT_ALLOWANCE, DEFAULT_RENT_ALLOWANCE, type Expectation, FARMS_PROGRAM, INSTRUCTION_NAMES, KAMINO_API, KAMINO_PROGRAM_ALLOWLIST, KLEND_PROGRAM, KNOWN_DECIMALS, KVAULT_PROGRAM, KaminoApi, KaminoBase, type KaminoBaseConfig, KaminoError, type KaminoMarketConfig, KaminoMarketProtocolSolana, type KaminoMarketRepayOptions, type KaminoMarketWithdrawOptions, type KaminoVaultConfig, KaminoVaultProtocolSolana, type KaminoVaultSupplyOptions, type KaminoVaultWithdrawOptions, type KtxLend, type KtxVaultDeposit, type KtxVaultWithdraw, MAIN_MARKET, MEMO_PROGRAM, type MarketInfo, type MarketPosition, type MarketQuote, type ReserveInfo, SOLANA_MAINNET, type SerializedGuard, type VaultInfo, type VaultPosition, type VaultSupplyQuote, type VaultWithdrawQuote, WAD, WITHDRAW_ALL, WSOL_MINT, KaminoVaultProtocolSolana as default, divWadUp, fromDecimalString, instructionName, lessBps, mulWad, toAmount, toDecimalString, toWad };
476
+ /** `findProgramAddress`: the first off-curve `sha256(seeds ‖ bump ‖ program ‖ "ProgramDerivedAddress")`, bump 255 → 0. */
477
+ declare function findProgramAddress(seeds: readonly Uint8Array[], programId: string): string;
478
+ /**
479
+ * The vanilla (plain lending) obligation of `user` in `market`: `[tag 0, id 0, user, market,
480
+ * default key, default key]` under klend — the one `/ktx/klend/*` deposits go through. Other
481
+ * obligation kinds (Multiply, Leverage…) live at other addresses.
482
+ */
483
+ declare function vanillaObligation(user: string, market: string, klendProgram?: string): string;
484
+ /** A kVault's shares mint: `["shares", vault]` under the kVault program. */
485
+ declare function vaultSharesMint(vault: string, kvaultProgram: string): string;
486
+
487
+ export { ADDRESS_LOOKUP_TABLE_PROGRAM, type AmountOption, type ApiLoanLeg, type ApiMarket, type ApiObligation, type ApiReserve, type ApiVault, type ApiVaultAllocation, type ApiVaultMetrics, type ApiVaultPosition, DEFAULT_FIRST_DEPOSIT_ALLOWANCE, DEFAULT_RENT_ALLOWANCE, type Expectation, FARMS_PROGRAM, INSTRUCTION_NAMES, KAMINO_API, KAMINO_PROGRAM_ALLOWLIST, KLEND_PROGRAM, KNOWN_DECIMALS, KVAULT_PROGRAM, KaminoApi, KaminoBase, type KaminoBaseConfig, KaminoError, type KaminoMarketConfig, KaminoMarketProtocolSolana, type KaminoMarketRepayOptions, type KaminoMarketWithdrawOptions, type KaminoVaultConfig, KaminoVaultProtocolSolana, type KaminoVaultSupplyOptions, type KaminoVaultWithdrawOptions, type KtxLend, type KtxVaultDeposit, type KtxVaultWithdraw, MAIN_MARKET, MEMO_PROGRAM, type MarketInfo, type MarketPosition, type MarketQuote, type ReserveInfo, SOLANA_MAINNET, type SerializedGuard, type VaultInfo, type VaultPosition, type VaultSupplyQuote, type VaultWithdrawQuote, WAD, WITHDRAW_ALL, WSOL_MINT, KaminoVaultProtocolSolana as default, divWadUp, findProgramAddress, fromDecimalString, instructionName, lessBps, mulWad, toAmount, toDecimalString, toWad, vanillaObligation, vaultSharesMint };
package/dist/index.d.ts CHANGED
@@ -135,7 +135,9 @@ interface KtxLend {
135
135
  declare class KaminoApi {
136
136
  private readonly endpoint;
137
137
  private readonly fetchImpl;
138
- constructor(endpoint?: string, fetchImpl?: typeof fetch);
138
+ private readonly timeoutMs;
139
+ /** `timeoutMs` bounds each call (default 15 s): a silent API must not hang a read or a write's build. */
140
+ constructor(endpoint?: string, fetchImpl?: typeof fetch, timeoutMs?: number);
139
141
  private request;
140
142
  /** Every Kamino Lend market (Main Market first). */
141
143
  listMarkets(): Promise<ApiMarket[]>;
@@ -176,6 +178,8 @@ interface KaminoBaseConfig {
176
178
  api?: string | KaminoApi;
177
179
  /** fetch implementation for the API (default global fetch). */
178
180
  fetch?: typeof fetch;
181
+ /** Per-call timeout for the API, in ms (default 15 000). Ignored when `api` is a prepared client. */
182
+ timeoutMs?: number;
179
183
  /** Tolerance on what the wallet must receive on withdrawals / borrows, in basis points (default 50). */
180
184
  slippageBps?: number;
181
185
  /** SOL the transaction may spend on rent and fees beyond the amount (default 0.01 SOL). */
@@ -247,8 +251,17 @@ declare abstract class KaminoBase<TConfig extends KaminoBaseConfig> extends Lend
247
251
  interface KaminoVaultConfig extends KaminoBaseConfig {
248
252
  /** The Earn vault (kVault) address. */
249
253
  vault: string;
250
- /** Keep the shares in the wallet instead of staking them in the vault farm (default false — staked, as the Kamino app does). */
254
+ /**
255
+ * Keep the shares in the wallet (default true). The guard then proves the shares arrive. With
256
+ * `false` they are staked in the vault farm, as the Kamino app does: they never reach the wallet,
257
+ * so the guard can only bound what leaves it, and the deposit's destination relies on the API.
258
+ */
251
259
  skipFarm?: boolean;
260
+ /**
261
+ * The mint the vault takes and pays out. The API's answer must name it; `supply` needs it here or
262
+ * as its `token`, so a changed API answer cannot make the wallet deposit another asset.
263
+ */
264
+ asset?: string;
252
265
  }
253
266
  interface KaminoVaultSupplyOptions extends Omit<SupplyOptions, 'token'> {
254
267
  token?: string;
@@ -311,7 +324,7 @@ interface VaultWithdrawQuote extends LendingQuote {
311
324
  }
312
325
  /**
313
326
  * A Kamino Earn vault (kVault) as a `LendingProtocol`: `supply` deposits the
314
- * vault's asset for shares (staked in the vault farm unless `skipFarm`),
327
+ * vault's asset for shares (kept in the wallet; staked in the vault farm with `skipFarm: false`),
315
328
  * `withdraw` redeems shares for the asset; `borrow` / `repay` reject, a vault
316
329
  * does not lend to its depositors.
317
330
  *
@@ -325,8 +338,16 @@ declare class KaminoVaultProtocolSolana extends KaminoBase<KaminoVaultConfig> {
325
338
  readonly vault: string;
326
339
  private _vault;
327
340
  constructor(account: IWalletAccountReadOnly | IWalletAccount, config: KaminoVaultConfig);
328
- /** The vault's static state (cached per instance). */
341
+ /** Shares stay in the wallet unless the app opts into the farm (round 3 review: only then can the guard prove them). */
342
+ private get skipFarm();
343
+ /**
344
+ * The vault's static state (cached per instance), checked against what the API cannot choose: it is
345
+ * this vault, on the kVault program, its shares mint is the one the program derives for it, and it
346
+ * takes the configured asset. Mint decimals come from the chain when the account can read them
347
+ * (round 3, H7: a changed `sharesMint` turned the withdraw guard into a pass for any token).
348
+ */
329
349
  protected state(): Promise<ApiVault>;
350
+ private verified;
330
351
  private info;
331
352
  /** The vault as the API describes it: asset, shares, rate, fees, TVL. */
332
353
  getVault(): Promise<VaultInfo>;
@@ -415,7 +436,11 @@ declare class KaminoMarketProtocolSolana extends KaminoBase<KaminoMarketConfig>
415
436
  /** Obligations and per-mint totals. */
416
437
  getPosition(): Promise<MarketPosition>;
417
438
  private lend;
418
- /** A wallet without an obligation here pays the rent of one on its first deposit. */
439
+ /**
440
+ * A wallet without its vanilla obligation here pays the rent of one on its first deposit. Only
441
+ * that obligation counts (a Multiply one does not hold a plain deposit), and an API failure is a
442
+ * refusal: guessing "first deposit" would widen what the transaction may spend.
443
+ */
419
444
  private firstDepositExtra;
420
445
  /** Resolve 'max' against the position's supplied / borrowed total for the mint. */
421
446
  private resolveMax;
@@ -448,4 +473,15 @@ declare const INSTRUCTION_NAMES: Readonly<Record<string, Readonly<Record<string,
448
473
  /** The instruction a Kamino program call is, from its data; undefined when unknown. */
449
474
  declare function instructionName(programId: string, data: Uint8Array): string | undefined;
450
475
 
451
- export { ADDRESS_LOOKUP_TABLE_PROGRAM, type AmountOption, type ApiLoanLeg, type ApiMarket, type ApiObligation, type ApiReserve, type ApiVault, type ApiVaultAllocation, type ApiVaultMetrics, type ApiVaultPosition, DEFAULT_FIRST_DEPOSIT_ALLOWANCE, DEFAULT_RENT_ALLOWANCE, type Expectation, FARMS_PROGRAM, INSTRUCTION_NAMES, KAMINO_API, KAMINO_PROGRAM_ALLOWLIST, KLEND_PROGRAM, KNOWN_DECIMALS, KVAULT_PROGRAM, KaminoApi, KaminoBase, type KaminoBaseConfig, KaminoError, type KaminoMarketConfig, KaminoMarketProtocolSolana, type KaminoMarketRepayOptions, type KaminoMarketWithdrawOptions, type KaminoVaultConfig, KaminoVaultProtocolSolana, type KaminoVaultSupplyOptions, type KaminoVaultWithdrawOptions, type KtxLend, type KtxVaultDeposit, type KtxVaultWithdraw, MAIN_MARKET, MEMO_PROGRAM, type MarketInfo, type MarketPosition, type MarketQuote, type ReserveInfo, SOLANA_MAINNET, type SerializedGuard, type VaultInfo, type VaultPosition, type VaultSupplyQuote, type VaultWithdrawQuote, WAD, WITHDRAW_ALL, WSOL_MINT, KaminoVaultProtocolSolana as default, divWadUp, fromDecimalString, instructionName, lessBps, mulWad, toAmount, toDecimalString, toWad };
476
+ /** `findProgramAddress`: the first off-curve `sha256(seeds ‖ bump ‖ program ‖ "ProgramDerivedAddress")`, bump 255 → 0. */
477
+ declare function findProgramAddress(seeds: readonly Uint8Array[], programId: string): string;
478
+ /**
479
+ * The vanilla (plain lending) obligation of `user` in `market`: `[tag 0, id 0, user, market,
480
+ * default key, default key]` under klend — the one `/ktx/klend/*` deposits go through. Other
481
+ * obligation kinds (Multiply, Leverage…) live at other addresses.
482
+ */
483
+ declare function vanillaObligation(user: string, market: string, klendProgram?: string): string;
484
+ /** A kVault's shares mint: `["shares", vault]` under the kVault program. */
485
+ declare function vaultSharesMint(vault: string, kvaultProgram: string): string;
486
+
487
+ export { ADDRESS_LOOKUP_TABLE_PROGRAM, type AmountOption, type ApiLoanLeg, type ApiMarket, type ApiObligation, type ApiReserve, type ApiVault, type ApiVaultAllocation, type ApiVaultMetrics, type ApiVaultPosition, DEFAULT_FIRST_DEPOSIT_ALLOWANCE, DEFAULT_RENT_ALLOWANCE, type Expectation, FARMS_PROGRAM, INSTRUCTION_NAMES, KAMINO_API, KAMINO_PROGRAM_ALLOWLIST, KLEND_PROGRAM, KNOWN_DECIMALS, KVAULT_PROGRAM, KaminoApi, KaminoBase, type KaminoBaseConfig, KaminoError, type KaminoMarketConfig, KaminoMarketProtocolSolana, type KaminoMarketRepayOptions, type KaminoMarketWithdrawOptions, type KaminoVaultConfig, KaminoVaultProtocolSolana, type KaminoVaultSupplyOptions, type KaminoVaultWithdrawOptions, type KtxLend, type KtxVaultDeposit, type KtxVaultWithdraw, MAIN_MARKET, MEMO_PROGRAM, type MarketInfo, type MarketPosition, type MarketQuote, type ReserveInfo, SOLANA_MAINNET, type SerializedGuard, type VaultInfo, type VaultPosition, type VaultSupplyQuote, type VaultWithdrawQuote, WAD, WITHDRAW_ALL, WSOL_MINT, KaminoVaultProtocolSolana as default, divWadUp, findProgramAddress, fromDecimalString, instructionName, lessBps, mulWad, toAmount, toDecimalString, toWad, vanillaObligation, vaultSharesMint };
package/dist/index.js CHANGED
@@ -64,15 +64,32 @@ var num = (x, d = 0) => x === null || x === void 0 || x === "" ? d : Number(x);
64
64
  var big = (x) => x === null || x === void 0 ? 0n : BigInt(String(x).split(".")[0]);
65
65
  var str = (x) => x === null || x === void 0 ? "0" : String(x);
66
66
  var KaminoApi = class {
67
- constructor(endpoint = KAMINO_API, fetchImpl = fetch) {
67
+ /** `timeoutMs` bounds each call (default 15 s): a silent API must not hang a read or a write's build. */
68
+ constructor(endpoint = KAMINO_API, fetchImpl = fetch, timeoutMs = 15e3) {
68
69
  this.endpoint = endpoint;
69
70
  this.fetchImpl = fetchImpl;
71
+ this.timeoutMs = timeoutMs;
70
72
  }
71
73
  endpoint;
72
74
  fetchImpl;
75
+ timeoutMs;
73
76
  async request(path, body) {
74
- const res = await this.fetchImpl(`${this.endpoint}${path}`, body === void 0 ? { headers: { accept: "application/json" } } : { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) });
75
- const text = await res.text();
77
+ const controller = new AbortController();
78
+ const signal = controller.signal;
79
+ let timer;
80
+ const timedOut = new Promise((_, reject) => {
81
+ timer = setTimeout(() => {
82
+ controller.abort();
83
+ reject(new KaminoError(`Kamino API ${path} did not answer within ${this.timeoutMs} ms.`));
84
+ }, this.timeoutMs);
85
+ });
86
+ const call = async () => {
87
+ const res2 = await this.fetchImpl(`${this.endpoint}${path}`, body === void 0 ? { headers: { accept: "application/json" }, signal } : { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body), signal });
88
+ return { res: res2, text: await res2.text() };
89
+ };
90
+ const { res, text } = await Promise.race([call(), timedOut]).catch((e) => {
91
+ throw signal.aborted ? new KaminoError(`Kamino API ${path} did not answer within ${this.timeoutMs} ms.`) : e;
92
+ }).finally(() => clearTimeout(timer));
76
93
  let json = null;
77
94
  try {
78
95
  json = text ? JSON.parse(text) : null;
@@ -338,7 +355,7 @@ var KaminoBase = class extends LendingProtocol {
338
355
  constructor(account, config) {
339
356
  super(account, config ?? {});
340
357
  const c = this._config;
341
- this.api = c.api instanceof KaminoApi ? c.api : new KaminoApi(c.api, c.fetch);
358
+ this.api = c.api instanceof KaminoApi ? c.api : new KaminoApi(c.api, c.fetch, c.timeoutMs);
342
359
  this.slippageBps = c.slippageBps ?? 50;
343
360
  if (!Number.isInteger(this.slippageBps) || this.slippageBps < 0 || this.slippageBps > 5e3) throw new KaminoError("'slippageBps' must be an integer between 0 and 5000.");
344
361
  this.rentAllowance = c.rentAllowanceLamports === void 0 ? DEFAULT_RENT_ALLOWANCE : BigInt(c.rentAllowanceLamports);
@@ -415,6 +432,38 @@ var KaminoBase = class extends LendingProtocol {
415
432
  }
416
433
  };
417
434
 
435
+ // src/pda.ts
436
+ import { ed25519 } from "@noble/curves/ed25519.js";
437
+ import { sha256 } from "@noble/hashes/sha2.js";
438
+ import { base58 } from "@scure/base";
439
+ var PDA_MARKER = new TextEncoder().encode("ProgramDerivedAddress");
440
+ function findProgramAddress(seeds, programId) {
441
+ const program = base58.decode(programId);
442
+ for (let bump = 255; bump >= 0; bump--) {
443
+ const parts = [...seeds, Uint8Array.of(bump), program, PDA_MARKER];
444
+ const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
445
+ let o = 0;
446
+ for (const p of parts) {
447
+ buf.set(p, o);
448
+ o += p.length;
449
+ }
450
+ const hash = sha256(buf);
451
+ try {
452
+ ed25519.Point.fromBytes(hash);
453
+ } catch {
454
+ return base58.encode(hash);
455
+ }
456
+ }
457
+ throw new Error("No program address found for these seeds.");
458
+ }
459
+ function vanillaObligation(user, market, klendProgram = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD") {
460
+ const zero = new Uint8Array(32);
461
+ return findProgramAddress([Uint8Array.of(0), Uint8Array.of(0), base58.decode(user), base58.decode(market), zero, zero], klendProgram);
462
+ }
463
+ function vaultSharesMint(vault, kvaultProgram) {
464
+ return findProgramAddress([new TextEncoder().encode("shares"), base58.decode(vault)], kvaultProgram);
465
+ }
466
+
418
467
  // src/vault.ts
419
468
  var KaminoVaultProtocolSolana = class extends KaminoBase {
420
469
  vault;
@@ -424,14 +473,40 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
424
473
  if (typeof config?.vault !== "string" || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(config.vault)) throw new KaminoError("'vault' must be the Earn vault's address.");
425
474
  this.vault = config.vault;
426
475
  }
427
- /** The vault's static state (cached per instance). */
476
+ /** Shares stay in the wallet unless the app opts into the farm (round 3 review: only then can the guard prove them). */
477
+ get skipFarm() {
478
+ return this._config.skipFarm !== false;
479
+ }
480
+ /**
481
+ * The vault's static state (cached per instance), checked against what the API cannot choose: it is
482
+ * this vault, on the kVault program, its shares mint is the one the program derives for it, and it
483
+ * takes the configured asset. Mint decimals come from the chain when the account can read them
484
+ * (round 3, H7: a changed `sharesMint` turned the withdraw guard into a pass for any token).
485
+ */
428
486
  state() {
429
- if (!this._vault) this._vault = this.api.getVault(this.vault).catch((e) => {
487
+ if (!this._vault) this._vault = this.api.getVault(this.vault).then((v) => this.verified(v)).catch((e) => {
430
488
  this._vault = null;
431
489
  throw e;
432
490
  });
433
491
  return this._vault;
434
492
  }
493
+ async verified(v) {
494
+ const refuse = (what) => {
495
+ throw new KaminoError(`Kamino's answer for vault ${this.vault} does not hold up: ${what}.`);
496
+ };
497
+ if (v.address !== this.vault) refuse(`it describes ${v.address}`);
498
+ if (v.programId !== KVAULT_PROGRAM) refuse(`program ${v.programId} is not the kVault program`);
499
+ const shares = vaultSharesMint(this.vault, KVAULT_PROGRAM);
500
+ if (v.sharesMint !== shares) refuse(`shares mint ${v.sharesMint} is not the vault's (${shares})`);
501
+ if (v.tokenMint === v.sharesMint) refuse("the asset is the shares mint");
502
+ const asset = this._config.asset;
503
+ if (asset !== void 0 && v.tokenMint !== asset) refuse(`it takes ${v.tokenMint}, not the configured ${asset}`);
504
+ if (typeof this.surface().getMintInfo === "function") {
505
+ const [td, sd] = await Promise.all([this.decimals(v.tokenMint), this.decimals(v.sharesMint)]);
506
+ if (td !== v.tokenMintDecimals || sd !== v.sharesMintDecimals) refuse(`mint decimals ${v.tokenMintDecimals} / ${v.sharesMintDecimals} are ${td} / ${sd} on chain`);
507
+ }
508
+ return v;
509
+ }
435
510
  info(v, m) {
436
511
  const d = v.tokenMintDecimals;
437
512
  return {
@@ -484,15 +559,17 @@ var KaminoVaultProtocolSolana = class extends KaminoBase {
484
559
  }
485
560
  async plan(o, me) {
486
561
  const amount = toAmount(o.amount);
562
+ const token = o.token ?? this._config.asset;
563
+ if (token === void 0) throw new KaminoError(`Name the asset to deposit: pass 'token' or set 'asset' in the vault config.`);
487
564
  const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
488
- if (o.token && o.token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} takes ${symbolOf(v)} (${v.tokenMint}), not ${o.token}.`);
565
+ if (token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} takes ${symbolOf(v)} (${v.tokenMint}), not ${token}.`);
489
566
  if (amount < v.minDepositAmount) throw new KaminoError(`Deposit below the vault minimum: ${amount} < ${v.minDepositAmount} base units.`);
490
- const base64 = await this.api.buildVaultDeposit({ wallet: me, kvault: this.vault, amount: toDecimalString(amount, v.tokenMintDecimals), skipFarm: this._config.skipFarm, memo: this.memo() });
567
+ const base64 = await this.api.buildVaultDeposit({ wallet: me, kvault: this.vault, amount: toDecimalString(amount, v.tokenMintDecimals), skipFarm: this.skipFarm, memo: this.memo() });
491
568
  return { base64, v, amount, expectedShares: this.assetsToShares(amount, v, toWad(m.tokensPerShare)) };
492
569
  }
493
570
  supplyExpectation(v, amount, expectedShares) {
494
571
  const e = this.spendExpectation(v.tokenMint, amount);
495
- return this._config.skipFarm ? { ...e, tokenIn: { mint: v.sharesMint, minAmount: lessBps(expectedShares, this.slippageBps) } } : e;
572
+ return this.skipFarm ? { ...e, tokenIn: { mint: v.sharesMint, minAmount: lessBps(expectedShares, this.slippageBps) } } : e;
496
573
  }
497
574
  async quoteSupply(o) {
498
575
  const me = await this.me();
@@ -638,10 +715,20 @@ var KaminoMarketProtocolSolana = class extends KaminoBase {
638
715
  const base64 = kind === "deposit" ? await this.api.buildLendDeposit(p) : kind === "withdraw" ? await this.api.buildLendWithdraw(p) : kind === "borrow" ? await this.api.buildLendBorrow(p) : await this.api.buildLendRepay(p);
639
716
  return { base64, reserve };
640
717
  }
641
- /** A wallet without an obligation here pays the rent of one on its first deposit. */
718
+ /**
719
+ * A wallet without its vanilla obligation here pays the rent of one on its first deposit. Only
720
+ * that obligation counts (a Multiply one does not hold a plain deposit), and an API failure is a
721
+ * refusal: guessing "first deposit" would widen what the transaction may spend.
722
+ */
642
723
  async firstDepositExtra(me) {
643
- const obligations = await this.api.getUserObligations(this.market, me).catch(() => []);
644
- return obligations.length === 0 ? this.firstDepositAllowance : 0n;
724
+ let obligations;
725
+ try {
726
+ obligations = await this.api.getUserObligations(this.market, me);
727
+ } catch (e) {
728
+ throw new KaminoError(`Kamino: could not tell whether ${me} already has an obligation on market ${this.market} (${e instanceof Error ? e.message : String(e)}); try again.`);
729
+ }
730
+ const vanilla = vanillaObligation(me, this.market, KLEND_PROGRAM);
731
+ return obligations.some((o) => o.obligation === vanilla) ? 0n : this.firstDepositAllowance;
645
732
  }
646
733
  /** Resolve 'max' against the position's supplied / borrowed total for the mint. */
647
734
  async resolveMax(amount, mint, side) {
@@ -733,12 +820,15 @@ export {
733
820
  WSOL_MINT,
734
821
  KaminoVaultProtocolSolana as default,
735
822
  divWadUp,
823
+ findProgramAddress,
736
824
  fromDecimalString,
737
825
  instructionName,
738
826
  lessBps,
739
827
  mulWad,
740
828
  toAmount,
741
829
  toDecimalString,
742
- toWad
830
+ toWad,
831
+ vanillaObligation,
832
+ vaultSharesMint
743
833
  };
744
834
  //# sourceMappingURL=index.js.map