@anywalletkit/protocol-lending-kamino-solana 0.0.0-stage → 0.1.2
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/LICENSE +202 -0
- package/README.md +96 -2
- package/dist/index.cjs +759 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +445 -0
- package/dist/index.d.ts +445 -0
- package/dist/index.js +736 -0
- package/dist/index.js.map +1 -0
- package/module.json +11 -0
- package/package.json +64 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
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 });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
ADDRESS_LOOKUP_TABLE_PROGRAM: () => ADDRESS_LOOKUP_TABLE_PROGRAM,
|
|
24
|
+
DEFAULT_FIRST_DEPOSIT_ALLOWANCE: () => DEFAULT_FIRST_DEPOSIT_ALLOWANCE,
|
|
25
|
+
DEFAULT_RENT_ALLOWANCE: () => DEFAULT_RENT_ALLOWANCE,
|
|
26
|
+
FARMS_PROGRAM: () => FARMS_PROGRAM,
|
|
27
|
+
INSTRUCTION_NAMES: () => INSTRUCTION_NAMES,
|
|
28
|
+
KAMINO_API: () => KAMINO_API,
|
|
29
|
+
KAMINO_PROGRAM_ALLOWLIST: () => KAMINO_PROGRAM_ALLOWLIST,
|
|
30
|
+
KLEND_PROGRAM: () => KLEND_PROGRAM,
|
|
31
|
+
KNOWN_DECIMALS: () => KNOWN_DECIMALS,
|
|
32
|
+
KVAULT_PROGRAM: () => KVAULT_PROGRAM,
|
|
33
|
+
KaminoApi: () => KaminoApi,
|
|
34
|
+
KaminoBase: () => KaminoBase,
|
|
35
|
+
KaminoError: () => KaminoError,
|
|
36
|
+
KaminoMarketProtocolSolana: () => KaminoMarketProtocolSolana,
|
|
37
|
+
KaminoVaultProtocolSolana: () => KaminoVaultProtocolSolana,
|
|
38
|
+
MAIN_MARKET: () => MAIN_MARKET,
|
|
39
|
+
MEMO_PROGRAM: () => MEMO_PROGRAM,
|
|
40
|
+
SOLANA_MAINNET: () => SOLANA_MAINNET,
|
|
41
|
+
WAD: () => WAD,
|
|
42
|
+
WITHDRAW_ALL: () => WITHDRAW_ALL,
|
|
43
|
+
WSOL_MINT: () => WSOL_MINT,
|
|
44
|
+
default: () => KaminoVaultProtocolSolana,
|
|
45
|
+
divWadUp: () => divWadUp,
|
|
46
|
+
fromDecimalString: () => fromDecimalString,
|
|
47
|
+
instructionName: () => instructionName,
|
|
48
|
+
lessBps: () => lessBps,
|
|
49
|
+
mulWad: () => mulWad,
|
|
50
|
+
toAmount: () => toAmount,
|
|
51
|
+
toDecimalString: () => toDecimalString,
|
|
52
|
+
toWad: () => toWad
|
|
53
|
+
});
|
|
54
|
+
module.exports = __toCommonJS(src_exports);
|
|
55
|
+
|
|
56
|
+
// src/vault.ts
|
|
57
|
+
var import_core2 = require("@anywalletkit/core");
|
|
58
|
+
|
|
59
|
+
// src/errors.ts
|
|
60
|
+
var KaminoError = class extends Error {
|
|
61
|
+
code;
|
|
62
|
+
constructor(message, code) {
|
|
63
|
+
super(message);
|
|
64
|
+
this.name = "KaminoError";
|
|
65
|
+
this.code = code;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// src/amounts.ts
|
|
70
|
+
function toAmount(amount) {
|
|
71
|
+
if (typeof amount !== "bigint" && !(typeof amount === "number" && Number.isSafeInteger(amount))) {
|
|
72
|
+
throw new KaminoError("'amount' must be a bigint or a safe integer (in base units), or 'max' where allowed.");
|
|
73
|
+
}
|
|
74
|
+
const value = BigInt(amount);
|
|
75
|
+
if (value <= 0n) throw new KaminoError("'amount' should be greater than zero.");
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
function toDecimalString(amount, decimals) {
|
|
79
|
+
const s = amount.toString().padStart(decimals + 1, "0");
|
|
80
|
+
const whole = s.slice(0, s.length - decimals), frac = s.slice(s.length - decimals).replace(/0+$/, "");
|
|
81
|
+
return frac ? `${whole}.${frac}` : whole;
|
|
82
|
+
}
|
|
83
|
+
function fromDecimalString(value, decimals) {
|
|
84
|
+
const s = String(value).trim();
|
|
85
|
+
const m = /^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
|
|
86
|
+
if (!m) throw new KaminoError(`Not a decimal number: ${s}`);
|
|
87
|
+
let [, sign, whole = "", frac = "", exp] = m;
|
|
88
|
+
if (exp) {
|
|
89
|
+
const e = Number(exp);
|
|
90
|
+
const digits = whole + frac;
|
|
91
|
+
let point = whole.length + e;
|
|
92
|
+
if (point <= 0) {
|
|
93
|
+
whole = "0";
|
|
94
|
+
frac = "0".repeat(-point) + digits;
|
|
95
|
+
} else if (point >= digits.length) {
|
|
96
|
+
whole = digits + "0".repeat(point - digits.length);
|
|
97
|
+
frac = "";
|
|
98
|
+
} else {
|
|
99
|
+
whole = digits.slice(0, point);
|
|
100
|
+
frac = digits.slice(point);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const scaled = (whole || "0") + (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
104
|
+
const out = BigInt(scaled.replace(/^0+(?=\d)/, ""));
|
|
105
|
+
return sign ? -out : out;
|
|
106
|
+
}
|
|
107
|
+
var WAD = 10n ** 18n;
|
|
108
|
+
var toWad = (value) => fromDecimalString(value, 18);
|
|
109
|
+
var mulWad = (a, wad) => a * wad / WAD;
|
|
110
|
+
var divWadUp = (a, wad) => wad === 0n ? 0n : (a * WAD + wad - 1n) / wad;
|
|
111
|
+
var lessBps = (amount, bps) => amount * BigInt(1e4 - bps) / 10000n;
|
|
112
|
+
|
|
113
|
+
// src/api.ts
|
|
114
|
+
var KAMINO_API = "https://api.kamino.finance";
|
|
115
|
+
var MAIN_MARKET = "7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF";
|
|
116
|
+
var WITHDRAW_ALL = "18446744073709551615";
|
|
117
|
+
var pct = (x) => x === null || x === void 0 ? 0 : Number(x) * 100;
|
|
118
|
+
var num = (x, d = 0) => x === null || x === void 0 || x === "" ? d : Number(x);
|
|
119
|
+
var big = (x) => x === null || x === void 0 ? 0n : BigInt(String(x).split(".")[0]);
|
|
120
|
+
var str = (x) => x === null || x === void 0 ? "0" : String(x);
|
|
121
|
+
var KaminoApi = class {
|
|
122
|
+
constructor(endpoint = KAMINO_API, fetchImpl = fetch) {
|
|
123
|
+
this.endpoint = endpoint;
|
|
124
|
+
this.fetchImpl = fetchImpl;
|
|
125
|
+
}
|
|
126
|
+
endpoint;
|
|
127
|
+
fetchImpl;
|
|
128
|
+
async request(path, body) {
|
|
129
|
+
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) });
|
|
130
|
+
const text = await res.text();
|
|
131
|
+
let json = null;
|
|
132
|
+
try {
|
|
133
|
+
json = text ? JSON.parse(text) : null;
|
|
134
|
+
} catch {
|
|
135
|
+
}
|
|
136
|
+
if (!res.ok) {
|
|
137
|
+
const e = json ?? {};
|
|
138
|
+
throw new KaminoError(`Kamino API ${res.status} ${path}: ${e.message ?? e.error ?? e.metadata ?? text.slice(0, 200)}`, e.code);
|
|
139
|
+
}
|
|
140
|
+
return json;
|
|
141
|
+
}
|
|
142
|
+
/** Every Kamino Lend market (Main Market first). */
|
|
143
|
+
async listMarkets() {
|
|
144
|
+
const rows = await this.request("/v2/kamino-market");
|
|
145
|
+
return rows.map((r) => ({
|
|
146
|
+
lendingMarket: String(r.lendingMarket),
|
|
147
|
+
name: String(r.name ?? ""),
|
|
148
|
+
description: String(r.description ?? ""),
|
|
149
|
+
isPrimary: !!r.isPrimary,
|
|
150
|
+
isCurated: !!r.isCurated,
|
|
151
|
+
lookupTable: r.lookupTable ? String(r.lookupTable) : null
|
|
152
|
+
})).sort((a, b) => Number(b.isPrimary) - Number(a.isPrimary));
|
|
153
|
+
}
|
|
154
|
+
/** A market's reserves with live rates. */
|
|
155
|
+
async getReserves(market) {
|
|
156
|
+
const rows = await this.request(`/kamino-market/${market}/reserves/metrics`);
|
|
157
|
+
return rows.map((r) => ({
|
|
158
|
+
reserve: String(r.reserve),
|
|
159
|
+
symbol: String(r.liquidityToken ?? ""),
|
|
160
|
+
mint: String(r.liquidityTokenMint),
|
|
161
|
+
maxLtv: num(r.maxLtv),
|
|
162
|
+
supplyApy: pct(r.supplyApy),
|
|
163
|
+
borrowApy: pct(r.borrowApy),
|
|
164
|
+
totalSupply: str(r.totalSupply),
|
|
165
|
+
totalBorrow: str(r.totalBorrow),
|
|
166
|
+
totalSupplyUsd: num(r.totalSupplyUsd),
|
|
167
|
+
totalBorrowUsd: num(r.totalBorrowUsd)
|
|
168
|
+
}));
|
|
169
|
+
}
|
|
170
|
+
vault(row) {
|
|
171
|
+
const s = row.state ?? {};
|
|
172
|
+
const alloc = Array.isArray(s.vaultAllocationStrategy) ? s.vaultAllocationStrategy : [];
|
|
173
|
+
return {
|
|
174
|
+
address: String(row.address),
|
|
175
|
+
programId: String(row.programId ?? ""),
|
|
176
|
+
name: String(s.name ?? ""),
|
|
177
|
+
tokenMint: String(s.tokenMint),
|
|
178
|
+
tokenMintDecimals: num(s.tokenMintDecimals),
|
|
179
|
+
tokenProgram: String(s.tokenProgram ?? ""),
|
|
180
|
+
sharesMint: String(s.sharesMint),
|
|
181
|
+
sharesMintDecimals: num(s.sharesMintDecimals),
|
|
182
|
+
tokenAvailable: big(s.tokenAvailable),
|
|
183
|
+
sharesIssued: big(s.sharesIssued),
|
|
184
|
+
minDepositAmount: big(s.minDepositAmount),
|
|
185
|
+
minWithdrawAmount: big(s.minWithdrawAmount),
|
|
186
|
+
performanceFeeBps: num(s.performanceFeeBps),
|
|
187
|
+
managementFeeBps: num(s.managementFeeBps),
|
|
188
|
+
vaultFarm: s.vaultFarm && String(s.vaultFarm) !== "11111111111111111111111111111111" ? String(s.vaultFarm) : null,
|
|
189
|
+
vaultLookupTable: s.vaultLookupTable ? String(s.vaultLookupTable) : null,
|
|
190
|
+
allocations: alloc.filter((a) => num(a.targetAllocationWeight) > 0 || big(a.ctokenAllocation) > 1n).map((a) => ({ reserve: String(a.reserve), targetAllocationWeight: num(a.targetAllocationWeight), tokenAllocationCap: big(a.tokenAllocationCap) }))
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** Every Earn vault (kVault) on the mainnet program. */
|
|
194
|
+
async listVaults() {
|
|
195
|
+
const rows = await this.request("/kvaults/vaults");
|
|
196
|
+
return rows.map((r) => this.vault(r));
|
|
197
|
+
}
|
|
198
|
+
async getVault(vault) {
|
|
199
|
+
return this.vault(await this.request(`/kvaults/vaults/${vault}`));
|
|
200
|
+
}
|
|
201
|
+
async getVaultMetrics(vault) {
|
|
202
|
+
const m = await this.request(`/kvaults/vaults/${vault}/metrics`);
|
|
203
|
+
return {
|
|
204
|
+
apy: pct(m.apy),
|
|
205
|
+
apy24h: pct(m.apy24h),
|
|
206
|
+
apy7d: pct(m.apy7d),
|
|
207
|
+
apy30d: pct(m.apy30d),
|
|
208
|
+
apyActual: pct(m.apyActual),
|
|
209
|
+
apyFarmRewards: pct(m.apyFarmRewards),
|
|
210
|
+
tokenPrice: str(m.tokenPrice),
|
|
211
|
+
sharePrice: str(m.sharePrice),
|
|
212
|
+
tokensPerShare: str(m.tokensPerShare),
|
|
213
|
+
tokensAvailable: str(m.tokensAvailable),
|
|
214
|
+
tokensInvested: str(m.tokensInvested),
|
|
215
|
+
tokensInvestedUsd: str(m.tokensInvestedUsd),
|
|
216
|
+
sharesIssued: str(m.sharesIssued),
|
|
217
|
+
numberOfHolders: num(m.numberOfHolders)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** The user's shares in one vault; a user the vault has never seen is a zero position. */
|
|
221
|
+
async getVaultPosition(user, vault) {
|
|
222
|
+
try {
|
|
223
|
+
const p = await this.request(`/kvaults/users/${user}/positions/${vault}`);
|
|
224
|
+
return { vaultAddress: String(p.vaultAddress ?? vault), stakedShares: str(p.stakedShares), unstakedShares: str(p.unstakedShares), totalShares: str(p.totalShares) };
|
|
225
|
+
} catch (e) {
|
|
226
|
+
if (e instanceof KaminoError && /\b404\b/.test(e.message)) return { vaultAddress: vault, stakedShares: "0", unstakedShares: "0", totalShares: "0" };
|
|
227
|
+
throw e;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
async listVaultPositions(user) {
|
|
231
|
+
const rows = await this.request(`/kvaults/users/${user}/positions`);
|
|
232
|
+
return rows.map((p) => ({ vaultAddress: String(p.vaultAddress), stakedShares: str(p.stakedShares), unstakedShares: str(p.unstakedShares), totalShares: str(p.totalShares) }));
|
|
233
|
+
}
|
|
234
|
+
obligation(row, market) {
|
|
235
|
+
const info = row.loanInfo ?? row;
|
|
236
|
+
const legs = (x) => (Array.isArray(x) ? x : []).map((l) => ({
|
|
237
|
+
mint: String(l.tokenMint ?? l.mint ?? ""),
|
|
238
|
+
symbol: String(l.tokenName ?? l.symbol ?? ""),
|
|
239
|
+
amount: str(l.tokenAmount ?? l.amount),
|
|
240
|
+
valueUsd: str(l.tokenValue ?? l.valueUsd)
|
|
241
|
+
}));
|
|
242
|
+
const coll = info.collateral ?? {}, debt = info.debt ?? {};
|
|
243
|
+
return {
|
|
244
|
+
obligation: String(row.loanId ?? row.obligation ?? row.address ?? ""),
|
|
245
|
+
market: String(row.marketId ?? market),
|
|
246
|
+
user: String(row.user ?? ""),
|
|
247
|
+
elevationGroup: num(row.elevationGroup),
|
|
248
|
+
deposits: legs(coll.deposits ?? row.deposits),
|
|
249
|
+
borrows: legs(debt.borrows ?? row.borrows),
|
|
250
|
+
currentLtv: num(info.currentLtv),
|
|
251
|
+
maxLtv: info.maxLtv === null || info.maxLtv === void 0 ? null : num(info.maxLtv),
|
|
252
|
+
liquidationLtv: num(info.liquidationLtv),
|
|
253
|
+
raw: row
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** The user's obligations (loans) in a market. */
|
|
257
|
+
async getUserObligations(market, user) {
|
|
258
|
+
const rows = await this.request(`/kamino-market/${market}/users/${user}/obligations`);
|
|
259
|
+
const list = Array.isArray(rows) ? rows : rows && typeof rows === "object" && Array.isArray(rows.obligations) ? rows.obligations : [];
|
|
260
|
+
return list.map((r) => this.obligation(r, market));
|
|
261
|
+
}
|
|
262
|
+
// ---- transaction builder --------------------------------------------------
|
|
263
|
+
async ktx(path, body) {
|
|
264
|
+
const r = await this.request(path, body);
|
|
265
|
+
if (!r?.transaction) throw new KaminoError(`Kamino API ${path} returned no transaction.`);
|
|
266
|
+
return r.transaction;
|
|
267
|
+
}
|
|
268
|
+
/** Base64 unsigned v0 transaction: deposit `amount` (decimal, token units) into an Earn vault. */
|
|
269
|
+
buildVaultDeposit(p) {
|
|
270
|
+
return this.ktx("/ktx/kvault/deposit", strip(p));
|
|
271
|
+
}
|
|
272
|
+
/** Base64 unsigned v0 transaction: redeem `amount` SHARES (decimal) — {@link WITHDRAW_ALL} for every share. */
|
|
273
|
+
buildVaultWithdraw(p) {
|
|
274
|
+
return this.ktx("/ktx/kvault/withdraw", strip(p));
|
|
275
|
+
}
|
|
276
|
+
buildLendDeposit(p) {
|
|
277
|
+
return this.ktx("/ktx/klend/deposit", strip(p));
|
|
278
|
+
}
|
|
279
|
+
buildLendWithdraw(p) {
|
|
280
|
+
return this.ktx("/ktx/klend/withdraw", strip(p));
|
|
281
|
+
}
|
|
282
|
+
buildLendBorrow(p) {
|
|
283
|
+
return this.ktx("/ktx/klend/borrow", strip(p));
|
|
284
|
+
}
|
|
285
|
+
buildLendRepay(p) {
|
|
286
|
+
return this.ktx("/ktx/klend/repay", strip(p));
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
function strip(o) {
|
|
290
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// src/base.ts
|
|
294
|
+
var import_core = require("@anywalletkit/core");
|
|
295
|
+
|
|
296
|
+
// src/programs.ts
|
|
297
|
+
var KLEND_PROGRAM = "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD";
|
|
298
|
+
var KVAULT_PROGRAM = "KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd";
|
|
299
|
+
var FARMS_PROGRAM = "FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr";
|
|
300
|
+
var ADDRESS_LOOKUP_TABLE_PROGRAM = "AddressLookupTab1e1111111111111111111111111";
|
|
301
|
+
var MEMO_PROGRAM = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
|
|
302
|
+
var SYSTEM_PROGRAM = "11111111111111111111111111111111";
|
|
303
|
+
var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
304
|
+
var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
305
|
+
var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
306
|
+
var COMPUTE_BUDGET_PROGRAM = "ComputeBudget111111111111111111111111111111";
|
|
307
|
+
var KAMINO_PROGRAM_ALLOWLIST = Object.freeze([
|
|
308
|
+
SYSTEM_PROGRAM,
|
|
309
|
+
TOKEN_PROGRAM,
|
|
310
|
+
TOKEN_2022_PROGRAM,
|
|
311
|
+
ASSOCIATED_TOKEN_PROGRAM,
|
|
312
|
+
COMPUTE_BUDGET_PROGRAM,
|
|
313
|
+
MEMO_PROGRAM,
|
|
314
|
+
KLEND_PROGRAM,
|
|
315
|
+
KVAULT_PROGRAM,
|
|
316
|
+
FARMS_PROGRAM,
|
|
317
|
+
ADDRESS_LOOKUP_TABLE_PROGRAM
|
|
318
|
+
]);
|
|
319
|
+
var INSTRUCTION_NAMES = Object.freeze({
|
|
320
|
+
[KLEND_PROGRAM]: Object.freeze({
|
|
321
|
+
"75a9b045c5170fa2": "initUserMetadata",
|
|
322
|
+
"fb0ae74c1b0b9f60": "initObligation",
|
|
323
|
+
"883f0fbad398a8a4": "initObligationFarmsForReserve",
|
|
324
|
+
"8c90fd150a4af803": "refreshObligationFarmsForReserve",
|
|
325
|
+
"02da8aeb4fc91966": "refreshReserve",
|
|
326
|
+
"218493e497c04859": "refreshObligation",
|
|
327
|
+
"d8e0bf1bcc9766af": "depositReserveLiquidityAndObligationCollateralV2",
|
|
328
|
+
"eb34779895c51407": "withdrawObligationCollateralAndRedeemReserveCollateralV2",
|
|
329
|
+
"a1808ff5abc7c206": "borrowObligationLiquidityV2",
|
|
330
|
+
"74aed54cb435d290": "repayObligationLiquidityV2",
|
|
331
|
+
"a9c91e7e06cd6644": "depositReserveLiquidity",
|
|
332
|
+
"ea75b57db98edc1d": "redeemReserveCollateral",
|
|
333
|
+
"2477fb8122f00793": "requestElevationGroup"
|
|
334
|
+
}),
|
|
335
|
+
[KVAULT_PROGRAM]: Object.freeze({
|
|
336
|
+
"f223c68952e1f2b6": "deposit",
|
|
337
|
+
"b712469c946da122": "withdraw",
|
|
338
|
+
"1383709baadc2239": "withdrawFromAvailable",
|
|
339
|
+
"0df5b467feb67904": "invest"
|
|
340
|
+
}),
|
|
341
|
+
[FARMS_PROGRAM]: Object.freeze({
|
|
342
|
+
"6f11b9fa3c7a26fe": "initializeUser",
|
|
343
|
+
"ceb0ca12c8d1b36c": "stake",
|
|
344
|
+
"5a5f6b2acd7c32e1": "unstake",
|
|
345
|
+
"2466bb31dc248443": "withdrawUnstakedDeposits",
|
|
346
|
+
"44c8e4e9b820e2bc": "harvestReward"
|
|
347
|
+
})
|
|
348
|
+
});
|
|
349
|
+
function instructionName(programId, data) {
|
|
350
|
+
const table = INSTRUCTION_NAMES[programId];
|
|
351
|
+
if (!table || data.length < 8) return void 0;
|
|
352
|
+
const hex = Array.from(data.subarray(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
353
|
+
return table[hex];
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// src/base.ts
|
|
357
|
+
var SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
358
|
+
var WSOL_MINT = "So11111111111111111111111111111111111111112";
|
|
359
|
+
var DEFAULT_RENT_ALLOWANCE = 10000000n;
|
|
360
|
+
var DEFAULT_FIRST_DEPOSIT_ALLOWANCE = 45000000n;
|
|
361
|
+
var KNOWN_DECIMALS = Object.freeze({
|
|
362
|
+
[WSOL_MINT]: 9,
|
|
363
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: 6,
|
|
364
|
+
// USDC
|
|
365
|
+
Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: 6,
|
|
366
|
+
// USDT
|
|
367
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": 6,
|
|
368
|
+
// PYUSD
|
|
369
|
+
"2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": 6,
|
|
370
|
+
// USDG
|
|
371
|
+
"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs": 8,
|
|
372
|
+
// ETH (Wormhole)
|
|
373
|
+
"3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh": 8,
|
|
374
|
+
// WBTC
|
|
375
|
+
cbbtcf3aa214zXHbiAZQwf4122FBYbraNdFqgw4iMij: 8,
|
|
376
|
+
// cbBTC
|
|
377
|
+
J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn: 9,
|
|
378
|
+
// JitoSOL
|
|
379
|
+
mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So: 9,
|
|
380
|
+
// mSOL
|
|
381
|
+
jupSoLaHXQiZZTSfEWMTRRgpnyFm8f6sZdosWBjx93v: 9,
|
|
382
|
+
// jupSOL
|
|
383
|
+
bSo13r4TkiE4KumL71LsHTPpL2euBYLFx6h9HP3piy1: 9,
|
|
384
|
+
// bSOL
|
|
385
|
+
KMNoPBQmDoVB7cQgqu5bufCPRChRMj3P4MaE8DxGZCz: 6
|
|
386
|
+
// KMNO
|
|
387
|
+
});
|
|
388
|
+
var KaminoBase = class extends import_core.LendingProtocol {
|
|
389
|
+
api;
|
|
390
|
+
slippageBps;
|
|
391
|
+
rentAllowance;
|
|
392
|
+
_decimals = /* @__PURE__ */ new Map();
|
|
393
|
+
constructor(account, config) {
|
|
394
|
+
super(account, config ?? {});
|
|
395
|
+
const c = this._config;
|
|
396
|
+
this.api = c.api instanceof KaminoApi ? c.api : new KaminoApi(c.api, c.fetch);
|
|
397
|
+
this.slippageBps = c.slippageBps ?? 50;
|
|
398
|
+
if (!Number.isInteger(this.slippageBps) || this.slippageBps < 0 || this.slippageBps > 5e3) throw new KaminoError("'slippageBps' must be an integer between 0 and 5000.");
|
|
399
|
+
this.rentAllowance = c.rentAllowanceLamports === void 0 ? DEFAULT_RENT_ALLOWANCE : BigInt(c.rentAllowanceLamports);
|
|
400
|
+
const chain = account?.chain;
|
|
401
|
+
if (chain && chain.startsWith("solana:") && chain !== SOLANA_MAINNET) throw new KaminoError(`Kamino lives on Solana mainnet; the account is on ${chain}.`);
|
|
402
|
+
}
|
|
403
|
+
/** Refuse anything that is not a mainnet Solana account before an API call is made in its name. */
|
|
404
|
+
requireSolana() {
|
|
405
|
+
const chain = this._account?.chain;
|
|
406
|
+
if (chain && chain !== SOLANA_MAINNET) throw new KaminoError(`Kamino needs a Solana mainnet account (${SOLANA_MAINNET}); this one is on ${chain}.`);
|
|
407
|
+
}
|
|
408
|
+
surface() {
|
|
409
|
+
return this._account;
|
|
410
|
+
}
|
|
411
|
+
async me() {
|
|
412
|
+
this.requireSolana();
|
|
413
|
+
return this._account.getAddress();
|
|
414
|
+
}
|
|
415
|
+
/** Mint decimals: the account reads the mint when it can; well-known mints need no RPC. */
|
|
416
|
+
decimals(mint) {
|
|
417
|
+
let p = this._decimals.get(mint);
|
|
418
|
+
if (!p) {
|
|
419
|
+
p = (async () => {
|
|
420
|
+
const known = KNOWN_DECIMALS[mint];
|
|
421
|
+
const s = this.surface();
|
|
422
|
+
if (typeof s.getMintInfo === "function") {
|
|
423
|
+
try {
|
|
424
|
+
return (await s.getMintInfo(mint)).decimals;
|
|
425
|
+
} catch (e) {
|
|
426
|
+
if (known !== void 0) return known;
|
|
427
|
+
throw e;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (known !== void 0) return known;
|
|
431
|
+
throw new KaminoError(`Cannot read the decimals of ${mint}: the account has no RPC and the mint is not a known one.`);
|
|
432
|
+
})().catch((e) => {
|
|
433
|
+
this._decimals.delete(mint);
|
|
434
|
+
throw e;
|
|
435
|
+
});
|
|
436
|
+
this._decimals.set(mint, p);
|
|
437
|
+
}
|
|
438
|
+
return p;
|
|
439
|
+
}
|
|
440
|
+
guard(expect) {
|
|
441
|
+
return { programAllowlist: KAMINO_PROGRAM_ALLOWLIST, expect };
|
|
442
|
+
}
|
|
443
|
+
/** The wallet sends `amount` of `mint` (SOL counts on the lamport side) and may lose rent on top. */
|
|
444
|
+
spendExpectation(mint, amount, extraLamports = 0n) {
|
|
445
|
+
const rent = this.rentAllowance + extraLamports;
|
|
446
|
+
return mint === WSOL_MINT ? { maxLamportsOut: amount + rent } : { maxLamportsOut: rent, maxTokenOut: { mint, amount } };
|
|
447
|
+
}
|
|
448
|
+
/** The wallet must receive at least `expected × (1 − slippage)` of `mint`; rent is the only SOL it may lose. */
|
|
449
|
+
receiveExpectation(mint, expected, extraLamports = 0n) {
|
|
450
|
+
const min = expected * BigInt(1e4 - this.slippageBps) / 10000n;
|
|
451
|
+
return { maxLamportsOut: this.rentAllowance + extraLamports, tokenIn: { mint, minAmount: min } };
|
|
452
|
+
}
|
|
453
|
+
/** Simulate the built transaction through the account's guard and return its fee; nothing is signed. */
|
|
454
|
+
async quoteBuilt(base64, expect) {
|
|
455
|
+
const s = this.surface();
|
|
456
|
+
if (typeof s.checkSerialized !== "function") throw new KaminoError("Quoting a Kamino transaction needs a @anywalletkit/wallet-solana account (checkSerialized).");
|
|
457
|
+
const check = await s.checkSerialized(base64, this.guard(expect));
|
|
458
|
+
return { fee: BigInt(check.quote.fee) };
|
|
459
|
+
}
|
|
460
|
+
/** Guard, sign and broadcast the built transaction; the account refuses before signing if the proof fails. */
|
|
461
|
+
async sendBuilt(base64, expect, method) {
|
|
462
|
+
const account = this.requireSigningAccount(`${method}(options)`);
|
|
463
|
+
if (typeof account.sendSerialized !== "function") throw new KaminoError(`${method}() needs a @anywalletkit/wallet-solana account (sendSerialized).`);
|
|
464
|
+
const sent = await account.sendSerialized(base64, this.guard(expect));
|
|
465
|
+
if (!sent?.hash) throw new KaminoError("The account returned no transaction signature.");
|
|
466
|
+
return { hash: sent.hash, fee: BigInt(sent.fee ?? 0) };
|
|
467
|
+
}
|
|
468
|
+
memo() {
|
|
469
|
+
return this._config.memo;
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
// src/vault.ts
|
|
474
|
+
var KaminoVaultProtocolSolana = class extends KaminoBase {
|
|
475
|
+
vault;
|
|
476
|
+
_vault = null;
|
|
477
|
+
constructor(account, config) {
|
|
478
|
+
super(account, config);
|
|
479
|
+
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.");
|
|
480
|
+
this.vault = config.vault;
|
|
481
|
+
}
|
|
482
|
+
/** The vault's static state (cached per instance). */
|
|
483
|
+
state() {
|
|
484
|
+
if (!this._vault) this._vault = this.api.getVault(this.vault).catch((e) => {
|
|
485
|
+
this._vault = null;
|
|
486
|
+
throw e;
|
|
487
|
+
});
|
|
488
|
+
return this._vault;
|
|
489
|
+
}
|
|
490
|
+
info(v, m) {
|
|
491
|
+
const d = v.tokenMintDecimals;
|
|
492
|
+
return {
|
|
493
|
+
vault: v.address,
|
|
494
|
+
programId: v.programId,
|
|
495
|
+
name: v.name,
|
|
496
|
+
asset: { mint: v.tokenMint, decimals: d, symbol: symbolOf(v) },
|
|
497
|
+
shares: { mint: v.sharesMint, decimals: v.sharesMintDecimals },
|
|
498
|
+
totalAssets: fromDecimalString(m.tokensAvailable, d) + fromDecimalString(m.tokensInvested, d),
|
|
499
|
+
sharesIssued: fromDecimalString(m.sharesIssued, v.sharesMintDecimals),
|
|
500
|
+
tokensPerShareWad: toWad(m.tokensPerShare),
|
|
501
|
+
tokenPriceUsd: Number(m.tokenPrice),
|
|
502
|
+
sharePriceUsd: Number(m.sharePrice),
|
|
503
|
+
apy: m.apy,
|
|
504
|
+
apy7d: m.apy7d,
|
|
505
|
+
apy30d: m.apy30d,
|
|
506
|
+
apyFarmRewards: m.apyFarmRewards,
|
|
507
|
+
fees: { performanceBps: v.performanceFeeBps, managementBps: v.managementFeeBps },
|
|
508
|
+
minDeposit: v.minDepositAmount,
|
|
509
|
+
minWithdraw: v.minWithdrawAmount,
|
|
510
|
+
holders: m.numberOfHolders,
|
|
511
|
+
farm: v.vaultFarm,
|
|
512
|
+
allocations: v.allocations
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
/** The vault as the API describes it: asset, shares, rate, fees, TVL. */
|
|
516
|
+
async getVault() {
|
|
517
|
+
const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
|
|
518
|
+
return this.info(v, m);
|
|
519
|
+
}
|
|
520
|
+
/** Net APY in percent. */
|
|
521
|
+
async getApy() {
|
|
522
|
+
return (await this.api.getVaultMetrics(this.vault)).apy;
|
|
523
|
+
}
|
|
524
|
+
/** Shares (wallet + farm) and what they are worth now. */
|
|
525
|
+
async getPosition() {
|
|
526
|
+
const me = await this.me();
|
|
527
|
+
const [v, m, p] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault), this.api.getVaultPosition(me, this.vault)]);
|
|
528
|
+
const sd = v.sharesMintDecimals;
|
|
529
|
+
const unstakedShares = fromDecimalString(p.unstakedShares, sd), stakedShares = fromDecimalString(p.stakedShares, sd);
|
|
530
|
+
const shares = fromDecimalString(p.totalShares, sd) || unstakedShares + stakedShares;
|
|
531
|
+
return { unstakedShares, stakedShares, shares, assets: this.sharesToAssets(shares, v, toWad(m.tokensPerShare)) };
|
|
532
|
+
}
|
|
533
|
+
/** shares (share units) × tokensPerShare → asset units; decimals may differ between the two mints. */
|
|
534
|
+
sharesToAssets(shares, v, tokensPerShareWad) {
|
|
535
|
+
return rescale(mulWad(shares, tokensPerShareWad), v.sharesMintDecimals, v.tokenMintDecimals);
|
|
536
|
+
}
|
|
537
|
+
assetsToShares(assets, v, tokensPerShareWad) {
|
|
538
|
+
return rescale(divWadUp(assets, tokensPerShareWad), v.tokenMintDecimals, v.sharesMintDecimals);
|
|
539
|
+
}
|
|
540
|
+
async plan(o, me) {
|
|
541
|
+
const amount = toAmount(o.amount);
|
|
542
|
+
const [v, m] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault)]);
|
|
543
|
+
if (o.token && o.token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} takes ${symbolOf(v)} (${v.tokenMint}), not ${o.token}.`);
|
|
544
|
+
if (amount < v.minDepositAmount) throw new KaminoError(`Deposit below the vault minimum: ${amount} < ${v.minDepositAmount} base units.`);
|
|
545
|
+
const base64 = await this.api.buildVaultDeposit({ wallet: me, kvault: this.vault, amount: toDecimalString(amount, v.tokenMintDecimals), skipFarm: this._config.skipFarm, memo: this.memo() });
|
|
546
|
+
return { base64, v, amount, expectedShares: this.assetsToShares(amount, v, toWad(m.tokensPerShare)) };
|
|
547
|
+
}
|
|
548
|
+
supplyExpectation(v, amount, expectedShares) {
|
|
549
|
+
const e = this.spendExpectation(v.tokenMint, amount);
|
|
550
|
+
return this._config.skipFarm ? { ...e, tokenIn: { mint: v.sharesMint, minAmount: lessBps(expectedShares, this.slippageBps) } } : e;
|
|
551
|
+
}
|
|
552
|
+
async quoteSupply(o) {
|
|
553
|
+
const me = await this.me();
|
|
554
|
+
const { base64, v, amount, expectedShares } = await this.plan(o, me);
|
|
555
|
+
const { fee } = await this.quoteBuilt(base64, this.supplyExpectation(v, amount, expectedShares));
|
|
556
|
+
return { fee, expectedShares };
|
|
557
|
+
}
|
|
558
|
+
async supply(o) {
|
|
559
|
+
this.requireSigningAccount("supply(options)");
|
|
560
|
+
const me = await this.me();
|
|
561
|
+
const { base64, v, amount, expectedShares } = await this.plan(o, me);
|
|
562
|
+
return this.sendBuilt(base64, this.supplyExpectation(v, amount, expectedShares), "supply");
|
|
563
|
+
}
|
|
564
|
+
async planWithdraw(o, me) {
|
|
565
|
+
const [v, m, position] = await Promise.all([this.state(), this.api.getVaultMetrics(this.vault), this.getPosition()]);
|
|
566
|
+
if (o.token && o.token !== v.tokenMint) throw new KaminoError(`Vault ${this.vault} pays out ${symbolOf(v)} (${v.tokenMint}), not ${o.token}.`);
|
|
567
|
+
if (position.shares === 0n) throw new KaminoError(`No position in vault ${this.vault} for ${me}.`);
|
|
568
|
+
const tps = toWad(m.tokensPerShare);
|
|
569
|
+
let shares, amountArg;
|
|
570
|
+
if (o.amount === "max") {
|
|
571
|
+
shares = position.shares;
|
|
572
|
+
amountArg = WITHDRAW_ALL;
|
|
573
|
+
} else {
|
|
574
|
+
const assets = toAmount(o.amount);
|
|
575
|
+
shares = this.assetsToShares(assets, v, tps);
|
|
576
|
+
if (shares > position.shares) throw new KaminoError(`Withdrawal exceeds the position: ${assets} asset units need ${shares} shares, the wallet holds ${position.shares}.`);
|
|
577
|
+
amountArg = toDecimalString(shares, v.sharesMintDecimals);
|
|
578
|
+
}
|
|
579
|
+
const expectedAssets = this.sharesToAssets(shares, v, tps);
|
|
580
|
+
if (expectedAssets < v.minWithdrawAmount) throw new KaminoError(`Withdrawal below the vault minimum: ${expectedAssets} < ${v.minWithdrawAmount} base units.`);
|
|
581
|
+
const base64 = await this.api.buildVaultWithdraw({ wallet: me, kvault: this.vault, amount: amountArg, memo: this.memo() });
|
|
582
|
+
return { base64, v, shares, expectedAssets };
|
|
583
|
+
}
|
|
584
|
+
async quoteWithdraw(o) {
|
|
585
|
+
const me = await this.me();
|
|
586
|
+
const { base64, v, shares, expectedAssets } = await this.planWithdraw(o, me);
|
|
587
|
+
const expect = this.receiveExpectation(v.tokenMint, expectedAssets);
|
|
588
|
+
const { fee } = await this.quoteBuilt(base64, expect);
|
|
589
|
+
return { fee, shares, expectedAssets, minAssets: expect.tokenIn.minAmount };
|
|
590
|
+
}
|
|
591
|
+
async withdraw(o) {
|
|
592
|
+
this.requireSigningAccount("withdraw(options)");
|
|
593
|
+
const me = await this.me();
|
|
594
|
+
const { base64, v, expectedAssets } = await this.planWithdraw(o, me);
|
|
595
|
+
return this.sendBuilt(base64, this.receiveExpectation(v.tokenMint, expectedAssets), "withdraw");
|
|
596
|
+
}
|
|
597
|
+
async borrow() {
|
|
598
|
+
throw new import_core2.NotImplementedError("borrow(options) \u2014 an Earn vault does not lend to its depositors; use KaminoMarketProtocolSolana.");
|
|
599
|
+
}
|
|
600
|
+
async quoteBorrow() {
|
|
601
|
+
throw new import_core2.NotImplementedError("quoteBorrow(options) \u2014 an Earn vault does not lend to its depositors; use KaminoMarketProtocolSolana.");
|
|
602
|
+
}
|
|
603
|
+
async repay() {
|
|
604
|
+
throw new import_core2.NotImplementedError("repay(options) \u2014 an Earn vault has no debt; use KaminoMarketProtocolSolana.");
|
|
605
|
+
}
|
|
606
|
+
async quoteRepay() {
|
|
607
|
+
throw new import_core2.NotImplementedError("quoteRepay(options) \u2014 an Earn vault has no debt; use KaminoMarketProtocolSolana.");
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
function rescale(amount, fromDecimals, toDecimals) {
|
|
611
|
+
if (fromDecimals === toDecimals) return amount;
|
|
612
|
+
return fromDecimals < toDecimals ? amount * 10n ** BigInt(toDecimals - fromDecimals) : amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
613
|
+
}
|
|
614
|
+
var SYMBOLS = Object.freeze({
|
|
615
|
+
So11111111111111111111111111111111111111112: "SOL",
|
|
616
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: "USDC",
|
|
617
|
+
Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: "USDT",
|
|
618
|
+
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": "PYUSD",
|
|
619
|
+
"2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": "USDG"
|
|
620
|
+
});
|
|
621
|
+
function symbolOf(v) {
|
|
622
|
+
return SYMBOLS[v.tokenMint] ?? v.tokenMint.slice(0, 4) + "\u2026";
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// src/market.ts
|
|
626
|
+
var KaminoMarketProtocolSolana = class extends KaminoBase {
|
|
627
|
+
market;
|
|
628
|
+
firstDepositAllowance;
|
|
629
|
+
_reserves = null;
|
|
630
|
+
constructor(account, config = {}) {
|
|
631
|
+
super(account, config);
|
|
632
|
+
this.market = config?.market ?? MAIN_MARKET;
|
|
633
|
+
if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(this.market)) throw new KaminoError("'market' must be the lending market's address.");
|
|
634
|
+
this.firstDepositAllowance = config?.firstDepositAllowanceLamports === void 0 ? DEFAULT_FIRST_DEPOSIT_ALLOWANCE : BigInt(config.firstDepositAllowanceLamports);
|
|
635
|
+
}
|
|
636
|
+
/** Reserves with rates, cached for a minute. */
|
|
637
|
+
async getReserves() {
|
|
638
|
+
const now = Date.now();
|
|
639
|
+
if (!this._reserves || now - this._reserves.at > 6e4) {
|
|
640
|
+
const p = this.api.getReserves(this.market).catch((e) => {
|
|
641
|
+
this._reserves = null;
|
|
642
|
+
throw e;
|
|
643
|
+
});
|
|
644
|
+
this._reserves = { at: now, p };
|
|
645
|
+
}
|
|
646
|
+
const rows = await this._reserves.p;
|
|
647
|
+
return rows.map((r) => ({ ...r, utilization: r.totalSupplyUsd > 0 ? r.totalBorrowUsd / r.totalSupplyUsd : 0 }));
|
|
648
|
+
}
|
|
649
|
+
/** The market's config entry plus its reserves. */
|
|
650
|
+
async getMarket() {
|
|
651
|
+
const [markets, reserves] = await Promise.all([this.api.listMarkets(), this.getReserves()]);
|
|
652
|
+
const m = markets.find((x) => x.lendingMarket === this.market);
|
|
653
|
+
if (!m) throw new KaminoError(`Market ${this.market} is not in Kamino's market list.`);
|
|
654
|
+
return { ...m, reserves };
|
|
655
|
+
}
|
|
656
|
+
/** The reserve a mint maps to: the pinned one, else the deepest by supplied value. */
|
|
657
|
+
async resolveReserve(mint) {
|
|
658
|
+
if (typeof mint !== "string" || !mint) throw new KaminoError("'token' must be the token's mint address.");
|
|
659
|
+
const reserves = await this.getReserves();
|
|
660
|
+
const pinned = this._config.reserves?.[mint];
|
|
661
|
+
if (pinned) {
|
|
662
|
+
const r = reserves.find((x) => x.reserve === pinned);
|
|
663
|
+
if (!r) throw new KaminoError(`Reserve ${pinned} is not in market ${this.market}.`);
|
|
664
|
+
if (r.mint !== mint) throw new KaminoError(`Reserve ${pinned} holds ${r.symbol} (${r.mint}), not ${mint}.`);
|
|
665
|
+
return r;
|
|
666
|
+
}
|
|
667
|
+
const candidates = reserves.filter((x) => x.mint === mint).sort((a, b) => b.totalSupplyUsd - a.totalSupplyUsd);
|
|
668
|
+
if (candidates.length === 0) throw new KaminoError(`Market ${this.market} has no reserve for ${mint}.`);
|
|
669
|
+
return candidates[0];
|
|
670
|
+
}
|
|
671
|
+
/** Obligations and per-mint totals. */
|
|
672
|
+
async getPosition() {
|
|
673
|
+
const me = await this.me();
|
|
674
|
+
const obligations = await this.api.getUserObligations(this.market, me);
|
|
675
|
+
const supplied = {}, borrowed = {};
|
|
676
|
+
for (const o of obligations) {
|
|
677
|
+
for (const d of o.deposits) if (d.mint) supplied[d.mint] = (supplied[d.mint] ?? 0n) + fromDecimalString(d.amount, await this.decimals(d.mint));
|
|
678
|
+
for (const b of o.borrows) if (b.mint) borrowed[b.mint] = (borrowed[b.mint] ?? 0n) + fromDecimalString(b.amount, await this.decimals(b.mint));
|
|
679
|
+
}
|
|
680
|
+
return { obligations, supplied, borrowed };
|
|
681
|
+
}
|
|
682
|
+
async lend(kind, me, mint, amount) {
|
|
683
|
+
const reserve = await this.resolveReserve(mint);
|
|
684
|
+
const p = { wallet: me, market: this.market, reserve: reserve.reserve, amount: toDecimalString(amount, await this.decimals(mint)), memo: this.memo() };
|
|
685
|
+
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);
|
|
686
|
+
return { base64, reserve };
|
|
687
|
+
}
|
|
688
|
+
/** A wallet without an obligation here pays the rent of one on its first deposit. */
|
|
689
|
+
async firstDepositExtra(me) {
|
|
690
|
+
const obligations = await this.api.getUserObligations(this.market, me).catch(() => []);
|
|
691
|
+
return obligations.length === 0 ? this.firstDepositAllowance : 0n;
|
|
692
|
+
}
|
|
693
|
+
/** Resolve 'max' against the position's supplied / borrowed total for the mint. */
|
|
694
|
+
async resolveMax(amount, mint, side) {
|
|
695
|
+
if (amount !== "max") return toAmount(amount);
|
|
696
|
+
const total = (await this.getPosition())[side][mint] ?? 0n;
|
|
697
|
+
if (total === 0n) throw new KaminoError(`Nothing ${side} in ${mint} on market ${this.market}.`);
|
|
698
|
+
return total;
|
|
699
|
+
}
|
|
700
|
+
async quoteSupply(o) {
|
|
701
|
+
const me = await this.me();
|
|
702
|
+
const amount = toAmount(o.amount);
|
|
703
|
+
const [{ base64, reserve }, extra] = await Promise.all([this.lend("deposit", me, o.token, amount), this.firstDepositExtra(me)]);
|
|
704
|
+
const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, amount, extra));
|
|
705
|
+
return { fee, reserve: reserve.reserve };
|
|
706
|
+
}
|
|
707
|
+
async supply(o) {
|
|
708
|
+
this.requireSigningAccount("supply(options)");
|
|
709
|
+
const me = await this.me();
|
|
710
|
+
const amount = toAmount(o.amount);
|
|
711
|
+
const [{ base64 }, extra] = await Promise.all([this.lend("deposit", me, o.token, amount), this.firstDepositExtra(me)]);
|
|
712
|
+
return this.sendBuilt(base64, this.spendExpectation(o.token, amount, extra), "supply");
|
|
713
|
+
}
|
|
714
|
+
async quoteWithdraw(o) {
|
|
715
|
+
const me = await this.me();
|
|
716
|
+
const amount = await this.resolveMax(o.amount, o.token, "supplied");
|
|
717
|
+
const { base64, reserve } = await this.lend("withdraw", me, o.token, amount);
|
|
718
|
+
const expect = this.receiveExpectation(o.token, amount);
|
|
719
|
+
const { fee } = await this.quoteBuilt(base64, expect);
|
|
720
|
+
return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
721
|
+
}
|
|
722
|
+
async withdraw(o) {
|
|
723
|
+
this.requireSigningAccount("withdraw(options)");
|
|
724
|
+
const me = await this.me();
|
|
725
|
+
const amount = await this.resolveMax(o.amount, o.token, "supplied");
|
|
726
|
+
const { base64 } = await this.lend("withdraw", me, o.token, amount);
|
|
727
|
+
return this.sendBuilt(base64, this.receiveExpectation(o.token, amount), "withdraw");
|
|
728
|
+
}
|
|
729
|
+
async quoteBorrow(o) {
|
|
730
|
+
const me = await this.me();
|
|
731
|
+
const amount = toAmount(o.amount);
|
|
732
|
+
const { base64, reserve } = await this.lend("borrow", me, o.token, amount);
|
|
733
|
+
const expect = this.receiveExpectation(o.token, amount);
|
|
734
|
+
const { fee } = await this.quoteBuilt(base64, expect);
|
|
735
|
+
return { fee, reserve: reserve.reserve, minReceived: expect.tokenIn.minAmount };
|
|
736
|
+
}
|
|
737
|
+
async borrow(o) {
|
|
738
|
+
this.requireSigningAccount("borrow(options)");
|
|
739
|
+
const me = await this.me();
|
|
740
|
+
const amount = toAmount(o.amount);
|
|
741
|
+
const { base64 } = await this.lend("borrow", me, o.token, amount);
|
|
742
|
+
return this.sendBuilt(base64, this.receiveExpectation(o.token, amount), "borrow");
|
|
743
|
+
}
|
|
744
|
+
async quoteRepay(o) {
|
|
745
|
+
const me = await this.me();
|
|
746
|
+
const amount = await this.resolveMax(o.amount, o.token, "borrowed");
|
|
747
|
+
const { base64, reserve } = await this.lend("repay", me, o.token, amount);
|
|
748
|
+
const { fee } = await this.quoteBuilt(base64, this.spendExpectation(o.token, amount + (amount - lessBps(amount, this.slippageBps))));
|
|
749
|
+
return { fee, reserve: reserve.reserve };
|
|
750
|
+
}
|
|
751
|
+
async repay(o) {
|
|
752
|
+
this.requireSigningAccount("repay(options)");
|
|
753
|
+
const me = await this.me();
|
|
754
|
+
const amount = await this.resolveMax(o.amount, o.token, "borrowed");
|
|
755
|
+
const { base64 } = await this.lend("repay", me, o.token, amount);
|
|
756
|
+
return this.sendBuilt(base64, this.spendExpectation(o.token, amount + (amount - lessBps(amount, this.slippageBps))), "repay");
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
//# sourceMappingURL=index.cjs.map
|