@naviprotocol/lending 1.2.0 → 1.2.2-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 NAVI
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2021 NAVI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,66 +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
-
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
+
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@mysten/sui/transactions"),o=require("@mysten/bcs"),E=require("@mysten/sui/client"),Q=require("lodash.camelcase"),X=require("@mysten/sui/utils"),V=require("@pythnetwork/pyth-sui-js"),j=require("bignumber.js"),h=require("@mysten/sui/bcs"),R=o.bcs.bytes(32).transform({input:e=>o.fromHex(e),output:e=>o.toHex(e)}),Z=o.bcs.struct("IncentiveAPYInfo",{asset_id:o.bcs.u8(),apy:o.bcs.u256(),coin_types:o.bcs.vector(o.bcs.string())}),N=o.bcs.struct("IncentivePoolInfo",{pool_id:R,funds:R,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()}),x=o.bcs.struct("IncentivePoolInfoByPhase",{phase:o.bcs.u64(),pools:o.bcs.vector(N)}),ee=o.bcs.struct("OracleInfo",{oracle_id:o.bcs.u8(),price:o.bcs.u256(),decimals:o.bcs.u8(),valid:o.bcs.bool()}),te=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()}),ae=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()}),D=o.bcs.struct("UserStateInfo",{asset_id:o.bcs.u8(),borrow_balance:o.bcs.u256(),supply_balance:o.bcs.u256()}),P=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function M(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 T(e){const a={};return(...c)=>{const t=M(c);return a[t]||(a[t]=e(...c).finally(()=>{a[t]=null})),a[t]}}function I(e){let a={};return(...c)=>{const t=c[c.length-1],r=M(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 S(e){return Array.isArray(e)?e.map(a=>S(a)):e!=null&&typeof e=="object"?Object.keys(e).reduce((a,c)=>({...a,[Q(c)]:S(e[c])}),{}):e}function p(e,a){return typeof e=="object"?e:a(e)}function ce(e,a){return typeof a=="string"?e.object(a):typeof a=="object"&&a.$kind?a:e.object(a.contract.pool)}function $(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 X.normalizeStructTag(e)}function q(e){const a=(e||0)/Math.pow(10,27);return a>Math.pow(10,5)?1/0:a}new V.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const re=27,U=(e,a)=>{if(!Number(e)||!Number(a))return new j(0);const c=new j(1).shiftedBy(1*re),t=c.multipliedBy(new j(.5));return new j(e).multipliedBy(new j(a)).plus(t).dividedBy(c).integerValue(j.ROUND_DOWN)},y=I(T(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})),g=1e3*60*5;var A=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(A||{});const B=I(T(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 B({...a,cacheTime:g});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 ne=I(T(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats").then(t=>t.json())).data)),se=I(T(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 y({...t,cacheTime:g}),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=p(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[p(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),p(c,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}async function oe(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t),s=p(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),p(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 ie(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t),s=p(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),p(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 ue(e,a,c,t){const r=await y({...t,cacheTime:g}),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=p(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3),p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}const le=I(T(async e=>{const a=await y({...e}),t=(await P.getObject({id:a.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function de(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 L(e,a,c,t,r,n,s){const i=await y({...s,cacheTime:g}),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),ce(e,u),p(a,e.pure.address),p(u.id,e.pure.u8),p(t,e.pure.u64),p(r,e.pure.u64),p(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function O(e,a,c){return L(e,a,0,0,0,!1,c)}const be=I(async(e,a)=>{var l;const c=await y({...a,cacheTime:g}),t=new F.Transaction,r=(l=a==null?void 0:a.client)!=null?l:P,n=await B(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=$(s,[h.bcs.vector(D)]);return S(i[0].filter(d=>d.supply_balance!=="0"||d.borrow_balance!=="0")).map(d=>{const w=n.find(C=>C.id===d.assetId),b=U(d.supplyBalance,w.currentSupplyIndex).toString(),m=U(d.borrowBalance,w.currentBorrowIndex).toString();return{...d,supplyBalance:b,borrowBalance:m,pool:w}}).filter(d=>!!d.pool)});async function pe(e,a){var s;const c=(s=a==null?void 0:a.client)!=null?s:P,t=new F.Transaction;await O(t,e,a);const r=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=$(r,[h.bcs.u256()]);return q(Number(n[0])||0)}async function fe(e,a,c,t){var b;const r=(b=t==null?void 0:t.client)!=null?b:P,n=new F.Transaction;let s=0,i=0;const u=await v(a,t);if(c.forEach(m=>{m.type===A.Supply?s+=m.amount:m.type===A.Withdraw?s-=m.amount:m.type===A.Borrow?i+=m.amount:m.type===A.Repay&&(i-=m.amount)}),s*i<0)throw new Error("Invalid operations");const l=s>0||i>0;await L(n,e,u,Math.abs(s),Math.abs(i),l,t);const d=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),w=$(d,[h.bcs.u256()]);return q(Number(w[0])||0)}const ge=T(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 me(e,a){var n;let c=null;const t=[],r=(n=a==null?void 0:a.client)!=null?n:P;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 G=new V.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function z(e){try{const a=[],c=await G.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 W(e,a,c){var n;const t=(n=c==null?void 0:c.client)!=null?n:P,r=await y({...c,cacheTime:g});try{const s=await G.getPriceFeedsUpdateData(a);return await new V.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 ye(e,a,c){const t=await y({...c,cacheTime:g});if(c!=null&&c.updatePythPriceFeeds){const r=a.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await z(r);n.length>0&&await W(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 Y(e){return(await y({...e,cacheTime:g})).oracle.feeds}function we(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 k=I(T(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 he(e,a){return(await k(a)).find(t=>typeof e=="string"?f(t.coinType)===f(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function ve(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t);if(!(await k({...t,cacheTime:g})).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),p(c,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}async function Ce(e,a,c,t,r){const n=await y({...r,cacheTime:g}),s=await v(a,r);if(!(await k({...r,cacheTime:g})).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),p(c,e.object),p(t,e.object)],typeArguments:[s.suiCoinType]});return[l]}async function Te(e,a,c,t,r,n){const s={...n,cacheTime:g},i=await y(s),u=await v(a,s),l=await v(t,s),[d,w]=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),p(c,e.object),e.pure.u8(l.id),e.object(l.contract.pool),p(r,e.pure.address),e.object(i.incentiveV2),e.object(i.incentiveV3)],typeArguments:[u.suiCoinType,l.suiCoinType]});return[d,w]}async function _e(e,a){var d;const c=await Y(a),t=await B(a),r=(d=a==null?void 0:a.client)!=null?d:P,n=await y({...a,cacheTime:g}),s=new F.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=$(i,[h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.u8()),h.bcs.vector(h.bcs.Address),h.bcs.vector(h.bcs.u256())]),l=[];if(u.length===5&&Array.isArray(u[0])){const w=u[0].length;for(let b=0;b<w;b++){const m=c.find(_=>f(_.coinType)===f(u[1][b])),C=t.find(_=>f(_.coinType)===f(u[0][b]));!m||!C||l.push({assetId:C.id,assetCoinType:f(u[0][b]),rewardCoinType:f(u[1][b]),option:Number(u[2][b]),userClaimableReward:Number(u[4][b])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(u[3][b])?u[3][b]:[u[3][b]]})}}return l}function je(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 Ie=T(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}),Pe=T(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 S({data:t.data.rewards})});async function Ae(e,a,c){var i;const t=await y({...c,cacheTime:g}),r=await B({...c,cacheTime:g}),n=new Map;for(const u of a){const{rewardCoinType:l,ruleIds:d}=u;for(const w of d){n.has(l)||n.set(l,{assetIds:[],ruleIds:[],amount:0});const b=n.get(l);b.assetIds.push(u.assetCoinType.replace("0x","")),b.ruleIds.push(w),b.amount+=u.userClaimableReward}}const s=[];for(const[u,{assetIds:l,ruleIds:d,amount:w}]of n){const b=r.find(C=>f(C.suiCoinType)===f(u));if(!b||!b.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${u}`);const m=b.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 C;c.accountCap?C=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(m),e.pure.vector("string",l),e.pure.vector("address",d),p(c.accountCap,e.object)],typeArguments:[u]}):C=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",d)],typeArguments:[u]});const[_]=e.moveCall({target:"0x2::coin::from_balance",arguments:[C],typeArguments:[u]});if((c==null?void 0:c.customCoinReceive.type)==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([_],p(c.customCoinReceive.transfer,e.pure.address))}if((c==null?void 0:c.customCoinReceive.type)==="depositNAVI"){const J=j(b.totalSupplyAmount).shiftedBy(-9),K=j(b.supplyCapCeiling).shiftedBy(-27);J.plus(w).isGreaterThan(K)&&((i=c==null?void 0:c.customCoinReceive.depositNAVI)!=null&&i.fallbackReceiveAddress)?e.transferObjects([_],e.pure.address(c.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await H(e,b,_,c)}else s.push({coin:_,identifier:b})}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(m),e.pure.vector("string",l),e.pure.vector("address",d)],typeArguments:[u]})}return s}async function Be(e,a){const c=await y({...a});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=g;exports.FlashLoanAssetConfig=te;exports.IncentiveAPYInfo=Z;exports.IncentivePoolInfo=N;exports.IncentivePoolInfoByPhase=x;exports.OracleInfo=ee;exports.PoolOperator=A;exports.ReserveDataInfo=ae;exports.UserStateInfo=D;exports.borrowCoinPTB=ie;exports.claimLendingRewardsPTB=Ae;exports.createAccountCapPTB=Be;exports.depositCoinPTB=H;exports.filterPriceFeeds=we;exports.flashloanPTB=ve;exports.getAllFlashLoanAssets=k;exports.getBorrowFee=le;exports.getCoins=me;exports.getConfig=y;exports.getFees=se;exports.getFlashLoanAsset=he;exports.getHealthFactor=pe;exports.getHealthFactorPTB=O;exports.getLendingState=be;exports.getPool=v;exports.getPools=B;exports.getPriceFeeds=Y;exports.getPythStalePriceFeedId=z;exports.getSimulatedHealthFactor=fe;exports.getSimulatedHealthFactorPTB=L;exports.getStats=ne;exports.getTransactions=ge;exports.getUserAvailableLendingRewards=_e;exports.getUserClaimedRewardHistory=Pe;exports.getUserTotalClaimedReward=Ie;exports.liquidatePTB=Te;exports.mergeCoinsPTB=de;exports.normalizeCoinType=f;exports.parseTxValue=p;exports.repayCoinPTB=ue;exports.repayFlashLoanPTB=Ce;exports.summaryLendingRewards=je;exports.updateOraclePricesPTB=ye;exports.updatePythPriceFeeds=W;exports.withCache=I;exports.withSingleton=T;exports.withdrawCoinPTB=oe;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@mysten/sui/transactions"),o=require("@mysten/bcs"),E=require("@mysten/sui/client"),Q=require("lodash.camelcase"),X=require("@mysten/sui/utils"),V=require("@pythnetwork/pyth-sui-js"),j=require("bignumber.js"),h=require("@mysten/sui/bcs"),R=o.bcs.bytes(32).transform({input:e=>o.fromHex(e),output:e=>o.toHex(e)}),Z=o.bcs.struct("IncentiveAPYInfo",{asset_id:o.bcs.u8(),apy:o.bcs.u256(),coin_types:o.bcs.vector(o.bcs.string())}),N=o.bcs.struct("IncentivePoolInfo",{pool_id:R,funds:R,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()}),x=o.bcs.struct("IncentivePoolInfoByPhase",{phase:o.bcs.u64(),pools:o.bcs.vector(N)}),ee=o.bcs.struct("OracleInfo",{oracle_id:o.bcs.u8(),price:o.bcs.u256(),decimals:o.bcs.u8(),valid:o.bcs.bool()}),te=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()}),ae=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()}),D=o.bcs.struct("UserStateInfo",{asset_id:o.bcs.u8(),borrow_balance:o.bcs.u256(),supply_balance:o.bcs.u256()}),P=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function M(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 T(e){const a={};return(...c)=>{const t=M(c);return a[t]||(a[t]=e(...c).finally(()=>{a[t]=null})),a[t]}}function I(e){let a={};return(...c)=>{const t=c[c.length-1],r=M(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 S(e){return Array.isArray(e)?e.map(a=>S(a)):e!=null&&typeof e=="object"?Object.keys(e).reduce((a,c)=>({...a,[Q(c)]:S(e[c])}),{}):e}function p(e,a){return typeof e=="object"?e:a(e)}function ce(e,a){return typeof a=="string"?e.object(a):typeof a=="object"&&a.$kind?a:e.object(a.contract.pool)}function $(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 X.normalizeStructTag(e)}function q(e){const a=(e||0)/Math.pow(10,27);return a>Math.pow(10,5)?1/0:a}new V.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const re=27,U=(e,a)=>{if(!Number(e)||!Number(a))return new j(0);const c=new j(1).shiftedBy(1*re),t=c.multipliedBy(new j(.5));return new j(e).multipliedBy(new j(a)).plus(t).dividedBy(c).integerValue(j.ROUND_DOWN)},y=I(T(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})),g=1e3*60*5;var A=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(A||{});const B=I(T(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 B({...a,cacheTime:g});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 ne=I(T(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats").then(t=>t.json())).data)),se=I(T(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 y({...t,cacheTime:g}),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=p(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[p(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),p(c,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}async function oe(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t),s=p(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),p(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 ie(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t),s=p(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),p(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 ue(e,a,c,t){const r=await y({...t,cacheTime:g}),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=p(t.amount,e.pure.u64):i=e.moveCall({target:"0x2::coin::value",arguments:[p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3),p(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),p(c,e.object),i,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}const le=I(T(async e=>{const a=await y({...e}),t=(await P.getObject({id:a.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function de(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 L(e,a,c,t,r,n,s){const i=await y({...s,cacheTime:g}),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),ce(e,u),p(a,e.pure.address),p(u.id,e.pure.u8),p(t,e.pure.u64),p(r,e.pure.u64),p(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function O(e,a,c){return L(e,a,0,0,0,!1,c)}const be=I(async(e,a)=>{var l;const c=await y({...a,cacheTime:g}),t=new F.Transaction,r=(l=a==null?void 0:a.client)!=null?l:P,n=await B(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=$(s,[h.bcs.vector(D)]);return S(i[0].filter(d=>d.supply_balance!=="0"||d.borrow_balance!=="0")).map(d=>{const w=n.find(C=>C.id===d.assetId),b=U(d.supplyBalance,w.currentSupplyIndex).toString(),m=U(d.borrowBalance,w.currentBorrowIndex).toString();return{...d,supplyBalance:b,borrowBalance:m,pool:w}}).filter(d=>!!d.pool)});async function pe(e,a){var s;const c=(s=a==null?void 0:a.client)!=null?s:P,t=new F.Transaction;await O(t,e,a);const r=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=$(r,[h.bcs.u256()]);return q(Number(n[0])||0)}async function fe(e,a,c,t){var b;const r=(b=t==null?void 0:t.client)!=null?b:P,n=new F.Transaction;let s=0,i=0;const u=await v(a,t);if(c.forEach(m=>{m.type===A.Supply?s+=m.amount:m.type===A.Withdraw?s-=m.amount:m.type===A.Borrow?i+=m.amount:m.type===A.Repay&&(i-=m.amount)}),s*i<0)throw new Error("Invalid operations");const l=s>0||i>0;await L(n,e,u,Math.abs(s),Math.abs(i),l,t);const d=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),w=$(d,[h.bcs.u256()]);return q(Number(w[0])||0)}const ge=T(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 me(e,a){var n;let c=null;const t=[],r=(n=a==null?void 0:a.client)!=null?n:P;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 G=new V.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function z(e){try{const a=[],c=await G.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 W(e,a,c){var n;const t=(n=c==null?void 0:c.client)!=null?n:P,r=await y({...c,cacheTime:g});try{const s=await G.getPriceFeedsUpdateData(a);return await new V.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 ye(e,a,c){const t=await y({...c,cacheTime:g});if(c!=null&&c.updatePythPriceFeeds){const r=a.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await z(r);n.length>0&&await W(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 Y(e){return(await y({...e,cacheTime:g})).oracle.feeds}function we(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 k=I(T(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 he(e,a){return(await k(a)).find(t=>typeof e=="string"?f(t.coinType)===f(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function ve(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t);if(!(await k({...t,cacheTime:g})).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),p(c,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}async function Ce(e,a,c,t,r){const n=await y({...r,cacheTime:g}),s=await v(a,r);if(!(await k({...r,cacheTime:g})).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),p(c,e.object),p(t,e.object)],typeArguments:[s.suiCoinType]});return[l]}async function Te(e,a,c,t,r,n){const s={...n,cacheTime:g},i=await y(s),u=await v(a,s),l=await v(t,s),[d,w]=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),p(c,e.object),e.pure.u8(l.id),e.object(l.contract.pool),p(r,e.pure.address),e.object(i.incentiveV2),e.object(i.incentiveV3)],typeArguments:[u.suiCoinType,l.suiCoinType]});return[d,w]}async function _e(e,a){var d;const c=await Y(a),t=await B({...a,cacheTime:g}),r=(d=a==null?void 0:a.client)!=null?d:P,n=await y({...a,cacheTime:g}),s=new F.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=$(i,[h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.u8()),h.bcs.vector(h.bcs.Address),h.bcs.vector(h.bcs.u256())]),l=[];if(u.length===5&&Array.isArray(u[0])){const w=u[0].length;for(let b=0;b<w;b++){const m=c.find(_=>f(_.coinType)===f(u[1][b])),C=t.find(_=>f(_.coinType)===f(u[0][b]));!m||!C||l.push({assetId:C.id,assetCoinType:f(u[0][b]),rewardCoinType:f(u[1][b]),option:Number(u[2][b]),userClaimableReward:Number(u[4][b])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(u[3][b])?u[3][b]:[u[3][b]]})}}return l}function je(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 Ie=T(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}),Pe=T(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 S({data:t.data.rewards})});async function Ae(e,a,c){var i;const t=await y({...c,cacheTime:g}),r=await B({...c,cacheTime:g}),n=new Map;for(const u of a){const{rewardCoinType:l,ruleIds:d}=u;for(const w of d){n.has(l)||n.set(l,{assetIds:[],ruleIds:[],amount:0});const b=n.get(l);b.assetIds.push(u.assetCoinType.replace("0x","")),b.ruleIds.push(w),b.amount+=u.userClaimableReward}}const s=[];for(const[u,{assetIds:l,ruleIds:d,amount:w}]of n){const b=r.find(C=>f(C.suiCoinType)===f(u));if(!b||!b.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${u}`);const m=b.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 C;c.accountCap?C=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(m),e.pure.vector("string",l),e.pure.vector("address",d),p(c.accountCap,e.object)],typeArguments:[u]}):C=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",d)],typeArguments:[u]});const[_]=e.moveCall({target:"0x2::coin::from_balance",arguments:[C],typeArguments:[u]});if((c==null?void 0:c.customCoinReceive.type)==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([_],p(c.customCoinReceive.transfer,e.pure.address))}if((c==null?void 0:c.customCoinReceive.type)==="depositNAVI"){const J=j(b.totalSupplyAmount).shiftedBy(-9),K=j(b.supplyCapCeiling).shiftedBy(-27);J.plus(w).isGreaterThan(K)&&((i=c==null?void 0:c.customCoinReceive.depositNAVI)!=null&&i.fallbackReceiveAddress)?e.transferObjects([_],e.pure.address(c.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await H(e,b,_,c)}else s.push({coin:_,identifier:b})}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(m),e.pure.vector("string",l),e.pure.vector("address",d)],typeArguments:[u]})}return s}async function Be(e,a){const c=await y({...a});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=g;exports.FlashLoanAssetConfig=te;exports.IncentiveAPYInfo=Z;exports.IncentivePoolInfo=N;exports.IncentivePoolInfoByPhase=x;exports.OracleInfo=ee;exports.PoolOperator=A;exports.ReserveDataInfo=ae;exports.UserStateInfo=D;exports.borrowCoinPTB=ie;exports.claimLendingRewardsPTB=Ae;exports.createAccountCapPTB=Be;exports.depositCoinPTB=H;exports.filterPriceFeeds=we;exports.flashloanPTB=ve;exports.getAllFlashLoanAssets=k;exports.getBorrowFee=le;exports.getCoins=me;exports.getConfig=y;exports.getFees=se;exports.getFlashLoanAsset=he;exports.getHealthFactor=pe;exports.getHealthFactorPTB=O;exports.getLendingState=be;exports.getPool=v;exports.getPools=B;exports.getPriceFeeds=Y;exports.getPythStalePriceFeedId=z;exports.getSimulatedHealthFactor=fe;exports.getSimulatedHealthFactorPTB=L;exports.getStats=ne;exports.getTransactions=ge;exports.getUserAvailableLendingRewards=_e;exports.getUserClaimedRewardHistory=Pe;exports.getUserTotalClaimedReward=Ie;exports.liquidatePTB=Te;exports.mergeCoinsPTB=de;exports.normalizeCoinType=f;exports.parseTxValue=p;exports.repayCoinPTB=ue;exports.repayFlashLoanPTB=Ce;exports.summaryLendingRewards=je;exports.updateOraclePricesPTB=ye;exports.updatePythPriceFeeds=W;exports.withCache=I;exports.withSingleton=T;exports.withdrawCoinPTB=oe;
2
2
  //# sourceMappingURL=index.cjs.js.map