@naviprotocol/lending 1.4.5-beta.1 → 1.4.5-beta.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"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"}
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("@mysten/sui/transactions"),m=require("@mysten/bcs"),X=require("@mysten/sui/client"),_e=require("lodash.camelcase"),Te=require("@mysten/sui/utils"),Y=require("@pythnetwork/pyth-sui-js"),p=require("bignumber.js"),_=require("@mysten/sui/bcs"),G=m.bcs.bytes(32).transform({input:e=>m.fromHex(e),output:e=>m.toHex(e)}),je=m.bcs.struct("IncentiveAPYInfo",{asset_id:m.bcs.u8(),apy:m.bcs.u256(),coin_types:m.bcs.vector(m.bcs.string())}),oe=m.bcs.struct("IncentivePoolInfo",{pool_id:G,funds:G,phase:m.bcs.u64(),start_at:m.bcs.u64(),end_at:m.bcs.u64(),closed_at:m.bcs.u64(),total_supply:m.bcs.u64(),asset_id:m.bcs.u8(),option:m.bcs.u8(),factor:m.bcs.u256(),distributed:m.bcs.u64(),available:m.bcs.u256(),total:m.bcs.u256()}),Ie=m.bcs.struct("IncentivePoolInfoByPhase",{phase:m.bcs.u64(),pools:m.bcs.vector(oe)}),Pe=m.bcs.struct("OracleInfo",{oracle_id:m.bcs.u8(),price:m.bcs.u256(),decimals:m.bcs.u8(),valid:m.bcs.bool()}),Be=m.bcs.struct("FlashLoanAssetConfig",{id:m.bcs.string(),asset_id:m.bcs.u8(),coin_type:m.bcs.string(),pool_id:m.bcs.string(),rate_to_supplier:m.bcs.u64(),rate_to_treasury:m.bcs.u64(),max:m.bcs.u64(),min:m.bcs.u64()}),Ae=m.bcs.struct("ReserveDataInfo",{id:m.bcs.u8(),oracle_id:m.bcs.u8(),coin_type:m.bcs.string(),supply_cap:m.bcs.u256(),borrow_cap:m.bcs.u256(),supply_rate:m.bcs.u256(),borrow_rate:m.bcs.u256(),supply_index:m.bcs.u256(),borrow_index:m.bcs.u256(),total_supply:m.bcs.u256(),total_borrow:m.bcs.u256(),last_update_at:m.bcs.u64(),ltv:m.bcs.u256(),treasury_factor:m.bcs.u256(),treasury_balance:m.bcs.u256(),base_rate:m.bcs.u256(),multiplier:m.bcs.u256(),jump_rate_multiplier:m.bcs.u256(),reserve_factor:m.bcs.u256(),optimal_utilization:m.bcs.u256(),liquidation_ratio:m.bcs.u256(),liquidation_bonus:m.bcs.u256(),liquidation_threshold:m.bcs.u256()}),ne=m.bcs.struct("UserStateInfo",{asset_id:m.bcs.u8(),borrow_balance:m.bcs.u256(),supply_balance:m.bcs.u256()}),Se="1.4.5-beta.1",M={version:Se},$e=M.version,Me=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),n=process.version,o=e.type(),r=e.arch();return`Node.js ${n.startsWith("v")?n.substring(1):n}; ${o}/${r}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},Ve=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${$e} (${Me()})`),e},x=Ve(),$=new X.SuiClient({url:X.getFullnodeUrl("mainnet")});function re(e){const n=[];return e.forEach((o,r)=>{const t=r===e.length-1;if(typeof o=="object"&&o!==null&&t){const{client:a,disableCache:i,cacheTime:c,...s}=o;n.push(s)}else n.push(o)}),JSON.stringify(n)}function j(e){const n={};return(...o)=>{const r=re(o);return n[r]||(n[r]=e(...o).finally(()=>{delete n[r]})),n[r]}}function A(e){let n={};return(...o)=>{const r=o[o.length-1],t=re(o),a=n[t];return!r?.disableCache&&typeof a?.data<"u"&&(typeof r?.cacheTime>"u"||r.cacheTime>Date.now()-a.cacheAt)?Promise.resolve(a.data):e(...o).then(i=>(n[t]={data:i,cacheAt:Date.now()},i))}}function z(e){return Array.isArray(e)?e.map(n=>z(n)):e!=null&&typeof e=="object"?Object.keys(e).reduce((n,o)=>({...n,[_e(o)]:z(e[o])}),{}):e}function g(e,n){return typeof e=="object"?e:n(e)}function Ee(e,n){return typeof n=="string"?e.object(n):typeof n=="object"&&n.$kind?n:e.object(n.contract.pool)}function H(e,n,o){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((r,t)=>(n[t]||n[0]).parse(Uint8Array.from(r[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function w(e){return Te.normalizeStructTag(e)}function ae(e){const n=(e||0)/Math.pow(10,27);return n>Math.pow(10,5)?1/0:n}new Y.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const Ue=27,ee=(e,n)=>{if(!Number(e)||!Number(n))return new p(0);const o=new p(1).shiftedBy(1*Ue),r=o.multipliedBy(new p(.5));return new p(e).multipliedBy(new p(n)).plus(r).dividedBy(o).integerValue(p.ROUND_DOWN)},E=x?{"User-Agent":x}:{};function K(e,n="uniqueId"){return e.reduce((o,r)=>(o[r[n]]=r,o),{})}function te(e,n="uniqueId"){return e.reduce((o,r)=>(o[r[n]]=r,o),{})}function q(e,n){const o=e.emodes.find(t=>t.emodeId===n.emodeId);if(!o)throw new Error("EMode not found in pool");const r=o.assets.find(t=>t.assetId===e.id);return{...e,emode:{...r,emodeId:o.emodeId},isEMode:!0}}function ce(e){const[n,o]=e.split("-");return!n||!o?null:{marketKey:n,poolId:parseInt(o)}}function P(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}var N=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(N||{});const L=A(j(async e=>{const n=(e?.markets||[V.main]).map(t=>T(t)),o=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${M.version}&market=${n.map(t=>t.key)}`,r=await fetch(o,{headers:E}).then(t=>t.json());return r.data.forEach(t=>{const i=r.meta.emodes.filter(f=>{const C=T(f.marketId);return t.market===C.key&&f.isActive}).filter(f=>!!f.assets.find(C=>C.assetId===t.id));t.emodes=i;const c=p(t.totalSupplyAmount).div(Math.pow(10,9)).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),s=p(t.borrowedAmount).shiftedBy(-9).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),l=p(c).multipliedBy(t.oracle.price).toString(),d=p(s).multipliedBy(t.oracle.price).toString(),y=p(t.supplyCapCeiling).shiftedBy(-27).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),h=p.max(p(t.borrowedAmount),p(t.validBorrowAmount)).shiftedBy(-9).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),b=p(y).multipliedBy(t.oracle.price).toString(),u=p(h).multipliedBy(t.oracle.price).toString();t.poolSupplyAmount=c,t.poolBorrowAmount=s,t.poolSupplyValue=l,t.poolBorrowValue=d,t.poolSupplyCapAmount=y,t.poolBorrowCapAmount=h,t.poolSupplyCapValue=b,t.poolBorrowCapValue=u}),r.data}));async function B(e,n){let o=n?.market;if(typeof e=="string"){const a=ce(e);a&&(o=a.marketKey,e=a.poolId)}const r=await L({...n,markets:[o||U],cacheTime:v});if(typeof e=="object")return e;const t=r.find(a=>typeof e=="string"?w(a.suiCoinType)===w(e):typeof e=="number"?a.id===e:!1);if(!t)throw new Error("Pool not found");return t.isDeprecated&&console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`),t}const De=A(j(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${M.version}`;return(await fetch(n,{headers:E}).then(r=>r.json())).data})),Oe=A(j(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${M.version}`;return await fetch(n,{headers:E}).then(r=>r.json())}));async function se(e,n,o,r){const t=await k({...r,cacheTime:v}),a=await B(n,r);r?.market;const i=r?.env||"prod";if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const c=typeof o=="object"&&o.$kind==="GasCoin";if(w(a.suiCoinType)===w("0x2::sui::SUI")&&c){if(!r?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[r.amount])}let s;return typeof r?.amount<"u"?s=g(r.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),r?.accountCap?e.moveCall({target:`${t.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]}):e.moveCall({target:`${t.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),s,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),t.version===2&&a.token.symbol==="SUI"&&i==="prod"&&e.moveCall({target:`${t.package}::pool::refresh_stake`,arguments:[e.object(a.contract.pool),e.object("0x05")]}),e}async function Fe(e,n,o,r){const t=await k({...r,cacheTime:v}),a=await B(n,r),i=g(o,e.pure.u64);let c;if(t.version===1)if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=l}else if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[c],typeArguments:[a.suiCoinType]})}async function Ne(e,n,o,r){const t=await k({...r,cacheTime:v}),a=await B(n,r);if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const i=g(o,e.pure.u64);let c;if(t.version===1)if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=l}else if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(c)],typeArguments:[a.suiCoinType]})}async function Re(e,n,o,r){const t=await k({...r,cacheTime:v}),a=await B(n,r),i=typeof o=="object"&&o.$kind==="GasCoin";if(w(a.suiCoinType)===w("0x2::sui::SUI")&&i){if(!r?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[r.amount])}let c;if(typeof r?.amount<"u"?c=g(r.amount,e.pure.u64):c=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),r?.accountCap){const[s]=e.moveCall({target:`${t.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[s],typeArguments:[a.suiCoinType]})}else return e.moveCall({target:`${t.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),c,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),e}const Le=A(j(async e=>{const n=await k({...e});if(e?.address&&typeof e?.asset<"u")try{const t=await B(e.asset,e),a=e?.client??$,i=new R.Transaction;i.moveCall({target:`${n.package}::incentive_v3::get_borrow_fee_v2`,arguments:[i.object(n.incentiveV3),i.pure.address(e.address),i.pure.u8(t.id),i.pure.u64(1e4)],typeArguments:[]});const c=await a.devInspectTransactionBlock({transactionBlock:i,sender:e.address}),s=H(c,[_.bcs.u64()]);return(Number(s[0])||0)/100}catch(t){console.error(t)}const r=(await $.getObject({id:n.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(r)/100})),U="main",V={main:{id:0,key:"main",name:"Main Market"},ember:{id:1,key:"ember",name:"Ember Market"},rwa:{id:2,key:"rwa",name:"Matrixdock Market"},"sui-eco":{id:3,key:"sui-eco",name:"Sui Eco Market"}};class ie{constructor(n,o){this.poolMap={},this.emodeMap={},this.pools=[],this.emodes=[],this.emodePools=[],this.emodeBorrowablePools=[],this.emodeSupplyablePools=[],this._overview={marketTotalSupplyValue:"0",marketTotalBorrowValue:"0"},this.config=T(n),this.initPools(o)}get overview(){return this._overview}initPools(n){const o=K(this.pools),r=te(this.emodes),t=new Set,a=new Set;let i=p(0),c=p(0);n.forEach(s=>{if(!this.checkMarket(s.market)){console.warn(`Pool is not in market ${this.config.name}`,s);return}o[s.uniqueId]||this.pools.push(s),s?.emodes?.forEach(d=>{r[d.uniqueId]||this.emodes.push(d),d.assets.forEach(y=>{y.isDebt&&d.assets.find(b=>b.isCollateral&&b.ltv>0&&b.assetId!==s.id)&&t.add(s.uniqueId),y.isCollateral&&d.assets.find(b=>b.isDebt&&b.assetId!==s.id)&&a.add(s.uniqueId)})}),c=c.plus(s.poolBorrowValue),i=i.plus(s.poolSupplyValue)}),this.poolMap=K(this.pools,"id"),this.emodeMap=te(this.emodes,"emodeId"),this.emodes.forEach(s=>{const l=this.getEModePools(s.emodeId);this.emodePools.push(...l)}),this._overview={marketTotalSupplyValue:i.toString(),marketTotalBorrowValue:c.toString()},this.emodeBorrowablePools=this.pools.filter(s=>t.has(s.uniqueId)),this.emodeSupplyablePools=this.pools.filter(s=>a.has(s.uniqueId))}getEMode(n){return this.emodeMap[n]||null}getEModeRelatePools(n,o){const{collateral:r,debt:t,emodeId:a}=o||{},i=[];return n.emodes.forEach(c=>{typeof a=="number"&&a!==c.emodeId||c.assets.forEach(s=>{typeof r=="boolean"&&r&&s.isCollateral&&s.assetId===n.id&&i.push(this.poolMap[s.assetId]),typeof t=="boolean"&&t&&s.isDebt&&s.assetId===n.id&&i.push(this.poolMap[s.assetId])})}),i}getEModePools(n){const o=this.getEMode(n);return o?o.assets.map(t=>t.assetId).map(t=>this.poolMap[t]).filter(t=>!!t).map(t=>{const a=o.assets.find(i=>i.assetId===t.id);return{...t,emode:{...a,emodeId:o.emodeId},isEMode:!0}}):[]}checkMarket(n){let o=!1;return typeof n=="number"&&n===this.config.id&&(o=!0),typeof n=="string"&&n===this.config.key&&(o=!0),typeof n=="object"&&n.id===this.config.id&&(o=!0),o}}const T=e=>{const o=Object.values(V).find(r=>typeof e=="number"?r.id===e:typeof e=="string"?r.key===e:r.id===e.id);if(!o)throw new Error("Market not found");return o},le=A(j(async(e,n)=>{const o=await L({cacheTime:6e4,...n,markets:e});return e.map(r=>{const t=T(r),a=o.filter(i=>i.market===t.key);return new ie(r,a)})})),qe=A(j(async(e,n)=>(await le([e],n))[0])),k=A(j(async e=>{const n=T(e?.market||U),o=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${M.version}&market=${n.key}`;return(await fetch(o,{headers:E}).then(t=>t.json())).data})),v=1e3*60*5;async function ue(e,n){const o=await k({cacheTime:v,...n});return e.moveCall({target:`${o.package}::lending::create_account`,arguments:[]})}async function pe(e,n,o){const r=await k({cacheTime:v,...o});return e.moveCall({target:`${r.package}::account::account_owner`,arguments:[n]})}async function de(e,n,o){const r=await k({...o,cacheTime:v});return o?.accountCap?e.moveCall({target:`${r.package}::lending::enter_emode_with_account_cap`,arguments:[e.object(r.storage),g(n,e.pure.u64),g(o.accountCap,e.object)]}):e.moveCall({target:`${r.package}::lending::enter_emode`,arguments:[e.object(r.storage),g(n,e.pure.u64)]}),e}async function He(e,n){const o=await k({...n,cacheTime:v});return n?.accountCap?e.moveCall({target:`${o.package}::lending::exit_emode_with_account_cap`,arguments:[e.object(o.storage),g(n.accountCap,e.object)]}):e.moveCall({target:`${o.package}::lending::exit_emode`,arguments:[e.object(o.storage)]}),e}async function We(e,n,o){const r=await k({cacheTime:v,...o}),t=await ue(e,o);await de(e,n,{...o,accountCap:t});const a=await T(o?.market||U),i=await pe(e,t,o);return e.moveCall({target:`${r.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,arguments:[e.object(r.emode.contract.registryObject),i,g(a.id,e.pure.u64),g(n,e.pure.u64)]}),t}const J=A(j(async(e,n)=>{const o=await k({cacheTime:v,...n}),r=new R.Transaction,t=n?.client??$;r.moveCall({target:`${o.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,arguments:[r.object(o.emode.contract.registryObject),r.pure.address(e)]});const i=(await t.devInspectTransactionBlock({transactionBlock:r,sender:e})).results[0].returnValues,c=_.bcs.vector(_.bcs.u64()).parse(Uint8Array.from(i[0][0])),s=_.bcs.vector(_.bcs.u64()).parse(Uint8Array.from(i[1][0])),l=_.bcs.vector(_.bcs.Address).parse(Uint8Array.from(i[2][0]));return c.map((d,y)=>({marketId:Number(d),emodeId:Number(s[y]),accountCap:l[y].toString()}))}));function Ge(e){return`${T(e.marketId).key}-${e.emodeId}`}function ze(e,n,o){const r=typeof o?.balance=="number",t=r?o.balance:0;let a=0;const i=[];let c="";if(n.sort((s,l)=>Number(l.balance)-Number(s.balance)).forEach(s=>{if(!(r&&a>=t)&&Number(s.balance)!==0){if(c||(c=s.coinType),c!==s.coinType)throw new Error("All coins must be of the same type");a+=Number(s.balance),i.push(s.coinObjectId)}}),i.length===0)throw new Error("No coins to merge");if(r&&a<t)throw new Error(`Balance is less than the specified balance: ${a} < ${t}`);return w(c)===w("0x2::sui::SUI")&&o?.useGasCoin?r?e.splitCoins(e.gas,[e.pure.u64(t)]):e.gas:(i.length===1?e.object(i[0]):e.mergeCoins(i[0],i.slice(1)),r?e.splitCoins(i[0],[e.pure.u64(t)]):i[0])}async function Z(e,n,o,r,t,a,i){const c=await k({...i,cacheTime:v}),s=await B(o,i);return e.moveCall({target:`${c.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(c.storage),e.object(c.oracle.priceOracle),Ee(e,s),g(n,e.pure.address),g(s.id,e.pure.u8),g(r,e.pure.u64),g(t,e.pure.u64),g(a,e.pure.bool)],typeArguments:[s.suiCoinType]})}async function me(e,n,o){return Z(e,n,0,0,0,!1,o)}async function fe(e,n,o){const r=new R.Transaction,t=o?.client??$,a=await L({...o,markets:Object.values(V)}),i=K(a);for(let d of n){const y=await k({...o,cacheTime:v,market:d.market});r.moveCall({target:`${y.uiGetter}::getter_unchecked::get_user_state`,arguments:[r.object(y.storage),r.pure.address(d.address)]})}const s=((await t.devInspectTransactionBlock({transactionBlock:r,sender:e})).results||[]).map(d=>d.returnValues?.map(y=>_.bcs.vector(ne).parse(Uint8Array.from(y[0])))[0]||[]),l=[];return s.forEach((d,y)=>{const h=n[y],b=T(h.market);d.forEach(u=>{if(u.supply_balance==="0"&&u.borrow_balance==="0"&&(h.emodeId===void 0||!o?.includeZeroBalanceEmodePositions))return;const f=i[`${b.key}-${u.asset_id}`];if(!f)return;const C=ee(u.supply_balance,f.currentSupplyIndex).toString(),I=ee(u.borrow_balance,f.currentBorrowIndex).toString();l.push({supplyBalance:C,borrowBalance:I,assetId:u.asset_id,market:b.key,pool:f,emodeId:h.emodeId})})}),l}const Ke=A(async(e,n)=>{const r=(n?.markets||Object.keys(V)).map(t=>T(t)).map(t=>({address:e,market:t.key}));return await fe(e,r,n)});async function Ye(e,n){const o=n?.client??$,r=new R.Transaction;await me(r,e,n);const t=await o.devInspectTransactionBlock({transactionBlock:r,sender:e}),a=H(t,[_.bcs.u256()]);return ae(Number(a[0])||0)}async function Je(e,n,o,r){const t=r?.client??$,a=new R.Transaction;let i=0,c=0;const s=await B(n,r);if(o.forEach(h=>{h.type===N.Supply?i+=h.amount:h.type===N.Withdraw?i-=h.amount:h.type===N.Borrow?c+=h.amount:h.type===N.Repay&&(c-=h.amount)}),i*c<0)throw new Error("Invalid operations");const l=i>0||c>0;await Z(a,e,s,Math.abs(i),Math.abs(c),l,r);const d=await t.devInspectTransactionBlock({transactionBlock:a,sender:e}),y=H(d,[_.bcs.u256()]);return ae(Number(y[0])||0)}const Ze=j(async(e,n)=>{const o=new URLSearchParams;n?.cursor&&o.set("cursor",n.cursor),o.set("userAddress",e);const r=`https://open-api.naviprotocol.io/api/navi/user/transactions?${o.toString()}&sdk=${M.version}`;return(await fetch(r,{headers:E}).then(a=>a.json())).data});async function Qe(e,n){let o=null;const r=[],t=n?.client??$;do{let a;if(n?.coinType?a=await t.getCoins({owner:e,coinType:n?.coinType,cursor:o,limit:100}):a=await t.getAllCoins({owner:e,cursor:o,limit:100}),!a.data||!a.data.length)break;r.push(...a.data),o=a.nextCursor}while(o);return r}const ge=A(async(e,n)=>{const o=[],r=(n?.markets||Object.keys(V)).map(c=>T(c));let t=[];try{t=await J(e,n)}catch(c){console.error(c)}const a=r.map(c=>({address:e,market:c.key})).concat(t.filter(c=>!!r.find(s=>s.id===c.marketId)).map(c=>({address:c.accountCap,market:T(c.marketId).key,emodeId:c.emodeId})));return(await fe(e,a,n)).forEach(c=>{const s=typeof c.emodeId=="number"?t.find(l=>{const d=T(c.market);return l.emodeId===c.emodeId&&l.marketId===d.id}):void 0;if(s){if(!c.pool.emodes.find(d=>d.emodeId===s.emodeId))return;if(p(c.supplyBalance).gte(0)){const d=p(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN),y=q(c.pool,s);if(d.gt(0)||y.emode.isCollateral)try{o.push({id:`${c.pool.uniqueId}_${s.emodeId}_navi-lending-emode-supply-${P()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:d.toString(),pool:q(c.pool,s),token:c.pool.token,valueUSD:d.multipliedBy(c.pool.oracle.price).toString(),emodeCap:s}})}catch(h){console.error(h)}}if(p(c.borrowBalance).gte(0)){const d=p(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN),y=q(c.pool,s);if(d.gt(0)||y.emode.isDebt)try{o.push({id:`${c.pool.uniqueId}_${s.emodeId}_navi-lending-emode-borrow-${P()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:d.toString(),pool:q(c.pool,s),token:c.pool.token,valueUSD:d.multipliedBy(c.pool.oracle.price).toString(),emodeCap:s}})}catch(h){console.error(h)}}}else{if(p(c.supplyBalance).gt(0)){const l=p(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-supply-${P()}`,wallet:e,protocol:"navi",type:"navi-lending-supply",market:c.market,"navi-lending-supply":{amount:l.toString(),pool:c.pool,token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString()}})}if(p(c.borrowBalance).gt(0)){const l=p(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-borrow-${P()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-borrow","navi-lending-borrow":{amount:l.toString(),pool:c.pool,token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString()}})}}}),o});class O{constructor(n,o){this._positions=[],this._priceMap={},this._overview={hf:1/0,netVaule:"0",netWorthApr:"0",totalSupplyValue:"0",totalBorrowValue:"0",totalsupplyApy:"0",totalBorrowApy:"0",maxLiquidationValue:"0",maxLoanToVaule:"0",supply:{},borrow:{}},this._priceMap=o||{},this.positions=n}get positions(){return this._positions}get overview(){return this._overview}get priceMap(){return this._priceMap}set positions(n){this._positions=n,this._overview=this.getPositionsOverview(n)}updatePriceMap(n){return this._priceMap=n,this._overview=this.getPositionsOverview(this._positions),this}getPrice(n){const o=w(n.suiCoinType);if(this._priceMap[o]!==void 0)return this._priceMap[o].toString();const r=n.suiCoinType;return this._priceMap[r]!==void 0?this._priceMap[r].toString():n.oracle.price}filterPositionsByPool(n){const r=!!n.isEMode?["navi-lending-emode-supply","navi-lending-emode-borrow"]:["navi-lending-supply","navi-lending-borrow"];return new O(this.positions.filter(t=>{const a=t[t.type];return r.includes(t.type)&&a.pool.uniqueId===n.uniqueId}),this._priceMap)}deposit(n,o){const r=!!n.isEMode,t=this.getPrice(n);let a;return r?a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:n.token,pool:n,emodeCap:{}}}:a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:n.token,pool:n}},new O([...this.positions,a],this._priceMap)}withdraw(n,o){const r=!!n.isEMode,t=this.getPrice(n);let a;return r?a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:n.token,pool:n,emodeCap:{}}}:a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:n.token,pool:n}},new O([...this.positions,a],this._priceMap)}borrow(n,o){const r=!!n.isEMode,t=this.getPrice(n);let a;return r?a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:n.token,pool:n,emodeCap:{}}}:a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:n.token,pool:n}},new O([...this.positions,a],this._priceMap)}repay(n,o){const r=!!n.isEMode,t=this.getPrice(n);let a;return r?a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:n.token,pool:n,emodeCap:{}}}:a={id:P(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:n.token,pool:n}},new O([...this.positions,a],this._priceMap)}resolveValueUSD(n){return Object.keys(this._priceMap).length>0?p(n.amount).multipliedBy(this.getPrice(n.pool)).toString():n.valueUSD}getPositionsOverview(n){const o={},r={};let t=new p(0),a=new p(0),i=new p(0),c=new p(0),s=new p(0),l=new p(0);n.forEach(b=>{if(b.type==="navi-lending-supply"){const u=b["navi-lending-supply"],f=this.resolveValueUSD(u);t=t.plus(f),s=s.plus(new p(f).multipliedBy(u.pool.liquidationFactor.threshold)),l=l.plus(new p(f).multipliedBy(u.pool.ltvValue))}else if(b.type==="navi-lending-borrow"){const u=b["navi-lending-borrow"];a=a.plus(this.resolveValueUSD(u))}else if(b.type==="navi-lending-emode-supply"){const u=b["navi-lending-emode-supply"],f=this.resolveValueUSD(u);t=t.plus(f);const C=u.pool.emode;s=s.plus(new p(f).multipliedBy(C.lt)),l=l.plus(new p(f).multipliedBy(C.ltv))}else if(b.type==="navi-lending-emode-borrow"){const u=b["navi-lending-emode-borrow"];a=a.plus(this.resolveValueUSD(u))}}),a=p.max(a,0),t=p.max(t,0),s=p.max(s,0),l=p.max(l,0),n.forEach(b=>{if(b.type==="navi-lending-supply"){const u=b["navi-lending-supply"],f=this.resolveValueUSD(u),C=u.pool.supplyIncentiveApyInfo.apy;t.gt(0)&&(i=i.plus(new p(f).dividedBy(t).multipliedBy(new p(C).dividedBy(100)))),o[u.pool.suiCoinType]=p(o[u.pool.suiCoinType]||0).plus(u.amount).toString()}else if(b.type==="navi-lending-borrow"){const u=b["navi-lending-borrow"],f=this.resolveValueUSD(u),C=u.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new p(f).dividedBy(a).multipliedBy(new p(C).dividedBy(100)))),r[u.pool.suiCoinType]=p(r[u.pool.suiCoinType]||0).plus(u.amount).toString()}else if(b.type==="navi-lending-emode-supply"){const u=b["navi-lending-emode-supply"],f=this.resolveValueUSD(u),C=u.pool.supplyIncentiveApyInfo.apy;t.gt(0)&&(i=i.plus(new p(f).dividedBy(t).multipliedBy(new p(C).dividedBy(100)))),o[u.pool.suiCoinType]=p(o[u.pool.suiCoinType]||0).plus(u.amount).toString()}else if(b.type==="navi-lending-emode-borrow"){const u=b["navi-lending-emode-borrow"],f=this.resolveValueUSD(u),C=u.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new p(f).dividedBy(a).multipliedBy(new p(C).dividedBy(100)))),r[u.pool.suiCoinType]=p(r[u.pool.suiCoinType]||0).plus(u.amount).toString()}});const d=t.minus(a),y=t.minus(a).eq(0)?new p(0):t.multipliedBy(i).minus(a.multipliedBy(c)).div(t.minus(a));return{hf:a.toNumber()!==0?s.dividedBy(a).toNumber():1/0,netVaule:d.toString(),netWorthApr:y.toString(),totalSupplyValue:t.toString(),totalBorrowValue:a.toString(),totalsupplyApy:i.toString(),totalBorrowApy:c.toString(),maxLiquidationValue:s.toString(),maxLoanToVaule:l.toString(),supply:o,borrow:r}}}async function Xe(e,n,o,r){const t=await k({...r,cacheTime:v});t.limter&&e.moveCall({target:`${t.limter}::navi_adaptor::verify_navi_position_healthy`,arguments:[e.object("0x06"),e.object(t.storage),e.object(t.priceOracle),g(n,e.pure.address),e.pure.u256(new p(o).shiftedBy(27).toNumber())]})}const ye=new Y.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function xe(e){try{const n=[],o=await ye.getLatestPriceFeeds(e);if(!o)return n;const r=Math.floor(new Date().valueOf()/1e3);for(const t of o){const a=t.getPriceUnchecked();if(a.publishTime>r){console.warn(`pyth price feed is invalid, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${r}`);continue}r-t.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${r}`),n.push(t.id))}return n}catch(n){throw new Error(`failed to get pyth stale price feed id, msg: ${n.message}`)}}async function et(e,n){try{const o=[],r=n?.client??$,t=e.map(i=>i.priceInfoObject),a=await r.multiGetObjects({ids:Array.from(new Set(t)),options:{showContent:!0}});for(const i of a){const c=i.data;if(!c||!c.content||c.content.dataType!=="moveObject"){console.warn(`fetched object ${c?.objectId} datatype should be moveObject`);continue}const s=e.find(u=>u.priceInfoObject==c.objectId);if(!s){console.warn(`unable to find pyth info from array, priceInfoObject: ${c.objectId}`);continue}const l=c.content.fields.price_info.fields.price_feed.fields.price.fields,{magnitude:d,negative:y}=l.price.fields,h=l.conf,b=l.timestamp;o.push({priceFeedId:s.priceFeedId,priceInfoObject:s.priceInfoObject,price:y?"-"+d:d,conf:h,publishTime:Number(b),expiration:s.expiration})}return o}catch(o){console.error(o,`Polling Sui on-chain price for ${e} failed.`);return}}async function be(e,n){try{const o=[],r=await et(e,n);if(!r)return o;const t=Math.floor(new Date().valueOf()/1e3);for(const a of r){if(a.publishTime>t){console.warn(`pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`);continue}const i=a.expiration||60;t-a.publishTime>i&&(console.info(`stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`),o.push(a.priceFeedId))}return o}catch(o){throw new Error(`failed to get pyth stale price feed id, msg: ${o.message}`)}}async function he(e,n,o){const r=o?.client??$,t=await k({...o,cacheTime:v});try{const a=await ye.getPriceFeedsUpdateData(n);return await new Y.SuiPythClient(r,t.oracle.pythStateId,t.oracle.wormholeStateId).updatePriceFeeds(e,a,n)}catch(a){throw new Error(`failed to update pyth price feeds, msg: ${a.message}`)}}async function ve(e,n,o){const r=await k({...o,cacheTime:v});if(o?.updatePythPriceFeeds){const t=n.filter(a=>!!a.pythPriceFeedId&&!!a.pythPriceInfoObject).map(a=>({priceFeedId:a.pythPriceFeedId,priceInfoObject:a.pythPriceInfoObject,expiration:30}));try{const a=await be(t,o);a.length>0&&await he(e,a,o)}catch{console.error("Failed to update Pyth price feeds")}}for(const t of n)o?.env==="dev"?e.moveCall({target:`${r.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(r.oracle.oracleConfig),e.object(r.oracle.priceOracle),e.object(r.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.pure.address(t.feedId)]}):e.moveCall({target:`${r.oracle.packageId}::oracle_pro::update_single_price_v2`,arguments:[e.object("0x6"),e.object(r.oracle.oracleConfig),e.object(r.oracle.priceOracle),e.object(r.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.object(r.oracle.switchboardAggregator),e.pure.address(t.feedId)]});return e}async function Q(e){return(await k({...e,cacheTime:v})).oracle.feeds}function we(e,n){return e.filter(o=>!!(n?.lendingState&&n.lendingState.find(t=>o.oracleId===t.pool.oracleId)||n?.lendingPositions&&n.lendingPositions.find(t=>{if(!["navi-lending-supply","navi-lending-borrow","navi-lending-emode-supply","navi-lending-emode-borrow"].includes(t.type))return!1;const i=t[t.type]?.pool;return o.oracleId===i?.oracleId})||n?.pools&&n.pools.find(t=>o.oracleId===t.oracleId)))}async function tt(e,n,o,r){try{const t=await Q({...r}),a=[];o.forEach(l=>{a.includes(l.market)||a.push(l.market)});const i=await ge(n,{...r,markets:a}),c=we(t,{lendingPositions:i,pools:o});return await ve(e,c,{updatePythPriceFeeds:!0,...r})}catch(t){if(r?.throws)throw t;return console.error(t),e}}const W=A(j(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${M.version}&market=${e?.market||U}`,o=await fetch(n,{headers:E}).then(r=>r.json());return Object.keys(o.data).map(r=>({...o.data[r],coinType:r}))}));async function ot(e,n){return(await W(n)).find(r=>typeof e=="string"?w(r.coinType)===w(e):typeof e=="number"?r.assetId===e:r.assetId===e.id)||null}async function nt(e,n,o,r){const t=await k({...r,cacheTime:v}),a=await B(n,r);if(!(await W({...r,cacheTime:v})).some(s=>w(s.coinType)===w(a.suiCoinType)))throw new Error("Pool does not support flashloan");if(t.version===1){const[s,l]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64)],typeArguments:[a.suiCoinType]});return[s,l]}else{const[s,l]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64),e.object("0x05")],typeArguments:[a.suiCoinType]});return[s,l]}}async function rt(e,n,o,r,t){const a=await k({...t,cacheTime:v}),i=await B(n,t);if(!(await W({...t,cacheTime:v})).some(d=>w(d.coinType)===w(i.suiCoinType)))throw new Error("Pool does not support flashloan");const[l]=e.moveCall({target:`${a.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(a.storage),e.object(i.contract.pool),g(o,e.object),g(r,e.object)],typeArguments:[i.suiCoinType]});return[l]}async function at(e,n,o,r,t,a){const i={...a,cacheTime:v},c=await k(i),s=await B(n,i),l=await B(r,i);if(c.version===1){const[d,y]=e.moveCall({target:`${c.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(s.id),e.object(s.contract.pool),g(o,e.object),e.pure.u8(l.id),e.object(l.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[s.suiCoinType,l.suiCoinType]});return[d,y]}else{const[d,y]=e.moveCall({target:`${c.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(s.id),e.object(s.contract.pool),g(o,e.object),e.pure.u8(l.id),e.object(l.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3),e.object("0x05")],typeArguments:[s.suiCoinType,l.suiCoinType]});return[d,y]}}async function ct(e,n,o){const r=o?.client??$,t=new R.Transaction,a=await L({...o,markets:Object.values(V),cacheTime:v}),i=await Q(o);for(let d of n){const y=await k({...o,cacheTime:v,market:d.market});t.moveCall({target:`${y.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[t.object("0x06"),t.object(y.storage),t.object(y.incentiveV3),t.pure.address(d.address)]})}const c=await r.devInspectTransactionBlock({transactionBlock:t,sender:e}),s=[];c?.results?.forEach(d=>{s.push(H({results:[d]},[_.bcs.vector(_.bcs.string()),_.bcs.vector(_.bcs.string()),_.bcs.vector(_.bcs.u8()),_.bcs.vector(_.bcs.Address),_.bcs.vector(_.bcs.u256())]))});const l=[];return s.forEach((d,y)=>{const h=n[y];if(d.length===5&&Array.isArray(d[0])){const b=d[0].length;for(let u=0;u<b;u++){const f=i.find(I=>w(I.coinType)===w(d[1][u])),C=a.find(I=>w(I.coinType)===w(d[0][u])&&I.market===h.market);!f||!C||l.push({assetId:C.id,assetCoinType:w(d[0][u]),rewardCoinType:w(d[1][u]),option:Number(d[2][u]),userClaimableReward:Number(d[4][u])/Math.pow(10,f.priceDecimal),ruleIds:Array.isArray(d[3][u])?d[3][u]:[d[3][u]],market:h.market,owner:h.owner,address:h.address,emodeId:h.emodeId})}}}),l}async function st(e,n){const o=(n?.markets||[V.main]).map(a=>T(a));let r=[];try{r=await J(e,n)}catch(a){console.error(a)}const t=o.map(a=>({address:e,owner:e,market:a.key})).concat(r.filter(a=>!!o.find(i=>i.id===a.marketId)).map(a=>{const i=T(a.marketId);return{address:a.accountCap,owner:e,market:i.key,emodeId:a.emodeId}}));return await ct(e,t,n)}function it(e){const n=new Map;e.forEach(r=>{const t=r.assetId,a=r.option,i=`${t}-${a}-${r.rewardCoinType}-${r.market}`;n.has(i)?n.get(i).total+=r.userClaimableReward:n.set(i,{assetId:t,rewardType:a,coinType:r.rewardCoinType,total:Number(r.userClaimableReward),market:r.market})});const o=new Map;for(const{assetId:r,rewardType:t,coinType:a,total:i,market:c}of n.values()){const s=`${r}-${t}-${c}`;o.has(s)||o.set(s,{assetId:r,rewardType:t,market:c,rewards:new Map});const l=o.get(s);l.rewards.set(a,(l.rewards.get(a)||0)+i)}return Array.from(o.values()).map(r=>({assetId:r.assetId,rewardType:r.rewardType,market:r.market,rewards:Array.from(r.rewards.entries()).map(([t,a])=>({coinType:t,available:a.toFixed(6)}))}))}const lt=j(async(e,n)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${M.version}&market=${n?.market||U}`;return(await fetch(o,{headers:E}).then(t=>t.json())).data}),ut=j(async(e,n)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${n?.page||1}&pageSize=${n?.size||400}&sdk=${M.version}&market=${n?.market||U}`,r=await fetch(o,{headers:E}).then(t=>t.json());return z({data:r.data.rewards})});async function pt(e,n,o){const r=await L({...o,markets:Object.values(V),cacheTime:v}),t=new Map;for(const i of n){const{rewardCoinType:c,ruleIds:s,market:l,owner:d,address:y,emodeId:h}=i,b=`${c}___${y}__${l}`;for(const u of s){t.has(b)||t.set(b,{assetIds:[],ruleIds:[],amount:0,market:l,owner:d,address:y,isEMode:typeof h<"u"});const f=t.get(b);f.assetIds.push(i.assetCoinType.replace("0x","")),f.ruleIds.push(u),f.amount+=i.userClaimableReward}}const a=[];for(const[i,{assetIds:c,ruleIds:s,amount:l,market:d,owner:y,address:h,isEMode:b}]of t){const u=await k({...o,cacheTime:v,market:d}),f=i.split("___")[0],C=r.filter(S=>w(S.suiCoinType)===w(f));C.sort((S,D)=>S.market===d?-1:1);const I=C[0],F=u.rewardFunds[w(f)];if(!F)throw new Error(`No matching rewardFund found for reward coin: ${f} ${d}`);if(o?.accountCap&&!o.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(o?.customCoinReceive){let S;o.accountCap?S=e.moveCall({target:`${u.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(u.incentiveV3),e.object(u.storage),e.object(F),e.pure.vector("string",c),e.pure.vector("address",s),g(o.accountCap,e.object)],typeArguments:[f]}):b?S=e.moveCall({target:`${u.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(u.incentiveV3),e.object(u.storage),e.object(F),e.pure.vector("string",c),e.pure.vector("address",s),g(h,e.object)],typeArguments:[f]}):S=e.moveCall({target:`${u.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(u.incentiveV3),e.object(u.storage),e.object(F),e.pure.vector("string",c),e.pure.vector("address",s)],typeArguments:[f]});const[D]=e.moveCall({target:"0x2::coin::from_balance",arguments:[S],typeArguments:[f]});if(o?.customCoinReceive.type==="transfer"){if(!o.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([D],g(o.customCoinReceive.transfer,e.pure.address))}if(o?.customCoinReceive.type==="depositNAVI"){const ke=p(I.totalSupplyAmount).shiftedBy(-9),Ce=p(I.supplyCapCeiling).shiftedBy(-27);ke.plus(l).isGreaterThan(Ce)&&o?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([D],e.pure.address(o.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await se(e,I,D,{...o,market:I.market})}else a.push({coin:D,identifier:I,owner:y,isEMode:b})}else if(o?.accountCap||b){const S=e.moveCall({target:`${u.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(u.incentiveV3),e.object(u.storage),e.object(F),e.pure.vector("string",c),e.pure.vector("address",s),g(o?.accountCap||h,e.object)],typeArguments:[f]}),[D]=e.moveCall({target:"0x2::coin::from_balance",arguments:[S],typeArguments:[f]});e.transferObjects([D],g(o?.accountCap||y,e.pure.address))}else e.moveCall({target:`${u.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(u.incentiveV3),e.object(u.storage),e.object(F),e.pure.vector("string",c),e.pure.vector("address",s)],typeArguments:[f]})}return a}exports.Address=G;exports.DEFAULT_CACHE_TIME=v;exports.DEFAULT_MARKET_IDENTITY=U;exports.FlashLoanAssetConfig=Be;exports.IncentiveAPYInfo=je;exports.IncentivePoolInfo=oe;exports.IncentivePoolInfoByPhase=Ie;exports.MARKETS=V;exports.Market=ie;exports.OracleInfo=Pe;exports.PoolOperator=N;exports.ReserveDataInfo=Ae;exports.UserPositions=O;exports.UserStateInfo=ne;exports.borrowCoinPTB=Ne;exports.claimLendingRewardsPTB=pt;exports.createAccountCapPTB=ue;exports.createEModeCapPTB=We;exports.depositCoinPTB=se;exports.emodeIdentityId=Ge;exports.enterEModePTB=de;exports.exitEModePTB=He;exports.filterPriceFeeds=we;exports.flashloanPTB=nt;exports.getAccountCapOwnerPTB=pe;exports.getAllFlashLoanAssets=W;exports.getBorrowFee=Le;exports.getCoins=Qe;exports.getConfig=k;exports.getFees=Oe;exports.getFlashLoanAsset=ot;exports.getHealthFactor=Ye;exports.getHealthFactorPTB=me;exports.getLendingPositions=ge;exports.getLendingState=Ke;exports.getMarket=qe;exports.getMarketConfig=T;exports.getMarkets=le;exports.getPool=B;exports.getPools=L;exports.getPriceFeeds=Q;exports.getPythStalePriceFeedId=xe;exports.getPythStalePriceFeedIdV2=be;exports.getSimulatedHealthFactor=Je;exports.getSimulatedHealthFactorPTB=Z;exports.getStats=De;exports.getTransactions=Ze;exports.getUserAvailableLendingRewards=st;exports.getUserClaimedRewardHistory=ut;exports.getUserEModeCaps=J;exports.getUserTotalClaimedReward=lt;exports.liquidatePTB=at;exports.mergeCoinsPTB=ze;exports.normalizeCoinType=w;exports.parsePoolUID=ce;exports.parseTxValue=g;exports.repayCoinPTB=Re;exports.repayFlashLoanPTB=rt;exports.summaryLendingRewards=it;exports.updateOraclePriceBeforeUserOperationPTB=tt;exports.updateOraclePricesPTB=ve;exports.updatePythPriceFeeds=he;exports.verifyHealthFactorPTB=Xe;exports.withCache=A;exports.withSingleton=j;exports.withdrawCoinPTB=Fe;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("@mysten/sui/transactions"),d=require("@mysten/bcs"),ee=require("@mysten/sui/client"),Be=require("lodash.camelcase"),Pe=require("@mysten/sui/utils"),Z=require("@pythnetwork/pyth-sui-js"),p=require("bignumber.js"),_=require("@mysten/sui/bcs"),z=d.bcs.bytes(32).transform({input:e=>d.fromHex(e),output:e=>d.toHex(e)}),Ae=d.bcs.struct("IncentiveAPYInfo",{asset_id:d.bcs.u8(),apy:d.bcs.u256(),coin_types:d.bcs.vector(d.bcs.string())}),ne=d.bcs.struct("IncentivePoolInfo",{pool_id:z,funds:z,phase:d.bcs.u64(),start_at:d.bcs.u64(),end_at:d.bcs.u64(),closed_at:d.bcs.u64(),total_supply:d.bcs.u64(),asset_id:d.bcs.u8(),option:d.bcs.u8(),factor:d.bcs.u256(),distributed:d.bcs.u64(),available:d.bcs.u256(),total:d.bcs.u256()}),Se=d.bcs.struct("IncentivePoolInfoByPhase",{phase:d.bcs.u64(),pools:d.bcs.vector(ne)}),$e=d.bcs.struct("OracleInfo",{oracle_id:d.bcs.u8(),price:d.bcs.u256(),decimals:d.bcs.u8(),valid:d.bcs.bool()}),Me=d.bcs.struct("FlashLoanAssetConfig",{id:d.bcs.string(),asset_id:d.bcs.u8(),coin_type:d.bcs.string(),pool_id:d.bcs.string(),rate_to_supplier:d.bcs.u64(),rate_to_treasury:d.bcs.u64(),max:d.bcs.u64(),min:d.bcs.u64()}),ae=d.bcs.struct("ReserveDataInfo",{id:d.bcs.u8(),oracle_id:d.bcs.u8(),coin_type:d.bcs.string(),supply_cap:d.bcs.u256(),borrow_cap:d.bcs.u256(),supply_rate:d.bcs.u256(),borrow_rate:d.bcs.u256(),supply_index:d.bcs.u256(),borrow_index:d.bcs.u256(),total_supply:d.bcs.u256(),total_borrow:d.bcs.u256(),last_update_at:d.bcs.u64(),ltv:d.bcs.u256(),treasury_factor:d.bcs.u256(),treasury_balance:d.bcs.u256(),base_rate:d.bcs.u256(),multiplier:d.bcs.u256(),jump_rate_multiplier:d.bcs.u256(),reserve_factor:d.bcs.u256(),optimal_utilization:d.bcs.u256(),liquidation_ratio:d.bcs.u256(),liquidation_bonus:d.bcs.u256(),liquidation_threshold:d.bcs.u256()}),ce=d.bcs.struct("UserStateInfo",{asset_id:d.bcs.u8(),borrow_balance:d.bcs.u256(),supply_balance:d.bcs.u256()}),Ve="1.4.5-beta.3",E={version:Ve},Ee=E.version,Ue=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),r=process.version,o=e.type(),n=e.arch();return`Node.js ${r.startsWith("v")?r.substring(1):r}; ${o}/${n}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},De=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${Ee} (${Ue()})`),e},te=De(),V=new ee.SuiClient({url:ee.getFullnodeUrl("mainnet")});function se(e){const r=[];return e.forEach((o,n)=>{const t=n===e.length-1;if(typeof o=="object"&&o!==null&&t){const{client:a,disableCache:i,cacheTime:c,...s}=o;r.push(s)}else r.push(o)}),JSON.stringify(r)}function P(e){const r={};return(...o)=>{const n=se(o);return r[n]||(r[n]=e(...o).finally(()=>{delete r[n]})),r[n]}}function M(e){let r={};return(...o)=>{const n=o[o.length-1],t=se(o),a=r[t];return!n?.disableCache&&typeof a?.data<"u"&&(typeof n?.cacheTime>"u"||n.cacheTime>Date.now()-a.cacheAt)?Promise.resolve(a.data):e(...o).then(i=>(r[t]={data:i,cacheAt:Date.now()},i))}}function Y(e){return Array.isArray(e)?e.map(r=>Y(r)):e!=null&&typeof e=="object"?Object.keys(e).reduce((r,o)=>({...r,[Be(o)]:Y(e[o])}),{}):e}function g(e,r){return typeof e=="object"?e:r(e)}function Oe(e,r){return typeof r=="string"?e.object(r):typeof r=="object"&&r.$kind?r:e.object(r.contract.pool)}function W(e,r,o){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((n,t)=>(r[t]||r[0]).parse(Uint8Array.from(n[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function k(e){return Pe.normalizeStructTag(e)}function ie(e){const r=(e||0)/Math.pow(10,27);return r>Math.pow(10,5)?1/0:r}new Z.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const Fe=27,oe=(e,r)=>{if(!Number(e)||!Number(r))return new p(0);const o=new p(1).shiftedBy(1*Fe),n=o.multipliedBy(new p(.5));return new p(e).multipliedBy(new p(r)).plus(n).dividedBy(o).integerValue(p.ROUND_DOWN)},D=te?{"User-Agent":te}:{};function J(e,r="uniqueId"){return e.reduce((o,n)=>(o[n[r]]=n,o),{})}function re(e,r="uniqueId"){return e.reduce((o,n)=>(o[n[r]]=n,o),{})}function H(e,r){const o=e.emodes.find(t=>t.emodeId===r.emodeId);if(!o)throw new Error("EMode not found in pool");const n=o.assets.find(t=>t.assetId===e.id);return{...e,emode:{...n,emodeId:o.emodeId},isEMode:!0}}function le(e){const[r,o]=e.split("-");return!r||!o?null:{marketKey:r,poolId:parseInt(o)}}function S(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}var N=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(N||{});const q=M(P(async e=>{const r=(e?.markets||[U.main]).map(t=>I(t)),o=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${E.version}&market=${r.map(t=>t.key)}`,n=await fetch(o,{headers:D}).then(t=>t.json());return n.data.forEach(t=>{const i=n.meta.emodes.filter(f=>{const v=I(f.marketId);return t.market===v.key&&f.isActive}).filter(f=>!!f.assets.find(v=>v.assetId===t.id));t.emodes=i;const c=p(t.totalSupplyAmount).div(Math.pow(10,9)).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),s=p(t.borrowedAmount).shiftedBy(-9).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),u=p(c).multipliedBy(t.oracle.price).toString(),m=p(s).multipliedBy(t.oracle.price).toString(),b=p(t.supplyCapCeiling).shiftedBy(-27).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),h=p.max(p(t.borrowedAmount),p(t.validBorrowAmount)).shiftedBy(-9).decimalPlaces(t.token.decimals,p.ROUND_DOWN).toString(),y=p(b).multipliedBy(t.oracle.price).toString(),l=p(h).multipliedBy(t.oracle.price).toString();t.poolSupplyAmount=c,t.poolBorrowAmount=s,t.poolSupplyValue=u,t.poolBorrowValue=m,t.poolSupplyCapAmount=b,t.poolBorrowCapAmount=h,t.poolSupplyCapValue=y,t.poolBorrowCapValue=l}),n.data}));async function $(e,r){let o=r?.market;if(typeof e=="string"){const a=le(e);a&&(o=a.marketKey,e=a.poolId)}const n=await q({...r,markets:[o||O],cacheTime:w});if(typeof e=="object")return e;const t=n.find(a=>typeof e=="string"?k(a.suiCoinType)===k(e):typeof e=="number"?a.id===e:!1);if(!t)throw new Error("Pool not found");return t.isDeprecated&&console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`),t}const Ne=M(P(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${E.version}`;return(await fetch(r,{headers:D}).then(n=>n.json())).data})),Re=M(P(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${E.version}`;return await fetch(r,{headers:D}).then(n=>n.json())}));async function ue(e,r,o,n){const t=await C({...n,cacheTime:w}),a=await $(r,n);n?.market;const i=n?.env||"prod";if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const c=typeof o=="object"&&o.$kind==="GasCoin";if(k(a.suiCoinType)===k("0x2::sui::SUI")&&c){if(!n?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[n.amount])}let s;return typeof n?.amount<"u"?s=g(n.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),n?.accountCap?e.moveCall({target:`${t.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object)],typeArguments:[a.suiCoinType]}):e.moveCall({target:`${t.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),s,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),t.version===2&&a.token.symbol==="SUI"&&i==="prod"&&e.moveCall({target:`${t.package}::pool::refresh_stake`,arguments:[e.object(a.contract.pool),e.object("0x05")]}),e}async function qe(e,r,o,n){const t=await C({...n,cacheTime:w}),a=await $(r,n),i=g(o,e.pure.u64);let c;if(t.version===1)if(n?.accountCap){const[u]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=u}else{const[u]=e.moveCall({target:`${t.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=u}else if(n?.accountCap){const[u]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=u}else{const[u]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[c],typeArguments:[a.suiCoinType]})}async function Le(e,r,o,n){const t=await C({...n,cacheTime:w}),a=await $(r,n);if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const i=g(o,e.pure.u64);let c;if(t.version===1)if(n?.accountCap){const[u]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=u}else{const[u]=e.moveCall({target:`${t.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=u}else if(n?.accountCap){const[u]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=u}else{const[u]=e.moveCall({target:`${t.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),i,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(c)],typeArguments:[a.suiCoinType]})}async function He(e,r,o,n){const t=await C({...n,cacheTime:w}),a=await $(r,n),i=typeof o=="object"&&o.$kind==="GasCoin";if(k(a.suiCoinType)===k("0x2::sui::SUI")&&i){if(!n?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[n.amount])}let c;if(typeof n?.amount<"u"?c=g(n.amount,e.pure.u64):c=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),n?.accountCap){const[s]=e.moveCall({target:`${t.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(n.accountCap,e.object)],typeArguments:[a.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[s],typeArguments:[a.suiCoinType]})}else return e.moveCall({target:`${t.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),c,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),e}const We=M(P(async e=>{const r=await C({...e});if(e?.address&&typeof e?.asset<"u")try{const t=await $(e.asset,e),a=e?.client??V,i=new R.Transaction;i.moveCall({target:`${r.package}::incentive_v3::get_borrow_fee_v2`,arguments:[i.object(r.incentiveV3),i.pure.address(e.address),i.pure.u8(t.id),i.pure.u64(1e4)],typeArguments:[]});const c=await a.devInspectTransactionBlock({transactionBlock:i,sender:e.address}),s=W(c,[_.bcs.u64()]);return(Number(s[0])||0)/100}catch(t){console.error(t)}const n=(await V.getObject({id:r.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(n)/100})),O="main",U={main:{id:0,key:"main",name:"Main Market"},ember:{id:1,key:"ember",name:"Ember Market"},rwa:{id:2,key:"rwa",name:"Matrixdock Market"},"sui-eco":{id:3,key:"sui-eco",name:"Sui Eco Market"}};class pe{constructor(r,o){this.poolMap={},this.emodeMap={},this.pools=[],this.emodes=[],this.emodePools=[],this.emodeBorrowablePools=[],this.emodeSupplyablePools=[],this._overview={marketTotalSupplyValue:"0",marketTotalBorrowValue:"0"},this.config=I(r),this.initPools(o)}get overview(){return this._overview}initPools(r){const o=J(this.pools),n=re(this.emodes),t=new Set,a=new Set;let i=p(0),c=p(0);r.forEach(s=>{if(!this.checkMarket(s.market)){console.warn(`Pool is not in market ${this.config.name}`,s);return}o[s.uniqueId]||this.pools.push(s),s?.emodes?.forEach(m=>{n[m.uniqueId]||this.emodes.push(m),m.assets.forEach(b=>{b.isDebt&&m.assets.find(y=>y.isCollateral&&y.ltv>0&&y.assetId!==s.id)&&t.add(s.uniqueId),b.isCollateral&&m.assets.find(y=>y.isDebt&&y.assetId!==s.id)&&a.add(s.uniqueId)})}),c=c.plus(s.poolBorrowValue),i=i.plus(s.poolSupplyValue)}),this.poolMap=J(this.pools,"id"),this.emodeMap=re(this.emodes,"emodeId"),this.emodes.forEach(s=>{const u=this.getEModePools(s.emodeId);this.emodePools.push(...u)}),this._overview={marketTotalSupplyValue:i.toString(),marketTotalBorrowValue:c.toString()},this.emodeBorrowablePools=this.pools.filter(s=>t.has(s.uniqueId)),this.emodeSupplyablePools=this.pools.filter(s=>a.has(s.uniqueId))}getEMode(r){return this.emodeMap[r]||null}getEModeRelatePools(r,o){const{collateral:n,debt:t,emodeId:a}=o||{},i=[];return r.emodes.forEach(c=>{typeof a=="number"&&a!==c.emodeId||c.assets.forEach(s=>{typeof n=="boolean"&&n&&s.isCollateral&&s.assetId===r.id&&i.push(this.poolMap[s.assetId]),typeof t=="boolean"&&t&&s.isDebt&&s.assetId===r.id&&i.push(this.poolMap[s.assetId])})}),i}getEModePools(r){const o=this.getEMode(r);return o?o.assets.map(t=>t.assetId).map(t=>this.poolMap[t]).filter(t=>!!t).map(t=>{const a=o.assets.find(i=>i.assetId===t.id);return{...t,emode:{...a,emodeId:o.emodeId},isEMode:!0}}):[]}checkMarket(r){let o=!1;return typeof r=="number"&&r===this.config.id&&(o=!0),typeof r=="string"&&r===this.config.key&&(o=!0),typeof r=="object"&&r.id===this.config.id&&(o=!0),o}}const I=e=>{const o=Object.values(U).find(n=>typeof e=="number"?n.id===e:typeof e=="string"?n.key===e:n.id===e.id);if(!o)throw new Error("Market not found");return o},de=M(P(async(e,r)=>{const o=await q({cacheTime:6e4,...r,markets:e});return e.map(n=>{const t=I(n),a=o.filter(i=>i.market===t.key);return new pe(n,a)})})),Ge=M(P(async(e,r)=>(await de([e],r))[0])),C=M(P(async e=>{const r=I(e?.market||O),o=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${E.version}&market=${r.key}`;return(await fetch(o,{headers:D}).then(t=>t.json())).data})),w=1e3*60*5;async function me(e,r){const o=await C({cacheTime:w,...r});return e.moveCall({target:`${o.package}::lending::create_account`,arguments:[]})}async function fe(e,r,o){const n=await C({cacheTime:w,...o});return e.moveCall({target:`${n.package}::account::account_owner`,arguments:[r]})}async function ge(e,r,o){const n=await C({...o,cacheTime:w});return o?.accountCap?e.moveCall({target:`${n.package}::lending::enter_emode_with_account_cap`,arguments:[e.object(n.storage),g(r,e.pure.u64),g(o.accountCap,e.object)]}):e.moveCall({target:`${n.package}::lending::enter_emode`,arguments:[e.object(n.storage),g(r,e.pure.u64)]}),e}async function Ke(e,r){const o=await C({...r,cacheTime:w});return r?.accountCap?e.moveCall({target:`${o.package}::lending::exit_emode_with_account_cap`,arguments:[e.object(o.storage),g(r.accountCap,e.object)]}):e.moveCall({target:`${o.package}::lending::exit_emode`,arguments:[e.object(o.storage)]}),e}async function ze(e,r,o){const n=await C({cacheTime:w,...o}),t=await me(e,o);await ge(e,r,{...o,accountCap:t});const a=await I(o?.market||O),i=await fe(e,t,o);return e.moveCall({target:`${n.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,arguments:[e.object(n.emode.contract.registryObject),i,g(a.id,e.pure.u64),g(r,e.pure.u64)]}),t}const Q=M(P(async(e,r)=>{const o=await C({cacheTime:w,...r}),n=new R.Transaction,t=r?.client??V;n.moveCall({target:`${o.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,arguments:[n.object(o.emode.contract.registryObject),n.pure.address(e)]});const i=(await t.devInspectTransactionBlock({transactionBlock:n,sender:e})).results[0].returnValues,c=_.bcs.vector(_.bcs.u64()).parse(Uint8Array.from(i[0][0])),s=_.bcs.vector(_.bcs.u64()).parse(Uint8Array.from(i[1][0])),u=_.bcs.vector(_.bcs.Address).parse(Uint8Array.from(i[2][0]));return c.map((m,b)=>({marketId:Number(m),emodeId:Number(s[b]),accountCap:u[b].toString()}))}));function Ye(e){return`${I(e.marketId).key}-${e.emodeId}`}function Je(e,r,o){const n=typeof o?.balance=="number",t=n?o.balance:0;let a=0;const i=[];let c="";if(r.sort((s,u)=>Number(u.balance)-Number(s.balance)).forEach(s=>{if(!(n&&a>=t)&&Number(s.balance)!==0){if(c||(c=s.coinType),c!==s.coinType)throw new Error("All coins must be of the same type");a+=Number(s.balance),i.push(s.coinObjectId)}}),i.length===0)throw new Error("No coins to merge");if(n&&a<t)throw new Error(`Balance is less than the specified balance: ${a} < ${t}`);return k(c)===k("0x2::sui::SUI")&&o?.useGasCoin?n?e.splitCoins(e.gas,[e.pure.u64(t)]):e.gas:(i.length===1?e.object(i[0]):e.mergeCoins(i[0],i.slice(1)),n?e.splitCoins(i[0],[e.pure.u64(t)]):i[0])}async function X(e,r,o,n,t,a,i){const c=await C({...i,cacheTime:w}),s=await $(o,i);return e.moveCall({target:`${c.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(c.storage),e.object(c.oracle.priceOracle),Oe(e,s),g(r,e.pure.address),g(s.id,e.pure.u8),g(n,e.pure.u64),g(t,e.pure.u64),g(a,e.pure.bool)],typeArguments:[s.suiCoinType]})}async function ye(e,r,o){return X(e,r,0,0,0,!1,o)}async function be(e,r,o){const n=new R.Transaction,t=o?.client??V,a=await q({...o,markets:Object.values(U)}),i=J(a),s=Array.from(new Set(r.map(l=>l.market))).map(l=>I(l));for(const l of s){const f=await C({...o,cacheTime:w,market:l.key});n.moveCall({target:`${f.uiGetter}::getter::get_reserve_data`,arguments:[n.object(f.storage)]})}for(let l of r){const f=await C({...o,cacheTime:w,market:l.market});n.moveCall({target:`${f.uiGetter}::getter_unchecked::get_user_state`,arguments:[n.object(f.storage),n.pure.address(l.address)]})}const m=(await t.devInspectTransactionBlock({transactionBlock:n,sender:e})).results||[],b={};s.forEach((l,f)=>{try{const v=m[f]?.returnValues?.map(B=>_.bcs.vector(ae).parse(Uint8Array.from(B[0])))[0]||[],j={};for(const B of v)j[B.id]={supplyIndex:B.supply_index,borrowIndex:B.borrow_index};b[l.key]=j}catch(v){console.warn(`[@naviprotocol/lending] Failed to decode reserve data for market "${l.key}", falling back to open-api pool indices`,v)}});const h=m.slice(s.length).map(l=>l.returnValues?.map(f=>_.bcs.vector(ce).parse(Uint8Array.from(f[0])))[0]||[]),y=[];return h.forEach((l,f)=>{const v=r[f],j=I(v.market),B=b[j.key]||{};l.forEach(T=>{if(T.supply_balance==="0"&&T.borrow_balance==="0"&&(v.emodeId===void 0||!o?.includeZeroBalanceEmodePositions))return;const A=i[`${j.key}-${T.asset_id}`];if(!A)return;const L=B[T.asset_id],K=L?.supplyIndex??A.currentSupplyIndex,Te=L?.borrowIndex??A.currentBorrowIndex,je=oe(T.supply_balance,K).toString(),Ie=oe(T.borrow_balance,Te).toString();y.push({supplyBalance:je,borrowBalance:Ie,assetId:T.asset_id,market:j.key,pool:A,emodeId:v.emodeId})})}),y}const Ze=M(async(e,r)=>{const n=(r?.markets||Object.keys(U)).map(t=>I(t)).map(t=>({address:e,market:t.key}));return await be(e,n,r)});async function Qe(e,r){const o=r?.client??V,n=new R.Transaction;await ye(n,e,r);const t=await o.devInspectTransactionBlock({transactionBlock:n,sender:e}),a=W(t,[_.bcs.u256()]);return ie(Number(a[0])||0)}async function Xe(e,r,o,n){const t=n?.client??V,a=new R.Transaction;let i=0,c=0;const s=await $(r,n);if(o.forEach(h=>{h.type===N.Supply?i+=h.amount:h.type===N.Withdraw?i-=h.amount:h.type===N.Borrow?c+=h.amount:h.type===N.Repay&&(c-=h.amount)}),i*c<0)throw new Error("Invalid operations");const u=i>0||c>0;await X(a,e,s,Math.abs(i),Math.abs(c),u,n);const m=await t.devInspectTransactionBlock({transactionBlock:a,sender:e}),b=W(m,[_.bcs.u256()]);return ie(Number(b[0])||0)}const xe=P(async(e,r)=>{const o=new URLSearchParams;r?.cursor&&o.set("cursor",r.cursor),o.set("userAddress",e);const n=`https://open-api.naviprotocol.io/api/navi/user/transactions?${o.toString()}&sdk=${E.version}`;return(await fetch(n,{headers:D}).then(a=>a.json())).data});async function et(e,r){let o=null;const n=[],t=r?.client??V;do{let a;if(r?.coinType?a=await t.getCoins({owner:e,coinType:r?.coinType,cursor:o,limit:100}):a=await t.getAllCoins({owner:e,cursor:o,limit:100}),!a.data||!a.data.length)break;n.push(...a.data),o=a.nextCursor}while(o);return n}const he=M(async(e,r)=>{const o=[],n=(r?.markets||Object.keys(U)).map(c=>I(c));let t=[];try{t=await Q(e,r)}catch(c){console.error(c)}const a=n.map(c=>({address:e,market:c.key})).concat(t.filter(c=>!!n.find(s=>s.id===c.marketId)).map(c=>({address:c.accountCap,market:I(c.marketId).key,emodeId:c.emodeId})));return(await be(e,a,r)).forEach(c=>{const s=typeof c.emodeId=="number"?t.find(u=>{const m=I(c.market);return u.emodeId===c.emodeId&&u.marketId===m.id}):void 0;if(s){if(!c.pool.emodes.find(m=>m.emodeId===s.emodeId))return;if(p(c.supplyBalance).gte(0)){const m=p(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN),b=H(c.pool,s);if(m.gt(0)||b.emode.isCollateral)try{o.push({id:`${c.pool.uniqueId}_${s.emodeId}_navi-lending-emode-supply-${S()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:m.toString(),pool:H(c.pool,s),token:c.pool.token,valueUSD:m.multipliedBy(c.pool.oracle.price).toString(),emodeCap:s}})}catch(h){console.error(h)}}if(p(c.borrowBalance).gte(0)){const m=p(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN),b=H(c.pool,s);if(m.gt(0)||b.emode.isDebt)try{o.push({id:`${c.pool.uniqueId}_${s.emodeId}_navi-lending-emode-borrow-${S()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:m.toString(),pool:H(c.pool,s),token:c.pool.token,valueUSD:m.multipliedBy(c.pool.oracle.price).toString(),emodeCap:s}})}catch(h){console.error(h)}}}else{if(p(c.supplyBalance).gt(0)){const u=p(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-supply-${S()}`,wallet:e,protocol:"navi",type:"navi-lending-supply",market:c.market,"navi-lending-supply":{amount:u.toString(),pool:c.pool,token:c.pool.token,valueUSD:u.multipliedBy(c.pool.oracle.price).toString()}})}if(p(c.borrowBalance).gt(0)){const u=p(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,p.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-borrow-${S()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-borrow","navi-lending-borrow":{amount:u.toString(),pool:c.pool,token:c.pool.token,valueUSD:u.multipliedBy(c.pool.oracle.price).toString()}})}}}),o});class F{constructor(r,o){this._positions=[],this._priceMap={},this._overview={hf:1/0,netVaule:"0",netWorthApr:"0",totalSupplyValue:"0",totalBorrowValue:"0",totalsupplyApy:"0",totalBorrowApy:"0",maxLiquidationValue:"0",maxLoanToVaule:"0",supply:{},borrow:{}},this._priceMap=o||{},this.positions=r}get positions(){return this._positions}get overview(){return this._overview}get priceMap(){return this._priceMap}set positions(r){this._positions=r,this._overview=this.getPositionsOverview(r)}updatePriceMap(r){return this._priceMap=r,this._overview=this.getPositionsOverview(this._positions),this}getPrice(r){const o=k(r.suiCoinType);if(this._priceMap[o]!==void 0)return this._priceMap[o].toString();const n=r.suiCoinType;return this._priceMap[n]!==void 0?this._priceMap[n].toString():r.oracle.price}filterPositionsByPool(r){const n=!!r.isEMode?["navi-lending-emode-supply","navi-lending-emode-borrow"]:["navi-lending-supply","navi-lending-borrow"];return new F(this.positions.filter(t=>{const a=t[t.type];return n.includes(t.type)&&a.pool.uniqueId===r.uniqueId}),this._priceMap)}deposit(r,o){const n=!!r.isEMode,t=this.getPrice(r);let a;return n?a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:r.token,pool:r,emodeCap:{}}}:a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:r.token,pool:r}},new F([...this.positions,a],this._priceMap)}withdraw(r,o){const n=!!r.isEMode,t=this.getPrice(r);let a;return n?a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:r.token,pool:r,emodeCap:{}}}:a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:r.token,pool:r}},new F([...this.positions,a],this._priceMap)}borrow(r,o){const n=!!r.isEMode,t=this.getPrice(r);let a;return n?a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:r.token,pool:r,emodeCap:{}}}:a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:o.toString(),valueUSD:p(o).multipliedBy(t).toString(),token:r.token,pool:r}},new F([...this.positions,a],this._priceMap)}repay(r,o){const n=!!r.isEMode,t=this.getPrice(r);let a;return n?a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:r.token,pool:r,emodeCap:{}}}:a={id:S(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:(-o).toString(),valueUSD:p(-o).multipliedBy(t).toString(),token:r.token,pool:r}},new F([...this.positions,a],this._priceMap)}resolveValueUSD(r){return Object.keys(this._priceMap).length>0?p(r.amount).multipliedBy(this.getPrice(r.pool)).toString():r.valueUSD}getPositionsOverview(r){const o={},n={};let t=new p(0),a=new p(0),i=new p(0),c=new p(0),s=new p(0),u=new p(0);r.forEach(y=>{if(y.type==="navi-lending-supply"){const l=y["navi-lending-supply"],f=this.resolveValueUSD(l);t=t.plus(f),s=s.plus(new p(f).multipliedBy(l.pool.liquidationFactor.threshold)),u=u.plus(new p(f).multipliedBy(l.pool.ltvValue))}else if(y.type==="navi-lending-borrow"){const l=y["navi-lending-borrow"];a=a.plus(this.resolveValueUSD(l))}else if(y.type==="navi-lending-emode-supply"){const l=y["navi-lending-emode-supply"],f=this.resolveValueUSD(l);t=t.plus(f);const v=l.pool.emode;s=s.plus(new p(f).multipliedBy(v.lt)),u=u.plus(new p(f).multipliedBy(v.ltv))}else if(y.type==="navi-lending-emode-borrow"){const l=y["navi-lending-emode-borrow"];a=a.plus(this.resolveValueUSD(l))}}),a=p.max(a,0),t=p.max(t,0),s=p.max(s,0),u=p.max(u,0),r.forEach(y=>{if(y.type==="navi-lending-supply"){const l=y["navi-lending-supply"],f=this.resolveValueUSD(l),v=l.pool.supplyIncentiveApyInfo.apy;t.gt(0)&&(i=i.plus(new p(f).dividedBy(t).multipliedBy(new p(v).dividedBy(100)))),o[l.pool.suiCoinType]=p(o[l.pool.suiCoinType]||0).plus(l.amount).toString()}else if(y.type==="navi-lending-borrow"){const l=y["navi-lending-borrow"],f=this.resolveValueUSD(l),v=l.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new p(f).dividedBy(a).multipliedBy(new p(v).dividedBy(100)))),n[l.pool.suiCoinType]=p(n[l.pool.suiCoinType]||0).plus(l.amount).toString()}else if(y.type==="navi-lending-emode-supply"){const l=y["navi-lending-emode-supply"],f=this.resolveValueUSD(l),v=l.pool.supplyIncentiveApyInfo.apy;t.gt(0)&&(i=i.plus(new p(f).dividedBy(t).multipliedBy(new p(v).dividedBy(100)))),o[l.pool.suiCoinType]=p(o[l.pool.suiCoinType]||0).plus(l.amount).toString()}else if(y.type==="navi-lending-emode-borrow"){const l=y["navi-lending-emode-borrow"],f=this.resolveValueUSD(l),v=l.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new p(f).dividedBy(a).multipliedBy(new p(v).dividedBy(100)))),n[l.pool.suiCoinType]=p(n[l.pool.suiCoinType]||0).plus(l.amount).toString()}});const m=t.minus(a),b=t.minus(a).eq(0)?new p(0):t.multipliedBy(i).minus(a.multipliedBy(c)).div(t.minus(a));return{hf:a.toNumber()!==0?s.dividedBy(a).toNumber():1/0,netVaule:m.toString(),netWorthApr:b.toString(),totalSupplyValue:t.toString(),totalBorrowValue:a.toString(),totalsupplyApy:i.toString(),totalBorrowApy:c.toString(),maxLiquidationValue:s.toString(),maxLoanToVaule:u.toString(),supply:o,borrow:n}}}async function tt(e,r,o,n){const t=await C({...n,cacheTime:w});t.limter&&e.moveCall({target:`${t.limter}::navi_adaptor::verify_navi_position_healthy`,arguments:[e.object("0x06"),e.object(t.storage),e.object(t.priceOracle),g(r,e.pure.address),e.pure.u256(new p(o).shiftedBy(27).toNumber())]})}const ve=new Z.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function ot(e){try{const r=[],o=await ve.getLatestPriceFeeds(e);if(!o)return r;const n=Math.floor(new Date().valueOf()/1e3);for(const t of o){const a=t.getPriceUnchecked();if(a.publishTime>n){console.warn(`pyth price feed is invalid, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${n}`);continue}n-t.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${n}`),r.push(t.id))}return r}catch(r){throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`)}}async function rt(e,r){try{const o=[],n=r?.client??V,t=e.map(i=>i.priceInfoObject),a=await n.multiGetObjects({ids:Array.from(new Set(t)),options:{showContent:!0}});for(const i of a){const c=i.data;if(!c||!c.content||c.content.dataType!=="moveObject"){console.warn(`fetched object ${c?.objectId} datatype should be moveObject`);continue}const s=e.find(l=>l.priceInfoObject==c.objectId);if(!s){console.warn(`unable to find pyth info from array, priceInfoObject: ${c.objectId}`);continue}const u=c.content.fields.price_info.fields.price_feed.fields.price.fields,{magnitude:m,negative:b}=u.price.fields,h=u.conf,y=u.timestamp;o.push({priceFeedId:s.priceFeedId,priceInfoObject:s.priceInfoObject,price:b?"-"+m:m,conf:h,publishTime:Number(y),expiration:s.expiration})}return o}catch(o){console.error(o,`Polling Sui on-chain price for ${e} failed.`);return}}async function we(e,r){try{const o=[],n=await rt(e,r);if(!n)return o;const t=Math.floor(new Date().valueOf()/1e3);for(const a of n){if(a.publishTime>t){console.warn(`pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`);continue}const i=a.expiration||60;t-a.publishTime>i&&(console.info(`stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`),o.push(a.priceFeedId))}return o}catch(o){throw new Error(`failed to get pyth stale price feed id, msg: ${o.message}`)}}async function ke(e,r,o){const n=o?.client??V,t=await C({...o,cacheTime:w});try{const a=await ve.getPriceFeedsUpdateData(r);return await new Z.SuiPythClient(n,t.oracle.pythStateId,t.oracle.wormholeStateId).updatePriceFeeds(e,a,r)}catch(a){throw new Error(`failed to update pyth price feeds, msg: ${a.message}`)}}async function Ce(e,r,o){const n=await C({...o,cacheTime:w});if(o?.updatePythPriceFeeds){const t=r.filter(a=>!!a.pythPriceFeedId&&!!a.pythPriceInfoObject).map(a=>({priceFeedId:a.pythPriceFeedId,priceInfoObject:a.pythPriceInfoObject,expiration:30}));try{const a=await we(t,o);a.length>0&&await ke(e,a,o)}catch{console.error("Failed to update Pyth price feeds")}}for(const t of r)o?.env==="dev"?e.moveCall({target:`${n.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(n.oracle.oracleConfig),e.object(n.oracle.priceOracle),e.object(n.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.pure.address(t.feedId)]}):e.moveCall({target:`${n.oracle.packageId}::oracle_pro::update_single_price_v2`,arguments:[e.object("0x6"),e.object(n.oracle.oracleConfig),e.object(n.oracle.priceOracle),e.object(n.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.object(n.oracle.switchboardAggregator),e.pure.address(t.feedId)]});return e}async function x(e){return(await C({...e,cacheTime:w})).oracle.feeds}function _e(e,r){return e.filter(o=>!!(r?.lendingState&&r.lendingState.find(t=>o.oracleId===t.pool.oracleId)||r?.lendingPositions&&r.lendingPositions.find(t=>{if(!["navi-lending-supply","navi-lending-borrow","navi-lending-emode-supply","navi-lending-emode-borrow"].includes(t.type))return!1;const i=t[t.type]?.pool;return o.oracleId===i?.oracleId})||r?.pools&&r.pools.find(t=>o.oracleId===t.oracleId)))}async function nt(e,r,o,n){try{const t=await x({...n}),a=[];o.forEach(u=>{a.includes(u.market)||a.push(u.market)});const i=await he(r,{...n,markets:a}),c=_e(t,{lendingPositions:i,pools:o});return await Ce(e,c,{updatePythPriceFeeds:!0,...n})}catch(t){if(n?.throws)throw t;return console.error(t),e}}const G=M(P(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${E.version}&market=${e?.market||O}`,o=await fetch(r,{headers:D}).then(n=>n.json());return Object.keys(o.data).map(n=>({...o.data[n],coinType:n}))}));async function at(e,r){return(await G(r)).find(n=>typeof e=="string"?k(n.coinType)===k(e):typeof e=="number"?n.assetId===e:n.assetId===e.id)||null}async function ct(e,r,o,n){const t=await C({...n,cacheTime:w}),a=await $(r,n);if(!(await G({...n,cacheTime:w})).some(s=>k(s.coinType)===k(a.suiCoinType)))throw new Error("Pool does not support flashloan");if(t.version===1){const[s,u]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64)],typeArguments:[a.suiCoinType]});return[s,u]}else{const[s,u]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64),e.object("0x05")],typeArguments:[a.suiCoinType]});return[s,u]}}async function st(e,r,o,n,t){const a=await C({...t,cacheTime:w}),i=await $(r,t);if(!(await G({...t,cacheTime:w})).some(m=>k(m.coinType)===k(i.suiCoinType)))throw new Error("Pool does not support flashloan");const[u]=e.moveCall({target:`${a.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(a.storage),e.object(i.contract.pool),g(o,e.object),g(n,e.object)],typeArguments:[i.suiCoinType]});return[u]}async function it(e,r,o,n,t,a){const i={...a,cacheTime:w},c=await C(i),s=await $(r,i),u=await $(n,i);if(c.version===1){const[m,b]=e.moveCall({target:`${c.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(s.id),e.object(s.contract.pool),g(o,e.object),e.pure.u8(u.id),e.object(u.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[s.suiCoinType,u.suiCoinType]});return[m,b]}else{const[m,b]=e.moveCall({target:`${c.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(s.id),e.object(s.contract.pool),g(o,e.object),e.pure.u8(u.id),e.object(u.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3),e.object("0x05")],typeArguments:[s.suiCoinType,u.suiCoinType]});return[m,b]}}async function lt(e,r,o){const n=o?.client??V,t=new R.Transaction,a=await q({...o,markets:Object.values(U),cacheTime:w}),i=await x(o);for(let m of r){const b=await C({...o,cacheTime:w,market:m.market});t.moveCall({target:`${b.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[t.object("0x06"),t.object(b.storage),t.object(b.incentiveV3),t.pure.address(m.address)]})}const c=await n.devInspectTransactionBlock({transactionBlock:t,sender:e}),s=[];c?.results?.forEach(m=>{s.push(W({results:[m]},[_.bcs.vector(_.bcs.string()),_.bcs.vector(_.bcs.string()),_.bcs.vector(_.bcs.u8()),_.bcs.vector(_.bcs.Address),_.bcs.vector(_.bcs.u256())]))});const u=[];return s.forEach((m,b)=>{const h=r[b];if(m.length===5&&Array.isArray(m[0])){const y=m[0].length;for(let l=0;l<y;l++){const f=i.find(j=>k(j.coinType)===k(m[1][l])),v=a.find(j=>k(j.coinType)===k(m[0][l])&&j.market===h.market);!f||!v||u.push({assetId:v.id,assetCoinType:k(m[0][l]),rewardCoinType:k(m[1][l]),option:Number(m[2][l]),userClaimableReward:Number(m[4][l])/Math.pow(10,f.priceDecimal),ruleIds:Array.isArray(m[3][l])?m[3][l]:[m[3][l]],market:h.market,owner:h.owner,address:h.address,emodeId:h.emodeId})}}}),u}async function ut(e,r){const o=(r?.markets||[U.main]).map(a=>I(a));let n=[];try{n=await Q(e,r)}catch(a){console.error(a)}const t=o.map(a=>({address:e,owner:e,market:a.key})).concat(n.filter(a=>!!o.find(i=>i.id===a.marketId)).map(a=>{const i=I(a.marketId);return{address:a.accountCap,owner:e,market:i.key,emodeId:a.emodeId}}));return await lt(e,t,r)}function pt(e){const r=new Map;e.forEach(n=>{const t=n.assetId,a=n.option,i=`${t}-${a}-${n.rewardCoinType}-${n.market}`;r.has(i)?r.get(i).total+=n.userClaimableReward:r.set(i,{assetId:t,rewardType:a,coinType:n.rewardCoinType,total:Number(n.userClaimableReward),market:n.market})});const o=new Map;for(const{assetId:n,rewardType:t,coinType:a,total:i,market:c}of r.values()){const s=`${n}-${t}-${c}`;o.has(s)||o.set(s,{assetId:n,rewardType:t,market:c,rewards:new Map});const u=o.get(s);u.rewards.set(a,(u.rewards.get(a)||0)+i)}return Array.from(o.values()).map(n=>({assetId:n.assetId,rewardType:n.rewardType,market:n.market,rewards:Array.from(n.rewards.entries()).map(([t,a])=>({coinType:t,available:a.toFixed(6)}))}))}const dt=P(async(e,r)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${E.version}&market=${r?.market||O}`;return(await fetch(o,{headers:D}).then(t=>t.json())).data}),mt=P(async(e,r)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${r?.page||1}&pageSize=${r?.size||400}&sdk=${E.version}&market=${r?.market||O}`,n=await fetch(o,{headers:D}).then(t=>t.json());return Y({data:n.data.rewards})});async function ft(e,r,o){const n=await q({...o,markets:Object.values(U),cacheTime:w}),t=new Map;for(const i of r){const{rewardCoinType:c,ruleIds:s,market:u,owner:m,address:b,emodeId:h}=i,y=`${c}___${b}__${u}`;for(const l of s){t.has(y)||t.set(y,{assetIds:[],ruleIds:[],amount:0,market:u,owner:m,address:b,isEMode:typeof h<"u"});const f=t.get(y);f.assetIds.push(i.assetCoinType.replace("0x","")),f.ruleIds.push(l),f.amount+=i.userClaimableReward}}const a=[];for(const[i,{assetIds:c,ruleIds:s,amount:u,market:m,owner:b,address:h,isEMode:y}]of t){const l=await C({...o,cacheTime:w,market:m}),f=i.split("___")[0],v=n.filter(T=>k(T.suiCoinType)===k(f));v.sort((T,A)=>T.market===m?-1:1);const j=v[0],B=l.rewardFunds[k(f)];if(!B)throw new Error(`No matching rewardFund found for reward coin: ${f} ${m}`);if(o?.accountCap&&!o.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(o?.customCoinReceive){let T;o.accountCap?T=e.moveCall({target:`${l.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(l.incentiveV3),e.object(l.storage),e.object(B),e.pure.vector("string",c),e.pure.vector("address",s),g(o.accountCap,e.object)],typeArguments:[f]}):y?T=e.moveCall({target:`${l.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(l.incentiveV3),e.object(l.storage),e.object(B),e.pure.vector("string",c),e.pure.vector("address",s),g(h,e.object)],typeArguments:[f]}):T=e.moveCall({target:`${l.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(l.incentiveV3),e.object(l.storage),e.object(B),e.pure.vector("string",c),e.pure.vector("address",s)],typeArguments:[f]});const[A]=e.moveCall({target:"0x2::coin::from_balance",arguments:[T],typeArguments:[f]});if(o?.customCoinReceive.type==="transfer"){if(!o.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([A],g(o.customCoinReceive.transfer,e.pure.address))}if(o?.customCoinReceive.type==="depositNAVI"){const L=p(j.totalSupplyAmount).shiftedBy(-9),K=p(j.supplyCapCeiling).shiftedBy(-27);L.plus(u).isGreaterThan(K)&&o?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([A],e.pure.address(o.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await ue(e,j,A,{...o,market:j.market})}else a.push({coin:A,identifier:j,owner:b,isEMode:y})}else if(o?.accountCap||y){const T=e.moveCall({target:`${l.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(l.incentiveV3),e.object(l.storage),e.object(B),e.pure.vector("string",c),e.pure.vector("address",s),g(o?.accountCap||h,e.object)],typeArguments:[f]}),[A]=e.moveCall({target:"0x2::coin::from_balance",arguments:[T],typeArguments:[f]});e.transferObjects([A],g(o?.accountCap||b,e.pure.address))}else e.moveCall({target:`${l.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(l.incentiveV3),e.object(l.storage),e.object(B),e.pure.vector("string",c),e.pure.vector("address",s)],typeArguments:[f]})}return a}exports.Address=z;exports.DEFAULT_CACHE_TIME=w;exports.DEFAULT_MARKET_IDENTITY=O;exports.FlashLoanAssetConfig=Me;exports.IncentiveAPYInfo=Ae;exports.IncentivePoolInfo=ne;exports.IncentivePoolInfoByPhase=Se;exports.MARKETS=U;exports.Market=pe;exports.OracleInfo=$e;exports.PoolOperator=N;exports.ReserveDataInfo=ae;exports.UserPositions=F;exports.UserStateInfo=ce;exports.borrowCoinPTB=Le;exports.claimLendingRewardsPTB=ft;exports.createAccountCapPTB=me;exports.createEModeCapPTB=ze;exports.depositCoinPTB=ue;exports.emodeIdentityId=Ye;exports.enterEModePTB=ge;exports.exitEModePTB=Ke;exports.filterPriceFeeds=_e;exports.flashloanPTB=ct;exports.getAccountCapOwnerPTB=fe;exports.getAllFlashLoanAssets=G;exports.getBorrowFee=We;exports.getCoins=et;exports.getConfig=C;exports.getFees=Re;exports.getFlashLoanAsset=at;exports.getHealthFactor=Qe;exports.getHealthFactorPTB=ye;exports.getLendingPositions=he;exports.getLendingState=Ze;exports.getMarket=Ge;exports.getMarketConfig=I;exports.getMarkets=de;exports.getPool=$;exports.getPools=q;exports.getPriceFeeds=x;exports.getPythStalePriceFeedId=ot;exports.getPythStalePriceFeedIdV2=we;exports.getSimulatedHealthFactor=Xe;exports.getSimulatedHealthFactorPTB=X;exports.getStats=Ne;exports.getTransactions=xe;exports.getUserAvailableLendingRewards=ut;exports.getUserClaimedRewardHistory=mt;exports.getUserEModeCaps=Q;exports.getUserTotalClaimedReward=dt;exports.liquidatePTB=it;exports.mergeCoinsPTB=Je;exports.normalizeCoinType=k;exports.parsePoolUID=le;exports.parseTxValue=g;exports.repayCoinPTB=He;exports.repayFlashLoanPTB=st;exports.summaryLendingRewards=pt;exports.updateOraclePriceBeforeUserOperationPTB=nt;exports.updateOraclePricesPTB=Ce;exports.updatePythPriceFeeds=ke;exports.verifyHealthFactorPTB=tt;exports.withCache=M;exports.withSingleton=P;exports.withdrawCoinPTB=qe;
2
2
  //# sourceMappingURL=index.cjs.js.map