@naviprotocol/lending 2.0.6 → 2.0.7

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.
Files changed (54) hide show
  1. package/dist/account-cap.d.ts +1 -1
  2. package/dist/account-cap.js +26 -0
  3. package/dist/account-cap.js.map +1 -0
  4. package/dist/account.d.ts +2 -2
  5. package/dist/account.js +655 -0
  6. package/dist/account.js.map +1 -0
  7. package/dist/bcs.js +137 -0
  8. package/dist/bcs.js.map +1 -0
  9. package/dist/config.d.ts +1 -1
  10. package/dist/config.js +22 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/emode.d.ts +1 -1
  13. package/dist/emode.js +90 -0
  14. package/dist/emode.js.map +1 -0
  15. package/dist/flashloan.d.ts +1 -1
  16. package/dist/flashloan.js +94 -0
  17. package/dist/flashloan.js.map +1 -0
  18. package/dist/index.d.ts +17 -17
  19. package/dist/index.js +100 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/liquidate.d.ts +1 -1
  22. package/dist/liquidate.js +76 -0
  23. package/dist/liquidate.js.map +1 -0
  24. package/dist/market.d.ts +1 -1
  25. package/dist/market.js +121 -0
  26. package/dist/market.js.map +1 -0
  27. package/dist/oracle.d.ts +1 -1
  28. package/dist/oracle.js +204 -0
  29. package/dist/oracle.js.map +1 -0
  30. package/dist/package.json.js +8 -0
  31. package/dist/package.json.js.map +1 -0
  32. package/dist/pool.d.ts +1 -1
  33. package/dist/pool.js +391 -0
  34. package/dist/pool.js.map +1 -0
  35. package/dist/pyth.d.ts +1 -1
  36. package/dist/pyth.js +305 -0
  37. package/dist/pyth.js.map +1 -0
  38. package/dist/reward.d.ts +1 -1
  39. package/dist/reward.js +343 -0
  40. package/dist/reward.js.map +1 -0
  41. package/dist/services.js +52 -0
  42. package/dist/services.js.map +1 -0
  43. package/dist/sui.d.ts +1 -1
  44. package/dist/sui.js +121 -0
  45. package/dist/sui.js.map +1 -0
  46. package/dist/types.d.ts +2 -2
  47. package/dist/ua.js +16 -0
  48. package/dist/ua.js.map +1 -0
  49. package/dist/utils.d.ts +2 -2
  50. package/dist/utils.js +227 -0
  51. package/dist/utils.js.map +1 -0
  52. package/package.json +5 -5
  53. package/dist/index.esm.js +0 -2749
  54. package/dist/index.esm.js.map +0 -1
package/dist/index.esm.js DELETED
@@ -1,2749 +0,0 @@
1
- import { Transaction as q } from "@mysten/sui/transactions";
2
- import { bcs as l } from "@mysten/sui/bcs";
3
- import { toHex as Ue, fromHex as De, normalizeStructTag as Y, SUI_CLOCK_OBJECT_ID as x, fromBase64 as Fe } from "@mysten/sui/utils";
4
- import Ne from "lodash.camelcase";
5
- import p from "bignumber.js";
6
- import { SuiJsonRpcClient as Re } from "@mysten/sui/jsonRpc";
7
- import { SuiGraphQLClient as Le } from "@mysten/sui/graphql";
8
- import { SuiGrpcClient as we, GrpcWebFetchTransport as be } from "@mysten/sui/grpc";
9
- const ie = l.bytes(32).transform({
10
- // To change the input type, you need to provide a type definition for the input
11
- input: (e) => De(e),
12
- output: (e) => Ue(e)
13
- }), zt = l.struct("IncentiveAPYInfo", {
14
- /** Asset identifier */
15
- asset_id: l.u8(),
16
- /** Annual Percentage Yield as a 256-bit integer */
17
- apy: l.u256(),
18
- /** List of supported coin types for this incentive */
19
- coin_types: l.vector(l.string())
20
- }), qe = l.struct("IncentivePoolInfo", {
21
- /** Unique pool identifier */
22
- pool_id: ie,
23
- /** Address holding the incentive funds */
24
- funds: ie,
25
- /** Current phase of the incentive program */
26
- phase: l.u64(),
27
- /** Timestamp when the incentive started */
28
- start_at: l.u64(),
29
- /** Timestamp when the incentive ends */
30
- end_at: l.u64(),
31
- /** Timestamp when the incentive was closed */
32
- closed_at: l.u64(),
33
- /** Total supply of incentive tokens */
34
- total_supply: l.u64(),
35
- /** Asset identifier for the incentive */
36
- asset_id: l.u8(),
37
- /** Option type for the incentive */
38
- option: l.u8(),
39
- /** Factor used in incentive calculations */
40
- factor: l.u256(),
41
- /** Amount of incentives already distributed */
42
- distributed: l.u64(),
43
- /** Amount of incentives currently available */
44
- available: l.u256(),
45
- /** Total amount of incentives */
46
- total: l.u256()
47
- }), Gt = l.struct("IncentivePoolInfoByPhase", {
48
- /** Phase number */
49
- phase: l.u64(),
50
- /** List of incentive pools in this phase */
51
- pools: l.vector(qe)
52
- }), Wt = l.struct("OracleInfo", {
53
- /** Oracle identifier */
54
- oracle_id: l.u8(),
55
- /** Current price as a 256-bit integer */
56
- price: l.u256(),
57
- /** Number of decimal places for the price */
58
- decimals: l.u8(),
59
- /** Whether the oracle data is valid */
60
- valid: l.bool()
61
- }), Ht = l.struct("FlashLoanAssetConfig", {
62
- /** Unique identifier for the flash loan asset */
63
- id: l.string(),
64
- /** Asset identifier */
65
- asset_id: l.u8(),
66
- /** Coin type for the asset */
67
- coin_type: l.string(),
68
- /** Pool identifier for the flash loan */
69
- pool_id: l.string(),
70
- /** Rate paid to suppliers for flash loans */
71
- rate_to_supplier: l.u64(),
72
- /** Rate paid to treasury for flash loans */
73
- rate_to_treasury: l.u64(),
74
- /** Maximum flash loan amount */
75
- max: l.u64(),
76
- /** Minimum flash loan amount */
77
- min: l.u64()
78
- }), ze = l.struct("ReserveDataInfo", {
79
- /** Reserve identifier */
80
- id: l.u8(),
81
- /** Oracle identifier for price feeds */
82
- oracle_id: l.u8(),
83
- /** Coin type for the reserve */
84
- coin_type: l.string(),
85
- /** Maximum supply capacity */
86
- supply_cap: l.u256(),
87
- /** Maximum borrow capacity */
88
- borrow_cap: l.u256(),
89
- /** Current supply interest rate */
90
- supply_rate: l.u256(),
91
- /** Current borrow interest rate */
92
- borrow_rate: l.u256(),
93
- /** Current supply index for interest calculation */
94
- supply_index: l.u256(),
95
- /** Current borrow index for interest calculation */
96
- borrow_index: l.u256(),
97
- /** Total amount supplied to the reserve */
98
- total_supply: l.u256(),
99
- /** Total amount borrowed from the reserve */
100
- total_borrow: l.u256(),
101
- /** Timestamp of last update */
102
- last_update_at: l.u64(),
103
- /** Loan-to-Value ratio for collateral */
104
- ltv: l.u256(),
105
- /** Treasury factor for fee calculations */
106
- treasury_factor: l.u256(),
107
- /** Current treasury balance */
108
- treasury_balance: l.u256(),
109
- /** Base interest rate */
110
- base_rate: l.u256(),
111
- /** Interest rate multiplier */
112
- multiplier: l.u256(),
113
- /** Jump rate multiplier for high utilization */
114
- jump_rate_multiplier: l.u256(),
115
- /** Reserve factor for protocol fees */
116
- reserve_factor: l.u256(),
117
- /** Optimal utilization rate */
118
- optimal_utilization: l.u256(),
119
- /** Liquidation ratio threshold */
120
- liquidation_ratio: l.u256(),
121
- /** Liquidation bonus for liquidators */
122
- liquidation_bonus: l.u256(),
123
- /** Liquidation threshold */
124
- liquidation_threshold: l.u256()
125
- }), Ge = l.struct("UserStateInfo", {
126
- /** Asset identifier */
127
- asset_id: l.u8(),
128
- /** User's current borrow balance */
129
- borrow_balance: l.u256(),
130
- /** User's current supply balance */
131
- supply_balance: l.u256()
132
- }), We = "2.0.6", V = {
133
- version: We
134
- }, He = V.version, Je = () => {
135
- if (typeof process < "u" && process.versions && process.versions.node) {
136
- const e = process.version;
137
- return `Node.js ${e.startsWith("v") ? e.substring(1) : e}`;
138
- }
139
- return "Node/Unknown";
140
- }, Ke = () => {
141
- let e = "";
142
- return typeof process < "u" && process.versions && process.versions.node && (e = `lending/${He} (${Je()})`), e;
143
- }, ce = Ke(), ve = "0x2::sui::SUI";
144
- class Qe extends Error {
145
- constructor(t) {
146
- super(
147
- `NAVI Sui SDK capability "${t}" requires an explicit graphql client; no public GraphQL fallback is configured`
148
- ), this.name = "NaviMissingGraphQLClientError";
149
- }
150
- }
151
- function ee(e) {
152
- return e == null ? void 0 : String(e);
153
- }
154
- function Ye(e, t) {
155
- return (BigInt(e) + BigInt(t)).toString();
156
- }
157
- function Ze(e, t) {
158
- return (BigInt(e) - BigInt(t)).toString();
159
- }
160
- function Ce(e) {
161
- const t = e.core;
162
- if (typeof t?.getBalance != "function" || typeof t?.listBalances != "function")
163
- throw new Error("NAVI Sui balance helpers require a v2 Core API client");
164
- return t;
165
- }
166
- function je(e, t = ve) {
167
- const r = ee(e.addressBalance ?? e.fundsInAddressBalance) ?? "0";
168
- let o = ee(e.balance ?? e.totalBalance), n = ee(e.coinBalance);
169
- return !n && o && (n = Ze(o, r)), !o && n && (o = Ye(n, r)), {
170
- coinType: Y(e.coinType ?? t),
171
- totalBalance: o ?? "0",
172
- coinBalance: n ?? "0",
173
- addressBalance: r,
174
- ...e.coinObjectCount === null || e.coinObjectCount === void 0 ? {} : { coinObjectCount: e.coinObjectCount }
175
- };
176
- }
177
- function Jt(e, t = ve) {
178
- const r = Y(t);
179
- return e.filter((o) => Y(o.coinType) === r).reduce((o, n) => o + BigInt(n.balance), 0n).toString();
180
- }
181
- async function Kt(e, t) {
182
- const r = await Ce(e).getBalance(t), o = r.balance;
183
- return je((o && typeof o == "object" ? o : r) ?? {}, t.coinType);
184
- }
185
- async function Qt(e, t) {
186
- const r = await Ce(e).listBalances(t), { balances: o = [] } = r;
187
- return {
188
- balances: o.map((n) => je(n)),
189
- nextCursor: r.nextCursor ?? r.cursor ?? null
190
- };
191
- }
192
- function Xe(e, t) {
193
- if ("client" in t)
194
- return t.client;
195
- const r = new be({
196
- baseUrl: t.url,
197
- meta: t.headers,
198
- fetchInit: t.fetchInit,
199
- fetch: t.fetch
200
- });
201
- return new we({
202
- network: e,
203
- transport: r
204
- });
205
- }
206
- function xe(e, t) {
207
- return "client" in t ? t.client : new Le({
208
- network: e,
209
- url: t.url,
210
- headers: t.headers,
211
- fetch: t.fetch
212
- });
213
- }
214
- function Ie(e, t) {
215
- return "client" in t ? t.client : new Re({
216
- network: e,
217
- url: t.url
218
- });
219
- }
220
- function et(e) {
221
- const t = Xe(e.network, e.grpc);
222
- return {
223
- network: e.network,
224
- coreClient: t,
225
- grpc: t,
226
- graphql: e.graphql ? xe(e.network, e.graphql) : void 0,
227
- legacyJsonRpc: e.legacyJsonRpc ? Ie(e.network, e.legacyJsonRpc) : void 0,
228
- services: e.services
229
- };
230
- }
231
- function Yt(e, t) {
232
- if (!e.graphql)
233
- throw new Qe(t);
234
- return e.graphql;
235
- }
236
- const tt = "https://fullnode.mainnet.sui.io:443";
237
- let te;
238
- function rt() {
239
- return te || (te = new we({
240
- network: "mainnet",
241
- transport: new be({ baseUrl: tt })
242
- })), te;
243
- }
244
- function nt(e, t = "mainnet") {
245
- return e ? typeof e == "string" ? Ie(t, { url: e }) : et(e) : rt();
246
- }
247
- const ot = 16 * 1024;
248
- function oe(e) {
249
- return e.replace(/^0x/i, "");
250
- }
251
- function se(e) {
252
- const t = oe(e), r = new Uint8Array(t.length / 2);
253
- for (let o = 0; o < r.length; o += 1)
254
- r[o] = parseInt(t.slice(o * 2, o * 2 + 2), 16);
255
- return r;
256
- }
257
- function at(e, t) {
258
- return (e[t] << 8) + e[t + 1];
259
- }
260
- function ue(e) {
261
- return l.vector(l.U8).serialize(Array.from(e), {
262
- maxSize: ot
263
- });
264
- }
265
- function le(e, t) {
266
- return {
267
- type: e,
268
- bcs: t
269
- };
270
- }
271
- function it(e) {
272
- return l.vector(l.U8).serialize(Array.from(new TextEncoder().encode(e))).toBytes();
273
- }
274
- function ct(e) {
275
- return l.struct("PriceIdentifier", {
276
- bytes: l.vector(l.U8)
277
- }).serialize({
278
- bytes: Array.from(e)
279
- }).toBytes();
280
- }
281
- function st(e) {
282
- const t = [];
283
- let r = 0, o = 0;
284
- for (let n = 0; n < e.length; n += 1) {
285
- const a = e[n];
286
- a === "<" ? r += 1 : a === ">" ? r -= 1 : a === "," && r === 0 && (t.push(e.slice(o, n).trim()), o = n + 1);
287
- }
288
- return t.push(e.slice(o).trim()), t;
289
- }
290
- function ut(e) {
291
- const r = e.indexOf("::table::Table"), o = e.indexOf("<", r), n = e.lastIndexOf(">"), a = "::price_identifier::PriceIdentifier";
292
- if (r < 0 || o < 0 || n <= o)
293
- throw new Error(`Unexpected Pyth price table type: ${e}`);
294
- const [c, i] = st(e.slice(o + 1, n));
295
- if (!c?.endsWith(a) || !i?.endsWith("::object::ID"))
296
- throw new Error(`Unexpected Pyth price table type arguments: ${e}`);
297
- return c.slice(0, -a.length);
298
- }
299
- function lt(e) {
300
- return Uint8Array.from(atob(e), (t) => t.charCodeAt(0));
301
- }
302
- class ke {
303
- constructor(t, r) {
304
- this.endpoint = t.replace(/\/$/, ""), this.timeout = r?.timeout ?? 1e4;
305
- }
306
- async getLatestPriceFeeds(t) {
307
- return (await this.get("/api/latest_price_feeds", t)).map((o) => ({
308
- id: o.id,
309
- getPriceUnchecked: () => ({
310
- price: o.price.price,
311
- conf: o.price.conf,
312
- expo: o.price.expo,
313
- publishTime: o.price.publish_time
314
- })
315
- }));
316
- }
317
- async getPriceFeedsUpdateData(t) {
318
- const r = await this.get(
319
- "/v2/updates/price/latest",
320
- t,
321
- {
322
- encoding: "base64",
323
- parsed: "false"
324
- }
325
- ), o = r.binary?.encoding, n = r.binary?.data ?? [];
326
- if (o && o !== "base64")
327
- throw new Error(`Unsupported Hermes price update encoding: ${o}`);
328
- if (n.length === 0)
329
- throw new Error("Hermes price update response did not include binary update data");
330
- return n.map(lt);
331
- }
332
- async get(t, r, o) {
333
- const n = new AbortController(), a = setTimeout(() => n.abort(), this.timeout), c = new URL(`${this.endpoint}${t}`);
334
- for (const [i, s] of Object.entries(o ?? {}))
335
- c.searchParams.set(i, s);
336
- for (const i of r)
337
- c.searchParams.append("ids[]", oe(i));
338
- try {
339
- const i = await fetch(c, {
340
- signal: n.signal
341
- });
342
- if (!i.ok)
343
- throw new Error(`Hermes request failed: ${i.status} ${i.statusText}`);
344
- return await i.json();
345
- } finally {
346
- clearTimeout(a);
347
- }
348
- }
349
- }
350
- class dt {
351
- constructor(t, r, o) {
352
- this.provider = t, this.pythStateId = r, this.wormholeStateId = o, this.priceFeedObjectIdCache = /* @__PURE__ */ new Map();
353
- }
354
- getCoreProvider() {
355
- const t = this.provider.core;
356
- return t && typeof t.getObject == "function" && typeof t.getDynamicObjectField == "function" && typeof t.getDynamicField == "function" ? t : null;
357
- }
358
- async getMoveObjectJson(t) {
359
- const r = this.getCoreProvider();
360
- if (r) {
361
- const n = await r.getObject({
362
- objectId: t,
363
- include: { json: !0 }
364
- });
365
- return n.object ? {
366
- objectId: n.object.objectId,
367
- type: n.object.type,
368
- fields: n.object.json
369
- } : null;
370
- }
371
- if (!this.provider.getObject)
372
- throw new Error("Sui Pyth provider does not support getObject");
373
- const o = await this.provider.getObject({
374
- id: t,
375
- options: { showContent: !0 }
376
- });
377
- return !o.data || !o.data.content || o.data.content.dataType !== "moveObject" ? null : {
378
- objectId: o.data.objectId,
379
- type: o.data.type,
380
- fields: o.data.content.fields
381
- };
382
- }
383
- async getDynamicMoveObjectJson(t, r) {
384
- const o = this.getCoreProvider();
385
- if (o) {
386
- const a = await o.getDynamicObjectField({
387
- parentId: t,
388
- name: r,
389
- include: { json: !0 }
390
- });
391
- return a.object ? {
392
- objectId: a.object.objectId,
393
- type: a.object.type,
394
- fields: a.object.json
395
- } : null;
396
- }
397
- if (!this.provider.getDynamicFieldObject)
398
- throw new Error("Sui Pyth provider does not support getDynamicFieldObject");
399
- const n = await this.provider.getDynamicFieldObject({
400
- parentId: t,
401
- name: r
402
- });
403
- return n.data ? n.data.content ? n.data.content.dataType !== "moveObject" ? null : {
404
- objectId: n.data.objectId,
405
- type: n.data.type,
406
- fields: n.data.content.fields
407
- } : {
408
- objectId: n.data.objectId,
409
- type: n.data.type,
410
- fields: void 0
411
- } : null;
412
- }
413
- async updatePriceFeeds(t, r, o) {
414
- const n = await this.getPythPackageId(), a = await this.verifyVaasAndGetHotPotato(t, r, n), c = await this.getBaseUpdateFee(), i = t.splitCoins(
415
- t.gas,
416
- o.map(() => t.pure.u64(c))
417
- );
418
- return this.executePriceFeedUpdates(t, n, o, a, i);
419
- }
420
- async getBaseUpdateFee() {
421
- if (this.baseUpdateFee === void 0) {
422
- const t = await this.getMoveObjectJson(this.pythStateId);
423
- if (!t?.fields)
424
- throw new Error("Unable to fetch pyth state object");
425
- this.baseUpdateFee = Number(t.fields.base_update_fee);
426
- }
427
- return this.baseUpdateFee;
428
- }
429
- async getPackageId(t) {
430
- const r = await this.getMoveObjectJson(t);
431
- if (r?.fields) {
432
- const o = r.fields;
433
- if ("upgrade_cap" in o) {
434
- const n = o.upgrade_cap, a = n?.package ?? n?.fields?.package;
435
- if (a)
436
- return a;
437
- }
438
- }
439
- throw new Error(`Cannot fetch package id for object ${t}`);
440
- }
441
- async verifyVaas(t, r) {
442
- const o = await this.getWormholePackageId();
443
- return t.map((n) => {
444
- const [a] = r.moveCall({
445
- target: `${o}::vaa::parse_and_verify`,
446
- arguments: [
447
- r.object(this.wormholeStateId),
448
- r.pure(ue(n)),
449
- r.object(x)
450
- ]
451
- });
452
- return a;
453
- });
454
- }
455
- async verifyVaasAndGetHotPotato(t, r, o) {
456
- if (r.length > 1)
457
- throw new Error(
458
- "SDK does not support sending multiple accumulator messages in a single transaction"
459
- );
460
- const n = this.extractVaaBytesFromAccumulatorMessage(r[0]), [a] = await this.verifyVaas([n], t), [c] = t.moveCall({
461
- target: `${o}::pyth::create_authenticated_price_infos_using_accumulator`,
462
- arguments: [
463
- t.object(this.pythStateId),
464
- t.pure(ue(r[0])),
465
- a,
466
- t.object(x)
467
- ]
468
- });
469
- return c;
470
- }
471
- async executePriceFeedUpdates(t, r, o, n, a) {
472
- const c = [];
473
- for (const [i, s] of o.entries()) {
474
- const u = await this.getPriceFeedObjectId(s);
475
- if (!u)
476
- throw new Error(`Price feed ${s} not found, please create it first`);
477
- c.push(u), [n] = t.moveCall({
478
- target: `${r}::pyth::update_single_price_feed`,
479
- arguments: [
480
- t.object(this.pythStateId),
481
- n,
482
- t.object(u),
483
- a[i],
484
- t.object(x)
485
- ]
486
- });
487
- }
488
- return t.moveCall({
489
- target: `${r}::hot_potato_vector::destroy`,
490
- arguments: [n],
491
- typeArguments: [`${r}::price_info::PriceInfo`]
492
- }), c;
493
- }
494
- async getWormholePackageId() {
495
- return this.wormholePackageId || (this.wormholePackageId = await this.getPackageId(this.wormholeStateId)), this.wormholePackageId;
496
- }
497
- async getPythPackageId() {
498
- return this.pythPackageId || (this.pythPackageId = await this.getPackageId(this.pythStateId)), this.pythPackageId;
499
- }
500
- async getPriceFeedObjectId(t) {
501
- const r = oe(t);
502
- if (!this.priceFeedObjectIdCache.has(r)) {
503
- const { id: o, fieldType: n } = await this.getPriceTableInfo(), a = `${n}::price_identifier::PriceIdentifier`, c = this.getCoreProvider();
504
- if (c) {
505
- const { dynamicField: i } = await c.getDynamicField({
506
- parentId: o,
507
- name: le(a, ct(se(r)))
508
- }), s = i?.value?.bcs;
509
- this.priceFeedObjectIdCache.set(
510
- r,
511
- s && s.length === 32 ? l.Address.parse(Uint8Array.from(s)) : void 0
512
- );
513
- } else {
514
- const i = await this.getDynamicMoveObjectJson(o, {
515
- type: a,
516
- value: {
517
- bytes: Array.from(se(r))
518
- }
519
- });
520
- i?.fields ? this.priceFeedObjectIdCache.set(r, i.fields.value) : this.priceFeedObjectIdCache.set(r, void 0);
521
- }
522
- }
523
- return this.priceFeedObjectIdCache.get(r);
524
- }
525
- async getPriceTableInfo() {
526
- if (!this.priceTableInfo) {
527
- const t = this.getCoreProvider() ? le("vector<u8>", it("price_info")) : {
528
- type: "vector<u8>",
529
- value: "price_info"
530
- }, r = await this.getDynamicMoveObjectJson(this.pythStateId, t);
531
- if (!r?.type)
532
- throw new Error("Price Table not found, contract may not be initialized");
533
- this.priceTableInfo = {
534
- id: r.objectId,
535
- fieldType: ut(r.type)
536
- };
537
- }
538
- return this.priceTableInfo;
539
- }
540
- extractVaaBytesFromAccumulatorMessage(t) {
541
- const o = 7 + t[6] + 1, n = at(t, o), a = o + 2;
542
- return t.subarray(a, a + n);
543
- }
544
- }
545
- const pt = "https://open-api.naviprotocol.io/api";
546
- let Q = {}, _e = 0;
547
- function mt(e) {
548
- return e.replace(/\/+$/, "");
549
- }
550
- function Zt(e) {
551
- Q = {
552
- ...Q,
553
- ...e,
554
- services: {
555
- ...Q.services,
556
- ...e.services
557
- }
558
- }, _e += 1;
559
- }
560
- function de() {
561
- return _e;
562
- }
563
- function M(e) {
564
- const t = e?.services?.naviOpenApi ?? Q.services?.naviOpenApi;
565
- return {
566
- baseUrl: mt(t?.baseUrl ?? pt),
567
- headers: t?.headers
568
- };
569
- }
570
- function F(e, t) {
571
- const r = M(t), o = e.startsWith("/") ? e : `/${e}`;
572
- return `${r.baseUrl}${o}`;
573
- }
574
- function ft(e) {
575
- if (e instanceof Headers) {
576
- const t = {};
577
- return e.forEach((r, o) => {
578
- t[o] = r;
579
- }), t;
580
- }
581
- return Array.isArray(e) ? Object.fromEntries(e) : e;
582
- }
583
- function N(e, t) {
584
- return {
585
- ...ft(e),
586
- ...t?.headers ?? {}
587
- };
588
- }
589
- const U = nt();
590
- function pe(e) {
591
- return e ? e instanceof Uint8Array ? Array.from(e) : Array.isArray(e) ? e : Array.from(Fe(e)) : [];
592
- }
593
- function yt(e) {
594
- const t = e?.commandResults ?? [], r = e?.Transaction ?? e?.FailedTransaction ?? {}, o = r.effects?.errors?.[0] ?? r.effects?.status?.error ?? r.status?.error ?? r.status?.errors?.[0];
595
- return o && console.warn("[lending] devInspect(core simulate) returned error:", o), {
596
- effects: r.effects,
597
- events: r.events,
598
- error: o,
599
- results: t.map((n) => ({
600
- returnValues: (n.returnValues ?? []).map((a) => [pe(a.bcs), ""]),
601
- mutableReferenceOutputs: (n.mutatedReferences ?? []).map((a) => [
602
- "",
603
- pe(a.bcs),
604
- ""
605
- ])
606
- }))
607
- };
608
- }
609
- async function W(e, t) {
610
- const r = e?.core;
611
- if (typeof r?.simulateTransaction != "function")
612
- throw new Error("devInspectTransaction requires a Sui v2 Core-capable client");
613
- const o = t.transaction ?? t.transactionBlock;
614
- o instanceof q && o.setSenderIfNotSet(t.sender);
615
- const n = await r.simulateTransaction({
616
- transaction: o,
617
- checksEnabled: !1,
618
- include: {
619
- effects: !0,
620
- events: !0,
621
- commandResults: !0
622
- }
623
- });
624
- return yt(n);
625
- }
626
- function Te(e) {
627
- return {
628
- json: !!e?.showContent,
629
- display: !!e?.showDisplay,
630
- previousTransaction: !!e?.showPreviousTransaction,
631
- objectBcs: !!e?.showBcs
632
- };
633
- }
634
- function Be(e) {
635
- return !e || e instanceof Error ? {
636
- error: e instanceof Error ? { code: "notFound", error: e.message } : void 0
637
- } : {
638
- data: {
639
- objectId: e.objectId,
640
- version: e.version,
641
- digest: e.digest,
642
- type: e.type,
643
- owner: e.owner,
644
- previousTransaction: e.previousTransaction,
645
- content: e.json === void 0 ? void 0 : {
646
- dataType: "moveObject",
647
- type: e.type,
648
- fields: e.json
649
- },
650
- display: e.display
651
- }
652
- };
653
- }
654
- async function gt(e, t) {
655
- const r = e?.core;
656
- if (typeof r?.getObject != "function")
657
- throw new Error("getSuiObject requires a Sui v2 Core-capable client");
658
- const { object: o } = await r.getObject({
659
- objectId: t.id,
660
- include: Te(t.options)
661
- });
662
- return Be(o);
663
- }
664
- async function ht(e, t) {
665
- const r = e?.core;
666
- if (typeof r?.getObjects != "function")
667
- throw new Error("multiGetSuiObjects requires a Sui v2 Core-capable client");
668
- const { objects: o } = await r.getObjects({
669
- objectIds: t.ids,
670
- include: Te(t.options)
671
- });
672
- return o.map(Be);
673
- }
674
- function Pe(e) {
675
- const t = [];
676
- let r = !1;
677
- return e.forEach((o, n) => {
678
- const a = n === e.length - 1;
679
- if (typeof o == "object" && o !== null && a) {
680
- const { client: c, disableCache: i, cacheTime: s, ...u } = o;
681
- u.__naviSdkServiceConfigVersion = de(), t.push(u), r = !0;
682
- } else
683
- t.push(o);
684
- }), r || t.push({
685
- __naviSdkServiceConfigVersion: de()
686
- }), JSON.stringify(t);
687
- }
688
- function S(e) {
689
- const t = {};
690
- return (...r) => {
691
- const o = Pe(r);
692
- return t[o] || (t[o] = e(...r).finally(() => {
693
- delete t[o];
694
- })), t[o];
695
- };
696
- }
697
- function O(e) {
698
- let t = {};
699
- return (...r) => {
700
- const o = r[r.length - 1], n = Pe(r), a = t[n];
701
- return !o?.disableCache && typeof a?.data < "u" && (typeof o?.cacheTime > "u" || o.cacheTime > Date.now() - a.cacheAt) ? Promise.resolve(a.data) : e(...r).then((c) => (t[n] = {
702
- data: c,
703
- cacheAt: Date.now()
704
- }, c));
705
- };
706
- }
707
- function re(e) {
708
- return Array.isArray(e) ? e.map((t) => re(t)) : e != null && typeof e == "object" ? Object.keys(e).reduce(
709
- (t, r) => ({
710
- ...t,
711
- [Ne(r)]: re(e[r])
712
- }),
713
- {}
714
- ) : e;
715
- }
716
- function h(e, t) {
717
- if (e == null)
718
- throw new Error("Transaction value is required");
719
- return typeof e == "object" ? e : t(e);
720
- }
721
- function wt(e, t) {
722
- return typeof t == "string" ? e.object(t) : typeof t == "object" && t.$kind ? t : e.object(t.contract.pool);
723
- }
724
- function Z(e, t, r) {
725
- if (e.results && e.results.length > 0) {
726
- if (e.results[0].returnValues && e.results[0].returnValues.length > 0)
727
- return e.results[0].returnValues.map((o, n) => (t[n] || t[0]).parse(Uint8Array.from(o[0])));
728
- } else if (e.error)
729
- return console.log(`Get an error, msg: ${e.error}`), [];
730
- return [];
731
- }
732
- function C(e) {
733
- return Y(e);
734
- }
735
- function Ae(e) {
736
- const t = (e || 0) / Math.pow(10, 27);
737
- return t > Math.pow(10, 5) ? 1 / 0 : t;
738
- }
739
- new ke("https://hermes.pyth.network", {
740
- timeout: 2e4
741
- });
742
- const bt = 27, me = (e, t) => {
743
- if (!Number(e) || !Number(t)) return new p(0);
744
- const r = new p(1).shiftedBy(1 * bt), o = r.multipliedBy(new p(0.5));
745
- return new p(e).multipliedBy(new p(t)).plus(o).dividedBy(r).integerValue(p.ROUND_DOWN);
746
- }, R = ce ? {
747
- "User-Agent": ce
748
- } : {};
749
- function ne(e, t = "uniqueId") {
750
- return e.reduce(
751
- (r, o) => (r[o[t]] = o, r),
752
- {}
753
- );
754
- }
755
- function fe(e, t = "uniqueId") {
756
- return e.reduce(
757
- (r, o) => (r[o[t]] = o, r),
758
- {}
759
- );
760
- }
761
- function K(e, t) {
762
- const r = e.emodes.find((n) => n.emodeId === t.emodeId);
763
- if (!r)
764
- throw new Error("EMode not found in pool");
765
- const o = r.assets.find((n) => n.assetId === e.id);
766
- return {
767
- ...e,
768
- emode: {
769
- ...o,
770
- emodeId: r.emodeId
771
- },
772
- isEMode: !0
773
- };
774
- }
775
- function vt(e) {
776
- const [t, r] = e.split("-");
777
- return !t || !r ? null : {
778
- marketKey: t,
779
- poolId: parseInt(r)
780
- };
781
- }
782
- function A() {
783
- return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
784
- }
785
- var H = /* @__PURE__ */ ((e) => (e[e.Supply = 1] = "Supply", e[e.Withdraw = 2] = "Withdraw", e[e.Borrow = 3] = "Borrow", e[e.Repay = 4] = "Repay", e))(H || {});
786
- const J = O(
787
- S(
788
- async (e) => {
789
- const t = (e?.markets || [L.main]).map((a) => P(a)), r = M(e), o = F(
790
- `/navi/pools?env=${e?.env || "prod"}&sdk=${V.version}&market=${t.map(
791
- (a) => a.key
792
- )}`,
793
- e
794
- ), n = await fetch(o, { headers: N(R, r) }).then(
795
- (a) => a.json()
796
- );
797
- return n.data.forEach((a) => {
798
- const i = n.meta.emodes.filter((b) => {
799
- const j = P(b.marketId);
800
- return a.market === j.key && b.isActive;
801
- }).filter((b) => !!b.assets.find((j) => j.assetId === a.id));
802
- a.emodes = i;
803
- const s = p(a.totalSupplyAmount).div(Math.pow(10, 9)).decimalPlaces(a.token.decimals, p.ROUND_DOWN).toString(), u = p(a.borrowedAmount).shiftedBy(-9).decimalPlaces(a.token.decimals, p.ROUND_DOWN).toString(), m = p(s).multipliedBy(a.oracle.price).toString(), w = p(u).multipliedBy(a.oracle.price).toString(), g = p(a.supplyCapCeiling).shiftedBy(-27).decimalPlaces(a.token.decimals, p.ROUND_DOWN).toString(), y = p.max(
804
- p(a.borrowedAmount),
805
- p(a.validBorrowAmount)
806
- ).shiftedBy(-9).decimalPlaces(a.token.decimals, p.ROUND_DOWN).toString(), d = p(g).multipliedBy(a.oracle.price).toString(), f = p(y).multipliedBy(a.oracle.price).toString();
807
- a.poolSupplyAmount = s, a.poolBorrowAmount = u, a.poolSupplyValue = m, a.poolBorrowValue = w, a.poolSupplyCapAmount = g, a.poolBorrowCapAmount = y, a.poolSupplyCapValue = d, a.poolBorrowCapValue = f;
808
- }), n.data;
809
- }
810
- )
811
- );
812
- async function E(e, t) {
813
- let r = t?.market;
814
- if (typeof e == "string") {
815
- const a = vt(e);
816
- a && (r = a.marketKey, e = a.poolId);
817
- }
818
- const o = await J({
819
- ...t,
820
- markets: [r || z],
821
- cacheTime: v
822
- });
823
- if (typeof e == "object")
824
- return e;
825
- const n = o.find((a) => typeof e == "string" ? C(a.suiCoinType) === C(e) : typeof e == "number" ? a.id === e : !1);
826
- if (!n)
827
- throw new Error("Pool not found");
828
- return n.isDeprecated && console.log(`The lending pool for coinType ${n.suiCoinType} is going to be deprecated.`), n;
829
- }
830
- const Xt = O(
831
- S(async (e) => {
832
- const t = M(e), r = F(`/navi/stats?sdk=${V.version}`, e);
833
- return (await fetch(r, {
834
- headers: N(R, t)
835
- }).then((n) => n.json())).data;
836
- })
837
- ), xt = O(
838
- S(
839
- async (e) => {
840
- const t = M(e), r = F(`/navi/fee?sdk=${V.version}`, e);
841
- return await fetch(r, {
842
- headers: N(R, t)
843
- }).then((n) => n.json());
844
- }
845
- )
846
- );
847
- async function Ct(e, t, r, o) {
848
- const n = await I({
849
- ...o,
850
- cacheTime: v
851
- }), a = await E(t, o), c = o?.market || z, i = o?.env || "prod";
852
- if (a?.deprecatedAt && Date.now() > a.deprecatedAt)
853
- throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);
854
- if (C(a.suiCoinType) === C("0x2::sui::SUI") && typeof r == "object" && r?.$kind === "GasCoin") {
855
- if (!o?.amount)
856
- throw new Error("Amount is required for sui coin");
857
- r = e.splitCoins(r, [o.amount]);
858
- }
859
- let s;
860
- return typeof o?.amount < "u" ? s = h(o.amount, e.pure.u64) : s = e.moveCall({
861
- target: "0x2::coin::value",
862
- arguments: [h(r, e.object)],
863
- typeArguments: [a.suiCoinType]
864
- }), o?.accountCap ? e.moveCall({
865
- target: `${n.package}::incentive_v3::deposit_with_account_cap`,
866
- arguments: [
867
- e.object("0x06"),
868
- e.object(n.storage),
869
- e.object(a.contract.pool),
870
- e.pure.u8(a.id),
871
- h(r, e.object),
872
- e.object(n.incentiveV2),
873
- e.object(n.incentiveV3),
874
- h(o.accountCap, e.object)
875
- ],
876
- typeArguments: [a.suiCoinType]
877
- }) : e.moveCall({
878
- target: `${n.package}::incentive_v3::entry_deposit`,
879
- arguments: [
880
- e.object("0x06"),
881
- e.object(n.storage),
882
- e.object(a.contract.pool),
883
- e.pure.u8(a.id),
884
- h(r, e.object),
885
- s,
886
- e.object(n.incentiveV2),
887
- e.object(n.incentiveV3)
888
- ],
889
- typeArguments: [a.suiCoinType]
890
- }), n.version === 2 && a.token.symbol === "SUI" && i === "prod" && c === "main" && e.moveCall({
891
- target: `${n.package}::pool::refresh_stake`,
892
- arguments: [e.object(a.contract.pool), e.object("0x05")]
893
- }), e;
894
- }
895
- async function er(e, t, r, o) {
896
- const n = await I({
897
- ...o,
898
- cacheTime: v
899
- }), a = await E(t, o), c = h(r, e.pure.u64);
900
- let i;
901
- if (n.version === 1)
902
- if (o?.accountCap) {
903
- const [u] = e.moveCall({
904
- target: `${n.package}::incentive_v3::withdraw_with_account_cap`,
905
- arguments: [
906
- e.object("0x06"),
907
- e.object(n.priceOracle),
908
- e.object(n.storage),
909
- e.object(a.contract.pool),
910
- e.pure.u8(a.id),
911
- c,
912
- e.object(n.incentiveV2),
913
- e.object(n.incentiveV3),
914
- h(o.accountCap, e.object)
915
- ],
916
- typeArguments: [a.suiCoinType]
917
- });
918
- i = u;
919
- } else {
920
- const [u] = e.moveCall({
921
- target: `${n.package}::incentive_v3::withdraw`,
922
- arguments: [
923
- e.object("0x06"),
924
- e.object(n.priceOracle),
925
- e.object(n.storage),
926
- e.object(a.contract.pool),
927
- e.pure.u8(a.id),
928
- c,
929
- e.object(n.incentiveV2),
930
- e.object(n.incentiveV3)
931
- ],
932
- typeArguments: [a.suiCoinType]
933
- });
934
- i = u;
935
- }
936
- else if (o?.accountCap) {
937
- const [u] = e.moveCall({
938
- target: `${n.package}::incentive_v3::withdraw_with_account_cap_v2`,
939
- arguments: [
940
- e.object("0x06"),
941
- e.object(n.priceOracle),
942
- e.object(n.storage),
943
- e.object(a.contract.pool),
944
- e.pure.u8(a.id),
945
- c,
946
- e.object(n.incentiveV2),
947
- e.object(n.incentiveV3),
948
- h(o.accountCap, e.object),
949
- e.object("0x05")
950
- ],
951
- typeArguments: [a.suiCoinType]
952
- });
953
- i = u;
954
- } else {
955
- const [u] = e.moveCall({
956
- target: `${n.package}::incentive_v3::withdraw_v2`,
957
- arguments: [
958
- e.object("0x06"),
959
- e.object(n.priceOracle),
960
- e.object(n.storage),
961
- e.object(a.contract.pool),
962
- e.pure.u8(a.id),
963
- c,
964
- e.object(n.incentiveV2),
965
- e.object(n.incentiveV3),
966
- e.object("0x05")
967
- ],
968
- typeArguments: [a.suiCoinType]
969
- });
970
- i = u;
971
- }
972
- return e.moveCall({
973
- target: "0x2::coin::from_balance",
974
- arguments: [i],
975
- typeArguments: [a.suiCoinType]
976
- });
977
- }
978
- async function tr(e, t, r, o) {
979
- const n = await I({
980
- ...o,
981
- cacheTime: v
982
- }), a = await E(t, o);
983
- if (a?.deprecatedAt && Date.now() > a.deprecatedAt)
984
- throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);
985
- const c = h(r, e.pure.u64);
986
- let i;
987
- if (n.version === 1)
988
- if (o?.accountCap) {
989
- const [u] = e.moveCall({
990
- target: `${n.package}::incentive_v3::borrow_with_account_cap`,
991
- arguments: [
992
- e.object("0x06"),
993
- e.object(n.priceOracle),
994
- e.object(n.storage),
995
- e.object(a.contract.pool),
996
- e.pure.u8(a.id),
997
- c,
998
- e.object(n.incentiveV2),
999
- e.object(n.incentiveV3),
1000
- h(o.accountCap, e.object)
1001
- ],
1002
- typeArguments: [a.suiCoinType]
1003
- });
1004
- i = u;
1005
- } else {
1006
- const [u] = e.moveCall({
1007
- target: `${n.package}::incentive_v3::borrow`,
1008
- arguments: [
1009
- e.object("0x06"),
1010
- e.object(n.priceOracle),
1011
- e.object(n.storage),
1012
- e.object(a.contract.pool),
1013
- e.pure.u8(a.id),
1014
- c,
1015
- e.object(n.incentiveV2),
1016
- e.object(n.incentiveV3)
1017
- ],
1018
- typeArguments: [a.suiCoinType]
1019
- });
1020
- i = u;
1021
- }
1022
- else if (o?.accountCap) {
1023
- const [u] = e.moveCall({
1024
- target: `${n.package}::incentive_v3::borrow_with_account_cap_v2`,
1025
- arguments: [
1026
- e.object("0x06"),
1027
- e.object(n.priceOracle),
1028
- e.object(n.storage),
1029
- e.object(a.contract.pool),
1030
- e.pure.u8(a.id),
1031
- c,
1032
- e.object(n.incentiveV2),
1033
- e.object(n.incentiveV3),
1034
- h(o.accountCap, e.object),
1035
- e.object("0x05")
1036
- ],
1037
- typeArguments: [a.suiCoinType]
1038
- });
1039
- i = u;
1040
- } else {
1041
- const [u] = e.moveCall({
1042
- target: `${n.package}::incentive_v3::borrow_v2`,
1043
- arguments: [
1044
- e.object("0x06"),
1045
- e.object(n.priceOracle),
1046
- e.object(n.storage),
1047
- e.object(a.contract.pool),
1048
- e.pure.u8(a.id),
1049
- c,
1050
- e.object(n.incentiveV2),
1051
- e.object(n.incentiveV3),
1052
- e.object("0x05")
1053
- ],
1054
- typeArguments: [a.suiCoinType]
1055
- });
1056
- i = u;
1057
- }
1058
- return e.moveCall({
1059
- target: "0x2::coin::from_balance",
1060
- arguments: [e.object(i)],
1061
- typeArguments: [a.suiCoinType]
1062
- });
1063
- }
1064
- async function rr(e, t, r, o) {
1065
- const n = await I({
1066
- ...o,
1067
- cacheTime: v
1068
- }), a = await E(t, o);
1069
- if (C(a.suiCoinType) === C("0x2::sui::SUI") && typeof r == "object" && r?.$kind === "GasCoin") {
1070
- if (!o?.amount)
1071
- throw new Error("Amount is required for sui coin");
1072
- r = e.splitCoins(r, [o.amount]);
1073
- }
1074
- let c;
1075
- if (typeof o?.amount < "u" ? c = h(o.amount, e.pure.u64) : c = e.moveCall({
1076
- target: "0x2::coin::value",
1077
- arguments: [h(r, e.object)],
1078
- typeArguments: [a.suiCoinType]
1079
- }), o?.accountCap) {
1080
- const [i] = e.moveCall({
1081
- target: `${n.package}::incentive_v3::repay_with_account_cap`,
1082
- arguments: [
1083
- e.object("0x06"),
1084
- e.object(n.priceOracle),
1085
- e.object(n.storage),
1086
- e.object(a.contract.pool),
1087
- e.pure.u8(a.id),
1088
- h(r, e.object),
1089
- e.object(n.incentiveV2),
1090
- e.object(n.incentiveV3),
1091
- h(o.accountCap, e.object)
1092
- ],
1093
- typeArguments: [a.suiCoinType]
1094
- });
1095
- return e.moveCall({
1096
- target: "0x2::coin::from_balance",
1097
- arguments: [i],
1098
- typeArguments: [a.suiCoinType]
1099
- });
1100
- } else
1101
- return e.moveCall({
1102
- target: `${n.package}::incentive_v3::entry_repay`,
1103
- arguments: [
1104
- e.object("0x06"),
1105
- e.object(n.priceOracle),
1106
- e.object(n.storage),
1107
- e.object(a.contract.pool),
1108
- e.pure.u8(a.id),
1109
- h(r, e.object),
1110
- c,
1111
- e.object(n.incentiveV2),
1112
- e.object(n.incentiveV3)
1113
- ],
1114
- typeArguments: [a.suiCoinType]
1115
- }), e;
1116
- }
1117
- const nr = O(
1118
- S(
1119
- async (e) => {
1120
- const t = await I({
1121
- ...e
1122
- }), r = e?.client ?? U;
1123
- if (e?.address && typeof e?.asset < "u")
1124
- try {
1125
- const a = await E(e.asset, e), c = new q();
1126
- c.moveCall({
1127
- target: `${t.package}::incentive_v3::get_borrow_fee_v2`,
1128
- arguments: [
1129
- c.object(t.incentiveV3),
1130
- c.pure.address(e.address),
1131
- c.pure.u8(a.id),
1132
- c.pure.u64(1e4)
1133
- ],
1134
- typeArguments: []
1135
- });
1136
- const i = await W(r, {
1137
- transactionBlock: c,
1138
- sender: e.address
1139
- }), s = Z(i, [l.u64()]);
1140
- return (Number(s[0]) || 0) / 100;
1141
- } catch (a) {
1142
- console.error(
1143
- "[lending] getBorrowFee per-user query failed, falling back to global rate:",
1144
- a
1145
- );
1146
- }
1147
- const n = (await gt(r, {
1148
- id: t.incentiveV3,
1149
- options: { showType: !0, showOwner: !0, showContent: !0 }
1150
- })).data.content.fields.borrow_fee_rate;
1151
- return Number(n) / 100;
1152
- }
1153
- )
1154
- ), z = "main", L = {
1155
- main: {
1156
- id: 0,
1157
- key: "main",
1158
- name: "Main Market"
1159
- },
1160
- ember: {
1161
- id: 1,
1162
- key: "ember",
1163
- name: "Ember Market"
1164
- },
1165
- rwa: {
1166
- id: 2,
1167
- key: "rwa",
1168
- name: "Matrixdock Market"
1169
- },
1170
- "sui-eco": {
1171
- id: 3,
1172
- key: "sui-eco",
1173
- name: "Sui Eco Market"
1174
- }
1175
- };
1176
- class jt {
1177
- constructor(t, r) {
1178
- this.poolMap = {}, this.emodeMap = {}, this.pools = [], this.emodes = [], this.emodePools = [], this.emodeBorrowablePools = [], this.emodeSupplyablePools = [], this._overview = {
1179
- marketTotalSupplyValue: "0",
1180
- marketTotalBorrowValue: "0"
1181
- }, this.config = P(t), this.initPools(r);
1182
- }
1183
- get overview() {
1184
- return this._overview;
1185
- }
1186
- initPools(t) {
1187
- const r = ne(this.pools), o = fe(this.emodes), n = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set();
1188
- let c = p(0), i = p(0);
1189
- t.forEach((s) => {
1190
- if (!this.checkMarket(s.market)) {
1191
- console.warn(`Pool is not in market ${this.config.name}`, s);
1192
- return;
1193
- }
1194
- r[s.uniqueId] || this.pools.push(s), s?.emodes?.forEach((m) => {
1195
- o[m.uniqueId] || this.emodes.push(m), m.assets.forEach((w) => {
1196
- w.isDebt && m.assets.find(
1197
- (y) => y.isCollateral && y.ltv > 0 && y.assetId !== s.id
1198
- ) && n.add(s.uniqueId), w.isCollateral && m.assets.find((y) => y.isDebt && y.assetId !== s.id) && a.add(s.uniqueId);
1199
- });
1200
- }), i = i.plus(s.poolBorrowValue), c = c.plus(s.poolSupplyValue);
1201
- }), this.poolMap = ne(this.pools, "id"), this.emodeMap = fe(this.emodes, "emodeId"), this.emodes.forEach((s) => {
1202
- const u = this.getEModePools(s.emodeId);
1203
- this.emodePools.push(...u);
1204
- }), this._overview = {
1205
- marketTotalSupplyValue: c.toString(),
1206
- marketTotalBorrowValue: i.toString()
1207
- }, this.emodeBorrowablePools = this.pools.filter((s) => n.has(s.uniqueId)), this.emodeSupplyablePools = this.pools.filter((s) => a.has(s.uniqueId));
1208
- }
1209
- getEMode(t) {
1210
- return this.emodeMap[t] || null;
1211
- }
1212
- getEModeRelatePools(t, r) {
1213
- const { collateral: o, debt: n, emodeId: a } = r || {}, c = [];
1214
- return t.emodes.forEach((i) => {
1215
- typeof a == "number" && a !== i.emodeId || i.assets.forEach((s) => {
1216
- typeof o == "boolean" && o && s.isCollateral && s.assetId === t.id && c.push(this.poolMap[s.assetId]), typeof n == "boolean" && n && s.isDebt && s.assetId === t.id && c.push(this.poolMap[s.assetId]);
1217
- });
1218
- }), c;
1219
- }
1220
- getEModePools(t) {
1221
- const r = this.getEMode(t);
1222
- return r ? r.assets.map((n) => n.assetId).map((n) => this.poolMap[n]).filter((n) => !!n).map((n) => {
1223
- const a = r.assets.find((c) => c.assetId === n.id);
1224
- return {
1225
- ...n,
1226
- emode: {
1227
- ...a,
1228
- emodeId: r.emodeId
1229
- },
1230
- isEMode: !0
1231
- };
1232
- }) : [];
1233
- }
1234
- checkMarket(t) {
1235
- let r = !1;
1236
- return typeof t == "number" && t === this.config.id && (r = !0), typeof t == "string" && t === this.config.key && (r = !0), typeof t == "object" && t.id === this.config.id && (r = !0), r;
1237
- }
1238
- }
1239
- const P = (e) => {
1240
- const r = Object.values(L).find((o) => typeof e == "number" ? o.id === e : typeof e == "string" ? o.key === e : o.id === e.id);
1241
- if (!r)
1242
- throw new Error("Market not found");
1243
- return r;
1244
- }, It = O(
1245
- S(
1246
- async (e, t) => {
1247
- const r = await J({
1248
- cacheTime: 6e4,
1249
- ...t,
1250
- markets: e
1251
- });
1252
- return e.map((o) => {
1253
- const n = P(o), a = r.filter((c) => c.market === n.key);
1254
- return new jt(o, a);
1255
- });
1256
- }
1257
- )
1258
- ), or = O(
1259
- S(
1260
- async (e, t) => (await It([e], t))[0]
1261
- )
1262
- ), I = O(
1263
- S(
1264
- async (e) => {
1265
- const t = P(e?.market || z), r = M(e), o = F(
1266
- `/navi/config?env=${e?.env || "prod"}&sdk=${V.version}&market=${t.key}`,
1267
- e
1268
- );
1269
- return (await fetch(o, {
1270
- headers: N(R, r)
1271
- }).then((a) => a.json())).data;
1272
- }
1273
- )
1274
- ), v = 1e3 * 60 * 5;
1275
- async function kt(e, t) {
1276
- const r = await I({
1277
- cacheTime: v,
1278
- ...t
1279
- });
1280
- return e.moveCall({
1281
- target: `${r.package}::lending::create_account`,
1282
- arguments: []
1283
- });
1284
- }
1285
- async function _t(e, t, r) {
1286
- const o = await I({
1287
- cacheTime: v,
1288
- ...r
1289
- });
1290
- return e.moveCall({
1291
- target: `${o.package}::account::account_owner`,
1292
- arguments: [t]
1293
- });
1294
- }
1295
- async function Tt(e, t, r) {
1296
- const o = await I({
1297
- ...r,
1298
- cacheTime: v
1299
- });
1300
- return r?.accountCap ? e.moveCall({
1301
- target: `${o.package}::lending::enter_emode_with_account_cap`,
1302
- arguments: [
1303
- e.object(o.storage),
1304
- h(t, e.pure.u64),
1305
- h(r.accountCap, e.object)
1306
- ]
1307
- }) : e.moveCall({
1308
- target: `${o.package}::lending::enter_emode`,
1309
- arguments: [e.object(o.storage), h(t, e.pure.u64)]
1310
- }), e;
1311
- }
1312
- async function ar(e, t) {
1313
- const r = await I({
1314
- ...t,
1315
- cacheTime: v
1316
- });
1317
- return t?.accountCap ? e.moveCall({
1318
- target: `${r.package}::lending::exit_emode_with_account_cap`,
1319
- arguments: [e.object(r.storage), h(t.accountCap, e.object)]
1320
- }) : e.moveCall({
1321
- target: `${r.package}::lending::exit_emode`,
1322
- arguments: [e.object(r.storage)]
1323
- }), e;
1324
- }
1325
- async function ir(e, t, r) {
1326
- const o = await I({
1327
- cacheTime: v,
1328
- ...r
1329
- }), n = await kt(e, r);
1330
- await Tt(e, t, {
1331
- ...r,
1332
- accountCap: n
1333
- });
1334
- const a = await P(r?.market || z), c = await _t(e, n, r);
1335
- return e.moveCall({
1336
- target: `${o.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,
1337
- arguments: [
1338
- e.object(o.emode.contract.registryObject),
1339
- c,
1340
- h(a.id, e.pure.u64),
1341
- h(t, e.pure.u64)
1342
- ]
1343
- }), n;
1344
- }
1345
- const Se = O(
1346
- S(
1347
- async (e, t) => {
1348
- const r = await I({
1349
- cacheTime: v,
1350
- ...t
1351
- }), o = new q(), n = t?.client ?? U;
1352
- o.moveCall({
1353
- target: `${r.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,
1354
- arguments: [o.object(r.emode.contract.registryObject), o.pure.address(e)]
1355
- });
1356
- const c = (await W(n, {
1357
- transactionBlock: o,
1358
- sender: e
1359
- })).results[0].returnValues, i = l.vector(l.u64()).parse(Uint8Array.from(c[0][0])), s = l.vector(l.u64()).parse(Uint8Array.from(c[1][0])), u = l.vector(l.Address).parse(Uint8Array.from(c[2][0]));
1360
- return i.map((m, w) => ({
1361
- marketId: Number(m),
1362
- emodeId: Number(s[w]),
1363
- accountCap: u[w].toString()
1364
- }));
1365
- }
1366
- )
1367
- );
1368
- function cr(e) {
1369
- return `${P(e.marketId).key}-${e.emodeId}`;
1370
- }
1371
- function Bt(e, t) {
1372
- return e.coinType ? e.coinType : t || (typeof e.type == "string" ? e.type.match(/::coin::Coin<(.+)>$/) : null)?.[1];
1373
- }
1374
- function ye(e, t) {
1375
- const r = Bt(e, t), o = e.coinObjectId ?? e.objectId;
1376
- return !r || !o || e.balance === void 0 || e.balance === null ? null : {
1377
- ...e,
1378
- coinType: C(r),
1379
- coinObjectId: o
1380
- };
1381
- }
1382
- function sr(e, t, r) {
1383
- const o = typeof r?.balance == "number", n = o ? r.balance : 0, a = BigInt(r?.addressBalance ?? 0);
1384
- let c = 0;
1385
- const i = [];
1386
- let s = "", u = 0n;
1387
- t.sort((B, X) => Number(X.balance) - Number(B.balance)).forEach((B) => {
1388
- if (u += BigInt(B.balance), !(o && c >= n) && Number(B.balance) !== 0) {
1389
- if (s || (s = B.coinType), s !== B.coinType)
1390
- throw new Error("All coins must be of the same type");
1391
- c += Number(B.balance), i.push(B.coinObjectId);
1392
- }
1393
- });
1394
- const m = r?.coinType, y = ((B) => {
1395
- if (!B)
1396
- return !1;
1397
- try {
1398
- return C(B) === C("0x2::sui::SUI");
1399
- } catch {
1400
- return !1;
1401
- }
1402
- })(s || m || "") && !!r?.useGasCoin, d = BigInt(n), f = !y && !!m, b = f ? a : 0n, j = u + b, _ = !o || u >= d ? 0n : d - u, k = f && _ > 0n && b >= _;
1403
- if (o && j < d)
1404
- throw new Error(`Balance is less than the specified balance: ${j} < ${d}`);
1405
- if (i.length === 0 && !k)
1406
- throw new Error("No coins to merge");
1407
- if (y)
1408
- return o ? e.splitCoins(e.gas, [e.pure.u64(n)]) : e.gas;
1409
- if (!k)
1410
- return i.length === 1 ? e.object(i[0]) : e.mergeCoins(i[0], i.slice(1)), o ? e.splitCoins(i[0], [e.pure.u64(n)]) : i[0];
1411
- const T = e.moveCall({
1412
- target: "0x2::coin::redeem_funds",
1413
- typeArguments: [m],
1414
- arguments: [e.withdrawal({ amount: _, type: m })]
1415
- });
1416
- let $;
1417
- const D = [];
1418
- if (i.length > 0) {
1419
- $ = e.object(i[0]);
1420
- for (const B of i.slice(1))
1421
- D.push(e.object(B));
1422
- D.push(T);
1423
- } else
1424
- $ = T;
1425
- return D.length > 0 && e.mergeCoins($, D), i.length === 0 ? $ : o ? e.splitCoins($, [e.pure.u64(n)]) : $;
1426
- }
1427
- async function $e(e, t, r, o, n, a, c) {
1428
- const i = await I({
1429
- ...c,
1430
- cacheTime: v
1431
- }), s = await E(r, c);
1432
- return e.moveCall({
1433
- target: `${i.uiGetter}::calculator_unchecked::dynamic_health_factor`,
1434
- arguments: [
1435
- e.object("0x06"),
1436
- e.object(i.storage),
1437
- e.object(i.oracle.priceOracle),
1438
- wt(e, s),
1439
- h(t, e.pure.address),
1440
- h(s.id, e.pure.u8),
1441
- h(o, e.pure.u64),
1442
- h(n, e.pure.u64),
1443
- h(a, e.pure.bool)
1444
- ],
1445
- typeArguments: [s.suiCoinType]
1446
- });
1447
- }
1448
- async function Pt(e, t, r) {
1449
- return $e(e, t, 0, 0, 0, !1, r);
1450
- }
1451
- async function Ee(e, t, r) {
1452
- const o = new q(), n = r?.client ?? U, a = await J({
1453
- ...r,
1454
- markets: Object.values(L)
1455
- }), c = ne(a), s = Array.from(new Set(t.map((d) => d.market))).map((d) => P(d));
1456
- for (const d of s) {
1457
- const f = await I({
1458
- ...r,
1459
- cacheTime: v,
1460
- market: d.key
1461
- });
1462
- o.moveCall({
1463
- target: `${f.uiGetter}::getter::get_reserve_data`,
1464
- arguments: [o.object(f.storage)]
1465
- });
1466
- }
1467
- for (let d of t) {
1468
- const f = await I({
1469
- ...r,
1470
- cacheTime: v,
1471
- market: d.market
1472
- });
1473
- o.moveCall({
1474
- target: `${f.uiGetter}::getter_unchecked::get_user_state`,
1475
- arguments: [o.object(f.storage), o.pure.address(d.address)]
1476
- });
1477
- }
1478
- const m = (await W(n, {
1479
- transactionBlock: o,
1480
- sender: e
1481
- })).results || [], w = {};
1482
- s.forEach((d, f) => {
1483
- try {
1484
- const b = m[f]?.returnValues?.map((_) => l.vector(ze).parse(Uint8Array.from(_[0])))[0] || [], j = {};
1485
- for (const _ of b)
1486
- j[_.id] = {
1487
- supplyIndex: _.supply_index,
1488
- borrowIndex: _.borrow_index
1489
- };
1490
- w[d.key] = j;
1491
- } catch (b) {
1492
- console.warn(
1493
- `[@naviprotocol/lending] Failed to decode reserve data for market "${d.key}", falling back to open-api pool indices`,
1494
- b
1495
- );
1496
- }
1497
- });
1498
- const g = m.slice(s.length).map((d) => d.returnValues?.map((f) => l.vector(Ge).parse(Uint8Array.from(f[0])))[0] || []), y = [];
1499
- return g.forEach((d, f) => {
1500
- const b = t[f], j = P(b.market), _ = w[j.key] || {};
1501
- d.forEach((k) => {
1502
- if (k.supply_balance === "0" && k.borrow_balance === "0" && (b.emodeId === void 0 || !r?.includeZeroBalanceEmodePositions))
1503
- return;
1504
- const T = c[`${j.key}-${k.asset_id}`];
1505
- if (!T)
1506
- return;
1507
- const $ = _[k.asset_id], D = $?.supplyIndex ?? T.currentSupplyIndex, B = $?.borrowIndex ?? T.currentBorrowIndex, X = me(k.supply_balance, D).toString(), Me = me(k.borrow_balance, B).toString();
1508
- y.push({
1509
- supplyBalance: X,
1510
- borrowBalance: Me,
1511
- assetId: k.asset_id,
1512
- market: j.key,
1513
- pool: T,
1514
- emodeId: b.emodeId
1515
- });
1516
- });
1517
- }), y;
1518
- }
1519
- const ur = O(
1520
- async (e, t) => {
1521
- const o = (t?.markets || Object.keys(L)).map((n) => P(n)).map((n) => ({
1522
- address: e,
1523
- market: n.key
1524
- }));
1525
- return await Ee(e, o, t);
1526
- }
1527
- );
1528
- async function lr(e, t) {
1529
- const r = t?.client ?? U, o = new q();
1530
- await Pt(o, e, t);
1531
- const n = await W(r, {
1532
- transactionBlock: o,
1533
- sender: e
1534
- }), a = Z(n, [l.u256()]);
1535
- return Ae(Number(a[0]) || 0);
1536
- }
1537
- async function dr(e, t, r, o) {
1538
- const n = o?.client ?? U, a = new q();
1539
- let c = 0, i = 0;
1540
- const s = await E(t, o);
1541
- if (r.forEach((g) => {
1542
- g.type === H.Supply ? c += g.amount : g.type === H.Withdraw ? c -= g.amount : g.type === H.Borrow ? i += g.amount : g.type === H.Repay && (i -= g.amount);
1543
- }), c * i < 0)
1544
- throw new Error("Invalid operations");
1545
- const u = c > 0 || i > 0;
1546
- await $e(
1547
- a,
1548
- e,
1549
- s,
1550
- Math.abs(c),
1551
- Math.abs(i),
1552
- u,
1553
- o
1554
- );
1555
- const m = await W(n, {
1556
- transactionBlock: a,
1557
- sender: e
1558
- }), w = Z(m, [l.u256()]);
1559
- return Ae(Number(w[0]) || 0);
1560
- }
1561
- const pr = S(
1562
- async (e, t) => {
1563
- const r = new URLSearchParams();
1564
- t?.cursor && r.set("cursor", t.cursor), r.set("userAddress", e);
1565
- const o = M(t), n = F(
1566
- `/navi/user/transactions?${r.toString()}&sdk=${V.version}`,
1567
- t
1568
- );
1569
- return (await fetch(n, {
1570
- headers: N(R, o)
1571
- }).then((c) => c.json())).data;
1572
- }
1573
- );
1574
- async function mr(e, t) {
1575
- let r = null;
1576
- const o = [], n = t?.client ?? U, a = n.core;
1577
- do {
1578
- let c;
1579
- if (t?.coinType)
1580
- if (typeof a?.listCoins == "function") {
1581
- const i = await a.listCoins({
1582
- owner: e,
1583
- coinType: t?.coinType,
1584
- cursor: r,
1585
- limit: 100
1586
- });
1587
- c = {
1588
- data: (i.objects ?? i.data ?? []).map((s) => ye(s, t?.coinType)).filter(Boolean),
1589
- nextCursor: i.cursor ?? i.nextCursor ?? null,
1590
- hasNextPage: i.hasNextPage ?? !1
1591
- };
1592
- } else {
1593
- if (typeof n.getCoins != "function")
1594
- throw new Error("getCoins requires core.listCoins or an explicit legacy getCoins client");
1595
- c = await n.getCoins({
1596
- owner: e,
1597
- coinType: t?.coinType,
1598
- cursor: r,
1599
- limit: 100
1600
- });
1601
- }
1602
- else if (typeof a?.listBalances == "function" && typeof a?.listCoins == "function") {
1603
- const i = /* @__PURE__ */ new Set();
1604
- let s = null;
1605
- do {
1606
- const u = await a.listBalances({
1607
- owner: e,
1608
- cursor: s,
1609
- limit: 100
1610
- });
1611
- for (const m of u.balances ?? [])
1612
- m?.coinType && i.add(m.coinType);
1613
- s = u.cursor ?? u.nextCursor ?? null;
1614
- } while (s);
1615
- for (const u of i) {
1616
- let m = null;
1617
- do {
1618
- const w = await a.listCoins({
1619
- owner: e,
1620
- coinType: u,
1621
- cursor: m,
1622
- limit: 100
1623
- });
1624
- o.push(
1625
- ...(w.objects ?? w.data ?? []).map((g) => ye(g, u)).filter(Boolean)
1626
- ), m = w.cursor ?? w.nextCursor ?? null;
1627
- } while (m);
1628
- }
1629
- break;
1630
- } else {
1631
- if (typeof n.getAllCoins != "function")
1632
- throw new Error(
1633
- "getCoins requires core.listBalances/core.listCoins or an explicit legacy getAllCoins client"
1634
- );
1635
- c = await n.getAllCoins({
1636
- owner: e,
1637
- cursor: r,
1638
- limit: 100
1639
- });
1640
- }
1641
- if (!c.data || !c.data.length)
1642
- break;
1643
- o.push(...c.data), r = c.nextCursor;
1644
- } while (r);
1645
- return o;
1646
- }
1647
- const At = O(
1648
- async (e, t) => {
1649
- const r = [], o = (t?.markets || Object.keys(L)).map((i) => P(i)), n = await Se(e, t), a = o.map((i) => ({
1650
- address: e,
1651
- market: i.key
1652
- })).concat(
1653
- n.filter((i) => !!o.find((s) => s.id === i.marketId)).map((i) => ({
1654
- address: i.accountCap,
1655
- market: P(i.marketId).key,
1656
- emodeId: i.emodeId
1657
- }))
1658
- );
1659
- return (await Ee(e, a, t)).forEach((i) => {
1660
- const s = typeof i.emodeId == "number" ? n.find((u) => {
1661
- const m = P(i.market);
1662
- return u.emodeId === i.emodeId && u.marketId === m.id;
1663
- }) : void 0;
1664
- if (s) {
1665
- if (!i.pool.emodes.find((m) => m.emodeId === s.emodeId))
1666
- return;
1667
- if (p(i.supplyBalance).gte(0)) {
1668
- const m = p(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN), w = K(i.pool, s);
1669
- if (m.gt(0) || w.emode.isCollateral)
1670
- try {
1671
- r.push({
1672
- id: `${i.pool.uniqueId}_${s.emodeId}_navi-lending-emode-supply-${A()}`,
1673
- wallet: e,
1674
- protocol: "navi",
1675
- market: i.market,
1676
- type: "navi-lending-emode-supply",
1677
- "navi-lending-emode-supply": {
1678
- amount: m.toString(),
1679
- pool: K(i.pool, s),
1680
- token: i.pool.token,
1681
- valueUSD: m.multipliedBy(i.pool.oracle.price).toString(),
1682
- emodeCap: s
1683
- }
1684
- });
1685
- } catch (g) {
1686
- console.error(g);
1687
- }
1688
- }
1689
- if (p(i.borrowBalance).gte(0)) {
1690
- const m = p(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN), w = K(i.pool, s);
1691
- if (m.gt(0) || w.emode.isDebt)
1692
- try {
1693
- r.push({
1694
- id: `${i.pool.uniqueId}_${s.emodeId}_navi-lending-emode-borrow-${A()}`,
1695
- wallet: e,
1696
- protocol: "navi",
1697
- market: i.market,
1698
- type: "navi-lending-emode-borrow",
1699
- "navi-lending-emode-borrow": {
1700
- amount: m.toString(),
1701
- pool: K(i.pool, s),
1702
- token: i.pool.token,
1703
- valueUSD: m.multipliedBy(i.pool.oracle.price).toString(),
1704
- emodeCap: s
1705
- }
1706
- });
1707
- } catch (g) {
1708
- console.error(g);
1709
- }
1710
- }
1711
- } else {
1712
- if (p(i.supplyBalance).gt(0)) {
1713
- const u = p(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN);
1714
- r.push({
1715
- id: `${i.pool.uniqueId}_navi-lending-supply-${A()}`,
1716
- wallet: e,
1717
- protocol: "navi",
1718
- type: "navi-lending-supply",
1719
- market: i.market,
1720
- "navi-lending-supply": {
1721
- amount: u.toString(),
1722
- pool: i.pool,
1723
- token: i.pool.token,
1724
- valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
1725
- }
1726
- });
1727
- }
1728
- if (p(i.borrowBalance).gt(0)) {
1729
- const u = p(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN);
1730
- r.push({
1731
- id: `${i.pool.uniqueId}_navi-lending-borrow-${A()}`,
1732
- wallet: e,
1733
- protocol: "navi",
1734
- market: i.market,
1735
- type: "navi-lending-borrow",
1736
- "navi-lending-borrow": {
1737
- amount: u.toString(),
1738
- pool: i.pool,
1739
- token: i.pool.token,
1740
- valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
1741
- }
1742
- });
1743
- }
1744
- }
1745
- }), r;
1746
- }
1747
- );
1748
- class G {
1749
- constructor(t, r) {
1750
- this._positions = [], this._priceMap = {}, this._overview = {
1751
- hf: 1 / 0,
1752
- netVaule: "0",
1753
- netWorthApr: "0",
1754
- totalSupplyValue: "0",
1755
- totalBorrowValue: "0",
1756
- totalsupplyApy: "0",
1757
- totalBorrowApy: "0",
1758
- maxLiquidationValue: "0",
1759
- maxLoanToVaule: "0",
1760
- supply: {},
1761
- borrow: {}
1762
- }, this._priceMap = r || {}, this.positions = t;
1763
- }
1764
- get positions() {
1765
- return this._positions;
1766
- }
1767
- get overview() {
1768
- return this._overview;
1769
- }
1770
- get priceMap() {
1771
- return this._priceMap;
1772
- }
1773
- set positions(t) {
1774
- this._positions = t, this._overview = this.getPositionsOverview(t);
1775
- }
1776
- updatePriceMap(t) {
1777
- return this._priceMap = t, this._overview = this.getPositionsOverview(this._positions), this;
1778
- }
1779
- getPrice(t) {
1780
- const r = C(t.suiCoinType);
1781
- if (this._priceMap[r] !== void 0)
1782
- return this._priceMap[r].toString();
1783
- const o = t.suiCoinType;
1784
- return this._priceMap[o] !== void 0 ? this._priceMap[o].toString() : t.oracle.price;
1785
- }
1786
- filterPositionsByPool(t) {
1787
- const o = !!t.isEMode ? ["navi-lending-emode-supply", "navi-lending-emode-borrow"] : ["navi-lending-supply", "navi-lending-borrow"];
1788
- return new G(
1789
- this.positions.filter((n) => {
1790
- const a = n[n.type];
1791
- return o.includes(n.type) && a.pool.uniqueId === t.uniqueId;
1792
- }),
1793
- this._priceMap
1794
- );
1795
- }
1796
- deposit(t, r) {
1797
- const o = !!t.isEMode, n = this.getPrice(t);
1798
- let a;
1799
- return o ? a = {
1800
- id: A(),
1801
- wallet: "",
1802
- protocol: "navi",
1803
- market: "",
1804
- type: "navi-lending-emode-supply",
1805
- "navi-lending-emode-supply": {
1806
- amount: r.toString(),
1807
- valueUSD: p(r).multipliedBy(n).toString(),
1808
- token: t.token,
1809
- pool: t,
1810
- emodeCap: {}
1811
- }
1812
- } : a = {
1813
- id: A(),
1814
- wallet: "",
1815
- protocol: "navi",
1816
- market: "",
1817
- type: "navi-lending-supply",
1818
- "navi-lending-supply": {
1819
- amount: r.toString(),
1820
- valueUSD: p(r).multipliedBy(n).toString(),
1821
- token: t.token,
1822
- pool: t
1823
- }
1824
- }, new G([...this.positions, a], this._priceMap);
1825
- }
1826
- withdraw(t, r) {
1827
- const o = !!t.isEMode, n = this.getPrice(t);
1828
- let a;
1829
- return o ? a = {
1830
- id: A(),
1831
- wallet: "",
1832
- protocol: "navi",
1833
- market: "",
1834
- type: "navi-lending-emode-supply",
1835
- "navi-lending-emode-supply": {
1836
- amount: (-r).toString(),
1837
- valueUSD: p(-r).multipliedBy(n).toString(),
1838
- token: t.token,
1839
- pool: t,
1840
- emodeCap: {}
1841
- }
1842
- } : a = {
1843
- id: A(),
1844
- wallet: "",
1845
- protocol: "navi",
1846
- market: "",
1847
- type: "navi-lending-supply",
1848
- "navi-lending-supply": {
1849
- amount: (-r).toString(),
1850
- valueUSD: p(-r).multipliedBy(n).toString(),
1851
- token: t.token,
1852
- pool: t
1853
- }
1854
- }, new G([...this.positions, a], this._priceMap);
1855
- }
1856
- borrow(t, r) {
1857
- const o = !!t.isEMode, n = this.getPrice(t);
1858
- let a;
1859
- return o ? a = {
1860
- id: A(),
1861
- wallet: "",
1862
- protocol: "navi",
1863
- market: "",
1864
- type: "navi-lending-emode-borrow",
1865
- "navi-lending-emode-borrow": {
1866
- amount: r.toString(),
1867
- valueUSD: p(r).multipliedBy(n).toString(),
1868
- token: t.token,
1869
- pool: t,
1870
- emodeCap: {}
1871
- }
1872
- } : a = {
1873
- id: A(),
1874
- wallet: "",
1875
- protocol: "navi",
1876
- market: "",
1877
- type: "navi-lending-borrow",
1878
- "navi-lending-borrow": {
1879
- amount: r.toString(),
1880
- valueUSD: p(r).multipliedBy(n).toString(),
1881
- token: t.token,
1882
- pool: t
1883
- }
1884
- }, new G([...this.positions, a], this._priceMap);
1885
- }
1886
- repay(t, r) {
1887
- const o = !!t.isEMode, n = this.getPrice(t);
1888
- let a;
1889
- return o ? a = {
1890
- id: A(),
1891
- wallet: "",
1892
- protocol: "navi",
1893
- market: "",
1894
- type: "navi-lending-emode-borrow",
1895
- "navi-lending-emode-borrow": {
1896
- amount: (-r).toString(),
1897
- valueUSD: p(-r).multipliedBy(n).toString(),
1898
- token: t.token,
1899
- pool: t,
1900
- emodeCap: {}
1901
- }
1902
- } : a = {
1903
- id: A(),
1904
- wallet: "",
1905
- protocol: "navi",
1906
- market: "",
1907
- type: "navi-lending-borrow",
1908
- "navi-lending-borrow": {
1909
- amount: (-r).toString(),
1910
- valueUSD: p(-r).multipliedBy(n).toString(),
1911
- token: t.token,
1912
- pool: t
1913
- }
1914
- }, new G([...this.positions, a], this._priceMap);
1915
- }
1916
- resolveValueUSD(t) {
1917
- return Object.keys(this._priceMap).length > 0 ? p(t.amount).multipliedBy(this.getPrice(t.pool)).toString() : t.valueUSD;
1918
- }
1919
- getPositionsOverview(t) {
1920
- const r = {}, o = {};
1921
- let n = new p(0), a = new p(0), c = new p(0), i = new p(0), s = new p(0), u = new p(0);
1922
- t.forEach((y) => {
1923
- if (y.type === "navi-lending-supply") {
1924
- const d = y["navi-lending-supply"], f = this.resolveValueUSD(d);
1925
- n = n.plus(f), s = s.plus(
1926
- new p(f).multipliedBy(d.pool.liquidationFactor.threshold)
1927
- ), u = u.plus(
1928
- new p(f).multipliedBy(d.pool.ltvValue)
1929
- );
1930
- } else if (y.type === "navi-lending-borrow") {
1931
- const d = y["navi-lending-borrow"];
1932
- a = a.plus(this.resolveValueUSD(d));
1933
- } else if (y.type === "navi-lending-emode-supply") {
1934
- const d = y["navi-lending-emode-supply"], f = this.resolveValueUSD(d);
1935
- n = n.plus(f);
1936
- const b = d.pool.emode;
1937
- s = s.plus(
1938
- new p(f).multipliedBy(b.lt)
1939
- ), u = u.plus(
1940
- new p(f).multipliedBy(b.ltv)
1941
- );
1942
- } else if (y.type === "navi-lending-emode-borrow") {
1943
- const d = y["navi-lending-emode-borrow"];
1944
- a = a.plus(this.resolveValueUSD(d));
1945
- }
1946
- }), a = p.max(a, 0), n = p.max(n, 0), s = p.max(s, 0), u = p.max(u, 0), t.forEach((y) => {
1947
- if (y.type === "navi-lending-supply") {
1948
- const d = y["navi-lending-supply"], f = this.resolveValueUSD(d), b = d.pool.supplyIncentiveApyInfo.apy;
1949
- n.gt(0) && (c = c.plus(
1950
- new p(f).dividedBy(n).multipliedBy(new p(b).dividedBy(100))
1951
- )), r[d.pool.suiCoinType] = p(r[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1952
- } else if (y.type === "navi-lending-borrow") {
1953
- const d = y["navi-lending-borrow"], f = this.resolveValueUSD(d), b = d.pool.borrowIncentiveApyInfo.apy;
1954
- a.gt(0) && (i = i.plus(
1955
- new p(f).dividedBy(a).multipliedBy(new p(b).dividedBy(100))
1956
- )), o[d.pool.suiCoinType] = p(o[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1957
- } else if (y.type === "navi-lending-emode-supply") {
1958
- const d = y["navi-lending-emode-supply"], f = this.resolveValueUSD(d), b = d.pool.supplyIncentiveApyInfo.apy;
1959
- n.gt(0) && (c = c.plus(
1960
- new p(f).dividedBy(n).multipliedBy(new p(b).dividedBy(100))
1961
- )), r[d.pool.suiCoinType] = p(r[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1962
- } else if (y.type === "navi-lending-emode-borrow") {
1963
- const d = y["navi-lending-emode-borrow"], f = this.resolveValueUSD(d), b = d.pool.borrowIncentiveApyInfo.apy;
1964
- a.gt(0) && (i = i.plus(
1965
- new p(f).dividedBy(a).multipliedBy(new p(b).dividedBy(100))
1966
- )), o[d.pool.suiCoinType] = p(o[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1967
- }
1968
- });
1969
- const m = n.minus(a), w = n.minus(a).eq(0) ? new p(0) : n.multipliedBy(c).minus(a.multipliedBy(i)).div(n.minus(a));
1970
- return {
1971
- hf: a.toNumber() !== 0 ? s.dividedBy(a).toNumber() : 1 / 0,
1972
- netVaule: m.toString(),
1973
- netWorthApr: w.toString(),
1974
- totalSupplyValue: n.toString(),
1975
- totalBorrowValue: a.toString(),
1976
- totalsupplyApy: c.toString(),
1977
- totalBorrowApy: i.toString(),
1978
- maxLiquidationValue: s.toString(),
1979
- maxLoanToVaule: u.toString(),
1980
- supply: r,
1981
- borrow: o
1982
- };
1983
- }
1984
- }
1985
- async function fr(e, t, r, o) {
1986
- const n = await I({
1987
- ...o,
1988
- cacheTime: v
1989
- });
1990
- n.limter && e.moveCall({
1991
- target: `${n.limter}::navi_adaptor::verify_navi_position_healthy`,
1992
- arguments: [
1993
- e.object("0x06"),
1994
- e.object(n.storage),
1995
- e.object(n.priceOracle),
1996
- h(t, e.pure.address),
1997
- e.pure.u256(new p(r).shiftedBy(27).toNumber())
1998
- ]
1999
- });
2000
- }
2001
- const ge = /* @__PURE__ */ new Map(), Oe = (e) => {
2002
- const t = e ?? "https://hermes.pyth.network";
2003
- let r = ge.get(t);
2004
- return r || (r = new ke(t, { timeout: 1e4 }), ge.set(t, r)), r;
2005
- };
2006
- async function yr(e, t) {
2007
- try {
2008
- const r = [], o = await I({ ...t, cacheTime: v }), n = await Oe(
2009
- o.oracle.hermesEndpoint
2010
- ).getLatestPriceFeeds(e);
2011
- if (!n) return r;
2012
- const a = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2013
- for (const c of n) {
2014
- const i = c.getPriceUnchecked();
2015
- if (i.publishTime > a) {
2016
- console.warn(
2017
- `pyth price feed is invalid, id: ${c.id}, publish time: ${i.publishTime}, current timestamp: ${a}`
2018
- );
2019
- continue;
2020
- }
2021
- a - c.getPriceUnchecked().publishTime > 30 && (console.info(
2022
- `stale price feed, id: ${c.id}, publish time: ${i.publishTime}, current timestamp: ${a}`
2023
- ), r.push(c.id));
2024
- }
2025
- return r;
2026
- } catch (r) {
2027
- throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`);
2028
- }
2029
- }
2030
- async function St(e, t) {
2031
- const r = [], o = t?.client ?? U, n = e.map((c) => c.priceInfoObject), a = await ht(o, {
2032
- ids: Array.from(new Set(n)),
2033
- options: { showContent: !0 }
2034
- });
2035
- for (const c of a) {
2036
- const i = c.data;
2037
- if (!i || !i.content || i.content.dataType !== "moveObject") {
2038
- console.warn(`fetched object ${i?.objectId} datatype should be moveObject`);
2039
- continue;
2040
- }
2041
- const s = e.find((f) => f.priceInfoObject == i.objectId);
2042
- if (!s) {
2043
- console.warn(`unable to find pyth info from array, priceInfoObject: ${i.objectId}`);
2044
- continue;
2045
- }
2046
- const u = i.content.fields?.price_info?.price_feed?.price, m = u?.price;
2047
- if (!m) {
2048
- console.warn(`unexpected pyth price struct, priceInfoObject: ${i.objectId}`);
2049
- continue;
2050
- }
2051
- const { magnitude: w, negative: g } = m, y = u.conf, d = u.timestamp;
2052
- r.push({
2053
- priceFeedId: s.priceFeedId,
2054
- priceInfoObject: s.priceInfoObject,
2055
- price: g ? "-" + w : w,
2056
- conf: y,
2057
- publishTime: Number(d),
2058
- expiration: s.expiration
2059
- });
2060
- }
2061
- return r;
2062
- }
2063
- async function $t(e, t) {
2064
- try {
2065
- const r = [], o = await St(e, t);
2066
- if (!o) return r;
2067
- const n = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2068
- for (const a of o) {
2069
- if (a.publishTime > n) {
2070
- console.warn(
2071
- `pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2072
- );
2073
- continue;
2074
- }
2075
- const c = a.expiration || 60;
2076
- n - a.publishTime > c && (console.info(
2077
- `stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2078
- ), r.push(a.priceFeedId));
2079
- }
2080
- return r;
2081
- } catch (r) {
2082
- throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`);
2083
- }
2084
- }
2085
- async function Et(e, t, r) {
2086
- const o = r?.client ?? U, n = await I({
2087
- ...r,
2088
- cacheTime: v
2089
- });
2090
- try {
2091
- const a = await Oe(
2092
- n.oracle.hermesEndpoint
2093
- ).getPriceFeedsUpdateData(t);
2094
- return await new dt(
2095
- o,
2096
- n.oracle.pythStateId,
2097
- n.oracle.wormholeStateId
2098
- ).updatePriceFeeds(e, a, t);
2099
- } catch (a) {
2100
- throw new Error(`failed to update pyth price feeds, msg: ${a.message}`);
2101
- }
2102
- }
2103
- async function he(e, t, r) {
2104
- const o = await I({
2105
- ...r,
2106
- cacheTime: v
2107
- });
2108
- if (r?.updatePythPriceFeeds) {
2109
- const n = t.filter((c) => !!c.pythPriceFeedId && !!c.pythPriceInfoObject).map((c) => ({
2110
- priceFeedId: c.pythPriceFeedId,
2111
- priceInfoObject: c.pythPriceInfoObject,
2112
- expiration: 30
2113
- })), a = await $t(n, r);
2114
- a.length > 0 && await Et(e, a, r);
2115
- }
2116
- for (const n of t)
2117
- e.moveCall({
2118
- target: `${o.oracle.packageId}::oracle_pro::${o.oracle.updateFunction ?? "update_single_price_v2"}`,
2119
- arguments: [
2120
- e.object("0x6"),
2121
- // Clock object
2122
- e.object(o.oracle.oracleConfig),
2123
- // Oracle configuration
2124
- e.object(o.oracle.priceOracle),
2125
- // Price oracle contract
2126
- e.object(o.oracle.supraOracleHolder),
2127
- // Supra oracle holder
2128
- e.object(n.pythPriceInfoObject),
2129
- // Pyth price info object
2130
- e.object(o.oracle.switchboardAggregator),
2131
- e.pure.address(n.feedId)
2132
- // Price feed ID
2133
- ]
2134
- });
2135
- return e;
2136
- }
2137
- async function Ve(e) {
2138
- return (await I({
2139
- ...e,
2140
- cacheTime: v
2141
- })).oracle.feeds;
2142
- }
2143
- function Ot(e, t) {
2144
- return e.filter((r) => !!(t?.lendingState && t.lendingState.find((n) => r.oracleId === n.pool.oracleId) || t?.lendingPositions && t.lendingPositions.find((n) => {
2145
- if (![
2146
- "navi-lending-supply",
2147
- "navi-lending-borrow",
2148
- "navi-lending-emode-supply",
2149
- "navi-lending-emode-borrow"
2150
- ].includes(n.type))
2151
- return !1;
2152
- const c = n[n.type]?.pool;
2153
- return r.oracleId === c?.oracleId;
2154
- }) || t?.pools && t.pools.find((n) => r.oracleId === n.oracleId)));
2155
- }
2156
- async function gr(e, t, r, o) {
2157
- let n;
2158
- try {
2159
- const a = await Ve({
2160
- ...o
2161
- }), c = [];
2162
- r.forEach((u) => {
2163
- c.includes(u.market) || c.push(u.market);
2164
- });
2165
- const i = await At(t, {
2166
- ...o,
2167
- markets: c
2168
- });
2169
- return n = Ot(a, {
2170
- lendingPositions: i,
2171
- pools: r
2172
- }), await he(e, n, {
2173
- updatePythPriceFeeds: !0,
2174
- ...o
2175
- });
2176
- } catch (a) {
2177
- if (o?.throws)
2178
- throw a;
2179
- if (console.error(a), n)
2180
- try {
2181
- return await he(e, n, {
2182
- ...o,
2183
- updatePythPriceFeeds: !1
2184
- });
2185
- } catch (c) {
2186
- console.error(c);
2187
- }
2188
- return e;
2189
- }
2190
- }
2191
- const ae = O(
2192
- S(
2193
- async (e) => {
2194
- const t = M(e), r = F(
2195
- `/navi/flashloan?env=${e?.env || "prod"}&sdk=${V.version}&market=${e?.market || z}`,
2196
- e
2197
- ), o = await fetch(r, {
2198
- headers: N(R, t)
2199
- }).then((n) => n.json());
2200
- return Object.keys(o.data).map((n) => ({
2201
- ...o.data[n],
2202
- coinType: n
2203
- }));
2204
- }
2205
- )
2206
- );
2207
- async function hr(e, t) {
2208
- return (await ae(t)).find((o) => typeof e == "string" ? C(o.coinType) === C(e) : typeof e == "number" ? o.assetId === e : o.assetId === e.id) || null;
2209
- }
2210
- async function wr(e, t, r, o) {
2211
- const n = await I({
2212
- ...o,
2213
- cacheTime: v
2214
- }), a = await E(t, o);
2215
- if (!(await ae({
2216
- ...o,
2217
- cacheTime: v
2218
- })).some(
2219
- (s) => C(s.coinType) === C(a.suiCoinType)
2220
- ))
2221
- throw new Error("Pool does not support flashloan");
2222
- if (n.version === 1) {
2223
- const [s, u] = e.moveCall({
2224
- target: `${n.package}::lending::flash_loan_with_ctx`,
2225
- arguments: [
2226
- e.object(n.flashloanConfig),
2227
- e.object(a.contract.pool),
2228
- h(r, e.pure.u64)
2229
- ],
2230
- typeArguments: [a.suiCoinType]
2231
- });
2232
- return [s, u];
2233
- } else {
2234
- const [s, u] = e.moveCall({
2235
- target: `${n.package}::lending::flash_loan_with_ctx_v2`,
2236
- arguments: [
2237
- e.object(n.flashloanConfig),
2238
- e.object(a.contract.pool),
2239
- h(r, e.pure.u64),
2240
- e.object("0x05")
2241
- ],
2242
- typeArguments: [a.suiCoinType]
2243
- });
2244
- return [s, u];
2245
- }
2246
- }
2247
- async function br(e, t, r, o, n) {
2248
- const a = await I({
2249
- ...n,
2250
- cacheTime: v
2251
- }), c = await E(t, n);
2252
- if (!(await ae({
2253
- ...n,
2254
- cacheTime: v
2255
- })).some(
2256
- (m) => C(m.coinType) === C(c.suiCoinType)
2257
- ))
2258
- throw new Error("Pool does not support flashloan");
2259
- const [u] = e.moveCall({
2260
- target: `${a.package}::lending::flash_repay_with_ctx`,
2261
- arguments: [
2262
- e.object("0x06"),
2263
- e.object(a.storage),
2264
- e.object(c.contract.pool),
2265
- h(r, e.object),
2266
- h(o, e.object)
2267
- ],
2268
- typeArguments: [c.suiCoinType]
2269
- });
2270
- return [u];
2271
- }
2272
- async function vr(e, t, r, o, n, a) {
2273
- const c = {
2274
- ...a,
2275
- cacheTime: v
2276
- }, i = await I(c), s = await E(t, c), u = await E(o, c);
2277
- if (i.version === 1) {
2278
- const [m, w] = e.moveCall({
2279
- target: `${i.package}::incentive_v3::liquidation`,
2280
- arguments: [
2281
- e.object("0x06"),
2282
- // Clock object
2283
- e.object(i.priceOracle),
2284
- // Price oracle for asset pricing
2285
- e.object(i.storage),
2286
- // Protocol storage
2287
- e.pure.u8(s.id),
2288
- // Pay asset ID
2289
- e.object(s.contract.pool),
2290
- // Pay asset pool contract
2291
- h(r, e.object),
2292
- // Debt repayment amount
2293
- e.pure.u8(u.id),
2294
- // Collateral asset ID
2295
- e.object(u.contract.pool),
2296
- // Collateral asset pool contract
2297
- h(n, e.pure.address),
2298
- // Borrower address
2299
- e.object(i.incentiveV2),
2300
- // Incentive V2 contract
2301
- e.object(i.incentiveV3)
2302
- // Incentive V3 contract
2303
- ],
2304
- typeArguments: [s.suiCoinType, u.suiCoinType]
2305
- });
2306
- return [m, w];
2307
- } else {
2308
- const [m, w] = e.moveCall({
2309
- target: `${i.package}::incentive_v3::liquidation_v2`,
2310
- arguments: [
2311
- e.object("0x06"),
2312
- // Clock object
2313
- e.object(i.priceOracle),
2314
- // Price oracle for asset pricing
2315
- e.object(i.storage),
2316
- // Protocol storage
2317
- e.pure.u8(s.id),
2318
- // Pay asset ID
2319
- e.object(s.contract.pool),
2320
- // Pay asset pool contract
2321
- h(r, e.object),
2322
- // Debt repayment amount
2323
- e.pure.u8(u.id),
2324
- // Collateral asset ID
2325
- e.object(u.contract.pool),
2326
- // Collateral asset pool contract
2327
- h(n, e.pure.address),
2328
- // Borrower address
2329
- e.object(i.incentiveV2),
2330
- // Incentive V2 contract
2331
- e.object(i.incentiveV3),
2332
- // Incentive V3 contract
2333
- e.object("0x05")
2334
- // SuiSystemState object
2335
- ],
2336
- typeArguments: [s.suiCoinType, u.suiCoinType]
2337
- });
2338
- return [m, w];
2339
- }
2340
- }
2341
- async function Vt(e, t, r) {
2342
- const o = r?.client ?? U, n = await J({
2343
- ...r,
2344
- markets: Object.values(L),
2345
- cacheTime: v
2346
- }), a = await Ve(r), c = [];
2347
- return await Promise.all(
2348
- t.map(async (i) => {
2349
- try {
2350
- const s = await I({
2351
- ...r,
2352
- cacheTime: v,
2353
- market: i.market
2354
- }), u = new q();
2355
- u.moveCall({
2356
- target: `${s.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
2357
- arguments: [
2358
- u.object("0x06"),
2359
- // Clock object
2360
- u.object(s.storage),
2361
- // Protocol storage
2362
- u.object(s.incentiveV3),
2363
- // Incentive V3 contract
2364
- u.pure.address(i.address)
2365
- // User address
2366
- ]
2367
- });
2368
- const w = (await W(o, {
2369
- transactionBlock: u,
2370
- sender: e
2371
- }))?.results?.[0];
2372
- if (!w)
2373
- return;
2374
- const g = Z({ results: [w] }, [
2375
- l.vector(l.string()),
2376
- // Asset coin types
2377
- l.vector(l.string()),
2378
- // Reward coin types
2379
- l.vector(l.u8()),
2380
- // Reward options
2381
- l.vector(l.Address),
2382
- // Rule IDs
2383
- l.vector(l.u256())
2384
- // Claimable amounts
2385
- ]);
2386
- if (g.length === 5 && Array.isArray(g[0])) {
2387
- const y = g[0].length;
2388
- for (let d = 0; d < y; d++) {
2389
- const f = a.find(
2390
- (j) => C(j.coinType) === C(g[1][d])
2391
- ), b = n.find(
2392
- (j) => C(j.coinType) === C(g[0][d]) && j.market === i.market
2393
- );
2394
- !f || !b || c.push({
2395
- assetId: b.id,
2396
- assetCoinType: C(g[0][d]),
2397
- rewardCoinType: C(g[1][d]),
2398
- option: Number(g[2][d]),
2399
- userClaimableReward: Number(g[4][d]) / Math.pow(10, f.priceDecimal),
2400
- ruleIds: Array.isArray(g[3][d]) ? g[3][d] : [g[3][d]],
2401
- market: i.market,
2402
- owner: i.owner,
2403
- address: i.address,
2404
- emodeId: i.emodeId
2405
- });
2406
- }
2407
- }
2408
- } catch (s) {
2409
- console.error(
2410
- `[lending] getLendingRewardsBatch task failed (market=${i.market}, address=${i.address}):`,
2411
- s
2412
- );
2413
- }
2414
- })
2415
- ), c;
2416
- }
2417
- async function Cr(e, t) {
2418
- const r = (t?.markets || [L.main]).map((a) => P(a)), o = await Se(e, t), n = r.map((a) => ({
2419
- address: e,
2420
- owner: e,
2421
- market: a.key
2422
- })).concat(
2423
- o.filter((a) => !!r.find((c) => c.id === a.marketId)).map((a) => {
2424
- const c = P(a.marketId);
2425
- return {
2426
- address: a.accountCap,
2427
- owner: e,
2428
- market: c.key,
2429
- emodeId: a.emodeId
2430
- };
2431
- })
2432
- );
2433
- return await Vt(e, n, t);
2434
- }
2435
- function jr(e) {
2436
- const t = /* @__PURE__ */ new Map();
2437
- e.forEach((o) => {
2438
- const n = o.assetId, a = o.option, c = `${n}-${a}-${o.rewardCoinType}-${o.market}`;
2439
- t.has(c) ? t.get(c).total += o.userClaimableReward : t.set(c, {
2440
- assetId: n,
2441
- rewardType: a,
2442
- coinType: o.rewardCoinType,
2443
- total: Number(o.userClaimableReward),
2444
- market: o.market
2445
- });
2446
- });
2447
- const r = /* @__PURE__ */ new Map();
2448
- for (const { assetId: o, rewardType: n, coinType: a, total: c, market: i } of t.values()) {
2449
- const s = `${o}-${n}-${i}`;
2450
- r.has(s) || r.set(s, { assetId: o, rewardType: n, market: i, rewards: /* @__PURE__ */ new Map() });
2451
- const u = r.get(s);
2452
- u.rewards.set(a, (u.rewards.get(a) || 0) + c);
2453
- }
2454
- return Array.from(r.values()).map((o) => ({
2455
- assetId: o.assetId,
2456
- rewardType: o.rewardType,
2457
- market: o.market,
2458
- rewards: Array.from(o.rewards.entries()).map(([n, a]) => ({
2459
- coinType: n,
2460
- available: a.toFixed(6)
2461
- }))
2462
- }));
2463
- }
2464
- const Ir = S(
2465
- async (e, t) => {
2466
- const r = M(t), o = F(
2467
- `/navi/user/total_claimed_reward?userAddress=${e}&sdk=${V.version}&market=${t?.market || z}`,
2468
- t
2469
- );
2470
- return (await fetch(o, {
2471
- headers: N(R, r)
2472
- }).then((a) => a.json())).data;
2473
- }
2474
- ), kr = S(
2475
- async (e, t) => {
2476
- const r = M(t), o = F(
2477
- `/navi/user/rewards?userAddress=${e}&page=${t?.page || 1}&pageSize=${t?.size || 400}&sdk=${V.version}&market=${t?.market || z}`,
2478
- t
2479
- ), n = await fetch(o, {
2480
- headers: N(R, r)
2481
- }).then((a) => a.json());
2482
- return re({
2483
- data: n.data.rewards
2484
- });
2485
- }
2486
- );
2487
- async function _r(e, t, r) {
2488
- const o = await J({
2489
- ...r,
2490
- markets: Object.values(L),
2491
- cacheTime: v
2492
- }), n = /* @__PURE__ */ new Map();
2493
- for (const c of t) {
2494
- const { rewardCoinType: i, ruleIds: s, market: u, owner: m, address: w, emodeId: g } = c, y = `${i}___${w}__${u}`;
2495
- for (const d of s) {
2496
- n.has(y) || n.set(y, {
2497
- assetIds: [],
2498
- ruleIds: [],
2499
- amount: 0,
2500
- market: u,
2501
- owner: m,
2502
- address: w,
2503
- isEMode: typeof g < "u"
2504
- });
2505
- const f = n.get(y);
2506
- f.assetIds.push(c.assetCoinType.replace("0x", "")), f.ruleIds.push(d), f.amount += c.userClaimableReward;
2507
- }
2508
- }
2509
- const a = [];
2510
- for (const [
2511
- c,
2512
- { assetIds: i, ruleIds: s, amount: u, market: m, owner: w, address: g, isEMode: y }
2513
- ] of n) {
2514
- const d = await I({
2515
- ...r,
2516
- cacheTime: v,
2517
- market: m
2518
- }), f = c.split("___")[0], b = o.filter(
2519
- (k) => C(k.suiCoinType) === C(f)
2520
- );
2521
- b.sort((k, T) => k.market === m ? -1 : 1);
2522
- const j = b[0], _ = d.rewardFunds[C(f)];
2523
- if (!_)
2524
- throw new Error(`No matching rewardFund found for reward coin: ${f} ${m}`);
2525
- if (r?.accountCap && !r.customCoinReceive)
2526
- throw new Error("customCoinReceive is required when accountCap is provided");
2527
- if (r?.customCoinReceive) {
2528
- let k;
2529
- r.accountCap ? k = e.moveCall({
2530
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2531
- arguments: [
2532
- e.object("0x06"),
2533
- // Clock object
2534
- e.object(d.incentiveV3),
2535
- // Incentive V3 contract
2536
- e.object(d.storage),
2537
- // Protocol storage
2538
- e.object(_),
2539
- // Reward fund
2540
- e.pure.vector("string", i),
2541
- // Asset IDs
2542
- e.pure.vector("address", s),
2543
- // Rule IDs
2544
- h(r.accountCap, e.object)
2545
- // Account capability
2546
- ],
2547
- typeArguments: [f]
2548
- }) : y ? k = e.moveCall({
2549
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2550
- arguments: [
2551
- e.object("0x06"),
2552
- // Clock object
2553
- e.object(d.incentiveV3),
2554
- // Incentive V3 contract
2555
- e.object(d.storage),
2556
- // Protocol storage
2557
- e.object(_),
2558
- // Reward fund
2559
- e.pure.vector("string", i),
2560
- // Asset IDs
2561
- e.pure.vector("address", s),
2562
- // Rule IDs
2563
- h(g, e.object)
2564
- // Account capability
2565
- ],
2566
- typeArguments: [f]
2567
- }) : k = e.moveCall({
2568
- target: `${d.package}::incentive_v3::claim_reward`,
2569
- arguments: [
2570
- e.object("0x06"),
2571
- // Clock object
2572
- e.object(d.incentiveV3),
2573
- // Incentive V3 contract
2574
- e.object(d.storage),
2575
- // Protocol storage
2576
- e.object(_),
2577
- // Reward fund
2578
- e.pure.vector("string", i),
2579
- // Asset IDs
2580
- e.pure.vector("address", s)
2581
- // Rule IDs
2582
- ],
2583
- typeArguments: [f]
2584
- });
2585
- const [T] = e.moveCall({
2586
- target: "0x2::coin::from_balance",
2587
- arguments: [k],
2588
- typeArguments: [f]
2589
- });
2590
- if (r?.customCoinReceive.type === "transfer") {
2591
- if (!r.customCoinReceive.transfer)
2592
- throw new Error("customCoinReceive.transfer is required");
2593
- e.transferObjects(
2594
- [T],
2595
- h(r.customCoinReceive.transfer, e.pure.address)
2596
- );
2597
- }
2598
- if (r?.customCoinReceive.type === "depositNAVI") {
2599
- const $ = p(j.totalSupplyAmount).shiftedBy(-9), D = p(j.supplyCapCeiling).shiftedBy(-27);
2600
- $.plus(u).isGreaterThan(D) && r?.customCoinReceive.depositNAVI?.fallbackReceiveAddress ? e.transferObjects(
2601
- [T],
2602
- e.pure.address(r.customCoinReceive.depositNAVI.fallbackReceiveAddress)
2603
- ) : await Ct(e, j, T, {
2604
- ...r,
2605
- market: j.market
2606
- });
2607
- } else
2608
- a.push({
2609
- coin: T,
2610
- identifier: j,
2611
- owner: w,
2612
- isEMode: y
2613
- });
2614
- } else if (r?.accountCap || y) {
2615
- const k = e.moveCall({
2616
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2617
- arguments: [
2618
- e.object("0x06"),
2619
- // Clock object
2620
- e.object(d.incentiveV3),
2621
- // Incentive V3 contract
2622
- e.object(d.storage),
2623
- // Protocol storage
2624
- e.object(_),
2625
- // Reward fund
2626
- e.pure.vector("string", i),
2627
- // Asset IDs
2628
- e.pure.vector("address", s),
2629
- // Rule IDs
2630
- h(r?.accountCap || g, e.object)
2631
- // Account capability
2632
- ],
2633
- typeArguments: [f]
2634
- }), [T] = e.moveCall({
2635
- target: "0x2::coin::from_balance",
2636
- arguments: [k],
2637
- typeArguments: [f]
2638
- });
2639
- e.transferObjects(
2640
- [T],
2641
- h(r?.accountCap || w, e.pure.address)
2642
- );
2643
- } else
2644
- e.moveCall({
2645
- target: `${d.package}::incentive_v3::claim_reward_entry`,
2646
- arguments: [
2647
- e.object("0x06"),
2648
- // Clock object
2649
- e.object(d.incentiveV3),
2650
- // Incentive V3 contract
2651
- e.object(d.storage),
2652
- // Protocol storage
2653
- e.object(_),
2654
- // Reward fund
2655
- e.pure.vector("string", i),
2656
- // Asset IDs
2657
- e.pure.vector("address", s)
2658
- // Rule IDs
2659
- ],
2660
- typeArguments: [f]
2661
- });
2662
- }
2663
- return a;
2664
- }
2665
- export {
2666
- ie as Address,
2667
- v as DEFAULT_CACHE_TIME,
2668
- z as DEFAULT_MARKET_IDENTITY,
2669
- Ht as FlashLoanAssetConfig,
2670
- zt as IncentiveAPYInfo,
2671
- qe as IncentivePoolInfo,
2672
- Gt as IncentivePoolInfoByPhase,
2673
- L as MARKETS,
2674
- jt as Market,
2675
- Qe as NaviMissingGraphQLClientError,
2676
- Wt as OracleInfo,
2677
- tt as PUBLIC_MAINNET_GRPC_URL,
2678
- H as PoolOperator,
2679
- ze as ReserveDataInfo,
2680
- ke as SuiPriceServiceConnection,
2681
- dt as SuiPythClient,
2682
- G as UserPositions,
2683
- Ge as UserStateInfo,
2684
- tr as borrowCoinPTB,
2685
- F as buildNaviOpenApiUrl,
2686
- _r as claimLendingRewardsPTB,
2687
- Zt as configureNaviSdk,
2688
- kt as createAccountCapPTB,
2689
- ir as createEModeCapPTB,
2690
- Ie as createNaviLegacyJsonRpcClient,
2691
- nt as createNaviSuiClient,
2692
- et as createNaviSuiClientBundle,
2693
- Ct as depositCoinPTB,
2694
- cr as emodeIdentityId,
2695
- Tt as enterEModePTB,
2696
- ar as exitEModePTB,
2697
- Ot as filterPriceFeeds,
2698
- wr as flashloanPTB,
2699
- _t as getAccountCapOwnerPTB,
2700
- Kt as getAddressBalance,
2701
- ae as getAllFlashLoanAssets,
2702
- nr as getBorrowFee,
2703
- Jt as getCoinObjectOnlyBalance,
2704
- mr as getCoins,
2705
- I as getConfig,
2706
- xt as getFees,
2707
- hr as getFlashLoanAsset,
2708
- lr as getHealthFactor,
2709
- Pt as getHealthFactorPTB,
2710
- At as getLendingPositions,
2711
- ur as getLendingState,
2712
- or as getMarket,
2713
- P as getMarketConfig,
2714
- It as getMarkets,
2715
- E as getPool,
2716
- J as getPools,
2717
- Ve as getPriceFeeds,
2718
- yr as getPythStalePriceFeedId,
2719
- $t as getPythStalePriceFeedIdV2,
2720
- dr as getSimulatedHealthFactor,
2721
- $e as getSimulatedHealthFactorPTB,
2722
- Xt as getStats,
2723
- pr as getTransactions,
2724
- Cr as getUserAvailableLendingRewards,
2725
- kr as getUserClaimedRewardHistory,
2726
- Se as getUserEModeCaps,
2727
- Ir as getUserTotalClaimedReward,
2728
- vr as liquidatePTB,
2729
- Qt as listAddressBalances,
2730
- sr as mergeCoinsPTB,
2731
- N as mergeServiceHeaders,
2732
- je as normalizeAddressBalance,
2733
- C as normalizeCoinType,
2734
- vt as parsePoolUID,
2735
- h as parseTxValue,
2736
- rr as repayCoinPTB,
2737
- br as repayFlashLoanPTB,
2738
- Yt as requireNaviGraphQLClient,
2739
- M as resolveNaviOpenApiEndpoint,
2740
- jr as summaryLendingRewards,
2741
- gr as updateOraclePriceBeforeUserOperationPTB,
2742
- he as updateOraclePricesPTB,
2743
- Et as updatePythPriceFeeds,
2744
- fr as verifyHealthFactorPTB,
2745
- O as withCache,
2746
- S as withSingleton,
2747
- er as withdrawCoinPTB
2748
- };
2749
- //# sourceMappingURL=index.esm.js.map