@naviprotocol/lending 2.0.5-dev.0 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/account-cap.d.ts +1 -1
  2. package/dist/account.d.ts +2 -2
  3. package/dist/config.d.ts +1 -1
  4. package/dist/emode.d.ts +1 -1
  5. package/dist/flashloan.d.ts +1 -1
  6. package/dist/index.d.ts +17 -17
  7. package/dist/index.esm.js +2749 -0
  8. package/dist/index.esm.js.map +1 -0
  9. package/dist/liquidate.d.ts +1 -1
  10. package/dist/market.d.ts +1 -1
  11. package/dist/oracle.d.ts +2 -2
  12. package/dist/oracle.d.ts.map +1 -1
  13. package/dist/pool.d.ts +1 -1
  14. package/dist/pyth.d.ts +1 -1
  15. package/dist/reward.d.ts +1 -1
  16. package/dist/sui.d.ts +1 -1
  17. package/dist/types.d.ts +6 -2
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/utils.d.ts +2 -2
  20. package/package.json +5 -5
  21. package/dist/account-cap.js +0 -26
  22. package/dist/account-cap.js.map +0 -1
  23. package/dist/account.js +0 -655
  24. package/dist/account.js.map +0 -1
  25. package/dist/bcs.js +0 -137
  26. package/dist/bcs.js.map +0 -1
  27. package/dist/config.js +0 -22
  28. package/dist/config.js.map +0 -1
  29. package/dist/emode.js +0 -90
  30. package/dist/emode.js.map +0 -1
  31. package/dist/flashloan.js +0 -94
  32. package/dist/flashloan.js.map +0 -1
  33. package/dist/index.js +0 -100
  34. package/dist/index.js.map +0 -1
  35. package/dist/liquidate.js +0 -76
  36. package/dist/liquidate.js.map +0 -1
  37. package/dist/market.js +0 -121
  38. package/dist/market.js.map +0 -1
  39. package/dist/oracle.js +0 -198
  40. package/dist/oracle.js.map +0 -1
  41. package/dist/package.json.js +0 -8
  42. package/dist/package.json.js.map +0 -1
  43. package/dist/pool.js +0 -391
  44. package/dist/pool.js.map +0 -1
  45. package/dist/pyth.js +0 -305
  46. package/dist/pyth.js.map +0 -1
  47. package/dist/reward.js +0 -343
  48. package/dist/reward.js.map +0 -1
  49. package/dist/services.js +0 -52
  50. package/dist/services.js.map +0 -1
  51. package/dist/sui.js +0 -121
  52. package/dist/sui.js.map +0 -1
  53. package/dist/ua.js +0 -16
  54. package/dist/ua.js.map +0 -1
  55. package/dist/utils.js +0 -227
  56. package/dist/utils.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"account.js","sources":["../src/account.ts"],"sourcesContent":["/**\n * Lending Account Management\n *\n * This module provides comprehensive account management functionality for the lending protocol.\n * It includes coin merging, health factor calculations, user state management, and various\n * lending operations like supply, borrow, withdraw, and repay.\n *\n * @module LendingAccount\n */\n\nimport type {\n UserLendingInfo,\n SuiClientOption,\n EnvOption,\n Pool,\n Transaction as NAVITransaction,\n AssetIdentifier,\n TransactionResult,\n CacheOption,\n AccountCap,\n MarketOption,\n LendingPosition,\n MarketsOption,\n EModePool,\n EModeCap,\n ServiceOption\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { UserStateInfo, ReserveDataInfo } from './bcs'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n parseDevInspectResult,\n devInspectTransaction,\n withSingleton,\n processContractHealthFactor,\n parseTxValue,\n parseTxPoolValue,\n withCache,\n normalizeCoinType,\n rayMathMulIndex,\n requestHeaders,\n poolToEModePool,\n getPoolsMap,\n uuid,\n suiClient\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport type { CoinStruct, PaginatedCoins } from '@mysten/sui/jsonRpc'\nimport { getPool, PoolOperator, getPools } from './pool'\nimport packageJson from '../package.json'\nimport { getUserEModeCaps } from './emode'\nimport BigNumber from 'bignumber.js'\nimport { getMarketConfig, MARKETS } from './market'\nimport { buildNaviOpenApiUrl, mergeServiceHeaders, resolveNaviOpenApiEndpoint } from './services'\n\nfunction getCoreCoinType(coin: any, fallbackCoinType?: string) {\n if (coin.coinType) return coin.coinType\n if (fallbackCoinType) return fallbackCoinType\n\n const match = typeof coin.type === 'string' ? coin.type.match(/::coin::Coin<(.+)>$/) : null\n return match?.[1]\n}\n\nfunction normalizeCoreCoin(coin: any, fallbackCoinType?: string): CoinStruct | null {\n const coinType = getCoreCoinType(coin, fallbackCoinType)\n const coinObjectId = coin.coinObjectId ?? coin.objectId\n if (!coinType || !coinObjectId || coin.balance === undefined || coin.balance === null) {\n return null\n }\n\n return {\n ...coin,\n coinType: normalizeCoinType(coinType),\n coinObjectId\n } as CoinStruct\n}\n\n/**\n * Merges multiple coins into a single coin for transaction building\n *\n * This function takes multiple coin objects and merges them into a single coin\n * that can be used in a transaction. It supports optional splitting to create\n * a specific balance amount.\n *\n * @param tx - Transaction object to add merge operations to\n * @param coins - Array of coin objects to merge\n * @param options - Optional parameters for balance splitting and gas coin usage\n * - `balance` - If provided, splits this amount from the resulting coin object\n * - `useGasCoin` - If true, uses the gas coin for the operation\n * - `addressBalance` - Funds held directly at the address level (v2 address\n * balances) for this coin type. `coins` only carries `Coin<T>` objects, so\n * when they fall short of `balance` this covers the remainder. Defaults to\n * `0`, which preserves the legacy coin-object-only behavior exactly.\n * - `coinType` - Coin type used to withdraw the shortfall from the address\n * balance via `0x2::coin::redeem_funds`. Required for the address-balance\n * path; ignored when the owned coin objects already cover `balance`.\n * @returns Transaction result representing the merged coin\n */\nexport function mergeCoinsPTB(\n tx: Transaction,\n coins: ({\n balance: string | number | bigint\n coinObjectId: string\n coinType: string\n } & CoinStruct)[],\n options?: {\n balance?: number\n useGasCoin?: boolean\n addressBalance?: string | number | bigint\n coinType?: string\n }\n) {\n const needSplit = typeof options?.balance === 'number'\n const splitBalance = needSplit ? options.balance! : 0\n const addressBalance = BigInt(options?.addressBalance ?? 0)\n let mergedBalance = 0\n const mergeList: string[] = []\n let coinType = ''\n // Full sum of the passed coin objects (used for the combined sufficiency\n // check and to size the address-balance shortfall). Kept separate from\n // `mergedBalance`, which can stop early once `splitBalance` is reached.\n let objectsBalance = 0n\n\n // Sort coins by balance (highest first) and collect valid coins\n coins\n .sort((a, b) => Number(b.balance) - Number(a.balance))\n .forEach((coin) => {\n objectsBalance += BigInt(coin.balance)\n if (needSplit && mergedBalance >= splitBalance) {\n return\n }\n if (Number(coin.balance) === 0) {\n return\n }\n if (!coinType) {\n coinType = coin.coinType\n }\n if (coinType !== coin.coinType) {\n throw new Error('All coins must be of the same type')\n }\n mergedBalance += Number(coin.balance)\n mergeList.push(coin.coinObjectId)\n })\n\n // Coin type driving the SUI/gas decision and the address-balance withdrawal.\n // When there are no coin objects the local `coinType` (derived from\n // `coins[i].coinType`) is empty, so fall back to the caller-supplied\n // `options.coinType` — required for the address-only case, and it also avoids\n // passing an empty string into `normalizeCoinType` (which would throw).\n const redeemCoinType = options?.coinType\n const effectiveType = coinType || redeemCoinType || ''\n // Tolerant SUI check: an unparseable/placeholder coin type is simply \"not SUI\"\n // and must not throw before the balance guards (which run below), matching the\n // original ordering.\n const isSuiType = (type: string) => {\n if (!type) {\n return false\n }\n try {\n return normalizeCoinType(type) === normalizeCoinType('0x2::sui::SUI')\n } catch {\n return false\n }\n }\n const isSuiGas = isSuiType(effectiveType) && !!options?.useGasCoin\n\n // Address balance is only actually spendable when we can redeem it: on the\n // non-gas path AND with a coinType to withdraw against. The SUI gas-coin path\n // cannot draw from it, and without a coinType there is no redeem_funds call —\n // so in those cases it must not count toward the sufficiency check (otherwise\n // the combined total would pass and we'd split against coin objects that are\n // still short).\n const need = BigInt(splitBalance)\n const canUseAddressBalance = !isSuiGas && !!redeemCoinType\n const usableAddressBalance = canUseAddressBalance ? addressBalance : 0n\n const combined = objectsBalance + usableAddressBalance\n // Shortfall the address balance must cover. Only meaningful when splitting.\n // `combined >= need` (checked below) guarantees `shortfall <= usableAddressBalance`.\n const shortfall = !needSplit || objectsBalance >= need ? 0n : need - objectsBalance\n const canRedeem = canUseAddressBalance && shortfall > 0n && usableAddressBalance >= shortfall\n\n // Insufficiency first: when splitting and the (usable) combined total is short,\n // report the balance shortfall — including the address-only case (no coin\n // objects but some address balance) — rather than the misleading empty-wallet\n // \"No coins to merge\".\n if (needSplit && combined < need) {\n throw new Error(`Balance is less than the specified balance: ${combined} < ${need}`)\n }\n // Genuinely nothing to work with: no coin objects and no address-balance\n // shortfall to redeem. Preserves the legacy \"No coins to merge\" behavior.\n if (mergeList.length === 0 && !canRedeem) {\n throw new Error('No coins to merge')\n }\n\n // Handle SUI gas coin specially. SUI stays on the gas-split path and is never\n // routed through redeem_funds.\n if (isSuiGas) {\n return needSplit ? tx.splitCoins(tx.gas, [tx.pure.u64(splitBalance)]) : tx.gas\n }\n\n // Legacy coin-object-only path: the owned objects already cover the request\n // (or no address balance is in play). Behavior is byte-for-byte unchanged.\n if (!canRedeem) {\n mergeList.length === 1\n ? tx.object(mergeList[0])\n : tx.mergeCoins(mergeList[0], mergeList.slice(1))\n\n return needSplit ? tx.splitCoins(mergeList[0], [tx.pure.u64(splitBalance)]) : mergeList[0]\n }\n\n // Address-balance path: withdraw the shortfall from the address balance and\n // merge it with the owned coin objects (largest first). When there are no\n // coin objects at all, the redeemed coin becomes the base.\n const redeemedCoin = tx.moveCall({\n target: '0x2::coin::redeem_funds',\n typeArguments: [redeemCoinType!],\n arguments: [tx.withdrawal({ amount: shortfall, type: redeemCoinType! })]\n })\n\n let baseCoin: any\n const restCoins: any[] = []\n if (mergeList.length > 0) {\n baseCoin = tx.object(mergeList[0])\n for (const id of mergeList.slice(1)) {\n restCoins.push(tx.object(id))\n }\n restCoins.push(redeemedCoin)\n } else {\n baseCoin = redeemedCoin\n }\n\n if (restCoins.length > 0) {\n tx.mergeCoins(baseCoin, restCoins)\n }\n\n // Pure address-balance case: the base is the redeemed coin (no owned coin\n // objects), and shortfall === splitBalance, so it already holds exactly the\n // requested amount. Return it directly — splitting the full amount would leave\n // a zero-balance redeemed Coin result unused, and Coin has no `drop` ability,\n // so the PTB would fail. (Mixed object + address paths split from an owned\n // object base, whose leftover stays in place and is fine.)\n if (mergeList.length === 0) {\n return baseCoin\n }\n\n return needSplit ? tx.splitCoins(baseCoin, [tx.pure.u64(splitBalance)]) : baseCoin\n}\n\n/**\n * Calculates dynamic health factor for a user after potential operations\n *\n * This function creates a transaction call to calculate the health factor\n * that would result after performing supply/borrow operations.\n *\n * @param tx - Transaction object to append calculation to\n * @param address - User address or transaction result\n * @param identifier - Asset identifier\n * @param estimatedSupply - Estimated supply amount\n * @param estimatedBorrow - Estimated borrow amount\n * @param isIncrease - Whether this is an increase operation\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getSimulatedHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n identifier: AssetIdentifier,\n estimatedSupply: number | TransactionResult,\n estimatedBorrow: number | TransactionResult,\n isIncrease: boolean | TransactionResult,\n options?: Partial<EnvOption & MarketOption>\n): Promise<TransactionResult> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n return tx.moveCall({\n target: `${config.uiGetter}::calculator_unchecked::dynamic_health_factor`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(config.oracle.priceOracle),\n parseTxPoolValue(tx, pool),\n parseTxValue(address, tx.pure.address),\n parseTxValue(pool.id, tx.pure.u8),\n parseTxValue(estimatedSupply, tx.pure.u64),\n parseTxValue(estimatedBorrow, tx.pure.u64),\n parseTxValue(isIncrease, tx.pure.bool)\n ],\n typeArguments: [pool.suiCoinType]\n })\n}\n\n/**\n * Gets the current health factor for a user\n *\n * @param tx - The transaction object to add health factor query operation to\n * @param address - User address or account cap or transaction result\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n options?: Partial<EnvOption>\n): Promise<TransactionResult> {\n return getSimulatedHealthFactorPTB(tx, address, 0, 0, 0, false, options)\n}\n\nasync function getLendingStateBatch(\n address: string,\n tasks: {\n address: string\n market: string\n emodeId?: number\n }[],\n options?: Partial<\n SuiClientOption &\n EnvOption &\n CacheOption & {\n includeZeroBalanceEmodePositions?: boolean\n }\n >\n): Promise<UserLendingInfo[]> {\n const tx = new Transaction()\n const client = options?.client ?? suiClient\n const pools = await getPools({\n ...options,\n markets: Object.values(MARKETS)\n })\n const poolsMap = getPoolsMap(pools)\n\n // Read the on-chain reserve indices for every market referenced by the\n // tasks in the SAME PTB as get_user_state. This guarantees that\n // supply_balance / borrow_balance and supply_index / borrow_index are\n // captured from the exact same chain snapshot. Without this, indices come\n // from the cached open-api /api/navi/pools response (typically lagging the\n // chain by seconds to minutes), so right after a deposit/withdraw the\n // displayed amount can drift by the interest accrued in between.\n const uniqueMarketKeys = Array.from(new Set(tasks.map((task) => task.market)))\n const uniqueMarkets = uniqueMarketKeys.map((key) => getMarketConfig(key))\n\n for (const market of uniqueMarkets) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME,\n market: market.key\n })\n tx.moveCall({\n target: `${config.uiGetter}::getter::get_reserve_data`,\n arguments: [tx.object(config.storage)]\n })\n }\n\n for (let task of tasks) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME,\n market: task.market\n })\n tx.moveCall({\n target: `${config.uiGetter}::getter_unchecked::get_user_state`,\n arguments: [tx.object(config.storage), tx.pure.address(task.address)]\n })\n }\n\n const resp = await devInspectTransaction(client, {\n transactionBlock: tx,\n sender: address\n })\n\n const results = resp.results || []\n\n const reserveIndicesByMarket: Record<\n string,\n Record<number, { supplyIndex: string; borrowIndex: string }>\n > = {}\n uniqueMarkets.forEach((market, idx) => {\n try {\n const reserves =\n results[idx]?.returnValues?.map((item: any) => {\n return bcs.vector(ReserveDataInfo as any).parse(Uint8Array.from(item[0]))\n })[0] || []\n const perAsset: Record<number, { supplyIndex: string; borrowIndex: string }> = {}\n for (const reserve of reserves as Array<{\n id: number\n supply_index: string\n borrow_index: string\n }>) {\n perAsset[reserve.id] = {\n supplyIndex: reserve.supply_index,\n borrowIndex: reserve.borrow_index\n }\n }\n reserveIndicesByMarket[market.key] = perAsset\n } catch (e) {\n // BCS decode failed (e.g. on-chain ReserveDataInfo layout changed and\n // our schema is out of date). Leave the entry empty so the per-asset\n // `?? pool.currentSupplyIndex` fallback below kicks in for this\n // market only, preserving the original 1.4.4 behaviour for the\n // affected market instead of turning a recoverable mismatch into a\n // hard failure that wipes out every position for the user.\n console.warn(\n `[@naviprotocol/lending] Failed to decode reserve data for market \"${market.key}\", falling back to open-api pool indices`,\n e\n )\n }\n })\n\n const stateList = results.slice(uniqueMarkets.length).map((result: any) => {\n return (\n result.returnValues?.map((item: any) => {\n return bcs.vector(UserStateInfo as any).parse(Uint8Array.from(item[0]))\n })[0] || []\n )\n }) as {\n supply_balance: string\n borrow_balance: string\n asset_id: number\n }[][]\n\n const result = [] as UserLendingInfo[]\n\n stateList.forEach((states, index) => {\n const task = tasks[index]\n const market = getMarketConfig(task.market)\n const marketReserves = reserveIndicesByMarket[market.key] || {}\n states.forEach((state) => {\n if (state.supply_balance === '0' && state.borrow_balance === '0') {\n if (task.emodeId === undefined) {\n return\n }\n if (!options?.includeZeroBalanceEmodePositions) {\n return\n }\n }\n const pool = poolsMap[`${market.key}-${state.asset_id}`]\n if (!pool) {\n return\n }\n // Prefer on-chain indices captured in the same PTB; fall back to the\n // open-api pool indices only when reserve data could not be decoded\n // for this asset (keeps behaviour backward compatible if the chain\n // ever stops exposing getter::get_reserve_data).\n const reserveIndices = marketReserves[state.asset_id]\n const supplyIndex = reserveIndices?.supplyIndex ?? pool!.currentSupplyIndex\n const borrowIndex = reserveIndices?.borrowIndex ?? pool!.currentBorrowIndex\n const supplyBalance = rayMathMulIndex(state.supply_balance, supplyIndex).toString()\n const borrowBalance = rayMathMulIndex(state.borrow_balance, borrowIndex).toString()\n result.push({\n supplyBalance,\n borrowBalance,\n assetId: state.asset_id,\n market: market.key,\n pool,\n emodeId: task.emodeId\n })\n })\n })\n\n return result\n}\n\n/**\n * Retrieves the current lending state for a user\n *\n * This function fetches all active lending positions for a user, including\n * supply and borrow balances for different assets.\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client, environment, and caching\n * @returns Promise<UserLendingInfo[]> - Array of user lending positions\n */\nexport const getLendingState = withCache(\n async (\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption & CacheOption & MarketsOption>\n ): Promise<UserLendingInfo[]> => {\n const markets = (options?.markets || Object.keys(MARKETS)).map((item) => {\n return getMarketConfig(item)\n })\n\n const tasks = markets.map((market) => {\n return {\n address,\n market: market.key\n }\n })\n\n return await getLendingStateBatch(address, tasks, options)\n }\n)\n\n/**\n * Calculates the current health factor for a user\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client and environment\n * @returns Promise<number> - Health factor value\n */\nexport async function getHealthFactor(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n await getHealthFactorPTB(tx, address, options)\n const result = await devInspectTransaction(client, {\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Calculates the health factor after performing lending operations\n *\n * This function simulates the health factor that would result after\n * performing a series of supply, withdraw, borrow, or repay operations.\n *\n * @param address - User wallet address or account cap\n * @param identifier - Asset identifier\n * @param operations - Array of operations to simulate\n * @param options - Options for client and environment\n * @returns Promise<number> - Projected health factor\n */\nexport async function getSimulatedHealthFactor(\n address: string | AccountCap,\n identifier: AssetIdentifier,\n operations: {\n type: PoolOperator\n amount: number\n }[],\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n let estimatedSupply = 0\n let estimatedBorrow = 0\n const pool = await getPool(identifier, options)\n\n // Calculate estimated changes from operations\n operations.forEach((operation) => {\n if (operation.type === PoolOperator.Supply) {\n estimatedSupply += operation.amount\n } else if (operation.type === PoolOperator.Withdraw) {\n estimatedSupply -= operation.amount\n } else if (operation.type === PoolOperator.Borrow) {\n estimatedBorrow += operation.amount\n } else if (operation.type === PoolOperator.Repay) {\n estimatedBorrow -= operation.amount\n }\n })\n\n // Validate operation consistency\n if (estimatedSupply * estimatedBorrow < 0) {\n throw new Error('Invalid operations')\n }\n\n // Determine if this is an increase operation\n const isIncrease = estimatedSupply > 0 || estimatedBorrow > 0\n\n // Calculate the dynamic health factor\n await getSimulatedHealthFactorPTB(\n tx,\n address,\n pool,\n Math.abs(estimatedSupply),\n Math.abs(estimatedBorrow),\n isIncrease,\n options\n )\n\n // Execute dry run to get the result\n const result = await devInspectTransaction(client, {\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Retrieves transaction history for a user from the Navi protocol API\n *\n * This function fetches the transaction history for a specific user address\n * from the Navi protocol's open API. It supports pagination through cursor-based navigation.\n *\n * @param address - User wallet address or account cap\n * @param options - Optional parameters including cursor for pagination\n * @returns Promise with transaction data and optional cursor for next page\n */\nexport const getTransactions = withSingleton(\n async (\n address: string | AccountCap,\n options?: {\n cursor?: string\n } & ServiceOption\n ): Promise<{\n data: NAVITransaction[]\n cursor?: string\n }> => {\n // Build query parameters for the API request\n const params = new URLSearchParams()\n if (options?.cursor) {\n params.set('cursor', options.cursor)\n }\n params.set('userAddress', address)\n\n // Fetch transaction history from Navi protocol API\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const url = buildNaviOpenApiUrl(\n `/navi/user/transactions?${params.toString()}&sdk=${packageJson.version}`,\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 * Retrieves all coins owned by a user address\n *\n * This function fetches all coin objects owned by a specific address from the Sui blockchain.\n * It supports filtering by coin type and handles pagination automatically to retrieve all coins.\n *\n * @param address - User wallet address\n * @param options - Optional parameters including coin type filter and client options\n * - `coinType` - If specified, retrieves only coins of this type\n * - `client` - If provided, uses this `SuiClient` instance instead of the default client\n * @returns Promise<CoinStruct[]> - Array of coin objects owned by the address\n */\nexport async function getCoins(\n address: string,\n options?: Partial<\n {\n coinType?: string\n } & SuiClientOption\n >\n): Promise<CoinStruct[]> {\n let cursor: string | undefined | null = null\n const allCoinDatas: CoinStruct[] = []\n const client = options?.client ?? suiClient\n const core = client.core as\n | {\n listBalances?(options: any): Promise<any>\n listCoins?(options: any): Promise<any>\n }\n | undefined\n\n // Fetch all coins using pagination\n do {\n let res: PaginatedCoins\n\n // Use specific coin type filter if provided, otherwise get all coins\n if (options?.coinType) {\n if (typeof core?.listCoins === 'function') {\n const response = await core.listCoins({\n owner: address,\n coinType: options?.coinType,\n cursor,\n limit: 100\n })\n res = {\n data: (response.objects ?? response.data ?? [])\n .map((coin: any) => normalizeCoreCoin(coin, options?.coinType))\n .filter(Boolean) as CoinStruct[],\n nextCursor: response.cursor ?? response.nextCursor ?? null,\n hasNextPage: response.hasNextPage ?? false\n } as PaginatedCoins\n } else {\n if (typeof client.getCoins !== 'function') {\n throw new Error('getCoins requires core.listCoins or an explicit legacy getCoins client')\n }\n res = await client.getCoins({\n owner: address,\n coinType: options?.coinType,\n cursor,\n limit: 100\n })\n }\n } else if (typeof core?.listBalances === 'function' && typeof core?.listCoins === 'function') {\n const coinTypes = new Set<string>()\n let balanceCursor: string | null | undefined = null\n do {\n const response = await core.listBalances({\n owner: address,\n cursor: balanceCursor,\n limit: 100\n })\n for (const balance of response.balances ?? []) {\n if (balance?.coinType) {\n coinTypes.add(balance.coinType)\n }\n }\n balanceCursor = response.cursor ?? response.nextCursor ?? null\n } while (balanceCursor)\n\n for (const coinType of coinTypes) {\n let coinCursor: string | null | undefined = null\n do {\n const response = await core.listCoins({\n owner: address,\n coinType,\n cursor: coinCursor,\n limit: 100\n })\n allCoinDatas.push(\n ...((response.objects ?? response.data ?? [])\n .map((coin: any) => normalizeCoreCoin(coin, coinType))\n .filter(Boolean) as CoinStruct[])\n )\n coinCursor = response.cursor ?? response.nextCursor ?? null\n } while (coinCursor)\n }\n break\n } else {\n if (typeof client.getAllCoins !== 'function') {\n throw new Error(\n 'getCoins requires core.listBalances/core.listCoins or an explicit legacy getAllCoins client'\n )\n }\n res = await client.getAllCoins({\n owner: address,\n cursor,\n limit: 100\n })\n }\n\n // Break if no more data\n if (!res.data || !res.data.length) {\n break\n }\n\n // Collect coin data and continue with next page\n allCoinDatas.push(...res.data)\n cursor = res.nextCursor\n } while (cursor)\n\n return allCoinDatas\n}\n\nexport const getLendingPositions = withCache(\n async (\n address: string,\n options?: Partial<\n SuiClientOption &\n EnvOption &\n CacheOption &\n MarketsOption & {\n includeZeroBalanceEmodePositions?: boolean\n }\n >\n ): Promise<LendingPosition[]> => {\n const positions: LendingPosition[] = []\n const markets = (options?.markets || Object.keys(MARKETS)).map((item) => {\n return getMarketConfig(item)\n })\n\n // Do not silently swallow E-Mode cap failures: the previous catch fell back\n // to an empty array, silently dropping the user's E-Mode positions (and\n // masking real endpoint/RPC errors). Throw so callers are aware\n // instead of returning incomplete positions.\n const emodeCaps: EModeCap[] = await getUserEModeCaps(address, options)\n\n const tasks = markets\n .map((market) => {\n return {\n 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((emodeCap) => {\n return {\n address: emodeCap.accountCap,\n market: getMarketConfig(emodeCap.marketId).key,\n emodeId: emodeCap.emodeId\n }\n })\n )\n\n const lendingStates = await getLendingStateBatch(address, tasks, options)\n\n lendingStates.forEach((lendingState) => {\n const emodeCap =\n typeof lendingState.emodeId === 'number'\n ? emodeCaps.find((cap) => {\n const market = getMarketConfig(lendingState.market)\n return cap.emodeId === lendingState.emodeId && cap.marketId === market.id\n })\n : undefined\n if (emodeCap) {\n const inEmode = lendingState.pool.emodes.find((emode) => emode.emodeId === emodeCap.emodeId)\n if (!inEmode) {\n return\n }\n if (BigNumber(lendingState.supplyBalance).gte(0)) {\n const supplyAmount = BigNumber(lendingState.supplyBalance)\n .shiftedBy(-9)\n .decimalPlaces(lendingState.pool.token.decimals, BigNumber.ROUND_DOWN)\n\n const emodePool = poolToEModePool(lendingState.pool, emodeCap)\n\n if (supplyAmount.gt(0) || emodePool.emode.isCollateral) {\n try {\n positions.push({\n id: `${lendingState.pool.uniqueId}_${emodeCap.emodeId}_navi-lending-emode-supply-${uuid()}`,\n wallet: address,\n protocol: 'navi',\n market: lendingState.market,\n type: 'navi-lending-emode-supply',\n 'navi-lending-emode-supply': {\n amount: supplyAmount.toString(),\n pool: poolToEModePool(lendingState.pool, emodeCap),\n token: lendingState.pool.token,\n valueUSD: supplyAmount.multipliedBy(lendingState.pool.oracle.price).toString(),\n emodeCap: emodeCap\n }\n })\n } catch (e) {\n console.error(e)\n }\n }\n }\n if (BigNumber(lendingState.borrowBalance).gte(0)) {\n const borrowAmount = BigNumber(lendingState.borrowBalance)\n .shiftedBy(-9)\n .decimalPlaces(lendingState.pool.token.decimals, BigNumber.ROUND_DOWN)\n\n const emodePool = poolToEModePool(lendingState.pool, emodeCap)\n\n if (borrowAmount.gt(0) || emodePool.emode.isDebt) {\n try {\n positions.push({\n id: `${lendingState.pool.uniqueId}_${emodeCap.emodeId}_navi-lending-emode-borrow-${uuid()}`,\n wallet: address,\n protocol: 'navi',\n market: lendingState.market,\n type: 'navi-lending-emode-borrow',\n 'navi-lending-emode-borrow': {\n amount: borrowAmount.toString(),\n pool: poolToEModePool(lendingState.pool, emodeCap),\n token: lendingState.pool.token,\n valueUSD: borrowAmount.multipliedBy(lendingState.pool.oracle.price).toString(),\n emodeCap: emodeCap\n }\n })\n } catch (e) {\n console.error(e)\n }\n }\n }\n } else {\n if (BigNumber(lendingState.supplyBalance).gt(0)) {\n const supplyAmount = BigNumber(lendingState.supplyBalance)\n .shiftedBy(-9)\n .decimalPlaces(lendingState.pool.token.decimals, BigNumber.ROUND_DOWN)\n positions.push({\n id: `${lendingState.pool.uniqueId}_navi-lending-supply-${uuid()}`,\n wallet: address,\n protocol: 'navi',\n type: 'navi-lending-supply',\n market: lendingState.market,\n 'navi-lending-supply': {\n amount: supplyAmount.toString(),\n pool: lendingState.pool,\n token: lendingState.pool.token,\n valueUSD: supplyAmount.multipliedBy(lendingState.pool.oracle.price).toString()\n }\n })\n }\n if (BigNumber(lendingState.borrowBalance).gt(0)) {\n const borrowAmount = BigNumber(lendingState.borrowBalance)\n .shiftedBy(-9)\n .decimalPlaces(lendingState.pool.token.decimals, BigNumber.ROUND_DOWN)\n positions.push({\n id: `${lendingState.pool.uniqueId}_navi-lending-borrow-${uuid()}`,\n wallet: address,\n protocol: 'navi',\n market: lendingState.market,\n type: 'navi-lending-borrow',\n 'navi-lending-borrow': {\n amount: borrowAmount.toString(),\n pool: lendingState.pool,\n token: lendingState.pool.token,\n valueUSD: borrowAmount.multipliedBy(lendingState.pool.oracle.price).toString()\n }\n })\n }\n }\n })\n return positions\n }\n)\n\nexport type TokenPriceMap = Record<string, number>\n\nexport class UserPositions {\n private _positions: LendingPosition[] = []\n private _priceMap: TokenPriceMap = {}\n private _overview = {\n hf: Infinity,\n netVaule: '0',\n netWorthApr: '0',\n totalSupplyValue: '0',\n totalBorrowValue: '0',\n totalsupplyApy: '0',\n totalBorrowApy: '0',\n maxLiquidationValue: '0',\n maxLoanToVaule: '0',\n supply: {} as Record<string, string>,\n borrow: {} as Record<string, string>\n }\n\n get positions() {\n return this._positions\n }\n\n get overview() {\n return this._overview\n }\n\n get priceMap() {\n return this._priceMap\n }\n\n set positions(positions: LendingPosition[]) {\n this._positions = positions\n this._overview = this.getPositionsOverview(positions)\n }\n\n constructor(positions: LendingPosition[], priceMap?: TokenPriceMap) {\n this._priceMap = priceMap || {}\n this.positions = positions\n }\n\n public updatePriceMap(priceMap: TokenPriceMap) {\n this._priceMap = priceMap\n this._overview = this.getPositionsOverview(this._positions)\n return this\n }\n\n private getPrice(pool: Pool | EModePool): string {\n const coinType = normalizeCoinType(pool.suiCoinType)\n if (this._priceMap[coinType] !== undefined) {\n return this._priceMap[coinType].toString()\n }\n const rawType = pool.suiCoinType\n if (this._priceMap[rawType] !== undefined) {\n return this._priceMap[rawType].toString()\n }\n return pool.oracle.price\n }\n\n public filterPositionsByPool(pool: Pool | EModePool) {\n const isEmode = !!(pool as EModePool).isEMode\n const types = isEmode\n ? ['navi-lending-emode-supply', 'navi-lending-emode-borrow']\n : ['navi-lending-supply', 'navi-lending-borrow']\n return new UserPositions(\n this.positions.filter((position) => {\n const positionData = position[position.type]!\n return types.includes(position.type) && positionData.pool.uniqueId === pool.uniqueId\n }),\n this._priceMap\n )\n }\n\n public deposit(pool: Pool | EModePool, amount: number) {\n const isEmode = !!(pool as EModePool).isEMode\n const price = this.getPrice(pool)\n let position: LendingPosition\n if (isEmode) {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-emode-supply',\n 'navi-lending-emode-supply': {\n amount: amount.toString(),\n valueUSD: BigNumber(amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as EModePool,\n emodeCap: {} as EModeCap\n }\n }\n } else {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-supply',\n 'navi-lending-supply': {\n amount: amount.toString(),\n valueUSD: BigNumber(amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as Pool\n }\n }\n }\n return new UserPositions([...this.positions, position], this._priceMap)\n }\n\n public withdraw(pool: Pool | EModePool, amount: number) {\n const isEmode = !!(pool as EModePool).isEMode\n const price = this.getPrice(pool)\n let position: LendingPosition\n if (isEmode) {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-emode-supply',\n 'navi-lending-emode-supply': {\n amount: (-amount).toString(),\n valueUSD: BigNumber(-amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as EModePool,\n emodeCap: {} as EModeCap\n }\n }\n } else {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-supply',\n 'navi-lending-supply': {\n amount: (-amount).toString(),\n valueUSD: BigNumber(-amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as Pool\n }\n }\n }\n return new UserPositions([...this.positions, position], this._priceMap)\n }\n\n public borrow(pool: Pool | EModePool, amount: number) {\n const isEmode = !!(pool as EModePool).isEMode\n const price = this.getPrice(pool)\n let position: LendingPosition\n if (isEmode) {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-emode-borrow',\n 'navi-lending-emode-borrow': {\n amount: amount.toString(),\n valueUSD: BigNumber(amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as EModePool,\n emodeCap: {} as EModeCap\n }\n }\n } else {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-borrow',\n 'navi-lending-borrow': {\n amount: amount.toString(),\n valueUSD: BigNumber(amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as Pool\n }\n }\n }\n return new UserPositions([...this.positions, position], this._priceMap)\n }\n\n public repay(pool: Pool | EModePool, amount: number) {\n const isEmode = !!(pool as EModePool).isEMode\n const price = this.getPrice(pool)\n let position: LendingPosition\n if (isEmode) {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-emode-borrow',\n 'navi-lending-emode-borrow': {\n amount: (-amount).toString(),\n valueUSD: BigNumber(-amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as EModePool,\n emodeCap: {} as EModeCap\n }\n }\n } else {\n position = {\n id: uuid(),\n wallet: '',\n protocol: 'navi',\n market: '',\n type: 'navi-lending-borrow',\n 'navi-lending-borrow': {\n amount: (-amount).toString(),\n valueUSD: BigNumber(-amount).multipliedBy(price).toString(),\n token: pool.token,\n pool: pool as Pool\n }\n }\n }\n return new UserPositions([...this.positions, position], this._priceMap)\n }\n\n private resolveValueUSD(data: {\n amount: string\n valueUSD: string\n pool: Pool | EModePool\n }): string {\n const hasPriceMap = Object.keys(this._priceMap).length > 0\n if (!hasPriceMap) return data.valueUSD\n return BigNumber(data.amount).multipliedBy(this.getPrice(data.pool)).toString()\n }\n\n getPositionsOverview(positions: LendingPosition[]) {\n const supply = {} as Record<string, string>\n const borrow = {} as Record<string, string>\n let totalSupplyValue = new BigNumber(0)\n let totalBorrowValue = new BigNumber(0)\n let totalsupplyApy = new BigNumber(0)\n let totalBorrowApy = new BigNumber(0)\n let maxLiquidationValue = new BigNumber(0)\n let maxLoanToVaule = new BigNumber(0)\n positions.forEach((position) => {\n if (position.type === 'navi-lending-supply') {\n const data = position['navi-lending-supply']!\n const valueUSD = this.resolveValueUSD(data)\n totalSupplyValue = totalSupplyValue.plus(valueUSD)\n maxLiquidationValue = maxLiquidationValue.plus(\n new BigNumber(valueUSD).multipliedBy(data.pool.liquidationFactor.threshold)\n )\n maxLoanToVaule = maxLoanToVaule.plus(\n new BigNumber(valueUSD).multipliedBy(data.pool.ltvValue)\n )\n } else if (position.type === 'navi-lending-borrow') {\n const data = position['navi-lending-borrow']!\n totalBorrowValue = totalBorrowValue.plus(this.resolveValueUSD(data))\n } else if (position.type === 'navi-lending-emode-supply') {\n const data = position['navi-lending-emode-supply']!\n const valueUSD = this.resolveValueUSD(data)\n totalSupplyValue = totalSupplyValue.plus(valueUSD)\n const poolEmodeConfig = data.pool.emode\n maxLiquidationValue = maxLiquidationValue.plus(\n new BigNumber(valueUSD).multipliedBy(poolEmodeConfig.lt)\n )\n maxLoanToVaule = maxLoanToVaule.plus(\n new BigNumber(valueUSD).multipliedBy(poolEmodeConfig.ltv)\n )\n } else if (position.type === 'navi-lending-emode-borrow') {\n const data = position['navi-lending-emode-borrow']!\n totalBorrowValue = totalBorrowValue.plus(this.resolveValueUSD(data))\n }\n })\n\n totalBorrowValue = BigNumber.max(totalBorrowValue, 0)\n totalSupplyValue = BigNumber.max(totalSupplyValue, 0)\n maxLiquidationValue = BigNumber.max(maxLiquidationValue, 0)\n maxLoanToVaule = BigNumber.max(maxLoanToVaule, 0)\n\n positions.forEach((position) => {\n if (position.type === 'navi-lending-supply') {\n const data = position['navi-lending-supply']!\n const valueUSD = this.resolveValueUSD(data)\n const apy = data.pool.supplyIncentiveApyInfo.apy\n if (totalSupplyValue.gt(0)) {\n totalsupplyApy = totalsupplyApy.plus(\n new BigNumber(valueUSD)\n .dividedBy(totalSupplyValue)\n .multipliedBy(new BigNumber(apy).dividedBy(100))\n )\n }\n supply[data.pool.suiCoinType] = BigNumber(supply[data.pool.suiCoinType] || 0)\n .plus(data.amount)\n .toString()\n } else if (position.type === 'navi-lending-borrow') {\n const data = position['navi-lending-borrow']!\n const valueUSD = this.resolveValueUSD(data)\n const apy = data.pool.borrowIncentiveApyInfo.apy\n if (totalBorrowValue.gt(0)) {\n totalBorrowApy = totalBorrowApy.plus(\n new BigNumber(valueUSD)\n .dividedBy(totalBorrowValue)\n .multipliedBy(new BigNumber(apy).dividedBy(100))\n )\n }\n borrow[data.pool.suiCoinType] = BigNumber(borrow[data.pool.suiCoinType] || 0)\n .plus(data.amount)\n .toString()\n } else if (position.type === 'navi-lending-emode-supply') {\n const data = position['navi-lending-emode-supply']!\n const valueUSD = this.resolveValueUSD(data)\n const apy = data.pool.supplyIncentiveApyInfo.apy\n if (totalSupplyValue.gt(0)) {\n totalsupplyApy = totalsupplyApy.plus(\n new BigNumber(valueUSD)\n .dividedBy(totalSupplyValue)\n .multipliedBy(new BigNumber(apy).dividedBy(100))\n )\n }\n supply[data.pool.suiCoinType] = BigNumber(supply[data.pool.suiCoinType] || 0)\n .plus(data.amount)\n .toString()\n } else if (position.type === 'navi-lending-emode-borrow') {\n const data = position['navi-lending-emode-borrow']!\n const valueUSD = this.resolveValueUSD(data)\n const apy = data.pool.borrowIncentiveApyInfo.apy\n if (totalBorrowValue.gt(0)) {\n totalBorrowApy = totalBorrowApy.plus(\n new BigNumber(valueUSD)\n .dividedBy(totalBorrowValue)\n .multipliedBy(new BigNumber(apy).dividedBy(100))\n )\n }\n borrow[data.pool.suiCoinType] = BigNumber(borrow[data.pool.suiCoinType] || 0)\n .plus(data.amount)\n .toString()\n }\n })\n\n const netVaule = totalSupplyValue.minus(totalBorrowValue)\n const netWorthApr = totalSupplyValue.minus(totalBorrowValue).eq(0)\n ? new BigNumber(0)\n : totalSupplyValue\n .multipliedBy(totalsupplyApy)\n .minus(totalBorrowValue.multipliedBy(totalBorrowApy))\n .div(totalSupplyValue.minus(totalBorrowValue))\n const hf =\n totalBorrowValue.toNumber() !== 0\n ? maxLiquidationValue.dividedBy(totalBorrowValue).toNumber()\n : Infinity\n\n return {\n hf,\n netVaule: netVaule.toString(),\n netWorthApr: netWorthApr.toString(),\n totalSupplyValue: totalSupplyValue.toString(),\n totalBorrowValue: totalBorrowValue.toString(),\n totalsupplyApy: totalsupplyApy.toString(),\n totalBorrowApy: totalBorrowApy.toString(),\n maxLiquidationValue: maxLiquidationValue.toString(),\n maxLoanToVaule: maxLoanToVaule.toString(),\n supply,\n borrow\n }\n }\n}\n\nexport async function verifyHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n hf: number,\n options?: Partial<EnvOption & MarketOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n if (config.limter) {\n tx.moveCall({\n target: `${config.limter}::navi_adaptor::verify_navi_position_healthy`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(config.priceOracle),\n parseTxValue(address, tx.pure.address),\n tx.pure.u256(new BigNumber(hf).shiftedBy(27).toNumber())\n ]\n })\n }\n}\n"],"names":["getCoreCoinType","coin","fallbackCoinType","normalizeCoreCoin","coinType","coinObjectId","normalizeCoinType","mergeCoinsPTB","tx","coins","options","needSplit","splitBalance","addressBalance","mergedBalance","mergeList","objectsBalance","a","b","redeemCoinType","isSuiGas","type","need","canUseAddressBalance","usableAddressBalance","combined","shortfall","canRedeem","redeemedCoin","baseCoin","restCoins","id","getSimulatedHealthFactorPTB","address","identifier","estimatedSupply","estimatedBorrow","isIncrease","config","getConfig","DEFAULT_CACHE_TIME","pool","getPool","parseTxPoolValue","parseTxValue","getHealthFactorPTB","getLendingStateBatch","tasks","Transaction","client","suiClient","pools","getPools","MARKETS","poolsMap","getPoolsMap","uniqueMarkets","task","key","getMarketConfig","market","results","devInspectTransaction","reserveIndicesByMarket","idx","reserves","item","bcs","ReserveDataInfo","perAsset","reserve","e","stateList","result","UserStateInfo","states","index","marketReserves","state","reserveIndices","supplyIndex","borrowIndex","supplyBalance","rayMathMulIndex","borrowBalance","getLendingState","withCache","getHealthFactor","res","parseDevInspectResult","processContractHealthFactor","getSimulatedHealthFactor","operations","operation","PoolOperator","getTransactions","withSingleton","params","endpoint","resolveNaviOpenApiEndpoint","url","buildNaviOpenApiUrl","packageJson","mergeServiceHeaders","requestHeaders","getCoins","cursor","allCoinDatas","core","response","coinTypes","balanceCursor","balance","coinCursor","getLendingPositions","positions","markets","emodeCaps","getUserEModeCaps","cap","emodeCap","lendingState","emode","BigNumber","supplyAmount","emodePool","poolToEModePool","uuid","borrowAmount","UserPositions","priceMap","rawType","types","position","positionData","amount","isEmode","price","data","supply","borrow","totalSupplyValue","totalBorrowValue","totalsupplyApy","totalBorrowApy","maxLiquidationValue","maxLoanToVaule","valueUSD","poolEmodeConfig","apy","netVaule","netWorthApr","verifyHealthFactorPTB","hf"],"mappings":";;;;;;;;;;;AAuDA,SAASA,GAAgBC,GAAWC,GAA2B;AAC7D,SAAID,EAAK,WAAiBA,EAAK,WAC3BC,MAEU,OAAOD,EAAK,QAAS,WAAWA,EAAK,KAAK,MAAM,qBAAqB,IAAI,QACxE,CAAC;AAClB;AAEA,SAASE,EAAkBF,GAAWC,GAA8C;AAClF,QAAME,IAAWJ,GAAgBC,GAAMC,CAAgB,GACjDG,IAAeJ,EAAK,gBAAgBA,EAAK;AAC/C,SAAI,CAACG,KAAY,CAACC,KAAgBJ,EAAK,YAAY,UAAaA,EAAK,YAAY,OACxE,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O,OAAO;AAAA,MACxB9B,EAAG,OAAO8B,EAAO,WAAW;AAAA,MAC5BM,EAAaX,GAASzB,EAAG,KAAK,OAAO;AAAA,MACrCA,EAAG,KAAK,KAAK,IAAImH,EAAU8B,CAAE,EAAE,UAAU,EAAE,EAAE,SAAA,CAAU;AAAA,IAAA;AAAA,EACzD,CACD;AAEL;"}
package/dist/bcs.js DELETED
@@ -1,137 +0,0 @@
1
- import { bcs as t } from "@mysten/sui/bcs";
2
- import { toHex as e, fromHex as s } from "@mysten/sui/utils";
3
- const u = t.bytes(32).transform({
4
- // To change the input type, you need to provide a type definition for the input
5
- input: (o) => s(o),
6
- output: (o) => e(o)
7
- }), i = t.struct("IncentiveAPYInfo", {
8
- /** Asset identifier */
9
- asset_id: t.u8(),
10
- /** Annual Percentage Yield as a 256-bit integer */
11
- apy: t.u256(),
12
- /** List of supported coin types for this incentive */
13
- coin_types: t.vector(t.string())
14
- }), a = t.struct("IncentivePoolInfo", {
15
- /** Unique pool identifier */
16
- pool_id: u,
17
- /** Address holding the incentive funds */
18
- funds: u,
19
- /** Current phase of the incentive program */
20
- phase: t.u64(),
21
- /** Timestamp when the incentive started */
22
- start_at: t.u64(),
23
- /** Timestamp when the incentive ends */
24
- end_at: t.u64(),
25
- /** Timestamp when the incentive was closed */
26
- closed_at: t.u64(),
27
- /** Total supply of incentive tokens */
28
- total_supply: t.u64(),
29
- /** Asset identifier for the incentive */
30
- asset_id: t.u8(),
31
- /** Option type for the incentive */
32
- option: t.u8(),
33
- /** Factor used in incentive calculations */
34
- factor: t.u256(),
35
- /** Amount of incentives already distributed */
36
- distributed: t.u64(),
37
- /** Amount of incentives currently available */
38
- available: t.u256(),
39
- /** Total amount of incentives */
40
- total: t.u256()
41
- }), l = t.struct("IncentivePoolInfoByPhase", {
42
- /** Phase number */
43
- phase: t.u64(),
44
- /** List of incentive pools in this phase */
45
- pools: t.vector(a)
46
- }), c = t.struct("OracleInfo", {
47
- /** Oracle identifier */
48
- oracle_id: t.u8(),
49
- /** Current price as a 256-bit integer */
50
- price: t.u256(),
51
- /** Number of decimal places for the price */
52
- decimals: t.u8(),
53
- /** Whether the oracle data is valid */
54
- valid: t.bool()
55
- }), _ = t.struct("FlashLoanAssetConfig", {
56
- /** Unique identifier for the flash loan asset */
57
- id: t.string(),
58
- /** Asset identifier */
59
- asset_id: t.u8(),
60
- /** Coin type for the asset */
61
- coin_type: t.string(),
62
- /** Pool identifier for the flash loan */
63
- pool_id: t.string(),
64
- /** Rate paid to suppliers for flash loans */
65
- rate_to_supplier: t.u64(),
66
- /** Rate paid to treasury for flash loans */
67
- rate_to_treasury: t.u64(),
68
- /** Maximum flash loan amount */
69
- max: t.u64(),
70
- /** Minimum flash loan amount */
71
- min: t.u64()
72
- }), p = t.struct("ReserveDataInfo", {
73
- /** Reserve identifier */
74
- id: t.u8(),
75
- /** Oracle identifier for price feeds */
76
- oracle_id: t.u8(),
77
- /** Coin type for the reserve */
78
- coin_type: t.string(),
79
- /** Maximum supply capacity */
80
- supply_cap: t.u256(),
81
- /** Maximum borrow capacity */
82
- borrow_cap: t.u256(),
83
- /** Current supply interest rate */
84
- supply_rate: t.u256(),
85
- /** Current borrow interest rate */
86
- borrow_rate: t.u256(),
87
- /** Current supply index for interest calculation */
88
- supply_index: t.u256(),
89
- /** Current borrow index for interest calculation */
90
- borrow_index: t.u256(),
91
- /** Total amount supplied to the reserve */
92
- total_supply: t.u256(),
93
- /** Total amount borrowed from the reserve */
94
- total_borrow: t.u256(),
95
- /** Timestamp of last update */
96
- last_update_at: t.u64(),
97
- /** Loan-to-Value ratio for collateral */
98
- ltv: t.u256(),
99
- /** Treasury factor for fee calculations */
100
- treasury_factor: t.u256(),
101
- /** Current treasury balance */
102
- treasury_balance: t.u256(),
103
- /** Base interest rate */
104
- base_rate: t.u256(),
105
- /** Interest rate multiplier */
106
- multiplier: t.u256(),
107
- /** Jump rate multiplier for high utilization */
108
- jump_rate_multiplier: t.u256(),
109
- /** Reserve factor for protocol fees */
110
- reserve_factor: t.u256(),
111
- /** Optimal utilization rate */
112
- optimal_utilization: t.u256(),
113
- /** Liquidation ratio threshold */
114
- liquidation_ratio: t.u256(),
115
- /** Liquidation bonus for liquidators */
116
- liquidation_bonus: t.u256(),
117
- /** Liquidation threshold */
118
- liquidation_threshold: t.u256()
119
- }), d = t.struct("UserStateInfo", {
120
- /** Asset identifier */
121
- asset_id: t.u8(),
122
- /** User's current borrow balance */
123
- borrow_balance: t.u256(),
124
- /** User's current supply balance */
125
- supply_balance: t.u256()
126
- });
127
- export {
128
- u as Address,
129
- _ as FlashLoanAssetConfig,
130
- i as IncentiveAPYInfo,
131
- a as IncentivePoolInfo,
132
- l as IncentivePoolInfoByPhase,
133
- c as OracleInfo,
134
- p as ReserveDataInfo,
135
- d as UserStateInfo
136
- };
137
- //# sourceMappingURL=bcs.js.map
package/dist/bcs.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"bcs.js","sources":["../src/bcs.ts"],"sourcesContent":["/**\n * BCS (Binary Canonical Serialization) Schemas for Lending Protocol\n *\n * This module defines the BCS schemas for serializing and deserializing\n * lending protocol data structures. BCS is used for efficient binary\n * encoding of complex data types for blockchain transactions and storage.\n */\n\nimport { bcs } from '@mysten/sui/bcs'\nimport { fromHex, toHex } from '@mysten/sui/utils'\n\n/**\n * BCS schema for Sui addresses with hex transformation\n * Converts between hex string representation and byte arrays\n */\nexport const Address = bcs.bytes(32).transform({\n // To change the input type, you need to provide a type definition for the input\n input: (val: string) => fromHex(val),\n output: (val) => toHex(val)\n})\n\n/**\n * BCS schema for incentive APY information\n * Contains asset ID, APY value, and supported coin types\n */\nexport const IncentiveAPYInfo = bcs.struct('IncentiveAPYInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Annual Percentage Yield as a 256-bit integer */\n apy: bcs.u256(),\n /** List of supported coin types for this incentive */\n coin_types: bcs.vector(bcs.string())\n})\n\n/**\n * BCS schema for incentive pool information\n * Contains comprehensive details about a lending incentive pool\n */\nexport const IncentivePoolInfo = bcs.struct('IncentivePoolInfo', {\n /** Unique pool identifier */\n pool_id: Address,\n /** Address holding the incentive funds */\n funds: Address,\n /** Current phase of the incentive program */\n phase: bcs.u64(),\n /** Timestamp when the incentive started */\n start_at: bcs.u64(),\n /** Timestamp when the incentive ends */\n end_at: bcs.u64(),\n /** Timestamp when the incentive was closed */\n closed_at: bcs.u64(),\n /** Total supply of incentive tokens */\n total_supply: bcs.u64(),\n /** Asset identifier for the incentive */\n asset_id: bcs.u8(),\n /** Option type for the incentive */\n option: bcs.u8(),\n /** Factor used in incentive calculations */\n factor: bcs.u256(),\n /** Amount of incentives already distributed */\n distributed: bcs.u64(),\n /** Amount of incentives currently available */\n available: bcs.u256(),\n /** Total amount of incentives */\n total: bcs.u256()\n})\n\n/**\n * BCS schema for incentive pool information grouped by phase\n * Contains phase number and list of pools in that phase\n */\nexport const IncentivePoolInfoByPhase = bcs.struct('IncentivePoolInfoByPhase', {\n /** Phase number */\n phase: bcs.u64(),\n /** List of incentive pools in this phase */\n pools: bcs.vector(IncentivePoolInfo)\n})\n\n/**\n * BCS schema for oracle price information\n * Contains price data from external price feeds\n */\nexport const OracleInfo = bcs.struct('OracleInfo', {\n /** Oracle identifier */\n oracle_id: bcs.u8(),\n /** Current price as a 256-bit integer */\n price: bcs.u256(),\n /** Number of decimal places for the price */\n decimals: bcs.u8(),\n /** Whether the oracle data is valid */\n valid: bcs.bool()\n})\n\n/**\n * BCS schema for flash loan asset configuration\n * Contains parameters for flash loan functionality\n */\nexport const FlashLoanAssetConfig = bcs.struct('FlashLoanAssetConfig', {\n /** Unique identifier for the flash loan asset */\n id: bcs.string(),\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Coin type for the asset */\n coin_type: bcs.string(),\n /** Pool identifier for the flash loan */\n pool_id: bcs.string(),\n /** Rate paid to suppliers for flash loans */\n rate_to_supplier: bcs.u64(),\n /** Rate paid to treasury for flash loans */\n rate_to_treasury: bcs.u64(),\n /** Maximum flash loan amount */\n max: bcs.u64(),\n /** Minimum flash loan amount */\n min: bcs.u64()\n})\n\n/**\n * BCS schema for reserve data information\n * Contains comprehensive details about a lending reserve\n */\nexport const ReserveDataInfo = bcs.struct('ReserveDataInfo', {\n /** Reserve identifier */\n id: bcs.u8(),\n /** Oracle identifier for price feeds */\n oracle_id: bcs.u8(),\n /** Coin type for the reserve */\n coin_type: bcs.string(),\n /** Maximum supply capacity */\n supply_cap: bcs.u256(),\n /** Maximum borrow capacity */\n borrow_cap: bcs.u256(),\n /** Current supply interest rate */\n supply_rate: bcs.u256(),\n /** Current borrow interest rate */\n borrow_rate: bcs.u256(),\n /** Current supply index for interest calculation */\n supply_index: bcs.u256(),\n /** Current borrow index for interest calculation */\n borrow_index: bcs.u256(),\n /** Total amount supplied to the reserve */\n total_supply: bcs.u256(),\n /** Total amount borrowed from the reserve */\n total_borrow: bcs.u256(),\n /** Timestamp of last update */\n last_update_at: bcs.u64(),\n /** Loan-to-Value ratio for collateral */\n ltv: bcs.u256(),\n /** Treasury factor for fee calculations */\n treasury_factor: bcs.u256(),\n /** Current treasury balance */\n treasury_balance: bcs.u256(),\n /** Base interest rate */\n base_rate: bcs.u256(),\n /** Interest rate multiplier */\n multiplier: bcs.u256(),\n /** Jump rate multiplier for high utilization */\n jump_rate_multiplier: bcs.u256(),\n /** Reserve factor for protocol fees */\n reserve_factor: bcs.u256(),\n /** Optimal utilization rate */\n optimal_utilization: bcs.u256(),\n /** Liquidation ratio threshold */\n liquidation_ratio: bcs.u256(),\n /** Liquidation bonus for liquidators */\n liquidation_bonus: bcs.u256(),\n /** Liquidation threshold */\n liquidation_threshold: bcs.u256()\n})\n\n/**\n * BCS schema for user state information\n * Contains user's borrowing and supplying balances for an asset\n */\nexport const UserStateInfo = bcs.struct('UserStateInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** User's current borrow balance */\n borrow_balance: bcs.u256(),\n /** User's current supply balance */\n supply_balance: bcs.u256()\n})\n"],"names":["Address","bcs","val","from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AmBA,EAAI,KAAA;AAAA;AAAA,EAEvB,mBAAmBA,EAAI,KAAA;AAAA;AAAA,EAEvB,uBAAuBA,EAAI,KAAA;AAC7B,CAAC,GAMYU,IAAgBV,EAAI,OAAO,iBAAiB;AAAA;AAAA,EAEvD,UAAUA,EAAI,GAAA;AAAA;AAAA,EAEd,gBAAgBA,EAAI,KAAA;AAAA;AAAA,EAEpB,gBAAgBA,EAAI,KAAA;AACtB,CAAC;"}
package/dist/config.js DELETED
@@ -1,22 +0,0 @@
1
- import { withCache as a, withSingleton as i, requestHeaders as s } from "./utils.js";
2
- import c from "./package.json.js";
3
- import { getMarketConfig as m, DEFAULT_MARKET_IDENTITY as p } from "./market.js";
4
- import { resolveNaviOpenApiEndpoint as d, buildNaviOpenApiUrl as f, mergeServiceHeaders as g } from "./services.js";
5
- const T = a(
6
- i(
7
- async (e) => {
8
- const r = m(e?.market || p), t = d(e), n = f(
9
- `/navi/config?env=${e?.env || "prod"}&sdk=${c.version}&market=${r.key}`,
10
- e
11
- );
12
- return (await fetch(n, {
13
- headers: g(s, t)
14
- }).then((o) => o.json())).data;
15
- }
16
- )
17
- ), l = 1e3 * 60 * 5;
18
- export {
19
- l as DEFAULT_CACHE_TIME,
20
- T as getConfig
21
- };
22
- //# sourceMappingURL=config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.js","sources":["../src/config.ts"],"sourcesContent":["/**\n * Lending Configuration Management\n *\n * This module provides configuration management for the lending protocol.\n * It handles fetching configuration from the Navi protocol API and provides\n * caching mechanisms for efficient configuration retrieval.\n *\n * @module LendingConfig\n */\n\nimport type { LendingConfig, EnvOption, CacheOption, MarketOption, ServiceOption } from './types'\nimport { withCache, withSingleton, requestHeaders } from './utils'\nimport packageJson from '../package.json'\nimport { DEFAULT_MARKET_IDENTITY, getMarketConfig } from './market'\nimport { buildNaviOpenApiUrl, mergeServiceHeaders, resolveNaviOpenApiEndpoint } from './services'\n\n/**\n * Fetches lending protocol configuration from the API\n *\n * This function retrieves the current configuration for the lending protocol\n * from the Navi protocol API. It's wrapped with both caching and singleton\n * behavior to ensure efficient and consistent configuration access.\n *\n * The configuration includes:\n * - Contract addresses for all protocol components\n * - Oracle configuration and price feed information\n * - Pool and incentive contract addresses\n * - Environment-specific settings\n *\n * @param options - Optional environment and caching options\n * @returns Promise<LendingConfig> - Complete lending protocol configuration\n */\nexport const getConfig = withCache(\n withSingleton(\n async (\n options?: Partial<EnvOption & CacheOption & MarketOption & ServiceOption>\n ): Promise<LendingConfig> => {\n const market = getMarketConfig(options?.market || DEFAULT_MARKET_IDENTITY)\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const url = buildNaviOpenApiUrl(\n `/navi/config?env=${options?.env || 'prod'}&sdk=${packageJson.version}&market=${market.key}`,\n options\n )\n\n // Fetch configuration from API\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/**\n * Default cache time for configuration data\n *\n * Configuration is cached for 5 minutes to reduce API calls\n * while ensuring reasonably fresh configuration data.\n */\nexport const DEFAULT_CACHE_TIME = 1000 * 60 * 5\n"],"names":["getConfig","withCache","withSingleton","options","market","getMarketConfig","DEFAULT_MARKET_IDENTITY","endpoint","resolveNaviOpenApiEndpoint","url","buildNaviOpenApiUrl","packageJson","mergeServiceHeaders","requestHeaders","res","DEFAULT_CACHE_TIME"],"mappings":";;;;AAgCO,MAAMA,IAAYC;AAAA,EACvBC;AAAA,IACE,OACEC,MAC2B;AAC3B,YAAMC,IAASC,EAAgBF,GAAS,UAAUG,CAAuB,GACnEC,IAAWC,EAA2BL,CAAO,GAC7CM,IAAMC;AAAA,QACV,oBAAoBP,GAAS,OAAO,MAAM,QAAQQ,EAAY,OAAO,WAAWP,EAAO,GAAG;AAAA,QAC1FD;AAAA,MAAA;AAOF,cAHY,MAAM,MAAMM,GAAK;AAAA,QAC3B,SAASG,EAAoBC,GAAgBN,CAAQ;AAAA,MAAA,CACtD,EAAE,KAAK,CAACO,MAAQA,EAAI,MAAM,GAChB;AAAA,IACb;AAAA,EAAA;AAEJ,GAQaC,IAAqB,MAAO,KAAK;"}
package/dist/emode.js DELETED
@@ -1,90 +0,0 @@
1
- import { withCache as _, parseTxValue as n, withSingleton as T, suiClient as k, devInspectTransaction as w } from "./utils.js";
2
- import { getMarketConfig as d, DEFAULT_MARKET_IDENTITY as y } from "./market.js";
3
- import { getConfig as m, DEFAULT_CACHE_TIME as i } from "./config.js";
4
- import { Transaction as b } from "@mysten/sui/transactions";
5
- import { createAccountCapPTB as v, getAccountCapOwnerPTB as j } from "./account-cap.js";
6
- import { bcs as c } from "@mysten/sui/bcs";
7
- async function A(e, a, t) {
8
- const r = await m({
9
- ...t,
10
- cacheTime: i
11
- });
12
- return t?.accountCap ? e.moveCall({
13
- target: `${r.package}::lending::enter_emode_with_account_cap`,
14
- arguments: [
15
- e.object(r.storage),
16
- n(a, e.pure.u64),
17
- n(t.accountCap, e.object)
18
- ]
19
- }) : e.moveCall({
20
- target: `${r.package}::lending::enter_emode`,
21
- arguments: [e.object(r.storage), n(a, e.pure.u64)]
22
- }), e;
23
- }
24
- async function B(e, a) {
25
- const t = await m({
26
- ...a,
27
- cacheTime: i
28
- });
29
- return a?.accountCap ? e.moveCall({
30
- target: `${t.package}::lending::exit_emode_with_account_cap`,
31
- arguments: [e.object(t.storage), n(a.accountCap, e.object)]
32
- }) : e.moveCall({
33
- target: `${t.package}::lending::exit_emode`,
34
- arguments: [e.object(t.storage)]
35
- }), e;
36
- }
37
- async function U(e, a, t) {
38
- const r = await m({
39
- cacheTime: i,
40
- ...t
41
- }), o = await v(e, t);
42
- await A(e, a, {
43
- ...t,
44
- accountCap: o
45
- });
46
- const u = await d(t?.market || y), s = await j(e, o, t);
47
- return e.moveCall({
48
- target: `${r.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,
49
- arguments: [
50
- e.object(r.emode.contract.registryObject),
51
- s,
52
- n(u.id, e.pure.u64),
53
- n(a, e.pure.u64)
54
- ]
55
- }), o;
56
- }
57
- const O = _(
58
- T(
59
- async (e, a) => {
60
- const t = await m({
61
- cacheTime: i,
62
- ...a
63
- }), r = new b(), o = a?.client ?? k;
64
- r.moveCall({
65
- target: `${t.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,
66
- arguments: [r.object(t.emode.contract.registryObject), r.pure.address(e)]
67
- });
68
- const s = (await w(o, {
69
- transactionBlock: r,
70
- sender: e
71
- })).results[0].returnValues, l = c.vector(c.u64()).parse(Uint8Array.from(s[0][0])), p = c.vector(c.u64()).parse(Uint8Array.from(s[1][0])), C = c.vector(c.Address).parse(Uint8Array.from(s[2][0]));
72
- return l.map((f, g) => ({
73
- marketId: Number(f),
74
- emodeId: Number(p[g]),
75
- accountCap: C[g].toString()
76
- }));
77
- }
78
- )
79
- );
80
- function D(e) {
81
- return `${d(e.marketId).key}-${e.emodeId}`;
82
- }
83
- export {
84
- U as createEModeCapPTB,
85
- D as emodeIdentityId,
86
- A as enterEModePTB,
87
- B as exitEModePTB,
88
- O as getUserEModeCaps
89
- };
90
- //# sourceMappingURL=emode.js.map
package/dist/emode.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"emode.js","sources":["../src/emode.ts"],"sourcesContent":["import {\n CacheOption,\n EnvOption,\n EModeCap,\n AccountCapOption,\n MarketOption,\n TransactionResult,\n SuiClientOption,\n EModeIdentity\n} from './types'\nimport { withSingleton, withCache, parseTxValue, devInspectTransaction, suiClient } from './utils'\nimport { DEFAULT_MARKET_IDENTITY, getMarketConfig } from './market'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { createAccountCapPTB, getAccountCapOwnerPTB } from './account-cap'\nimport { bcs } from '@mysten/sui/bcs'\n\nexport async function enterEModePTB(\n tx: Transaction,\n emodeId: number | TransactionResult,\n options?: Partial<EnvOption & AccountCapOption & MarketOption>\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n if (!options?.accountCap) {\n tx.moveCall({\n target: `${config.package}::lending::enter_emode`,\n arguments: [tx.object(config.storage), parseTxValue(emodeId, tx.pure.u64)]\n })\n } else {\n tx.moveCall({\n target: `${config.package}::lending::enter_emode_with_account_cap`,\n arguments: [\n tx.object(config.storage),\n parseTxValue(emodeId, tx.pure.u64),\n parseTxValue(options.accountCap, tx.object)\n ]\n })\n }\n\n return tx\n}\n\nexport async function exitEModePTB(\n tx: Transaction,\n options?: Partial<EnvOption & AccountCapOption & MarketOption>\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n if (!options?.accountCap) {\n tx.moveCall({\n target: `${config.package}::lending::exit_emode`,\n arguments: [tx.object(config.storage)]\n })\n } else {\n tx.moveCall({\n target: `${config.package}::lending::exit_emode_with_account_cap`,\n arguments: [tx.object(config.storage), parseTxValue(options.accountCap, tx.object)]\n })\n }\n return tx\n}\n\nexport async function createEModeCapPTB(\n tx: Transaction,\n emodeId: number | TransactionResult,\n options?: Partial<EnvOption & MarketOption>\n) {\n const config = await getConfig({\n cacheTime: DEFAULT_CACHE_TIME,\n ...options\n })\n const accountCap = await createAccountCapPTB(tx, options)\n await enterEModePTB(tx, emodeId, {\n ...options,\n accountCap: accountCap\n })\n const market = await getMarketConfig(options?.market || DEFAULT_MARKET_IDENTITY)\n const accountCapOwner = await getAccountCapOwnerPTB(tx, accountCap, options)\n tx.moveCall({\n target: `${config.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,\n arguments: [\n tx.object(config.emode.contract.registryObject),\n accountCapOwner,\n parseTxValue(market.id, tx.pure.u64),\n parseTxValue(emodeId, tx.pure.u64)\n ]\n })\n return accountCap\n}\n\nexport const getUserEModeCaps = withCache(\n withSingleton(\n async (\n address: string,\n options?: Partial<SuiClientOption & EnvOption & CacheOption>\n ): Promise<EModeCap[]> => {\n const config = await getConfig({\n cacheTime: DEFAULT_CACHE_TIME,\n ...options\n })\n const tx = new Transaction()\n const client = options?.client ?? suiClient\n\n tx.moveCall({\n target: `${config.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,\n arguments: [tx.object(config.emode.contract.registryObject), tx.pure.address(address!)]\n })\n\n const result: any = await devInspectTransaction(client, {\n transactionBlock: tx,\n sender: address\n })\n\n const values = result.results[0].returnValues\n\n const marketIds = bcs.vector(bcs.u64()).parse(Uint8Array.from(values[0][0]))\n const emodeIds = bcs.vector(bcs.u64()).parse(Uint8Array.from(values[1][0]))\n const accountCaps = bcs.vector(bcs.Address).parse(Uint8Array.from(values[2][0]))\n\n return marketIds.map((marketId, index) => ({\n marketId: Number(marketId),\n emodeId: Number(emodeIds[index]),\n accountCap: accountCaps[index].toString()\n }))\n }\n )\n)\n\nexport function emodeIdentityId(identifier: EModeIdentity) {\n const market = getMarketConfig(identifier.marketId)\n return `${market.key}-${identifier.emodeId}`\n}\n"],"names":["enterEModePTB","tx","emodeId","options","config","getConfig","DEFAULT_CACHE_TIME","parseTxValue","exitEModePTB","createEModeCapPTB","accountCap","createAccountCapPTB","market","getMarketConfig","DEFAULT_MARKET_IDENTITY","accountCapOwner","getAccountCapOwnerPTB","getUserEModeCaps","withCache","withSingleton","address","Transaction","client","suiClient","values","devInspectTransaction","marketIds","bcs","emodeIds","accountCaps","marketId","index","emodeIdentityId","identifier"],"mappings":";;;;;;AAiBA,eAAsBA,EACpBC,GACAC,GACAC,GACsB;AACtB,QAAMC,IAAS,MAAMC,EAAU;AAAA,IAC7B,GAAGF;AAAA,IACH,WAAWG;AAAA,EAAA,CACZ;AACD,SAAKH,GAAS,aAMZF,EAAG,SAAS;AAAA,IACV,QAAQ,GAAGG,EAAO,OAAO;AAAA,IACzB,WAAW;AAAA,MACTH,EAAG,OAAOG,EAAO,OAAO;AAAA,MACxBG,EAAaL,GAASD,EAAG,KAAK,GAAG;AAAA,MACjCM,EAAaJ,EAAQ,YAAYF,EAAG,MAAM;AAAA,IAAA;AAAA,EAC5C,CACD,IAZDA,E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ED
@@ -1,94 +0,0 @@
1
- import { getConfig as m, DEFAULT_CACHE_TIME as p } from "./config.js";
2
- import { withCache as y, withSingleton as w, requestHeaders as b, normalizeCoinType as c, parseTxValue as u } from "./utils.js";
3
- import { resolveNaviOpenApiEndpoint as A, buildNaviOpenApiUrl as d, mergeServiceHeaders as C } from "./services.js";
4
- import { getPool as h } from "./pool.js";
5
- import _ from "./package.json.js";
6
- import { DEFAULT_MARKET_IDENTITY as v } from "./market.js";
7
- const f = y(
8
- w(
9
- async (e) => {
10
- const n = A(e), s = d(
11
- `/navi/flashloan?env=${e?.env || "prod"}&sdk=${_.version}&market=${e?.market || v}`,
12
- e
13
- ), a = await fetch(s, {
14
- headers: C(b, n)
15
- }).then((o) => o.json());
16
- return Object.keys(a.data).map((o) => ({
17
- ...a.data[o],
18
- coinType: o
19
- }));
20
- }
21
- )
22
- );
23
- async function F(e, n) {
24
- return (await f(n)).find((a) => typeof e == "string" ? c(a.coinType) === c(e) : typeof e == "number" ? a.assetId === e : a.assetId === e.id) || null;
25
- }
26
- async function I(e, n, s, a) {
27
- const o = await m({
28
- ...a,
29
- cacheTime: p
30
- }), t = await h(n, a);
31
- if (!(await f({
32
- ...a,
33
- cacheTime: p
34
- })).some(
35
- (r) => c(r.coinType) === c(t.suiCoinType)
36
- ))
37
- throw new Error("Pool does not support flashloan");
38
- if (o.version === 1) {
39
- const [r, l] = e.moveCall({
40
- target: `${o.package}::lending::flash_loan_with_ctx`,
41
- arguments: [
42
- e.object(o.flashloanConfig),
43
- e.object(t.contract.pool),
44
- u(s, e.pure.u64)
45
- ],
46
- typeArguments: [t.suiCoinType]
47
- });
48
- return [r, l];
49
- } else {
50
- const [r, l] = e.moveCall({
51
- target: `${o.package}::lending::flash_loan_with_ctx_v2`,
52
- arguments: [
53
- e.object(o.flashloanConfig),
54
- e.object(t.contract.pool),
55
- u(s, e.pure.u64),
56
- e.object("0x05")
57
- ],
58
- typeArguments: [t.suiCoinType]
59
- });
60
- return [r, l];
61
- }
62
- }
63
- async function P(e, n, s, a, o) {
64
- const t = await m({
65
- ...o,
66
- cacheTime: p
67
- }), i = await h(n, o);
68
- if (!(await f({
69
- ...o,
70
- cacheTime: p
71
- })).some(
72
- (T) => c(T.coinType) === c(i.suiCoinType)
73
- ))
74
- throw new Error("Pool does not support flashloan");
75
- const [l] = e.moveCall({
76
- target: `${t.package}::lending::flash_repay_with_ctx`,
77
- arguments: [
78
- e.object("0x06"),
79
- e.object(t.storage),
80
- e.object(i.contract.pool),
81
- u(s, e.object),
82
- u(a, e.object)
83
- ],
84
- typeArguments: [i.suiCoinType]
85
- });
86
- return [l];
87
- }
88
- export {
89
- I as flashloanPTB,
90
- f as getAllFlashLoanAssets,
91
- F as getFlashLoanAsset,
92
- P as repayFlashLoanPTB
93
- };
94
- //# sourceMappingURL=flashloan.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"flashloan.js","sources":["../src/flashloan.ts"],"sourcesContent":["/**\n * Flash Loan Functionality for Lending Protocol\n *\n * This module provides flash loan capabilities for the lending protocol.\n * Flash loans allow users to borrow assets without collateral for a single transaction,\n * as long as the borrowed amount is repaid within the same transaction.\n */\n\nimport type { Transaction } from '@mysten/sui/transactions'\nimport type {\n EnvOption,\n AssetIdentifier,\n CoinObject,\n CacheOption,\n FloashloanAsset,\n TransactionResult,\n MarketOption,\n ServiceOption\n} from './types'\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport { parseTxValue, normalizeCoinType, withCache, withSingleton, requestHeaders } from './utils'\nimport { buildNaviOpenApiUrl, mergeServiceHeaders, resolveNaviOpenApiEndpoint } from './services'\nimport { getPool } from './pool'\nimport packageJson from '../package.json'\nimport { DEFAULT_MARKET_IDENTITY } from './market'\n\n/**\n * Get all available flash loan assets from the API\n * Uses caching to avoid repeated API calls\n *\n * @param options - Optional environment and cache configuration\n * @returns Array of flash loan asset configurations\n */\nexport const getAllFlashLoanAssets = withCache(\n withSingleton(\n async (\n options?: Partial<EnvOption & CacheOption & MarketOption & ServiceOption>\n ): Promise<FloashloanAsset[]> => {\n const endpoint = resolveNaviOpenApiEndpoint(options)\n const url = buildNaviOpenApiUrl(\n `/navi/flashloan?env=${options?.env || 'prod'}&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 Object.keys(res.data).map((coinType) => {\n return {\n ...res.data[coinType],\n coinType\n }\n })\n }\n )\n)\n\n/**\n * Get a specific flash loan asset by identifier\n *\n * @param identifier - Asset identifier (string coin type, number asset ID, or object with id)\n * @param options - Optional environment configuration\n * @returns Flash loan asset configuration or null if not found\n */\nexport async function getFlashLoanAsset(\n identifier: AssetIdentifier,\n options?: Partial<EnvOption & ServiceOption>\n): Promise<FloashloanAsset | null> {\n const assets = await getAllFlashLoanAssets(options)\n return (\n assets.find((asset) => {\n if (typeof identifier === 'string') {\n return normalizeCoinType(asset.coinType) === normalizeCoinType(identifier)\n }\n if (typeof identifier === 'number') {\n return asset.assetId === identifier\n }\n return asset.assetId === identifier.id\n }) || null\n )\n}\n\n/**\n * Create a flash loan transaction in the PTB (Programmable Transaction Block)\n *\n * This function initiates a flash loan by borrowing the specified amount of assets.\n * The borrowed assets must be repaid within the same transaction using repayFlashLoanPTB.\n *\n * @param tx - The transaction block to add the flash loan operation to\n * @param identifier - Asset identifier to borrow\n * @param amount - Amount to borrow (number or transaction result)\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance, receipt] where receipt is needed for repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function flashloanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption & MarketOption & ServiceOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n if (config.version === 1) {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64)\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n } else {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx_v2`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n }\n}\n\n/**\n * Repay a flash loan transaction in the PTB\n *\n * This function repays the flash loan using the receipt from the original flash loan\n * and the coin object containing the repayment amount.\n *\n * @param tx - The transaction block to add the repayment operation to\n * @param identifier - Asset identifier being repaid\n * @param receipt - Receipt from the original flash loan transaction\n * @param coinObject - Coin object containing the repayment amount\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance] after repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function repayFlashLoanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n receipt: TransactionResult | string,\n coinObject: CoinObject,\n options?: Partial<EnvOption & MarketOption & ServiceOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n // v2 entry is not required to repay\n const [balance] = tx.moveCall({\n target: `${config.package}::lending::flash_repay_with_ctx`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n parseTxValue(receipt, tx.object),\n parseTxValue(coinObject, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n return [balance]\n}\n"],"names":["getAllFlashLoanAssets","withCache","withSingleton","options","endpoint","resolveNaviOpenApiEndpoint","url","buildNaviOpenApiUrl","packageJson","DEFAULT_MARKET_IDENTITY","res","mergeServiceHeaders","requestHeaders","coinType","getFlashLoanAsset","identifier","asset","normalizeCoinType","flashloanPTB","tx","amount","config","getConfig","DEFAULT_CACHE_TIME","pool","getPool","balance","receipt","parseTxValue","repayFlashLoanPTB","coinObject"],"mappings":";;;;;;AAiCO,MAAMA,IAAwBC;AAAA,EACnCC;AAAA,IACE,OACEC,MAC+B;AAC/B,YAAMC,IAAWC,EAA2BF,CAAO,GAC7CG,IAAMC;AAAA,QACV,uBAAuBJ,GAAS,OAAO,MAAM,QAAQK,EAAY,OAAO,WAAWL,GAAS,UAAUM,CAAuB;AAAA,QAC7HN;AAAA,MAAA,GAEIO,IAAM,MAAM,MAAMJ,GAAK;AAAA,QAC3B,SAASK,EAAoBC,GAAgBR,CAAQ;AAAA,MAAA,CACtD,EAAE,KAAK,CAACM,MAAQA,EAAI,MAAM;AAC3B,aAAO,OAAO,KAAKA,EAAI,IAAI,EAAE,IAAI,CAACG,OACzB;AAAA,QACL,GAAGH,EAAI,KAAKG,CAAQ;AAAA,QACpB,UAAAA;AAAA,MAAA,EAEH;AAAA,IACH;AAAA,EAAA;AAEJ;AASA,eAAsBC,EACpBC,GACAZ,GACiC;AAEjC,UADe,MAAMH,EAAsBG,CAAO,GAEzC,KAAK,CAACa,MACP,OAAOD,KAAe,WACjBE,EAAkBD,EAAM,QAAQ,MAAMC,EAAkBF,CAAU,IAEvE,OAAOA,KAAe,WACjBC,EAAM,YAAYD,IAEpBC,EAAM,YAAYD,EAAW,EACrC,KAAK;AAEV;AAeA,eAAsBG,EACpBC,GACAJ,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