@naviprotocol/lending 1.3.6 → 1.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +609 -617
- package/dist/index.esm.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/package.json +14 -14
- package/LICENSE +0 -21
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),U=require("@mysten/sui/client"),x=require("lodash.camelcase"),ee=require("@mysten/sui/utils"),L=require("@pythnetwork/pyth-sui-js"),A=require("bignumber.js"),w=require("@mysten/sui/bcs"),N=i.bcs.bytes(32).transform({input:e=>i.fromHex(e),output:e=>i.toHex(e)}),te=i.bcs.struct("IncentiveAPYInfo",{asset_id:i.bcs.u8(),apy:i.bcs.u256(),coin_types:i.bcs.vector(i.bcs.string())}),M=i.bcs.struct("IncentivePoolInfo",{pool_id:N,funds:N,phase:i.bcs.u64(),start_at:i.bcs.u64(),end_at:i.bcs.u64(),closed_at:i.bcs.u64(),total_supply:i.bcs.u64(),asset_id:i.bcs.u8(),option:i.bcs.u8(),factor:i.bcs.u256(),distributed:i.bcs.u64(),available:i.bcs.u256(),total:i.bcs.u256()}),re=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(M)}),ce=i.bcs.struct("OracleInfo",{oracle_id:i.bcs.u8(),price:i.bcs.u256(),decimals:i.bcs.u8(),valid:i.bcs.bool()}),ae=i.bcs.struct("FlashLoanAssetConfig",{id:i.bcs.string(),asset_id:i.bcs.u8(),coin_type:i.bcs.string(),pool_id:i.bcs.string(),rate_to_supplier:i.bcs.u64(),rate_to_treasury:i.bcs.u64(),max:i.bcs.u64(),min:i.bcs.u64()}),ne=i.bcs.struct("ReserveDataInfo",{id:i.bcs.u8(),oracle_id:i.bcs.u8(),coin_type:i.bcs.string(),supply_cap:i.bcs.u256(),borrow_cap:i.bcs.u256(),supply_rate:i.bcs.u256(),borrow_rate:i.bcs.u256(),supply_index:i.bcs.u256(),borrow_index:i.bcs.u256(),total_supply:i.bcs.u256(),total_borrow:i.bcs.u256(),last_update_at:i.bcs.u64(),ltv:i.bcs.u256(),treasury_factor:i.bcs.u256(),treasury_balance:i.bcs.u256(),base_rate:i.bcs.u256(),multiplier:i.bcs.u256(),jump_rate_multiplier:i.bcs.u256(),reserve_factor:i.bcs.u256(),optimal_utilization:i.bcs.u256(),liquidation_ratio:i.bcs.u256(),liquidation_bonus:i.bcs.u256(),liquidation_threshold:i.bcs.u256()}),H=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),se="1.3.6",T={version:se},oe=T.version,ie=()=>{if(typeof process!="undefined"&&process.versions&&process.versions.node)try{const e=require("os"),r=process.version,a=e.type(),t=e.arch();return`Node.js ${r.startsWith("v")?r.substring(1):r}; ${a}/${t}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},ue=()=>{let e="";return typeof process!="undefined"&&process.versions&&process.versions.node&&(e=`lending/${oe} (${ie()})`),e},D=ue(),I=new U.SuiClient({url:U.getFullnodeUrl("mainnet")});function O(e){const r=[];return e.forEach((a,t)=>{const c=t===e.length-1;if(typeof a=="object"&&c){const{client:n,disableCache:s,cacheTime:o,...u}=a;r.push(u)}else r.push(a)}),JSON.stringify(r)}function j(e){const r={};return(...a)=>{const t=O(a);return r[t]||(r[t]=e(...a).finally(()=>{r[t]=null})),r[t]}}function P(e){let r={};return(...a)=>{const t=a[a.length-1],c=O(a),n=r[c];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(...a).then(s=>(r[c]={data:s,cacheAt:Date.now()},s))}}function V(e){return Array.isArray(e)?e.map(r=>V(r)):e!=null&&typeof e=="object"?Object.keys(e).reduce((r,a)=>({...r,[x(a)]:V(e[a])}),{}):e}function d(e,r){return typeof e=="object"?e:r(e)}function le(e,r){return typeof r=="string"?e.object(r):typeof r=="object"&&r.$kind?r:e.object(r.contract.pool)}function S(e,r,a){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,c)=>(r[c]||r[0]).parse(Uint8Array.from(t[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function g(e){return ee.normalizeStructTag(e)}function G(e){const r=(e||0)/Math.pow(10,27);return r>Math.pow(10,5)?1/0:r}new L.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const de=27,q=(e,r)=>{if(!Number(e)||!Number(r))return new A(0);const a=new A(1).shiftedBy(1*de),t=a.multipliedBy(new A(.5));return new A(e).multipliedBy(new A(r)).plus(t).dividedBy(a).integerValue(A.ROUND_DOWN)},$=D?{"User-Agent":D}:{},y=P(j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/config?env=${(e==null?void 0:e.env)||"prod"}&sdk=${T.version}`;return(await fetch(r,{headers:$}).then(t=>t.json())).data})),f=1e3*60*5;var B=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(B||{});const F=P(j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/pools?env=${(e==null?void 0:e.env)||"prod"}&sdk=${T.version}`;return(await fetch(r,{headers:$}).then(t=>t.json())).data}));async function v(e,r){const a=await F({...r,cacheTime:f});if(typeof e=="object")return e;const t=a.find(c=>typeof e=="string"?g(c.suiCoinType)===g(e):typeof e=="number"?c.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 be=P(j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${T.version}`;return(await fetch(r,{headers:$}).then(t=>t.json())).data})),pe=P(j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${T.version}`;return await fetch(r,{headers:$}).then(t=>t.json())}));async function z(e,r,a,t){const c=await y({...t,cacheTime:f}),n=await v(r,t);if(n!=null&&n.deprecatedAt&&Date.now()>n.deprecatedAt)throw new Error(`The lending pool for coinType ${n.suiCoinType} has been deprecated.`);const s=typeof a=="object"&&a.$kind==="GasCoin";if(g(n.suiCoinType)===g("0x2::sui::SUI")&&s){if(!(t!=null&&t.amount))throw new Error("Amount is required for sui coin");a=e.splitCoins(a,[t.amount])}let o;return typeof(t==null?void 0:t.amount)!="undefined"?o=d(t.amount,e.pure.u64):o=e.moveCall({target:"0x2::coin::value",arguments:[d(a,e.object)],typeArguments:[n.suiCoinType]}),t!=null&&t.accountCap?e.moveCall({target:`${c.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]}):e.moveCall({target:`${c.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[n.suiCoinType]}),c.version===2&&n.id===0&&e.moveCall({target:`${c.package}::pool::refresh_stake`,arguments:[e.object(n.contract.pool),e.object("0x05")]}),e}async function ge(e,r,a,t){const c=await y({...t,cacheTime:f}),n=await v(r,t),s=d(a,e.pure.u64);let o;if(c.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${c.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${c.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${c.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${c.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[o],typeArguments:[n.suiCoinType]})}async function fe(e,r,a,t){const c=await y({...t,cacheTime:f}),n=await v(r,t);if(n!=null&&n.deprecatedAt&&Date.now()>n.deprecatedAt)throw new Error(`The lending pool for coinType ${n.suiCoinType} has been deprecated.`);const s=d(a,e.pure.u64);let o;if(c.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${c.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${c.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${c.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${c.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(c.incentiveV2),e.object(c.incentiveV3),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(o)],typeArguments:[n.suiCoinType]})}async function me(e,r,a,t){const c=await y({...t,cacheTime:f}),n=await v(r,t),s=typeof a=="object"&&a.$kind==="GasCoin";if(g(n.suiCoinType)===g("0x2::sui::SUI")&&s){if(!(t!=null&&t.amount))throw new Error("Amount is required for sui coin");a=e.splitCoins(a,[t.amount])}let o;if(typeof(t==null?void 0:t.amount)!="undefined"?o=d(t.amount,e.pure.u64):o=e.moveCall({target:"0x2::coin::value",arguments:[d(a,e.object)],typeArguments:[n.suiCoinType]}),t!=null&&t.accountCap){const[u]=e.moveCall({target:`${c.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(c.incentiveV2),e.object(c.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[u],typeArguments:[n.suiCoinType]})}else return e.moveCall({target:`${c.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[n.suiCoinType]}),e}const ye=P(j(async e=>{var c;const r=await y({...e});if(e!=null&&e.address&&typeof(e==null?void 0:e.asset)!="undefined")try{const n=await v(e.asset,e),s=(c=e==null?void 0:e.client)!=null?c:I,o=new k.Transaction;o.moveCall({target:`${r.package}::incentive_v3::get_borrow_fee_v2`,arguments:[o.object(r.incentiveV3),o.pure.address(e.address),o.pure.u8(n.id),o.pure.u64(1e4)],typeArguments:[]});const u=await s.devInspectTransactionBlock({transactionBlock:o,sender:e.address}),l=S(u,[w.bcs.u64()]);return(Number(l[0])||0)/100}catch(n){console.error(n)}const t=(await I.getObject({id:r.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function he(e,r,a){const t=typeof(a==null?void 0:a.balance)=="number",c=t?a.balance:0;let n=0;const s=[];let o="";if(r.sort((l,b)=>Number(b.balance)-Number(l.balance)).forEach(l=>{if(!(t&&n>=c)&&Number(l.balance)!==0){if(o||(o=l.coinType),o!==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<c)throw new Error(`Balance is less than the specified balance: ${n} < ${c}`);if(g(o)===g("0x2::sui::SUI")&&(a!=null&&a.useGasCoin))return t?e.splitCoins(e.gas,[e.pure.u64(c)]):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(c)]):u}async function E(e,r,a,t,c,n,s){const o=await y({...s,cacheTime:f}),u=await v(a,s);return e.moveCall({target:`${o.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(o.storage),e.object(o.oracle.priceOracle),le(e,u),d(r,e.pure.address),d(u.id,e.pure.u8),d(t,e.pure.u64),d(c,e.pure.u64),d(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function W(e,r,a){return E(e,r,0,0,0,!1,a)}const we=P(async(e,r)=>{var l;const a=await y({...r,cacheTime:f}),t=new k.Transaction,c=(l=r==null?void 0:r.client)!=null?l:I,n=await F(r);t.moveCall({target:`${a.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(a.storage),t.pure.address(e)]});const s=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=S(s,[w.bcs.vector(H)]);return V(o[0].filter(b=>b.supply_balance!=="0"||b.borrow_balance!=="0")).map(b=>{const h=n.find(C=>C.id===b.assetId),p=q(b.supplyBalance,h.currentSupplyIndex).toString(),m=q(b.borrowBalance,h.currentBorrowIndex).toString();return{...b,supplyBalance:p,borrowBalance:m,pool:h}}).filter(b=>!!b.pool)});async function ve(e,r){var s;const a=(s=r==null?void 0:r.client)!=null?s:I,t=new k.Transaction;await W(t,e,r);const c=await a.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=S(c,[w.bcs.u256()]);return G(Number(n[0])||0)}async function Ce(e,r,a,t){var p;const c=(p=t==null?void 0:t.client)!=null?p:I,n=new k.Transaction;let s=0,o=0;const u=await v(r,t);if(a.forEach(m=>{m.type===B.Supply?s+=m.amount:m.type===B.Withdraw?s-=m.amount:m.type===B.Borrow?o+=m.amount:m.type===B.Repay&&(o-=m.amount)}),s*o<0)throw new Error("Invalid operations");const l=s>0||o>0;await E(n,e,u,Math.abs(s),Math.abs(o),l,t);const b=await c.devInspectTransactionBlock({transactionBlock:n,sender:e}),h=S(b,[w.bcs.u256()]);return G(Number(h[0])||0)}const je=j(async(e,r)=>{const a=new URLSearchParams;r!=null&&r.cursor&&a.set("cursor",r.cursor),a.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${a.toString()}&sdk=${T.version}`;return(await fetch(t,{headers:$}).then(n=>n.json())).data});async function Te(e,r){var n;let a=null;const t=[],c=(n=r==null?void 0:r.client)!=null?n:I;do{let s;if(r!=null&&r.coinType?s=await c.getCoins({owner:e,coinType:r==null?void 0:r.coinType,cursor:a,limit:100}):s=await c.getAllCoins({owner:e,cursor:a,limit:100}),!s.data||!s.data.length)break;t.push(...s.data),a=s.nextCursor}while(a);return t}const J=new L.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function Y(e){try{const r=[],a=await J.getLatestPriceFeeds(e);if(!a)return r;const t=Math.floor(new Date().valueOf()/1e3);for(const c of a){const n=c.getPriceUnchecked();if(n.publishTime>t){console.warn(`pyth price feed is invalid, id: ${c.id}, publish time: ${n.publishTime}, current timestamp: ${t}`);continue}t-c.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${c.id}, publish time: ${n.publishTime}, current timestamp: ${t}`),r.push(c.id))}return r}catch(r){throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`)}}async function K(e,r,a){var n;const t=(n=a==null?void 0:a.client)!=null?n:I,c=await y({...a,cacheTime:f});try{const s=await J.getPriceFeedsUpdateData(r);return await new L.SuiPythClient(t,c.oracle.pythStateId,c.oracle.wormholeStateId).updatePriceFeeds(e,s,r)}catch(s){throw new Error(`failed to update pyth price feeds, msg: ${s.message}`)}}async function _e(e,r,a){const t=await y({...a,cacheTime:f});if(a!=null&&a.updatePythPriceFeeds){const c=r.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await Y(c);n.length>0&&await K(e,n,a)}catch{}}for(const c of r)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(c.pythPriceInfoObject),e.pure.address(c.feedId)]});return e}async function Q(e){return(await y({...e,cacheTime:f})).oracle.feeds}function Ae(e,r){return e.filter(a=>!!(r!=null&&r.lendingState&&r.lendingState.find(c=>c.assetId===a.assetId)||r!=null&&r.pools&&r.pools.find(c=>c.id===a.assetId)))}const R=P(j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${(e==null?void 0:e.env)||"prod"}&sdk=${T.version}`,a=await fetch(r,{headers:$}).then(t=>t.json());return Object.keys(a.data).map(t=>({...a.data[t],coinType:t}))}));async function Ie(e,r){return(await R(r)).find(t=>typeof e=="string"?g(t.coinType)===g(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function Pe(e,r,a,t){const c=await y({...t,cacheTime:f}),n=await v(r,t);if(!(await R({...t,cacheTime:f})).some(u=>g(u.coinType)===g(n.suiCoinType)))throw new Error("Pool does not support flashloan");if(c.version===1){const[u,l]=e.moveCall({target:`${c.package}::lending::flash_loan_with_ctx`,arguments:[e.object(c.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}else{const[u,l]=e.moveCall({target:`${c.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(c.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64),e.object("0x05")],typeArguments:[n.suiCoinType]});return[u,l]}}async function $e(e,r,a,t,c){const n=await y({...c,cacheTime:f}),s=await v(r,c);if(!(await R({...c,cacheTime:f})).some(b=>g(b.coinType)===g(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),d(a,e.object),d(t,e.object)],typeArguments:[s.suiCoinType]});return[l]}async function Be(e,r,a,t,c,n){const s={...n,cacheTime:f},o=await y(s),u=await v(r,s),l=await v(t,s);if(o.version===1){const[b,h]=e.moveCall({target:`${o.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(o.priceOracle),e.object(o.storage),e.pure.u8(u.id),e.object(u.contract.pool),d(a,e.object),e.pure.u8(l.id),e.object(l.contract.pool),d(c,e.pure.address),e.object(o.incentiveV2),e.object(o.incentiveV3)],typeArguments:[u.suiCoinType,l.suiCoinType]});return[b,h]}else{const[b,h]=e.moveCall({target:`${o.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(o.priceOracle),e.object(o.storage),e.pure.u8(u.id),e.object(u.contract.pool),d(a,e.object),e.pure.u8(l.id),e.object(l.contract.pool),d(c,e.pure.address),e.object(o.incentiveV2),e.object(o.incentiveV3),e.object("0x05")],typeArguments:[u.suiCoinType,l.suiCoinType]});return[b,h]}}async function ke(e,r){var b;const a=await Q(r),t=await F({...r,cacheTime:f}),c=(b=r==null?void 0:r.client)!=null?b:I,n=await y({...r,cacheTime:f}),s=new k.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 o=await c.devInspectTransactionBlock({transactionBlock:s,sender:e}),u=S(o,[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 h=u[0].length;for(let p=0;p<h;p++){const m=a.find(_=>g(_.coinType)===g(u[1][p])),C=t.find(_=>g(_.coinType)===g(u[0][p]));!m||!C||l.push({assetId:C.id,assetCoinType:g(u[0][p]),rewardCoinType:g(u[1][p]),option:Number(u[2][p]),userClaimableReward:Number(u[4][p])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(u[3][p])?u[3][p]:[u[3][p]]})}}return l}function Se(e){const r=new Map;e.forEach(t=>{const c=t.assetId,n=t.option,s=`${c}-${n}-${t.rewardCoinType}`;r.has(s)?r.get(s).total+=t.userClaimableReward:r.set(s,{assetId:c,rewardType:n,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const a=new Map;for(const{assetId:t,rewardType:c,coinType:n,total:s}of r.values()){const o=`${t}-${c}`;a.has(o)||a.set(o,{assetId:t,rewardType:c,rewards:new Map});const u=a.get(o);u.rewards.set(n,(u.rewards.get(n)||0)+s)}return Array.from(a.values()).map(t=>({assetId:t.assetId,rewardType:t.rewardType,rewards:Array.from(t.rewards.entries()).map(([c,n])=>({coinType:c,available:n.toFixed(6)}))}))}const Fe=j(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${T.version}`;return(await fetch(r,{headers:$}).then(t=>t.json())).data}),Ve=j(async(e,r)=>{const a=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${(r==null?void 0:r.page)||1}&pageSize=${(r==null?void 0:r.size)||400}&sdk=${T.version}`,t=await fetch(a,{headers:$}).then(c=>c.json());return V({data:t.data.rewards})});async function Re(e,r,a){var o;const t=await y({...a,cacheTime:f}),c=await F({...a,cacheTime:f}),n=new Map;for(const u of r){const{rewardCoinType:l,ruleIds:b}=u;for(const h of b){n.has(l)||n.set(l,{assetIds:[],ruleIds:[],amount:0});const p=n.get(l);p.assetIds.push(u.assetCoinType.replace("0x","")),p.ruleIds.push(h),p.amount+=u.userClaimableReward}}const s=[];for(const[u,{assetIds:l,ruleIds:b,amount:h}]of n){const p=c.find(C=>g(C.suiCoinType)===g(u));if(!p||!p.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${u}`);const m=p.contract.rewardFundId;if(a!=null&&a.accountCap&&!a.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(a!=null&&a.customCoinReceive){let C;a.accountCap?C=e.moveCall({target:`${t.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",b),d(a.accountCap,e.object)],typeArguments:[u]}):C=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",b)],typeArguments:[u]});const[_]=e.moveCall({target:"0x2::coin::from_balance",arguments:[C],typeArguments:[u]});if((a==null?void 0:a.customCoinReceive.type)==="transfer"){if(!a.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([_],d(a.customCoinReceive.transfer,e.pure.address))}if((a==null?void 0:a.customCoinReceive.type)==="depositNAVI"){const X=A(p.totalSupplyAmount).shiftedBy(-9),Z=A(p.supplyCapCeiling).shiftedBy(-27);X.plus(h).isGreaterThan(Z)&&((o=a==null?void 0:a.customCoinReceive.depositNAVI)!=null&&o.fallbackReceiveAddress)?e.transferObjects([_],e.pure.address(a.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await z(e,p,_,a)}else s.push({coin:_,identifier:p})}else e.moveCall({target:`${t.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",b)],typeArguments:[u]})}return s}async function Ne(e,r){const a=await y({...r});return e.moveCall({target:`${a.package}::lending::create_account`,arguments:[]})}exports.Address=N;exports.DEFAULT_CACHE_TIME=f;exports.FlashLoanAssetConfig=ae;exports.IncentiveAPYInfo=te;exports.IncentivePoolInfo=M;exports.IncentivePoolInfoByPhase=re;exports.OracleInfo=ce;exports.PoolOperator=B;exports.ReserveDataInfo=ne;exports.UserStateInfo=H;exports.borrowCoinPTB=fe;exports.claimLendingRewardsPTB=Re;exports.createAccountCapPTB=Ne;exports.depositCoinPTB=z;exports.filterPriceFeeds=Ae;exports.flashloanPTB=Pe;exports.getAllFlashLoanAssets=R;exports.getBorrowFee=ye;exports.getCoins=Te;exports.getConfig=y;exports.getFees=pe;exports.getFlashLoanAsset=Ie;exports.getHealthFactor=ve;exports.getHealthFactorPTB=W;exports.getLendingState=we;exports.getPool=v;exports.getPools=F;exports.getPriceFeeds=Q;exports.getPythStalePriceFeedId=Y;exports.getSimulatedHealthFactor=Ce;exports.getSimulatedHealthFactorPTB=E;exports.getStats=be;exports.getTransactions=je;exports.getUserAvailableLendingRewards=ke;exports.getUserClaimedRewardHistory=Ve;exports.getUserTotalClaimedReward=Fe;exports.liquidatePTB=Be;exports.mergeCoinsPTB=he;exports.normalizeCoinType=g;exports.parseTxValue=d;exports.repayCoinPTB=me;exports.repayFlashLoanPTB=$e;exports.summaryLendingRewards=Se;exports.updateOraclePricesPTB=_e;exports.updatePythPriceFeeds=K;exports.withCache=P;exports.withSingleton=j;exports.withdrawCoinPTB=ge;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),E=require("@mysten/sui/client"),Z=require("lodash.camelcase"),x=require("@mysten/sui/utils"),N=require("@pythnetwork/pyth-sui-js"),_=require("bignumber.js"),h=require("@mysten/sui/bcs"),R=i.bcs.bytes(32).transform({input:e=>i.fromHex(e),output:e=>i.toHex(e)}),ee=i.bcs.struct("IncentiveAPYInfo",{asset_id:i.bcs.u8(),apy:i.bcs.u256(),coin_types:i.bcs.vector(i.bcs.string())}),q=i.bcs.struct("IncentivePoolInfo",{pool_id:R,funds:R,phase:i.bcs.u64(),start_at:i.bcs.u64(),end_at:i.bcs.u64(),closed_at:i.bcs.u64(),total_supply:i.bcs.u64(),asset_id:i.bcs.u8(),option:i.bcs.u8(),factor:i.bcs.u256(),distributed:i.bcs.u64(),available:i.bcs.u256(),total:i.bcs.u256()}),te=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(q)}),ne=i.bcs.struct("OracleInfo",{oracle_id:i.bcs.u8(),price:i.bcs.u256(),decimals:i.bcs.u8(),valid:i.bcs.bool()}),re=i.bcs.struct("FlashLoanAssetConfig",{id:i.bcs.string(),asset_id:i.bcs.u8(),coin_type:i.bcs.string(),pool_id:i.bcs.string(),rate_to_supplier:i.bcs.u64(),rate_to_treasury:i.bcs.u64(),max:i.bcs.u64(),min:i.bcs.u64()}),oe=i.bcs.struct("ReserveDataInfo",{id:i.bcs.u8(),oracle_id:i.bcs.u8(),coin_type:i.bcs.string(),supply_cap:i.bcs.u256(),borrow_cap:i.bcs.u256(),supply_rate:i.bcs.u256(),borrow_rate:i.bcs.u256(),supply_index:i.bcs.u256(),borrow_index:i.bcs.u256(),total_supply:i.bcs.u256(),total_borrow:i.bcs.u256(),last_update_at:i.bcs.u64(),ltv:i.bcs.u256(),treasury_factor:i.bcs.u256(),treasury_balance:i.bcs.u256(),base_rate:i.bcs.u256(),multiplier:i.bcs.u256(),jump_rate_multiplier:i.bcs.u256(),reserve_factor:i.bcs.u256(),optimal_utilization:i.bcs.u256(),liquidation_ratio:i.bcs.u256(),liquidation_bonus:i.bcs.u256(),liquidation_threshold:i.bcs.u256()}),M=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),ce="1.3.7",j={version:ce},ae=j.version,se=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),r=process.version,c=e.type(),t=e.arch();return`Node.js ${r.startsWith("v")?r.substring(1):r}; ${c}/${t}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},ie=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${ae} (${se()})`),e},D=ie(),A=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function H(e){const r=[];return e.forEach((c,t)=>{const n=t===e.length-1;if(typeof c=="object"&&c!==null&&n){const{client:o,disableCache:s,cacheTime:a,...l}=c;r.push(l)}else r.push(c)}),JSON.stringify(r)}function C(e){const r={};return(...c)=>{const t=H(c);return r[t]||(r[t]=e(...c).finally(()=>{delete r[t]})),r[t]}}function I(e){let r={};return(...c)=>{const t=c[c.length-1],n=H(c),o=r[n];return!t?.disableCache&&typeof o?.data<"u"&&(typeof t?.cacheTime>"u"||t.cacheTime>Date.now()-o.cacheAt)?o.data:e(...c).then(s=>(r[n]={data:s,cacheAt:Date.now()},s))}}function F(e){return Array.isArray(e)?e.map(r=>F(r)):e!=null&&typeof e=="object"?Object.keys(e).reduce((r,c)=>({...r,[Z(c)]:F(e[c])}),{}):e}function p(e,r){return typeof e=="object"?e:r(e)}function ue(e,r){return typeof r=="string"?e.object(r):typeof r=="object"&&r.$kind?r:e.object(r.contract.pool)}function k(e,r,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,n)=>(r[n]||r[0]).parse(Uint8Array.from(t[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function b(e){return x.normalizeStructTag(e)}function O(e){const r=(e||0)/Math.pow(10,27);return r>Math.pow(10,5)?1/0:r}new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const le=27,U=(e,r)=>{if(!Number(e)||!Number(r))return new _(0);const c=new _(1).shiftedBy(1*le),t=c.multipliedBy(new _(.5));return new _(e).multipliedBy(new _(r)).plus(t).dividedBy(c).integerValue(_.ROUND_DOWN)},P=D?{"User-Agent":D}:{},y=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),g=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 S=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}));async function w(e,r){const c=await S({...r,cacheTime:g});if(typeof e=="object")return e;const t=c.find(n=>typeof e=="string"?b(n.suiCoinType)===b(e):typeof e=="number"?n.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 pe=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),de=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${j.version}`;return await fetch(r,{headers:P}).then(t=>t.json())}));async function G(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const s=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&s){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let a;return typeof t?.amount<"u"?a=p(t.amount,e.pure.u64):a=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap?e.moveCall({target:`${n.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]}):e.moveCall({target:`${n.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),n.version===2&&o.id===0&&e.moveCall({target:`${n.package}::pool::refresh_stake`,arguments:[e.object(o.contract.pool),e.object("0x05")]}),e}async function be(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),s=p(c,e.pure.u64);let a;if(n.version===1)if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});a=u}else if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[a],typeArguments:[o.suiCoinType]})}async function ge(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const s=p(c,e.pure.u64);let a;if(n.version===1)if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});a=u}else if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(a)],typeArguments:[o.suiCoinType]})}async function fe(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&s){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let a;if(typeof t?.amount<"u"?a=p(t.amount,e.pure.u64):a=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[l],typeArguments:[o.suiCoinType]})}else return e.moveCall({target:`${n.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),e}const me=I(C(async e=>{const r=await y({...e});if(e?.address&&typeof e?.asset<"u")try{const n=await w(e.asset,e),o=e?.client??A,s=new B.Transaction;s.moveCall({target:`${r.package}::incentive_v3::get_borrow_fee_v2`,arguments:[s.object(r.incentiveV3),s.pure.address(e.address),s.pure.u8(n.id),s.pure.u64(1e4)],typeArguments:[]});const a=await o.devInspectTransactionBlock({transactionBlock:s,sender:e.address}),l=k(a,[h.bcs.u64()]);return(Number(l[0])||0)/100}catch(n){console.error(n)}const t=(await A.getObject({id:r.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function ye(e,r,c){const t=typeof c?.balance=="number",n=t?c.balance:0;let o=0;const s=[];let a="";if(r.sort((u,f)=>Number(f.balance)-Number(u.balance)).forEach(u=>{if(!(t&&o>=n)&&Number(u.balance)!==0){if(a||(a=u.coinType),a!==u.coinType)throw new Error("All coins must be of the same type");o+=Number(u.balance),s.push(u.coinObjectId)}}),s.length===0)throw new Error("No coins to merge");if(t&&o<n)throw new Error(`Balance is less than the specified balance: ${o} < ${n}`);if(b(a)===b("0x2::sui::SUI")&&c?.useGasCoin)return t?e.splitCoins(e.gas,[e.pure.u64(n)]):e.gas;const l=s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1));return t?e.splitCoins(l,[e.pure.u64(n)]):l}async function L(e,r,c,t,n,o,s){const a=await y({...s,cacheTime:g}),l=await w(c,s);return e.moveCall({target:`${a.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(a.storage),e.object(a.oracle.priceOracle),ue(e,l),p(r,e.pure.address),p(l.id,e.pure.u8),p(t,e.pure.u64),p(n,e.pure.u64),p(o,e.pure.bool)],typeArguments:[l.suiCoinType]})}async function z(e,r,c){return L(e,r,0,0,0,!1,c)}const he=I(async(e,r)=>{const c=await y({...r,cacheTime:g}),t=new B.Transaction,n=r?.client??A,o=await S(r);t.moveCall({target:`${c.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(c.storage),t.pure.address(e)]});const s=await n.devInspectTransactionBlock({transactionBlock:t,sender:e}),a=k(s,[h.bcs.vector(M)]);return F(a[0].filter(u=>u.supply_balance!=="0"||u.borrow_balance!=="0")).map(u=>{const f=o.find(v=>v.id===u.assetId),d=U(u.supplyBalance,f.currentSupplyIndex).toString(),m=U(u.borrowBalance,f.currentBorrowIndex).toString();return{...u,supplyBalance:d,borrowBalance:m,pool:f}}).filter(u=>!!u.pool)});async function we(e,r){const c=r?.client??A,t=new B.Transaction;await z(t,e,r);const n=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=k(n,[h.bcs.u256()]);return O(Number(o[0])||0)}async function ve(e,r,c,t){const n=t?.client??A,o=new B.Transaction;let s=0,a=0;const l=await w(r,t);if(c.forEach(m=>{m.type===$.Supply?s+=m.amount:m.type===$.Withdraw?s-=m.amount:m.type===$.Borrow?a+=m.amount:m.type===$.Repay&&(a-=m.amount)}),s*a<0)throw new Error("Invalid operations");const u=s>0||a>0;await L(o,e,l,Math.abs(s),Math.abs(a),u,t);const f=await n.devInspectTransactionBlock({transactionBlock:o,sender:e}),d=k(f,[h.bcs.u256()]);return O(Number(d[0])||0)}const Ce=C(async(e,r)=>{const c=new URLSearchParams;r?.cursor&&c.set("cursor",r.cursor),c.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${c.toString()}&sdk=${j.version}`;return(await fetch(t,{headers:P}).then(o=>o.json())).data});async function je(e,r){let c=null;const t=[],n=r?.client??A;do{let o;if(r?.coinType?o=await n.getCoins({owner:e,coinType:r?.coinType,cursor:c,limit:100}):o=await n.getAllCoins({owner:e,cursor:c,limit:100}),!o.data||!o.data.length)break;t.push(...o.data),c=o.nextCursor}while(c);return t}const W=new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function J(e){try{const r=[],c=await W.getLatestPriceFeeds(e);if(!c)return r;const t=Math.floor(new Date().valueOf()/1e3);for(const n of c){const o=n.getPriceUnchecked();if(o.publishTime>t){console.warn(`pyth price feed is invalid, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`);continue}t-n.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`),r.push(n.id))}return r}catch(r){throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`)}}async function Y(e,r,c){const t=c?.client??A,n=await y({...c,cacheTime:g});try{const o=await W.getPriceFeedsUpdateData(r);return await new N.SuiPythClient(t,n.oracle.pythStateId,n.oracle.wormholeStateId).updatePriceFeeds(e,o,r)}catch(o){throw new Error(`failed to update pyth price feeds, msg: ${o.message}`)}}async function Te(e,r,c){const t=await y({...c,cacheTime:g});if(c?.updatePythPriceFeeds){const n=r.filter(o=>!!o.pythPriceFeedId).map(o=>o.pythPriceFeedId);try{const o=await J(n);o.length>0&&await Y(e,o,c)}catch{}}for(const n of r)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(n.pythPriceInfoObject),e.pure.address(n.feedId)]});return e}async function K(e){return(await y({...e,cacheTime:g})).oracle.feeds}function _e(e,r){return e.filter(c=>!!(r?.lendingState&&r.lendingState.find(n=>n.assetId===c.assetId)||r?.pools&&r.pools.find(n=>n.id===c.assetId)))}const V=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${j.version}`,c=await fetch(r,{headers:P}).then(t=>t.json());return Object.keys(c.data).map(t=>({...c.data[t],coinType:t}))}));async function Ae(e,r){return(await V(r)).find(t=>typeof e=="string"?b(t.coinType)===b(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function Ie(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(!(await V({...t,cacheTime:g})).some(l=>b(l.coinType)===b(o.suiCoinType)))throw new Error("Pool does not support flashloan");if(n.version===1){const[l,u]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64)],typeArguments:[o.suiCoinType]});return[l,u]}else{const[l,u]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64),e.object("0x05")],typeArguments:[o.suiCoinType]});return[l,u]}}async function Pe(e,r,c,t,n){const o=await y({...n,cacheTime:g}),s=await w(r,n);if(!(await V({...n,cacheTime:g})).some(f=>b(f.coinType)===b(s.suiCoinType)))throw new Error("Pool does not support flashloan");const[u]=e.moveCall({target:`${o.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(o.storage),e.object(s.contract.pool),p(c,e.object),p(t,e.object)],typeArguments:[s.suiCoinType]});return[u]}async function $e(e,r,c,t,n,o){const s={...o,cacheTime:g},a=await y(s),l=await w(r,s),u=await w(t,s);if(a.version===1){const[f,d]=e.moveCall({target:`${a.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(a.priceOracle),e.object(a.storage),e.pure.u8(l.id),e.object(l.contract.pool),p(c,e.object),e.pure.u8(u.id),e.object(u.contract.pool),p(n,e.pure.address),e.object(a.incentiveV2),e.object(a.incentiveV3)],typeArguments:[l.suiCoinType,u.suiCoinType]});return[f,d]}else{const[f,d]=e.moveCall({target:`${a.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(a.priceOracle),e.object(a.storage),e.pure.u8(l.id),e.object(l.contract.pool),p(c,e.object),e.pure.u8(u.id),e.object(u.contract.pool),p(n,e.pure.address),e.object(a.incentiveV2),e.object(a.incentiveV3),e.object("0x05")],typeArguments:[l.suiCoinType,u.suiCoinType]});return[f,d]}}async function Be(e,r){const c=await K(r),t=await S({...r,cacheTime:g}),n=r?.client??A,o=await y({...r,cacheTime:g}),s=new B.Transaction;s.moveCall({target:`${o.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[s.object("0x06"),s.object(o.storage),s.object(o.incentiveV3),s.pure.address(e)]});const a=await n.devInspectTransactionBlock({transactionBlock:s,sender:e}),l=k(a,[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())]),u=[];if(l.length===5&&Array.isArray(l[0])){const f=l[0].length;for(let d=0;d<f;d++){const m=c.find(T=>b(T.coinType)===b(l[1][d])),v=t.find(T=>b(T.coinType)===b(l[0][d]));!m||!v||u.push({assetId:v.id,assetCoinType:b(l[0][d]),rewardCoinType:b(l[1][d]),option:Number(l[2][d]),userClaimableReward:Number(l[4][d])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(l[3][d])?l[3][d]:[l[3][d]]})}}return u}function ke(e){const r=new Map;e.forEach(t=>{const n=t.assetId,o=t.option,s=`${n}-${o}-${t.rewardCoinType}`;r.has(s)?r.get(s).total+=t.userClaimableReward:r.set(s,{assetId:n,rewardType:o,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const c=new Map;for(const{assetId:t,rewardType:n,coinType:o,total:s}of r.values()){const a=`${t}-${n}`;c.has(a)||c.set(a,{assetId:t,rewardType:n,rewards:new Map});const l=c.get(a);l.rewards.set(o,(l.rewards.get(o)||0)+s)}return Array.from(c.values()).map(t=>({assetId:t.assetId,rewardType:t.rewardType,rewards:Array.from(t.rewards.entries()).map(([n,o])=>({coinType:n,available:o.toFixed(6)}))}))}const Se=C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}),Fe=C(async(e,r)=>{const c=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${r?.page||1}&pageSize=${r?.size||400}&sdk=${j.version}`,t=await fetch(c,{headers:P}).then(n=>n.json());return F({data:t.data.rewards})});async function Ve(e,r,c){const t=await y({...c,cacheTime:g}),n=await S({...c,cacheTime:g}),o=new Map;for(const a of r){const{rewardCoinType:l,ruleIds:u}=a;for(const f of u){o.has(l)||o.set(l,{assetIds:[],ruleIds:[],amount:0});const d=o.get(l);d.assetIds.push(a.assetCoinType.replace("0x","")),d.ruleIds.push(f),d.amount+=a.userClaimableReward}}const s=[];for(const[a,{assetIds:l,ruleIds:u,amount:f}]of o){const d=n.find(v=>b(v.suiCoinType)===b(a));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${a}`);const m=d.contract.rewardFundId;if(c?.accountCap&&!c.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(c?.customCoinReceive){let v;c.accountCap?v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",u),p(c.accountCap,e.object)],typeArguments:[a]}):v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",u)],typeArguments:[a]});const[T]=e.moveCall({target:"0x2::coin::from_balance",arguments:[v],typeArguments:[a]});if(c?.customCoinReceive.type==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([T],p(c.customCoinReceive.transfer,e.pure.address))}if(c?.customCoinReceive.type==="depositNAVI"){const Q=_(d.totalSupplyAmount).shiftedBy(-9),X=_(d.supplyCapCeiling).shiftedBy(-27);Q.plus(f).isGreaterThan(X)&&c?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([T],e.pure.address(c.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await G(e,d,T,c)}else s.push({coin:T,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(m),e.pure.vector("string",l),e.pure.vector("address",u)],typeArguments:[a]})}return s}async function Re(e,r){const c=await y({...r});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=g;exports.FlashLoanAssetConfig=re;exports.IncentiveAPYInfo=ee;exports.IncentivePoolInfo=q;exports.IncentivePoolInfoByPhase=te;exports.OracleInfo=ne;exports.PoolOperator=$;exports.ReserveDataInfo=oe;exports.UserStateInfo=M;exports.borrowCoinPTB=ge;exports.claimLendingRewardsPTB=Ve;exports.createAccountCapPTB=Re;exports.depositCoinPTB=G;exports.filterPriceFeeds=_e;exports.flashloanPTB=Ie;exports.getAllFlashLoanAssets=V;exports.getBorrowFee=me;exports.getCoins=je;exports.getConfig=y;exports.getFees=de;exports.getFlashLoanAsset=Ae;exports.getHealthFactor=we;exports.getHealthFactorPTB=z;exports.getLendingState=he;exports.getPool=w;exports.getPools=S;exports.getPriceFeeds=K;exports.getPythStalePriceFeedId=J;exports.getSimulatedHealthFactor=ve;exports.getSimulatedHealthFactorPTB=L;exports.getStats=pe;exports.getTransactions=Ce;exports.getUserAvailableLendingRewards=Be;exports.getUserClaimedRewardHistory=Fe;exports.getUserTotalClaimedReward=Se;exports.liquidatePTB=$e;exports.mergeCoinsPTB=ye;exports.normalizeCoinType=b;exports.parseTxValue=p;exports.repayCoinPTB=fe;exports.repayFlashLoanPTB=Pe;exports.summaryLendingRewards=ke;exports.updateOraclePricesPTB=Te;exports.updatePythPriceFeeds=Y;exports.withCache=I;exports.withSingleton=C;exports.withdrawCoinPTB=be;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|