@naviprotocol/lending 2.0.5-beta.1 → 2.0.5-dev.0

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 (55) 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 -55
  25. package/dist/market.d.ts.map +1 -1
  26. package/dist/market.js +121 -0
  27. package/dist/market.js.map +1 -0
  28. package/dist/oracle.d.ts +1 -1
  29. package/dist/oracle.js +198 -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 +2 -2
  48. package/dist/ua.js +16 -0
  49. package/dist/ua.js.map +1 -0
  50. package/dist/utils.d.ts +2 -2
  51. package/dist/utils.js +227 -0
  52. package/dist/utils.js.map +1 -0
  53. package/package.json +5 -5
  54. package/dist/index.esm.js +0 -2773
  55. package/dist/index.esm.js.map +0 -1
package/dist/index.esm.js DELETED
@@ -1,2773 +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 Me, 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 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) => Me(e),
12
- output: (e) => Ue(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-beta.1", 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(), we = "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 = we) {
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 = we) {
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 be({
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 ke(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 ? ke(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 be({ baseUrl: et })
242
- })), te;
243
- }
244
- function rt(e, t = "mainnet") {
245
- return e ? typeof e == "string" ? ke(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 = {}, je = 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
- }, je += 1;
559
- }
560
- function de() {
561
- return je;
562
- }
563
- function U(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 = U(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 M = 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 A(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 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 wt(e) {
776
- const [t, r] = e.split("-");
777
- return !t || !r ? null : {
778
- marketKey: t,
779
- poolId: parseInt(r)
780
- };
781
- }
782
- function S() {
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
- A(
788
- async (e) => {
789
- const t = (e?.markets || [L.main]).map((a) => P(a)), r = U(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((w) => {
799
- const k = P(w.marketId);
800
- return a.market === k.key && w.isActive;
801
- }).filter((w) => !!w.assets.find((k) => k.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(), b = 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 = b, 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 = wt(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
- A(async (e) => {
832
- const t = U(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
- A(
839
- async (e) => {
840
- const t = U(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
- A(
1119
- async (e) => {
1120
- const t = await I({
1121
- ...e
1122
- }), r = e?.client ?? M;
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
- "sui-usdc": {
1176
- id: 4,
1177
- key: "sui-usdc",
1178
- name: "SUI/USDC Market"
1179
- },
1180
- "wbtc-usdc": {
1181
- id: 5,
1182
- key: "wbtc-usdc",
1183
- name: "WBTC/USDC Market"
1184
- },
1185
- "xbtc-usdc": {
1186
- id: 6,
1187
- key: "xbtc-usdc",
1188
- name: "xBTC/USDC Market"
1189
- },
1190
- "vsui-usdc": {
1191
- id: 7,
1192
- key: "vsui-usdc",
1193
- name: "vSUI/USDC Market"
1194
- },
1195
- "vsui-sui": {
1196
- id: 8,
1197
- key: "vsui-sui",
1198
- name: "vSUI/SUI Market"
1199
- },
1200
- "hasui-sui": {
1201
- id: 9,
1202
- key: "hasui-sui",
1203
- name: "hasSUI/SUI Market"
1204
- }
1205
- };
1206
- class Ct {
1207
- constructor(t, r) {
1208
- this.poolMap = {}, this.emodeMap = {}, this.pools = [], this.emodes = [], this.emodePools = [], this.emodeBorrowablePools = [], this.emodeSupplyablePools = [], this._overview = {
1209
- marketTotalSupplyValue: "0",
1210
- marketTotalBorrowValue: "0"
1211
- }, this.config = P(t), this.initPools(r);
1212
- }
1213
- get overview() {
1214
- return this._overview;
1215
- }
1216
- initPools(t) {
1217
- const r = ne(this.pools), o = fe(this.emodes), n = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set();
1218
- let c = p(0), i = p(0);
1219
- t.forEach((s) => {
1220
- if (!this.checkMarket(s.market)) {
1221
- console.warn(`Pool is not in market ${this.config.name}`, s);
1222
- return;
1223
- }
1224
- r[s.uniqueId] || this.pools.push(s), s?.emodes?.forEach((m) => {
1225
- o[m.uniqueId] || this.emodes.push(m), m.assets.forEach((b) => {
1226
- b.isDebt && m.assets.find(
1227
- (y) => y.isCollateral && y.ltv > 0 && y.assetId !== s.id
1228
- ) && n.add(s.uniqueId), b.isCollateral && m.assets.find((y) => y.isDebt && y.assetId !== s.id) && a.add(s.uniqueId);
1229
- });
1230
- }), i = i.plus(s.poolBorrowValue), c = c.plus(s.poolSupplyValue);
1231
- }), this.poolMap = ne(this.pools, "id"), this.emodeMap = fe(this.emodes, "emodeId"), this.emodes.forEach((s) => {
1232
- const u = this.getEModePools(s.emodeId);
1233
- this.emodePools.push(...u);
1234
- }), this._overview = {
1235
- marketTotalSupplyValue: c.toString(),
1236
- marketTotalBorrowValue: i.toString()
1237
- }, this.emodeBorrowablePools = this.pools.filter((s) => n.has(s.uniqueId)), this.emodeSupplyablePools = this.pools.filter((s) => a.has(s.uniqueId));
1238
- }
1239
- getEMode(t) {
1240
- return this.emodeMap[t] || null;
1241
- }
1242
- getEModeRelatePools(t, r) {
1243
- const { collateral: o, debt: n, emodeId: a } = r || {}, c = [];
1244
- return t.emodes.forEach((i) => {
1245
- typeof a == "number" && a !== i.emodeId || i.assets.forEach((s) => {
1246
- 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]);
1247
- });
1248
- }), c;
1249
- }
1250
- getEModePools(t) {
1251
- const r = this.getEMode(t);
1252
- return r ? r.assets.map((n) => n.assetId).map((n) => this.poolMap[n]).filter((n) => !!n).map((n) => {
1253
- const a = r.assets.find((c) => c.assetId === n.id);
1254
- return {
1255
- ...n,
1256
- emode: {
1257
- ...a,
1258
- emodeId: r.emodeId
1259
- },
1260
- isEMode: !0
1261
- };
1262
- }) : [];
1263
- }
1264
- checkMarket(t) {
1265
- let r = !1;
1266
- 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;
1267
- }
1268
- }
1269
- const P = (e) => {
1270
- const r = Object.values(L).find((o) => typeof e == "number" ? o.id === e : typeof e == "string" ? o.key === e : o.id === e.id);
1271
- if (!r)
1272
- throw new Error("Market not found");
1273
- return r;
1274
- }, kt = O(
1275
- A(
1276
- async (e, t) => {
1277
- const r = await J({
1278
- cacheTime: 6e4,
1279
- ...t,
1280
- markets: e
1281
- });
1282
- return e.map((o) => {
1283
- const n = P(o), a = r.filter((c) => c.market === n.key);
1284
- return new Ct(o, a);
1285
- });
1286
- }
1287
- )
1288
- ), nr = O(
1289
- A(
1290
- async (e, t) => (await kt([e], t))[0]
1291
- )
1292
- ), I = O(
1293
- A(
1294
- async (e) => {
1295
- const t = P(e?.market || z), r = U(e), o = F(
1296
- `/navi/config?env=${e?.env || "prod"}&sdk=${V.version}&market=${t.key}`,
1297
- e
1298
- );
1299
- return (await fetch(o, {
1300
- headers: N(R, r)
1301
- }).then((a) => a.json())).data;
1302
- }
1303
- )
1304
- ), v = 1e3 * 60 * 5;
1305
- async function It(e, t) {
1306
- const r = await I({
1307
- cacheTime: v,
1308
- ...t
1309
- });
1310
- return e.moveCall({
1311
- target: `${r.package}::lending::create_account`,
1312
- arguments: []
1313
- });
1314
- }
1315
- async function jt(e, t, r) {
1316
- const o = await I({
1317
- cacheTime: v,
1318
- ...r
1319
- });
1320
- return e.moveCall({
1321
- target: `${o.package}::account::account_owner`,
1322
- arguments: [t]
1323
- });
1324
- }
1325
- async function _t(e, t, r) {
1326
- const o = await I({
1327
- ...r,
1328
- cacheTime: v
1329
- });
1330
- return r?.accountCap ? e.moveCall({
1331
- target: `${o.package}::lending::enter_emode_with_account_cap`,
1332
- arguments: [
1333
- e.object(o.storage),
1334
- h(t, e.pure.u64),
1335
- h(r.accountCap, e.object)
1336
- ]
1337
- }) : e.moveCall({
1338
- target: `${o.package}::lending::enter_emode`,
1339
- arguments: [e.object(o.storage), h(t, e.pure.u64)]
1340
- }), e;
1341
- }
1342
- async function or(e, t) {
1343
- const r = await I({
1344
- ...t,
1345
- cacheTime: v
1346
- });
1347
- return t?.accountCap ? e.moveCall({
1348
- target: `${r.package}::lending::exit_emode_with_account_cap`,
1349
- arguments: [e.object(r.storage), h(t.accountCap, e.object)]
1350
- }) : e.moveCall({
1351
- target: `${r.package}::lending::exit_emode`,
1352
- arguments: [e.object(r.storage)]
1353
- }), e;
1354
- }
1355
- async function ar(e, t, r) {
1356
- const o = await I({
1357
- cacheTime: v,
1358
- ...r
1359
- }), n = await It(e, r);
1360
- await _t(e, t, {
1361
- ...r,
1362
- accountCap: n
1363
- });
1364
- const a = await P(r?.market || z), c = await jt(e, n, r);
1365
- return e.moveCall({
1366
- target: `${o.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,
1367
- arguments: [
1368
- e.object(o.emode.contract.registryObject),
1369
- c,
1370
- h(a.id, e.pure.u64),
1371
- h(t, e.pure.u64)
1372
- ]
1373
- }), n;
1374
- }
1375
- const Se = O(
1376
- A(
1377
- async (e, t) => {
1378
- const r = await I({
1379
- cacheTime: v,
1380
- ...t
1381
- }), o = new q(), n = t?.client ?? M;
1382
- o.moveCall({
1383
- target: `${r.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,
1384
- arguments: [o.object(r.emode.contract.registryObject), o.pure.address(e)]
1385
- });
1386
- const c = (await W(n, {
1387
- transactionBlock: o,
1388
- sender: e
1389
- })).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]));
1390
- return i.map((m, b) => ({
1391
- marketId: Number(m),
1392
- emodeId: Number(s[b]),
1393
- accountCap: u[b].toString()
1394
- }));
1395
- }
1396
- )
1397
- );
1398
- function ir(e) {
1399
- return `${P(e.marketId).key}-${e.emodeId}`;
1400
- }
1401
- function Tt(e, t) {
1402
- return e.coinType ? e.coinType : t || (typeof e.type == "string" ? e.type.match(/::coin::Coin<(.+)>$/) : null)?.[1];
1403
- }
1404
- function ye(e, t) {
1405
- const r = Tt(e, t), o = e.coinObjectId ?? e.objectId;
1406
- return !r || !o || e.balance === void 0 || e.balance === null ? null : {
1407
- ...e,
1408
- coinType: C(r),
1409
- coinObjectId: o
1410
- };
1411
- }
1412
- function cr(e, t, r) {
1413
- const o = typeof r?.balance == "number", n = o ? r.balance : 0, a = BigInt(r?.addressBalance ?? 0);
1414
- let c = 0;
1415
- const i = [];
1416
- let s = "", u = 0n;
1417
- t.sort((B, X) => Number(X.balance) - Number(B.balance)).forEach((B) => {
1418
- if (u += BigInt(B.balance), !(o && c >= n) && Number(B.balance) !== 0) {
1419
- if (s || (s = B.coinType), s !== B.coinType)
1420
- throw new Error("All coins must be of the same type");
1421
- c += Number(B.balance), i.push(B.coinObjectId);
1422
- }
1423
- });
1424
- const m = r?.coinType, y = ((B) => {
1425
- if (!B)
1426
- return !1;
1427
- try {
1428
- return C(B) === C("0x2::sui::SUI");
1429
- } catch {
1430
- return !1;
1431
- }
1432
- })(s || m || "") && !!r?.useGasCoin, d = BigInt(n), f = !y && !!m, w = f ? a : 0n, k = u + w, _ = !o || u >= d ? 0n : d - u, j = f && _ > 0n && w >= _;
1433
- if (o && k < d)
1434
- throw new Error(`Balance is less than the specified balance: ${k} < ${d}`);
1435
- if (i.length === 0 && !j)
1436
- throw new Error("No coins to merge");
1437
- if (y)
1438
- return o ? e.splitCoins(e.gas, [e.pure.u64(n)]) : e.gas;
1439
- if (!j)
1440
- 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];
1441
- const T = e.moveCall({
1442
- target: "0x2::coin::redeem_funds",
1443
- typeArguments: [m],
1444
- arguments: [e.withdrawal({ amount: _, type: m })]
1445
- });
1446
- let $;
1447
- const D = [];
1448
- if (i.length > 0) {
1449
- $ = e.object(i[0]);
1450
- for (const B of i.slice(1))
1451
- D.push(e.object(B));
1452
- D.push(T);
1453
- } else
1454
- $ = T;
1455
- return D.length > 0 && e.mergeCoins($, D), i.length === 0 ? $ : o ? e.splitCoins($, [e.pure.u64(n)]) : $;
1456
- }
1457
- async function Ae(e, t, r, o, n, a, c) {
1458
- const i = await I({
1459
- ...c,
1460
- cacheTime: v
1461
- }), s = await E(r, c);
1462
- return e.moveCall({
1463
- target: `${i.uiGetter}::calculator_unchecked::dynamic_health_factor`,
1464
- arguments: [
1465
- e.object("0x06"),
1466
- e.object(i.storage),
1467
- e.object(i.oracle.priceOracle),
1468
- ht(e, s),
1469
- h(t, e.pure.address),
1470
- h(s.id, e.pure.u8),
1471
- h(o, e.pure.u64),
1472
- h(n, e.pure.u64),
1473
- h(a, e.pure.bool)
1474
- ],
1475
- typeArguments: [s.suiCoinType]
1476
- });
1477
- }
1478
- async function Bt(e, t, r) {
1479
- return Ae(e, t, 0, 0, 0, !1, r);
1480
- }
1481
- async function $e(e, t, r) {
1482
- const o = new q(), n = r?.client ?? M, a = await J({
1483
- ...r,
1484
- markets: Object.values(L)
1485
- }), c = ne(a), s = Array.from(new Set(t.map((d) => d.market))).map((d) => P(d));
1486
- for (const d of s) {
1487
- const f = await I({
1488
- ...r,
1489
- cacheTime: v,
1490
- market: d.key
1491
- });
1492
- o.moveCall({
1493
- target: `${f.uiGetter}::getter::get_reserve_data`,
1494
- arguments: [o.object(f.storage)]
1495
- });
1496
- }
1497
- for (let d of t) {
1498
- const f = await I({
1499
- ...r,
1500
- cacheTime: v,
1501
- market: d.market
1502
- });
1503
- o.moveCall({
1504
- target: `${f.uiGetter}::getter_unchecked::get_user_state`,
1505
- arguments: [o.object(f.storage), o.pure.address(d.address)]
1506
- });
1507
- }
1508
- const m = (await W(n, {
1509
- transactionBlock: o,
1510
- sender: e
1511
- })).results || [], b = {};
1512
- s.forEach((d, f) => {
1513
- try {
1514
- const w = m[f]?.returnValues?.map((_) => l.vector(qe).parse(Uint8Array.from(_[0])))[0] || [], k = {};
1515
- for (const _ of w)
1516
- k[_.id] = {
1517
- supplyIndex: _.supply_index,
1518
- borrowIndex: _.borrow_index
1519
- };
1520
- b[d.key] = k;
1521
- } catch (w) {
1522
- console.warn(
1523
- `[@naviprotocol/lending] Failed to decode reserve data for market "${d.key}", falling back to open-api pool indices`,
1524
- w
1525
- );
1526
- }
1527
- });
1528
- const g = m.slice(s.length).map((d) => d.returnValues?.map((f) => l.vector(ze).parse(Uint8Array.from(f[0])))[0] || []), y = [];
1529
- return g.forEach((d, f) => {
1530
- const w = t[f], k = P(w.market), _ = b[k.key] || {};
1531
- d.forEach((j) => {
1532
- if (j.supply_balance === "0" && j.borrow_balance === "0" && (w.emodeId === void 0 || !r?.includeZeroBalanceEmodePositions))
1533
- return;
1534
- const T = c[`${k.key}-${j.asset_id}`];
1535
- if (!T)
1536
- return;
1537
- const $ = _[j.asset_id], D = $?.supplyIndex ?? T.currentSupplyIndex, B = $?.borrowIndex ?? T.currentBorrowIndex, X = me(j.supply_balance, D).toString(), Ve = me(j.borrow_balance, B).toString();
1538
- y.push({
1539
- supplyBalance: X,
1540
- borrowBalance: Ve,
1541
- assetId: j.asset_id,
1542
- market: k.key,
1543
- pool: T,
1544
- emodeId: w.emodeId
1545
- });
1546
- });
1547
- }), y;
1548
- }
1549
- const sr = O(
1550
- async (e, t) => {
1551
- const o = (t?.markets || Object.keys(L)).map((n) => P(n)).map((n) => ({
1552
- address: e,
1553
- market: n.key
1554
- }));
1555
- return await $e(e, o, t);
1556
- }
1557
- );
1558
- async function ur(e, t) {
1559
- const r = t?.client ?? M, o = new q();
1560
- await Bt(o, e, t);
1561
- const n = await W(r, {
1562
- transactionBlock: o,
1563
- sender: e
1564
- }), a = Z(n, [l.u256()]);
1565
- return Pe(Number(a[0]) || 0);
1566
- }
1567
- async function lr(e, t, r, o) {
1568
- const n = o?.client ?? M, a = new q();
1569
- let c = 0, i = 0;
1570
- const s = await E(t, o);
1571
- if (r.forEach((g) => {
1572
- 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);
1573
- }), c * i < 0)
1574
- throw new Error("Invalid operations");
1575
- const u = c > 0 || i > 0;
1576
- await Ae(
1577
- a,
1578
- e,
1579
- s,
1580
- Math.abs(c),
1581
- Math.abs(i),
1582
- u,
1583
- o
1584
- );
1585
- const m = await W(n, {
1586
- transactionBlock: a,
1587
- sender: e
1588
- }), b = Z(m, [l.u256()]);
1589
- return Pe(Number(b[0]) || 0);
1590
- }
1591
- const dr = A(
1592
- async (e, t) => {
1593
- const r = new URLSearchParams();
1594
- t?.cursor && r.set("cursor", t.cursor), r.set("userAddress", e);
1595
- const o = U(t), n = F(
1596
- `/navi/user/transactions?${r.toString()}&sdk=${V.version}`,
1597
- t
1598
- );
1599
- return (await fetch(n, {
1600
- headers: N(R, o)
1601
- }).then((c) => c.json())).data;
1602
- }
1603
- );
1604
- async function pr(e, t) {
1605
- let r = null;
1606
- const o = [], n = t?.client ?? M, a = n.core;
1607
- do {
1608
- let c;
1609
- if (t?.coinType)
1610
- if (typeof a?.listCoins == "function") {
1611
- const i = await a.listCoins({
1612
- owner: e,
1613
- coinType: t?.coinType,
1614
- cursor: r,
1615
- limit: 100
1616
- });
1617
- c = {
1618
- data: (i.objects ?? i.data ?? []).map((s) => ye(s, t?.coinType)).filter(Boolean),
1619
- nextCursor: i.cursor ?? i.nextCursor ?? null,
1620
- hasNextPage: i.hasNextPage ?? !1
1621
- };
1622
- } else {
1623
- if (typeof n.getCoins != "function")
1624
- throw new Error("getCoins requires core.listCoins or an explicit legacy getCoins client");
1625
- c = await n.getCoins({
1626
- owner: e,
1627
- coinType: t?.coinType,
1628
- cursor: r,
1629
- limit: 100
1630
- });
1631
- }
1632
- else if (typeof a?.listBalances == "function" && typeof a?.listCoins == "function") {
1633
- const i = /* @__PURE__ */ new Set();
1634
- let s = null;
1635
- do {
1636
- const u = await a.listBalances({
1637
- owner: e,
1638
- cursor: s,
1639
- limit: 100
1640
- });
1641
- for (const m of u.balances ?? [])
1642
- m?.coinType && i.add(m.coinType);
1643
- s = u.cursor ?? u.nextCursor ?? null;
1644
- } while (s);
1645
- for (const u of i) {
1646
- let m = null;
1647
- do {
1648
- const b = await a.listCoins({
1649
- owner: e,
1650
- coinType: u,
1651
- cursor: m,
1652
- limit: 100
1653
- });
1654
- o.push(
1655
- ...(b.objects ?? b.data ?? []).map((g) => ye(g, u)).filter(Boolean)
1656
- ), m = b.cursor ?? b.nextCursor ?? null;
1657
- } while (m);
1658
- }
1659
- break;
1660
- } else {
1661
- if (typeof n.getAllCoins != "function")
1662
- throw new Error(
1663
- "getCoins requires core.listBalances/core.listCoins or an explicit legacy getAllCoins client"
1664
- );
1665
- c = await n.getAllCoins({
1666
- owner: e,
1667
- cursor: r,
1668
- limit: 100
1669
- });
1670
- }
1671
- if (!c.data || !c.data.length)
1672
- break;
1673
- o.push(...c.data), r = c.nextCursor;
1674
- } while (r);
1675
- return o;
1676
- }
1677
- const Pt = O(
1678
- async (e, t) => {
1679
- const r = [], o = (t?.markets || Object.keys(L)).map((i) => P(i)), n = await Se(e, t), a = o.map((i) => ({
1680
- address: e,
1681
- market: i.key
1682
- })).concat(
1683
- n.filter((i) => !!o.find((s) => s.id === i.marketId)).map((i) => ({
1684
- address: i.accountCap,
1685
- market: P(i.marketId).key,
1686
- emodeId: i.emodeId
1687
- }))
1688
- );
1689
- return (await $e(e, a, t)).forEach((i) => {
1690
- const s = typeof i.emodeId == "number" ? n.find((u) => {
1691
- const m = P(i.market);
1692
- return u.emodeId === i.emodeId && u.marketId === m.id;
1693
- }) : void 0;
1694
- if (s) {
1695
- if (!i.pool.emodes.find((m) => m.emodeId === s.emodeId))
1696
- return;
1697
- if (p(i.supplyBalance).gte(0)) {
1698
- const m = p(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN), b = K(i.pool, s);
1699
- if (m.gt(0) || b.emode.isCollateral)
1700
- try {
1701
- r.push({
1702
- id: `${i.pool.uniqueId}_${s.emodeId}_navi-lending-emode-supply-${S()}`,
1703
- wallet: e,
1704
- protocol: "navi",
1705
- market: i.market,
1706
- type: "navi-lending-emode-supply",
1707
- "navi-lending-emode-supply": {
1708
- amount: m.toString(),
1709
- pool: K(i.pool, s),
1710
- token: i.pool.token,
1711
- valueUSD: m.multipliedBy(i.pool.oracle.price).toString(),
1712
- emodeCap: s
1713
- }
1714
- });
1715
- } catch (g) {
1716
- console.error(g);
1717
- }
1718
- }
1719
- if (p(i.borrowBalance).gte(0)) {
1720
- const m = p(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN), b = K(i.pool, s);
1721
- if (m.gt(0) || b.emode.isDebt)
1722
- try {
1723
- r.push({
1724
- id: `${i.pool.uniqueId}_${s.emodeId}_navi-lending-emode-borrow-${S()}`,
1725
- wallet: e,
1726
- protocol: "navi",
1727
- market: i.market,
1728
- type: "navi-lending-emode-borrow",
1729
- "navi-lending-emode-borrow": {
1730
- amount: m.toString(),
1731
- pool: K(i.pool, s),
1732
- token: i.pool.token,
1733
- valueUSD: m.multipliedBy(i.pool.oracle.price).toString(),
1734
- emodeCap: s
1735
- }
1736
- });
1737
- } catch (g) {
1738
- console.error(g);
1739
- }
1740
- }
1741
- } else {
1742
- if (p(i.supplyBalance).gt(0)) {
1743
- const u = p(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN);
1744
- r.push({
1745
- id: `${i.pool.uniqueId}_navi-lending-supply-${S()}`,
1746
- wallet: e,
1747
- protocol: "navi",
1748
- type: "navi-lending-supply",
1749
- market: i.market,
1750
- "navi-lending-supply": {
1751
- amount: u.toString(),
1752
- pool: i.pool,
1753
- token: i.pool.token,
1754
- valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
1755
- }
1756
- });
1757
- }
1758
- if (p(i.borrowBalance).gt(0)) {
1759
- const u = p(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals, p.ROUND_DOWN);
1760
- r.push({
1761
- id: `${i.pool.uniqueId}_navi-lending-borrow-${S()}`,
1762
- wallet: e,
1763
- protocol: "navi",
1764
- market: i.market,
1765
- type: "navi-lending-borrow",
1766
- "navi-lending-borrow": {
1767
- amount: u.toString(),
1768
- pool: i.pool,
1769
- token: i.pool.token,
1770
- valueUSD: u.multipliedBy(i.pool.oracle.price).toString()
1771
- }
1772
- });
1773
- }
1774
- }
1775
- }), r;
1776
- }
1777
- );
1778
- class G {
1779
- constructor(t, r) {
1780
- this._positions = [], this._priceMap = {}, this._overview = {
1781
- hf: 1 / 0,
1782
- netVaule: "0",
1783
- netWorthApr: "0",
1784
- totalSupplyValue: "0",
1785
- totalBorrowValue: "0",
1786
- totalsupplyApy: "0",
1787
- totalBorrowApy: "0",
1788
- maxLiquidationValue: "0",
1789
- maxLoanToVaule: "0",
1790
- supply: {},
1791
- borrow: {}
1792
- }, this._priceMap = r || {}, this.positions = t;
1793
- }
1794
- get positions() {
1795
- return this._positions;
1796
- }
1797
- get overview() {
1798
- return this._overview;
1799
- }
1800
- get priceMap() {
1801
- return this._priceMap;
1802
- }
1803
- set positions(t) {
1804
- this._positions = t, this._overview = this.getPositionsOverview(t);
1805
- }
1806
- updatePriceMap(t) {
1807
- return this._priceMap = t, this._overview = this.getPositionsOverview(this._positions), this;
1808
- }
1809
- getPrice(t) {
1810
- const r = C(t.suiCoinType);
1811
- if (this._priceMap[r] !== void 0)
1812
- return this._priceMap[r].toString();
1813
- const o = t.suiCoinType;
1814
- return this._priceMap[o] !== void 0 ? this._priceMap[o].toString() : t.oracle.price;
1815
- }
1816
- filterPositionsByPool(t) {
1817
- const o = !!t.isEMode ? ["navi-lending-emode-supply", "navi-lending-emode-borrow"] : ["navi-lending-supply", "navi-lending-borrow"];
1818
- return new G(
1819
- this.positions.filter((n) => {
1820
- const a = n[n.type];
1821
- return o.includes(n.type) && a.pool.uniqueId === t.uniqueId;
1822
- }),
1823
- this._priceMap
1824
- );
1825
- }
1826
- deposit(t, r) {
1827
- const o = !!t.isEMode, n = this.getPrice(t);
1828
- let a;
1829
- return o ? a = {
1830
- id: S(),
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: S(),
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
- withdraw(t, r) {
1857
- const o = !!t.isEMode, n = this.getPrice(t);
1858
- let a;
1859
- return o ? a = {
1860
- id: S(),
1861
- wallet: "",
1862
- protocol: "navi",
1863
- market: "",
1864
- type: "navi-lending-emode-supply",
1865
- "navi-lending-emode-supply": {
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: S(),
1874
- wallet: "",
1875
- protocol: "navi",
1876
- market: "",
1877
- type: "navi-lending-supply",
1878
- "navi-lending-supply": {
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
- borrow(t, r) {
1887
- const o = !!t.isEMode, n = this.getPrice(t);
1888
- let a;
1889
- return o ? a = {
1890
- id: S(),
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: S(),
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
- repay(t, r) {
1917
- const o = !!t.isEMode, n = this.getPrice(t);
1918
- let a;
1919
- return o ? a = {
1920
- id: S(),
1921
- wallet: "",
1922
- protocol: "navi",
1923
- market: "",
1924
- type: "navi-lending-emode-borrow",
1925
- "navi-lending-emode-borrow": {
1926
- amount: (-r).toString(),
1927
- valueUSD: p(-r).multipliedBy(n).toString(),
1928
- token: t.token,
1929
- pool: t,
1930
- emodeCap: {}
1931
- }
1932
- } : a = {
1933
- id: S(),
1934
- wallet: "",
1935
- protocol: "navi",
1936
- market: "",
1937
- type: "navi-lending-borrow",
1938
- "navi-lending-borrow": {
1939
- amount: (-r).toString(),
1940
- valueUSD: p(-r).multipliedBy(n).toString(),
1941
- token: t.token,
1942
- pool: t
1943
- }
1944
- }, new G([...this.positions, a], this._priceMap);
1945
- }
1946
- resolveValueUSD(t) {
1947
- return Object.keys(this._priceMap).length > 0 ? p(t.amount).multipliedBy(this.getPrice(t.pool)).toString() : t.valueUSD;
1948
- }
1949
- getPositionsOverview(t) {
1950
- const r = {}, o = {};
1951
- 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);
1952
- t.forEach((y) => {
1953
- if (y.type === "navi-lending-supply") {
1954
- const d = y["navi-lending-supply"], f = this.resolveValueUSD(d);
1955
- n = n.plus(f), s = s.plus(
1956
- new p(f).multipliedBy(d.pool.liquidationFactor.threshold)
1957
- ), u = u.plus(
1958
- new p(f).multipliedBy(d.pool.ltvValue)
1959
- );
1960
- } else if (y.type === "navi-lending-borrow") {
1961
- const d = y["navi-lending-borrow"];
1962
- a = a.plus(this.resolveValueUSD(d));
1963
- } else if (y.type === "navi-lending-emode-supply") {
1964
- const d = y["navi-lending-emode-supply"], f = this.resolveValueUSD(d);
1965
- n = n.plus(f);
1966
- const w = d.pool.emode;
1967
- s = s.plus(
1968
- new p(f).multipliedBy(w.lt)
1969
- ), u = u.plus(
1970
- new p(f).multipliedBy(w.ltv)
1971
- );
1972
- } else if (y.type === "navi-lending-emode-borrow") {
1973
- const d = y["navi-lending-emode-borrow"];
1974
- a = a.plus(this.resolveValueUSD(d));
1975
- }
1976
- }), a = p.max(a, 0), n = p.max(n, 0), s = p.max(s, 0), u = p.max(u, 0), t.forEach((y) => {
1977
- if (y.type === "navi-lending-supply") {
1978
- const d = y["navi-lending-supply"], f = this.resolveValueUSD(d), w = d.pool.supplyIncentiveApyInfo.apy;
1979
- n.gt(0) && (c = c.plus(
1980
- new p(f).dividedBy(n).multipliedBy(new p(w).dividedBy(100))
1981
- )), r[d.pool.suiCoinType] = p(r[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1982
- } else if (y.type === "navi-lending-borrow") {
1983
- const d = y["navi-lending-borrow"], f = this.resolveValueUSD(d), w = d.pool.borrowIncentiveApyInfo.apy;
1984
- a.gt(0) && (i = i.plus(
1985
- new p(f).dividedBy(a).multipliedBy(new p(w).dividedBy(100))
1986
- )), o[d.pool.suiCoinType] = p(o[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1987
- } else if (y.type === "navi-lending-emode-supply") {
1988
- const d = y["navi-lending-emode-supply"], f = this.resolveValueUSD(d), w = d.pool.supplyIncentiveApyInfo.apy;
1989
- n.gt(0) && (c = c.plus(
1990
- new p(f).dividedBy(n).multipliedBy(new p(w).dividedBy(100))
1991
- )), r[d.pool.suiCoinType] = p(r[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1992
- } else if (y.type === "navi-lending-emode-borrow") {
1993
- const d = y["navi-lending-emode-borrow"], f = this.resolveValueUSD(d), w = d.pool.borrowIncentiveApyInfo.apy;
1994
- a.gt(0) && (i = i.plus(
1995
- new p(f).dividedBy(a).multipliedBy(new p(w).dividedBy(100))
1996
- )), o[d.pool.suiCoinType] = p(o[d.pool.suiCoinType] || 0).plus(d.amount).toString();
1997
- }
1998
- });
1999
- const m = n.minus(a), b = n.minus(a).eq(0) ? new p(0) : n.multipliedBy(c).minus(a.multipliedBy(i)).div(n.minus(a));
2000
- return {
2001
- hf: a.toNumber() !== 0 ? s.dividedBy(a).toNumber() : 1 / 0,
2002
- netVaule: m.toString(),
2003
- netWorthApr: b.toString(),
2004
- totalSupplyValue: n.toString(),
2005
- totalBorrowValue: a.toString(),
2006
- totalsupplyApy: c.toString(),
2007
- totalBorrowApy: i.toString(),
2008
- maxLiquidationValue: s.toString(),
2009
- maxLoanToVaule: u.toString(),
2010
- supply: r,
2011
- borrow: o
2012
- };
2013
- }
2014
- }
2015
- async function mr(e, t, r, o) {
2016
- const n = await I({
2017
- ...o,
2018
- cacheTime: v
2019
- });
2020
- n.limter && e.moveCall({
2021
- target: `${n.limter}::navi_adaptor::verify_navi_position_healthy`,
2022
- arguments: [
2023
- e.object("0x06"),
2024
- e.object(n.storage),
2025
- e.object(n.priceOracle),
2026
- h(t, e.pure.address),
2027
- e.pure.u256(new p(r).shiftedBy(27).toNumber())
2028
- ]
2029
- });
2030
- }
2031
- const Ee = new Ie("https://hermes.pyth.network", {
2032
- timeout: 1e4
2033
- });
2034
- async function fr(e) {
2035
- try {
2036
- const t = [], r = await Ee.getLatestPriceFeeds(e);
2037
- if (!r) return t;
2038
- const o = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2039
- for (const n of r) {
2040
- const a = n.getPriceUnchecked();
2041
- if (a.publishTime > o) {
2042
- console.warn(
2043
- `pyth price feed is invalid, id: ${n.id}, publish time: ${a.publishTime}, current timestamp: ${o}`
2044
- );
2045
- continue;
2046
- }
2047
- o - n.getPriceUnchecked().publishTime > 30 && (console.info(
2048
- `stale price feed, id: ${n.id}, publish time: ${a.publishTime}, current timestamp: ${o}`
2049
- ), t.push(n.id));
2050
- }
2051
- return t;
2052
- } catch (t) {
2053
- throw new Error(`failed to get pyth stale price feed id, msg: ${t.message}`);
2054
- }
2055
- }
2056
- async function St(e, t) {
2057
- const r = [], o = t?.client ?? M, n = e.map((c) => c.priceInfoObject), a = await gt(o, {
2058
- ids: Array.from(new Set(n)),
2059
- options: { showContent: !0 }
2060
- });
2061
- for (const c of a) {
2062
- const i = c.data;
2063
- if (!i || !i.content || i.content.dataType !== "moveObject") {
2064
- console.warn(`fetched object ${i?.objectId} datatype should be moveObject`);
2065
- continue;
2066
- }
2067
- const s = e.find((f) => f.priceInfoObject == i.objectId);
2068
- if (!s) {
2069
- console.warn(`unable to find pyth info from array, priceInfoObject: ${i.objectId}`);
2070
- continue;
2071
- }
2072
- const u = i.content.fields?.price_info?.price_feed?.price, m = u?.price;
2073
- if (!m) {
2074
- console.warn(`unexpected pyth price struct, priceInfoObject: ${i.objectId}`);
2075
- continue;
2076
- }
2077
- const { magnitude: b, negative: g } = m, y = u.conf, d = u.timestamp;
2078
- r.push({
2079
- priceFeedId: s.priceFeedId,
2080
- priceInfoObject: s.priceInfoObject,
2081
- price: g ? "-" + b : b,
2082
- conf: y,
2083
- publishTime: Number(d),
2084
- expiration: s.expiration
2085
- });
2086
- }
2087
- return r;
2088
- }
2089
- async function At(e, t) {
2090
- try {
2091
- const r = [], o = await St(e, t);
2092
- if (!o) return r;
2093
- const n = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
2094
- for (const a of o) {
2095
- if (a.publishTime > n) {
2096
- console.warn(
2097
- `pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2098
- );
2099
- continue;
2100
- }
2101
- const c = a.expiration || 60;
2102
- n - a.publishTime > c && (console.info(
2103
- `stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${n}`
2104
- ), r.push(a.priceFeedId));
2105
- }
2106
- return r;
2107
- } catch (r) {
2108
- throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`);
2109
- }
2110
- }
2111
- async function $t(e, t, r) {
2112
- const o = r?.client ?? M, n = await I({
2113
- ...r,
2114
- cacheTime: v
2115
- });
2116
- try {
2117
- const a = await Ee.getPriceFeedsUpdateData(t);
2118
- return await new lt(
2119
- o,
2120
- n.oracle.pythStateId,
2121
- n.oracle.wormholeStateId
2122
- ).updatePriceFeeds(e, a, t);
2123
- } catch (a) {
2124
- throw new Error(`failed to update pyth price feeds, msg: ${a.message}`);
2125
- }
2126
- }
2127
- async function ge(e, t, r) {
2128
- const o = await I({
2129
- ...r,
2130
- cacheTime: v
2131
- });
2132
- if (r?.updatePythPriceFeeds) {
2133
- const n = t.filter((c) => !!c.pythPriceFeedId && !!c.pythPriceInfoObject).map((c) => ({
2134
- priceFeedId: c.pythPriceFeedId,
2135
- priceInfoObject: c.pythPriceInfoObject,
2136
- expiration: 30
2137
- })), a = await At(n, r);
2138
- a.length > 0 && await $t(e, a, r);
2139
- }
2140
- for (const n of t)
2141
- e.moveCall({
2142
- target: `${o.oracle.packageId}::oracle_pro::update_single_price_v2`,
2143
- arguments: [
2144
- e.object("0x6"),
2145
- // Clock object
2146
- e.object(o.oracle.oracleConfig),
2147
- // Oracle configuration
2148
- e.object(o.oracle.priceOracle),
2149
- // Price oracle contract
2150
- e.object(o.oracle.supraOracleHolder),
2151
- // Supra oracle holder
2152
- e.object(n.pythPriceInfoObject),
2153
- // Pyth price info object
2154
- e.object(o.oracle.switchboardAggregator),
2155
- e.pure.address(n.feedId)
2156
- // Price feed ID
2157
- ]
2158
- });
2159
- return e;
2160
- }
2161
- async function Oe(e) {
2162
- return (await I({
2163
- ...e,
2164
- cacheTime: v
2165
- })).oracle.feeds;
2166
- }
2167
- function Et(e, t) {
2168
- return e.filter((r) => !!(t?.lendingState && t.lendingState.find((n) => r.oracleId === n.pool.oracleId) || t?.lendingPositions && t.lendingPositions.find((n) => {
2169
- if (![
2170
- "navi-lending-supply",
2171
- "navi-lending-borrow",
2172
- "navi-lending-emode-supply",
2173
- "navi-lending-emode-borrow"
2174
- ].includes(n.type))
2175
- return !1;
2176
- const c = n[n.type]?.pool;
2177
- return r.oracleId === c?.oracleId;
2178
- }) || t?.pools && t.pools.find((n) => r.oracleId === n.oracleId)));
2179
- }
2180
- async function yr(e, t, r, o) {
2181
- let n;
2182
- try {
2183
- const a = await Oe({
2184
- ...o
2185
- }), c = [];
2186
- r.forEach((u) => {
2187
- c.includes(u.market) || c.push(u.market);
2188
- });
2189
- const i = await Pt(t, {
2190
- ...o,
2191
- markets: c
2192
- });
2193
- return n = Et(a, {
2194
- lendingPositions: i,
2195
- pools: r
2196
- }), await ge(e, n, {
2197
- updatePythPriceFeeds: !0,
2198
- ...o
2199
- });
2200
- } catch (a) {
2201
- if (o?.throws)
2202
- throw a;
2203
- if (console.error(a), n)
2204
- try {
2205
- return await ge(e, n, {
2206
- ...o,
2207
- updatePythPriceFeeds: !1
2208
- });
2209
- } catch (c) {
2210
- console.error(c);
2211
- }
2212
- return e;
2213
- }
2214
- }
2215
- const ae = O(
2216
- A(
2217
- async (e) => {
2218
- const t = U(e), r = F(
2219
- `/navi/flashloan?env=${e?.env || "prod"}&sdk=${V.version}&market=${e?.market || z}`,
2220
- e
2221
- ), o = await fetch(r, {
2222
- headers: N(R, t)
2223
- }).then((n) => n.json());
2224
- return Object.keys(o.data).map((n) => ({
2225
- ...o.data[n],
2226
- coinType: n
2227
- }));
2228
- }
2229
- )
2230
- );
2231
- async function gr(e, t) {
2232
- 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;
2233
- }
2234
- async function hr(e, t, r, o) {
2235
- const n = await I({
2236
- ...o,
2237
- cacheTime: v
2238
- }), a = await E(t, o);
2239
- if (!(await ae({
2240
- ...o,
2241
- cacheTime: v
2242
- })).some(
2243
- (s) => C(s.coinType) === C(a.suiCoinType)
2244
- ))
2245
- throw new Error("Pool does not support flashloan");
2246
- if (n.version === 1) {
2247
- const [s, u] = e.moveCall({
2248
- target: `${n.package}::lending::flash_loan_with_ctx`,
2249
- arguments: [
2250
- e.object(n.flashloanConfig),
2251
- e.object(a.contract.pool),
2252
- h(r, e.pure.u64)
2253
- ],
2254
- typeArguments: [a.suiCoinType]
2255
- });
2256
- return [s, u];
2257
- } else {
2258
- const [s, u] = e.moveCall({
2259
- target: `${n.package}::lending::flash_loan_with_ctx_v2`,
2260
- arguments: [
2261
- e.object(n.flashloanConfig),
2262
- e.object(a.contract.pool),
2263
- h(r, e.pure.u64),
2264
- e.object("0x05")
2265
- ],
2266
- typeArguments: [a.suiCoinType]
2267
- });
2268
- return [s, u];
2269
- }
2270
- }
2271
- async function br(e, t, r, o, n) {
2272
- const a = await I({
2273
- ...n,
2274
- cacheTime: v
2275
- }), c = await E(t, n);
2276
- if (!(await ae({
2277
- ...n,
2278
- cacheTime: v
2279
- })).some(
2280
- (m) => C(m.coinType) === C(c.suiCoinType)
2281
- ))
2282
- throw new Error("Pool does not support flashloan");
2283
- const [u] = e.moveCall({
2284
- target: `${a.package}::lending::flash_repay_with_ctx`,
2285
- arguments: [
2286
- e.object("0x06"),
2287
- e.object(a.storage),
2288
- e.object(c.contract.pool),
2289
- h(r, e.object),
2290
- h(o, e.object)
2291
- ],
2292
- typeArguments: [c.suiCoinType]
2293
- });
2294
- return [u];
2295
- }
2296
- async function wr(e, t, r, o, n, a) {
2297
- const c = {
2298
- ...a,
2299
- cacheTime: v
2300
- }, i = await I(c), s = await E(t, c), u = await E(o, c);
2301
- if (i.version === 1) {
2302
- const [m, b] = e.moveCall({
2303
- target: `${i.package}::incentive_v3::liquidation`,
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
- ],
2328
- typeArguments: [s.suiCoinType, u.suiCoinType]
2329
- });
2330
- return [m, b];
2331
- } else {
2332
- const [m, b] = e.moveCall({
2333
- target: `${i.package}::incentive_v3::liquidation_v2`,
2334
- arguments: [
2335
- e.object("0x06"),
2336
- // Clock object
2337
- e.object(i.priceOracle),
2338
- // Price oracle for asset pricing
2339
- e.object(i.storage),
2340
- // Protocol storage
2341
- e.pure.u8(s.id),
2342
- // Pay asset ID
2343
- e.object(s.contract.pool),
2344
- // Pay asset pool contract
2345
- h(r, e.object),
2346
- // Debt repayment amount
2347
- e.pure.u8(u.id),
2348
- // Collateral asset ID
2349
- e.object(u.contract.pool),
2350
- // Collateral asset pool contract
2351
- h(n, e.pure.address),
2352
- // Borrower address
2353
- e.object(i.incentiveV2),
2354
- // Incentive V2 contract
2355
- e.object(i.incentiveV3),
2356
- // Incentive V3 contract
2357
- e.object("0x05")
2358
- // SuiSystemState object
2359
- ],
2360
- typeArguments: [s.suiCoinType, u.suiCoinType]
2361
- });
2362
- return [m, b];
2363
- }
2364
- }
2365
- async function Ot(e, t, r) {
2366
- const o = r?.client ?? M, n = await J({
2367
- ...r,
2368
- markets: Object.values(L),
2369
- cacheTime: v
2370
- }), a = await Oe(r), c = [];
2371
- return await Promise.all(
2372
- t.map(async (i) => {
2373
- try {
2374
- const s = await I({
2375
- ...r,
2376
- cacheTime: v,
2377
- market: i.market
2378
- }), u = new q();
2379
- u.moveCall({
2380
- target: `${s.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
2381
- arguments: [
2382
- u.object("0x06"),
2383
- // Clock object
2384
- u.object(s.storage),
2385
- // Protocol storage
2386
- u.object(s.incentiveV3),
2387
- // Incentive V3 contract
2388
- u.pure.address(i.address)
2389
- // User address
2390
- ]
2391
- });
2392
- const b = (await W(o, {
2393
- transactionBlock: u,
2394
- sender: e
2395
- }))?.results?.[0];
2396
- if (!b)
2397
- return;
2398
- const g = Z({ results: [b] }, [
2399
- l.vector(l.string()),
2400
- // Asset coin types
2401
- l.vector(l.string()),
2402
- // Reward coin types
2403
- l.vector(l.u8()),
2404
- // Reward options
2405
- l.vector(l.Address),
2406
- // Rule IDs
2407
- l.vector(l.u256())
2408
- // Claimable amounts
2409
- ]);
2410
- if (g.length === 5 && Array.isArray(g[0])) {
2411
- const y = g[0].length;
2412
- for (let d = 0; d < y; d++) {
2413
- const f = a.find(
2414
- (k) => C(k.coinType) === C(g[1][d])
2415
- ), w = n.find(
2416
- (k) => C(k.coinType) === C(g[0][d]) && k.market === i.market
2417
- );
2418
- !f || !w || c.push({
2419
- assetId: w.id,
2420
- assetCoinType: C(g[0][d]),
2421
- rewardCoinType: C(g[1][d]),
2422
- option: Number(g[2][d]),
2423
- userClaimableReward: Number(g[4][d]) / Math.pow(10, f.priceDecimal),
2424
- ruleIds: Array.isArray(g[3][d]) ? g[3][d] : [g[3][d]],
2425
- market: i.market,
2426
- owner: i.owner,
2427
- address: i.address,
2428
- emodeId: i.emodeId
2429
- });
2430
- }
2431
- }
2432
- } catch (s) {
2433
- console.error(
2434
- `[lending] getLendingRewardsBatch task failed (market=${i.market}, address=${i.address}):`,
2435
- s
2436
- );
2437
- }
2438
- })
2439
- ), c;
2440
- }
2441
- async function vr(e, t) {
2442
- const r = (t?.markets || [L.main]).map((a) => P(a)), o = await Se(e, t), n = r.map((a) => ({
2443
- address: e,
2444
- owner: e,
2445
- market: a.key
2446
- })).concat(
2447
- o.filter((a) => !!r.find((c) => c.id === a.marketId)).map((a) => {
2448
- const c = P(a.marketId);
2449
- return {
2450
- address: a.accountCap,
2451
- owner: e,
2452
- market: c.key,
2453
- emodeId: a.emodeId
2454
- };
2455
- })
2456
- );
2457
- return await Ot(e, n, t);
2458
- }
2459
- function Cr(e) {
2460
- const t = /* @__PURE__ */ new Map();
2461
- e.forEach((o) => {
2462
- const n = o.assetId, a = o.option, c = `${n}-${a}-${o.rewardCoinType}-${o.market}`;
2463
- t.has(c) ? t.get(c).total += o.userClaimableReward : t.set(c, {
2464
- assetId: n,
2465
- rewardType: a,
2466
- coinType: o.rewardCoinType,
2467
- total: Number(o.userClaimableReward),
2468
- market: o.market
2469
- });
2470
- });
2471
- const r = /* @__PURE__ */ new Map();
2472
- for (const { assetId: o, rewardType: n, coinType: a, total: c, market: i } of t.values()) {
2473
- const s = `${o}-${n}-${i}`;
2474
- r.has(s) || r.set(s, { assetId: o, rewardType: n, market: i, rewards: /* @__PURE__ */ new Map() });
2475
- const u = r.get(s);
2476
- u.rewards.set(a, (u.rewards.get(a) || 0) + c);
2477
- }
2478
- return Array.from(r.values()).map((o) => ({
2479
- assetId: o.assetId,
2480
- rewardType: o.rewardType,
2481
- market: o.market,
2482
- rewards: Array.from(o.rewards.entries()).map(([n, a]) => ({
2483
- coinType: n,
2484
- available: a.toFixed(6)
2485
- }))
2486
- }));
2487
- }
2488
- const kr = A(
2489
- async (e, t) => {
2490
- const r = U(t), o = F(
2491
- `/navi/user/total_claimed_reward?userAddress=${e}&sdk=${V.version}&market=${t?.market || z}`,
2492
- t
2493
- );
2494
- return (await fetch(o, {
2495
- headers: N(R, r)
2496
- }).then((a) => a.json())).data;
2497
- }
2498
- ), Ir = A(
2499
- async (e, t) => {
2500
- const r = U(t), o = F(
2501
- `/navi/user/rewards?userAddress=${e}&page=${t?.page || 1}&pageSize=${t?.size || 400}&sdk=${V.version}&market=${t?.market || z}`,
2502
- t
2503
- ), n = await fetch(o, {
2504
- headers: N(R, r)
2505
- }).then((a) => a.json());
2506
- return re({
2507
- data: n.data.rewards
2508
- });
2509
- }
2510
- );
2511
- async function jr(e, t, r) {
2512
- const o = await J({
2513
- ...r,
2514
- markets: Object.values(L),
2515
- cacheTime: v
2516
- }), n = /* @__PURE__ */ new Map();
2517
- for (const c of t) {
2518
- const { rewardCoinType: i, ruleIds: s, market: u, owner: m, address: b, emodeId: g } = c, y = `${i}___${b}__${u}`;
2519
- for (const d of s) {
2520
- n.has(y) || n.set(y, {
2521
- assetIds: [],
2522
- ruleIds: [],
2523
- amount: 0,
2524
- market: u,
2525
- owner: m,
2526
- address: b,
2527
- isEMode: typeof g < "u"
2528
- });
2529
- const f = n.get(y);
2530
- f.assetIds.push(c.assetCoinType.replace("0x", "")), f.ruleIds.push(d), f.amount += c.userClaimableReward;
2531
- }
2532
- }
2533
- const a = [];
2534
- for (const [
2535
- c,
2536
- { assetIds: i, ruleIds: s, amount: u, market: m, owner: b, address: g, isEMode: y }
2537
- ] of n) {
2538
- const d = await I({
2539
- ...r,
2540
- cacheTime: v,
2541
- market: m
2542
- }), f = c.split("___")[0], w = o.filter(
2543
- (j) => C(j.suiCoinType) === C(f)
2544
- );
2545
- w.sort((j, T) => j.market === m ? -1 : 1);
2546
- const k = w[0], _ = d.rewardFunds[C(f)];
2547
- if (!_)
2548
- throw new Error(`No matching rewardFund found for reward coin: ${f} ${m}`);
2549
- if (r?.accountCap && !r.customCoinReceive)
2550
- throw new Error("customCoinReceive is required when accountCap is provided");
2551
- if (r?.customCoinReceive) {
2552
- let j;
2553
- r.accountCap ? j = e.moveCall({
2554
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2555
- arguments: [
2556
- e.object("0x06"),
2557
- // Clock object
2558
- e.object(d.incentiveV3),
2559
- // Incentive V3 contract
2560
- e.object(d.storage),
2561
- // Protocol storage
2562
- e.object(_),
2563
- // Reward fund
2564
- e.pure.vector("string", i),
2565
- // Asset IDs
2566
- e.pure.vector("address", s),
2567
- // Rule IDs
2568
- h(r.accountCap, e.object)
2569
- // Account capability
2570
- ],
2571
- typeArguments: [f]
2572
- }) : y ? j = e.moveCall({
2573
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2574
- arguments: [
2575
- e.object("0x06"),
2576
- // Clock object
2577
- e.object(d.incentiveV3),
2578
- // Incentive V3 contract
2579
- e.object(d.storage),
2580
- // Protocol storage
2581
- e.object(_),
2582
- // Reward fund
2583
- e.pure.vector("string", i),
2584
- // Asset IDs
2585
- e.pure.vector("address", s),
2586
- // Rule IDs
2587
- h(g, e.object)
2588
- // Account capability
2589
- ],
2590
- typeArguments: [f]
2591
- }) : j = e.moveCall({
2592
- target: `${d.package}::incentive_v3::claim_reward`,
2593
- arguments: [
2594
- e.object("0x06"),
2595
- // Clock object
2596
- e.object(d.incentiveV3),
2597
- // Incentive V3 contract
2598
- e.object(d.storage),
2599
- // Protocol storage
2600
- e.object(_),
2601
- // Reward fund
2602
- e.pure.vector("string", i),
2603
- // Asset IDs
2604
- e.pure.vector("address", s)
2605
- // Rule IDs
2606
- ],
2607
- typeArguments: [f]
2608
- });
2609
- const [T] = e.moveCall({
2610
- target: "0x2::coin::from_balance",
2611
- arguments: [j],
2612
- typeArguments: [f]
2613
- });
2614
- if (r?.customCoinReceive.type === "transfer") {
2615
- if (!r.customCoinReceive.transfer)
2616
- throw new Error("customCoinReceive.transfer is required");
2617
- e.transferObjects(
2618
- [T],
2619
- h(r.customCoinReceive.transfer, e.pure.address)
2620
- );
2621
- }
2622
- if (r?.customCoinReceive.type === "depositNAVI") {
2623
- const $ = p(k.totalSupplyAmount).shiftedBy(-9), D = p(k.supplyCapCeiling).shiftedBy(-27);
2624
- $.plus(u).isGreaterThan(D) && r?.customCoinReceive.depositNAVI?.fallbackReceiveAddress ? e.transferObjects(
2625
- [T],
2626
- e.pure.address(r.customCoinReceive.depositNAVI.fallbackReceiveAddress)
2627
- ) : await vt(e, k, T, {
2628
- ...r,
2629
- market: k.market
2630
- });
2631
- } else
2632
- a.push({
2633
- coin: T,
2634
- identifier: k,
2635
- owner: b,
2636
- isEMode: y
2637
- });
2638
- } else if (r?.accountCap || y) {
2639
- const j = e.moveCall({
2640
- target: `${d.package}::incentive_v3::claim_reward_with_account_cap`,
2641
- arguments: [
2642
- e.object("0x06"),
2643
- // Clock object
2644
- e.object(d.incentiveV3),
2645
- // Incentive V3 contract
2646
- e.object(d.storage),
2647
- // Protocol storage
2648
- e.object(_),
2649
- // Reward fund
2650
- e.pure.vector("string", i),
2651
- // Asset IDs
2652
- e.pure.vector("address", s),
2653
- // Rule IDs
2654
- h(r?.accountCap || g, e.object)
2655
- // Account capability
2656
- ],
2657
- typeArguments: [f]
2658
- }), [T] = e.moveCall({
2659
- target: "0x2::coin::from_balance",
2660
- arguments: [j],
2661
- typeArguments: [f]
2662
- });
2663
- e.transferObjects(
2664
- [T],
2665
- h(r?.accountCap || b, e.pure.address)
2666
- );
2667
- } else
2668
- e.moveCall({
2669
- target: `${d.package}::incentive_v3::claim_reward_entry`,
2670
- arguments: [
2671
- e.object("0x06"),
2672
- // Clock object
2673
- e.object(d.incentiveV3),
2674
- // Incentive V3 contract
2675
- e.object(d.storage),
2676
- // Protocol storage
2677
- e.object(_),
2678
- // Reward fund
2679
- e.pure.vector("string", i),
2680
- // Asset IDs
2681
- e.pure.vector("address", s)
2682
- // Rule IDs
2683
- ],
2684
- typeArguments: [f]
2685
- });
2686
- }
2687
- return a;
2688
- }
2689
- export {
2690
- ie as Address,
2691
- v as DEFAULT_CACHE_TIME,
2692
- z as DEFAULT_MARKET_IDENTITY,
2693
- Wt as FlashLoanAssetConfig,
2694
- qt as IncentiveAPYInfo,
2695
- Le as IncentivePoolInfo,
2696
- zt as IncentivePoolInfoByPhase,
2697
- L as MARKETS,
2698
- Ct as Market,
2699
- Ke as NaviMissingGraphQLClientError,
2700
- Gt as OracleInfo,
2701
- et as PUBLIC_MAINNET_GRPC_URL,
2702
- H as PoolOperator,
2703
- qe as ReserveDataInfo,
2704
- Ie as SuiPriceServiceConnection,
2705
- lt as SuiPythClient,
2706
- G as UserPositions,
2707
- ze as UserStateInfo,
2708
- er as borrowCoinPTB,
2709
- F as buildNaviOpenApiUrl,
2710
- jr as claimLendingRewardsPTB,
2711
- Yt as configureNaviSdk,
2712
- It as createAccountCapPTB,
2713
- ar as createEModeCapPTB,
2714
- ke as createNaviLegacyJsonRpcClient,
2715
- rt as createNaviSuiClient,
2716
- xe as createNaviSuiClientBundle,
2717
- vt as depositCoinPTB,
2718
- ir as emodeIdentityId,
2719
- _t as enterEModePTB,
2720
- or as exitEModePTB,
2721
- Et as filterPriceFeeds,
2722
- hr as flashloanPTB,
2723
- jt as getAccountCapOwnerPTB,
2724
- Jt as getAddressBalance,
2725
- ae as getAllFlashLoanAssets,
2726
- rr as getBorrowFee,
2727
- Ht as getCoinObjectOnlyBalance,
2728
- pr as getCoins,
2729
- I as getConfig,
2730
- Xt as getFees,
2731
- gr as getFlashLoanAsset,
2732
- ur as getHealthFactor,
2733
- Bt as getHealthFactorPTB,
2734
- Pt as getLendingPositions,
2735
- sr as getLendingState,
2736
- nr as getMarket,
2737
- P as getMarketConfig,
2738
- kt as getMarkets,
2739
- E as getPool,
2740
- J as getPools,
2741
- Oe as getPriceFeeds,
2742
- fr as getPythStalePriceFeedId,
2743
- At as getPythStalePriceFeedIdV2,
2744
- lr as getSimulatedHealthFactor,
2745
- Ae as getSimulatedHealthFactorPTB,
2746
- Zt as getStats,
2747
- dr as getTransactions,
2748
- vr as getUserAvailableLendingRewards,
2749
- Ir as getUserClaimedRewardHistory,
2750
- Se as getUserEModeCaps,
2751
- kr as getUserTotalClaimedReward,
2752
- wr as liquidatePTB,
2753
- Kt as listAddressBalances,
2754
- cr as mergeCoinsPTB,
2755
- N as mergeServiceHeaders,
2756
- Ce as normalizeAddressBalance,
2757
- C as normalizeCoinType,
2758
- wt as parsePoolUID,
2759
- h as parseTxValue,
2760
- tr as repayCoinPTB,
2761
- br as repayFlashLoanPTB,
2762
- Qt as requireNaviGraphQLClient,
2763
- U as resolveNaviOpenApiEndpoint,
2764
- Cr as summaryLendingRewards,
2765
- yr as updateOraclePriceBeforeUserOperationPTB,
2766
- ge as updateOraclePricesPTB,
2767
- $t as updatePythPriceFeeds,
2768
- mr as verifyHealthFactorPTB,
2769
- O as withCache,
2770
- A as withSingleton,
2771
- xt as withdrawCoinPTB
2772
- };
2773
- //# sourceMappingURL=index.esm.js.map