@naviprotocol/lending 1.0.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.
@@ -0,0 +1,983 @@
1
+ import { Transaction as A } from "@mysten/sui/transactions";
2
+ import { bcs as s, toHex as M, fromHex as D } from "@mysten/bcs";
3
+ import { SuiClient as N, getFullnodeUrl as H } from "@mysten/sui/client";
4
+ import q from "lodash.camelcase";
5
+ import { normalizeStructTag as G } from "@mysten/sui/utils";
6
+ import { SuiPriceServiceConnection as V, SuiPythClient as z } from "@pythnetwork/pyth-sui-js";
7
+ import { bcs as b } from "@mysten/sui/bcs";
8
+ const F = s.bytes(32).transform({
9
+ // To change the input type, you need to provide a type definition for the input
10
+ input: (e) => D(e),
11
+ output: (e) => M(e)
12
+ }), oe = s.struct("IncentiveAPYInfo", {
13
+ /** Asset identifier */
14
+ asset_id: s.u8(),
15
+ /** Annual Percentage Yield as a 256-bit integer */
16
+ apy: s.u256(),
17
+ /** List of supported coin types for this incentive */
18
+ coin_types: s.vector(s.string())
19
+ }), W = s.struct("IncentivePoolInfo", {
20
+ /** Unique pool identifier */
21
+ pool_id: F,
22
+ /** Address holding the incentive funds */
23
+ funds: F,
24
+ /** Current phase of the incentive program */
25
+ phase: s.u64(),
26
+ /** Timestamp when the incentive started */
27
+ start_at: s.u64(),
28
+ /** Timestamp when the incentive ends */
29
+ end_at: s.u64(),
30
+ /** Timestamp when the incentive was closed */
31
+ closed_at: s.u64(),
32
+ /** Total supply of incentive tokens */
33
+ total_supply: s.u64(),
34
+ /** Asset identifier for the incentive */
35
+ asset_id: s.u8(),
36
+ /** Option type for the incentive */
37
+ option: s.u8(),
38
+ /** Factor used in incentive calculations */
39
+ factor: s.u256(),
40
+ /** Amount of incentives already distributed */
41
+ distributed: s.u64(),
42
+ /** Amount of incentives currently available */
43
+ available: s.u256(),
44
+ /** Total amount of incentives */
45
+ total: s.u256()
46
+ }), se = s.struct("IncentivePoolInfoByPhase", {
47
+ /** Phase number */
48
+ phase: s.u64(),
49
+ /** List of incentive pools in this phase */
50
+ pools: s.vector(W)
51
+ }), ie = s.struct("OracleInfo", {
52
+ /** Oracle identifier */
53
+ oracle_id: s.u8(),
54
+ /** Current price as a 256-bit integer */
55
+ price: s.u256(),
56
+ /** Number of decimal places for the price */
57
+ decimals: s.u8(),
58
+ /** Whether the oracle data is valid */
59
+ valid: s.bool()
60
+ }), ue = s.struct("FlashLoanAssetConfig", {
61
+ /** Unique identifier for the flash loan asset */
62
+ id: s.string(),
63
+ /** Asset identifier */
64
+ asset_id: s.u8(),
65
+ /** Coin type for the asset */
66
+ coin_type: s.string(),
67
+ /** Pool identifier for the flash loan */
68
+ pool_id: s.string(),
69
+ /** Rate paid to suppliers for flash loans */
70
+ rate_to_supplier: s.u64(),
71
+ /** Rate paid to treasury for flash loans */
72
+ rate_to_treasury: s.u64(),
73
+ /** Maximum flash loan amount */
74
+ max: s.u64(),
75
+ /** Minimum flash loan amount */
76
+ min: s.u64()
77
+ }), le = s.struct("ReserveDataInfo", {
78
+ /** Reserve identifier */
79
+ id: s.u8(),
80
+ /** Oracle identifier for price feeds */
81
+ oracle_id: s.u8(),
82
+ /** Coin type for the reserve */
83
+ coin_type: s.string(),
84
+ /** Maximum supply capacity */
85
+ supply_cap: s.u256(),
86
+ /** Maximum borrow capacity */
87
+ borrow_cap: s.u256(),
88
+ /** Current supply interest rate */
89
+ supply_rate: s.u256(),
90
+ /** Current borrow interest rate */
91
+ borrow_rate: s.u256(),
92
+ /** Current supply index for interest calculation */
93
+ supply_index: s.u256(),
94
+ /** Current borrow index for interest calculation */
95
+ borrow_index: s.u256(),
96
+ /** Total amount supplied to the reserve */
97
+ total_supply: s.u256(),
98
+ /** Total amount borrowed from the reserve */
99
+ total_borrow: s.u256(),
100
+ /** Timestamp of last update */
101
+ last_update_at: s.u64(),
102
+ /** Loan-to-Value ratio for collateral */
103
+ ltv: s.u256(),
104
+ /** Treasury factor for fee calculations */
105
+ treasury_factor: s.u256(),
106
+ /** Current treasury balance */
107
+ treasury_balance: s.u256(),
108
+ /** Base interest rate */
109
+ base_rate: s.u256(),
110
+ /** Interest rate multiplier */
111
+ multiplier: s.u256(),
112
+ /** Jump rate multiplier for high utilization */
113
+ jump_rate_multiplier: s.u256(),
114
+ /** Reserve factor for protocol fees */
115
+ reserve_factor: s.u256(),
116
+ /** Optimal utilization rate */
117
+ optimal_utilization: s.u256(),
118
+ /** Liquidation ratio threshold */
119
+ liquidation_ratio: s.u256(),
120
+ /** Liquidation bonus for liquidators */
121
+ liquidation_bonus: s.u256(),
122
+ /** Liquidation threshold */
123
+ liquidation_threshold: s.u256()
124
+ }), K = s.struct("UserStateInfo", {
125
+ /** Asset identifier */
126
+ asset_id: s.u8(),
127
+ /** User's current borrow balance */
128
+ borrow_balance: s.u256(),
129
+ /** User's current supply balance */
130
+ supply_balance: s.u256()
131
+ }), _ = new N({
132
+ url: H("mainnet")
133
+ });
134
+ function R(e) {
135
+ const a = [];
136
+ return e.forEach((r, t) => {
137
+ const c = t === e.length - 1;
138
+ if (typeof r == "object" && c) {
139
+ const { client: n, disableCache: o, cacheTime: i, ...u } = r;
140
+ a.push(u);
141
+ } else
142
+ a.push(r);
143
+ }), JSON.stringify(a);
144
+ }
145
+ function C(e) {
146
+ const a = {};
147
+ return (...r) => {
148
+ const t = R(r);
149
+ return a[t] || (a[t] = e(...r).finally(() => {
150
+ a[t] = null;
151
+ })), a[t];
152
+ };
153
+ }
154
+ function j(e) {
155
+ let a = {};
156
+ return (...r) => {
157
+ const t = r[r.length - 1], c = R(r), n = a[c];
158
+ return !(t != null && t.disableCache) && typeof (n == null ? void 0 : n.data) != "undefined" && (typeof (t == null ? void 0 : t.cacheTime) == "undefined" || t.cacheTime > Date.now() - n.cacheAt) ? n.data : e(...r).then((o) => (a[c] = {
159
+ data: o,
160
+ cacheAt: Date.now()
161
+ }, o));
162
+ };
163
+ }
164
+ function I(e) {
165
+ return Array.isArray(e) ? e.map((a) => I(a)) : e != null && typeof e == "object" ? Object.keys(e).reduce(
166
+ (a, r) => ({
167
+ ...a,
168
+ [q(r)]: I(e[r])
169
+ }),
170
+ {}
171
+ ) : e;
172
+ }
173
+ function f(e, a) {
174
+ return typeof e == "object" ? e : a(e);
175
+ }
176
+ function O(e, a) {
177
+ return typeof a == "string" ? e.object(a) : typeof a == "object" && a.$kind ? a : e.object(a.contract.pool);
178
+ }
179
+ function P(e, a, r) {
180
+ if (e.results && e.results.length > 0) {
181
+ if (e.results[0].returnValues && e.results[0].returnValues.length > 0)
182
+ return e.results[0].returnValues.map((t, c) => (a[c] || a[0]).parse(Uint8Array.from(t[0])));
183
+ } else if (e.error)
184
+ return console.log(`Get an error, msg: ${e.error}`), [];
185
+ return [];
186
+ }
187
+ function m(e) {
188
+ return G(e);
189
+ }
190
+ function E(e) {
191
+ const a = (e || 0) / Math.pow(10, 27);
192
+ return a > Math.pow(10, 5) ? 1 / 0 : a;
193
+ }
194
+ new V("https://hermes.pyth.network", {
195
+ timeout: 2e4
196
+ });
197
+ const h = j(
198
+ C(async (e) => {
199
+ const a = `https://open-api.naviprotocol.io/api/navi/config?env=${(e == null ? void 0 : e.env) || "prod"}`;
200
+ return (await fetch(a).then((t) => t.json())).data;
201
+ })
202
+ ), g = 1e3 * 60 * 5;
203
+ var T = /* @__PURE__ */ ((e) => (e[e.Supply = 1] = "Supply", e[e.Withdraw = 2] = "Withdraw", e[e.Borrow = 3] = "Borrow", e[e.Repay = 4] = "Repay", e))(T || {});
204
+ const $ = j(
205
+ C(async (e) => {
206
+ const a = `https://open-api.naviprotocol.io/api/navi/pools?env=${(e == null ? void 0 : e.env) || "prod"}`;
207
+ return (await fetch(a).then((t) => t.json())).data;
208
+ })
209
+ );
210
+ async function v(e, a) {
211
+ const r = await $({
212
+ ...a,
213
+ cacheTime: g
214
+ });
215
+ if (typeof e == "object")
216
+ return e;
217
+ const t = r.find((c) => typeof e == "string" ? m(c.suiCoinType) === m(e) : typeof e == "number" ? c.id === e : !1);
218
+ if (!t)
219
+ throw new Error("Pool not found");
220
+ return t;
221
+ }
222
+ const de = j(
223
+ C(async (e) => (await fetch("https://open-api.naviprotocol.io/api/navi/stats").then((t) => t.json())).data)
224
+ ), fe = j(
225
+ C(
226
+ async (e) => await fetch("https://open-api.naviprotocol.io/api/navi/fee").then((t) => t.json())
227
+ )
228
+ );
229
+ async function Y(e, a, r, t) {
230
+ const c = await h({
231
+ ...t,
232
+ cacheTime: g
233
+ }), n = await v(a, t), o = typeof r == "object" && r.$kind === "GasCoin";
234
+ if (m(n.suiCoinType) === m("0x2::sui::SUI") && o) {
235
+ if (!(t != null && t.amount))
236
+ throw new Error("Amount is required for sui coin");
237
+ r = e.splitCoins(r, [t.amount]);
238
+ }
239
+ let i;
240
+ return typeof (t == null ? void 0 : t.amount) != "undefined" ? i = f(t.amount, e.pure.u64) : i = e.moveCall({
241
+ target: "0x2::coin::value",
242
+ arguments: [f(r, e.object)],
243
+ typeArguments: [n.suiCoinType]
244
+ }), t != null && t.accountCap ? e.moveCall({
245
+ target: `${c.package}::incentive_v3::deposit_with_account_cap`,
246
+ arguments: [
247
+ e.object("0x06"),
248
+ e.object(c.storage),
249
+ e.object(n.contract.pool),
250
+ e.pure.u8(n.id),
251
+ f(r, e.object),
252
+ e.object(c.incentiveV2),
253
+ e.object(c.incentiveV3),
254
+ f(t.accountCap, e.object)
255
+ ],
256
+ typeArguments: [n.suiCoinType]
257
+ }) : e.moveCall({
258
+ target: `${c.package}::incentive_v3::entry_deposit`,
259
+ arguments: [
260
+ e.object("0x06"),
261
+ e.object(c.storage),
262
+ e.object(n.contract.pool),
263
+ e.pure.u8(n.id),
264
+ f(r, e.object),
265
+ i,
266
+ e.object(c.incentiveV2),
267
+ e.object(c.incentiveV3)
268
+ ],
269
+ typeArguments: [n.suiCoinType]
270
+ }), e;
271
+ }
272
+ async function pe(e, a, r, t) {
273
+ const c = await h({
274
+ ...t,
275
+ cacheTime: g
276
+ }), n = await v(a, t), o = f(r, e.pure.u64);
277
+ let i;
278
+ if (t != null && t.accountCap) {
279
+ const [l] = e.moveCall({
280
+ target: `${c.package}::incentive_v3::withdraw_with_account_cap`,
281
+ arguments: [
282
+ e.object("0x06"),
283
+ e.object(c.priceOracle),
284
+ e.object(c.storage),
285
+ e.object(n.contract.pool),
286
+ e.pure.u8(n.id),
287
+ o,
288
+ e.object(c.incentiveV2),
289
+ e.object(c.incentiveV3),
290
+ f(t.accountCap, e.object)
291
+ ],
292
+ typeArguments: [n.suiCoinType]
293
+ });
294
+ i = l;
295
+ } else {
296
+ const [l] = e.moveCall({
297
+ target: `${c.package}::incentive_v3::withdraw`,
298
+ arguments: [
299
+ e.object("0x06"),
300
+ e.object(c.priceOracle),
301
+ e.object(c.storage),
302
+ e.object(n.contract.pool),
303
+ e.pure.u8(n.id),
304
+ o,
305
+ e.object(c.incentiveV2),
306
+ e.object(c.incentiveV3)
307
+ ],
308
+ typeArguments: [n.suiCoinType]
309
+ });
310
+ i = l;
311
+ }
312
+ return e.moveCall({
313
+ target: "0x2::coin::from_balance",
314
+ arguments: [i],
315
+ typeArguments: [n.suiCoinType]
316
+ });
317
+ }
318
+ async function me(e, a, r, t) {
319
+ const c = await h({
320
+ ...t,
321
+ cacheTime: g
322
+ }), n = await v(a, t), o = f(r, e.pure.u64);
323
+ let i;
324
+ if (t != null && t.accountCap) {
325
+ const [l] = e.moveCall({
326
+ target: `${c.package}::incentive_v3::borrow_with_account_cap`,
327
+ arguments: [
328
+ e.object("0x06"),
329
+ e.object(c.priceOracle),
330
+ e.object(c.storage),
331
+ e.object(n.contract.pool),
332
+ e.pure.u8(n.id),
333
+ o,
334
+ e.object(c.incentiveV2),
335
+ e.object(c.incentiveV3),
336
+ f(t.accountCap, e.object)
337
+ ],
338
+ typeArguments: [n.suiCoinType]
339
+ });
340
+ i = l;
341
+ } else {
342
+ const [l] = e.moveCall({
343
+ target: `${c.package}::incentive_v3::borrow`,
344
+ arguments: [
345
+ e.object("0x06"),
346
+ e.object(c.priceOracle),
347
+ e.object(c.storage),
348
+ e.object(n.contract.pool),
349
+ e.pure.u8(n.id),
350
+ o,
351
+ e.object(c.incentiveV2),
352
+ e.object(c.incentiveV3)
353
+ ],
354
+ typeArguments: [n.suiCoinType]
355
+ });
356
+ i = l;
357
+ }
358
+ return e.moveCall({
359
+ target: "0x2::coin::from_balance",
360
+ arguments: [e.object(i)],
361
+ typeArguments: [n.suiCoinType]
362
+ });
363
+ }
364
+ async function ge(e, a, r, t) {
365
+ const c = await h({
366
+ ...t,
367
+ cacheTime: g
368
+ }), n = await v(a, t), o = typeof r == "object" && r.$kind === "GasCoin";
369
+ if (m(n.suiCoinType) === m("0x2::sui::SUI") && o) {
370
+ if (!(t != null && t.amount))
371
+ throw new Error("Amount is required for sui coin");
372
+ r = e.splitCoins(r, [t.amount]);
373
+ }
374
+ let i;
375
+ return typeof (t == null ? void 0 : t.amount) != "undefined" ? i = f(t.amount, e.pure.u64) : i = e.moveCall({
376
+ target: "0x2::coin::value",
377
+ arguments: [f(r, e.object)],
378
+ typeArguments: [n.suiCoinType]
379
+ }), t != null && t.accountCap ? e.moveCall({
380
+ target: `${c.package}::incentive_v3::repay_with_account_cap`,
381
+ arguments: [
382
+ e.object("0x06"),
383
+ e.object(c.priceOracle),
384
+ e.object(c.storage),
385
+ e.object(n.contract.pool),
386
+ e.pure.u8(n.id),
387
+ f(r, e.object),
388
+ i,
389
+ e.object(c.incentiveV2),
390
+ e.object(c.incentiveV3),
391
+ f(t.accountCap, e.object)
392
+ ],
393
+ typeArguments: [n.suiCoinType]
394
+ }) : e.moveCall({
395
+ target: `${c.package}::incentive_v3::entry_repay`,
396
+ arguments: [
397
+ e.object("0x06"),
398
+ e.object(c.priceOracle),
399
+ e.object(c.storage),
400
+ e.object(n.contract.pool),
401
+ e.pure.u8(n.id),
402
+ f(r, e.object),
403
+ i,
404
+ e.object(c.incentiveV2),
405
+ e.object(c.incentiveV3)
406
+ ],
407
+ typeArguments: [n.suiCoinType]
408
+ }), e;
409
+ }
410
+ function ye(e, a, r) {
411
+ const t = typeof (r == null ? void 0 : r.balance) == "number", c = t ? r.balance : 0;
412
+ let n = 0;
413
+ const o = [];
414
+ let i = "";
415
+ if (a.sort((l, d) => Number(d.balance) - Number(l.balance)).forEach((l) => {
416
+ if (!(t && n >= c) && Number(l.balance) !== 0) {
417
+ if (i || (i = l.coinType), i !== l.coinType)
418
+ throw new Error("All coins must be of the same type");
419
+ n += Number(l.balance), o.push(l.coinObjectId);
420
+ }
421
+ }), o.length === 0)
422
+ throw new Error("No coins to merge");
423
+ if (t && n < c)
424
+ throw new Error(
425
+ `Balance is less than the specified balance: ${n} < ${c}`
426
+ );
427
+ if (m(i) === m("0x2::sui::SUI") && (r != null && r.useGasCoin))
428
+ return t ? e.splitCoins(e.gas, [e.pure.u64(c)]) : e.gas;
429
+ const u = o.length === 1 ? e.object(o[0]) : e.mergeCoins(o[0], o.slice(1));
430
+ return t ? e.splitCoins(u, [e.pure.u64(c)]) : u;
431
+ }
432
+ async function L(e, a, r, t, c, n, o) {
433
+ const i = await h({
434
+ ...o,
435
+ cacheTime: g
436
+ }), u = await v(r, o);
437
+ return e.moveCall({
438
+ target: `${i.uiGetter}::calculator_unchecked::dynamic_health_factor`,
439
+ arguments: [
440
+ e.object("0x06"),
441
+ e.object(i.storage),
442
+ e.object(i.oracle.priceOracle),
443
+ O(e, u),
444
+ f(a, e.pure.address),
445
+ f(u.id, e.pure.u8),
446
+ f(t, e.pure.u64),
447
+ f(c, e.pure.u64),
448
+ f(n, e.pure.bool)
449
+ ],
450
+ typeArguments: [u.suiCoinType]
451
+ });
452
+ }
453
+ async function J(e, a, r) {
454
+ return L(e, a, 0, 0, 0, !1, r);
455
+ }
456
+ const he = j(
457
+ async (e, a) => {
458
+ var l;
459
+ const r = await h({
460
+ ...a,
461
+ cacheTime: g
462
+ }), t = new A(), c = (l = a == null ? void 0 : a.client) != null ? l : _, n = await $(a);
463
+ t.moveCall({
464
+ target: `${r.uiGetter}::getter_unchecked::get_user_state`,
465
+ arguments: [t.object(r.storage), t.pure.address(e)]
466
+ });
467
+ const o = await c.devInspectTransactionBlock({
468
+ transactionBlock: t,
469
+ sender: e
470
+ }), i = P(o, [b.vector(K)]);
471
+ return I(
472
+ i[0].filter((d) => d.supply_balance !== "0" || d.borrow_balance !== "0")
473
+ ).map((d) => {
474
+ const w = n.find((p) => p.id === d.assetId);
475
+ return {
476
+ ...d,
477
+ pool: w
478
+ };
479
+ }).filter((d) => !!d.pool);
480
+ }
481
+ );
482
+ async function we(e, a) {
483
+ var o;
484
+ const r = (o = a == null ? void 0 : a.client) != null ? o : _, t = new A();
485
+ await J(t, e, a);
486
+ const c = await r.devInspectTransactionBlock({
487
+ transactionBlock: t,
488
+ sender: e
489
+ }), n = P(c, [b.u256()]);
490
+ return E(Number(n[0]) || 0);
491
+ }
492
+ async function be(e, a, r, t) {
493
+ var p;
494
+ const c = (p = t == null ? void 0 : t.client) != null ? p : _, n = new A();
495
+ let o = 0, i = 0;
496
+ const u = await v(a, t);
497
+ if (r.forEach((y) => {
498
+ y.type === T.Supply ? o += y.amount : y.type === T.Withdraw ? o -= y.amount : y.type === T.Borrow ? i += y.amount : y.type === T.Repay && (i -= y.amount);
499
+ }), o * i < 0)
500
+ throw new Error("Invalid operations");
501
+ const l = o > 0 || i > 0;
502
+ await L(
503
+ n,
504
+ e,
505
+ u,
506
+ Math.abs(o),
507
+ Math.abs(i),
508
+ l,
509
+ t
510
+ );
511
+ const d = await c.devInspectTransactionBlock({
512
+ transactionBlock: n,
513
+ sender: e
514
+ }), w = P(d, [b.u256()]);
515
+ return E(Number(w[0]) || 0);
516
+ }
517
+ const ve = C(
518
+ async (e, a) => {
519
+ const r = new URLSearchParams();
520
+ a != null && a.cursor && r.set("cursor", a.cursor), r.set("userAddress", e);
521
+ const t = `https://open-api.naviprotocol.io/api/navi/user/transactions?${r.toString()}`;
522
+ return (await fetch(t).then((n) => n.json())).data;
523
+ }
524
+ );
525
+ async function Ce(e, a) {
526
+ var n;
527
+ let r = null;
528
+ const t = [], c = (n = a == null ? void 0 : a.client) != null ? n : _;
529
+ do {
530
+ let o;
531
+ if (a != null && a.coinType ? o = await c.getCoins({
532
+ owner: e,
533
+ coinType: a == null ? void 0 : a.coinType,
534
+ cursor: r,
535
+ limit: 100
536
+ }) : o = await c.getAllCoins({
537
+ owner: e,
538
+ cursor: r,
539
+ limit: 100
540
+ }), !o.data || !o.data.length)
541
+ break;
542
+ t.push(...o.data), r = o.nextCursor;
543
+ } while (r);
544
+ return t;
545
+ }
546
+ const U = new V("https://hermes.pyth.network", {
547
+ timeout: 1e4
548
+ });
549
+ async function Q(e) {
550
+ try {
551
+ const a = [], r = await U.getLatestPriceFeeds(e);
552
+ if (!r) return a;
553
+ const t = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
554
+ for (const c of r) {
555
+ const n = c.getPriceUnchecked();
556
+ if (n.publishTime > t) {
557
+ console.warn(
558
+ `pyth price feed is invalid, id: ${c.id}, publish time: ${n.publishTime}, current timestamp: ${t}`
559
+ );
560
+ continue;
561
+ }
562
+ t - c.getPriceUnchecked().publishTime > 30 && (console.info(
563
+ `stale price feed, id: ${c.id}, publish time: ${n.publishTime}, current timestamp: ${t}`
564
+ ), a.push(c.id));
565
+ }
566
+ return a;
567
+ } catch (a) {
568
+ throw new Error(`failed to get pyth stale price feed id, msg: ${a.message}`);
569
+ }
570
+ }
571
+ async function X(e, a, r) {
572
+ var n;
573
+ const t = (n = r == null ? void 0 : r.client) != null ? n : _, c = await h({
574
+ ...r,
575
+ cacheTime: g
576
+ });
577
+ try {
578
+ const o = await U.getPriceFeedsUpdateData(a);
579
+ return await new z(
580
+ t,
581
+ c.oracle.pythStateId,
582
+ c.oracle.wormholeStateId
583
+ ).updatePriceFeeds(e, o, a);
584
+ } catch (o) {
585
+ throw new Error(`failed to update pyth price feeds, msg: ${o.message}`);
586
+ }
587
+ }
588
+ async function _e(e, a, r) {
589
+ const t = await h({
590
+ ...r,
591
+ cacheTime: g
592
+ });
593
+ if (r != null && r.updatePythPriceFeeds) {
594
+ const c = a.filter((n) => !!n.pythPriceFeedId).map((n) => n.pythPriceFeedId);
595
+ try {
596
+ const n = await Q(c);
597
+ n.length > 0 && await X(e, n, r);
598
+ } catch {
599
+ }
600
+ }
601
+ for (const c of a)
602
+ e.moveCall({
603
+ target: `${t.oracle.packageId}::oracle_pro::update_single_price`,
604
+ arguments: [
605
+ e.object("0x6"),
606
+ // Clock object
607
+ e.object(t.oracle.oracleConfig),
608
+ // Oracle configuration
609
+ e.object(t.oracle.priceOracle),
610
+ // Price oracle contract
611
+ e.object(t.oracle.supraOracleHolder),
612
+ // Supra oracle holder
613
+ e.object(c.pythPriceInfoObject),
614
+ // Pyth price info object
615
+ e.pure.address(c.feedId)
616
+ // Price feed ID
617
+ ]
618
+ });
619
+ return e;
620
+ }
621
+ async function Z(e) {
622
+ return (await h({
623
+ ...e,
624
+ cacheTime: g
625
+ })).oracle.feeds;
626
+ }
627
+ function je(e, a) {
628
+ return e.filter((r) => !!(a != null && a.lendingState && a.lendingState.find((c) => c.assetId === r.assetId) || a != null && a.pools && a.pools.find((c) => c.id === r.assetId)));
629
+ }
630
+ const S = j(
631
+ C(async (e) => {
632
+ const a = `https://open-api.naviprotocol.io/api/navi/flashloan?env=${(e == null ? void 0 : e.env) || "prod"}`, r = await fetch(a).then((t) => t.json());
633
+ return Object.keys(r.data).map((t) => ({
634
+ ...r.data[t],
635
+ coinType: t
636
+ }));
637
+ })
638
+ );
639
+ async function Te(e, a) {
640
+ return (await S(a)).find((t) => typeof e == "string" ? m(t.coinType) === m(e) : typeof e == "number" ? t.assetId === e : t.assetId === e.id) || null;
641
+ }
642
+ async function Ie(e, a, r, t) {
643
+ const c = await h({
644
+ ...t,
645
+ cacheTime: g
646
+ }), n = await v(a, t);
647
+ if (!(await S({
648
+ ...t,
649
+ cacheTime: g
650
+ })).some(
651
+ (d) => m(d.coinType) === m(n.suiCoinType)
652
+ ))
653
+ throw new Error("Pool does not support flashloan");
654
+ const [u, l] = e.moveCall({
655
+ target: `${c.package}::lending::flash_loan_with_ctx`,
656
+ arguments: [
657
+ e.object(c.flashloanConfig),
658
+ e.object(n.contract.pool),
659
+ f(r, e.pure.u64)
660
+ ],
661
+ typeArguments: [n.suiCoinType]
662
+ });
663
+ return [u, l];
664
+ }
665
+ async function Ae(e, a, r, t, c) {
666
+ const n = await h({
667
+ ...c,
668
+ cacheTime: g
669
+ }), o = await v(a, c);
670
+ if (!(await S({
671
+ ...c,
672
+ cacheTime: g
673
+ })).some(
674
+ (d) => m(d.coinType) === m(o.suiCoinType)
675
+ ))
676
+ throw new Error("Pool does not support flashloan");
677
+ const [l] = e.moveCall({
678
+ target: `${n.package}::lending::flash_repay_with_ctx`,
679
+ arguments: [
680
+ e.object("0x06"),
681
+ e.object(n.storage),
682
+ e.object(o.contract.pool),
683
+ f(r, e.object),
684
+ f(t, e.object)
685
+ ],
686
+ typeArguments: [o.suiCoinType]
687
+ });
688
+ return [l];
689
+ }
690
+ async function Pe(e, a, r, t, c, n) {
691
+ const o = {
692
+ ...n,
693
+ cacheTime: g
694
+ }, i = await h(o), u = await v(a, o), l = await v(t, o), [d, w] = e.moveCall({
695
+ target: `${i.package}::incentive_v3::liquidation`,
696
+ arguments: [
697
+ e.object("0x06"),
698
+ // Clock object
699
+ e.object(i.priceOracle),
700
+ // Price oracle for asset pricing
701
+ e.object(i.storage),
702
+ // Protocol storage
703
+ e.pure.u8(u.id),
704
+ // Pay asset ID
705
+ e.object(u.contract.pool),
706
+ // Pay asset pool contract
707
+ f(r, e.object),
708
+ // Debt repayment amount
709
+ e.pure.u8(l.id),
710
+ // Collateral asset ID
711
+ e.object(l.contract.pool),
712
+ // Collateral asset pool contract
713
+ f(c, e.pure.address),
714
+ // Borrower address
715
+ e.object(i.incentiveV2),
716
+ // Incentive V2 contract
717
+ e.object(i.incentiveV3)
718
+ // Incentive V3 contract
719
+ ],
720
+ typeArguments: [u.suiCoinType, l.suiCoinType]
721
+ });
722
+ return [d, w];
723
+ }
724
+ async function $e(e, a) {
725
+ var d;
726
+ const r = await Z(a), t = await $(a), c = (d = a == null ? void 0 : a.client) != null ? d : _, n = await h({
727
+ ...a,
728
+ cacheTime: g
729
+ }), o = new A();
730
+ o.moveCall({
731
+ target: `${n.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
732
+ arguments: [
733
+ o.object("0x06"),
734
+ // Clock object
735
+ o.object(n.storage),
736
+ // Protocol storage
737
+ o.object(n.incentiveV3),
738
+ // Incentive V3 contract
739
+ o.pure.address(e)
740
+ // User address
741
+ ]
742
+ });
743
+ const i = await c.devInspectTransactionBlock({
744
+ transactionBlock: o,
745
+ sender: e
746
+ }), u = P(
747
+ i,
748
+ [
749
+ b.vector(b.string()),
750
+ // Asset coin types
751
+ b.vector(b.string()),
752
+ // Reward coin types
753
+ b.vector(b.u8()),
754
+ // Reward options
755
+ b.vector(b.Address),
756
+ // Rule IDs
757
+ b.vector(b.u256())
758
+ // Claimable amounts
759
+ ]
760
+ ), l = [];
761
+ if (u.length === 5 && Array.isArray(u[0])) {
762
+ const w = u[0].length;
763
+ for (let p = 0; p < w; p++) {
764
+ const y = r.find(
765
+ (k) => m(k.coinType) === m(u[0][p])
766
+ ), B = t.find(
767
+ (k) => m(k.coinType) === m(u[0][p])
768
+ );
769
+ !y || !B || l.push({
770
+ assetId: B.id,
771
+ assetCoinType: m(u[0][p]),
772
+ rewardCoinType: m(u[1][p]),
773
+ option: Number(u[2][p]),
774
+ userClaimableReward: Number(u[4][p]) / Math.pow(10, y.priceDecimal),
775
+ ruleIds: Array.isArray(u[3][p]) ? u[3][p] : [u[3][p]]
776
+ });
777
+ }
778
+ }
779
+ return l;
780
+ }
781
+ function ke(e) {
782
+ const a = /* @__PURE__ */ new Map();
783
+ e.forEach((t) => {
784
+ const c = t.assetId, n = t.option, o = `${c}-${n}-${t.rewardCoinType}`;
785
+ a.has(o) ? a.get(o).total += t.userClaimableReward : a.set(o, {
786
+ assetId: c,
787
+ rewardType: n,
788
+ coinType: t.rewardCoinType,
789
+ total: Number(t.userClaimableReward)
790
+ });
791
+ });
792
+ const r = /* @__PURE__ */ new Map();
793
+ for (const { assetId: t, rewardType: c, coinType: n, total: o } of a.values()) {
794
+ const i = `${t}-${c}`;
795
+ r.has(i) || r.set(i, { assetId: t, rewardType: c, rewards: /* @__PURE__ */ new Map() });
796
+ const u = r.get(i);
797
+ u.rewards.set(n, (u.rewards.get(n) || 0) + o);
798
+ }
799
+ return Array.from(r.values()).map((t) => ({
800
+ assetId: t.assetId,
801
+ rewardType: t.rewardType,
802
+ rewards: Array.from(t.rewards.entries()).map(([c, n]) => ({
803
+ coinType: c,
804
+ available: n.toFixed(6)
805
+ }))
806
+ }));
807
+ }
808
+ const Se = C(
809
+ async (e) => {
810
+ const a = `https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}`;
811
+ return (await fetch(a).then((t) => t.json())).data;
812
+ }
813
+ ), Be = C(
814
+ async (e, a) => {
815
+ const r = `https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${(a == null ? void 0 : a.page) || 1}&pageSize=${(a == null ? void 0 : a.size) || 400}`, t = await fetch(r).then((c) => c.json());
816
+ return I({
817
+ data: t.data.rewards
818
+ });
819
+ }
820
+ );
821
+ async function Fe(e, a, r) {
822
+ const t = await h({
823
+ ...r,
824
+ cacheTime: g
825
+ }), c = await $({
826
+ ...r,
827
+ cacheTime: g
828
+ }), n = /* @__PURE__ */ new Map();
829
+ for (const i of a) {
830
+ const { rewardCoinType: u, ruleIds: l } = i;
831
+ for (const d of l) {
832
+ n.has(u) || n.set(u, { assetIds: [], ruleIds: [] });
833
+ const w = n.get(u);
834
+ w.assetIds.push(i.assetCoinType.replace("0x", "")), w.ruleIds.push(d);
835
+ }
836
+ }
837
+ const o = [];
838
+ for (const [i, { assetIds: u, ruleIds: l }] of n) {
839
+ const d = c.find(
840
+ (p) => m(p.suiCoinType) === m(i)
841
+ );
842
+ if (!d || !d.contract.rewardFundId)
843
+ throw new Error(`No matching rewardFund found for reward coin: ${i}`);
844
+ const w = d.contract.rewardFundId;
845
+ if (r != null && r.accountCap && !r.customCoinReceive)
846
+ throw new Error("customCoinReceive is required when accountCap is provided");
847
+ if (r != null && r.customCoinReceive) {
848
+ let p;
849
+ r.accountCap ? p = e.moveCall({
850
+ target: `${t.package}::incentive_v3::claim_reward_with_account_cap`,
851
+ arguments: [
852
+ e.object("0x06"),
853
+ // Clock object
854
+ e.object(t.incentiveV3),
855
+ // Incentive V3 contract
856
+ e.object(t.storage),
857
+ // Protocol storage
858
+ e.object(w),
859
+ // Reward fund
860
+ e.pure.vector("string", u),
861
+ // Asset IDs
862
+ e.pure.vector("address", l),
863
+ // Rule IDs
864
+ f(r.accountCap, e.object)
865
+ // Account capability
866
+ ],
867
+ typeArguments: [i]
868
+ }) : p = e.moveCall({
869
+ target: `${t.package}::incentive_v3::claim_reward`,
870
+ arguments: [
871
+ e.object("0x06"),
872
+ // Clock object
873
+ e.object(t.incentiveV3),
874
+ // Incentive V3 contract
875
+ e.object(t.storage),
876
+ // Protocol storage
877
+ e.object(w),
878
+ // Reward fund
879
+ e.pure.vector("string", u),
880
+ // Asset IDs
881
+ e.pure.vector("address", l)
882
+ // Rule IDs
883
+ ],
884
+ typeArguments: [i]
885
+ });
886
+ const [y] = e.moveCall({
887
+ target: "0x2::coin::from_balance",
888
+ arguments: [p],
889
+ typeArguments: [i]
890
+ });
891
+ if ((r == null ? void 0 : r.customCoinReceive.type) === "transfer") {
892
+ if (!r.customCoinReceive.transfer)
893
+ throw new Error("customCoinReceive.transfer is required");
894
+ e.transferObjects(
895
+ [y],
896
+ f(r.customCoinReceive.transfer, e.pure.address)
897
+ );
898
+ }
899
+ (r == null ? void 0 : r.customCoinReceive.type) === "depositNAVI" ? await Y(e, d, y, r) : o.push({
900
+ coin: y,
901
+ identifier: d
902
+ });
903
+ } else
904
+ e.moveCall({
905
+ target: `${t.package}::incentive_v3::claim_reward_entry`,
906
+ arguments: [
907
+ e.object("0x06"),
908
+ // Clock object
909
+ e.object(t.incentiveV3),
910
+ // Incentive V3 contract
911
+ e.object(t.storage),
912
+ // Protocol storage
913
+ e.object(w),
914
+ // Reward fund
915
+ e.pure.vector("string", u),
916
+ // Asset IDs
917
+ e.pure.vector("address", l)
918
+ // Rule IDs
919
+ ],
920
+ typeArguments: [i]
921
+ });
922
+ }
923
+ return o;
924
+ }
925
+ async function Ve(e, a) {
926
+ const r = await h({
927
+ ...a
928
+ });
929
+ return e.moveCall({
930
+ target: `${r.package}::lending::create_account`,
931
+ arguments: []
932
+ });
933
+ }
934
+ export {
935
+ F as Address,
936
+ g as DEFAULT_CACHE_TIME,
937
+ ue as FlashLoanAssetConfig,
938
+ oe as IncentiveAPYInfo,
939
+ W as IncentivePoolInfo,
940
+ se as IncentivePoolInfoByPhase,
941
+ ie as OracleInfo,
942
+ T as PoolOperator,
943
+ le as ReserveDataInfo,
944
+ K as UserStateInfo,
945
+ me as borrowCoinPTB,
946
+ Fe as claimLendingRewardsPTB,
947
+ Ve as createAccountCapPTB,
948
+ Y as depositCoinPTB,
949
+ je as filterPriceFeeds,
950
+ Ie as flashloanPTB,
951
+ S as getAllFlashLoanAssets,
952
+ Ce as getCoins,
953
+ h as getConfig,
954
+ fe as getFees,
955
+ Te as getFlashLoanAsset,
956
+ we as getHealthFactor,
957
+ J as getHealthFactorPTB,
958
+ he as getLendingState,
959
+ v as getPool,
960
+ $ as getPools,
961
+ Z as getPriceFeeds,
962
+ Q as getPythStalePriceFeedId,
963
+ be as getSimulatedHealthFactor,
964
+ L as getSimulatedHealthFactorPTB,
965
+ de as getStats,
966
+ ve as getTransactions,
967
+ $e as getUserAvailableLendingRewards,
968
+ Be as getUserClaimedRewardHistory,
969
+ Se as getUserTotalClaimedReward,
970
+ Pe as liquidatePTB,
971
+ ye as mergeCoinsPTB,
972
+ m as normalizeCoinType,
973
+ f as parseTxValue,
974
+ ge as repayCoinPTB,
975
+ Ae as repayFlashLoanPTB,
976
+ ke as summaryLendingRewards,
977
+ _e as updateOraclePricesPTB,
978
+ X as updatePythPriceFeeds,
979
+ j as withCache,
980
+ C as withSingleton,
981
+ pe as withdrawCoinPTB
982
+ };
983
+ //# sourceMappingURL=index.esm.js.map