@naviprotocol/lending 1.0.0 → 1.0.2

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 ADDED
@@ -0,0 +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 +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,EAA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AAM,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/index.cjs.js CHANGED
@@ -1,2 +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;
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"),J=require("lodash.camelcase"),K=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)}),Q=o.bcs.struct("IncentiveAPYInfo",{asset_id:o.bcs.u8(),apy:o.bcs.u256(),coin_types:o.bcs.vector(o.bcs.string())}),D=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(D)}),Z=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()}),ee=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()}),M=o.bcs.struct("UserStateInfo",{asset_id:o.bcs.u8(),borrow_balance:o.bcs.u256(),supply_balance:o.bcs.u256()}),_=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function N(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=N(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=N(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 B(e){return Array.isArray(e)?e.map(a=>B(a)):e!=null&&typeof e=="object"?Object.keys(e).reduce((a,c)=>({...a,[J(c)]:B(e[c])}),{}):e}function b(e,a){return typeof e=="object"?e:a(e)}function te(e,a){return typeof a=="string"?e.object(a):typeof a=="object"&&a.$kind?a:e.object(a.contract.pool)}function S(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 p(e){return K.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 ae=27,U=(e,a)=>{if(!Number(e)||!Number(a))return new j(0);const c=new j(1).shiftedBy(1*ae),t=c.multipliedBy(new j(.5));return new j(e).multipliedBy(new j(a)).plus(t).dividedBy(c).integerValue(j.ROUND_DOWN)},y=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})),g=1e3*60*5;var P=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(P||{});const I=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 I({...a,cacheTime:g});if(typeof e=="object")return e;const t=c.find(r=>typeof e=="string"?p(r.suiCoinType)===p(e):typeof e=="number"?r.id===e:!1);if(!t)throw new Error("Pool not found");return t}const ce=T(C(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats").then(t=>t.json())).data)),re=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 y({...t,cacheTime:g}),n=await v(a,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(p(n.suiCoinType)===p("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 ne(e,a,c,t){const r=await y({...t,cacheTime:g}),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 se(e,a,c,t){const r=await y({...t,cacheTime:g}),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 oe(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(p(n.suiCoinType)===p("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}const ie=T(C(async e=>{const a=await y({...e}),t=(await _.getObject({id:a.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function ue(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(p(i)===p("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),te(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 O(e,a,c){return L(e,a,0,0,0,!1,c)}const le=T(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:_,n=await I(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(s,[h.bcs.vector(M)]);return B(i[0].filter(d=>d.supply_balance!=="0"||d.borrow_balance!=="0")).map(d=>{const w=n.find(A=>A.id===d.assetId),f=U(d.supplyBalance,w.currentSupplyIndex).toString(),m=U(d.borrowBalance,w.currentBorrowIndex).toString();return{...d,supplyBalance:f,borrowBalance:m,pool:w}}).filter(d=>!!d.pool)});async function de(e,a){var s;const c=(s=a==null?void 0:a.client)!=null?s:_,t=new F.Transaction;await O(t,e,a);const r=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=S(r,[h.bcs.u256()]);return q(Number(n[0])||0)}async function be(e,a,c,t){var f;const r=(f=t==null?void 0:t.client)!=null?f:_,n=new F.Transaction;let s=0,i=0;const u=await v(a,t);if(c.forEach(m=>{m.type===P.Supply?s+=m.amount:m.type===P.Withdraw?s-=m.amount:m.type===P.Borrow?i+=m.amount:m.type===P.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=S(d,[h.bcs.u256()]);return q(Number(w[0])||0)}const pe=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 fe(e,a){var n;let c=null;const t=[],r=(n=a==null?void 0:a.client)!=null?n:_;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:_,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 ge(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 me(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 $=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 ye(e,a){return(await $(a)).find(t=>typeof e=="string"?p(t.coinType)===p(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function we(e,a,c,t){const r=await y({...t,cacheTime:g}),n=await v(a,t);if(!(await $({...t,cacheTime:g})).some(d=>p(d.coinType)===p(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 he(e,a,c,t,r){const n=await y({...r,cacheTime:g}),s=await v(a,r);if(!(await $({...r,cacheTime:g})).some(d=>p(d.coinType)===p(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 ve(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),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,w]}async function Ce(e,a){var d;const c=await Y(a),t=await I(a),r=(d=a==null?void 0:a.client)!=null?d:_,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=S(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 f=0;f<w;f++){const m=c.find(k=>p(k.coinType)===p(u[1][f])),A=t.find(k=>p(k.coinType)===p(u[0][f]));!m||!A||l.push({assetId:A.id,assetCoinType:p(u[0][f]),rewardCoinType:p(u[1][f]),option:Number(u[2][f]),userClaimableReward:Number(u[4][f])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(u[3][f])?u[3][f]:[u[3][f]]})}}return l}function Te(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 _e=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}),je=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 B({data:t.data.rewards})});async function Pe(e,a,c){const t=await y({...c,cacheTime:g}),r=await I({...c,cacheTime:g}),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 w=n.get(u);w.assetIds.push(i.assetCoinType.replace("0x","")),w.ruleIds.push(d)}}const s=[];for(const[i,{assetIds:u,ruleIds:l}]of n){const d=r.find(f=>p(f.suiCoinType)===p(i));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${i}`);const w=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 f;c.accountCap?f=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(w),e.pure.vector("string",u),e.pure.vector("address",l),b(c.accountCap,e.object)],typeArguments:[i]}):f=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(w),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[i]});const[m]=e.moveCall({target:"0x2::coin::from_balance",arguments:[f],typeArguments:[i]});if((c==null?void 0:c.customCoinReceive.type)==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([m],b(c.customCoinReceive.transfer,e.pure.address))}(c==null?void 0:c.customCoinReceive.type)==="depositNAVI"?await H(e,d,m,c):s.push({coin:m,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(w),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[i]})}return s}async function Ie(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=x;exports.IncentiveAPYInfo=Q;exports.IncentivePoolInfo=D;exports.IncentivePoolInfoByPhase=X;exports.OracleInfo=Z;exports.PoolOperator=P;exports.ReserveDataInfo=ee;exports.UserStateInfo=M;exports.borrowCoinPTB=se;exports.claimLendingRewardsPTB=Pe;exports.createAccountCapPTB=Ie;exports.depositCoinPTB=H;exports.filterPriceFeeds=me;exports.flashloanPTB=we;exports.getAllFlashLoanAssets=$;exports.getBorrowFee=ie;exports.getCoins=fe;exports.getConfig=y;exports.getFees=re;exports.getFlashLoanAsset=ye;exports.getHealthFactor=de;exports.getHealthFactorPTB=O;exports.getLendingState=le;exports.getPool=v;exports.getPools=I;exports.getPriceFeeds=Y;exports.getPythStalePriceFeedId=z;exports.getSimulatedHealthFactor=be;exports.getSimulatedHealthFactorPTB=L;exports.getStats=ce;exports.getTransactions=pe;exports.getUserAvailableLendingRewards=Ce;exports.getUserClaimedRewardHistory=je;exports.getUserTotalClaimedReward=_e;exports.liquidatePTB=ve;exports.mergeCoinsPTB=ue;exports.normalizeCoinType=p;exports.parseTxValue=b;exports.repayCoinPTB=oe;exports.repayFlashLoanPTB=he;exports.summaryLendingRewards=Te;exports.updateOraclePricesPTB=ge;exports.updatePythPriceFeeds=W;exports.withCache=T;exports.withSingleton=C;exports.withdrawCoinPTB=ne;
2
2
  //# sourceMappingURL=index.cjs.js.map