@naviprotocol/lending 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # @naviprotocol/lending
2
+
3
+ [![npm version](https://badge.fury.io/js/%40naviprotocol%2Flending.svg)](https://badge.fury.io/js/%40naviprotocol%2Flending)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ NAVI Lending SDK is a lending SDK designed specifically for the Sui blockchain, providing complete lending functionality including account management, pool operations, flash loans, liquidation, and reward systems.
7
+
8
+ ## Documentation
9
+
10
+ For SDK documentation visit http://sdk.naviprotocol.io/lending
11
+
12
+ ## Core Concepts
13
+
14
+ ### Lending Protocol Basics
15
+
16
+ The NAVI lending protocol allows users to:
17
+
18
+ - **Deposit**: Deposit assets into pools to earn interest
19
+ - **Borrow**: Use deposits as collateral to borrow other assets
20
+ - **Repay**: Repay loans and pay interest
21
+ - **Withdraw**: Withdraw deposits from pools
22
+
23
+ ### Health Factor
24
+
25
+ Health factor is an important metric for measuring the safety of a user's lending account:
26
+
27
+ - **Health Factor > 1**: Account is safe and can continue borrowing
28
+ - **Health Factor ≤ 1**: Account is at risk of liquidation
29
+
30
+ ### Flash Loan
31
+
32
+ Flash loans allow users to borrow assets without collateral, but must be repaid within the same transaction.
33
+
34
+ ## Installation
35
+
36
+ ```npm
37
+ npm install @naviprotocol/lending
38
+ ```
39
+
40
+ ## Code Style and Conventions
41
+
42
+ ### Interface Optional Parameters
43
+
44
+ The last `options` parameter of the interface is usually an optional object used to customize interface behavior. Common optional parameters include but are not limited to:
45
+
46
+ - `client`: Sui network client instance (such as `SuiClient`), used for customizing network requests, suitable for scenarios that require custom RPC nodes or multi-network environments.
47
+ - `env`: Specify environment (such as `'prod'`、`'dev'`), affecting data sources and on-chain contract addresses, ensuring data isolation and compatibility in different deployment environments.
48
+ - `cacheTime`: Custom cache time in milliseconds. By setting cache time, you can reduce duplicate requests and improve performance. For example, `cacheTime: 60000` means cache for 60 seconds.
49
+ - `disableCache`: Whether to disable cache
50
+ - `accountCap`: In ptb-related operations, use account cap
51
+
52
+ **Usage Recommendations:**
53
+
54
+ - If you don't pass `options`, the SDK will automatically use default configuration, suitable for most regular scenarios.
55
+ - When you need to customize network, environment, or cache strategy, it's recommended to pass corresponding parameters for more flexible control.
56
+
57
+
58
+ ### Interface Naming
59
+
60
+ - Interfaces with PTB suffix indicate that the current interface is used for constructing transactions.
61
+
62
+
63
+ ## Support
64
+
65
+ - Issues: [GitHub Issues](https://github.com/naviprotocol/naviprotocol-monorepo/issues)
66
+
@@ -0,0 +1,16 @@
1
+ import { EnvOption } from './types';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+
4
+ /**
5
+ * Create an account capability transaction in the PTB (Programmable Transaction Block)
6
+ *
7
+ * This function creates a new account capability for the lending protocol.
8
+ * Account capabilities are required to perform lending operations such as
9
+ * borrowing, repaying, and managing collateral positions.
10
+ *
11
+ * @param tx - The transaction block to add the account creation operation to
12
+ * @param options - Optional environment configuration options
13
+ * @returns The transaction call result for creating an account capability
14
+ */
15
+ export declare function createAccountCapPTB(tx: Transaction, options?: Partial<EnvOption>): Promise<import('@mysten/sui/dist/cjs/transactions').TransactionResult>;
16
+ //# sourceMappingURL=account-cap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-cap.d.ts","sourceRoot":"","sources":["../src/account-cap.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAEtD;;;;;;;;;;GAUG;AACH,wBAAsB,mBAAmB,CAAC,EAAE,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,0EAQtF"}
@@ -0,0 +1,126 @@
1
+ import { UserLendingInfo, SuiClientOption, EnvOption, Transaction as NAVITransaction, AssetIdentifier, TransactionResult, CacheOption, AccountCap } from './types';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+ import { CoinStruct } from '@mysten/sui/client';
4
+ import { PoolOperator } from './pool';
5
+
6
+ /**
7
+ * Merges multiple coins into a single coin for transaction building
8
+ *
9
+ * This function takes multiple coin objects and merges them into a single coin
10
+ * that can be used in a transaction. It supports optional splitting to create
11
+ * a specific balance amount.
12
+ *
13
+ * @param tx - Transaction object to add merge operations to
14
+ * @param coins - Array of coin objects to merge
15
+ * @param options - Optional parameters for balance splitting and gas coin usage
16
+ * - `balance` - If provided, splits this amount from the resulting coin object
17
+ * - `useGasCoin` - If true, uses the gas coin for the operation
18
+ * @returns Transaction result representing the merged coin
19
+ */
20
+ export declare function mergeCoinsPTB(tx: Transaction, coins: ({
21
+ balance: string | number | bigint;
22
+ coinObjectId: string;
23
+ coinType: string;
24
+ } & CoinStruct)[], options?: {
25
+ balance?: number;
26
+ useGasCoin?: boolean;
27
+ }): import('@mysten/sui/dist/cjs/transactions').TransactionResult | {
28
+ $kind: "Input";
29
+ Input: number;
30
+ type?: "object";
31
+ } | {
32
+ $kind: "GasCoin";
33
+ GasCoin: true;
34
+ };
35
+ /**
36
+ * Calculates dynamic health factor for a user after potential operations
37
+ *
38
+ * This function creates a transaction call to calculate the health factor
39
+ * that would result after performing supply/borrow operations.
40
+ *
41
+ * @param tx - Transaction object to append calculation to
42
+ * @param address - User address or transaction result
43
+ * @param identifier - Asset identifier
44
+ * @param estimatedSupply - Estimated supply amount
45
+ * @param estimatedBorrow - Estimated borrow amount
46
+ * @param isIncrease - Whether this is an increase operation
47
+ * @param options - Environment options
48
+ * @returns Transaction result for health factor calculation
49
+ */
50
+ export declare function getSimulatedHealthFactorPTB(tx: Transaction, address: string | AccountCap | TransactionResult, identifier: AssetIdentifier, estimatedSupply: number | TransactionResult, estimatedBorrow: number | TransactionResult, isIncrease: boolean | TransactionResult, options?: Partial<EnvOption>): Promise<TransactionResult>;
51
+ /**
52
+ * Gets the current health factor for a user
53
+ *
54
+ * @param tx - The transaction object to add health factor query operation to
55
+ * @param address - User address or account cap or transaction result
56
+ * @param options - Environment options
57
+ * @returns Transaction result for health factor calculation
58
+ */
59
+ export declare function getHealthFactorPTB(tx: Transaction, address: string | AccountCap | TransactionResult, options?: Partial<EnvOption>): Promise<TransactionResult>;
60
+ /**
61
+ * Retrieves the current lending state for a user
62
+ *
63
+ * This function fetches all active lending positions for a user, including
64
+ * supply and borrow balances for different assets.
65
+ *
66
+ * @param address - User wallet address or account cap
67
+ * @param options - Options for client, environment, and caching
68
+ * @returns Promise<UserLendingInfo[]> - Array of user lending positions
69
+ */
70
+ export declare const getLendingState: (address: string | AccountCap, options?: Partial<SuiClientOption & EnvOption & CacheOption>) => Promise<UserLendingInfo[]>;
71
+ /**
72
+ * Calculates the current health factor for a user
73
+ *
74
+ * @param address - User wallet address or account cap
75
+ * @param options - Options for client and environment
76
+ * @returns Promise<number> - Health factor value
77
+ */
78
+ export declare function getHealthFactor(address: string | AccountCap, options?: Partial<SuiClientOption & EnvOption>): Promise<number>;
79
+ /**
80
+ * Calculates the health factor after performing lending operations
81
+ *
82
+ * This function simulates the health factor that would result after
83
+ * performing a series of supply, withdraw, borrow, or repay operations.
84
+ *
85
+ * @param address - User wallet address or account cap
86
+ * @param identifier - Asset identifier
87
+ * @param operations - Array of operations to simulate
88
+ * @param options - Options for client and environment
89
+ * @returns Promise<number> - Projected health factor
90
+ */
91
+ export declare function getSimulatedHealthFactor(address: string | AccountCap, identifier: AssetIdentifier, operations: {
92
+ type: PoolOperator;
93
+ amount: number;
94
+ }[], options?: Partial<SuiClientOption & EnvOption>): Promise<number>;
95
+ /**
96
+ * Retrieves transaction history for a user from the Navi protocol API
97
+ *
98
+ * This function fetches the transaction history for a specific user address
99
+ * from the Navi protocol's open API. It supports pagination through cursor-based navigation.
100
+ *
101
+ * @param address - User wallet address or account cap
102
+ * @param options - Optional parameters including cursor for pagination
103
+ * @returns Promise with transaction data and optional cursor for next page
104
+ */
105
+ export declare const getTransactions: (address: string | AccountCap, options?: {
106
+ cursor?: string;
107
+ }) => Promise<{
108
+ data: NAVITransaction[];
109
+ cursor?: string;
110
+ }>;
111
+ /**
112
+ * Retrieves all coins owned by a user address
113
+ *
114
+ * This function fetches all coin objects owned by a specific address from the Sui blockchain.
115
+ * It supports filtering by coin type and handles pagination automatically to retrieve all coins.
116
+ *
117
+ * @param address - User wallet address
118
+ * @param options - Optional parameters including coin type filter and client options
119
+ * - `coinType` - If specified, retrieves only coins of this type
120
+ * - `client` - If provided, uses this `SuiClient` instance instead of the default client
121
+ * @returns Promise<CoinStruct[]> - Array of coin objects owned by the address
122
+ */
123
+ export declare function getCoins(address: string, options?: Partial<{
124
+ coinType?: string;
125
+ } & SuiClientOption>): Promise<CoinStruct[]>;
126
+ //# sourceMappingURL=account.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,SAAS,EAET,WAAW,IAAI,eAAe,EAC9B,eAAe,EACf,iBAAiB,EACjB,WAAW,EACX,UAAU,EACX,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAetD,OAAO,EAAE,UAAU,EAAkB,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAqB,YAAY,EAAE,MAAM,QAAQ,CAAA;AAExD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAC3B,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,CAAC;IACN,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;IACjC,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;CACjB,GAAG,UAAU,CAAC,EAAE,EACjB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;;;;;;;EAiDF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,2BAA2B,CAC/C,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,iBAAiB,EAChD,UAAU,EAAE,eAAe,EAC3B,eAAe,EAAE,MAAM,GAAG,iBAAiB,EAC3C,eAAe,EAAE,MAAM,GAAG,iBAAiB,EAC3C,UAAU,EAAE,OAAO,GAAG,iBAAiB,EACvC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAqB5B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,iBAAiB,EAChD,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAE5B;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,YAEf,MAAM,GAAG,UAAU,YAClB,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,WAAW,CAAC,KAC3D,OAAO,CAAC,eAAe,EAAE,CAmD7B,CAAA;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,MAAM,GAAG,UAAU,EAC5B,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,GAC7C,OAAO,CAAC,MAAM,CAAC,CAUjB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,GAAG,UAAU,EAC5B,UAAU,EAAE,eAAe,EAC3B,UAAU,EAAE;IACV,IAAI,EAAE,YAAY,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;CACf,EAAE,EACH,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,GAC7C,OAAO,CAAC,MAAM,CAAC,CA8CjB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,YAEf,MAAM,GAAG,UAAU,YAClB;IACR,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,KACA,OAAO,CAAC;IACT,IAAI,EAAE,eAAe,EAAE,CAAA;IACvB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAaF,CAAA;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,OAAO,CACf;IACE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GAAG,eAAe,CACpB,GACA,OAAO,CAAC,UAAU,EAAE,CAAC,CAoCvB"}
package/dist/bcs.d.ts ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * BCS (Binary Canonical Serialization) Schemas for Lending Protocol
3
+ *
4
+ * This module defines the BCS schemas for serializing and deserializing
5
+ * lending protocol data structures. BCS is used for efficient binary
6
+ * encoding of complex data types for blockchain transactions and storage.
7
+ */
8
+ /**
9
+ * BCS schema for Sui addresses with hex transformation
10
+ * Converts between hex string representation and byte arrays
11
+ */
12
+ export declare const Address: import('@mysten/bcs').BcsType<string, string>;
13
+ /**
14
+ * BCS schema for incentive APY information
15
+ * Contains asset ID, APY value, and supported coin types
16
+ */
17
+ export declare const IncentiveAPYInfo: import('@mysten/bcs').BcsType<{
18
+ asset_id: number;
19
+ apy: string;
20
+ coin_types: string[];
21
+ }, {
22
+ asset_id: number;
23
+ apy: string | number | bigint;
24
+ coin_types: Iterable<string> & {
25
+ length: number;
26
+ };
27
+ }>;
28
+ /**
29
+ * BCS schema for incentive pool information
30
+ * Contains comprehensive details about a lending incentive pool
31
+ */
32
+ export declare const IncentivePoolInfo: import('@mysten/bcs').BcsType<{
33
+ pool_id: string;
34
+ funds: string;
35
+ phase: string;
36
+ start_at: string;
37
+ end_at: string;
38
+ closed_at: string;
39
+ total_supply: string;
40
+ asset_id: number;
41
+ option: number;
42
+ factor: string;
43
+ distributed: string;
44
+ available: string;
45
+ total: string;
46
+ }, {
47
+ pool_id: string;
48
+ funds: string;
49
+ phase: string | number | bigint;
50
+ start_at: string | number | bigint;
51
+ end_at: string | number | bigint;
52
+ closed_at: string | number | bigint;
53
+ total_supply: string | number | bigint;
54
+ asset_id: number;
55
+ option: number;
56
+ factor: string | number | bigint;
57
+ distributed: string | number | bigint;
58
+ available: string | number | bigint;
59
+ total: string | number | bigint;
60
+ }>;
61
+ /**
62
+ * BCS schema for incentive pool information grouped by phase
63
+ * Contains phase number and list of pools in that phase
64
+ */
65
+ export declare const IncentivePoolInfoByPhase: import('@mysten/bcs').BcsType<{
66
+ phase: string;
67
+ pools: {
68
+ pool_id: string;
69
+ funds: string;
70
+ phase: string;
71
+ start_at: string;
72
+ end_at: string;
73
+ closed_at: string;
74
+ total_supply: string;
75
+ asset_id: number;
76
+ option: number;
77
+ factor: string;
78
+ distributed: string;
79
+ available: string;
80
+ total: string;
81
+ }[];
82
+ }, {
83
+ phase: string | number | bigint;
84
+ pools: Iterable<{
85
+ pool_id: string;
86
+ funds: string;
87
+ phase: string | number | bigint;
88
+ start_at: string | number | bigint;
89
+ end_at: string | number | bigint;
90
+ closed_at: string | number | bigint;
91
+ total_supply: string | number | bigint;
92
+ asset_id: number;
93
+ option: number;
94
+ factor: string | number | bigint;
95
+ distributed: string | number | bigint;
96
+ available: string | number | bigint;
97
+ total: string | number | bigint;
98
+ }> & {
99
+ length: number;
100
+ };
101
+ }>;
102
+ /**
103
+ * BCS schema for oracle price information
104
+ * Contains price data from external price feeds
105
+ */
106
+ export declare const OracleInfo: import('@mysten/bcs').BcsType<{
107
+ oracle_id: number;
108
+ price: string;
109
+ decimals: number;
110
+ valid: boolean;
111
+ }, {
112
+ oracle_id: number;
113
+ price: string | number | bigint;
114
+ decimals: number;
115
+ valid: boolean;
116
+ }>;
117
+ /**
118
+ * BCS schema for flash loan asset configuration
119
+ * Contains parameters for flash loan functionality
120
+ */
121
+ export declare const FlashLoanAssetConfig: import('@mysten/bcs').BcsType<{
122
+ id: string;
123
+ asset_id: number;
124
+ coin_type: string;
125
+ pool_id: string;
126
+ rate_to_supplier: string;
127
+ rate_to_treasury: string;
128
+ max: string;
129
+ min: string;
130
+ }, {
131
+ id: string;
132
+ asset_id: number;
133
+ coin_type: string;
134
+ pool_id: string;
135
+ rate_to_supplier: string | number | bigint;
136
+ rate_to_treasury: string | number | bigint;
137
+ max: string | number | bigint;
138
+ min: string | number | bigint;
139
+ }>;
140
+ /**
141
+ * BCS schema for reserve data information
142
+ * Contains comprehensive details about a lending reserve
143
+ */
144
+ export declare const ReserveDataInfo: import('@mysten/bcs').BcsType<{
145
+ id: number;
146
+ oracle_id: number;
147
+ coin_type: string;
148
+ supply_cap: string;
149
+ borrow_cap: string;
150
+ supply_rate: string;
151
+ borrow_rate: string;
152
+ supply_index: string;
153
+ borrow_index: string;
154
+ total_supply: string;
155
+ total_borrow: string;
156
+ last_update_at: string;
157
+ ltv: string;
158
+ treasury_factor: string;
159
+ treasury_balance: string;
160
+ base_rate: string;
161
+ multiplier: string;
162
+ jump_rate_multiplier: string;
163
+ reserve_factor: string;
164
+ optimal_utilization: string;
165
+ liquidation_ratio: string;
166
+ liquidation_bonus: string;
167
+ liquidation_threshold: string;
168
+ }, {
169
+ id: number;
170
+ oracle_id: number;
171
+ coin_type: string;
172
+ supply_cap: string | number | bigint;
173
+ borrow_cap: string | number | bigint;
174
+ supply_rate: string | number | bigint;
175
+ borrow_rate: string | number | bigint;
176
+ supply_index: string | number | bigint;
177
+ borrow_index: string | number | bigint;
178
+ total_supply: string | number | bigint;
179
+ total_borrow: string | number | bigint;
180
+ last_update_at: string | number | bigint;
181
+ ltv: string | number | bigint;
182
+ treasury_factor: string | number | bigint;
183
+ treasury_balance: string | number | bigint;
184
+ base_rate: string | number | bigint;
185
+ multiplier: string | number | bigint;
186
+ jump_rate_multiplier: string | number | bigint;
187
+ reserve_factor: string | number | bigint;
188
+ optimal_utilization: string | number | bigint;
189
+ liquidation_ratio: string | number | bigint;
190
+ liquidation_bonus: string | number | bigint;
191
+ liquidation_threshold: string | number | bigint;
192
+ }>;
193
+ /**
194
+ * BCS schema for user state information
195
+ * Contains user's borrowing and supplying balances for an asset
196
+ */
197
+ export declare const UserStateInfo: import('@mysten/bcs').BcsType<{
198
+ asset_id: number;
199
+ borrow_balance: string;
200
+ supply_balance: string;
201
+ }, {
202
+ asset_id: number;
203
+ borrow_balance: string | number | bigint;
204
+ supply_balance: string | number | bigint;
205
+ }>;
206
+ //# sourceMappingURL=bcs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bcs.d.ts","sourceRoot":"","sources":["../src/bcs.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH;;;GAGG;AACH,eAAO,MAAM,OAAO,+CAIlB,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;EAO3B,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2B5B,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAKnC,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,UAAU;;;;;;;;;;EASrB,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;EAiB/B,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+C1B,CAAA;AAEF;;;GAGG;AACH,eAAO,MAAM,aAAa;;;;;;;;EAOxB,CAAA"}
@@ -0,0 +1,27 @@
1
+ import { LendingConfig, EnvOption, CacheOption } from './types';
2
+
3
+ /**
4
+ * Fetches lending protocol configuration from the API
5
+ *
6
+ * This function retrieves the current configuration for the lending protocol
7
+ * from the Navi protocol API. It's wrapped with both caching and singleton
8
+ * behavior to ensure efficient and consistent configuration access.
9
+ *
10
+ * The configuration includes:
11
+ * - Contract addresses for all protocol components
12
+ * - Oracle configuration and price feed information
13
+ * - Pool and incentive contract addresses
14
+ * - Environment-specific settings
15
+ *
16
+ * @param options - Optional environment and caching options
17
+ * @returns Promise<LendingConfig> - Complete lending protocol configuration
18
+ */
19
+ export declare const getConfig: (options?: Partial<EnvOption & CacheOption>) => Promise<LendingConfig>;
20
+ /**
21
+ * Default cache time for configuration data
22
+ *
23
+ * Configuration is cached for 5 minutes to reduce API calls
24
+ * while ensuring reasonably fresh configuration data.
25
+ */
26
+ export declare const DEFAULT_CACHE_TIME: number;
27
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAGpE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,SAAS,aACW,OAAO,CAAC,SAAS,GAAG,WAAW,CAAC,KAAG,OAAO,CAAC,aAAa,CAQxF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,QAAgB,CAAA"}
@@ -0,0 +1,55 @@
1
+ import { Transaction } from '@mysten/sui/transactions';
2
+ import { EnvOption, AssetIdentifier, CoinObject, CacheOption, FloashloanAsset, TransactionResult } from './types';
3
+
4
+ /**
5
+ * Get all available flash loan assets from the API
6
+ * Uses caching to avoid repeated API calls
7
+ *
8
+ * @param options - Optional environment and cache configuration
9
+ * @returns Array of flash loan asset configurations
10
+ */
11
+ export declare const getAllFlashLoanAssets: (options?: Partial<EnvOption & CacheOption>) => Promise<FloashloanAsset[]>;
12
+ /**
13
+ * Get a specific flash loan asset by identifier
14
+ *
15
+ * @param identifier - Asset identifier (string coin type, number asset ID, or object with id)
16
+ * @param options - Optional environment configuration
17
+ * @returns Flash loan asset configuration or null if not found
18
+ */
19
+ export declare function getFlashLoanAsset(identifier: AssetIdentifier, options?: Partial<EnvOption>): Promise<FloashloanAsset | null>;
20
+ /**
21
+ * Create a flash loan transaction in the PTB (Programmable Transaction Block)
22
+ *
23
+ * This function initiates a flash loan by borrowing the specified amount of assets.
24
+ * The borrowed assets must be repaid within the same transaction using repayFlashLoanPTB.
25
+ *
26
+ * @param tx - The transaction block to add the flash loan operation to
27
+ * @param identifier - Asset identifier to borrow
28
+ * @param amount - Amount to borrow (number or transaction result)
29
+ * @param options - Optional environment configuration
30
+ * @returns Tuple containing [balance, receipt] where receipt is needed for repayment
31
+ * @throws Error if the pool does not support flash loans
32
+ */
33
+ export declare function flashloanPTB(tx: Transaction, identifier: AssetIdentifier, amount: number | TransactionResult, options?: Partial<EnvOption>): Promise<{
34
+ $kind: "NestedResult";
35
+ NestedResult: [number, number];
36
+ }[]>;
37
+ /**
38
+ * Repay a flash loan transaction in the PTB
39
+ *
40
+ * This function repays the flash loan using the receipt from the original flash loan
41
+ * and the coin object containing the repayment amount.
42
+ *
43
+ * @param tx - The transaction block to add the repayment operation to
44
+ * @param identifier - Asset identifier being repaid
45
+ * @param receipt - Receipt from the original flash loan transaction
46
+ * @param coinObject - Coin object containing the repayment amount
47
+ * @param options - Optional environment configuration
48
+ * @returns Tuple containing [balance] after repayment
49
+ * @throws Error if the pool does not support flash loans
50
+ */
51
+ export declare function repayFlashLoanPTB(tx: Transaction, identifier: AssetIdentifier, receipt: TransactionResult | string, coinObject: CoinObject, options?: Partial<EnvOption>): Promise<{
52
+ $kind: "NestedResult";
53
+ NestedResult: [number, number];
54
+ }[]>;
55
+ //# sourceMappingURL=flashloan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flashloan.d.ts","sourceRoot":"","sources":["../src/flashloan.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,KAAK,EACV,SAAS,EACT,eAAe,EACf,UAAU,EACV,WAAW,EACX,eAAe,EACf,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAKhB;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,aACD,OAAO,CAAC,SAAS,GAAG,WAAW,CAAC,KAAG,OAAO,CAAC,eAAe,EAAE,CAU5F,CAAA;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,eAAe,EAC3B,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAC3B,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAajC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,WAAW,EACf,UAAU,EAAE,eAAe,EAC3B,MAAM,EAAE,MAAM,GAAG,iBAAiB,EAClC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC;;;KAgC7B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,WAAW,EACf,UAAU,EAAE,eAAe,EAC3B,OAAO,EAAE,iBAAiB,GAAG,MAAM,EACnC,UAAU,EAAE,UAAU,EACtB,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC;;;KAiC7B"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("@mysten/sui/transactions"),o=require("@mysten/bcs"),L=require("@mysten/sui/client"),W=require("lodash.camelcase"),Y=require("@mysten/sui/utils"),k=require("@pythnetwork/pyth-sui-js"),w=require("@mysten/sui/bcs"),F=o.bcs.bytes(32).transform({input:e=>o.fromHex(e),output:e=>o.toHex(e)}),J=o.bcs.struct("IncentiveAPYInfo",{asset_id:o.bcs.u8(),apy:o.bcs.u256(),coin_types:o.bcs.vector(o.bcs.string())}),E=o.bcs.struct("IncentivePoolInfo",{pool_id:F,funds:F,phase:o.bcs.u64(),start_at:o.bcs.u64(),end_at:o.bcs.u64(),closed_at:o.bcs.u64(),total_supply:o.bcs.u64(),asset_id:o.bcs.u8(),option:o.bcs.u8(),factor:o.bcs.u256(),distributed:o.bcs.u64(),available:o.bcs.u256(),total:o.bcs.u256()}),K=o.bcs.struct("IncentivePoolInfoByPhase",{phase:o.bcs.u64(),pools:o.bcs.vector(E)}),Q=o.bcs.struct("OracleInfo",{oracle_id:o.bcs.u8(),price:o.bcs.u256(),decimals:o.bcs.u8(),valid:o.bcs.bool()}),X=o.bcs.struct("FlashLoanAssetConfig",{id:o.bcs.string(),asset_id:o.bcs.u8(),coin_type:o.bcs.string(),pool_id:o.bcs.string(),rate_to_supplier:o.bcs.u64(),rate_to_treasury:o.bcs.u64(),max:o.bcs.u64(),min:o.bcs.u64()}),Z=o.bcs.struct("ReserveDataInfo",{id:o.bcs.u8(),oracle_id:o.bcs.u8(),coin_type:o.bcs.string(),supply_cap:o.bcs.u256(),borrow_cap:o.bcs.u256(),supply_rate:o.bcs.u256(),borrow_rate:o.bcs.u256(),supply_index:o.bcs.u256(),borrow_index:o.bcs.u256(),total_supply:o.bcs.u256(),total_borrow:o.bcs.u256(),last_update_at:o.bcs.u64(),ltv:o.bcs.u256(),treasury_factor:o.bcs.u256(),treasury_balance:o.bcs.u256(),base_rate:o.bcs.u256(),multiplier:o.bcs.u256(),jump_rate_multiplier:o.bcs.u256(),reserve_factor:o.bcs.u256(),optimal_utilization:o.bcs.u256(),liquidation_ratio:o.bcs.u256(),liquidation_bonus:o.bcs.u256(),liquidation_threshold:o.bcs.u256()}),U=o.bcs.struct("UserStateInfo",{asset_id:o.bcs.u8(),borrow_balance:o.bcs.u256(),supply_balance:o.bcs.u256()}),j=new L.SuiClient({url:L.getFullnodeUrl("mainnet")});function q(e){const a=[];return e.forEach((c,t)=>{const r=t===e.length-1;if(typeof c=="object"&&r){const{client:n,disableCache:s,cacheTime:i,...u}=c;a.push(u)}else a.push(c)}),JSON.stringify(a)}function C(e){const a={};return(...c)=>{const t=q(c);return a[t]||(a[t]=e(...c).finally(()=>{a[t]=null})),a[t]}}function T(e){let a={};return(...c)=>{const t=c[c.length-1],r=q(c),n=a[r];return!(t!=null&&t.disableCache)&&typeof(n==null?void 0:n.data)!="undefined"&&(typeof(t==null?void 0:t.cacheTime)=="undefined"||t.cacheTime>Date.now()-n.cacheAt)?n.data:e(...c).then(s=>(a[r]={data:s,cacheAt:Date.now()},s))}}function I(e){return Array.isArray(e)?e.map(a=>I(a)):e!=null&&typeof e=="object"?Object.keys(e).reduce((a,c)=>({...a,[W(c)]:I(e[c])}),{}):e}function b(e,a){return typeof e=="object"?e:a(e)}function x(e,a){return typeof a=="string"?e.object(a):typeof a=="object"&&a.$kind?a:e.object(a.contract.pool)}function B(e,a,c){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((t,r)=>(a[r]||a[0]).parse(Uint8Array.from(t[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function f(e){return Y.normalizeStructTag(e)}function M(e){const a=(e||0)/Math.pow(10,27);return a>Math.pow(10,5)?1/0:a}new k.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const m=T(C(async e=>{const a=`https://open-api.naviprotocol.io/api/navi/config?env=${(e==null?void 0:e.env)||"prod"}`;return(await fetch(a).then(t=>t.json())).data})),p=1e3*60*5;var _=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(_||{});const P=T(C(async e=>{const a=`https://open-api.naviprotocol.io/api/navi/pools?env=${(e==null?void 0:e.env)||"prod"}`;return(await fetch(a).then(t=>t.json())).data}));async function v(e,a){const c=await P({...a,cacheTime:p});if(typeof e=="object")return e;const t=c.find(r=>typeof e=="string"?f(r.suiCoinType)===f(e):typeof e=="number"?r.id===e:!1);if(!t)throw new Error("Pool not found");return t}const ee=T(C(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats").then(t=>t.json())).data)),te=T(C(async e=>await fetch("https://open-api.naviprotocol.io/api/navi/fee").then(t=>t.json())));async function H(e,a,c,t){const r=await m({...t,cacheTime:p}),n=await v(a,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(f(n.suiCoinType)===f("0x2::sui::SUI")&&s){if(!(t!=null&&t.amount))throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let i;return typeof(t==null?void 0:t.amount)!="undefined"?i=b(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[b(c,e.object)],typeArguments:[n.suiCoinType]}),t!=null&&t.accountCap?e.moveCall({target:`${r.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),b(c,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),b(t.accountCap,e.object)],typeArguments:[n.suiCoinType]}):e.moveCall({target:`${r.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),b(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}async function ae(e,a,c,t){const r=await m({...t,cacheTime:p}),n=await v(a,t),s=b(c,e.pure.u64);let i;if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),b(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});i=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});i=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[i],typeArguments:[n.suiCoinType]})}async function ce(e,a,c,t){const r=await m({...t,cacheTime:p}),n=await v(a,t),s=b(c,e.pure.u64);let i;if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),b(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});i=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});i=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(i)],typeArguments:[n.suiCoinType]})}async function re(e,a,c,t){const r=await m({...t,cacheTime:p}),n=await v(a,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(f(n.suiCoinType)===f("0x2::sui::SUI")&&s){if(!(t!=null&&t.amount))throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let i;return typeof(t==null?void 0:t.amount)!="undefined"?i=b(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[b(c,e.object)],typeArguments:[n.suiCoinType]}),t!=null&&t.accountCap?e.moveCall({target:`${r.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),b(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3),b(t.accountCap,e.object)],typeArguments:[n.suiCoinType]}):e.moveCall({target:`${r.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),b(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}function ne(e,a,c){const t=typeof(c==null?void 0:c.balance)=="number",r=t?c.balance:0;let n=0;const s=[];let i="";if(a.sort((l,d)=>Number(d.balance)-Number(l.balance)).forEach(l=>{if(!(t&&n>=r)&&Number(l.balance)!==0){if(i||(i=l.coinType),i!==l.coinType)throw new Error("All coins must be of the same type");n+=Number(l.balance),s.push(l.coinObjectId)}}),s.length===0)throw new Error("No coins to merge");if(t&&n<r)throw new Error(`Balance is less than the specified balance: ${n} < ${r}`);if(f(i)===f("0x2::sui::SUI")&&(c!=null&&c.useGasCoin))return t?e.splitCoins(e.gas,[e.pure.u64(r)]):e.gas;const u=s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1));return t?e.splitCoins(u,[e.pure.u64(r)]):u}async function R(e,a,c,t,r,n,s){const i=await m({...s,cacheTime:p}),u=await v(c,s);return e.moveCall({target:`${i.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(i.storage),e.object(i.oracle.priceOracle),x(e,u),b(a,e.pure.address),b(u.id,e.pure.u8),b(t,e.pure.u64),b(r,e.pure.u64),b(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function D(e,a,c){return R(e,a,0,0,0,!1,c)}const se=T(async(e,a)=>{var l;const c=await m({...a,cacheTime:p}),t=new A.Transaction,r=(l=a==null?void 0:a.client)!=null?l:j,n=await P(a);t.moveCall({target:`${c.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(c.storage),t.pure.address(e)]});const s=await r.devInspectTransactionBlock({transactionBlock:t,sender:e}),i=B(s,[w.bcs.vector(U)]);return I(i[0].filter(d=>d.supply_balance!=="0"||d.borrow_balance!=="0")).map(d=>{const y=n.find(g=>g.id===d.assetId);return{...d,pool:y}}).filter(d=>!!d.pool)});async function oe(e,a){var s;const c=(s=a==null?void 0:a.client)!=null?s:j,t=new A.Transaction;await D(t,e,a);const r=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=B(r,[w.bcs.u256()]);return M(Number(n[0])||0)}async function ie(e,a,c,t){var g;const r=(g=t==null?void 0:t.client)!=null?g:j,n=new A.Transaction;let s=0,i=0;const u=await v(a,t);if(c.forEach(h=>{h.type===_.Supply?s+=h.amount:h.type===_.Withdraw?s-=h.amount:h.type===_.Borrow?i+=h.amount:h.type===_.Repay&&(i-=h.amount)}),s*i<0)throw new Error("Invalid operations");const l=s>0||i>0;await R(n,e,u,Math.abs(s),Math.abs(i),l,t);const d=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),y=B(d,[w.bcs.u256()]);return M(Number(y[0])||0)}const ue=C(async(e,a)=>{const c=new URLSearchParams;a!=null&&a.cursor&&c.set("cursor",a.cursor),c.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${c.toString()}`;return(await fetch(t).then(n=>n.json())).data});async function le(e,a){var n;let c=null;const t=[],r=(n=a==null?void 0:a.client)!=null?n:j;do{let s;if(a!=null&&a.coinType?s=await r.getCoins({owner:e,coinType:a==null?void 0:a.coinType,cursor:c,limit:100}):s=await r.getAllCoins({owner:e,cursor:c,limit:100}),!s.data||!s.data.length)break;t.push(...s.data),c=s.nextCursor}while(c);return t}const N=new k.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function G(e){try{const a=[],c=await N.getLatestPriceFeeds(e);if(!c)return a;const t=Math.floor(new Date().valueOf()/1e3);for(const r of c){const n=r.getPriceUnchecked();if(n.publishTime>t){console.warn(`pyth price feed is invalid, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`);continue}t-r.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`),a.push(r.id))}return a}catch(a){throw new Error(`failed to get pyth stale price feed id, msg: ${a.message}`)}}async function z(e,a,c){var n;const t=(n=c==null?void 0:c.client)!=null?n:j,r=await m({...c,cacheTime:p});try{const s=await N.getPriceFeedsUpdateData(a);return await new k.SuiPythClient(t,r.oracle.pythStateId,r.oracle.wormholeStateId).updatePriceFeeds(e,s,a)}catch(s){throw new Error(`failed to update pyth price feeds, msg: ${s.message}`)}}async function de(e,a,c){const t=await m({...c,cacheTime:p});if(c!=null&&c.updatePythPriceFeeds){const r=a.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await G(r);n.length>0&&await z(e,n,c)}catch{}}for(const r of a)e.moveCall({target:`${t.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(t.oracle.oracleConfig),e.object(t.oracle.priceOracle),e.object(t.oracle.supraOracleHolder),e.object(r.pythPriceInfoObject),e.pure.address(r.feedId)]});return e}async function O(e){return(await m({...e,cacheTime:p})).oracle.feeds}function be(e,a){return e.filter(c=>!!(a!=null&&a.lendingState&&a.lendingState.find(r=>r.assetId===c.assetId)||a!=null&&a.pools&&a.pools.find(r=>r.id===c.assetId)))}const S=T(C(async e=>{const a=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${(e==null?void 0:e.env)||"prod"}`,c=await fetch(a).then(t=>t.json());return Object.keys(c.data).map(t=>({...c.data[t],coinType:t}))}));async function fe(e,a){return(await S(a)).find(t=>typeof e=="string"?f(t.coinType)===f(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function ge(e,a,c,t){const r=await m({...t,cacheTime:p}),n=await v(a,t);if(!(await S({...t,cacheTime:p})).some(d=>f(d.coinType)===f(n.suiCoinType)))throw new Error("Pool does not support flashloan");const[u,l]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx`,arguments:[e.object(r.flashloanConfig),e.object(n.contract.pool),b(c,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}async function pe(e,a,c,t,r){const n=await m({...r,cacheTime:p}),s=await v(a,r);if(!(await S({...r,cacheTime:p})).some(d=>f(d.coinType)===f(s.suiCoinType)))throw new Error("Pool does not support flashloan");const[l]=e.moveCall({target:`${n.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(n.storage),e.object(s.contract.pool),b(c,e.object),b(t,e.object)],typeArguments:[s.suiCoinType]});return[l]}async function me(e,a,c,t,r,n){const s={...n,cacheTime:p},i=await m(s),u=await v(a,s),l=await v(t,s),[d,y]=e.moveCall({target:`${i.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(i.priceOracle),e.object(i.storage),e.pure.u8(u.id),e.object(u.contract.pool),b(c,e.object),e.pure.u8(l.id),e.object(l.contract.pool),b(r,e.pure.address),e.object(i.incentiveV2),e.object(i.incentiveV3)],typeArguments:[u.suiCoinType,l.suiCoinType]});return[d,y]}async function he(e,a){var d;const c=await O(a),t=await P(a),r=(d=a==null?void 0:a.client)!=null?d:j,n=await m({...a,cacheTime:p}),s=new A.Transaction;s.moveCall({target:`${n.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[s.object("0x06"),s.object(n.storage),s.object(n.incentiveV3),s.pure.address(e)]});const i=await r.devInspectTransactionBlock({transactionBlock:s,sender:e}),u=B(i,[w.bcs.vector(w.bcs.string()),w.bcs.vector(w.bcs.string()),w.bcs.vector(w.bcs.u8()),w.bcs.vector(w.bcs.Address),w.bcs.vector(w.bcs.u256())]),l=[];if(u.length===5&&Array.isArray(u[0])){const y=u[0].length;for(let g=0;g<y;g++){const h=c.find($=>f($.coinType)===f(u[0][g])),V=t.find($=>f($.coinType)===f(u[0][g]));!h||!V||l.push({assetId:V.id,assetCoinType:f(u[0][g]),rewardCoinType:f(u[1][g]),option:Number(u[2][g]),userClaimableReward:Number(u[4][g])/Math.pow(10,h.priceDecimal),ruleIds:Array.isArray(u[3][g])?u[3][g]:[u[3][g]]})}}return l}function ye(e){const a=new Map;e.forEach(t=>{const r=t.assetId,n=t.option,s=`${r}-${n}-${t.rewardCoinType}`;a.has(s)?a.get(s).total+=t.userClaimableReward:a.set(s,{assetId:r,rewardType:n,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const c=new Map;for(const{assetId:t,rewardType:r,coinType:n,total:s}of a.values()){const i=`${t}-${r}`;c.has(i)||c.set(i,{assetId:t,rewardType:r,rewards:new Map});const u=c.get(i);u.rewards.set(n,(u.rewards.get(n)||0)+s)}return Array.from(c.values()).map(t=>({assetId:t.assetId,rewardType:t.rewardType,rewards:Array.from(t.rewards.entries()).map(([r,n])=>({coinType:r,available:n.toFixed(6)}))}))}const we=C(async e=>{const a=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}`;return(await fetch(a).then(t=>t.json())).data}),ve=C(async(e,a)=>{const c=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${(a==null?void 0:a.page)||1}&pageSize=${(a==null?void 0:a.size)||400}`,t=await fetch(c).then(r=>r.json());return I({data:t.data.rewards})});async function Ce(e,a,c){const t=await m({...c,cacheTime:p}),r=await P({...c,cacheTime:p}),n=new Map;for(const i of a){const{rewardCoinType:u,ruleIds:l}=i;for(const d of l){n.has(u)||n.set(u,{assetIds:[],ruleIds:[]});const y=n.get(u);y.assetIds.push(i.assetCoinType.replace("0x","")),y.ruleIds.push(d)}}const s=[];for(const[i,{assetIds:u,ruleIds:l}]of n){const d=r.find(g=>f(g.suiCoinType)===f(i));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${i}`);const y=d.contract.rewardFundId;if(c!=null&&c.accountCap&&!c.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(c!=null&&c.customCoinReceive){let g;c.accountCap?g=e.moveCall({target:`${t.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(y),e.pure.vector("string",u),e.pure.vector("address",l),b(c.accountCap,e.object)],typeArguments:[i]}):g=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(y),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[i]});const[h]=e.moveCall({target:"0x2::coin::from_balance",arguments:[g],typeArguments:[i]});if((c==null?void 0:c.customCoinReceive.type)==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([h],b(c.customCoinReceive.transfer,e.pure.address))}(c==null?void 0:c.customCoinReceive.type)==="depositNAVI"?await H(e,d,h,c):s.push({coin:h,identifier:d})}else e.moveCall({target:`${t.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(y),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[i]})}return s}async function Te(e,a){const c=await m({...a});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=F;exports.DEFAULT_CACHE_TIME=p;exports.FlashLoanAssetConfig=X;exports.IncentiveAPYInfo=J;exports.IncentivePoolInfo=E;exports.IncentivePoolInfoByPhase=K;exports.OracleInfo=Q;exports.PoolOperator=_;exports.ReserveDataInfo=Z;exports.UserStateInfo=U;exports.borrowCoinPTB=ce;exports.claimLendingRewardsPTB=Ce;exports.createAccountCapPTB=Te;exports.depositCoinPTB=H;exports.filterPriceFeeds=be;exports.flashloanPTB=ge;exports.getAllFlashLoanAssets=S;exports.getCoins=le;exports.getConfig=m;exports.getFees=te;exports.getFlashLoanAsset=fe;exports.getHealthFactor=oe;exports.getHealthFactorPTB=D;exports.getLendingState=se;exports.getPool=v;exports.getPools=P;exports.getPriceFeeds=O;exports.getPythStalePriceFeedId=G;exports.getSimulatedHealthFactor=ie;exports.getSimulatedHealthFactorPTB=R;exports.getStats=ee;exports.getTransactions=ue;exports.getUserAvailableLendingRewards=he;exports.getUserClaimedRewardHistory=ve;exports.getUserTotalClaimedReward=we;exports.liquidatePTB=me;exports.mergeCoinsPTB=ne;exports.normalizeCoinType=f;exports.parseTxValue=b;exports.repayCoinPTB=re;exports.repayFlashLoanPTB=pe;exports.summaryLendingRewards=ye;exports.updateOraclePricesPTB=de;exports.updatePythPriceFeeds=z;exports.withCache=T;exports.withSingleton=C;exports.withdrawCoinPTB=ae;
2
+ //# sourceMappingURL=index.cjs.js.map