@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/reward.js ADDED
@@ -0,0 +1,343 @@
1
+ import { Transaction as D } from "@mysten/sui/transactions";
2
+ import { DEFAULT_CACHE_TIME as T, getConfig as $ } from "./config.js";
3
+ import { withSingleton as R, requestHeaders as E, camelize as P, normalizeCoinType as v, parseTxValue as h, suiClient as S, devInspectTransaction as z, parseDevInspectResult as H } from "./utils.js";
4
+ import { bcs as f } from "@mysten/sui/bcs";
5
+ import { getPriceFeeds as q } from "./oracle.js";
6
+ import { getPools as M, depositCoinPTB as K } from "./pool.js";
7
+ import A from "bignumber.js";
8
+ import N from "./package.json.js";
9
+ import { MARKETS as j, getMarketConfig as I, DEFAULT_MARKET_IDENTITY as B } from "./market.js";
10
+ import { getUserEModeCaps as G } from "./emode.js";
11
+ import { resolveNaviOpenApiEndpoint as V, buildNaviOpenApiUrl as L, mergeServiceHeaders as F } from "./services.js";
12
+ async function J(e, n, r) {
13
+ const t = r?.client ?? S, o = await M({
14
+ ...r,
15
+ markets: Object.values(j),
16
+ cacheTime: T
17
+ }), s = await q(r), i = [];
18
+ return await Promise.all(
19
+ n.map(async (c) => {
20
+ try {
21
+ const d = await $({
22
+ ...r,
23
+ cacheTime: T,
24
+ market: c.market
25
+ }), l = new D();
26
+ l.moveCall({
27
+ target: `${d.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,
28
+ arguments: [
29
+ l.object("0x06"),
30
+ // Clock object
31
+ l.object(d.storage),
32
+ // Protocol storage
33
+ l.object(d.incentiveV3),
34
+ // Incentive V3 contract
35
+ l.pure.address(c.address)
36
+ // User address
37
+ ]
38
+ });
39
+ const y = (await z(t, {
40
+ transactionBlock: l,
41
+ sender: e
42
+ }))?.results?.[0];
43
+ if (!y)
44
+ return;
45
+ const m = H({ results: [y] }, [
46
+ f.vector(f.string()),
47
+ // Asset coin types
48
+ f.vector(f.string()),
49
+ // Reward coin types
50
+ f.vector(f.u8()),
51
+ // Reward options
52
+ f.vector(f.Address),
53
+ // Rule IDs
54
+ f.vector(f.u256())
55
+ // Claimable amounts
56
+ ]);
57
+ if (m.length === 5 && Array.isArray(m[0])) {
58
+ const w = m[0].length;
59
+ for (let a = 0; a < w; a++) {
60
+ const u = s.find(
61
+ (p) => v(p.coinType) === v(m[1][a])
62
+ ), _ = o.find(
63
+ (p) => v(p.coinType) === v(m[0][a]) && p.market === c.market
64
+ );
65
+ !u || !_ || i.push({
66
+ assetId: _.id,
67
+ assetCoinType: v(m[0][a]),
68
+ rewardCoinType: v(m[1][a]),
69
+ option: Number(m[2][a]),
70
+ userClaimableReward: Number(m[4][a]) / Math.pow(10, u.priceDecimal),
71
+ ruleIds: Array.isArray(m[3][a]) ? m[3][a] : [m[3][a]],
72
+ market: c.market,
73
+ owner: c.owner,
74
+ address: c.address,
75
+ emodeId: c.emodeId
76
+ });
77
+ }
78
+ }
79
+ } catch (d) {
80
+ console.error(
81
+ `[lending] getLendingRewardsBatch task failed (market=${c.market}, address=${c.address}):`,
82
+ d
83
+ );
84
+ }
85
+ })
86
+ ), i;
87
+ }
88
+ async function ne(e, n) {
89
+ const r = (n?.markets || [j.main]).map((s) => I(s)), t = await G(e, n), o = r.map((s) => ({
90
+ address: e,
91
+ owner: e,
92
+ market: s.key
93
+ })).concat(
94
+ t.filter((s) => !!r.find((i) => i.id === s.marketId)).map((s) => {
95
+ const i = I(s.marketId);
96
+ return {
97
+ address: s.accountCap,
98
+ owner: e,
99
+ market: i.key,
100
+ emodeId: s.emodeId
101
+ };
102
+ })
103
+ );
104
+ return await J(e, o, n);
105
+ }
106
+ function ce(e) {
107
+ const n = /* @__PURE__ */ new Map();
108
+ e.forEach((t) => {
109
+ const o = t.assetId, s = t.option, i = `${o}-${s}-${t.rewardCoinType}-${t.market}`;
110
+ n.has(i) ? n.get(i).total += t.userClaimableReward : n.set(i, {
111
+ assetId: o,
112
+ rewardType: s,
113
+ coinType: t.rewardCoinType,
114
+ total: Number(t.userClaimableReward),
115
+ market: t.market
116
+ });
117
+ });
118
+ const r = /* @__PURE__ */ new Map();
119
+ for (const { assetId: t, rewardType: o, coinType: s, total: i, market: c } of n.values()) {
120
+ const d = `${t}-${o}-${c}`;
121
+ r.has(d) || r.set(d, { assetId: t, rewardType: o, market: c, rewards: /* @__PURE__ */ new Map() });
122
+ const l = r.get(d);
123
+ l.rewards.set(s, (l.rewards.get(s) || 0) + i);
124
+ }
125
+ return Array.from(r.values()).map((t) => ({
126
+ assetId: t.assetId,
127
+ rewardType: t.rewardType,
128
+ market: t.market,
129
+ rewards: Array.from(t.rewards.entries()).map(([o, s]) => ({
130
+ coinType: o,
131
+ available: s.toFixed(6)
132
+ }))
133
+ }));
134
+ }
135
+ const oe = R(
136
+ async (e, n) => {
137
+ const r = V(n), t = L(
138
+ `/navi/user/total_claimed_reward?userAddress=${e}&sdk=${N.version}&market=${n?.market || B}`,
139
+ n
140
+ );
141
+ return (await fetch(t, {
142
+ headers: F(E, r)
143
+ }).then((s) => s.json())).data;
144
+ }
145
+ ), ie = R(
146
+ async (e, n) => {
147
+ const r = V(n), t = L(
148
+ `/navi/user/rewards?userAddress=${e}&page=${n?.page || 1}&pageSize=${n?.size || 400}&sdk=${N.version}&market=${n?.market || B}`,
149
+ n
150
+ ), o = await fetch(t, {
151
+ headers: F(E, r)
152
+ }).then((s) => s.json());
153
+ return P({
154
+ data: o.data.rewards
155
+ });
156
+ }
157
+ );
158
+ async function de(e, n, r) {
159
+ const t = await M({
160
+ ...r,
161
+ markets: Object.values(j),
162
+ cacheTime: T
163
+ }), o = /* @__PURE__ */ new Map();
164
+ for (const i of n) {
165
+ const { rewardCoinType: c, ruleIds: d, market: l, owner: b, address: y, emodeId: m } = i, w = `${c}___${y}__${l}`;
166
+ for (const a of d) {
167
+ o.has(w) || o.set(w, {
168
+ assetIds: [],
169
+ ruleIds: [],
170
+ amount: 0,
171
+ market: l,
172
+ owner: b,
173
+ address: y,
174
+ isEMode: typeof m < "u"
175
+ });
176
+ const u = o.get(w);
177
+ u.assetIds.push(i.assetCoinType.replace("0x", "")), u.ruleIds.push(a), u.amount += i.userClaimableReward;
178
+ }
179
+ }
180
+ const s = [];
181
+ for (const [
182
+ i,
183
+ { assetIds: c, ruleIds: d, amount: l, market: b, owner: y, address: m, isEMode: w }
184
+ ] of o) {
185
+ const a = await $({
186
+ ...r,
187
+ cacheTime: T,
188
+ market: b
189
+ }), u = i.split("___")[0], _ = t.filter(
190
+ (g) => v(g.suiCoinType) === v(u)
191
+ );
192
+ _.sort((g, C) => g.market === b ? -1 : 1);
193
+ const p = _[0], k = a.rewardFunds[v(u)];
194
+ if (!k)
195
+ throw new Error(`No matching rewardFund found for reward coin: ${u} ${b}`);
196
+ if (r?.accountCap && !r.customCoinReceive)
197
+ throw new Error("customCoinReceive is required when accountCap is provided");
198
+ if (r?.customCoinReceive) {
199
+ let g;
200
+ r.accountCap ? g = e.moveCall({
201
+ target: `${a.package}::incentive_v3::claim_reward_with_account_cap`,
202
+ arguments: [
203
+ e.object("0x06"),
204
+ // Clock object
205
+ e.object(a.incentiveV3),
206
+ // Incentive V3 contract
207
+ e.object(a.storage),
208
+ // Protocol storage
209
+ e.object(k),
210
+ // Reward fund
211
+ e.pure.vector("string", c),
212
+ // Asset IDs
213
+ e.pure.vector("address", d),
214
+ // Rule IDs
215
+ h(r.accountCap, e.object)
216
+ // Account capability
217
+ ],
218
+ typeArguments: [u]
219
+ }) : w ? g = e.moveCall({
220
+ target: `${a.package}::incentive_v3::claim_reward_with_account_cap`,
221
+ arguments: [
222
+ e.object("0x06"),
223
+ // Clock object
224
+ e.object(a.incentiveV3),
225
+ // Incentive V3 contract
226
+ e.object(a.storage),
227
+ // Protocol storage
228
+ e.object(k),
229
+ // Reward fund
230
+ e.pure.vector("string", c),
231
+ // Asset IDs
232
+ e.pure.vector("address", d),
233
+ // Rule IDs
234
+ h(m, e.object)
235
+ // Account capability
236
+ ],
237
+ typeArguments: [u]
238
+ }) : g = e.moveCall({
239
+ target: `${a.package}::incentive_v3::claim_reward`,
240
+ arguments: [
241
+ e.object("0x06"),
242
+ // Clock object
243
+ e.object(a.incentiveV3),
244
+ // Incentive V3 contract
245
+ e.object(a.storage),
246
+ // Protocol storage
247
+ e.object(k),
248
+ // Reward fund
249
+ e.pure.vector("string", c),
250
+ // Asset IDs
251
+ e.pure.vector("address", d)
252
+ // Rule IDs
253
+ ],
254
+ typeArguments: [u]
255
+ });
256
+ const [C] = e.moveCall({
257
+ target: "0x2::coin::from_balance",
258
+ arguments: [g],
259
+ typeArguments: [u]
260
+ });
261
+ if (r?.customCoinReceive.type === "transfer") {
262
+ if (!r.customCoinReceive.transfer)
263
+ throw new Error("customCoinReceive.transfer is required");
264
+ e.transferObjects(
265
+ [C],
266
+ h(r.customCoinReceive.transfer, e.pure.address)
267
+ );
268
+ }
269
+ if (r?.customCoinReceive.type === "depositNAVI") {
270
+ const O = A(p.totalSupplyAmount).shiftedBy(-9), U = A(p.supplyCapCeiling).shiftedBy(-27);
271
+ O.plus(l).isGreaterThan(U) && r?.customCoinReceive.depositNAVI?.fallbackReceiveAddress ? e.transferObjects(
272
+ [C],
273
+ e.pure.address(r.customCoinReceive.depositNAVI.fallbackReceiveAddress)
274
+ ) : await K(e, p, C, {
275
+ ...r,
276
+ market: p.market
277
+ });
278
+ } else
279
+ s.push({
280
+ coin: C,
281
+ identifier: p,
282
+ owner: y,
283
+ isEMode: w
284
+ });
285
+ } else if (r?.accountCap || w) {
286
+ const g = e.moveCall({
287
+ target: `${a.package}::incentive_v3::claim_reward_with_account_cap`,
288
+ arguments: [
289
+ e.object("0x06"),
290
+ // Clock object
291
+ e.object(a.incentiveV3),
292
+ // Incentive V3 contract
293
+ e.object(a.storage),
294
+ // Protocol storage
295
+ e.object(k),
296
+ // Reward fund
297
+ e.pure.vector("string", c),
298
+ // Asset IDs
299
+ e.pure.vector("address", d),
300
+ // Rule IDs
301
+ h(r?.accountCap || m, e.object)
302
+ // Account capability
303
+ ],
304
+ typeArguments: [u]
305
+ }), [C] = e.moveCall({
306
+ target: "0x2::coin::from_balance",
307
+ arguments: [g],
308
+ typeArguments: [u]
309
+ });
310
+ e.transferObjects(
311
+ [C],
312
+ h(r?.accountCap || y, e.pure.address)
313
+ );
314
+ } else
315
+ e.moveCall({
316
+ target: `${a.package}::incentive_v3::claim_reward_entry`,
317
+ arguments: [
318
+ e.object("0x06"),
319
+ // Clock object
320
+ e.object(a.incentiveV3),
321
+ // Incentive V3 contract
322
+ e.object(a.storage),
323
+ // Protocol storage
324
+ e.object(k),
325
+ // Reward fund
326
+ e.pure.vector("string", c),
327
+ // Asset IDs
328
+ e.pure.vector("address", d)
329
+ // Rule IDs
330
+ ],
331
+ typeArguments: [u]
332
+ });
333
+ }
334
+ return s;
335
+ }
336
+ export {
337
+ de as claimLendingRewardsPTB,
338
+ ne as getUserAvailableLendingRewards,
339
+ ie as getUserClaimedRewardHistory,
340
+ oe as getUserTotalClaimedReward,
341
+ ce as summaryLendingRewards
342
+ };
343
+ //# sourceMappingURL=reward.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reward.js","sources":["../src/reward.ts"],"sourcesContent":["/**\n * Lending Reward Management for Lending Protocol\n *\n * This module provides comprehensive reward functionality for the lending protocol.\n * It handles reward calculations, claiming, and management for users who participate\n * in lending activities such as supplying assets or borrowing.\n */\n\nimport type {\n SuiClientOption,\n EnvOption,\n LendingRewardSummary,\n LendingReward,\n HistoryClaimedReward,\n LendingClaimedReward,\n TransactionResult,\n AccountCapOption,\n AccountCap,\n MarketOption,\n MarketsOption,\n EModeCap,\n ServiceOption\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n camelize,\n parseDevInspectResult,\n devInspectTransaction,\n normalizeCoinType,\n withSingleton,\n parseTxValue,\n requestHeaders,\n suiClient\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport { getPriceFeeds } from './oracle'\nimport { getPools, depositCoinPTB } from './pool'\nimport BigNumber from 'bignumber.js'\nimport packageJson from '../package.json'\nimport { DEFAULT_MARKET_IDENTITY, getMarketConfig, MARKETS } from './market'\nimport { getUserEModeCaps } from './emode'\nimport { buildNaviOpenApiUrl, mergeServiceHeaders, resolveNaviOpenApiEndpoint } from './services'\n\nasync function getLendingRewardsBatch(\n address: string,\n tasks: {\n address: string\n market: string\n owner: string\n emodeId?: number\n }[],\n options?: Partial<SuiClientOption & EnvOption & ServiceOption>\n): Promise<LendingReward[]> {\n const client = options?.client ?? suiClient\n\n const pools = await getPools({\n ...options,\n markets: Object.values(MARKETS),\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const feeds = await getPriceFeeds(options)\n\n const rewardsList: {\n userClaimableReward: number\n userClaimedReward?: string\n option: number\n ruleIds: string[]\n assetCoinType: string\n rewardCoinType: string\n assetId: number\n market: string\n owner: string\n address: string\n emodeId?: number\n }[] = []\n\n // Per-task independent devInspect: previously all market + EMode cap moveCalls\n // were packed into one PTB with a single devInspect, so any sub-call abort\n // (a market not wired for incentive_v3, or an expired/mismatched EMode\n // accountCap) collapsed the whole batch to [] silently. Now each task runs its\n // own devInspect with try/catch isolation: one failure only skips that task\n // and does not take down the rest (matching the legacy navi-sdk per-market,\n // mutually-independent semantics). Failures are logged, not silently swallowed.\n await Promise.all(\n tasks.map(async (task) => {\n try {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME,\n market: task.market\n })\n const tx = new Transaction()\n tx.moveCall({\n target: `${config.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.storage), // Protocol storage\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.pure.address(task.address) // User address\n ]\n })\n\n const result = await devInspectTransaction(client, {\n transactionBlock: tx,\n sender: address\n })\n\n const item = result?.results?.[0]\n if (!item) {\n // No result for this task (abort/empty): skip it, does not affect others.\n return\n }\n\n const rewardsData = parseDevInspectResult<\n [string[], string[], number[], string[], number[]]\n >({ results: [item] } as any, [\n bcs.vector(bcs.string()), // Asset coin types\n bcs.vector(bcs.string()), // Reward coin types\n bcs.vector(bcs.u8()), // Reward options\n bcs.vector(bcs.Address), // Rule IDs\n bcs.vector(bcs.u256()) // Claimable amounts\n ])\n\n if (rewardsData.length === 5 && Array.isArray(rewardsData[0])) {\n const count = rewardsData[0].length\n for (let i = 0; i < count; i++) {\n const feed = feeds.find(\n (feed) => normalizeCoinType(feed.coinType) === normalizeCoinType(rewardsData[1][i])\n )\n const pool = pools.find(\n (pool) =>\n normalizeCoinType(pool.coinType) === normalizeCoinType(rewardsData[0][i]) &&\n pool.market === task.market\n )\n if (!feed || !pool) {\n continue\n }\n rewardsList.push({\n assetId: pool.id,\n assetCoinType: normalizeCoinType(rewardsData[0][i]),\n rewardCoinType: normalizeCoinType(rewardsData[1][i]),\n option: Number(rewardsData[2][i]),\n userClaimableReward: Number(rewardsData[4][i]) / Math.pow(10, feed.priceDecimal),\n ruleIds: Array.isArray(rewardsData[3][i])\n ? (rewardsData[3][i] as any)\n : [rewardsData[3][i]],\n market: task.market,\n owner: task.owner,\n address: task.address,\n emodeId: task.emodeId\n })\n }\n }\n } catch (e) {\n // A single task failure must not take down the whole batch; log it explicitly rather than swallow.\n console.error(\n `[lending] getLendingRewardsBatch task failed (market=${task.market}, address=${task.address}):`,\n e\n )\n }\n })\n )\n\n return rewardsList\n}\n\n/**\n * Get user's available lending rewards\n *\n * This function retrieves all available rewards for a user from the lending protocol.\n * It uses devInspect to simulate the reward calculation and returns detailed\n * information about claimable rewards for each asset and reward type.\n *\n * @param address - User's wallet address or account cap\n * @param options - Optional client and environment configuration\n * @returns Array of lending rewards available for claiming\n */\nexport async function getUserAvailableLendingRewards(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption & MarketsOption & ServiceOption>\n): Promise<LendingReward[]> {\n const markets = (options?.markets || [MARKETS.main]).map((identity) => {\n return getMarketConfig(identity)\n })\n\n // Do not silently swallow E-Mode cap failures: the previous catch fell back to\n // an empty array, silently dropping E-Mode-related reward tasks (and masking\n // real endpoint/RPC errors). Throw so callers are aware instead of\n // returning incomplete results.\n const emodeCaps: EModeCap[] = await getUserEModeCaps(address, options)\n\n const tasks = markets\n .map((market) => {\n return {\n address,\n owner: address,\n market: market.key\n }\n })\n .concat(\n emodeCaps\n .filter((cap) => {\n return !!markets.find((market) => market.id === cap.marketId)\n })\n .map((cap) => {\n const market = getMarketConfig(cap.marketId)\n return {\n address: cap.accountCap,\n owner: address,\n market: market.key,\n emodeId: cap.emodeId\n }\n })\n )\n\n return await getLendingRewardsBatch(address, tasks, options)\n}\n\n/**\n * Summarize lending rewards by asset and reward type\n *\n * This function aggregates rewards by asset ID and reward type, providing\n * a summary view of all available rewards for easier display and management.\n *\n * @param rewards - Array of lending rewards to summarize\n * @returns Array of summarized reward information grouped by asset and type\n */\nexport function summaryLendingRewards(rewards: LendingReward[]): LendingRewardSummary[] {\n // Aggregate rewards by asset ID, reward type, and coin type\n const agg = new Map<\n string,\n { assetId: number; rewardType: number; coinType: string; total: number; market: string }\n >()\n\n rewards.forEach((reward) => {\n const assetId = reward.assetId\n const rewardType = reward.option\n const key = `${assetId}-${rewardType}-${reward.rewardCoinType}-${reward.market}`\n if (agg.has(key)) {\n agg.get(key)!.total += reward.userClaimableReward\n } else {\n agg.set(key, {\n assetId,\n rewardType,\n coinType: reward.rewardCoinType,\n total: Number(reward.userClaimableReward),\n market: reward.market\n })\n }\n })\n\n // Group rewards by asset ID and reward type\n const groupMap = new Map<\n string,\n { assetId: number; rewardType: number; market: string; rewards: Map<string, number> }\n >()\n for (const { assetId, rewardType, coinType, total, market } of agg.values()) {\n const groupKey = `${assetId}-${rewardType}-${market}`\n if (!groupMap.has(groupKey)) {\n groupMap.set(groupKey, { assetId, rewardType, market, rewards: new Map<string, number>() })\n }\n const rewardMap = groupMap.get(groupKey)!\n rewardMap.rewards.set(coinType, (rewardMap.rewards.get(coinType) || 0) + total)\n }\n\n // Convert to summary format\n return Array.from(groupMap.values()).map((group) => ({\n assetId: group.assetId,\n rewardType: group.rewardType,\n market: group.market,\n rewards: Array.from(group.rewards.entries()).map(([coinType, available]) => ({\n coinType,\n available: available.toFixed(6)\n }))\n }))\n}\n\n/**\n * Get user's total claimed rewards in USD value\n *\n * Fetches the total amount of rewards that a user has claimed historically,\n * converted to USD value for easy comparison and display.\n *\n * @param address - User's wallet address or account cap\n * @returns Object containing total claimed rewards in USD\n */\nexport const getUserTotalClaimedReward = withSingleton(\n async (\n address: string | AccountCap,\n options?: Partial<MarketOption & ServiceOption>\n ): Promise<{\n USDValue: number\n }> => {\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const url = buildNaviOpenApiUrl(\n `/navi/user/total_claimed_reward?userAddress=${address}&sdk=${packageJson.version}&market=${options?.market || DEFAULT_MARKET_IDENTITY}`,\n options\n )\n const res = await fetch(url, {\n headers: mergeServiceHeaders(requestHeaders, endpoint)\n }).then((res) => res.json())\n return res.data\n }\n)\n\n/**\n * Get user's claimed reward history\n *\n * Retrieves a paginated list of all rewards that a user has claimed historically.\n * Useful for tracking reward history and generating reports.\n *\n * @param address - User's wallet address or account cap\n * @param options - Pagination options (page number and size)\n * @returns Object containing claimed reward history and pagination cursor\n */\nexport const getUserClaimedRewardHistory = withSingleton(\n async (\n address: string | AccountCap,\n options?: Partial<\n MarketOption & {\n page: number\n size: number\n } & ServiceOption\n >\n ): Promise<{\n data: HistoryClaimedReward[]\n cursor?: string\n }> => {\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const url = buildNaviOpenApiUrl(\n `/navi/user/rewards?userAddress=${address}&page=${options?.page || 1}&pageSize=${options?.size || 400}&sdk=${packageJson.version}&market=${options?.market || DEFAULT_MARKET_IDENTITY}`,\n options\n )\n const res = await fetch(url, {\n headers: mergeServiceHeaders(requestHeaders, endpoint)\n }).then((res) => res.json())\n return camelize({\n data: res.data.rewards\n })\n }\n)\n\n/**\n * Claim lending rewards in the PTB (Programmable Transaction Block)\n *\n * This function adds operations to a transaction block to claim rewards from the lending protocol.\n * It supports different claiming methods including direct claiming, claiming with\n * account capabilities, and custom coin handling (transfer or deposit).\n *\n * @param tx - The transaction block to add reward claiming operations to\n * @param rewards - Array of rewards to claim\n * @param options - Optional configuration including account capabilities and custom coin handling\n * @param options.customCoinReceive.type - The type of custom coin handling, can be 'transfer', 'depositNAVI' or 'skip'\n * @param options.customCoinReceive.transfer - The address to transfer the reward to, only used when options.customCoinReceive.type is 'transfer'\n * @param options.customCoinReceive.depositNAVI.fallbackReceiveAddress - The address to transfer the reward to if the pool is full, only used when options.customCoinReceive.type is 'depositNAVI'\n * @returns Array of claimed reward coins and their identifiers\n * @throws Error if reward fund not found or invalid configuration\n */\nexport async function claimLendingRewardsPTB(\n tx: Transaction,\n rewards: LendingReward[],\n options?: Partial<\n EnvOption &\n AccountCapOption &\n ServiceOption &\n MarketOption & {\n customCoinReceive?: {\n type: 'transfer' | 'depositNAVI' | 'skip'\n transfer?: string | TransactionResult\n depositNAVI?: {\n fallbackReceiveAddress?: string\n }\n }\n }\n >\n) {\n const pools = await getPools({\n ...options,\n markets: Object.values(MARKETS),\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Group rewards by reward coin type and collect asset IDs and rule IDs\n const rewardMap = new Map<\n string,\n {\n assetIds: string[]\n ruleIds: string[]\n amount: number\n market: string\n owner: string\n address: string\n isEMode: boolean\n }\n >()\n\n for (const reward of rewards) {\n const { rewardCoinType, ruleIds, market, owner, address, emodeId } = reward\n\n const key = `${rewardCoinType}___${address}__${market}`\n\n for (const ruleId of ruleIds) {\n if (!rewardMap.has(key)) {\n rewardMap.set(key, {\n assetIds: [],\n ruleIds: [],\n amount: 0,\n market,\n owner,\n address,\n isEMode: typeof emodeId !== 'undefined'\n })\n }\n\n const group = rewardMap.get(key)!\n group.assetIds.push(reward.assetCoinType.replace('0x', ''))\n group.ruleIds.push(ruleId)\n group.amount += reward.userClaimableReward\n }\n }\n\n const rewardCoins = [] as LendingClaimedReward[]\n\n // Process each reward coin type\n for (const [\n rewardCoinType,\n { assetIds, ruleIds, amount, market, owner, address, isEMode }\n ] of rewardMap) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME,\n market\n })\n const coinType = rewardCoinType.split('___')[0]\n const filterPools = pools.filter(\n (p) => normalizeCoinType(p.suiCoinType) === normalizeCoinType(coinType)\n )\n filterPools.sort((a, b) => (a.market === market ? -1 : 1))\n const pool = filterPools[0]\n\n const matchedRewardFund = config.rewardFunds[normalizeCoinType(coinType)]\n\n if (!matchedRewardFund) {\n throw new Error(`No matching rewardFund found for reward coin: ${coinType} ${market}`)\n }\n\n // Validate configuration\n if (options?.accountCap && !options.customCoinReceive) {\n throw new Error('customCoinReceive is required when accountCap is provided')\n }\n\n // Handle custom coin receiving logic\n if (options?.customCoinReceive) {\n let rewardBalance\n\n // Claim rewards with or without account capability\n if (options.accountCap) {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_with_account_cap`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds), // Rule IDs\n parseTxValue(options.accountCap, tx.object) // Account capability\n ],\n typeArguments: [coinType]\n })\n } else if (isEMode) {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_with_account_cap`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds), // Rule IDs\n parseTxValue(address, tx.object) // Account capability\n ],\n typeArguments: [coinType]\n })\n } else {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [coinType]\n })\n }\n\n // Convert balance to coin object\n const [rewardCoin]: any = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [rewardBalance],\n typeArguments: [coinType]\n })\n\n // Handle different custom coin receiving types\n if (options?.customCoinReceive.type === 'transfer') {\n if (!options.customCoinReceive.transfer) {\n throw new Error('customCoinReceive.transfer is required')\n }\n tx.transferObjects(\n [rewardCoin],\n parseTxValue(options.customCoinReceive.transfer, tx.pure.address)\n )\n }\n if (options?.customCoinReceive.type === 'depositNAVI') {\n const supplyAmount = BigNumber(pool.totalSupplyAmount).shiftedBy(-9)\n const cap = BigNumber(pool.supplyCapCeiling).shiftedBy(-27)\n\n // if the pool is full, transfer the reward to the fallback receive address\n if (\n supplyAmount.plus(amount).isGreaterThan(cap) &&\n !!options?.customCoinReceive.depositNAVI?.fallbackReceiveAddress\n ) {\n tx.transferObjects(\n [rewardCoin],\n tx.pure.address(options.customCoinReceive.depositNAVI.fallbackReceiveAddress)\n )\n } else {\n await depositCoinPTB(tx, pool, rewardCoin, {\n ...options,\n market: pool.market\n })\n }\n } else {\n rewardCoins.push({\n coin: rewardCoin,\n identifier: pool,\n owner,\n isEMode\n })\n }\n } else {\n // Standard reward claiming without custom handling\n if (!!options?.accountCap || isEMode) {\n const rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_with_account_cap`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds), // Rule IDs\n parseTxValue(options?.accountCap || address, tx.object) // Account capability\n ],\n typeArguments: [coinType]\n })\n\n const [rewardCoin]: any = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [rewardBalance],\n typeArguments: [coinType]\n })\n\n tx.transferObjects(\n [rewardCoin],\n parseTxValue(options?.accountCap || owner, tx.pure.address)\n )\n } else {\n tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_entry`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [coinType]\n })\n }\n }\n }\n return rewardCoins\n}\n"],"names":["getLendingRewardsBatch","address","tasks","options","client","suiClient","pools","getPools","MARKETS","DEFAULT_CACHE_TIME","feeds","getPriceFeeds","rewardsList","task","config","getConfig","tx","Transaction","item","devInspectTransaction","rewardsData","parseDevInspectResult","bcs","count","i","feed","normalizeCoinType","pool","e","getUserAvailableLendingRewards","markets","identity","getMarketConfig","emodeCaps","getUserEModeCaps","market","cap","summaryLendingRewards","rewards","agg","reward","assetId","rewardType","key","groupMap","coinType","total","groupKey","rewardMap","group","available","getUserTotalClaimedReward","withSingleton","endpoint","resolveNaviOpenApiEndpoint","url","buildNaviOpenApiUrl","packageJson","DEFAULT_MARKET_IDENTITY","mergeServiceHeaders","requestHeaders","res","getUserClaimedRewardHistory","camelize","claimLendingRewardsPTB","rewardCoinType","ruleIds","owner","emodeId","ruleId","rewardCoins","assetIds","amount","isEMode","filterPools","p","a","b","matchedRewardFund","rewardBalance","parseTxValue","rewardCoin","supplyAmount","BigNumber","depositCoinPTB"],"mappings":";;;;;;;;;;;AA4CA,eAAeA,EACbC,GACAC,GAMAC,GAC0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ACpC,QAAQ;AAAA,QACR,WAAW,CAAC+D,CAAa;AAAA,QACzB,eAAe,CAAClC,CAAQ;AAAA,MAAA,CACzB;AAED,MAAA7B,EAAG;AAAA,QACD,CAACiE,CAAU;AAAA,QACXD,EAAa7E,GAAS,cAAcgE,GAAOnD,EAAG,KAAK,OAAO;AAAA,MAAA;AAAA,IAE9D;AACE,MAAAA,EAAG,SAAS;AAAA,QACV,QAAQ,GAAGF,EAAO,OAAO;AAAA,QACzB,WAAW;AAAA,UACTE,EAAG,OAAO,MAAM;AAAA;AAAA,UAChBA,EAAG,OAAOF,EAAO,WAAW;AAAA;AAAA,UAC5BE,EAAG,OAAOF,EAAO,OAAO;AAAA;AAAA,UACxBE,EAAG,OAAO8D,CAAiB;AAAA;AAAA,UAC3B9D,EAAG,KAAK,OAAO,UAAUuD,CAAQ;AAAA;AAAA,UACjCvD,EAAG,KAAK,OAAO,WAAWkD,CAAO;AAAA;AAAA,QAAA;AAAA,QAEnC,eAAe,CAACrB,CAAQ;AAAA,MAAA,CACzB;AAAA,EAGP;AACA,SAAOyB;AACT;"}
@@ -0,0 +1,52 @@
1
+ const s = "https://open-api.naviprotocol.io/api";
2
+ let r = {}, t = 0;
3
+ function c(e) {
4
+ return e.replace(/\/+$/, "");
5
+ }
6
+ function p(e) {
7
+ r = {
8
+ ...r,
9
+ ...e,
10
+ services: {
11
+ ...r.services,
12
+ ...e.services
13
+ }
14
+ }, t += 1;
15
+ }
16
+ function f() {
17
+ return t;
18
+ }
19
+ function a(e) {
20
+ const n = e?.services?.naviOpenApi ?? r.services?.naviOpenApi;
21
+ return {
22
+ baseUrl: c(n?.baseUrl ?? s),
23
+ headers: n?.headers
24
+ };
25
+ }
26
+ function l(e, n) {
27
+ const i = a(n), o = e.startsWith("/") ? e : `/${e}`;
28
+ return `${i.baseUrl}${o}`;
29
+ }
30
+ function u(e) {
31
+ if (e instanceof Headers) {
32
+ const n = {};
33
+ return e.forEach((i, o) => {
34
+ n[o] = i;
35
+ }), n;
36
+ }
37
+ return Array.isArray(e) ? Object.fromEntries(e) : e;
38
+ }
39
+ function v(e, n) {
40
+ return {
41
+ ...u(e),
42
+ ...n?.headers ?? {}
43
+ };
44
+ }
45
+ export {
46
+ l as buildNaviOpenApiUrl,
47
+ p as configureNaviSdk,
48
+ f as getNaviSdkConfigVersion,
49
+ v as mergeServiceHeaders,
50
+ a as resolveNaviOpenApiEndpoint
51
+ };
52
+ //# sourceMappingURL=services.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services.js","sources":["../src/services.ts"],"sourcesContent":["export type NaviServiceEndpoint = {\n baseUrl: string\n headers?: Record<string, string>\n}\n\nexport type NaviSdkServiceOptions = {\n naviOpenApi?: NaviServiceEndpoint\n astrosApi?: NaviServiceEndpoint\n}\n\nexport type NaviSdkConfig = {\n services?: NaviSdkServiceOptions\n}\n\nexport type ServiceEndpointOption = {\n services?: NaviSdkServiceOptions\n}\n\nconst DEFAULT_NAVI_OPEN_API_BASE_URL = 'https://open-api.naviprotocol.io/api'\n\nlet globalConfig: NaviSdkConfig = {}\nlet serviceConfigVersion = 0\n\nfunction normalizeBaseUrl(baseUrl: string) {\n return baseUrl.replace(/\\/+$/, '')\n}\n\nexport function configureNaviSdk(config: NaviSdkConfig) {\n globalConfig = {\n ...globalConfig,\n ...config,\n services: {\n ...globalConfig.services,\n ...config.services\n }\n }\n serviceConfigVersion += 1\n}\n\nexport function getNaviSdkConfigVersion() {\n return serviceConfigVersion\n}\n\nexport function resolveNaviOpenApiEndpoint(options?: ServiceEndpointOption): NaviServiceEndpoint {\n const endpoint = options?.services?.naviOpenApi ?? globalConfig.services?.naviOpenApi\n return {\n baseUrl: normalizeBaseUrl(endpoint?.baseUrl ?? DEFAULT_NAVI_OPEN_API_BASE_URL),\n headers: endpoint?.headers\n }\n}\n\nexport function buildNaviOpenApiUrl(path: string, options?: ServiceEndpointOption) {\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const normalizedPath = path.startsWith('/') ? path : `/${path}`\n return `${endpoint.baseUrl}${normalizedPath}`\n}\n\nfunction headersInitToRecord(headers: HeadersInit): Record<string, string> {\n if (headers instanceof Headers) {\n const record: Record<string, string> = {}\n headers.forEach((value, key) => {\n record[key] = value\n })\n return record\n }\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers)\n }\n return headers\n}\n\nexport function mergeServiceHeaders(defaults: HeadersInit, endpoint?: NaviServiceEndpoint) {\n return {\n ...headersInitToRecord(defaults),\n ...(endpoint?.headers ?? {})\n }\n}\n"],"names":["DEFAULT_NAVI_OPEN_API_BASE_URL","globalConfig","serviceConfigVersion","normalizeBaseUrl","baseUrl","configureNaviSdk","config","getNaviSdkConfigVersion","resolveNaviOpenApiEndpoint","options","endpoint","buildNaviOpenApiUrl","path","normalizedPath","headersInitToRecord","headers","record","value","key","mergeServiceHeaders","defaults"],"mappings":"AAkBA,MAAMA,IAAiC;AAEvC,IAAIC,IAA8B,CAAA,GAC9BC,IAAuB;AAE3B,SAASC,EAAiBC,GAAiB;AACzC,SAAOA,EAAQ,QAAQ,QAAQ,EAAE;AACnC;AAEO,SAASC,EAAiBC,GAAuB;AACtD,EAAAL,IAAe;AAAA,IACb,GAAGA;AAAA,IACH,GAAGK;AAAA,IACH,UAAU;AAAA,MACR,GAAGL,EAAa;AAAA,MAChB,GAAGK,EAAO;AAAA,IAAA;AAAA,EACZ,GAEFJ,KAAwB;AAC1B;AAEO,SAASK,IAA0B;AACxC,SAAOL;AACT;AAEO,SAASM,EAA2BC,GAAsD;AAC/F,QAAMC,IAAWD,GAAS,UAAU,eAAeR,EAAa,UAAU;AAC1E,SAAO;AAAA,IACL,SAASE,EAAiBO,GAAU,WAAWV,CAA8B;AAAA,IAC7E,SAASU,GAAU;AAAA,EAAA;AAEvB;AAEO,SAASC,EAAoBC,GAAcH,GAAiC;AACjF,QAAMC,IAAWF,EAA2BC,CAAO,GAC7CI,IAAiBD,EAAK,WAAW,GAAG,IAAIA,IAAO,IAAIA,CAAI;AAC7D,SAAO,GAAGF,EAAS,OAAO,GAAGG,CAAc;AAC7C;AAEA,SAASC,EAAoBC,GAA8C;AACzE,MAAIA,aAAmB,SAAS;AAC9B,UAAMC,IAAiC,CAAA;AACvC,WAAAD,EAAQ,QAAQ,CAACE,GAAOC,MAAQ;AAC9B,MAAAF,EAAOE,CAAG,IAAID;AAAA,IAChB,CAAC,GACMD;AAAA,EACT;AACA,SAAI,MAAM,QAAQD,CAAO,IAChB,OAAO,YAAYA,CAAO,IAE5BA;AACT;AAEO,SAASI,EAAoBC,GAAuBV,GAAgC;AACzF,SAAO;AAAA,IACL,GAAGI,EAAoBM,CAAQ;AAAA,IAC/B,GAAIV,GAAU,WAAW,CAAA;AAAA,EAAC;AAE9B;"}
package/dist/sui.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CoinStruct } from '@mysten/sui/jsonRpc';
2
- import { NaviSdkServiceOptions } from './services';
2
+ import { NaviSdkServiceOptions } from './services.js';
3
3
 
4
4
  export type NaviSuiNetwork = 'mainnet' | 'testnet' | 'devnet' | 'localnet' | (string & {});
5
5
  export type NaviSuiGrpcEndpoint = {
package/dist/sui.js ADDED
@@ -0,0 +1,121 @@
1
+ import { SuiJsonRpcClient as C } from "@mysten/sui/jsonRpc";
2
+ import { SuiGraphQLClient as p } from "@mysten/sui/graphql";
3
+ import { SuiGrpcClient as o, GrpcWebFetchTransport as u } from "@mysten/sui/grpc";
4
+ import { normalizeStructTag as l } from "@mysten/sui/utils";
5
+ const s = "0x2::sui::SUI";
6
+ class g extends Error {
7
+ constructor(e) {
8
+ super(
9
+ `NAVI Sui SDK capability "${e}" requires an explicit graphql client; no public GraphQL fallback is configured`
10
+ ), this.name = "NaviMissingGraphQLClientError";
11
+ }
12
+ }
13
+ function c(n) {
14
+ return n == null ? void 0 : String(n);
15
+ }
16
+ function h(n, e) {
17
+ return (BigInt(n) + BigInt(e)).toString();
18
+ }
19
+ function S(n, e) {
20
+ return (BigInt(n) - BigInt(e)).toString();
21
+ }
22
+ function f(n) {
23
+ const e = n.core;
24
+ if (typeof e?.getBalance != "function" || typeof e?.listBalances != "function")
25
+ throw new Error("NAVI Sui balance helpers require a v2 Core API client");
26
+ return e;
27
+ }
28
+ function d(n, e = s) {
29
+ const r = c(n.addressBalance ?? n.fundsInAddressBalance) ?? "0";
30
+ let t = c(n.balance ?? n.totalBalance), i = c(n.coinBalance);
31
+ return !i && t && (i = S(t, r)), !t && i && (t = h(i, r)), {
32
+ coinType: l(n.coinType ?? e),
33
+ totalBalance: t ?? "0",
34
+ coinBalance: i ?? "0",
35
+ addressBalance: r,
36
+ ...n.coinObjectCount === null || n.coinObjectCount === void 0 ? {} : { coinObjectCount: n.coinObjectCount }
37
+ };
38
+ }
39
+ function L(n, e = s) {
40
+ const r = l(e);
41
+ return n.filter((t) => l(t.coinType) === r).reduce((t, i) => t + BigInt(i.balance), 0n).toString();
42
+ }
43
+ async function A(n, e) {
44
+ const r = await f(n).getBalance(e), t = r.balance;
45
+ return d((t && typeof t == "object" ? t : r) ?? {}, e.coinType);
46
+ }
47
+ async function k(n, e) {
48
+ const r = await f(n).listBalances(e), { balances: t = [] } = r;
49
+ return {
50
+ balances: t.map((i) => d(i)),
51
+ nextCursor: r.nextCursor ?? r.cursor ?? null
52
+ };
53
+ }
54
+ function w(n, e) {
55
+ if ("client" in e)
56
+ return e.client;
57
+ const r = new u({
58
+ baseUrl: e.url,
59
+ meta: e.headers,
60
+ fetchInit: e.fetchInit,
61
+ fetch: e.fetch
62
+ });
63
+ return new o({
64
+ network: n,
65
+ transport: r
66
+ });
67
+ }
68
+ function m(n, e) {
69
+ return "client" in e ? e.client : new p({
70
+ network: n,
71
+ url: e.url,
72
+ headers: e.headers,
73
+ fetch: e.fetch
74
+ });
75
+ }
76
+ function B(n, e) {
77
+ return "client" in e ? e.client : new C({
78
+ network: n,
79
+ url: e.url
80
+ });
81
+ }
82
+ function I(n) {
83
+ const e = w(n.network, n.grpc);
84
+ return {
85
+ network: n.network,
86
+ coreClient: e,
87
+ grpc: e,
88
+ graphql: n.graphql ? m(n.network, n.graphql) : void 0,
89
+ legacyJsonRpc: n.legacyJsonRpc ? B(n.network, n.legacyJsonRpc) : void 0,
90
+ services: n.services
91
+ };
92
+ }
93
+ function E(n, e) {
94
+ if (!n.graphql)
95
+ throw new g(e);
96
+ return n.graphql;
97
+ }
98
+ const y = "https://fullnode.mainnet.sui.io:443";
99
+ let a;
100
+ function b() {
101
+ return a || (a = new o({
102
+ network: "mainnet",
103
+ transport: new u({ baseUrl: y })
104
+ })), a;
105
+ }
106
+ function j(n, e = "mainnet") {
107
+ return n ? typeof n == "string" ? B(e, { url: n }) : I(n) : b();
108
+ }
109
+ export {
110
+ g as NaviMissingGraphQLClientError,
111
+ y as PUBLIC_MAINNET_GRPC_URL,
112
+ B as createNaviLegacyJsonRpcClient,
113
+ j as createNaviSuiClient,
114
+ I as createNaviSuiClientBundle,
115
+ A as getAddressBalance,
116
+ L as getCoinObjectOnlyBalance,
117
+ k as listAddressBalances,
118
+ d as normalizeAddressBalance,
119
+ E as requireNaviGraphQLClient
120
+ };
121
+ //# sourceMappingURL=sui.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sui.js","sources":["../src/sui.ts"],"sourcesContent":["import type { CoinStruct } from '@mysten/sui/jsonRpc'\nimport { SuiJsonRpcClient } from '@mysten/sui/jsonRpc'\nimport { SuiGraphQLClient } from '@mysten/sui/graphql'\nimport { GrpcWebFetchTransport, SuiGrpcClient } from '@mysten/sui/grpc'\nimport { normalizeStructTag } from '@mysten/sui/utils'\nimport type { NaviSdkServiceOptions } from './services'\n\nconst DEFAULT_SUI_COIN_TYPE = '0x2::sui::SUI'\nexport type NaviSuiNetwork = 'mainnet' | 'testnet' | 'devnet' | 'localnet' | (string & {})\n\nexport type NaviSuiGrpcEndpoint = {\n url: string\n headers?: Record<string, string>\n fetchInit?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'>\n fetch?: typeof fetch\n}\n\nexport type NaviSuiGraphQLEndpoint = {\n url: string\n headers?: Record<string, string>\n fetch?: typeof fetch\n}\n\nexport type NaviSuiGrpcOptions =\n | {\n client: NaviCoreClient\n url?: never\n headers?: never\n fetchInit?: never\n fetch?: never\n }\n | NaviSuiGrpcEndpoint\n\nexport type NaviSuiGraphQLOptions =\n | {\n client: NaviCoreClient & { query?(options: any): Promise<any> }\n url?: never\n headers?: never\n fetch?: never\n }\n | NaviSuiGraphQLEndpoint\n\nexport type NaviSuiLegacyJsonRpcOptions =\n | {\n client: NaviJsonRpcCompatClient\n url?: never\n }\n | {\n url: string\n }\n\nexport type NaviSuiClientOptions = {\n network: NaviSuiNetwork\n grpc: NaviSuiGrpcOptions\n graphql?: NaviSuiGraphQLOptions\n /**\n * @deprecated JSON-RPC is a short-lived compatibility transport. New main paths must use gRPC/Core.\n */\n legacyJsonRpc?: NaviSuiLegacyJsonRpcOptions\n services?: NaviSdkServiceOptions\n}\n\nexport type NaviSuiClientBundle = {\n network: NaviSuiNetwork\n coreClient: NaviCoreClient\n grpc: NaviCoreClient\n graphql?: NaviCoreClient & { query?(options: any): Promise<any> }\n /**\n * @deprecated JSON-RPC is a short-lived compatibility transport.\n */\n legacyJsonRpc?: NaviJsonRpcCompatClient\n services?: NaviSdkServiceOptions\n}\n\ntype SuiAddressBalanceLike = {\n coinType?: string | null\n balance?: string | number | bigint | null\n totalBalance?: string | number | bigint | null\n coinBalance?: string | number | bigint | null\n addressBalance?: string | number | bigint | null\n fundsInAddressBalance?: string | number | bigint | null\n coinObjectCount?: number | null\n}\n\ntype NaviBalanceCore = {\n getBalance(options: any): Promise<{ balance?: SuiAddressBalanceLike } | SuiAddressBalanceLike>\n listBalances(options: any): Promise<{\n balances?: SuiAddressBalanceLike[]\n cursor?: string | null\n nextCursor?: string | null\n hasNextPage?: boolean\n }>\n}\n\nexport type NaviCoreClient = {\n core: unknown\n}\n\nexport type NaviJsonRpcCompatClient = NaviCoreClient & {\n devInspectTransactionBlock(options: any): Promise<any>\n dryRunTransactionBlock(options: any): Promise<any>\n executeTransactionBlock(options: any): Promise<any>\n getAllCoins(options: any): Promise<any>\n getCoinMetadata(options: any): Promise<any>\n getCoins(options: any): Promise<any>\n getDynamicFieldObject(options: any): Promise<any>\n getObject(options: any): Promise<any>\n getTransactionBlock(options: any): Promise<any>\n multiGetObjects(options: any): Promise<any>\n signAndExecuteTransaction(options: any): Promise<any>\n waitForTransaction(options: any): Promise<any>\n}\n\nexport type NaviSuiClient = NaviCoreClient & Partial<NaviJsonRpcCompatClient>\n\nexport type NaviAddressBalance = {\n coinType: string\n totalBalance: string\n coinBalance: string\n addressBalance: string\n coinObjectCount?: number\n}\n\nexport class NaviMissingGraphQLClientError extends Error {\n constructor(capability: string) {\n super(\n `NAVI Sui SDK capability \"${capability}\" requires an explicit graphql client; no public GraphQL fallback is configured`\n )\n this.name = 'NaviMissingGraphQLClientError'\n }\n}\n\nfunction balanceValueToString(value: string | number | bigint | null | undefined) {\n return value === null || value === undefined ? undefined : String(value)\n}\n\nfunction addBalanceStrings(left: string, right: string) {\n return (BigInt(left) + BigInt(right)).toString()\n}\n\nfunction subtractBalanceStrings(left: string, right: string) {\n return (BigInt(left) - BigInt(right)).toString()\n}\n\nfunction getCoreBalanceClient(client: NaviCoreClient): NaviBalanceCore {\n const core = client.core as Partial<NaviBalanceCore> | undefined\n if (typeof core?.getBalance !== 'function' || typeof core?.listBalances !== 'function') {\n throw new Error('NAVI Sui balance helpers require a v2 Core API client')\n }\n return core as NaviBalanceCore\n}\n\nexport function normalizeAddressBalance(\n balance: SuiAddressBalanceLike,\n fallbackCoinType = DEFAULT_SUI_COIN_TYPE\n): NaviAddressBalance {\n const addressBalance =\n balanceValueToString(balance.addressBalance ?? balance.fundsInAddressBalance) ?? '0'\n let totalBalance = balanceValueToString(balance.balance ?? balance.totalBalance)\n let coinBalance = balanceValueToString(balance.coinBalance)\n\n if (!coinBalance && totalBalance) {\n coinBalance = subtractBalanceStrings(totalBalance, addressBalance)\n }\n if (!totalBalance && coinBalance) {\n totalBalance = addBalanceStrings(coinBalance, addressBalance)\n }\n\n return {\n coinType: normalizeStructTag(balance.coinType ?? fallbackCoinType),\n totalBalance: totalBalance ?? '0',\n coinBalance: coinBalance ?? '0',\n addressBalance,\n ...(balance.coinObjectCount === null || balance.coinObjectCount === undefined\n ? {}\n : { coinObjectCount: balance.coinObjectCount })\n }\n}\n\nexport function getCoinObjectOnlyBalance(coins: CoinStruct[], coinType = DEFAULT_SUI_COIN_TYPE) {\n const normalizedCoinType = normalizeStructTag(coinType)\n return coins\n .filter((coin) => normalizeStructTag(coin.coinType) === normalizedCoinType)\n .reduce((sum, coin) => sum + BigInt(coin.balance), 0n)\n .toString()\n}\n\nexport async function getAddressBalance(\n client: NaviCoreClient,\n options: { owner: string; coinType?: string }\n) {\n const response = await getCoreBalanceClient(client).getBalance(options)\n const responseBalance = (response as { balance?: SuiAddressBalanceLike }).balance\n const balance =\n responseBalance && typeof responseBalance === 'object'\n ? responseBalance\n : (response as SuiAddressBalanceLike)\n return normalizeAddressBalance(balance ?? {}, options.coinType)\n}\n\nexport async function listAddressBalances(\n client: NaviCoreClient,\n options: { owner: string; cursor?: string | null; limit?: number }\n) {\n const response = await getCoreBalanceClient(client).listBalances(options)\n const { balances = [] } = response\n return {\n balances: balances.map((balance) => normalizeAddressBalance(balance)),\n nextCursor: response.nextCursor ?? response.cursor ?? null\n }\n}\n\nfunction createGrpcClient(network: NaviSuiNetwork, grpc: NaviSuiGrpcOptions): NaviCoreClient {\n if ('client' in grpc) {\n return grpc.client\n }\n const transport = new GrpcWebFetchTransport({\n baseUrl: grpc.url,\n meta: grpc.headers,\n fetchInit: grpc.fetchInit,\n fetch: grpc.fetch\n })\n return new SuiGrpcClient({\n network,\n transport\n })\n}\n\nfunction createGraphQLClient(\n network: NaviSuiNetwork,\n graphql: NaviSuiGraphQLOptions\n): NaviCoreClient & { query?(options: any): Promise<any> } {\n if ('client' in graphql) {\n return graphql.client\n }\n return new SuiGraphQLClient({\n network,\n url: graphql.url,\n headers: graphql.headers,\n fetch: graphql.fetch\n })\n}\n\nexport function createNaviLegacyJsonRpcClient(\n network: NaviSuiNetwork,\n legacyJsonRpc: NaviSuiLegacyJsonRpcOptions\n): NaviJsonRpcCompatClient {\n if ('client' in legacyJsonRpc) {\n return legacyJsonRpc.client\n }\n return new SuiJsonRpcClient({\n network,\n url: legacyJsonRpc.url\n })\n}\n\nexport function createNaviSuiClientBundle(options: NaviSuiClientOptions): NaviSuiClientBundle {\n const grpc = createGrpcClient(options.network, options.grpc)\n return {\n network: options.network,\n coreClient: grpc,\n grpc,\n graphql: options.graphql ? createGraphQLClient(options.network, options.graphql) : undefined,\n legacyJsonRpc: options.legacyJsonRpc\n ? createNaviLegacyJsonRpcClient(options.network, options.legacyJsonRpc)\n : undefined,\n services: options.services\n }\n}\n\nexport function requireNaviGraphQLClient(\n bundle: Pick<NaviSuiClientBundle, 'graphql'>,\n capability: string\n) {\n if (!bundle.graphql) {\n throw new NaviMissingGraphQLClientError(capability)\n }\n return bundle.graphql\n}\n\n/** Public mainnet gRPC endpoint used when no client is provided (same idea as v1's getFullnodeUrl('mainnet')). */\nexport const PUBLIC_MAINNET_GRPC_URL = 'https://fullnode.mainnet.sui.io:443'\n\nlet defaultPublicSuiClient: NaviSuiClient | undefined\n\n/**\n * Default public-mainnet client, matching v1 behavior: when the caller does not\n * pass a client, fall back to the public mainnet fullnode. Fine for development\n * and low volume; production should pass its own client (private endpoint/auth).\n */\nfunction createDefaultNaviSuiClient(): NaviSuiClient {\n if (!defaultPublicSuiClient) {\n defaultPublicSuiClient = new SuiGrpcClient({\n network: 'mainnet',\n transport: new GrpcWebFetchTransport({ baseUrl: PUBLIC_MAINNET_GRPC_URL })\n }) as unknown as NaviSuiClient\n }\n return defaultPublicSuiClient\n}\n\nexport function createNaviSuiClient(options: NaviSuiClientOptions): NaviSuiClientBundle\n/**\n * @deprecated JSON-RPC is a short-lived compatibility transport. Use\n * `createNaviSuiClientBundle({ network, grpc, legacyJsonRpc? })` for release paths.\n */\nexport function createNaviSuiClient(url: string, network?: NaviSuiNetwork): NaviJsonRpcCompatClient\nexport function createNaviSuiClient(): NaviSuiClient\nexport function createNaviSuiClient(\n optionsOrUrl?: NaviSuiClientOptions | string,\n network: NaviSuiNetwork = 'mainnet'\n): NaviSuiClientBundle | NaviJsonRpcCompatClient | NaviSuiClient {\n if (!optionsOrUrl) {\n return createDefaultNaviSuiClient()\n }\n if (typeof optionsOrUrl === 'string') {\n return createNaviLegacyJsonRpcClient(network, { url: optionsOrUrl })\n }\n return createNaviSuiClientBundle(optionsOrUrl)\n}\n"],"names":["DEFAULT_SUI_COIN_TYPE","NaviMissingGraphQLClientError","capability","balanceValueToString","value","addBalanceStrings","left","right","subtractBalanceStrings","getCoreBalanceClient","client","core","normalizeAddressBalance","balance","fallbackCoinType","addressBalance","totalBalance","coinBalance","normalizeStructTag","getCoinObjectOnlyBalance","coins","coinType","normalizedCoinType","coin","sum","getAddressBalance","options","response","responseBalance","listAddressBalances","balances","createGrpcClient","network","grpc","transport","GrpcWebFetchTransport","SuiGrpcClient","createGraphQLClient","graphql","SuiGraphQLClient","createNaviLegacyJsonRpcClient","legacyJsonRpc","SuiJsonRpcClient","createNaviSuiClientBundle","requireNaviGraphQLClient","bundle","PUBLIC_MAINNET_GRPC_URL","defaultPublicSuiClient","createDefaultNaviSuiClient","createNaviSuiClient","optionsOrUrl"],"mappings":";;;;AAOA,MAAMA,IAAwB;AAoHvB,MAAMC,UAAsC,MAAM;AAAA,EACvD,YAAYC,GAAoB;AAC9B;AAAA,MACE,4BAA4BA,CAAU;AAAA,IAAA,GAExC,KAAK,OAAO;AAAA,EACd;AACF;AAEA,SAASC,EAAqBC,GAAoD;AAChF,SAAOA,KAAU,OAA8B,SAAY,OAAOA,CAAK;AACzE;AAEA,SAASC,EAAkBC,GAAcC,GAAe;AACtD,UAAQ,OAAOD,CAAI,IAAI,OAAOC,CAAK,GAAG,SAAA;AACxC;AAEA,SAASC,EAAuBF,GAAcC,GA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c,EAA8Bd,EAAQ,SAASA,EAAQ,aAAa,IACpE;AAAA,IACJ,UAAUA,EAAQ;AAAA,EAAA;AAEtB;AAEO,SAASkB,EACdC,GACA3C,GACA;AACA,MAAI,CAAC2C,EAAO;AACV,UAAM,IAAI5C,EAA8BC,CAAU;AAEpD,SAAO2C,EAAO;AAChB;AAGO,MAAMC,IAA0B;AAEvC,IAAIC;AAOJ,SAASC,IAA4C;AACnD,SAAKD,MACHA,IAAyB,IAAIX,EAAc;AAAA,IACzC,SAAS;AAAA,IACT,WAAW,IAAID,EAAsB,EAAE,SAASW,GAAyB;AAAA,EAAA,CAC1E,IAEIC;AACT;AASO,SAASE,EACdC,GACAlB,IAA0B,WACqC;AAC/D,SAAKkB,IAGD,OAAOA,KAAiB,WACnBV,EAA8BR,GAAS,EAAE,KAAKkB,GAAc,IAE9DP,EAA0BO,CAAY,IALpCF,EAAA;AAMX;"}
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { NaviSuiClient } from './sui';
2
- import { ServiceEndpointOption } from './services';
1
+ import { NaviSuiClient } from './sui.js';
2
+ import { ServiceEndpointOption } from './services.js';
3
3
  import { TransactionObjectArgument as TransactionObjectArgumentType, TransactionObjectInput as TransactionObjectInputType, TransactionResult as TransactionResultType } from '@mysten/sui/transactions';
4
4
 
5
5
  export type MarketConfig = {
package/dist/ua.js ADDED
@@ -0,0 +1,16 @@
1
+ import s from "./package.json.js";
2
+ const n = s.version, r = () => {
3
+ if (typeof process < "u" && process.versions && process.versions.node) {
4
+ const e = process.version;
5
+ return `Node.js ${e.startsWith("v") ? e.substring(1) : e}`;
6
+ }
7
+ return "Node/Unknown";
8
+ }, t = () => {
9
+ let e = "";
10
+ return typeof process < "u" && process.versions && process.versions.node && (e = `lending/${n} (${r()})`), e;
11
+ }, d = t();
12
+ export {
13
+ t as getUserAgent,
14
+ d as userAgent
15
+ };
16
+ //# sourceMappingURL=ua.js.map