@naviprotocol/wallet-client 2.0.5 → 2.0.7
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.
- package/dist/client.d.ts +3 -3
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/modules/balanceModule/index.d.ts +4 -4
- package/dist/modules/balanceModule/index.js +214 -0
- package/dist/modules/balanceModule/index.js.map +1 -0
- package/dist/modules/balanceModule/portfolio.js +105 -0
- package/dist/modules/balanceModule/portfolio.js.map +1 -0
- package/dist/modules/haedalModule/index.d.ts +2 -2
- package/dist/modules/haedalModule/index.js +114 -0
- package/dist/modules/haedalModule/index.js.map +1 -0
- package/dist/modules/index.d.ts +5 -5
- package/dist/modules/index.js +21 -0
- package/dist/modules/index.js.map +1 -0
- package/dist/modules/lendingModule/index.d.ts +5 -5
- package/dist/modules/lendingModule/index.js +410 -0
- package/dist/modules/lendingModule/index.js.map +1 -0
- package/dist/modules/lendingModule/migrate.js +225 -0
- package/dist/modules/lendingModule/migrate.js.map +1 -0
- package/dist/modules/lendingModule/protocols/navi.d.ts +1 -1
- package/dist/modules/lendingModule/protocols/navi.js +37 -0
- package/dist/modules/lendingModule/protocols/navi.js.map +1 -0
- package/dist/modules/lendingModule/protocols/suilend.d.ts +1 -1
- package/dist/{suilend-CWugUjwd.js → modules/lendingModule/protocols/suilend.js} +1 -1
- package/dist/{suilend-CWugUjwd.js.map → modules/lendingModule/protocols/suilend.js.map} +1 -1
- package/dist/modules/module.d.ts +1 -1
- package/dist/modules/module.js +46 -0
- package/dist/modules/module.js.map +1 -0
- package/dist/modules/swapModule/index.d.ts +2 -2
- package/dist/modules/swapModule/index.js +159 -0
- package/dist/modules/swapModule/index.js.map +1 -0
- package/dist/modules/voloModule/index.d.ts +2 -2
- package/dist/modules/voloModule/index.js +128 -0
- package/dist/modules/voloModule/index.js.map +1 -0
- package/dist/signer.d.ts +1 -1
- package/dist/signer.js +102 -0
- package/dist/signer.js.map +1 -0
- package/dist/transaction-result.d.ts +1 -1
- package/dist/transaction-result.js +59 -0
- package/dist/transaction-result.js.map +1 -0
- package/package.json +7 -7
- package/dist/index.esm.js +0 -1686
- package/dist/index.esm.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/modules/lendingModule/index.ts"],"sourcesContent":["/**\n * Lending Module Implementation\n *\n * This module provides comprehensive lending protocol functionality for the wallet client.\n * It handles deposit, withdraw, borrow, repay operations, liquidation, reward claiming,\n * and oracle price updates for the Navi lending protocol.\n *\n * @module LendingModule\n */\n\nimport { isSuccessfulTransaction } from '../../transaction-result'\nimport type { NaviWalletTransactionResult } from '../../types'\nimport { Module } from '../module'\nimport {\n depositCoinPTB,\n withdrawCoinPTB,\n borrowCoinPTB,\n repayCoinPTB,\n AssetIdentifier,\n getPool,\n getPools,\n mergeCoinsPTB,\n getHealthFactor,\n liquidatePTB,\n claimLendingRewardsPTB,\n getUserAvailableLendingRewards,\n updateOraclePricesPTB,\n getPriceFeeds,\n getLendingState,\n filterPriceFeeds,\n CacheOption,\n LendingReward,\n AccountCapOption,\n Pool,\n createAccountCapPTB,\n getUserClaimedRewardHistory,\n type NaviSdkServiceOptions\n} from '@naviprotocol/lending'\nimport { Transaction } from '@mysten/sui/transactions'\nimport type { SuiGrpcClient } from '@mysten/sui/grpc'\nimport {\n migrateBalanceToSupplyPTB,\n migrateBetweenBorrowPTB,\n migrateBetweenSupplyPTB\n} from './migrate'\nimport NaviProtocol from './protocols/navi'\nimport { LendingProtocol } from './protocols'\nimport { WalletClient } from '../../client'\n\n/**\n * Configuration options for the lending module\n */\nexport interface LendingModuleConfig {\n /** Environment setting for protocol interaction */\n env: 'dev' | 'prod'\n /** Lending protocols */\n protocols: LendingProtocol[]\n /** Enable the optional Suilend adapter. Defaults to true to preserve v1 business behavior. */\n enableSuilend: boolean\n /** Optional Suilend v3 gRPC client. Defaults to a client derived from the wallet Sui network. */\n suilendGrpcClient?: SuiGrpcClient\n /** Optional Suilend v3 gRPC endpoint. Used when suilendGrpcClient is not provided. */\n suilendGrpcUrl?: string\n /** Optional NAVI service endpoint overrides. */\n services?: NaviSdkServiceOptions\n}\n\n/**\n * Events emitted by the lending module\n */\nexport type Events = {\n /** Emitted when a deposit is successfully completed */\n 'lending:deposit-success': {\n /** Asset identifier for the deposited asset */\n identifier: AssetIdentifier\n /** Amount deposited */\n amount: number\n }\n /** Emitted when a withdrawal is successfully completed */\n 'lending:withdraw-success': {\n /** Asset identifier for the withdrawn asset */\n identifier: AssetIdentifier\n /** Amount withdrawn */\n amount: number\n }\n /** Emitted when a borrow is successfully completed */\n 'lending:borrow-success': {\n /** Asset identifier for the borrowed asset */\n identifier: AssetIdentifier\n /** Amount borrowed */\n amount: number\n }\n /** Emitted when a repayment is successfully completed */\n 'lending:repay-success': {\n /** Asset identifier for the repaid asset */\n identifier: AssetIdentifier\n /** Amount repaid */\n amount: number\n }\n /** Emitted when a liquidation is successfully completed */\n 'lending:liquidate-success': {\n /** Asset identifier for the debt being paid */\n payIdentifier: AssetIdentifier\n /** Amount of debt paid */\n payAmount: number\n /** Asset identifier for the collateral being liquidated */\n collateralIdentifier: AssetIdentifier\n /** Address of the account being liquidated */\n liquidationAddress: string\n }\n /** Emitted when rewards are successfully claimed */\n 'lending:claim-rewards-success': {\n /** Array of claimed rewards */\n rewards: LendingReward[]\n }\n}\n\n/**\n * Lending protocol module for wallet operations\n *\n * This module provides comprehensive lending functionality including:\n * - Deposit and withdraw operations\n * - Borrow and repay operations\n * - Liquidation functionality\n * - Reward claiming\n * - Oracle price updates\n * - Health factor monitoring\n * - Pool information retrieval\n */\nexport class LendingModule extends Module<LendingModuleConfig, Events> {\n /** Module name identifier */\n readonly name = 'lending'\n\n /** Default configuration values */\n readonly defaultConfig: LendingModuleConfig = {\n env: 'prod',\n protocols: [],\n enableSuilend: true\n }\n\n /** Internal protocols storage */\n private _protocols: LendingProtocol[] = []\n\n /** Get protocols (either from internal storage or config) */\n get protocols(): LendingProtocol[] {\n return this._protocols.length > 0 ? this._protocols : this.config.protocols\n }\n\n get naviServiceOptions() {\n const services = this.config.services ?? this.walletClient?.clientBundle.services\n return {\n ...(services ? { services } : {})\n }\n }\n\n install(walletClient: WalletClient): void {\n super.install(walletClient)\n this._protocols = []\n }\n\n async getProtocol(name: string) {\n if (!this.protocols || this.protocols.length === 0) {\n await this.initializeProtocols()\n }\n return this.protocols.find((p) => p.name === name)\n }\n\n /**\n * Gets all available lending pools\n *\n * @param options - Optional caching options\n * @returns Array of pool information\n */\n async getPools(options?: Partial<CacheOption>) {\n return await getPools({\n ...this.naviServiceOptions,\n env: this.config.env,\n ...options\n })\n }\n\n /**\n * Gets information for a specific lending pool\n *\n * @param identifier - Asset identifier (string, Pool object, or number)\n * @param options - Optional caching options\n * @returns Pool information\n */\n async getPool(identifier: AssetIdentifier, options?: Partial<CacheOption>) {\n return await getPool(identifier, {\n ...this.naviServiceOptions,\n env: this.config.env,\n ...options\n })\n }\n\n /**\n * Deposits coins into a lending pool\n *\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to deposit\n * @param options - Optional parameters including dry run mode and account capability\n * @returns Transaction response or dry run response\n */\n async deposit<T extends boolean = false>(\n identifier: AssetIdentifier,\n amount: number,\n options?: { dryRun: T } & Partial<AccountCapOption>\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n // Get pool information\n const pool = await getPool(identifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n // Wait for latest balance update\n await this.walletClient.module('balance').waitForUpdate()\n\n // Build transaction\n const tx = new Transaction()\n\n // Get coin balance and merge coins for deposit\n const coinBalance = this.walletClient.module('balance').portfolio.getBalance(pool.suiCoinType)\n\n const mergedCoin = mergeCoinsPTB(tx, coinBalance.coins, {\n balance: amount,\n useGasCoin: true,\n addressBalance: coinBalance.addressBalance.toFixed(0),\n coinType: pool.suiCoinType\n })\n\n // Build deposit transaction\n await depositCoinPTB(tx, pool, mergedCoin, {\n ...this.naviServiceOptions,\n env: this.config.env,\n amount,\n accountCap: options?.accountCap\n })\n\n // Execute transaction\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n // Handle successful deposit\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:deposit-success', {\n identifier,\n amount\n })\n\n // Update balance portfolio\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n /**\n * Withdraws coins from a lending pool\n *\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to withdraw\n * @param options - Optional parameters including dry run mode and account capability\n * @returns Transaction response or dry run response\n */\n async withdraw<T extends boolean = false>(\n identifier: AssetIdentifier,\n amount: number,\n options?: { dryRun: T; disableUpdateOracle?: boolean } & Partial<AccountCapOption>\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n // Get pool information\n const pool = await getPool(identifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n // Build transaction\n const tx = new Transaction()\n\n if (!options?.disableUpdateOracle) {\n await this.updateOraclePTB(tx, [pool])\n }\n\n // Build withdraw transaction\n const coin = await withdrawCoinPTB(tx, pool, amount, {\n ...this.naviServiceOptions,\n env: this.config.env,\n accountCap: options?.accountCap\n })\n\n // Transfer withdrawn coins to wallet\n tx.transferObjects([coin], this.walletClient.address)\n\n // Execute transaction\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n // Handle successful withdrawal\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:withdraw-success', {\n identifier,\n amount\n })\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n /**\n * Borrows coins from a lending pool\n *\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to borrow\n * @param options - Optional parameters including dry run mode and account capability\n * @returns Transaction response or dry run response\n */\n async borrow<T extends boolean = false>(\n identifier: AssetIdentifier,\n amount: number,\n options?: { dryRun: T; disableUpdateOracle?: boolean } & Partial<AccountCapOption>\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n // Get pool information\n const pool = await getPool(identifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n // Build transaction\n const tx = new Transaction()\n\n if (!options?.disableUpdateOracle) {\n await this.updateOraclePTB(tx, [pool])\n }\n\n // Build borrow transaction\n const coin = await borrowCoinPTB(tx, pool, amount, {\n ...this.naviServiceOptions,\n env: this.config.env,\n accountCap: options?.accountCap\n })\n\n // Transfer borrowed coins to wallet\n tx.transferObjects([coin], this.walletClient.address)\n\n // Execute transaction\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n // Handle successful borrow\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:borrow-success', {\n identifier,\n amount\n })\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n /**\n * Repays borrowed coins to a lending pool\n *\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to repay\n * @param options - Optional parameters including dry run mode and account capability\n * @returns Transaction response or dry run response\n */\n async repay<T extends boolean = false>(\n identifier: AssetIdentifier,\n amount: number,\n options?: { dryRun: T } & Partial<AccountCapOption>\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n // Wait for latest balance update\n await this.walletClient.module('balance').waitForUpdate()\n\n // Get pool information\n const pool = await getPool(identifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n // Build transaction\n const tx = new Transaction()\n\n // Get coin balance and merge coins for repayment\n const coinBalance = this.walletClient.module('balance').portfolio.getBalance(pool.suiCoinType)\n\n const mergedCoin = mergeCoinsPTB(tx, coinBalance.coins, {\n balance: amount,\n useGasCoin: true,\n addressBalance: coinBalance.addressBalance.toFixed(0),\n coinType: pool.suiCoinType\n })\n\n // Build repay transaction\n await repayCoinPTB(tx, pool, mergedCoin, {\n ...this.naviServiceOptions,\n env: this.config.env,\n amount,\n accountCap: options?.accountCap\n })\n\n // Execute transaction\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n // Handle successful repayment\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:repay-success', {\n identifier,\n amount\n })\n\n // Update balance portfolio\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n /**\n * Gets the current health factor for the user\n *\n * @returns Current health factor value\n */\n async getHealthFactor() {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const address = this.walletClient.address\n\n const healthFactor = await getHealthFactor(address, {\n ...this.naviServiceOptions,\n env: this.config.env,\n client: this.walletClient.client\n })\n\n return healthFactor\n }\n\n /**\n * Initiates a liquidation process\n *\n * @param payIdentifier - Asset identifier for the debt being paid\n * @param payAmount - Amount of debt to pay\n * @param collateralIdentifier - Asset identifier for the collateral being liquidated\n * @param liquidationAddress - Address of the account being liquidated\n * @param options - Optional parameters including dry run mode\n * @returns Transaction response or dry run response\n */\n async liquidate<T extends boolean = false>(\n payIdentifier: AssetIdentifier,\n payAmount: number,\n collateralIdentifier: AssetIdentifier,\n liquidationAddress: string,\n options?: { dryRun: T }\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const payPool = await getPool(payIdentifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n const collateralPool = await getPool(collateralIdentifier, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n const tx = new Transaction()\n\n const payCoinBalance = this.walletClient\n .module('balance')\n .portfolio.getBalance(payPool.suiCoinType)\n\n const mergedCoin = mergeCoinsPTB(tx, payCoinBalance.coins, {\n balance: payAmount,\n useGasCoin: true,\n addressBalance: payCoinBalance.addressBalance.toFixed(0),\n coinType: payPool.suiCoinType\n })\n\n const [collateralBalance, remainDebtBalance] = await liquidatePTB(\n tx,\n payPool,\n mergedCoin,\n collateralPool,\n liquidationAddress,\n {\n ...this.naviServiceOptions,\n env: this.config.env\n }\n )\n\n const [collateralCoin] = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [collateralBalance],\n typeArguments: [collateralPool.suiCoinType]\n })\n\n const [leftDebtCoin] = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [remainDebtBalance],\n typeArguments: [payPool.suiCoinType]\n })\n\n tx.transferObjects([collateralCoin, leftDebtCoin], this.walletClient.address)\n\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:liquidate-success', {\n payIdentifier,\n payAmount,\n collateralIdentifier,\n liquidationAddress\n })\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n /**\n * Gets the available lending rewards for the current user.\n *\n * @param options - Optional cache options.\n * @returns The available lending rewards for the user.\n * @throws If the wallet client is not found.\n */\n async getAvailableRewards(options?: Partial<CacheOption>) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n return getUserAvailableLendingRewards(this.walletClient.address, {\n ...this.naviServiceOptions,\n ...options,\n env: this.config.env,\n client: this.walletClient.client\n })\n }\n\n /**\n * Gets the claimed reward history for the current user.\n *\n * @param options - Optional cache options.\n * @returns The claimed reward history for the user.\n * @throws If the wallet client is not found.\n */\n async getClaimedRewardHistory(\n options?: Partial<CacheOption> & {\n page?: number\n size?: number\n }\n ) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n return getUserClaimedRewardHistory(this.walletClient.address, {\n ...this.naviServiceOptions,\n ...options\n })\n }\n\n /**\n * Claims all available lending rewards for the user\n *\n * @param options - Optional parameters including dry run mode and account capability\n * @returns Transaction response or dry run response\n */\n async claimAllRewards<T extends boolean = false>(\n options?: { dryRun: T } & Partial<AccountCapOption>\n ): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const tx = new Transaction()\n\n const rewards = await getUserAvailableLendingRewards(this.walletClient.address, {\n ...this.naviServiceOptions,\n env: this.config.env,\n client: this.walletClient.client\n })\n\n await claimLendingRewardsPTB(tx, rewards, {\n ...this.naviServiceOptions,\n env: this.config.env,\n accountCap: options?.accountCap\n })\n\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n if (!options?.dryRun && isSuccessfulTransaction(result)) {\n this.emit('lending:claim-rewards-success', {\n rewards\n })\n this.walletClient.module('balance').updatePortfolio()\n }\n\n return result as any\n }\n\n private async updateOraclePTB(tx: Transaction, pools?: Pool[]) {\n const feeds = await getPriceFeeds({\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n const lendingState = await this.getLendingState({\n cacheTime: 60 * 1000\n })\n\n const filteredFeeds = filterPriceFeeds(feeds, {\n lendingState,\n pools\n })\n\n await updateOraclePricesPTB(tx, filteredFeeds, {\n ...this.naviServiceOptions,\n env: this.config.env,\n updatePythPriceFeeds: true,\n client: this.walletClient?.client\n })\n }\n\n /**\n * Updates the oracle prices for the lending protocol\n *\n * @param options - Optional parameters including dry run mode and pools\n * @param options.dryRun - Whether to perform a dry run\n * @returns Transaction response or dry run response\n */\n async updateOracle<T extends boolean = false>(options?: {\n dryRun: T\n pools?: Pool[]\n }): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const tx = new Transaction()\n\n await this.updateOraclePTB(tx, options?.pools)\n\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n return result as any\n }\n\n /**\n * Gets all active lending positions for the user\n *\n * @param options - Optional caching options\n * @returns User's lending state information\n */\n async getLendingState(options?: Partial<CacheOption>) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n return await getLendingState(this.walletClient.address, {\n ...this.naviServiceOptions,\n env: this.config.env,\n ...options,\n client: this.walletClient.client\n })\n }\n\n /**\n * Creates an account capability for the lending protocol\n *\n * @param options - Optional parameters including dry run mode\n * @returns Transaction response or dry run response\n */\n async createAccountCap<T extends boolean = false>(options?: {\n dryRun: T\n }): Promise<NaviWalletTransactionResult<T>> {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const tx = new Transaction()\n\n const cap = await createAccountCapPTB(tx)\n\n tx.transferObjects([cap], this.walletClient.address)\n\n const result = await this.walletClient.signExecuteTransaction({\n transaction: tx,\n dryRun: options?.dryRun ?? false\n })\n\n return result as any\n }\n\n migrateBetweenSupplyPTB = migrateBetweenSupplyPTB\n migrateBetweenBorrowPTB = migrateBetweenBorrowPTB\n migrateBalanceToSupplyPTB = migrateBalanceToSupplyPTB\n\n constructor() {\n super()\n this.migrateBetweenSupplyPTB = migrateBetweenSupplyPTB.bind(this)\n this.migrateBetweenBorrowPTB = migrateBetweenBorrowPTB.bind(this)\n this.migrateBalanceToSupplyPTB = migrateBalanceToSupplyPTB.bind(this)\n }\n\n async initializeProtocols() {\n if (!this.walletClient) {\n console.warn('Wallet client not available during protocol initialization')\n return\n }\n\n const protocols = []\n protocols.push(new NaviProtocol(this.walletClient))\n\n if (this.config.enableSuilend) {\n try {\n const { default: SuilendProtocol } = await import('./protocols/suilend')\n protocols.push(\n await SuilendProtocol.create(this.walletClient, {\n grpcClient: this.config.suilendGrpcClient,\n grpcUrl: this.config.suilendGrpcUrl\n })\n )\n } catch (error) {\n console.warn('Failed to initialize SuilendProtocol:', error)\n }\n }\n\n this._protocols = protocols as LendingProtocol[]\n }\n}\n"],"names":["LendingModule","Module","migrateBetweenSupplyPTB","migrateBetweenBorrowPTB","migrateBalanceToSupplyPTB","services","walletClient","name","p","options","getPools","identifier","getPool","amount","pool","tx","Transaction","coinBalance","mergedCoin","mergeCoinsPTB","depositCoinPTB","result","isSuccessfulTransaction","coin","withdrawCoinPTB","borrowCoinPTB","repayCoinPTB","address","getHealthFactor","payIdentifier","payAmount","collateralIdentifier","liquidationAddress","payPool","collateralPool","payCoinBalance","collateralBalance","remainDebtBalance","liquidatePTB","collateralCoin","leftDebtCoin","getUserAvailableLendingRewards","getUserClaimedRewardHistory","rewards","claimLendingRewardsPTB","pools","feeds","getPriceFeeds","lendingState","filteredFeeds","filterPriceFeeds","updateOraclePricesPTB","getLendingState","cap","createAccountCapPTB","protocols","NaviProtocol","SuilendProtocol","error"],"mappings":";;;;;;AAiIO,MAAMA,UAAsBC,EAAoC;AAAA,EA+lBrE,cAAc;AACZ,UAAA,GA9lBF,KAAS,OAAO,WAGhB,KAAS,gBAAqC;AAAA,MAC5C,KAAK;AAAA,MACL,WAAW,CAAA;AAAA,MACX,eAAe;AAAA,IAAA,GAIjB,KAAQ,aAAgC,CAAA,GA+kBxC,KAAA,0BAA0BC,GAC1B,KAAA,0BAA0BC,GAC1B,KAAA,4BAA4BC,GAI1B,KAAK,0BAA0BF,EAAwB,KAAK,IAAI,GAChE,KAAK,0BAA0BC,EAAwB,KAAK,IAAI,GAChE,KAAK,4BAA4BC,EAA0B,KAAK,IAAI;AAAA,EACtE;AAAA;AAAA,EArlBA,IAAI,YAA+B;AACjC,WAAO,KAAK,WAAW,SAAS,IAAI,KAAK,aAAa,KAAK,OAAO;AAAA,EACpE;AAAA,EAEA,IAAI,qBAAqB;AACvB,UAAMC,IAAW,KAAK,OAAO,YAAY,KAAK,cAAc,aAAa;AACzE,WAAO;AAAA,MACL,GAAIA,IAAW,EAAE,UAAAA,MAAa,CAAA;AAAA,IAAC;AAAA,EAEnC;AAAA,EAEA,QAAQC,GAAkC;AACxC,UAAM,QAAQA,CAAY,GAC1B,KAAK,aAAa,CAAA;AAAA,EACpB;AAAA,EAEA,MAAM,YAAYC,GAAc;AAC9B,YAAI,CAAC,KAAK,aAAa,KAAK,UA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AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,iBAA4CA,GAEN;AAC1C,QAAI,CAAC,KAAK;AACR,YAAM,IAAI,MAAM,yBAAyB;AAG3C,UAAMM,IAAK,IAAIC,EAAA,GAETqC,IAAM,MAAMC,EAAoBvC,CAAE;AAExC,WAAAA,EAAG,gBAAgB,CAACsC,CAAG,GAAG,KAAK,aAAa,OAAO,GAEpC,MAAM,KAAK,aAAa,uBAAuB;AAAA,MAC5D,aAAatC;AAAA,MACb,QAAQN,GAAS,UAAU;AAAA,IAAA,CAC5B;AAAA,EAGH;AAAA,EAaA,MAAM,sBAAsB;AAC1B,QAAI,CAAC,KAAK,cAAc;AACtB,cAAQ,KAAK,4DAA4D;AACzE;AAAA,IACF;AAEA,UAAM8C,IAAY,CAAA;AAGlB,QAFAA,EAAU,KAAK,IAAIC,EAAa,KAAK,YAAY,CAAC,GAE9C,KAAK,OAAO;AACd,UAAI;AACF,cAAM,EAAE,SAASC,MAAoB,MAAM,OAAO,wBAAqB;AACvE,QAAAF,EAAU;AAAA,UACR,MAAME,EAAgB,OAAO,KAAK,cAAc;AAAA,YAC9C,YAAY,KAAK,OAAO;AAAA,YACxB,SAAS,KAAK,OAAO;AAAA,UAAA,CACtB;AAAA,QAAA;AAAA,MAEL,SAASC,GAAO;AACd,gBAAQ,KAAK,yCAAyCA,CAAK;AAAA,MAC7D;AAGF,SAAK,aAAaH;AAAA,EACpB;AACF;"}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { getPriceFeeds as Q, updateOraclePricesPTB as M, filterPriceFeeds as L, depositCoinPTB as y, getFlashLoanAsset as $, flashloanPTB as I, repayFlashLoanPTB as W, borrowCoinPTB as U, getCoins as j, getAddressBalance as z, mergeCoinsPTB as G } from "@naviprotocol/lending";
|
|
2
|
+
import { buildSwapPTBFromQuote as k } from "@naviprotocol/astros-aggregator-sdk";
|
|
3
|
+
import _ from "bignumber.js";
|
|
4
|
+
import { normalizeStructTag as v } from "@mysten/sui/utils";
|
|
5
|
+
import { UserPortfolio as D } from "../balanceModule/portfolio.js";
|
|
6
|
+
async function Y(o, a, C, e) {
|
|
7
|
+
if (!this.walletClient)
|
|
8
|
+
throw new Error("Wallet client not found");
|
|
9
|
+
const r = await this.getPool(a), t = await this.getPool(C), l = await this.getLendingState(), P = this.walletClient.address, c = e?.protocol ?? "navi", n = await this.getProtocol(c);
|
|
10
|
+
if (!n)
|
|
11
|
+
throw new Error(`Protocol ${c} not found`);
|
|
12
|
+
const i = await n.getPool(r.coinType);
|
|
13
|
+
if (console.log("migrateBetweenSupplyPTB", {
|
|
14
|
+
fromPoolLending: i
|
|
15
|
+
}), c === "navi" && i.supplyBalance === 0)
|
|
16
|
+
throw new Error("No supply balance");
|
|
17
|
+
if (e?.amount && e.amount > i.supplyBalance)
|
|
18
|
+
throw new Error("Amount is less than supply balance");
|
|
19
|
+
const m = e?.slippage ?? 5e-3, w = e?.amount ?? Number(i.supplyBalance), s = await Q(this.naviServiceOptions), p = await Promise.all([r, t]);
|
|
20
|
+
if (await M(
|
|
21
|
+
o,
|
|
22
|
+
L(s, {
|
|
23
|
+
lendingState: l,
|
|
24
|
+
pools: p
|
|
25
|
+
}),
|
|
26
|
+
this.naviServiceOptions
|
|
27
|
+
), c !== "navi" && r.id === t.id) {
|
|
28
|
+
const F = await n.withdrawCoinPTB(
|
|
29
|
+
o,
|
|
30
|
+
r.suiCoinType,
|
|
31
|
+
w
|
|
32
|
+
);
|
|
33
|
+
return await y(o, t, F, {
|
|
34
|
+
...this.naviServiceOptions,
|
|
35
|
+
amount: w
|
|
36
|
+
}), o;
|
|
37
|
+
}
|
|
38
|
+
const u = await $(t, {
|
|
39
|
+
...this.naviServiceOptions,
|
|
40
|
+
env: this.config.env
|
|
41
|
+
});
|
|
42
|
+
if (!u)
|
|
43
|
+
throw new Error(`${t.token.symbol} pool not support flashloan`);
|
|
44
|
+
const B = await this.walletClient.swap.getQuote(
|
|
45
|
+
r.suiCoinType,
|
|
46
|
+
t.suiCoinType,
|
|
47
|
+
w
|
|
48
|
+
), f = Number(B.amount_out);
|
|
49
|
+
if (f <= 0)
|
|
50
|
+
throw new Error("The amount of swapAmountOut must be greater than 0.");
|
|
51
|
+
const b = Math.floor(f * (1 - m)), h = Math.floor(b / (1 + u.flashloanFee));
|
|
52
|
+
if (h <= 0)
|
|
53
|
+
throw new Error("The calculated borrow amount must be positive.");
|
|
54
|
+
const [g, d] = await I(
|
|
55
|
+
o,
|
|
56
|
+
t,
|
|
57
|
+
h,
|
|
58
|
+
this.naviServiceOptions
|
|
59
|
+
), [T] = o.moveCall({
|
|
60
|
+
target: "0x2::coin::from_balance",
|
|
61
|
+
arguments: [g],
|
|
62
|
+
typeArguments: [t.suiCoinType]
|
|
63
|
+
});
|
|
64
|
+
await y(o, t, T, {
|
|
65
|
+
...this.naviServiceOptions,
|
|
66
|
+
amount: h
|
|
67
|
+
});
|
|
68
|
+
const S = await n.withdrawCoinPTB(o, r.suiCoinType, w), A = await k(
|
|
69
|
+
P,
|
|
70
|
+
o,
|
|
71
|
+
b,
|
|
72
|
+
S,
|
|
73
|
+
B
|
|
74
|
+
), O = o.moveCall({
|
|
75
|
+
target: "0x2::coin::into_balance",
|
|
76
|
+
arguments: [A],
|
|
77
|
+
typeArguments: [t.suiCoinType]
|
|
78
|
+
}), [N] = await W(
|
|
79
|
+
o,
|
|
80
|
+
t,
|
|
81
|
+
d,
|
|
82
|
+
O,
|
|
83
|
+
this.naviServiceOptions
|
|
84
|
+
), [E] = o.moveCall({
|
|
85
|
+
target: "0x2::coin::from_balance",
|
|
86
|
+
arguments: [N],
|
|
87
|
+
typeArguments: [t.suiCoinType]
|
|
88
|
+
});
|
|
89
|
+
return await y(o, t, E, this.naviServiceOptions), o;
|
|
90
|
+
}
|
|
91
|
+
async function Z(o, a, C, e) {
|
|
92
|
+
if (!this.walletClient)
|
|
93
|
+
throw new Error("Wallet client not found");
|
|
94
|
+
const r = this.walletClient.address, t = await this.getPool(a), l = await this.getPool(C), P = await this.getLendingState(), c = e?.protocol ?? "navi", n = await this.getProtocol(c);
|
|
95
|
+
if (!n)
|
|
96
|
+
throw new Error(`Protocol ${c} not found`);
|
|
97
|
+
const i = await n.getPool(t.coinType);
|
|
98
|
+
if (console.log("migrateBetweenBorrowPTB", {
|
|
99
|
+
fromPoolLending: i
|
|
100
|
+
}), i.borrowBalance === 0)
|
|
101
|
+
throw new Error("No borrow balance");
|
|
102
|
+
if (e?.amount && e.amount > i.borrowBalance)
|
|
103
|
+
throw new Error("Amount is more than borrow balance");
|
|
104
|
+
const m = await Q(this.naviServiceOptions), w = await Promise.all([t, l]);
|
|
105
|
+
await M(
|
|
106
|
+
o,
|
|
107
|
+
L(m, {
|
|
108
|
+
lendingState: P,
|
|
109
|
+
pools: w
|
|
110
|
+
}),
|
|
111
|
+
this.naviServiceOptions
|
|
112
|
+
);
|
|
113
|
+
let s = e?.amount ?? Number(i.borrowBalance);
|
|
114
|
+
if (Number(i.borrowBalance) === s) {
|
|
115
|
+
const R = i.borrowAPR / 100;
|
|
116
|
+
s = Math.ceil(
|
|
117
|
+
new _(s).multipliedBy(R * (60 * 3) / (365 * 24 * 3600)).plus(new _(1).shiftedBy(-t.token.decimals)).plus(s).toNumber()
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
const p = await $(t, {
|
|
121
|
+
...this.naviServiceOptions,
|
|
122
|
+
env: this.config.env
|
|
123
|
+
});
|
|
124
|
+
if (!p)
|
|
125
|
+
throw new Error(`${t.token.symbol} pool not support flashloan`);
|
|
126
|
+
if (!this.walletClient)
|
|
127
|
+
throw new Error("Wallet client not found");
|
|
128
|
+
const u = e?.slippage ?? 5e-3, B = Math.ceil(s * (1 + p.flashloanFee)), f = B, b = await this.walletClient.swap.getQuote(
|
|
129
|
+
t.suiCoinType,
|
|
130
|
+
l.suiCoinType,
|
|
131
|
+
f
|
|
132
|
+
);
|
|
133
|
+
let h = 1 + u, g = Math.ceil(Number(b.amount_out) * h), d = await this.walletClient.swap.getQuote(
|
|
134
|
+
l.suiCoinType,
|
|
135
|
+
t.suiCoinType,
|
|
136
|
+
g
|
|
137
|
+
);
|
|
138
|
+
for (; Number(d.amount_out) < f; )
|
|
139
|
+
h = h * Math.max(f / Number(d.amount_out), 1.001), g = Math.ceil(Number(b.amount_out) * h), d = await this.walletClient.swap.getQuote(
|
|
140
|
+
l.suiCoinType,
|
|
141
|
+
t.suiCoinType,
|
|
142
|
+
g
|
|
143
|
+
);
|
|
144
|
+
const [T, S] = await I(
|
|
145
|
+
o,
|
|
146
|
+
t,
|
|
147
|
+
s,
|
|
148
|
+
this.naviServiceOptions
|
|
149
|
+
), [A] = o.moveCall({
|
|
150
|
+
target: "0x2::coin::from_balance",
|
|
151
|
+
arguments: [T],
|
|
152
|
+
typeArguments: [t.suiCoinType]
|
|
153
|
+
});
|
|
154
|
+
await n.repayCoinPTB(o, t.suiCoinType, A, s);
|
|
155
|
+
const O = await U(o, l, g, this.naviServiceOptions), N = await k(
|
|
156
|
+
r,
|
|
157
|
+
o,
|
|
158
|
+
B,
|
|
159
|
+
O,
|
|
160
|
+
d
|
|
161
|
+
), E = o.moveCall({
|
|
162
|
+
target: "0x2::coin::into_balance",
|
|
163
|
+
arguments: [N],
|
|
164
|
+
typeArguments: [t.suiCoinType]
|
|
165
|
+
}), [F] = await W(
|
|
166
|
+
o,
|
|
167
|
+
t,
|
|
168
|
+
S,
|
|
169
|
+
E,
|
|
170
|
+
this.naviServiceOptions
|
|
171
|
+
), [q] = o.moveCall({
|
|
172
|
+
target: "0x2::coin::from_balance",
|
|
173
|
+
arguments: [F],
|
|
174
|
+
typeArguments: [t.suiCoinType]
|
|
175
|
+
});
|
|
176
|
+
return o.transferObjects([q], r), o;
|
|
177
|
+
}
|
|
178
|
+
async function x(o, a, C, e) {
|
|
179
|
+
if (!this.walletClient)
|
|
180
|
+
throw new Error("Wallet client not found");
|
|
181
|
+
const r = await j(this.walletClient.address, {
|
|
182
|
+
client: this.walletClient.client,
|
|
183
|
+
coinType: a
|
|
184
|
+
}), t = await this.getPool(C);
|
|
185
|
+
let l = "0";
|
|
186
|
+
if (typeof this.walletClient.client.core?.getBalance == "function")
|
|
187
|
+
try {
|
|
188
|
+
l = (await z(this.walletClient.client, {
|
|
189
|
+
owner: this.walletClient.address,
|
|
190
|
+
coinType: a
|
|
191
|
+
})).addressBalance;
|
|
192
|
+
} catch (u) {
|
|
193
|
+
console.error(u);
|
|
194
|
+
}
|
|
195
|
+
const c = new D(r, { [a]: l }), n = c.getBalance(a), m = v(a) === v("0x2::sui::SUI") ? n.amount : c.combinedBalanceOf(a);
|
|
196
|
+
if (m.eq(0))
|
|
197
|
+
throw new Error(`No balance of ${a}`);
|
|
198
|
+
if (console.log("migrateBalanceToSupplyPTB", {
|
|
199
|
+
balance: m.toNumber()
|
|
200
|
+
}), e?.amount && m.lt(e.amount))
|
|
201
|
+
throw new Error("Amount is greater than balance");
|
|
202
|
+
const w = e?.amount ?? m.toNumber(), s = e?.slippage ?? 5e-3;
|
|
203
|
+
let p = await G(o, n.coins, {
|
|
204
|
+
balance: w,
|
|
205
|
+
useGasCoin: !0,
|
|
206
|
+
addressBalance: n.addressBalance.toFixed(0),
|
|
207
|
+
coinType: a
|
|
208
|
+
});
|
|
209
|
+
if (v(a) !== v(t.suiCoinType)) {
|
|
210
|
+
const u = await this.walletClient.swap.getQuote(a, t.suiCoinType, w);
|
|
211
|
+
p = await this.walletClient.swap.buildSwapPTBFromQuote(
|
|
212
|
+
o,
|
|
213
|
+
u,
|
|
214
|
+
p,
|
|
215
|
+
s
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
return await y(o, t, p, this.naviServiceOptions), o;
|
|
219
|
+
}
|
|
220
|
+
export {
|
|
221
|
+
x as migrateBalanceToSupplyPTB,
|
|
222
|
+
Z as migrateBetweenBorrowPTB,
|
|
223
|
+
Y as migrateBetweenSupplyPTB
|
|
224
|
+
};
|
|
225
|
+
//# sourceMappingURL=migrate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate.js","sources":["../../../src/modules/lendingModule/migrate.ts"],"sourcesContent":["import { Transaction } from '@mysten/sui/transactions'\nimport {\n AssetIdentifier,\n getFlashLoanAsset,\n flashloanPTB,\n depositCoinPTB,\n repayFlashLoanPTB,\n borrowCoinPTB,\n mergeCoinsPTB,\n updateOraclePricesPTB,\n getCoins,\n getAddressBalance\n} from '@naviprotocol/lending'\nimport { buildSwapPTBFromQuote } from '@naviprotocol/astros-aggregator-sdk'\nimport type { LendingModule } from '.'\nimport BigNumber from 'bignumber.js'\nimport { normalizeStructTag } from '@mysten/sui/utils'\nimport { getPriceFeeds, filterPriceFeeds } from '@naviprotocol/lending'\nimport { UserPortfolio } from '../balanceModule/portfolio'\n\nexport async function migrateBetweenSupplyPTB(\n this: LendingModule,\n tx: Transaction,\n from: AssetIdentifier,\n to: AssetIdentifier,\n options?: Partial<{\n protocol?: 'navi' | 'suilend'\n amount?: number\n slippage?: number\n }>\n) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n const fromPool = await this.getPool(from)\n const toPool = await this.getPool(to)\n const lendingState = await this.getLendingState()\n const address = this.walletClient.address\n\n const protocolName = options?.protocol ?? 'navi'\n const fromProtocol = await this.getProtocol(protocolName)\n if (!fromProtocol) {\n throw new Error(`Protocol ${protocolName} not found`)\n }\n const fromPoolLending = await fromProtocol.getPool(fromPool.coinType)\n\n console.log('migrateBetweenSupplyPTB', {\n fromPoolLending\n })\n\n if (protocolName === 'navi' && fromPoolLending.supplyBalance === 0) {\n throw new Error('No supply balance')\n }\n\n if (options?.amount && options.amount > fromPoolLending.supplyBalance) {\n throw new Error('Amount is less than supply balance')\n }\n\n const slippage = options?.slippage ?? 0.005\n\n const formAmount = options?.amount ?? Number(fromPoolLending.supplyBalance)\n\n const priceFeeds = await getPriceFeeds(this.naviServiceOptions)\n const pools = await Promise.all([fromPool, toPool])\n await updateOraclePricesPTB(\n tx,\n filterPriceFeeds(priceFeeds, {\n lendingState,\n pools\n }),\n this.naviServiceOptions\n )\n\n if (protocolName !== 'navi' && fromPool.id === toPool.id) {\n const withdrawnFromCoin = await fromProtocol.withdrawCoinPTB(\n tx,\n fromPool.suiCoinType,\n formAmount\n )\n await depositCoinPTB(tx, toPool, withdrawnFromCoin, {\n ...this.naviServiceOptions,\n amount: formAmount\n })\n return tx\n }\n\n const toPoolFlashloanAsset = await getFlashLoanAsset(toPool, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n if (!toPoolFlashloanAsset) {\n throw new Error(`${toPool.token.symbol} pool not support flashloan`)\n }\n\n const quote = await this.walletClient.swap.getQuote(\n fromPool.suiCoinType,\n toPool.suiCoinType,\n formAmount\n )\n\n const shouldSwapAmount = Number(quote.amount_out)\n\n if (shouldSwapAmount <= 0) {\n throw new Error('The amount of swapAmountOut must be greater than 0.')\n }\n\n const minAmountOut = Math.floor(shouldSwapAmount * (1 - slippage))\n\n const borrowAmountInMin = Math.floor(minAmountOut / (1 + toPoolFlashloanAsset.flashloanFee))\n\n if (borrowAmountInMin <= 0) {\n throw new Error('The calculated borrow amount must be positive.')\n }\n\n const [flashloanBalance, receipt] = await flashloanPTB(\n tx,\n toPool,\n borrowAmountInMin,\n this.naviServiceOptions\n )\n\n const [flashCoin] = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [flashloanBalance],\n typeArguments: [toPool.suiCoinType]\n })\n\n await depositCoinPTB(tx, toPool, flashCoin, {\n ...this.naviServiceOptions,\n amount: borrowAmountInMin\n })\n\n const withdrawnFromCoin = await fromProtocol.withdrawCoinPTB(tx, fromPool.suiCoinType, formAmount)\n\n const swappedToCoin = await buildSwapPTBFromQuote(\n address,\n tx,\n minAmountOut,\n withdrawnFromCoin,\n quote\n )\n\n const repayBalance = tx.moveCall({\n target: '0x2::coin::into_balance',\n arguments: [swappedToCoin],\n typeArguments: [toPool.suiCoinType]\n })\n\n const [leftBalance] = await repayFlashLoanPTB(\n tx,\n toPool,\n receipt,\n repayBalance,\n this.naviServiceOptions\n )\n\n const [extraCoin] = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [leftBalance],\n typeArguments: [toPool.suiCoinType]\n })\n\n await depositCoinPTB(tx, toPool, extraCoin, this.naviServiceOptions)\n\n return tx\n}\n\nexport async function migrateBetweenBorrowPTB(\n this: LendingModule,\n tx: Transaction,\n from: AssetIdentifier,\n to: AssetIdentifier,\n options?: Partial<{\n amount?: number\n slippage?: number\n protocol?: 'navi' | 'suilend'\n }>\n) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n const address = this.walletClient.address\n const fromPool = await this.getPool(from)\n const toPool = await this.getPool(to)\n const lendingState = await this.getLendingState()\n\n const protocolName = options?.protocol ?? 'navi'\n const fromProtocol = await this.getProtocol(protocolName)\n if (!fromProtocol) {\n throw new Error(`Protocol ${protocolName} not found`)\n }\n const fromPoolLending = await fromProtocol.getPool(fromPool.coinType)\n\n console.log('migrateBetweenBorrowPTB', {\n fromPoolLending\n })\n\n if (fromPoolLending.borrowBalance === 0) {\n throw new Error('No borrow balance')\n }\n\n if (options?.amount && options.amount > fromPoolLending.borrowBalance) {\n throw new Error('Amount is more than borrow balance')\n }\n\n const priceFeeds = await getPriceFeeds(this.naviServiceOptions)\n const pools = await Promise.all([fromPool, toPool])\n await updateOraclePricesPTB(\n tx,\n filterPriceFeeds(priceFeeds, {\n lendingState,\n pools\n }),\n this.naviServiceOptions\n )\n\n let formAmount = options?.amount ?? Number(fromPoolLending.borrowBalance)\n\n if (Number(fromPoolLending.borrowBalance) === formAmount) {\n const borrowRate = fromPoolLending.borrowAPR / 100\n formAmount = Math.ceil(\n new BigNumber(formAmount)\n .multipliedBy((borrowRate * (60 * 3)) / (365 * 24 * 3600))\n .plus(new BigNumber(1).shiftedBy(-fromPool.token.decimals))\n .plus(formAmount)\n .toNumber()\n )\n }\n\n const fromPoolFlashloanAsset = await getFlashLoanAsset(fromPool, {\n ...this.naviServiceOptions,\n env: this.config.env\n })\n\n if (!fromPoolFlashloanAsset) {\n throw new Error(`${fromPool.token.symbol} pool not support flashloan`)\n }\n\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const slippage = options?.slippage ?? 0.005\n\n const flashloanRepayAmount = Math.ceil(formAmount * (1 + fromPoolFlashloanAsset.flashloanFee))\n const minSwapAmount = flashloanRepayAmount\n\n const fromQuote = await this.walletClient.swap.getQuote(\n fromPool.suiCoinType,\n toPool.suiCoinType,\n minSwapAmount\n )\n\n let rate = 1 + slippage\n\n let shouldBorrowAmount = Math.ceil(Number(fromQuote.amount_out) * rate)\n\n let toQuote = await this.walletClient.swap.getQuote(\n toPool.suiCoinType,\n fromPool.suiCoinType,\n shouldBorrowAmount\n )\n\n while (Number(toQuote.amount_out) < minSwapAmount) {\n rate = rate * Math.max(minSwapAmount / Number(toQuote.amount_out), 1.001)\n shouldBorrowAmount = Math.ceil(Number(fromQuote.amount_out) * rate)\n toQuote = await this.walletClient.swap.getQuote(\n toPool.suiCoinType,\n fromPool.suiCoinType,\n shouldBorrowAmount\n )\n }\n\n const [flashloanBalance, receipt] = await flashloanPTB(\n tx,\n fromPool,\n formAmount,\n this.naviServiceOptions\n )\n\n const [flashCoin]: any = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [flashloanBalance],\n typeArguments: [fromPool.suiCoinType]\n })\n\n await fromProtocol.repayCoinPTB(tx, fromPool.suiCoinType, flashCoin, formAmount)\n\n const borrowCoin = await borrowCoinPTB(tx, toPool, shouldBorrowAmount, this.naviServiceOptions)\n\n const swappedFromCoin = await buildSwapPTBFromQuote(\n address,\n tx,\n flashloanRepayAmount,\n borrowCoin,\n toQuote\n )\n\n const repayBalance = tx.moveCall({\n target: '0x2::coin::into_balance',\n arguments: [swappedFromCoin],\n typeArguments: [fromPool.suiCoinType]\n })\n\n const [leftBalance] = await repayFlashLoanPTB(\n tx,\n fromPool,\n receipt,\n repayBalance,\n this.naviServiceOptions\n )\n\n const [extraCoin] = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [leftBalance],\n typeArguments: [fromPool.suiCoinType]\n })\n tx.transferObjects([extraCoin], address)\n\n return tx\n}\n\nexport async function migrateBalanceToSupplyPTB(\n this: LendingModule,\n tx: Transaction,\n coinType: string,\n to: AssetIdentifier,\n options?: Partial<{\n amount?: number\n slippage?: number\n }>\n) {\n if (!this.walletClient) {\n throw new Error('Wallet client not found')\n }\n\n const coins = await getCoins(this.walletClient.address, {\n client: this.walletClient.client,\n coinType\n })\n const toPool = await this.getPool(to)\n\n // Include v2 address-level funds for this coin type when the core client\n // supports it; otherwise fall back to coin-object-only balances.\n let addressBalance = '0'\n const core = (this.walletClient.client as { core?: Record<string, unknown> }).core\n if (typeof core?.getBalance === 'function') {\n try {\n const balanceInfo = await getAddressBalance(this.walletClient.client, {\n owner: this.walletClient.address,\n coinType\n })\n addressBalance = balanceInfo.addressBalance\n } catch (error) {\n console.error(error)\n }\n }\n\n const portfolio = new UserPortfolio(coins, { [coinType]: addressBalance })\n const balance = portfolio.getBalance(coinType)\n // SUI is supplied via the gas coin (useGasCoin below), which cannot draw from\n // the address balance, so its spendable total counts coin objects only; other\n // coins can redeem the address balance through mergeCoinsPTB.\n const isSui = normalizeStructTag(coinType) === normalizeStructTag('0x2::sui::SUI')\n const spendableBalance = isSui ? balance.amount : portfolio.combinedBalanceOf(coinType)\n\n if (spendableBalance.eq(0)) {\n throw new Error(`No balance of ${coinType}`)\n }\n\n console.log('migrateBalanceToSupplyPTB', {\n balance: spendableBalance.toNumber()\n })\n\n if (options?.amount && spendableBalance.lt(options.amount)) {\n throw new Error('Amount is greater than balance')\n }\n\n const formAmount = options?.amount ?? spendableBalance.toNumber()\n\n const slippage = options?.slippage ?? 0.005\n\n let depositCoin = await mergeCoinsPTB(tx, balance.coins, {\n balance: formAmount,\n useGasCoin: true,\n addressBalance: balance.addressBalance.toFixed(0),\n coinType\n })\n\n if (normalizeStructTag(coinType) !== normalizeStructTag(toPool.suiCoinType)) {\n const quote = await this.walletClient.swap.getQuote(coinType, toPool.suiCoinType, formAmount)\n depositCoin = (await this.walletClient.swap.buildSwapPTBFromQuote(\n tx,\n quote,\n depositCoin,\n slippage\n )) as typeof depositCoin\n }\n\n await depositCoinPTB(tx, toPool, depositCoin, this.naviServiceOptions)\n\n return tx\n}\n"],"names":["migrateBetweenSupplyPTB","tx","from","to","options","fromPool","toPool","lendingState","address","protocolName","fromProtocol","fromPoolLending","slippage","formAmount","priceFeeds","getPriceFeeds","pools","updateOraclePricesPTB","filterPriceFeeds","withdrawnFromCoin","depositCoinPTB","toPoolFlashloanAsset","getFlashLoanAsset","quote","shouldSwapAmount","minAmountOut","borrowAmountInMin","flashloanBalance","receipt","flashloanPTB","flashCoin","swappedToCoin","buildSwapPTBFromQuote","repayBalance","leftBalance","repayFlashLoanPTB","extraCoin","migrateBetweenBorrowPTB","borrowRate","BigNumber","fromPoolFlashloanAsset","flashloanRepayAmount","minSwapAmount","fromQuote","rate","shouldBorrowAmount","toQuote","borrowCoin","borrowCoinPTB","swappedFromCoin","migrateBalanceToSupplyPTB","coinType","coins","getCoins","addressBalance","getAddressBalance","error","portfolio","UserPortfolio","balance","spendableBalance","normalizeStructTag","depositCoin","mergeCoinsPTB"],"mappings":";;;;;AAoBA,eAAsBA,EAEpBC,GACAC,GACAC,GACAC,GAKA;AACA,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,yBAAyB;AAE3C,QAAMC,IAAW,MAAM,KAAK,QAAQH,CAAI,GAClCI,IAAS,MAAM,KAAK,QAAQH,CAAE,GAC9BI,IAAe,MAAM,KAAK,gBAAA,GAC1BC,IAAU,KAAK,aAAa,SAE5BC,IAAeL,GAAS,YAAY,QACpCM,IAAe,MAAM,KAAK,YAAYD,CAAY;AACxD,MAAI,CAACC;AACH,UAAM,IAAI,MAAM,YAAYD,CAAY,YAAY;AAEtD,QAAME,IAAkB,MAAMD,EAAa,QAAQL,EAAS,QAAQ;AAMpE,MAJA,QAAQ,IAAI,2BAA2B;AAAA,IACrC,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,EAAmB,eAAe,IAChDF,EAAQ,SAASF,EAAU,kBAAkBN,CAAQ;AAEtF,MAAIS,EAAiB,GAAG,CAAC;AACvB,UAAM,IAAI,MAAM,iBAAiBT,CAAQ,EAAE;AAO7C,MAJA,QAAQ,IAAI,6BAA6B;AAAA,IACvC,SAASS,EAAiB,SAAA;AAAA,EAAS,CACpC,GAEGxD,GAAS,UAAUwD,EAAiB,GAAGxD,EAAQ,MAAM;AACvD,UAAM,IAAI,MAAM,gCAAgC;AAGlD,QAAMS,IAAaT,GAAS,UAAUwD,EAAiB,SAAA,GAEjDhD,IAAWR,GAAS,YAAY;AAEtC,MAAI0D,IAAc,MAAMC,EAAc9D,GAAI0D,EAAQ,OAAO;AAAA,IACvD,SAAS9C;AAAA,IACT,YAAY;AAAA,IACZ,gBAAgB8C,EAAQ,eAAe,QAAQ,CAAC;AAAA,IAChD,UAAAR;AAAA,EAAA,CACD;AAED,MAAIU,EAAmBV,CAAQ,MAAMU,EAAmBvD,EAAO,WAAW,GAAG;AAC3E,UAAMiB,IAAQ,MAAM,KAAK,aAAa,KAAK,SAAS4B,GAAU7C,EAAO,aAAaO,CAAU;AAC5F,IAAAiD,IAAe,MAAM,KAAK,aAAa,KAAK;AAAA,MAC1C7D;AAAA,MACAsB;AAAA,MACAuC;AAAA,MACAlD;AAAA,IAAA;AAAA,EAEJ;AAEA,eAAMQ,EAAenB,GAAIK,GAAQwD,GAAa,KAAK,kBAAkB,GAE9D7D;AACT;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LendingPool, LendingProtocol } from '.';
|
|
2
2
|
import { Transaction, TransactionObjectInput, TransactionResult } from '@mysten/sui/transactions';
|
|
3
3
|
import { CoinObject } from '@naviprotocol/lending';
|
|
4
|
-
import { WalletClient } from '../../../client';
|
|
4
|
+
import { WalletClient } from '../../../client.js';
|
|
5
5
|
|
|
6
6
|
declare class NaviProtocol implements LendingProtocol {
|
|
7
7
|
readonly name = "navi";
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { withdrawCoinPTB as s, repayCoinPTB as c } from "@naviprotocol/lending";
|
|
2
|
+
import i from "bignumber.js";
|
|
3
|
+
import { normalizeStructTag as p } from "@mysten/sui/utils";
|
|
4
|
+
class y {
|
|
5
|
+
constructor(n) {
|
|
6
|
+
this.name = "navi", this.walletClient = n;
|
|
7
|
+
}
|
|
8
|
+
async getPool(n) {
|
|
9
|
+
const t = await this.walletClient.lending.getPool(n), o = (await this.walletClient.lending.getLendingState()).find(
|
|
10
|
+
(l) => l.pool.suiCoinType === p(n)
|
|
11
|
+
), r = o ? new i(o.supplyBalance).toNumber() : 0, a = o ? new i(o.borrowBalance).toNumber() : 0;
|
|
12
|
+
return {
|
|
13
|
+
supplyBalance: r,
|
|
14
|
+
borrowBalance: a,
|
|
15
|
+
borrowAPR: parseFloat(t.borrowIncentiveApyInfo.apy)
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async depositCoinPTB(n, t, e, o) {
|
|
19
|
+
throw new Error("Not implemented");
|
|
20
|
+
}
|
|
21
|
+
async withdrawCoinPTB(n, t, e) {
|
|
22
|
+
return s(n, t, e, this.walletClient.lending.naviServiceOptions);
|
|
23
|
+
}
|
|
24
|
+
async borrowCoinPTB(n, t, e) {
|
|
25
|
+
throw new Error("Not implemented");
|
|
26
|
+
}
|
|
27
|
+
async repayCoinPTB(n, t, e, o) {
|
|
28
|
+
c(n, t, e, {
|
|
29
|
+
...this.walletClient.lending.naviServiceOptions,
|
|
30
|
+
amount: o
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
y as default
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=navi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"navi.js","sources":["../../../../src/modules/lendingModule/protocols/navi.ts"],"sourcesContent":["import { LendingPool, LendingProtocol } from '.'\nimport { Transaction, TransactionObjectInput, TransactionResult } from '@mysten/sui/transactions'\nimport { withdrawCoinPTB, repayCoinPTB, CoinObject, getPool } from '@naviprotocol/lending'\nimport { WalletClient } from '../../../client'\nimport BigNumber from 'bignumber.js'\nimport { normalizeStructTag } from '@mysten/sui/utils'\n\nclass NaviProtocol implements LendingProtocol {\n readonly name = 'navi'\n private walletClient: WalletClient\n\n constructor(walletClient: WalletClient) {\n this.walletClient = walletClient\n }\n\n async getPool(coinType: string): Promise<LendingPool> {\n const pool = await this.walletClient.lending.getPool(coinType)\n const lendingState = await this.walletClient.lending.getLendingState()\n const userPosition = lendingState.find(\n (position) => position.pool.suiCoinType === normalizeStructTag(coinType)\n )\n\n const supplyBalance = userPosition ? new BigNumber(userPosition.supplyBalance).toNumber() : 0\n const borrowBalance = userPosition ? new BigNumber(userPosition.borrowBalance).toNumber() : 0\n\n return {\n supplyBalance: supplyBalance,\n borrowBalance: borrowBalance,\n borrowAPR: parseFloat(pool.borrowIncentiveApyInfo.apy)\n }\n }\n\n async depositCoinPTB(\n tx: Transaction,\n coinType: string,\n coinObject: TransactionObjectInput,\n amount: number\n ): Promise<void> {\n throw new Error('Not implemented')\n }\n\n async withdrawCoinPTB(\n tx: Transaction,\n coinType: string,\n amount: number\n ): Promise<TransactionResult> {\n return withdrawCoinPTB(tx, coinType, amount, this.walletClient.lending.naviServiceOptions)\n }\n\n async borrowCoinPTB(\n tx: Transaction,\n coinType: string,\n amount: number\n ): Promise<TransactionResult> {\n throw new Error('Not implemented')\n }\n\n async repayCoinPTB(\n tx: Transaction,\n coinType: string,\n coinObject: CoinObject,\n amount: number\n ): Promise<void> {\n repayCoinPTB(tx, coinType, coinObject, {\n ...this.walletClient.lending.naviServiceOptions,\n amount\n })\n }\n}\n\nexport default NaviProtocol\n"],"names":["NaviProtocol","walletClient","coinType","pool","userPosition","position","normalizeStructTag","supplyBalance","BigNumber","borrowBalance","tx","coinObject","amount","withdrawCoinPTB","repayCoinPTB"],"mappings":";;;AAOA,MAAMA,EAAwC;AAAA,EAI5C,YAAYC,GAA4B;AAHxC,SAAS,OAAO,QAId,KAAK,eAAeA;AAAA,EACtB;AAAA,EAEA,MAAM,QAAQC,GAAwC;AACpD,UAAMC,IAAO,MAAM,KAAK,aAAa,QAAQ,QAAQD,CAAQ,GAEvDE,KADe,MAAM,KAAK,aAAa,QAAQ,gBAAA,GACnB;AAAA,MAChC,CAACC,MAAaA,EAAS,KAAK,gBAAgBC,EAAmBJ,CAAQ;AAAA,IAAA,GAGnEK,IAAgBH,IAAe,IAAII,EAAUJ,EAAa,aAAa,EAAE,aAAa,GACtFK,IAAgBL,IAAe,IAAII,EAAUJ,EAAa,aAAa,EAAE,aAAa;AAE5F,WAAO;AAAA,MACL,eAAAG;AAAA,MACA,eAAAE;AAAA,MACA,WAAW,WAAWN,EAAK,uBAAuB,GAAG;AAAA,IAAA;AAAA,EAEzD;AAAA,EAEA,MAAM,eACJO,GACAR,GACAS,GACAC,GACe;AACf,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AAAA,EAEA,MAAM,gBACJF,GACAR,GACAU,GAC4B;AAC5B,WAAOC,EAAgBH,GAAIR,GAAUU,GAAQ,KAAK,aAAa,QAAQ,kBAAkB;AAAA,EAC3F;AAAA,EAEA,MAAM,cACJF,GACAR,GACAU,GAC4B;AAC5B,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AAAA,EAEA,MAAM,aACJF,GACAR,GACAS,GACAC,GACe;AACf,IAAAE,EAAaJ,GAAIR,GAAUS,GAAY;AAAA,MACrC,GAAG,KAAK,aAAa,QAAQ;AAAA,MAC7B,QAAAC;AAAA,IAAA,CACD;AAAA,EACH;AACF;"}
|
|
@@ -3,7 +3,7 @@ import { Transaction, TransactionObjectInput, TransactionResult } from '@mysten/
|
|
|
3
3
|
import { SuiGrpcClient } from '@mysten/sui/grpc';
|
|
4
4
|
import { SuilendClient } from '@suilend/sdk/client';
|
|
5
5
|
import { ObligationOwnerCap } from '@suilend/sdk/_generated/suilend/lending-market/structs';
|
|
6
|
-
import { WalletClient } from '../../../client';
|
|
6
|
+
import { WalletClient } from '../../../client.js';
|
|
7
7
|
|
|
8
8
|
type SuilendProtocolCreateOptions = {
|
|
9
9
|
grpcClient?: SuiGrpcClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suilend
|
|
1
|
+
{"version":3,"file":"suilend.js","sources":["../../../../src/modules/lendingModule/protocols/suilend.ts"],"sourcesContent":["import { LendingPool, LendingProtocol } from '.'\nimport { Transaction, TransactionObjectInput, TransactionResult } from '@mysten/sui/transactions'\nimport { SuiGrpcClient } from '@mysten/sui/grpc'\nimport { SuilendClient, LENDING_MARKET_ID, LENDING_MARKET_TYPE } from '@suilend/sdk/client'\nimport { parseObligation } from '@suilend/sdk/parsers/obligation'\nimport { parseReserve } from '@suilend/sdk/parsers/reserve'\nimport type { ObligationOwnerCap } from '@suilend/sdk/_generated/suilend/lending-market/structs'\nimport { WalletClient } from '../../../client'\nimport { getCoinMetadataMap } from '@suilend/sui-fe/lib/coinMetadata'\nimport { MAX_U64 } from '@suilend/sui-fe/lib/constants'\nimport BigNumber from 'bignumber.js'\nimport { normalizeStructTag } from '@mysten/sui/utils'\n\ntype SuilendProtocolCreateOptions = {\n grpcClient?: SuiGrpcClient\n grpcUrl?: string\n}\n\nfunction createSuilendGrpcClient(\n walletClient: WalletClient,\n options: SuilendProtocolCreateOptions\n) {\n if (options.grpcClient) {\n return options.grpcClient\n }\n\n const network = walletClient.clientBundle.network\n\n if (options.grpcUrl) {\n return new SuiGrpcClient({\n network,\n baseUrl: options.grpcUrl\n })\n }\n\n if (walletClient.clientBundle.grpc !== walletClient.clientBundle.legacyJsonRpc) {\n return walletClient.clientBundle.grpc as SuiGrpcClient\n }\n\n throw new Error(\n 'Suilend requires an explicit Sui gRPC client or grpcUrl; JSON-RPC endpoints are not valid gRPC endpoints'\n )\n}\n\nclass SuilendProtocol implements LendingProtocol {\n readonly name = 'suilend'\n private walletClient: WalletClient\n private obligationOwnerCap: ObligationOwnerCap<string>\n private suilendClient: SuilendClient\n\n constructor(\n walletClient: WalletClient,\n obligationOwnerCap: ObligationOwnerCap<string>,\n suilendClient: SuilendClient\n ) {\n this.walletClient = walletClient\n this.obligationOwnerCap = obligationOwnerCap\n this.suilendClient = suilendClient\n }\n\n static async create(walletClient: WalletClient, options: SuilendProtocolCreateOptions = {}) {\n const suilendGrpcClient = createSuilendGrpcClient(walletClient, options)\n const [suilendClient, obligations] = await Promise.all([\n SuilendClient.initialize(LENDING_MARKET_ID, LENDING_MARKET_TYPE, suilendGrpcClient),\n SuilendClient.getObligationOwnerCaps(\n walletClient.address,\n [LENDING_MARKET_TYPE],\n suilendGrpcClient\n )\n ])\n if (obligations.length === 0) {\n throw new Error('No existing obligations found for wallet address: ' + walletClient.address)\n }\n return new SuilendProtocol(walletClient, obligations[0], suilendClient)\n }\n\n async getPool(coinType: string): Promise<LendingPool & { cTokenExchangeRate: number }> {\n const normalizedCoinType = normalizeStructTag(coinType)\n\n const allReserves = this.suilendClient.lendingMarket.reserves\n\n const coinTypes = new Set<string>()\n\n allReserves.forEach((reserve) => {\n coinTypes.add(normalizeStructTag(reserve.coinType.name))\n reserve.depositsPoolRewardManager.poolRewards.forEach((reward) => {\n if (reward) {\n coinTypes.add(normalizeStructTag(reward.coinType.name))\n }\n })\n reserve.borrowsPoolRewardManager.poolRewards.forEach((reward) => {\n if (reward) {\n coinTypes.add(normalizeStructTag(reward.coinType.name))\n }\n })\n })\n\n const coinMetadataMap = await getCoinMetadataMap(Array.from(coinTypes))\n\n const parsedReserves = allReserves.map((reserve) => parseReserve(reserve, coinMetadataMap))\n const reservesMap = parsedReserves.reduce(\n (acc, reserve) => {\n acc[reserve.coinType] = reserve\n return acc\n },\n {} as Record<string, any>\n )\n\n const rawObligation = await this.suilendClient.getObligation(\n this.obligationOwnerCap.obligationId\n )\n\n const obligation = parseObligation(rawObligation, reservesMap)\n\n const deposit = obligation.deposits.find((deposit) => deposit.coinType === normalizedCoinType)\n const borrow = obligation.borrows.find((borrow) => borrow.coinType === normalizedCoinType)\n\n const decimals = coinMetadataMap[normalizedCoinType].decimals\n const cTokenExchangeRate = reservesMap[normalizedCoinType].cTokenExchangeRate.toNumber()\n\n return {\n cTokenExchangeRate: cTokenExchangeRate,\n supplyBalance: deposit?.depositedAmount.shiftedBy(decimals).decimalPlaces(0).toNumber() ?? 0,\n borrowBalance: borrow?.borrowedAmount.shiftedBy(decimals).decimalPlaces(0).toNumber() ?? 0,\n borrowAPR: reservesMap[normalizedCoinType].borrowAprPercent.toNumber()\n }\n }\n\n async depositCoinPTB(\n tx: Transaction,\n coinType: string,\n coinObject: TransactionObjectInput,\n amount: number\n ): Promise<void> {\n throw new Error('Not implemented')\n }\n\n async withdrawCoinPTB(tx: Transaction, coinType: string, amount: number) {\n const pool = await this.getPool(coinType)\n const isMax = amount === pool.supplyBalance\n\n return await this.suilendClient.withdraw(\n this.obligationOwnerCap.id,\n this.obligationOwnerCap.obligationId,\n coinType,\n isMax ? MAX_U64.toString() : Math.ceil(amount / pool.cTokenExchangeRate).toString(),\n tx\n )\n }\n\n async borrowCoinPTB(\n tx: Transaction,\n coinType: string,\n amount: number\n ): Promise<TransactionResult> {\n throw new Error('Not implemented')\n }\n\n async repayCoinPTB(\n tx: Transaction,\n coinType: string,\n coinObject: TransactionObjectInput,\n amount: number\n ): Promise<void> {\n this.suilendClient.repay(this.obligationOwnerCap.obligationId, coinType, coinObject, tx)\n tx.transferObjects([coinObject as any], tx.pure.address(this.walletClient.address))\n }\n}\n\nexport default SuilendProtocol\n"],"names":["createSuilendGrpcClient","walletClient","options","network","SuiGrpcClient","SuilendProtocol","obligationOwnerCap","suilendClient","suilendGrpcClient","obligations","SuilendClient","LENDING_MARKET_ID","LENDING_MARKET_TYPE","coinType","normalizedCoinType","normalizeStructTag","allReserves","coinTypes","reserve","reward","coinMetadataMap","getCoinMetadataMap","reservesMap","parseReserve","acc","rawObligation","obligation","parseObligation","deposit","borrow","decimals","tx","coinObject","amount","pool","isMax","M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CAAQ,GAClCsB,IAAQF,MAAWC,EAAK;AAE9B,WAAO,MAAM,KAAK,cAAc;AAAA,MAC9B,KAAK,mBAAmB;AAAA,MACxB,KAAK,mBAAmB;AAAA,MACxBrB;AAAA,MACAsB,IAAQC,EAAQ,SAAA,IAAa,KAAK,KAAKH,IAASC,EAAK,kBAAkB,EAAE,SAAA;AAAA,MACzEH;AAAA,IAAA;AAAA,EAEJ;AAAA,EAEA,MAAM,cACJA,GACAlB,GACAoB,GAC4B;AAC5B,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AAAA,EAEA,MAAM,aACJF,GACAlB,GACAmB,GACAC,GACe;AACf,SAAK,cAAc,MAAM,KAAK,mBAAmB,cAAcpB,GAAUmB,GAAYD,CAAE,GACvFA,EAAG,gBAAgB,CAACC,CAAiB,GAAGD,EAAG,KAAK,QAAQ,KAAK,aAAa,OAAO,CAAC;AAAA,EACpF;AACF;"}
|
package/dist/modules/module.d.ts
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
class i {
|
|
2
|
+
/**
|
|
3
|
+
* Gets the current configuration for this module
|
|
4
|
+
*
|
|
5
|
+
* This combines the default configuration with any user-provided overrides
|
|
6
|
+
* from the wallet client configuration.
|
|
7
|
+
*
|
|
8
|
+
* @returns The merged configuration for this module
|
|
9
|
+
*/
|
|
10
|
+
get config() {
|
|
11
|
+
return this.walletClient ? this.walletClient.config(this.name) : this.defaultConfig;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Emits an event through the wallet client's event system
|
|
15
|
+
*
|
|
16
|
+
* @param event - The event name to emit
|
|
17
|
+
* @param data - The event data to emit
|
|
18
|
+
*/
|
|
19
|
+
emit(t, l) {
|
|
20
|
+
this.walletClient?.events.emit(t, l);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Installs this module into a wallet client
|
|
24
|
+
*
|
|
25
|
+
* This method is called by the wallet client during initialization
|
|
26
|
+
* to establish the connection between the module and the client.
|
|
27
|
+
*
|
|
28
|
+
* @param walletClient - The wallet client instance to install into
|
|
29
|
+
*/
|
|
30
|
+
install(t) {
|
|
31
|
+
this.walletClient = t;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Uninstalls this module from the wallet client
|
|
35
|
+
*
|
|
36
|
+
* This method removes the reference to the wallet client,
|
|
37
|
+
* effectively disconnecting the module.
|
|
38
|
+
*/
|
|
39
|
+
uninstall() {
|
|
40
|
+
this.walletClient = void 0;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
i as Module
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=module.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.js","sources":["../../src/modules/module.ts"],"sourcesContent":["/**\n * Wallet Client Module System\n *\n * This module defines the base architecture for the wallet client's modular system.\n * It provides the foundation for different functionality modules like swap, lending,\n * balance management, and other DeFi operations.\n *\n * @module WalletClientModule\n */\n\nimport { WalletClient } from '../client'\nimport { ModuleName } from '.'\n\n/**\n * Base interface for module configuration\n *\n * All modules must implement this interface to define their configuration structure.\n */\nexport interface ModuleConfig {\n [key: string]: any\n}\n\n/**\n * Base interface for module events\n *\n * All modules must implement this interface to define their event structure.\n */\nexport type ModuleEvents = {\n [key: string]: any\n}\n\n/**\n * Abstract base class for all wallet client modules\n *\n * This class provides the foundation for modular functionality in the wallet client.\n * Each module (swap, lending, balance, etc.) extends this class to provide\n * specific functionality while maintaining a consistent interface.\n *\n * @template TConfig - The configuration type for this module\n * @template TEvents - The events type for this module\n */\nexport abstract class Module<TConfig extends ModuleConfig, TEvents extends ModuleEvents> {\n /** The unique name identifier for this module */\n abstract readonly name: string\n\n /** Default configuration values for this module */\n abstract readonly defaultConfig: TConfig\n\n /** Reference to the wallet client instance that owns this module */\n protected walletClient?: WalletClient\n\n /**\n * Gets the current configuration for this module\n *\n * This combines the default configuration with any user-provided overrides\n * from the wallet client configuration.\n *\n * @returns The merged configuration for this module\n */\n get config(): TConfig {\n return this.walletClient\n ? (this.walletClient.config(this.name as ModuleName) as unknown as TConfig)\n : this.defaultConfig\n }\n\n /**\n * Emits an event through the wallet client's event system\n *\n * @param event - The event name to emit\n * @param data - The event data to emit\n */\n emit(event: keyof TEvents, data: TEvents[keyof TEvents]) {\n this.walletClient?.events.emit(event as any, data)\n }\n\n /**\n * Installs this module into a wallet client\n *\n * This method is called by the wallet client during initialization\n * to establish the connection between the module and the client.\n *\n * @param walletClient - The wallet client instance to install into\n */\n install(walletClient: WalletClient): void {\n this.walletClient = walletClient\n }\n\n /**\n * Uninstalls this module from the wallet client\n *\n * This method removes the reference to the wallet client,\n * effectively disconnecting the module.\n */\n uninstall() {\n this.walletClient = undefined\n }\n}\n"],"names":["Module","event","data","walletClient"],"mappings":"AAyCO,MAAeA,EAAmE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBvF,IAAI,SAAkB;AACpB,WAAO,KAAK,eACP,KAAK,aAAa,OAAO,KAAK,IAAkB,IACjD,KAAK;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,KAAKC,GAAsBC,GAA8B;AACvD,SAAK,cAAc,OAAO,KAAKD,GAAcC,CAAI;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,QAAQC,GAAkC;AACxC,SAAK,eAAeA;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAY;AACV,SAAK,eAAe;AAAA,EACtB;AACF;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Dex, FeeOption, Quote } from '@naviprotocol/astros-aggregator-sdk';
|
|
2
2
|
import { Transaction } from '@mysten/sui/transactions';
|
|
3
|
-
import { Module } from '../module';
|
|
4
|
-
import { NaviWalletTransactionResult } from '../../types';
|
|
3
|
+
import { Module } from '../module.js';
|
|
4
|
+
import { NaviWalletTransactionResult } from '../../types.js';
|
|
5
5
|
import { NaviSdkServiceOptions } from '@naviprotocol/lending';
|
|
6
6
|
|
|
7
7
|
/**
|