@naviprotocol/lending 2.0.5 → 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 (56) 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 +2 -2
  28. package/dist/oracle.d.ts.map +1 -1
  29. package/dist/oracle.js +204 -0
  30. package/dist/oracle.js.map +1 -0
  31. package/dist/package.json.js +8 -0
  32. package/dist/package.json.js.map +1 -0
  33. package/dist/pool.d.ts +1 -1
  34. package/dist/pool.js +391 -0
  35. package/dist/pool.js.map +1 -0
  36. package/dist/pyth.d.ts +1 -1
  37. package/dist/pyth.js +305 -0
  38. package/dist/pyth.js.map +1 -0
  39. package/dist/reward.d.ts +1 -1
  40. package/dist/reward.js +343 -0
  41. package/dist/reward.js.map +1 -0
  42. package/dist/services.js +52 -0
  43. package/dist/services.js.map +1 -0
  44. package/dist/sui.d.ts +1 -1
  45. package/dist/sui.js +121 -0
  46. package/dist/sui.js.map +1 -0
  47. package/dist/types.d.ts +6 -2
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/ua.js +16 -0
  50. package/dist/ua.js.map +1 -0
  51. package/dist/utils.d.ts +2 -2
  52. package/dist/utils.js +227 -0
  53. package/dist/utils.js.map +1 -0
  54. package/package.json +5 -5
  55. package/dist/index.esm.js +0 -2743
  56. package/dist/index.esm.js.map +0 -1
package/dist/index.esm.js DELETED
@@ -1,2743 +0,0 @@
1
- import { Transaction as q } from "@mysten/sui/transactions";
2
- import { bcs as l } from "@mysten/sui/bcs";
3
- import { toHex as Me, fromHex as Ue, normalizeStructTag as Y, SUI_CLOCK_OBJECT_ID as x, fromBase64 as De } from "@mysten/sui/utils";
4
- import Fe from "lodash.camelcase";
5
- import p from "bignumber.js";
6
- import { SuiJsonRpcClient as Ne } from "@mysten/sui/jsonRpc";
7
- import { SuiGraphQLClient as Re } from "@mysten/sui/graphql";
8
- import { SuiGrpcClient as he, GrpcWebFetchTransport as we } 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) => Ue(e),
12
- output: (e) => Me(e)
13
- }), qt = 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
- }), Le = 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
- }), zt = l.struct("IncentivePoolInfoByPhase", {
48
- /** Phase number */
49
- phase: l.u64(),
50
- /** List of incentive pools in this phase */
51
- pools: l.vector(Le)
52
- }), Gt = 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
- }), Wt = 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
- }), qe = 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
- }), ze = 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
- }), Ge = "2.0.5", V = {
133
- version: Ge
134
- }, We = V.version, He = () => {
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
- }, Je = () => {
141
- let e = "";
142
- return typeof process < "u" && process.versions && process.versions.node && (e = `lending/${We} (${He()})`), e;
143
- }, ce = Je(), be = "0x2::sui::SUI";
144
- class Ke 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 Qe(e, t) {
155
- return (BigInt(e) + BigInt(t)).toString();
156
- }
157
- function Ye(e, t) {
158
- return (BigInt(e) - BigInt(t)).toString();
159
- }
160
- function ve(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 Ce(e, t = be) {
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 = Ye(o, r)), !o && n && (o = Qe(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 Ht(e, t = be) {
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 Jt(e, t) {
182
- const r = await ve(e).getBalance(t), o = r.balance;
183
- return Ce((o && typeof o == "object" ? o : r) ?? {}, t.coinType);
184
- }
185
- async function Kt(e, t) {
186
- const r = await ve(e).listBalances(t), { balances: o = [] } = r;
187
- return {
188
- balances: o.map((n) => Ce(n)),
189
- nextCursor: r.nextCursor ?? r.cursor ?? null
190
- };
191
- }
192
- function Ze(e, t) {
193
- if ("client" in t)
194
- return t.client;
195
- const r = new we({
196
- baseUrl: t.url,
197
- meta: t.headers,
198
- fetchInit: t.fetchInit,
199
- fetch: t.fetch
200
- });
201
- return new he({
202
- network: e,
203
- transport: r
204
- });
205
- }
206
- function Xe(e, t) {
207
- return "client" in t ? t.client : new Re({
208
- network: e,
209
- url: t.url,
210
- headers: t.headers,
211
- fetch: t.fetch
212
- });
213
- }
214
- function je(e, t) {
215
- return "client" in t ? t.client : new Ne({
216
- network: e,
217
- url: t.url
218
- });
219
- }
220
- function xe(e) {
221
- const t = Ze(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 ? je(e.network, e.legacyJsonRpc) : void 0,
228
- services: e.services
229
- };
230
- }
231
- function Qt(e, t) {
232
- if (!e.graphql)
233
- throw new Ke(t);
234
- return e.graphql;
235
- }
236
- const et = "https://fullnode.mainnet.sui.io:443";
237
- let te;
238
- function tt() {
239
- return te || (te = new he({
240
- network: "mainnet",
241
- transport: new we({ baseUrl: et })
242
- })), te;
243
- }
244
- function rt(e, t = "mainnet") {
245
- return e ? typeof e == "string" ? je(t, { url: e }) : xe(e) : tt();
246
- }
247
- const nt = 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 ot(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: nt
263
- });
264
- }
265
- function le(e, t) {
266
- return {
267
- type: e,
268
- bcs: t
269
- };
270
- }
271
- function at(e) {
272
- return l.vector(l.U8).serialize(Array.from(new TextEncoder().encode(e))).toBytes();
273
- }
274
- function it(e) {
275
- return l.struct("PriceIdentifier", {
276
- bytes: l.vector(l.U8)
277
- }).serialize({
278
- bytes: Array.from(e)
279
- }).toBytes();
280
- }
281
- function ct(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 st(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] = ct(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 ut(e) {
300
- return Uint8Array.from(atob(e), (t) => t.charCodeAt(0));
301
- }
302
- class Ie {
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(ut);
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 lt {
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, it(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>", at("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: st(r.type)
536
- };
537
- }
538
- return this.priceTableInfo;
539
- }
540
- extractVaaBytesFromAccumulatorMessage(t) {
541
- const o = 7 + t[6] + 1, n = ot(t, o), a = o + 2;
542
- return t.subarray(a, a + n);
543
- }
544
- }
545
- const dt = "https://open-api.naviprotocol.io/api";
546
- let Q = {}, ke = 0;
547
- function pt(e) {
548
- return e.replace(/\/+$/, "");
549
- }
550
- function Yt(e) {
551
- Q = {
552
- ...Q,
553
- ...e,
554
- services: {
555
- ...Q.services,
556
- ...e.services
557
- }
558
- }, ke += 1;
559
- }
560
- function de() {
561
- return ke;
562
- }
563
- function M(e) {
564
- const t = e?.services?.naviOpenApi ?? Q.services?.naviOpenApi;
565
- return {
566
- baseUrl: pt(t?.baseUrl ?? dt),
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 mt(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
- ...mt(e),
586
- ...t?.headers ?? {}
587
- };
588
- }
589
- const U = rt();
590
- function pe(e) {
591
- return e ? e instanceof Uint8Array ? Array.from(e) : Array.isArray(e) ? e : Array.from(De(e)) : [];
592
- }
593
- function ft(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 ft(n);
625
- }
626
- function _e(e) {
627
- return {
628
- json: !!e?.showContent,
629
- display: !!e?.showDisplay,
630
- previousTransaction: !!e?.showPreviousTransaction,
631
- objectBcs: !!e?.showBcs
632
- };
633
- }
634
- function Te(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 yt(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: _e(t.options)
661
- });
662
- return Te(o);
663
- }
664
- async function gt(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: _e(t.options)
671
- });
672
- return o.map(Te);
673
- }
674
- function Be(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 = Be(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 = Be(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
- [Fe(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 ht(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 Pe(e) {
736
- const t = (e || 0) / Math.pow(10, 27);
737
- return t > Math.pow(10, 5) ? 1 / 0 : t;
738
- }
739
- new Ie("https://hermes.pyth.network", {
740
- timeout: 2e4
741
- });
742
- const wt = 27, me = (e, t) => {
743
- if (!Number(e) || !Number(t)) return new p(0);
744
- const r = new p(1).shiftedBy(1 * wt), 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 bt(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 = bt(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 Zt = 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 vt(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 xt(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 er(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 tr(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 rr = 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 yt(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 Ct {
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
- }, jt = 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 Ct(o, a);
1255
- });
1256
- }
1257
- )
1258
- ), nr = O(
1259
- S(
1260
- async (e, t) => (await jt([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 It(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 kt(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 _t(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 or(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 ar(e, t, r) {
1326
- const o = await I({
1327
- cacheTime: v,
1328
- ...r
1329
- }), n = await It(e, r);
1330
- await _t(e, t, {
1331
- ...r,
1332
- accountCap: n
1333
- });
1334
- const a = await P(r?.market || z), c = await kt(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 Ae = 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 ir(e) {
1369
- return `${P(e.marketId).key}-${e.emodeId}`;
1370
- }
1371
- function Tt(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 = Tt(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 cr(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 Se(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
- ht(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 Bt(e, t, r) {
1449
- return Se(e, t, 0, 0, 0, !1, r);
1450
- }
1451
- async function $e(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(qe).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(ze).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(), Ve = me(k.borrow_balance, B).toString();
1508
- y.push({
1509
- supplyBalance: X,
1510
- borrowBalance: Ve,
1511
- assetId: k.asset_id,
1512
- market: j.key,
1513
- pool: T,
1514
- emodeId: b.emodeId
1515
- });
1516
- });
1517
- }), y;
1518
- }
1519
- const sr = 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 $e(e, o, t);
1526
- }
1527
- );
1528
- async function ur(e, t) {
1529
- const r = t?.client ?? U, o = new q();
1530
- await Bt(o, e, t);
1531
- const n = await W(r, {
1532
- transactionBlock: o,
1533
- sender: e
1534
- }), a = Z(n, [l.u256()]);
1535
- return Pe(Number(a[0]) || 0);
1536
- }
1537
- async function lr(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 Se(
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 Pe(Number(w[0]) || 0);
1560
- }
1561
- const dr = 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 pr(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 Pt = O(
1648
- async (e, t) => {
1649
- const r = [], o = (t?.markets || Object.keys(L)).map((i) => P(i)), n = await Ae(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 $e(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 mr(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 Ee = new Ie("https://hermes.pyth.network", {
2002
- timeout: 1e4
2003
- });
2004
- async function fr(e) {
2005
- try {
2006
- const t = [], r = await Ee.getLatestPriceFeeds(e);
2007
- if (!r) return t;
2008
- const o = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2009
- for (const n of r) {
2010
- const a = n.getPriceUnchecked();
2011
- if (a.publishTime > o) {
2012
- console.warn(
2013
- `pyth price feed is invalid, id: ${n.id}, publish time: ${a.publishTime}, current timestamp: ${o}`
2014
- );
2015
- continue;
2016
- }
2017
- o - n.getPriceUnchecked().publishTime > 30 && (console.info(
2018
- `stale price feed, id: ${n.id}, publish time: ${a.publishTime}, current timestamp: ${o}`
2019
- ), t.push(n.id));
2020
- }
2021
- return t;
2022
- } catch (t) {
2023
- throw new Error(`failed to get pyth stale price feed id, msg: ${t.message}`);
2024
- }
2025
- }
2026
- async function At(e, t) {
2027
- const r = [], o = t?.client ?? U, n = e.map((c) => c.priceInfoObject), a = await gt(o, {
2028
- ids: Array.from(new Set(n)),
2029
- options: { showContent: !0 }
2030
- });
2031
- for (const c of a) {
2032
- const i = c.data;
2033
- if (!i || !i.content || i.content.dataType !== "moveObject") {
2034
- console.warn(`fetched object ${i?.objectId} datatype should be moveObject`);
2035
- continue;
2036
- }
2037
- const s = e.find((f) => f.priceInfoObject == i.objectId);
2038
- if (!s) {
2039
- console.warn(`unable to find pyth info from array, priceInfoObject: ${i.objectId}`);
2040
- continue;
2041
- }
2042
- const u = i.content.fields?.price_info?.price_feed?.price, m = u?.price;
2043
- if (!m) {
2044
- console.warn(`unexpected pyth price struct, priceInfoObject: ${i.objectId}`);
2045
- continue;
2046
- }
2047
- const { magnitude: w, negative: g } = m, y = u.conf, d = u.timestamp;
2048
- r.push({
2049
- priceFeedId: s.priceFeedId,
2050
- priceInfoObject: s.priceInfoObject,
2051
- price: g ? "-" + w : w,
2052
- conf: y,
2053
- publishTime: Number(d),
2054
- expiration: s.expiration
2055
- });
2056
- }
2057
- return r;
2058
- }
2059
- async function St(e, t) {
2060
- try {
2061
- const r = [], o = await At(e, t);
2062
- if (!o) return r;
2063
- const n = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2064
- for (const a of o) {
2065
- if (a.publishTime > n) {
2066
- console.warn(
2067
- `pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2068
- );
2069
- continue;
2070
- }
2071
- const c = a.expiration || 60;
2072
- n - a.publishTime > c && (console.info(
2073
- `stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2074
- ), r.push(a.priceFeedId));
2075
- }
2076
- return r;
2077
- } catch (r) {
2078
- throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`);
2079
- }
2080
- }
2081
- async function $t(e, t, r) {
2082
- const o = r?.client ?? U, n = await I({
2083
- ...r,
2084
- cacheTime: v
2085
- });
2086
- try {
2087
- const a = await Ee.getPriceFeedsUpdateData(t);
2088
- return await new lt(
2089
- o,
2090
- n.oracle.pythStateId,
2091
- n.oracle.wormholeStateId
2092
- ).updatePriceFeeds(e, a, t);
2093
- } catch (a) {
2094
- throw new Error(`failed to update pyth price feeds, msg: ${a.message}`);
2095
- }
2096
- }
2097
- async function ge(e, t, r) {
2098
- const o = await I({
2099
- ...r,
2100
- cacheTime: v
2101
- });
2102
- if (r?.updatePythPriceFeeds) {
2103
- const n = t.filter((c) => !!c.pythPriceFeedId && !!c.pythPriceInfoObject).map((c) => ({
2104
- priceFeedId: c.pythPriceFeedId,
2105
- priceInfoObject: c.pythPriceInfoObject,
2106
- expiration: 30
2107
- })), a = await St(n, r);
2108
- a.length > 0 && await $t(e, a, r);
2109
- }
2110
- for (const n of t)
2111
- e.moveCall({
2112
- target: `${o.oracle.packageId}::oracle_pro::update_single_price_v2`,
2113
- arguments: [
2114
- e.object("0x6"),
2115
- // Clock object
2116
- e.object(o.oracle.oracleConfig),
2117
- // Oracle configuration
2118
- e.object(o.oracle.priceOracle),
2119
- // Price oracle contract
2120
- e.object(o.oracle.supraOracleHolder),
2121
- // Supra oracle holder
2122
- e.object(n.pythPriceInfoObject),
2123
- // Pyth price info object
2124
- e.object(o.oracle.switchboardAggregator),
2125
- e.pure.address(n.feedId)
2126
- // Price feed ID
2127
- ]
2128
- });
2129
- return e;
2130
- }
2131
- async function Oe(e) {
2132
- return (await I({
2133
- ...e,
2134
- cacheTime: v
2135
- })).oracle.feeds;
2136
- }
2137
- function Et(e, t) {
2138
- return e.filter((r) => !!(t?.lendingState && t.lendingState.find((n) => r.oracleId === n.pool.oracleId) || t?.lendingPositions && t.lendingPositions.find((n) => {
2139
- if (![
2140
- "navi-lending-supply",
2141
- "navi-lending-borrow",
2142
- "navi-lending-emode-supply",
2143
- "navi-lending-emode-borrow"
2144
- ].includes(n.type))
2145
- return !1;
2146
- const c = n[n.type]?.pool;
2147
- return r.oracleId === c?.oracleId;
2148
- }) || t?.pools && t.pools.find((n) => r.oracleId === n.oracleId)));
2149
- }
2150
- async function yr(e, t, r, o) {
2151
- let n;
2152
- try {
2153
- const a = await Oe({
2154
- ...o
2155
- }), c = [];
2156
- r.forEach((u) => {
2157
- c.includes(u.market) || c.push(u.market);
2158
- });
2159
- const i = await Pt(t, {
2160
- ...o,
2161
- markets: c
2162
- });
2163
- return n = Et(a, {
2164
- lendingPositions: i,
2165
- pools: r
2166
- }), await ge(e, n, {
2167
- updatePythPriceFeeds: !0,
2168
- ...o
2169
- });
2170
- } catch (a) {
2171
- if (o?.throws)
2172
- throw a;
2173
- if (console.error(a), n)
2174
- try {
2175
- return await ge(e, n, {
2176
- ...o,
2177
- updatePythPriceFeeds: !1
2178
- });
2179
- } catch (c) {
2180
- console.error(c);
2181
- }
2182
- return e;
2183
- }
2184
- }
2185
- const ae = O(
2186
- S(
2187
- async (e) => {
2188
- const t = M(e), r = F(
2189
- `/navi/flashloan?env=${e?.env || "prod"}&sdk=${V.version}&market=${e?.market || z}`,
2190
- e
2191
- ), o = await fetch(r, {
2192
- headers: N(R, t)
2193
- }).then((n) => n.json());
2194
- return Object.keys(o.data).map((n) => ({
2195
- ...o.data[n],
2196
- coinType: n
2197
- }));
2198
- }
2199
- )
2200
- );
2201
- async function gr(e, t) {
2202
- 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;
2203
- }
2204
- async function hr(e, t, r, o) {
2205
- const n = await I({
2206
- ...o,
2207
- cacheTime: v
2208
- }), a = await E(t, o);
2209
- if (!(await ae({
2210
- ...o,
2211
- cacheTime: v
2212
- })).some(
2213
- (s) => C(s.coinType) === C(a.suiCoinType)
2214
- ))
2215
- throw new Error("Pool does not support flashloan");
2216
- if (n.version === 1) {
2217
- const [s, u] = e.moveCall({
2218
- target: `${n.package}::lending::flash_loan_with_ctx`,
2219
- arguments: [
2220
- e.object(n.flashloanConfig),
2221
- e.object(a.contract.pool),
2222
- h(r, e.pure.u64)
2223
- ],
2224
- typeArguments: [a.suiCoinType]
2225
- });
2226
- return [s, u];
2227
- } else {
2228
- const [s, u] = e.moveCall({
2229
- target: `${n.package}::lending::flash_loan_with_ctx_v2`,
2230
- arguments: [
2231
- e.object(n.flashloanConfig),
2232
- e.object(a.contract.pool),
2233
- h(r, e.pure.u64),
2234
- e.object("0x05")
2235
- ],
2236
- typeArguments: [a.suiCoinType]
2237
- });
2238
- return [s, u];
2239
- }
2240
- }
2241
- async function wr(e, t, r, o, n) {
2242
- const a = await I({
2243
- ...n,
2244
- cacheTime: v
2245
- }), c = await E(t, n);
2246
- if (!(await ae({
2247
- ...n,
2248
- cacheTime: v
2249
- })).some(
2250
- (m) => C(m.coinType) === C(c.suiCoinType)
2251
- ))
2252
- throw new Error("Pool does not support flashloan");
2253
- const [u] = e.moveCall({
2254
- target: `${a.package}::lending::flash_repay_with_ctx`,
2255
- arguments: [
2256
- e.object("0x06"),
2257
- e.object(a.storage),
2258
- e.object(c.contract.pool),
2259
- h(r, e.object),
2260
- h(o, e.object)
2261
- ],
2262
- typeArguments: [c.suiCoinType]
2263
- });
2264
- return [u];
2265
- }
2266
- async function br(e, t, r, o, n, a) {
2267
- const c = {
2268
- ...a,
2269
- cacheTime: v
2270
- }, i = await I(c), s = await E(t, c), u = await E(o, c);
2271
- if (i.version === 1) {
2272
- const [m, w] = e.moveCall({
2273
- target: `${i.package}::incentive_v3::liquidation`,
2274
- arguments: [
2275
- e.object("0x06"),
2276
- // Clock object
2277
- e.object(i.priceOracle),
2278
- // Price oracle for asset pricing
2279
- e.object(i.storage),
2280
- // Protocol storage
2281
- e.pure.u8(s.id),
2282
- // Pay asset ID
2283
- e.object(s.contract.pool),
2284
- // Pay asset pool contract
2285
- h(r, e.object),
2286
- // Debt repayment amount
2287
- e.pure.u8(u.id),
2288
- // Collateral asset ID
2289
- e.object(u.contract.pool),
2290
- // Collateral asset pool contract
2291
- h(n, e.pure.address),
2292
- // Borrower address
2293
- e.object(i.incentiveV2),
2294
- // Incentive V2 contract
2295
- e.object(i.incentiveV3)
2296
- // Incentive V3 contract
2297
- ],
2298
- typeArguments: [s.suiCoinType, u.suiCoinType]
2299
- });
2300
- return [m, w];
2301
- } else {
2302
- const [m, w] = e.moveCall({
2303
- target: `${i.package}::incentive_v3::liquidation_v2`,
2304
- arguments: [
2305
- e.object("0x06"),
2306
- // Clock object
2307
- e.object(i.priceOracle),
2308
- // Price oracle for asset pricing
2309
- e.object(i.storage),
2310
- // Protocol storage
2311
- e.pure.u8(s.id),
2312
- // Pay asset ID
2313
- e.object(s.contract.pool),
2314
- // Pay asset pool contract
2315
- h(r, e.object),
2316
- // Debt repayment amount
2317
- e.pure.u8(u.id),
2318
- // Collateral asset ID
2319
- e.object(u.contract.pool),
2320
- // Collateral asset pool contract
2321
- h(n, e.pure.address),
2322
- // Borrower address
2323
- e.object(i.incentiveV2),
2324
- // Incentive V2 contract
2325
- e.object(i.incentiveV3),
2326
- // Incentive V3 contract
2327
- e.object("0x05")
2328
- // SuiSystemState object
2329
- ],
2330
- typeArguments: [s.suiCoinType, u.suiCoinType]
2331
- });
2332
- return [m, w];
2333
- }
2334
- }
2335
- async function Ot(e, t, r) {
2336
- const o = r?.client ?? U, n = await J({
2337
- ...r,
2338
- markets: Object.values(L),
2339
- cacheTime: v
2340
- }), a = await Oe(r), c = [];
2341
- return await Promise.all(
2342
- t.map(async (i) => {
2343
- try {
2344
- const s = await I({
2345
- ...r,
2346
- cacheTime: v,
2347
- market: i.market
2348
- }), u = new q();
2349
- u.moveCall({
2350
- target: `${s.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
2351
- arguments: [
2352
- u.object("0x06"),
2353
- // Clock object
2354
- u.object(s.storage),
2355
- // Protocol storage
2356
- u.object(s.incentiveV3),
2357
- // Incentive V3 contract
2358
- u.pure.address(i.address)
2359
- // User address
2360
- ]
2361
- });
2362
- const w = (await W(o, {
2363
- transactionBlock: u,
2364
- sender: e
2365
- }))?.results?.[0];
2366
- if (!w)
2367
- return;
2368
- const g = Z({ results: [w] }, [
2369
- l.vector(l.string()),
2370
- // Asset coin types
2371
- l.vector(l.string()),
2372
- // Reward coin types
2373
- l.vector(l.u8()),
2374
- // Reward options
2375
- l.vector(l.Address),
2376
- // Rule IDs
2377
- l.vector(l.u256())
2378
- // Claimable amounts
2379
- ]);
2380
- if (g.length === 5 && Array.isArray(g[0])) {
2381
- const y = g[0].length;
2382
- for (let d = 0; d < y; d++) {
2383
- const f = a.find(
2384
- (j) => C(j.coinType) === C(g[1][d])
2385
- ), b = n.find(
2386
- (j) => C(j.coinType) === C(g[0][d]) && j.market === i.market
2387
- );
2388
- !f || !b || c.push({
2389
- assetId: b.id,
2390
- assetCoinType: C(g[0][d]),
2391
- rewardCoinType: C(g[1][d]),
2392
- option: Number(g[2][d]),
2393
- userClaimableReward: Number(g[4][d]) / Math.pow(10, f.priceDecimal),
2394
- ruleIds: Array.isArray(g[3][d]) ? g[3][d] : [g[3][d]],
2395
- market: i.market,
2396
- owner: i.owner,
2397
- address: i.address,
2398
- emodeId: i.emodeId
2399
- });
2400
- }
2401
- }
2402
- } catch (s) {
2403
- console.error(
2404
- `[lending] getLendingRewardsBatch task failed (market=${i.market}, address=${i.address}):`,
2405
- s
2406
- );
2407
- }
2408
- })
2409
- ), c;
2410
- }
2411
- async function vr(e, t) {
2412
- const r = (t?.markets || [L.main]).map((a) => P(a)), o = await Ae(e, t), n = r.map((a) => ({
2413
- address: e,
2414
- owner: e,
2415
- market: a.key
2416
- })).concat(
2417
- o.filter((a) => !!r.find((c) => c.id === a.marketId)).map((a) => {
2418
- const c = P(a.marketId);
2419
- return {
2420
- address: a.accountCap,
2421
- owner: e,
2422
- market: c.key,
2423
- emodeId: a.emodeId
2424
- };
2425
- })
2426
- );
2427
- return await Ot(e, n, t);
2428
- }
2429
- function Cr(e) {
2430
- const t = /* @__PURE__ */ new Map();
2431
- e.forEach((o) => {
2432
- const n = o.assetId, a = o.option, c = `${n}-${a}-${o.rewardCoinType}-${o.market}`;
2433
- t.has(c) ? t.get(c).total += o.userClaimableReward : t.set(c, {
2434
- assetId: n,
2435
- rewardType: a,
2436
- coinType: o.rewardCoinType,
2437
- total: Number(o.userClaimableReward),
2438
- market: o.market
2439
- });
2440
- });
2441
- const r = /* @__PURE__ */ new Map();
2442
- for (const { assetId: o, rewardType: n, coinType: a, total: c, market: i } of t.values()) {
2443
- const s = `${o}-${n}-${i}`;
2444
- r.has(s) || r.set(s, { assetId: o, rewardType: n, market: i, rewards: /* @__PURE__ */ new Map() });
2445
- const u = r.get(s);
2446
- u.rewards.set(a, (u.rewards.get(a) || 0) + c);
2447
- }
2448
- return Array.from(r.values()).map((o) => ({
2449
- assetId: o.assetId,
2450
- rewardType: o.rewardType,
2451
- market: o.market,
2452
- rewards: Array.from(o.rewards.entries()).map(([n, a]) => ({
2453
- coinType: n,
2454
- available: a.toFixed(6)
2455
- }))
2456
- }));
2457
- }
2458
- const jr = S(
2459
- async (e, t) => {
2460
- const r = M(t), o = F(
2461
- `/navi/user/total_claimed_reward?userAddress=${e}&sdk=${V.version}&market=${t?.market || z}`,
2462
- t
2463
- );
2464
- return (await fetch(o, {
2465
- headers: N(R, r)
2466
- }).then((a) => a.json())).data;
2467
- }
2468
- ), Ir = S(
2469
- async (e, t) => {
2470
- const r = M(t), o = F(
2471
- `/navi/user/rewards?userAddress=${e}&page=${t?.page || 1}&pageSize=${t?.size || 400}&sdk=${V.version}&market=${t?.market || z}`,
2472
- t
2473
- ), n = await fetch(o, {
2474
- headers: N(R, r)
2475
- }).then((a) => a.json());
2476
- return re({
2477
- data: n.data.rewards
2478
- });
2479
- }
2480
- );
2481
- async function kr(e, t, r) {
2482
- const o = await J({
2483
- ...r,
2484
- markets: Object.values(L),
2485
- cacheTime: v
2486
- }), n = /* @__PURE__ */ new Map();
2487
- for (const c of t) {
2488
- const { rewardCoinType: i, ruleIds: s, market: u, owner: m, address: w, emodeId: g } = c, y = `${i}___${w}__${u}`;
2489
- for (const d of s) {
2490
- n.has(y) || n.set(y, {
2491
- assetIds: [],
2492
- ruleIds: [],
2493
- amount: 0,
2494
- market: u,
2495
- owner: m,
2496
- address: w,
2497
- isEMode: typeof g < "u"
2498
- });
2499
- const f = n.get(y);
2500
- f.assetIds.push(c.assetCoinType.replace("0x", "")), f.ruleIds.push(d), f.amount += c.userClaimableReward;
2501
- }
2502
- }
2503
- const a = [];
2504
- for (const [
2505
- c,
2506
- { assetIds: i, ruleIds: s, amount: u, market: m, owner: w, address: g, isEMode: y }
2507
- ] of n) {
2508
- const d = await I({
2509
- ...r,
2510
- cacheTime: v,
2511
- market: m
2512
- }), f = c.split("___")[0], b = o.filter(
2513
- (k) => C(k.suiCoinType) === C(f)
2514
- );
2515
- b.sort((k, T) => k.market === m ? -1 : 1);
2516
- const j = b[0], _ = d.rewardFunds[C(f)];
2517
- if (!_)
2518
- throw new Error(`No matching rewardFund found for reward coin: ${f} ${m}`);
2519
- if (r?.accountCap && !r.customCoinReceive)
2520
- throw new Error("customCoinReceive is required when accountCap is provided");
2521
- if (r?.customCoinReceive) {
2522
- let k;
2523
- r.accountCap ? k = e.moveCall({
2524
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2525
- arguments: [
2526
- e.object("0x06"),
2527
- // Clock object
2528
- e.object(d.incentiveV3),
2529
- // Incentive V3 contract
2530
- e.object(d.storage),
2531
- // Protocol storage
2532
- e.object(_),
2533
- // Reward fund
2534
- e.pure.vector("string", i),
2535
- // Asset IDs
2536
- e.pure.vector("address", s),
2537
- // Rule IDs
2538
- h(r.accountCap, e.object)
2539
- // Account capability
2540
- ],
2541
- typeArguments: [f]
2542
- }) : y ? k = e.moveCall({
2543
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2544
- arguments: [
2545
- e.object("0x06"),
2546
- // Clock object
2547
- e.object(d.incentiveV3),
2548
- // Incentive V3 contract
2549
- e.object(d.storage),
2550
- // Protocol storage
2551
- e.object(_),
2552
- // Reward fund
2553
- e.pure.vector("string", i),
2554
- // Asset IDs
2555
- e.pure.vector("address", s),
2556
- // Rule IDs
2557
- h(g, e.object)
2558
- // Account capability
2559
- ],
2560
- typeArguments: [f]
2561
- }) : k = e.moveCall({
2562
- target: `${d.package}::incentive_v3::claim_reward`,
2563
- arguments: [
2564
- e.object("0x06"),
2565
- // Clock object
2566
- e.object(d.incentiveV3),
2567
- // Incentive V3 contract
2568
- e.object(d.storage),
2569
- // Protocol storage
2570
- e.object(_),
2571
- // Reward fund
2572
- e.pure.vector("string", i),
2573
- // Asset IDs
2574
- e.pure.vector("address", s)
2575
- // Rule IDs
2576
- ],
2577
- typeArguments: [f]
2578
- });
2579
- const [T] = e.moveCall({
2580
- target: "0x2::coin::from_balance",
2581
- arguments: [k],
2582
- typeArguments: [f]
2583
- });
2584
- if (r?.customCoinReceive.type === "transfer") {
2585
- if (!r.customCoinReceive.transfer)
2586
- throw new Error("customCoinReceive.transfer is required");
2587
- e.transferObjects(
2588
- [T],
2589
- h(r.customCoinReceive.transfer, e.pure.address)
2590
- );
2591
- }
2592
- if (r?.customCoinReceive.type === "depositNAVI") {
2593
- const $ = p(j.totalSupplyAmount).shiftedBy(-9), D = p(j.supplyCapCeiling).shiftedBy(-27);
2594
- $.plus(u).isGreaterThan(D) && r?.customCoinReceive.depositNAVI?.fallbackReceiveAddress ? e.transferObjects(
2595
- [T],
2596
- e.pure.address(r.customCoinReceive.depositNAVI.fallbackReceiveAddress)
2597
- ) : await vt(e, j, T, {
2598
- ...r,
2599
- market: j.market
2600
- });
2601
- } else
2602
- a.push({
2603
- coin: T,
2604
- identifier: j,
2605
- owner: w,
2606
- isEMode: y
2607
- });
2608
- } else if (r?.accountCap || y) {
2609
- const k = e.moveCall({
2610
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2611
- arguments: [
2612
- e.object("0x06"),
2613
- // Clock object
2614
- e.object(d.incentiveV3),
2615
- // Incentive V3 contract
2616
- e.object(d.storage),
2617
- // Protocol storage
2618
- e.object(_),
2619
- // Reward fund
2620
- e.pure.vector("string", i),
2621
- // Asset IDs
2622
- e.pure.vector("address", s),
2623
- // Rule IDs
2624
- h(r?.accountCap || g, e.object)
2625
- // Account capability
2626
- ],
2627
- typeArguments: [f]
2628
- }), [T] = e.moveCall({
2629
- target: "0x2::coin::from_balance",
2630
- arguments: [k],
2631
- typeArguments: [f]
2632
- });
2633
- e.transferObjects(
2634
- [T],
2635
- h(r?.accountCap || w, e.pure.address)
2636
- );
2637
- } else
2638
- e.moveCall({
2639
- target: `${d.package}::incentive_v3::claim_reward_entry`,
2640
- arguments: [
2641
- e.object("0x06"),
2642
- // Clock object
2643
- e.object(d.incentiveV3),
2644
- // Incentive V3 contract
2645
- e.object(d.storage),
2646
- // Protocol storage
2647
- e.object(_),
2648
- // Reward fund
2649
- e.pure.vector("string", i),
2650
- // Asset IDs
2651
- e.pure.vector("address", s)
2652
- // Rule IDs
2653
- ],
2654
- typeArguments: [f]
2655
- });
2656
- }
2657
- return a;
2658
- }
2659
- export {
2660
- ie as Address,
2661
- v as DEFAULT_CACHE_TIME,
2662
- z as DEFAULT_MARKET_IDENTITY,
2663
- Wt as FlashLoanAssetConfig,
2664
- qt as IncentiveAPYInfo,
2665
- Le as IncentivePoolInfo,
2666
- zt as IncentivePoolInfoByPhase,
2667
- L as MARKETS,
2668
- Ct as Market,
2669
- Ke as NaviMissingGraphQLClientError,
2670
- Gt as OracleInfo,
2671
- et as PUBLIC_MAINNET_GRPC_URL,
2672
- H as PoolOperator,
2673
- qe as ReserveDataInfo,
2674
- Ie as SuiPriceServiceConnection,
2675
- lt as SuiPythClient,
2676
- G as UserPositions,
2677
- ze as UserStateInfo,
2678
- er as borrowCoinPTB,
2679
- F as buildNaviOpenApiUrl,
2680
- kr as claimLendingRewardsPTB,
2681
- Yt as configureNaviSdk,
2682
- It as createAccountCapPTB,
2683
- ar as createEModeCapPTB,
2684
- je as createNaviLegacyJsonRpcClient,
2685
- rt as createNaviSuiClient,
2686
- xe as createNaviSuiClientBundle,
2687
- vt as depositCoinPTB,
2688
- ir as emodeIdentityId,
2689
- _t as enterEModePTB,
2690
- or as exitEModePTB,
2691
- Et as filterPriceFeeds,
2692
- hr as flashloanPTB,
2693
- kt as getAccountCapOwnerPTB,
2694
- Jt as getAddressBalance,
2695
- ae as getAllFlashLoanAssets,
2696
- rr as getBorrowFee,
2697
- Ht as getCoinObjectOnlyBalance,
2698
- pr as getCoins,
2699
- I as getConfig,
2700
- Xt as getFees,
2701
- gr as getFlashLoanAsset,
2702
- ur as getHealthFactor,
2703
- Bt as getHealthFactorPTB,
2704
- Pt as getLendingPositions,
2705
- sr as getLendingState,
2706
- nr as getMarket,
2707
- P as getMarketConfig,
2708
- jt as getMarkets,
2709
- E as getPool,
2710
- J as getPools,
2711
- Oe as getPriceFeeds,
2712
- fr as getPythStalePriceFeedId,
2713
- St as getPythStalePriceFeedIdV2,
2714
- lr as getSimulatedHealthFactor,
2715
- Se as getSimulatedHealthFactorPTB,
2716
- Zt as getStats,
2717
- dr as getTransactions,
2718
- vr as getUserAvailableLendingRewards,
2719
- Ir as getUserClaimedRewardHistory,
2720
- Ae as getUserEModeCaps,
2721
- jr as getUserTotalClaimedReward,
2722
- br as liquidatePTB,
2723
- Kt as listAddressBalances,
2724
- cr as mergeCoinsPTB,
2725
- N as mergeServiceHeaders,
2726
- Ce as normalizeAddressBalance,
2727
- C as normalizeCoinType,
2728
- bt as parsePoolUID,
2729
- h as parseTxValue,
2730
- tr as repayCoinPTB,
2731
- wr as repayFlashLoanPTB,
2732
- Qt as requireNaviGraphQLClient,
2733
- M as resolveNaviOpenApiEndpoint,
2734
- Cr as summaryLendingRewards,
2735
- yr as updateOraclePriceBeforeUserOperationPTB,
2736
- ge as updateOraclePricesPTB,
2737
- $t as updatePythPriceFeeds,
2738
- mr as verifyHealthFactorPTB,
2739
- O as withCache,
2740
- S as withSingleton,
2741
- xt as withdrawCoinPTB
2742
- };
2743
- //# sourceMappingURL=index.esm.js.map