@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/oracle.js ADDED
@@ -0,0 +1,198 @@
1
+ import { getConfig as p, DEFAULT_CACHE_TIME as l } from "./config.js";
2
+ import { SuiPriceServiceConnection as w, SuiPythClient as j } from "./pyth.js";
3
+ import { suiClient as m, multiGetSuiObjects as F } from "./utils.js";
4
+ import { getLendingPositions as T } from "./account.js";
5
+ const b = new w("https://hermes.pyth.network", {
6
+ timeout: 1e4
7
+ });
8
+ async function U(t) {
9
+ try {
10
+ const n = [], r = await b.getLatestPriceFeeds(t);
11
+ if (!r) return n;
12
+ const c = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
13
+ for (const e of r) {
14
+ const i = e.getPriceUnchecked();
15
+ if (i.publishTime > c) {
16
+ console.warn(
17
+ `pyth price feed is invalid, id: ${e.id}, publish time: ${i.publishTime}, current timestamp: ${c}`
18
+ );
19
+ continue;
20
+ }
21
+ c - e.getPriceUnchecked().publishTime > 30 && (console.info(
22
+ `stale price feed, id: ${e.id}, publish time: ${i.publishTime}, current timestamp: ${c}`
23
+ ), n.push(e.id));
24
+ }
25
+ return n;
26
+ } catch (n) {
27
+ throw new Error(`failed to get pyth stale price feed id, msg: ${n.message}`);
28
+ }
29
+ }
30
+ async function O(t, n) {
31
+ const r = [], c = n?.client ?? m, e = t.map((o) => o.priceInfoObject), i = await F(c, {
32
+ ids: Array.from(new Set(e)),
33
+ options: { showContent: !0 }
34
+ });
35
+ for (const o of i) {
36
+ const a = o.data;
37
+ if (!a || !a.content || a.content.dataType !== "moveObject") {
38
+ console.warn(`fetched object ${a?.objectId} datatype should be moveObject`);
39
+ continue;
40
+ }
41
+ const d = t.find((I) => I.priceInfoObject == a.objectId);
42
+ if (!d) {
43
+ console.warn(`unable to find pyth info from array, priceInfoObject: ${a.objectId}`);
44
+ continue;
45
+ }
46
+ const s = a.content.fields?.price_info?.price_feed?.price, u = s?.price;
47
+ if (!u) {
48
+ console.warn(`unexpected pyth price struct, priceInfoObject: ${a.objectId}`);
49
+ continue;
50
+ }
51
+ const { magnitude: f, negative: y } = u, P = s.conf, g = s.timestamp;
52
+ r.push({
53
+ priceFeedId: d.priceFeedId,
54
+ priceInfoObject: d.priceInfoObject,
55
+ price: y ? "-" + f : f,
56
+ conf: P,
57
+ publishTime: Number(g),
58
+ expiration: d.expiration
59
+ });
60
+ }
61
+ return r;
62
+ }
63
+ async function $(t, n) {
64
+ try {
65
+ const r = [], c = await O(t, n);
66
+ if (!c) return r;
67
+ const e = Math.floor((/* @__PURE__ */ new Date()).valueOf() / 1e3);
68
+ for (const i of c) {
69
+ if (i.publishTime > e) {
70
+ console.warn(
71
+ `pyth price feed is invalid, id: ${i.priceFeedId}, publish time: ${i.publishTime}, current timestamp: ${e}`
72
+ );
73
+ continue;
74
+ }
75
+ const o = i.expiration || 60;
76
+ e - i.publishTime > o && (console.info(
77
+ `stale price feed, id: ${i.priceFeedId}, publish time: ${i.publishTime}, current timestamp: ${e}`
78
+ ), r.push(i.priceFeedId));
79
+ }
80
+ return r;
81
+ } catch (r) {
82
+ throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`);
83
+ }
84
+ }
85
+ async function v(t, n, r) {
86
+ const c = r?.client ?? m, e = await p({
87
+ ...r,
88
+ cacheTime: l
89
+ });
90
+ try {
91
+ const i = await b.getPriceFeedsUpdateData(n);
92
+ return await new j(
93
+ c,
94
+ e.oracle.pythStateId,
95
+ e.oracle.wormholeStateId
96
+ ).updatePriceFeeds(t, i, n);
97
+ } catch (i) {
98
+ throw new Error(`failed to update pyth price feeds, msg: ${i.message}`);
99
+ }
100
+ }
101
+ async function h(t, n, r) {
102
+ const c = await p({
103
+ ...r,
104
+ cacheTime: l
105
+ });
106
+ if (r?.updatePythPriceFeeds) {
107
+ const e = n.filter((o) => !!o.pythPriceFeedId && !!o.pythPriceInfoObject).map((o) => ({
108
+ priceFeedId: o.pythPriceFeedId,
109
+ priceInfoObject: o.pythPriceInfoObject,
110
+ expiration: 30
111
+ })), i = await $(e, r);
112
+ i.length > 0 && await v(t, i, r);
113
+ }
114
+ for (const e of n)
115
+ t.moveCall({
116
+ target: `${c.oracle.packageId}::oracle_pro::update_single_price_v2`,
117
+ arguments: [
118
+ t.object("0x6"),
119
+ // Clock object
120
+ t.object(c.oracle.oracleConfig),
121
+ // Oracle configuration
122
+ t.object(c.oracle.priceOracle),
123
+ // Price oracle contract
124
+ t.object(c.oracle.supraOracleHolder),
125
+ // Supra oracle holder
126
+ t.object(e.pythPriceInfoObject),
127
+ // Pyth price info object
128
+ t.object(c.oracle.switchboardAggregator),
129
+ t.pure.address(e.feedId)
130
+ // Price feed ID
131
+ ]
132
+ });
133
+ return t;
134
+ }
135
+ async function S(t) {
136
+ return (await p({
137
+ ...t,
138
+ cacheTime: l
139
+ })).oracle.feeds;
140
+ }
141
+ function C(t, n) {
142
+ return t.filter((r) => !!(n?.lendingState && n.lendingState.find((e) => r.oracleId === e.pool.oracleId) || n?.lendingPositions && n.lendingPositions.find((e) => {
143
+ if (![
144
+ "navi-lending-supply",
145
+ "navi-lending-borrow",
146
+ "navi-lending-emode-supply",
147
+ "navi-lending-emode-borrow"
148
+ ].includes(e.type))
149
+ return !1;
150
+ const o = e[e.type]?.pool;
151
+ return r.oracleId === o?.oracleId;
152
+ }) || n?.pools && n.pools.find((e) => r.oracleId === e.oracleId)));
153
+ }
154
+ async function A(t, n, r, c) {
155
+ let e;
156
+ try {
157
+ const i = await S({
158
+ ...c
159
+ }), o = [];
160
+ r.forEach((s) => {
161
+ o.includes(s.market) || o.push(s.market);
162
+ });
163
+ const a = await T(n, {
164
+ ...c,
165
+ markets: o
166
+ });
167
+ return e = C(i, {
168
+ lendingPositions: a,
169
+ pools: r
170
+ }), await h(t, e, {
171
+ updatePythPriceFeeds: !0,
172
+ ...c
173
+ });
174
+ } catch (i) {
175
+ if (c?.throws)
176
+ throw i;
177
+ if (console.error(i), e)
178
+ try {
179
+ return await h(t, e, {
180
+ ...c,
181
+ updatePythPriceFeeds: !1
182
+ });
183
+ } catch (o) {
184
+ console.error(o);
185
+ }
186
+ return t;
187
+ }
188
+ }
189
+ export {
190
+ C as filterPriceFeeds,
191
+ S as getPriceFeeds,
192
+ U as getPythStalePriceFeedId,
193
+ $ as getPythStalePriceFeedIdV2,
194
+ A as updateOraclePriceBeforeUserOperationPTB,
195
+ h as updateOraclePricesPTB,
196
+ v as updatePythPriceFeeds
197
+ };
198
+ //# sourceMappingURL=oracle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oracle.js","sources":["../src/oracle.ts"],"sourcesContent":["/**\n * Oracle Price Feed Management for Lending Protocol\n *\n * This module provides oracle price feed functionality for the lending protocol.\n * It integrates with Pyth Network for real-time price data and manages price updates\n * for various assets used in lending operations.\n */\n\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport type {\n OraclePriceFeed,\n EnvOption,\n UserLendingInfo,\n Pool,\n SuiClientOption,\n MarketOption,\n LendingPosition,\n ServiceOption\n} from './types'\nimport { SuiPriceServiceConnection, SuiPythClient } from './pyth'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { multiGetSuiObjects, suiClient } from './utils'\nimport { getLendingPositions } from './account'\n\ntype PythInfo = {\n priceFeedId: string\n priceInfoObject: string\n expiration?: number\n}\n\nexport type PythPriceInfo = {\n priceFeedId: string\n priceInfoObject: string\n price: string\n conf: string\n publishTime: number\n expiration?: number\n}\n\n/**\n * Pyth Network connection for price feed data\n * Connects to the Hermes endpoint for real-time price updates\n */\nconst suiPythConnection = new SuiPriceServiceConnection('https://hermes.pyth.network', {\n timeout: 10000\n})\n\n/**\n * Get stale price feed IDs from Pyth Network\n *\n * Identifies price feeds that have not been updated recently (more than 30 seconds old).\n * This helps ensure that only fresh price data is used for lending operations.\n *\n * @param priceIds - Array of Pyth price feed IDs to check\n * @returns Array of stale price feed IDs that need updating\n * @throws Error if failed to fetch price feed data\n */\nexport async function getPythStalePriceFeedId(priceIds: string[]): Promise<string[]> {\n try {\n const returnData: string[] = []\n const latestPriceFeeds = await suiPythConnection.getLatestPriceFeeds(priceIds)\n if (!latestPriceFeeds) return returnData\n\n const currentTimestamp = Math.floor(new Date().valueOf() / 1000)\n for (const priceFeed of latestPriceFeeds) {\n const uncheckedPrice = priceFeed.getPriceUnchecked()\n if (uncheckedPrice.publishTime > currentTimestamp) {\n console.warn(\n `pyth price feed is invalid, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n continue\n }\n\n // From pyth state is 60, but setting it to 30 makes more sense.\n if (currentTimestamp - priceFeed.getPriceUnchecked().publishTime > 30) {\n console.info(\n `stale price feed, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n returnData.push(priceFeed.id)\n }\n }\n return returnData\n } catch (error) {\n throw new Error(`failed to get pyth stale price feed id, msg: ${(error as Error).message}`)\n }\n}\n\nasync function getOnChainPriceInfo(\n pythInfos: PythInfo[],\n options?: Partial<SuiClientOption>\n): Promise<PythPriceInfo[]> {\n // Whole-read failures (endpoint/RPC errors) propagate to the caller:\n // swallowing them here would silently skip the Pyth staleness update and let\n // transactions build against stale on-chain prices. Only per-feed anomalies\n // are skipped below.\n const priceInfos: PythPriceInfo[] = []\n const client = options?.client ?? suiClient\n\n const priceInfoObjectIds = pythInfos.map((k) => k.priceInfoObject)\n const priceInfoObjects = await multiGetSuiObjects(client, {\n ids: Array.from(new Set(priceInfoObjectIds)),\n options: { showContent: true }\n })\n for (const obj of priceInfoObjects) {\n const data = obj.data\n if (!data || !data.content || data.content.dataType !== 'moveObject') {\n console.warn(`fetched object ${data?.objectId} datatype should be moveObject`)\n continue\n }\n\n const pythInfo = pythInfos.find((v) => v.priceInfoObject == data.objectId)\n if (!pythInfo) {\n console.warn(`unable to find pyth info from array, priceInfoObject: ${data.objectId}`)\n continue\n }\n\n // The Sui v2 client returns nested Move structs directly, without the\n // per-level `.fields` wrapper the legacy JSON-RPC object shape carried.\n // Read the flattened shape and skip (not throw) on an unexpected object so\n // a single malformed feed can't abort the whole batch and silently leave\n // every on-chain price un-refreshed.\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n const priceStruct = data.content.fields?.price_info?.price_feed?.price\n const priceValue = priceStruct?.price\n if (!priceValue) {\n console.warn(`unexpected pyth price struct, priceInfoObject: ${data.objectId}`)\n continue\n }\n const { magnitude, negative } = priceValue\n const conf = priceStruct.conf\n const timestamp = priceStruct.timestamp\n\n priceInfos.push({\n priceFeedId: pythInfo.priceFeedId,\n priceInfoObject: pythInfo.priceInfoObject,\n price: negative ? '-' + magnitude : magnitude,\n conf,\n publishTime: Number(timestamp),\n expiration: pythInfo.expiration\n })\n }\n return priceInfos\n}\n\nexport async function getPythStalePriceFeedIdV2(\n pythInfos: PythInfo[],\n options?: Partial<SuiClientOption>\n): Promise<string[]> {\n try {\n const returnData: string[] = []\n const latestPriceFeeds = await getOnChainPriceInfo(pythInfos, options)\n if (!latestPriceFeeds) return returnData\n\n const currentTimestamp = Math.floor(new Date().valueOf() / 1000)\n\n for (const priceFeed of latestPriceFeeds) {\n if (priceFeed.publishTime > currentTimestamp) {\n console.warn(\n `pyth price feed is invalid, id: ${priceFeed.priceFeedId}, publish time: ${priceFeed.publishTime}, current timestamp: ${currentTimestamp}`\n )\n continue\n }\n\n const maxTime = priceFeed.expiration || 60\n // 3s is the margin of error for the price feed.\n if (currentTimestamp - priceFeed.publishTime > maxTime) {\n console.info(\n `stale price feed, id: ${priceFeed.priceFeedId}, publish time: ${priceFeed.publishTime}, current timestamp: ${currentTimestamp}`\n )\n returnData.push(priceFeed.priceFeedId)\n }\n }\n return returnData\n } catch (error) {\n throw new Error(`failed to get pyth stale price feed id, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update Pyth price feeds in a transaction\n *\n * Fetches the latest price update data from Pyth Network and adds the update\n * operations to the transaction block.\n *\n * @param tx - The transaction block to add price feed updates to\n * @param priceFeedIds - Array of Pyth price feed IDs to update\n * @param options - Optional client and environment configuration\n * @returns Promise that resolves when price feeds are updated\n * @throws Error if failed to update price feeds\n */\nexport async function updatePythPriceFeeds(\n tx: Transaction,\n priceFeedIds: string[],\n options?: Partial<SuiClientOption & EnvOption & MarketOption>\n) {\n const client = options?.client ?? suiClient\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n try {\n const priceUpdateData = await suiPythConnection.getPriceFeedsUpdateData(priceFeedIds)\n const suiPythClient = new SuiPythClient(\n client as any,\n config.oracle.pythStateId,\n config.oracle.wormholeStateId\n )\n\n return await suiPythClient.updatePriceFeeds(tx as any, priceUpdateData, priceFeedIds)\n } catch (error) {\n throw new Error(`failed to update pyth price feeds, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update oracle prices in the PTB (Programmable Transaction Block)\n *\n * This function updates price feeds for the lending protocol. It can optionally\n * update Pyth price feeds first if they are stale, then updates individual\n * price feeds in the oracle contract.\n *\n * @param tx - The transaction block to add price update operations to\n * @param priceFeeds - Array of oracle price feeds to update\n * @param options - Optional configuration including whether to update Pyth feeds\n * @returns The updated transaction block\n */\nexport async function updateOraclePricesPTB(\n tx: Transaction,\n priceFeeds: OraclePriceFeed[],\n options?: Partial<\n EnvOption &\n SuiClientOption &\n ServiceOption &\n MarketOption & {\n updatePythPriceFeeds?: boolean\n }\n >\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Optionally update Pyth price feeds if they are stale\n if (options?.updatePythPriceFeeds) {\n const pythInfos = priceFeeds\n .filter((feed) => !!feed.pythPriceFeedId && !!feed.pythPriceInfoObject)\n .map((feed) => ({\n priceFeedId: feed.pythPriceFeedId,\n priceInfoObject: feed.pythPriceInfoObject,\n expiration: 30\n }))\n\n // Do not silently swallow Pyth stale-price update failures: the previous\n // catch kept building the tx with possibly stale on-chain prices and masked\n // real endpoint/RPC errors. Throw so callers are aware (avoids\n // lending/liquidation based on stale prices).\n const stalePriceFeedIds = await getPythStalePriceFeedIdV2(pythInfos, options)\n if (stalePriceFeedIds.length > 0) {\n await updatePythPriceFeeds(tx, stalePriceFeedIds, options)\n }\n }\n\n // Update individual price feeds in the oracle contract\n for (const priceFeed of priceFeeds) {\n tx.moveCall({\n target: `${config.oracle.packageId}::oracle_pro::update_single_price_v2`,\n arguments: [\n tx.object('0x6'), // Clock object\n tx.object(config.oracle.oracleConfig), // Oracle configuration\n tx.object(config.oracle.priceOracle), // Price oracle contract\n tx.object(config.oracle.supraOracleHolder), // Supra oracle holder\n tx.object(priceFeed.pythPriceInfoObject), // Pyth price info object\n tx.object(config.oracle.switchboardAggregator),\n tx.pure.address(priceFeed.feedId) // Price feed ID\n ]\n })\n }\n return tx\n}\n\n/**\n * Get all available price feeds from the configuration\n *\n * @param options - Optional environment configuration\n * @returns Array of oracle price feed configurations\n */\nexport async function getPriceFeeds(\n options?: Partial<EnvOption & ServiceOption>\n): Promise<OraclePriceFeed[]> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n return config.oracle.feeds\n}\n\n/**\n * Filter price feeds based on lending state and pools\n *\n * This function filters price feeds to only include those that are relevant\n * to the current lending state or available pools.\n *\n * @param feeds - Array of price feeds to filter\n * @param filters - Filter criteria including lending state and pools\n * @returns Filtered array of price feeds\n */\nexport function filterPriceFeeds(\n feeds: OraclePriceFeed[],\n filters: {\n lendingState?: UserLendingInfo[]\n pools?: Pool[]\n lendingPositions?: LendingPosition[]\n }\n): OraclePriceFeed[] {\n return feeds.filter((feed) => {\n // Filter by lending state (user's current positions)\n if (filters?.lendingState) {\n const inState = filters.lendingState.find((state) => {\n return feed.oracleId === state.pool.oracleId\n })\n if (inState) {\n return true\n }\n }\n\n if (filters?.lendingPositions) {\n const inPosition = filters.lendingPositions.find((position) => {\n const availableTypes = [\n 'navi-lending-supply',\n 'navi-lending-borrow',\n 'navi-lending-emode-supply',\n 'navi-lending-emode-borrow'\n ]\n if (!availableTypes.includes(position.type)) {\n return false\n }\n const pool = position[position.type]?.pool\n return feed.oracleId === pool?.oracleId\n })\n if (inPosition) {\n return true\n }\n }\n\n // Filter by available pools\n if (filters?.pools) {\n const inPool = filters.pools.find((pool) => {\n return feed.oracleId === pool.oracleId\n })\n if (inPool) {\n return true\n }\n }\n return false\n })\n}\n\nexport async function updateOraclePriceBeforeUserOperationPTB(\n tx: Transaction,\n address: string,\n pools: Pool[],\n options?: Partial<\n EnvOption &\n SuiClientOption &\n MarketOption & {\n throws?: boolean\n }\n >\n) {\n let relevantFeeds: OraclePriceFeed[] | undefined\n try {\n const allPriceFeeds = await getPriceFeeds({\n ...options\n })\n\n const markets = [] as string[]\n\n pools.forEach((pool) => {\n if (!markets.includes(pool.market)) {\n markets.push(pool.market)\n }\n })\n\n const lendingPositions = await getLendingPositions(address, {\n ...options,\n markets\n })\n\n relevantFeeds = filterPriceFeeds(allPriceFeeds, {\n lendingPositions,\n pools\n })\n\n const updatedTx = await updateOraclePricesPTB(tx, relevantFeeds, {\n updatePythPriceFeeds: true,\n ...options\n })\n return updatedTx\n } catch (e) {\n if (options?.throws) {\n throw e\n }\n console.error(e)\n // Degraded path: a Pyth refresh failure happens before any moveCall is\n // appended, so the tx is still clean. Retry the oracle update without the\n // Pyth feed refresh (matches the pre-v2 behavior where Pyth failures were\n // swallowed but update_single_price calls were still appended) instead of\n // dropping the oracle update entirely.\n if (relevantFeeds) {\n try {\n return await updateOraclePricesPTB(tx, relevantFeeds, {\n ...options,\n updatePythPriceFeeds: false\n })\n } catch (fallbackError) {\n console.error(fallbackError)\n }\n }\n return tx\n }\n}\n"],"names":["suiPythConnection","SuiPriceServiceConnection","getPythStalePriceFeedId","priceIds","returnData","latestPriceFeeds","currentTimestamp","priceFeed","uncheckedPrice","error","getOnChainPriceInfo","pythInfos","options","priceInfos","client","suiClient","priceInfoObjectIds","k","priceInfoObjects","multiGetSuiObjects","obj","data","pythInfo","v","priceStruct","priceValue","magnitude","negative","conf","timestamp","getPythStalePriceFeedIdV2","maxTime","updatePythPriceFeeds","tx","priceFeedIds","config","getConfig","DEFAULT_CACHE_TIME","priceUpdateData","SuiPythClient","updateOraclePricesPTB","priceFeeds","feed","stalePriceFeedIds","getPriceFeeds","filterPriceFeeds","feeds","filters","state","position","pool","updateOraclePriceBeforeUserOperationPTB","address","pools","relevantFeeds","allPriceFeeds","markets","lendingPositions","getLendingPositions","e","fallbackError"],"mappings":";;;;AA2CA,MAAMA,IAAoB,IAAIC,EAA0B,+BAA+B;AAAA,EACrF,SAAS;AACX,CAAC;AAYD,eAAsBC,EAAwBC,GAAuC;AACnF,MAAI;AACF,UAAMC,IAAuB,CAAA,GACvBC,IAAmB,MAAML,EAAkB,oBAAoBG,CAAQ;AAC7E,QAAI,CAACE,EAAkB,QAAOD;AAE9B,UAAME,IAAmB,KAAK,OAAM,oBAAI,QAAO,QAAA,IAAY,GAAI;AAC/D,eAAWC,KAAaF,GAAkB;AACxC,YAAMG,IAAiBD,EAAU,kBAAA;AACjC,UAAIC,EAAe,cAAcF,GAAkB;AACjD,gBAAQ;AAAA,UACN,mCAAmCC,EAAU,EAAE,mBAAmBC,EAAe,WAAW,wBAAwBF,CAAgB;AAAA,QAAA;AAEtI;AAAA,MACF;AAGA,MAAIA,IAAmBC,EAAU,kBAAA,EAAoB,cAAc,OACjE,QAAQ;AAAA,QACN,yBAAyBA,EAAU,EAAE,mBAAmBC,EAAe,WAAW,wBAAwBF,CAAgB;AAAA,MAAA,GAE5HF,EAAW,KAAKG,EAAU,EAAE;AAAA,IAEhC;AACA,WAAOH;AAAA,EACT,SAASK,GAAO;AACd,UAAM,IAAI,MAAM,gDAAiDA,EAAgB,OAAO,EAAE;AAAA,EAC5F;AACF;AA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+ o as version
7
+ };
8
+ //# sourceMappingURL=package.json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.json.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
package/dist/pool.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EnvOption, CacheOption, Pool, AssetIdentifier, PoolStats, FeeDetail, CoinObject, TransactionResult, SingleCoinTransactionResult, AccountCapOption, BorrowFeeOption, SuiClientOption, MarketOption, MarketsOption, ServiceOption } from './types';
1
+ import { EnvOption, CacheOption, Pool, AssetIdentifier, PoolStats, FeeDetail, CoinObject, TransactionResult, SingleCoinTransactionResult, AccountCapOption, BorrowFeeOption, SuiClientOption, MarketOption, MarketsOption, ServiceOption } from './types.js';
2
2
  import { Transaction } from '@mysten/sui/transactions';
3
3
 
4
4
  /**
package/dist/pool.js ADDED
@@ -0,0 +1,391 @@
1
+ import { DEFAULT_CACHE_TIME as g, getConfig as d } from "./config.js";
2
+ import { withCache as y, withSingleton as w, requestHeaders as C, parsePoolUID as N, normalizeCoinType as m, parseTxValue as u, suiClient as I, devInspectTransaction as U, parseDevInspectResult as R, getSuiObject as F } from "./utils.js";
3
+ import { resolveNaviOpenApiEndpoint as f, buildNaviOpenApiUrl as h, mergeServiceHeaders as _ } from "./services.js";
4
+ import { Transaction as W } from "@mysten/sui/transactions";
5
+ import p from "bignumber.js";
6
+ import { bcs as M } from "@mysten/sui/bcs";
7
+ import T from "./package.json.js";
8
+ import { MARKETS as P, getMarketConfig as V, DEFAULT_MARKET_IDENTITY as B } from "./market.js";
9
+ var q = /* @__PURE__ */ ((e) => (e[e.Supply = 1] = "Supply", e[e.Withdraw = 2] = "Withdraw", e[e.Borrow = 3] = "Borrow", e[e.Repay = 4] = "Repay", e))(q || {});
10
+ const H = y(
11
+ w(
12
+ async (e) => {
13
+ const a = (e?.markets || [P.main]).map((t) => V(t)), r = f(e), n = h(
14
+ `/navi/pools?env=${e?.env || "prod"}&sdk=${T.version}&market=${a.map(
15
+ (t) => t.key
16
+ )}`,
17
+ e
18
+ ), o = await fetch(n, { headers: _(C, r) }).then(
19
+ (t) => t.json()
20
+ );
21
+ return o.data.forEach((t) => {
22
+ const i = o.meta.emodes.filter((v) => {
23
+ const j = V(v.marketId);
24
+ return t.market === j.key && v.isActive;
25
+ }).filter((v) => !!v.assets.find((j) => j.assetId === t.id));
26
+ t.emodes = i;
27
+ const l = p(t.totalSupplyAmount).div(Math.pow(10, 9)).decimalPlaces(t.token.decimals, p.ROUND_DOWN).toString(), s = p(t.borrowedAmount).shiftedBy(-9).decimalPlaces(t.token.decimals, p.ROUND_DOWN).toString(), S = p(l).multipliedBy(t.oracle.price).toString(), $ = p(s).multipliedBy(t.oracle.price).toString(), A = p(t.supplyCapCeiling).shiftedBy(-27).decimalPlaces(t.token.decimals, p.ROUND_DOWN).toString(), k = p.max(
28
+ p(t.borrowedAmount),
29
+ p(t.validBorrowAmount)
30
+ ).shiftedBy(-9).decimalPlaces(t.token.decimals, p.ROUND_DOWN).toString(), D = p(A).multipliedBy(t.oracle.price).toString(), E = p(k).multipliedBy(t.oracle.price).toString();
31
+ t.poolSupplyAmount = l, t.poolBorrowAmount = s, t.poolSupplyValue = S, t.poolBorrowValue = $, t.poolSupplyCapAmount = A, t.poolBorrowCapAmount = k, t.poolSupplyCapValue = D, t.poolBorrowCapValue = E;
32
+ }), o.data;
33
+ }
34
+ )
35
+ );
36
+ async function b(e, a) {
37
+ let r = a?.market;
38
+ if (typeof e == "string") {
39
+ const t = N(e);
40
+ t && (r = t.marketKey, e = t.poolId);
41
+ }
42
+ const n = await H({
43
+ ...a,
44
+ markets: [r || B],
45
+ cacheTime: g
46
+ });
47
+ if (typeof e == "object")
48
+ return e;
49
+ const o = n.find((t) => typeof e == "string" ? m(t.suiCoinType) === m(e) : typeof e == "number" ? t.id === e : !1);
50
+ if (!o)
51
+ throw new Error("Pool not found");
52
+ return o.isDeprecated && console.log(`The lending pool for coinType ${o.suiCoinType} is going to be deprecated.`), o;
53
+ }
54
+ const X = y(
55
+ w(async (e) => {
56
+ const a = f(e), r = h(`/navi/stats?sdk=${T.version}`, e);
57
+ return (await fetch(r, {
58
+ headers: _(C, a)
59
+ }).then((o) => o.json())).data;
60
+ })
61
+ ), Z = y(
62
+ w(
63
+ async (e) => {
64
+ const a = f(e), r = h(`/navi/fee?sdk=${T.version}`, e);
65
+ return await fetch(r, {
66
+ headers: _(C, a)
67
+ }).then((o) => o.json());
68
+ }
69
+ )
70
+ );
71
+ async function x(e, a, r, n) {
72
+ const o = await d({
73
+ ...n,
74
+ cacheTime: g
75
+ }), t = await b(a, n), c = n?.market || B, i = n?.env || "prod";
76
+ if (t?.deprecatedAt && Date.now() > t.deprecatedAt)
77
+ throw new Error(`The lending pool for coinType ${t.suiCoinType} has been deprecated.`);
78
+ if (m(t.suiCoinType) === m("0x2::sui::SUI") && typeof r == "object" && r?.$kind === "GasCoin") {
79
+ if (!n?.amount)
80
+ throw new Error("Amount is required for sui coin");
81
+ r = e.splitCoins(r, [n.amount]);
82
+ }
83
+ let l;
84
+ return typeof n?.amount < "u" ? l = u(n.amount, e.pure.u64) : l = e.moveCall({
85
+ target: "0x2::coin::value",
86
+ arguments: [u(r, e.object)],
87
+ typeArguments: [t.suiCoinType]
88
+ }), n?.accountCap ? e.moveCall({
89
+ target: `${o.package}::incentive_v3::deposit_with_account_cap`,
90
+ arguments: [
91
+ e.object("0x06"),
92
+ e.object(o.storage),
93
+ e.object(t.contract.pool),
94
+ e.pure.u8(t.id),
95
+ u(r, e.object),
96
+ e.object(o.incentiveV2),
97
+ e.object(o.incentiveV3),
98
+ u(n.accountCap, e.object)
99
+ ],
100
+ typeArguments: [t.suiCoinType]
101
+ }) : e.moveCall({
102
+ target: `${o.package}::incentive_v3::entry_deposit`,
103
+ arguments: [
104
+ e.object("0x06"),
105
+ e.object(o.storage),
106
+ e.object(t.contract.pool),
107
+ e.pure.u8(t.id),
108
+ u(r, e.object),
109
+ l,
110
+ e.object(o.incentiveV2),
111
+ e.object(o.incentiveV3)
112
+ ],
113
+ typeArguments: [t.suiCoinType]
114
+ }), o.version === 2 && t.token.symbol === "SUI" && i === "prod" && c === "main" && e.moveCall({
115
+ target: `${o.package}::pool::refresh_stake`,
116
+ arguments: [e.object(t.contract.pool), e.object("0x05")]
117
+ }), e;
118
+ }
119
+ async function ee(e, a, r, n) {
120
+ const o = await d({
121
+ ...n,
122
+ cacheTime: g
123
+ }), t = await b(a, n), c = u(r, e.pure.u64);
124
+ let i;
125
+ if (o.version === 1)
126
+ if (n?.accountCap) {
127
+ const [s] = e.moveCall({
128
+ target: `${o.package}::incentive_v3::withdraw_with_account_cap`,
129
+ arguments: [
130
+ e.object("0x06"),
131
+ e.object(o.priceOracle),
132
+ e.object(o.storage),
133
+ e.object(t.contract.pool),
134
+ e.pure.u8(t.id),
135
+ c,
136
+ e.object(o.incentiveV2),
137
+ e.object(o.incentiveV3),
138
+ u(n.accountCap, e.object)
139
+ ],
140
+ typeArguments: [t.suiCoinType]
141
+ });
142
+ i = s;
143
+ } else {
144
+ const [s] = e.moveCall({
145
+ target: `${o.package}::incentive_v3::withdraw`,
146
+ arguments: [
147
+ e.object("0x06"),
148
+ e.object(o.priceOracle),
149
+ e.object(o.storage),
150
+ e.object(t.contract.pool),
151
+ e.pure.u8(t.id),
152
+ c,
153
+ e.object(o.incentiveV2),
154
+ e.object(o.incentiveV3)
155
+ ],
156
+ typeArguments: [t.suiCoinType]
157
+ });
158
+ i = s;
159
+ }
160
+ else if (n?.accountCap) {
161
+ const [s] = e.moveCall({
162
+ target: `${o.package}::incentive_v3::withdraw_with_account_cap_v2`,
163
+ arguments: [
164
+ e.object("0x06"),
165
+ e.object(o.priceOracle),
166
+ e.object(o.storage),
167
+ e.object(t.contract.pool),
168
+ e.pure.u8(t.id),
169
+ c,
170
+ e.object(o.incentiveV2),
171
+ e.object(o.incentiveV3),
172
+ u(n.accountCap, e.object),
173
+ e.object("0x05")
174
+ ],
175
+ typeArguments: [t.suiCoinType]
176
+ });
177
+ i = s;
178
+ } else {
179
+ const [s] = e.moveCall({
180
+ target: `${o.package}::incentive_v3::withdraw_v2`,
181
+ arguments: [
182
+ e.object("0x06"),
183
+ e.object(o.priceOracle),
184
+ e.object(o.storage),
185
+ e.object(t.contract.pool),
186
+ e.pure.u8(t.id),
187
+ c,
188
+ e.object(o.incentiveV2),
189
+ e.object(o.incentiveV3),
190
+ e.object("0x05")
191
+ ],
192
+ typeArguments: [t.suiCoinType]
193
+ });
194
+ i = s;
195
+ }
196
+ return e.moveCall({
197
+ target: "0x2::coin::from_balance",
198
+ arguments: [i],
199
+ typeArguments: [t.suiCoinType]
200
+ });
201
+ }
202
+ async function te(e, a, r, n) {
203
+ const o = await d({
204
+ ...n,
205
+ cacheTime: g
206
+ }), t = await b(a, n);
207
+ if (t?.deprecatedAt && Date.now() > t.deprecatedAt)
208
+ throw new Error(`The lending pool for coinType ${t.suiCoinType} has been deprecated.`);
209
+ const c = u(r, e.pure.u64);
210
+ let i;
211
+ if (o.version === 1)
212
+ if (n?.accountCap) {
213
+ const [s] = e.moveCall({
214
+ target: `${o.package}::incentive_v3::borrow_with_account_cap`,
215
+ arguments: [
216
+ e.object("0x06"),
217
+ e.object(o.priceOracle),
218
+ e.object(o.storage),
219
+ e.object(t.contract.pool),
220
+ e.pure.u8(t.id),
221
+ c,
222
+ e.object(o.incentiveV2),
223
+ e.object(o.incentiveV3),
224
+ u(n.accountCap, e.object)
225
+ ],
226
+ typeArguments: [t.suiCoinType]
227
+ });
228
+ i = s;
229
+ } else {
230
+ const [s] = e.moveCall({
231
+ target: `${o.package}::incentive_v3::borrow`,
232
+ arguments: [
233
+ e.object("0x06"),
234
+ e.object(o.priceOracle),
235
+ e.object(o.storage),
236
+ e.object(t.contract.pool),
237
+ e.pure.u8(t.id),
238
+ c,
239
+ e.object(o.incentiveV2),
240
+ e.object(o.incentiveV3)
241
+ ],
242
+ typeArguments: [t.suiCoinType]
243
+ });
244
+ i = s;
245
+ }
246
+ else if (n?.accountCap) {
247
+ const [s] = e.moveCall({
248
+ target: `${o.package}::incentive_v3::borrow_with_account_cap_v2`,
249
+ arguments: [
250
+ e.object("0x06"),
251
+ e.object(o.priceOracle),
252
+ e.object(o.storage),
253
+ e.object(t.contract.pool),
254
+ e.pure.u8(t.id),
255
+ c,
256
+ e.object(o.incentiveV2),
257
+ e.object(o.incentiveV3),
258
+ u(n.accountCap, e.object),
259
+ e.object("0x05")
260
+ ],
261
+ typeArguments: [t.suiCoinType]
262
+ });
263
+ i = s;
264
+ } else {
265
+ const [s] = e.moveCall({
266
+ target: `${o.package}::incentive_v3::borrow_v2`,
267
+ arguments: [
268
+ e.object("0x06"),
269
+ e.object(o.priceOracle),
270
+ e.object(o.storage),
271
+ e.object(t.contract.pool),
272
+ e.pure.u8(t.id),
273
+ c,
274
+ e.object(o.incentiveV2),
275
+ e.object(o.incentiveV3),
276
+ e.object("0x05")
277
+ ],
278
+ typeArguments: [t.suiCoinType]
279
+ });
280
+ i = s;
281
+ }
282
+ return e.moveCall({
283
+ target: "0x2::coin::from_balance",
284
+ arguments: [e.object(i)],
285
+ typeArguments: [t.suiCoinType]
286
+ });
287
+ }
288
+ async function oe(e, a, r, n) {
289
+ const o = await d({
290
+ ...n,
291
+ cacheTime: g
292
+ }), t = await b(a, n);
293
+ if (m(t.suiCoinType) === m("0x2::sui::SUI") && typeof r == "object" && r?.$kind === "GasCoin") {
294
+ if (!n?.amount)
295
+ throw new Error("Amount is required for sui coin");
296
+ r = e.splitCoins(r, [n.amount]);
297
+ }
298
+ let c;
299
+ if (typeof n?.amount < "u" ? c = u(n.amount, e.pure.u64) : c = e.moveCall({
300
+ target: "0x2::coin::value",
301
+ arguments: [u(r, e.object)],
302
+ typeArguments: [t.suiCoinType]
303
+ }), n?.accountCap) {
304
+ const [i] = e.moveCall({
305
+ target: `${o.package}::incentive_v3::repay_with_account_cap`,
306
+ arguments: [
307
+ e.object("0x06"),
308
+ e.object(o.priceOracle),
309
+ e.object(o.storage),
310
+ e.object(t.contract.pool),
311
+ e.pure.u8(t.id),
312
+ u(r, e.object),
313
+ e.object(o.incentiveV2),
314
+ e.object(o.incentiveV3),
315
+ u(n.accountCap, e.object)
316
+ ],
317
+ typeArguments: [t.suiCoinType]
318
+ });
319
+ return e.moveCall({
320
+ target: "0x2::coin::from_balance",
321
+ arguments: [i],
322
+ typeArguments: [t.suiCoinType]
323
+ });
324
+ } else
325
+ return e.moveCall({
326
+ target: `${o.package}::incentive_v3::entry_repay`,
327
+ arguments: [
328
+ e.object("0x06"),
329
+ e.object(o.priceOracle),
330
+ e.object(o.storage),
331
+ e.object(t.contract.pool),
332
+ e.pure.u8(t.id),
333
+ u(r, e.object),
334
+ c,
335
+ e.object(o.incentiveV2),
336
+ e.object(o.incentiveV3)
337
+ ],
338
+ typeArguments: [t.suiCoinType]
339
+ }), e;
340
+ }
341
+ const ne = y(
342
+ w(
343
+ async (e) => {
344
+ const a = await d({
345
+ ...e
346
+ }), r = e?.client ?? I;
347
+ if (e?.address && typeof e?.asset < "u")
348
+ try {
349
+ const t = await b(e.asset, e), c = new W();
350
+ c.moveCall({
351
+ target: `${a.package}::incentive_v3::get_borrow_fee_v2`,
352
+ arguments: [
353
+ c.object(a.incentiveV3),
354
+ c.pure.address(e.address),
355
+ c.pure.u8(t.id),
356
+ c.pure.u64(1e4)
357
+ ],
358
+ typeArguments: []
359
+ });
360
+ const i = await U(r, {
361
+ transactionBlock: c,
362
+ sender: e.address
363
+ }), l = R(i, [M.u64()]);
364
+ return (Number(l[0]) || 0) / 100;
365
+ } catch (t) {
366
+ console.error(
367
+ "[lending] getBorrowFee per-user query failed, falling back to global rate:",
368
+ t
369
+ );
370
+ }
371
+ const o = (await F(r, {
372
+ id: a.incentiveV3,
373
+ options: { showType: !0, showOwner: !0, showContent: !0 }
374
+ })).data.content.fields.borrow_fee_rate;
375
+ return Number(o) / 100;
376
+ }
377
+ )
378
+ );
379
+ export {
380
+ q as PoolOperator,
381
+ te as borrowCoinPTB,
382
+ x as depositCoinPTB,
383
+ ne as getBorrowFee,
384
+ Z as getFees,
385
+ b as getPool,
386
+ H as getPools,
387
+ X as getStats,
388
+ oe as repayCoinPTB,
389
+ ee as withdrawCoinPTB
390
+ };
391
+ //# sourceMappingURL=pool.js.map