@naviprotocol/lending 1.3.4-dev.5 → 1.3.4
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 +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),E=require("@mysten/sui/client"),x=require("lodash.camelcase"),ee=require("@mysten/sui/utils"),N=require("@pythnetwork/pyth-sui-js"),_=require("bignumber.js"),w=require("@mysten/sui/bcs"),R=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())}),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()}),ce=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(q)}),re=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()}),M=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),se="1.3.4-dev.5",H={version:se},oe=H.version,ie=()=>{if(typeof process!="undefined"&&process.versions&&process.versions.node)try{const e=require("os"),c=process.version,a=e.type(),t=e.arch();return`Node.js ${c.startsWith("v")?c.substring(1):c}; ${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},U=ue(),A=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function O(e){const c=[];return e.forEach((a,t)=>{const r=t===e.length-1;if(typeof a=="object"&&r){const{client:n,disableCache:s,cacheTime:o,...u}=a;c.push(u)}else c.push(a)}),JSON.stringify(c)}function j(e){const c={};return(...a)=>{const t=O(a);return c[t]||(c[t]=e(...a).finally(()=>{c[t]=null})),c[t]}}function I(e){let c={};return(...a)=>{const t=a[a.length-1],r=O(a),n=c[r];return!(t!=null&&t.disableCache)&&typeof(n==null?void 0:n.data)!="undefined"&&(typeof(t==null?void 0:t.cacheTime)=="undefined"||t.cacheTime>Date.now()-n.cacheAt)?n.data:e(...a).then(s=>(c[r]={data:s,cacheAt:Date.now()},s))}}function F(e){return Array.isArray(e)?e.map(c=>F(c)):e!=null&&typeof e=="object"?Object.keys(e).reduce((c,a)=>({...c,[x(a)]:F(e[a])}),{}):e}function d(e,c){return typeof e=="object"?e:c(e)}function le(e,c){return typeof c=="string"?e.object(c):typeof c=="object"&&c.$kind?c:e.object(c.contract.pool)}function k(e,c,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,r)=>(c[r]||c[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 c=(e||0)/Math.pow(10,27);return c>Math.pow(10,5)?1/0:c}new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const de=27,D=(e,c)=>{if(!Number(e)||!Number(c))return new _(0);const a=new _(1).shiftedBy(1*de),t=a.multipliedBy(new _(.5));return new _(e).multipliedBy(new _(c)).plus(t).dividedBy(a).integerValue(_.ROUND_DOWN)},P=U?{"User-Agent":U}:{},y=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/config?env=${(e==null?void 0:e.env)||"prod"}&sdk=${H.version}`;return(await fetch(c,{headers:P}).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 S=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/pools?env=${(e==null?void 0:e.env)||"prod"}`;return(await fetch(c,{headers:P}).then(t=>t.json())).data}));async function v(e,c){const a=await S({...c,cacheTime:f});if(typeof e=="object")return e;const t=a.find(r=>typeof e=="string"?g(r.suiCoinType)===g(e):typeof e=="number"?r.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=I(j(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats",{headers:P}).then(t=>t.json())).data)),pe=I(j(async e=>await fetch("https://open-api.naviprotocol.io/api/navi/fee",{headers:P}).then(t=>t.json())));async function z(e,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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:`${r.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]}):e.moveCall({target:`${r.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),r.version===2&&n.id===0&&e.moveCall({target:`${r.package}::pool::refresh_stake`,arguments:[e.object(n.contract.pool),e.object("0x05")]}),e}async function ge(e,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,t),s=d(a,e.pure.u64);let o;if(r.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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(r.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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:`${r.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(r.incentiveV2),e.object(r.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:`${r.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}const ye=I(j(async e=>{var r;const c=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=(r=e==null?void 0:e.client)!=null?r:A,o=new $.Transaction;o.moveCall({target:`${c.package}::incentive_v3::get_borrow_fee_v2`,arguments:[o.object(c.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=k(u,[w.bcs.u64()]);return(Number(l[0])||0)/100}catch(n){console.error(n)}const t=(await A.getObject({id:c.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function he(e,c,a){const t=typeof(a==null?void 0:a.balance)=="number",r=t?a.balance:0;let n=0;const s=[];let o="";if(c.sort((l,b)=>Number(b.balance)-Number(l.balance)).forEach(l=>{if(!(t&&n>=r)&&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<r)throw new Error(`Balance is less than the specified balance: ${n} < ${r}`);if(g(o)===g("0x2::sui::SUI")&&(a!=null&&a.useGasCoin))return t?e.splitCoins(e.gas,[e.pure.u64(r)]):e.gas;const u=s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1));return t?e.splitCoins(u,[e.pure.u64(r)]):u}async function L(e,c,a,t,r,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(c,e.pure.address),d(u.id,e.pure.u8),d(t,e.pure.u64),d(r,e.pure.u64),d(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function W(e,c,a){return L(e,c,0,0,0,!1,a)}const we=I(async(e,c)=>{var l;const a=await y({...c,cacheTime:f}),t=new $.Transaction,r=(l=c==null?void 0:c.client)!=null?l:A,n=await S(c);t.moveCall({target:`${a.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(a.storage),t.pure.address(e)]});const s=await r.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=k(s,[w.bcs.vector(M)]);return F(o[0].filter(b=>b.supply_balance!=="0"||b.borrow_balance!=="0")).map(b=>{const h=n.find(C=>C.id===b.assetId),p=D(b.supplyBalance,h.currentSupplyIndex).toString(),m=D(b.borrowBalance,h.currentBorrowIndex).toString();return{...b,supplyBalance:p,borrowBalance:m,pool:h}}).filter(b=>!!b.pool)});async function ve(e,c){var s;const a=(s=c==null?void 0:c.client)!=null?s:A,t=new $.Transaction;await W(t,e,c);const r=await a.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=k(r,[w.bcs.u256()]);return G(Number(n[0])||0)}async function Ce(e,c,a,t){var p;const r=(p=t==null?void 0:t.client)!=null?p:A,n=new $.Transaction;let s=0,o=0;const u=await v(c,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 L(n,e,u,Math.abs(s),Math.abs(o),l,t);const b=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),h=k(b,[w.bcs.u256()]);return G(Number(h[0])||0)}const je=j(async(e,c)=>{const a=new URLSearchParams;c!=null&&c.cursor&&a.set("cursor",c.cursor),a.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${a.toString()}`;return(await fetch(t,{headers:P}).then(n=>n.json())).data});async function Te(e,c){var n;let a=null;const t=[],r=(n=c==null?void 0:c.client)!=null?n:A;do{let s;if(c!=null&&c.coinType?s=await r.getCoins({owner:e,coinType:c==null?void 0:c.coinType,cursor:a,limit:100}):s=await r.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 N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function Y(e){try{const c=[],a=await J.getLatestPriceFeeds(e);if(!a)return c;const t=Math.floor(new Date().valueOf()/1e3);for(const r of a){const n=r.getPriceUnchecked();if(n.publishTime>t){console.warn(`pyth price feed is invalid, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`);continue}t-r.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`),c.push(r.id))}return c}catch(c){throw new Error(`failed to get pyth stale price feed id, msg: ${c.message}`)}}async function K(e,c,a){var n;const t=(n=a==null?void 0:a.client)!=null?n:A,r=await y({...a,cacheTime:f});try{const s=await J.getPriceFeedsUpdateData(c);return await new N.SuiPythClient(t,r.oracle.pythStateId,r.oracle.wormholeStateId).updatePriceFeeds(e,s,c)}catch(s){throw new Error(`failed to update pyth price feeds, msg: ${s.message}`)}}async function _e(e,c,a){const t=await y({...a,cacheTime:f});if(a!=null&&a.updatePythPriceFeeds){const r=c.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await Y(r);n.length>0&&await K(e,n,a)}catch{}}for(const r of c)e.moveCall({target:`${t.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(t.oracle.oracleConfig),e.object(t.oracle.priceOracle),e.object(t.oracle.supraOracleHolder),e.object(r.pythPriceInfoObject),e.pure.address(r.feedId)]});return e}async function Q(e){return(await y({...e,cacheTime:f})).oracle.feeds}function Ae(e,c){return e.filter(a=>!!(c!=null&&c.lendingState&&c.lendingState.find(r=>r.assetId===a.assetId)||c!=null&&c.pools&&c.pools.find(r=>r.id===a.assetId)))}const V=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${(e==null?void 0:e.env)||"prod"}`,a=await fetch(c,{headers:P}).then(t=>t.json());return Object.keys(a.data).map(t=>({...a.data[t],coinType:t}))}));async function Ie(e,c){return(await V(c)).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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,t);if(!(await V({...t,cacheTime:f})).some(u=>g(u.coinType)===g(n.suiCoinType)))throw new Error("Pool does not support flashloan");if(r.version===1){const[u,l]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx`,arguments:[e.object(r.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}else{const[u,l]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(r.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64),e.object("0x05")],typeArguments:[n.suiCoinType]});return[u,l]}}async function Be(e,c,a,t,r){const n=await y({...r,cacheTime:f}),s=await v(c,r);if(!(await V({...r,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 $e(e,c,a,t,r,n){const s={...n,cacheTime:f},o=await y(s),u=await v(c,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(r,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(r,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,c){var b;const a=await Q(c),t=await S({...c,cacheTime:f}),r=(b=c==null?void 0:c.client)!=null?b:A,n=await y({...c,cacheTime:f}),s=new $.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 r.devInspectTransactionBlock({transactionBlock:s,sender:e}),u=k(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(T=>g(T.coinType)===g(u[1][p])),C=t.find(T=>g(T.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 c=new Map;e.forEach(t=>{const r=t.assetId,n=t.option,s=`${r}-${n}-${t.rewardCoinType}`;c.has(s)?c.get(s).total+=t.userClaimableReward:c.set(s,{assetId:r,rewardType:n,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const a=new Map;for(const{assetId:t,rewardType:r,coinType:n,total:s}of c.values()){const o=`${t}-${r}`;a.has(o)||a.set(o,{assetId:t,rewardType:r,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(([r,n])=>({coinType:r,available:n.toFixed(6)}))}))}const Fe=j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}`;return(await fetch(c,{headers:P}).then(t=>t.json())).data}),Ve=j(async(e,c)=>{const a=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${(c==null?void 0:c.page)||1}&pageSize=${(c==null?void 0:c.size)||400}`,t=await fetch(a,{headers:P}).then(r=>r.json());return F({data:t.data.rewards})});async function Re(e,c,a){var o;const t=await y({...a,cacheTime:f}),r=await S({...a,cacheTime:f}),n=new Map;for(const u of c){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=r.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[T]=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([T],d(a.customCoinReceive.transfer,e.pure.address))}if((a==null?void 0:a.customCoinReceive.type)==="depositNAVI"){const X=_(p.totalSupplyAmount).shiftedBy(-9),Z=_(p.supplyCapCeiling).shiftedBy(-27);X.plus(h).isGreaterThan(Z)&&((o=a==null?void 0:a.customCoinReceive.depositNAVI)!=null&&o.fallbackReceiveAddress)?e.transferObjects([T],e.pure.address(a.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await z(e,p,T,a)}else s.push({coin:T,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,c){const a=await y({...c});return e.moveCall({target:`${a.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=f;exports.FlashLoanAssetConfig=ae;exports.IncentiveAPYInfo=te;exports.IncentivePoolInfo=q;exports.IncentivePoolInfoByPhase=ce;exports.OracleInfo=re;exports.PoolOperator=B;exports.ReserveDataInfo=ne;exports.UserStateInfo=M;exports.borrowCoinPTB=fe;exports.claimLendingRewardsPTB=Re;exports.createAccountCapPTB=Ne;exports.depositCoinPTB=z;exports.filterPriceFeeds=Ae;exports.flashloanPTB=Pe;exports.getAllFlashLoanAssets=V;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=S;exports.getPriceFeeds=Q;exports.getPythStalePriceFeedId=Y;exports.getSimulatedHealthFactor=Ce;exports.getSimulatedHealthFactorPTB=L;exports.getStats=be;exports.getTransactions=je;exports.getUserAvailableLendingRewards=ke;exports.getUserClaimedRewardHistory=Ve;exports.getUserTotalClaimedReward=Fe;exports.liquidatePTB=$e;exports.mergeCoinsPTB=he;exports.normalizeCoinType=g;exports.parseTxValue=d;exports.repayCoinPTB=me;exports.repayFlashLoanPTB=Be;exports.summaryLendingRewards=Se;exports.updateOraclePricesPTB=_e;exports.updatePythPriceFeeds=K;exports.withCache=I;exports.withSingleton=j;exports.withdrawCoinPTB=ge;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),E=require("@mysten/sui/client"),x=require("lodash.camelcase"),ee=require("@mysten/sui/utils"),N=require("@pythnetwork/pyth-sui-js"),_=require("bignumber.js"),w=require("@mysten/sui/bcs"),R=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())}),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()}),ce=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(q)}),re=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()}),M=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),se="1.3.4",H={version:se},oe=H.version,ie=()=>{if(typeof process!="undefined"&&process.versions&&process.versions.node)try{const e=require("os"),c=process.version,a=e.type(),t=e.arch();return`Node.js ${c.startsWith("v")?c.substring(1):c}; ${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},U=ue(),A=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function O(e){const c=[];return e.forEach((a,t)=>{const r=t===e.length-1;if(typeof a=="object"&&r){const{client:n,disableCache:s,cacheTime:o,...u}=a;c.push(u)}else c.push(a)}),JSON.stringify(c)}function j(e){const c={};return(...a)=>{const t=O(a);return c[t]||(c[t]=e(...a).finally(()=>{c[t]=null})),c[t]}}function I(e){let c={};return(...a)=>{const t=a[a.length-1],r=O(a),n=c[r];return!(t!=null&&t.disableCache)&&typeof(n==null?void 0:n.data)!="undefined"&&(typeof(t==null?void 0:t.cacheTime)=="undefined"||t.cacheTime>Date.now()-n.cacheAt)?n.data:e(...a).then(s=>(c[r]={data:s,cacheAt:Date.now()},s))}}function F(e){return Array.isArray(e)?e.map(c=>F(c)):e!=null&&typeof e=="object"?Object.keys(e).reduce((c,a)=>({...c,[x(a)]:F(e[a])}),{}):e}function d(e,c){return typeof e=="object"?e:c(e)}function le(e,c){return typeof c=="string"?e.object(c):typeof c=="object"&&c.$kind?c:e.object(c.contract.pool)}function k(e,c,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,r)=>(c[r]||c[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 c=(e||0)/Math.pow(10,27);return c>Math.pow(10,5)?1/0:c}new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const de=27,D=(e,c)=>{if(!Number(e)||!Number(c))return new _(0);const a=new _(1).shiftedBy(1*de),t=a.multipliedBy(new _(.5));return new _(e).multipliedBy(new _(c)).plus(t).dividedBy(a).integerValue(_.ROUND_DOWN)},P=U?{"User-Agent":U}:{},y=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/config?env=${(e==null?void 0:e.env)||"prod"}&sdk=${H.version}`;return(await fetch(c,{headers:P}).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 S=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/pools?env=${(e==null?void 0:e.env)||"prod"}`;return(await fetch(c,{headers:P}).then(t=>t.json())).data}));async function v(e,c){const a=await S({...c,cacheTime:f});if(typeof e=="object")return e;const t=a.find(r=>typeof e=="string"?g(r.suiCoinType)===g(e):typeof e=="number"?r.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=I(j(async e=>(await fetch("https://open-api.naviprotocol.io/api/navi/stats",{headers:P}).then(t=>t.json())).data)),pe=I(j(async e=>await fetch("https://open-api.naviprotocol.io/api/navi/fee",{headers:P}).then(t=>t.json())));async function z(e,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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:`${r.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]}):e.moveCall({target:`${r.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),r.version===2&&n.id===0&&e.moveCall({target:`${r.package}::pool::refresh_stake`,arguments:[e.object(n.contract.pool),e.object("0x05")]}),e}async function ge(e,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,t),s=d(a,e.pure.u64);let o;if(r.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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(r.version===1)if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object)],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]});o=l}else if(t!=null&&t.accountCap){const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),d(t.accountCap,e.object),e.object("0x05")],typeArguments:[n.suiCoinType]});o=l}else{const[l]=e.moveCall({target:`${r.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),s,e.object(r.incentiveV2),e.object(r.incentiveV3),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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,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:`${r.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),e.object(r.incentiveV2),e.object(r.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:`${r.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(n.contract.pool),e.pure.u8(n.id),d(a,e.object),o,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[n.suiCoinType]}),e}const ye=I(j(async e=>{var r;const c=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=(r=e==null?void 0:e.client)!=null?r:A,o=new $.Transaction;o.moveCall({target:`${c.package}::incentive_v3::get_borrow_fee_v2`,arguments:[o.object(c.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=k(u,[w.bcs.u64()]);return(Number(l[0])||0)/100}catch(n){console.error(n)}const t=(await A.getObject({id:c.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function he(e,c,a){const t=typeof(a==null?void 0:a.balance)=="number",r=t?a.balance:0;let n=0;const s=[];let o="";if(c.sort((l,b)=>Number(b.balance)-Number(l.balance)).forEach(l=>{if(!(t&&n>=r)&&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<r)throw new Error(`Balance is less than the specified balance: ${n} < ${r}`);if(g(o)===g("0x2::sui::SUI")&&(a!=null&&a.useGasCoin))return t?e.splitCoins(e.gas,[e.pure.u64(r)]):e.gas;const u=s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1));return t?e.splitCoins(u,[e.pure.u64(r)]):u}async function L(e,c,a,t,r,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(c,e.pure.address),d(u.id,e.pure.u8),d(t,e.pure.u64),d(r,e.pure.u64),d(n,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function W(e,c,a){return L(e,c,0,0,0,!1,a)}const we=I(async(e,c)=>{var l;const a=await y({...c,cacheTime:f}),t=new $.Transaction,r=(l=c==null?void 0:c.client)!=null?l:A,n=await S(c);t.moveCall({target:`${a.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(a.storage),t.pure.address(e)]});const s=await r.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=k(s,[w.bcs.vector(M)]);return F(o[0].filter(b=>b.supply_balance!=="0"||b.borrow_balance!=="0")).map(b=>{const h=n.find(C=>C.id===b.assetId),p=D(b.supplyBalance,h.currentSupplyIndex).toString(),m=D(b.borrowBalance,h.currentBorrowIndex).toString();return{...b,supplyBalance:p,borrowBalance:m,pool:h}}).filter(b=>!!b.pool)});async function ve(e,c){var s;const a=(s=c==null?void 0:c.client)!=null?s:A,t=new $.Transaction;await W(t,e,c);const r=await a.devInspectTransactionBlock({transactionBlock:t,sender:e}),n=k(r,[w.bcs.u256()]);return G(Number(n[0])||0)}async function Ce(e,c,a,t){var p;const r=(p=t==null?void 0:t.client)!=null?p:A,n=new $.Transaction;let s=0,o=0;const u=await v(c,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 L(n,e,u,Math.abs(s),Math.abs(o),l,t);const b=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),h=k(b,[w.bcs.u256()]);return G(Number(h[0])||0)}const je=j(async(e,c)=>{const a=new URLSearchParams;c!=null&&c.cursor&&a.set("cursor",c.cursor),a.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${a.toString()}`;return(await fetch(t,{headers:P}).then(n=>n.json())).data});async function Te(e,c){var n;let a=null;const t=[],r=(n=c==null?void 0:c.client)!=null?n:A;do{let s;if(c!=null&&c.coinType?s=await r.getCoins({owner:e,coinType:c==null?void 0:c.coinType,cursor:a,limit:100}):s=await r.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 N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function Y(e){try{const c=[],a=await J.getLatestPriceFeeds(e);if(!a)return c;const t=Math.floor(new Date().valueOf()/1e3);for(const r of a){const n=r.getPriceUnchecked();if(n.publishTime>t){console.warn(`pyth price feed is invalid, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`);continue}t-r.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${r.id}, publish time: ${n.publishTime}, current timestamp: ${t}`),c.push(r.id))}return c}catch(c){throw new Error(`failed to get pyth stale price feed id, msg: ${c.message}`)}}async function K(e,c,a){var n;const t=(n=a==null?void 0:a.client)!=null?n:A,r=await y({...a,cacheTime:f});try{const s=await J.getPriceFeedsUpdateData(c);return await new N.SuiPythClient(t,r.oracle.pythStateId,r.oracle.wormholeStateId).updatePriceFeeds(e,s,c)}catch(s){throw new Error(`failed to update pyth price feeds, msg: ${s.message}`)}}async function _e(e,c,a){const t=await y({...a,cacheTime:f});if(a!=null&&a.updatePythPriceFeeds){const r=c.filter(n=>!!n.pythPriceFeedId).map(n=>n.pythPriceFeedId);try{const n=await Y(r);n.length>0&&await K(e,n,a)}catch{}}for(const r of c)e.moveCall({target:`${t.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(t.oracle.oracleConfig),e.object(t.oracle.priceOracle),e.object(t.oracle.supraOracleHolder),e.object(r.pythPriceInfoObject),e.pure.address(r.feedId)]});return e}async function Q(e){return(await y({...e,cacheTime:f})).oracle.feeds}function Ae(e,c){return e.filter(a=>!!(c!=null&&c.lendingState&&c.lendingState.find(r=>r.assetId===a.assetId)||c!=null&&c.pools&&c.pools.find(r=>r.id===a.assetId)))}const V=I(j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${(e==null?void 0:e.env)||"prod"}`,a=await fetch(c,{headers:P}).then(t=>t.json());return Object.keys(a.data).map(t=>({...a.data[t],coinType:t}))}));async function Ie(e,c){return(await V(c)).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,c,a,t){const r=await y({...t,cacheTime:f}),n=await v(c,t);if(!(await V({...t,cacheTime:f})).some(u=>g(u.coinType)===g(n.suiCoinType)))throw new Error("Pool does not support flashloan");if(r.version===1){const[u,l]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx`,arguments:[e.object(r.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64)],typeArguments:[n.suiCoinType]});return[u,l]}else{const[u,l]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(r.flashloanConfig),e.object(n.contract.pool),d(a,e.pure.u64),e.object("0x05")],typeArguments:[n.suiCoinType]});return[u,l]}}async function Be(e,c,a,t,r){const n=await y({...r,cacheTime:f}),s=await v(c,r);if(!(await V({...r,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 $e(e,c,a,t,r,n){const s={...n,cacheTime:f},o=await y(s),u=await v(c,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(r,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(r,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,c){var b;const a=await Q(c),t=await S({...c,cacheTime:f}),r=(b=c==null?void 0:c.client)!=null?b:A,n=await y({...c,cacheTime:f}),s=new $.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 r.devInspectTransactionBlock({transactionBlock:s,sender:e}),u=k(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(T=>g(T.coinType)===g(u[1][p])),C=t.find(T=>g(T.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 c=new Map;e.forEach(t=>{const r=t.assetId,n=t.option,s=`${r}-${n}-${t.rewardCoinType}`;c.has(s)?c.get(s).total+=t.userClaimableReward:c.set(s,{assetId:r,rewardType:n,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const a=new Map;for(const{assetId:t,rewardType:r,coinType:n,total:s}of c.values()){const o=`${t}-${r}`;a.has(o)||a.set(o,{assetId:t,rewardType:r,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(([r,n])=>({coinType:r,available:n.toFixed(6)}))}))}const Fe=j(async e=>{const c=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}`;return(await fetch(c,{headers:P}).then(t=>t.json())).data}),Ve=j(async(e,c)=>{const a=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${(c==null?void 0:c.page)||1}&pageSize=${(c==null?void 0:c.size)||400}`,t=await fetch(a,{headers:P}).then(r=>r.json());return F({data:t.data.rewards})});async function Re(e,c,a){var o;const t=await y({...a,cacheTime:f}),r=await S({...a,cacheTime:f}),n=new Map;for(const u of c){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=r.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[T]=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([T],d(a.customCoinReceive.transfer,e.pure.address))}if((a==null?void 0:a.customCoinReceive.type)==="depositNAVI"){const X=_(p.totalSupplyAmount).shiftedBy(-9),Z=_(p.supplyCapCeiling).shiftedBy(-27);X.plus(h).isGreaterThan(Z)&&((o=a==null?void 0:a.customCoinReceive.depositNAVI)!=null&&o.fallbackReceiveAddress)?e.transferObjects([T],e.pure.address(a.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await z(e,p,T,a)}else s.push({coin:T,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,c){const a=await y({...c});return e.moveCall({target:`${a.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=f;exports.FlashLoanAssetConfig=ae;exports.IncentiveAPYInfo=te;exports.IncentivePoolInfo=q;exports.IncentivePoolInfoByPhase=ce;exports.OracleInfo=re;exports.PoolOperator=B;exports.ReserveDataInfo=ne;exports.UserStateInfo=M;exports.borrowCoinPTB=fe;exports.claimLendingRewardsPTB=Re;exports.createAccountCapPTB=Ne;exports.depositCoinPTB=z;exports.filterPriceFeeds=Ae;exports.flashloanPTB=Pe;exports.getAllFlashLoanAssets=V;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=S;exports.getPriceFeeds=Q;exports.getPythStalePriceFeedId=Y;exports.getSimulatedHealthFactor=Ce;exports.getSimulatedHealthFactorPTB=L;exports.getStats=be;exports.getTransactions=je;exports.getUserAvailableLendingRewards=ke;exports.getUserClaimedRewardHistory=Ve;exports.getUserTotalClaimedReward=Fe;exports.liquidatePTB=$e;exports.mergeCoinsPTB=he;exports.normalizeCoinType=g;exports.parseTxValue=d;exports.repayCoinPTB=me;exports.repayFlashLoanPTB=Be;exports.summaryLendingRewards=Se;exports.updateOraclePricesPTB=_e;exports.updatePythPriceFeeds=K;exports.withCache=I;exports.withSingleton=j;exports.withdrawCoinPTB=ge;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/bcs.ts","../src/ua.ts","../src/utils.ts","../src/config.ts","../src/pool.ts","../src/account.ts","../src/oracle.ts","../src/flashloan.ts","../src/liquidate.ts","../src/reward.ts","../src/account-cap.ts"],"sourcesContent":["/**\n * BCS (Binary Canonical Serialization) Schemas for Lending Protocol\n *\n * This module defines the BCS schemas for serializing and deserializing\n * lending protocol data structures. BCS is used for efficient binary\n * encoding of complex data types for blockchain transactions and storage.\n */\n\nimport { bcs, fromHex, toHex } from '@mysten/bcs'\n\n/**\n * BCS schema for Sui addresses with hex transformation\n * Converts between hex string representation and byte arrays\n */\nexport const Address = bcs.bytes(32).transform({\n // To change the input type, you need to provide a type definition for the input\n input: (val: string) => fromHex(val),\n output: (val) => toHex(val)\n})\n\n/**\n * BCS schema for incentive APY information\n * Contains asset ID, APY value, and supported coin types\n */\nexport const IncentiveAPYInfo = bcs.struct('IncentiveAPYInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Annual Percentage Yield as a 256-bit integer */\n apy: bcs.u256(),\n /** List of supported coin types for this incentive */\n coin_types: bcs.vector(bcs.string())\n})\n\n/**\n * BCS schema for incentive pool information\n * Contains comprehensive details about a lending incentive pool\n */\nexport const IncentivePoolInfo = bcs.struct('IncentivePoolInfo', {\n /** Unique pool identifier */\n pool_id: Address,\n /** Address holding the incentive funds */\n funds: Address,\n /** Current phase of the incentive program */\n phase: bcs.u64(),\n /** Timestamp when the incentive started */\n start_at: bcs.u64(),\n /** Timestamp when the incentive ends */\n end_at: bcs.u64(),\n /** Timestamp when the incentive was closed */\n closed_at: bcs.u64(),\n /** Total supply of incentive tokens */\n total_supply: bcs.u64(),\n /** Asset identifier for the incentive */\n asset_id: bcs.u8(),\n /** Option type for the incentive */\n option: bcs.u8(),\n /** Factor used in incentive calculations */\n factor: bcs.u256(),\n /** Amount of incentives already distributed */\n distributed: bcs.u64(),\n /** Amount of incentives currently available */\n available: bcs.u256(),\n /** Total amount of incentives */\n total: bcs.u256()\n})\n\n/**\n * BCS schema for incentive pool information grouped by phase\n * Contains phase number and list of pools in that phase\n */\nexport const IncentivePoolInfoByPhase = bcs.struct('IncentivePoolInfoByPhase', {\n /** Phase number */\n phase: bcs.u64(),\n /** List of incentive pools in this phase */\n pools: bcs.vector(IncentivePoolInfo)\n})\n\n/**\n * BCS schema for oracle price information\n * Contains price data from external price feeds\n */\nexport const OracleInfo = bcs.struct('OracleInfo', {\n /** Oracle identifier */\n oracle_id: bcs.u8(),\n /** Current price as a 256-bit integer */\n price: bcs.u256(),\n /** Number of decimal places for the price */\n decimals: bcs.u8(),\n /** Whether the oracle data is valid */\n valid: bcs.bool()\n})\n\n/**\n * BCS schema for flash loan asset configuration\n * Contains parameters for flash loan functionality\n */\nexport const FlashLoanAssetConfig = bcs.struct('FlashLoanAssetConfig', {\n /** Unique identifier for the flash loan asset */\n id: bcs.string(),\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Coin type for the asset */\n coin_type: bcs.string(),\n /** Pool identifier for the flash loan */\n pool_id: bcs.string(),\n /** Rate paid to suppliers for flash loans */\n rate_to_supplier: bcs.u64(),\n /** Rate paid to treasury for flash loans */\n rate_to_treasury: bcs.u64(),\n /** Maximum flash loan amount */\n max: bcs.u64(),\n /** Minimum flash loan amount */\n min: bcs.u64()\n})\n\n/**\n * BCS schema for reserve data information\n * Contains comprehensive details about a lending reserve\n */\nexport const ReserveDataInfo = bcs.struct('ReserveDataInfo', {\n /** Reserve identifier */\n id: bcs.u8(),\n /** Oracle identifier for price feeds */\n oracle_id: bcs.u8(),\n /** Coin type for the reserve */\n coin_type: bcs.string(),\n /** Maximum supply capacity */\n supply_cap: bcs.u256(),\n /** Maximum borrow capacity */\n borrow_cap: bcs.u256(),\n /** Current supply interest rate */\n supply_rate: bcs.u256(),\n /** Current borrow interest rate */\n borrow_rate: bcs.u256(),\n /** Current supply index for interest calculation */\n supply_index: bcs.u256(),\n /** Current borrow index for interest calculation */\n borrow_index: bcs.u256(),\n /** Total amount supplied to the reserve */\n total_supply: bcs.u256(),\n /** Total amount borrowed from the reserve */\n total_borrow: bcs.u256(),\n /** Timestamp of last update */\n last_update_at: bcs.u64(),\n /** Loan-to-Value ratio for collateral */\n ltv: bcs.u256(),\n /** Treasury factor for fee calculations */\n treasury_factor: bcs.u256(),\n /** Current treasury balance */\n treasury_balance: bcs.u256(),\n /** Base interest rate */\n base_rate: bcs.u256(),\n /** Interest rate multiplier */\n multiplier: bcs.u256(),\n /** Jump rate multiplier for high utilization */\n jump_rate_multiplier: bcs.u256(),\n /** Reserve factor for protocol fees */\n reserve_factor: bcs.u256(),\n /** Optimal utilization rate */\n optimal_utilization: bcs.u256(),\n /** Liquidation ratio threshold */\n liquidation_ratio: bcs.u256(),\n /** Liquidation bonus for liquidators */\n liquidation_bonus: bcs.u256(),\n /** Liquidation threshold */\n liquidation_threshold: bcs.u256()\n})\n\n/**\n * BCS schema for user state information\n * Contains user's borrowing and supplying balances for an asset\n */\nexport const UserStateInfo = bcs.struct('UserStateInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** User's current borrow balance */\n borrow_balance: bcs.u256(),\n /** User's current supply balance */\n supply_balance: bcs.u256()\n})\n","import packageJson from '../package.json'\n\nconst sdkVersion = packageJson.version\n\nconst getNodeInfo = (): string => {\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n try {\n const os = require('os')\n const nodeVersion: string = process.version\n const osType: string = os.type()\n const osArch: string = os.arch()\n\n const formattedNodeVersion: string = nodeVersion.startsWith('v')\n ? nodeVersion.substring(1)\n : nodeVersion\n\n return `Node.js ${formattedNodeVersion}; ${osType}/${osArch}`\n } catch (e) {\n return `Node.js ${process.version}; OS/Unknown (Error)`\n }\n }\n return 'Node/Unknown'\n}\n\nexport const getUserAgent = (): string => {\n let environmentInfo: string = ''\n\n const isNode = typeof process !== 'undefined' && process.versions && process.versions.node\n\n if (isNode) {\n environmentInfo = `lending/${sdkVersion} (${getNodeInfo()})`\n }\n\n return environmentInfo\n}\n\nexport const userAgent = getUserAgent()\n","/**\n * Lending Utilities\n *\n * This module provides utility functions for the lending protocol, including\n * caching mechanisms, data transformation, transaction parsing, and blockchain\n * interaction helpers.\n *\n * @module LendingUtils\n */\n\nimport type { CacheOption, Pool, TransactionResult } from './types'\nimport type { DevInspectResults } from '@mysten/sui/client'\nimport { SuiClient, getFullnodeUrl } from '@mysten/sui/client'\nimport camelCase from 'lodash.camelcase'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { BcsType } from '@mysten/sui/bcs'\nimport { normalizeStructTag } from '@mysten/sui/utils'\nimport { SuiPriceServiceConnection } from '@pythnetwork/pyth-sui-js'\nimport BigNumber from 'bignumber.js'\nimport { userAgent } from './ua'\n\n/**\n * Default Sui client instance configured for mainnet\n */\nexport const suiClient = new SuiClient({\n url: getFullnodeUrl('mainnet')\n})\n\n/**\n * Generates a cache key from function arguments\n *\n * This function creates a unique key for caching by serializing the arguments\n * and removing cache-specific options that shouldn't affect the cache key.\n *\n * @param args - Function arguments to generate key from\n * @returns JSON string representing the arguments\n */\nfunction argsKey(args: any[]) {\n const serializergs = [] as any[]\n args.forEach((option: any, index) => {\n const isLast = index === args.length - 1\n if (typeof option === 'object' && isLast) {\n const { client, disableCache, cacheTime, ...rest } = option\n serializergs.push(rest)\n } else {\n serializergs.push(option)\n }\n })\n return JSON.stringify(serializergs)\n}\n\n/**\n * Wraps a function with singleton behavior to prevent duplicate concurrent calls\n *\n * This decorator ensures that if the same function is called with the same arguments\n * while a previous call is still pending, it returns the existing promise instead\n * of making a new call.\n *\n * @param fn - Function to wrap with singleton behavior\n * @returns Wrapped function with singleton behavior\n */\nexport function withSingleton<T extends (...args: any[]) => Promise<any>>(fn: T): T {\n const promiseMap: Record<string, Promise<any> | null> = {}\n\n return ((...args: any[]) => {\n const key = argsKey(args)\n if (!promiseMap[key]) {\n promiseMap[key] = fn(...args).finally(() => {\n promiseMap[key] = null\n })\n }\n return promiseMap[key]\n }) as T\n}\n\n/**\n * Wraps a function with caching behavior\n *\n * This decorator caches function results based on arguments and cache options.\n * It respects cache time settings and can be disabled per call.\n *\n * @param fn - Function to wrap with caching behavior\n * @returns Wrapped function with caching behavior\n */\nexport function withCache<T extends (...args: any[]) => Promise<any>>(fn: T): T {\n let cache: Record<\n string,\n {\n data: undefined\n cacheAt: number\n }\n > = {}\n\n return ((...args: any[]) => {\n const options = args[args.length - 1] as Partial<CacheOption>\n const key = argsKey(args)\n const cacheData = cache[key]\n\n // Check if cache is valid and not disabled\n if (!options?.disableCache && typeof cacheData?.data !== 'undefined') {\n if (\n typeof options?.cacheTime === 'undefined' ||\n options.cacheTime > Date.now() - cacheData.cacheAt\n ) {\n return cacheData.data\n }\n }\n\n // Execute function and cache result\n return fn(...args).then((result) => {\n cache[key] = {\n data: result,\n cacheAt: Date.now()\n }\n return result\n })\n }) as T\n}\n\n/**\n * Converts object keys from snake_case to camelCase recursively\n *\n * This function transforms all keys in an object (including nested objects and arrays)\n * from snake_case format to camelCase format.\n *\n * @param obj - Object to transform\n * @returns Object with camelCase keys\n */\nexport function camelize<T extends Record<string, any>>(obj: T): T {\n if (Array.isArray(obj)) {\n return obj.map((v) => camelize(v)) as unknown as T\n } else if (obj != null && typeof obj === 'object') {\n return Object.keys(obj).reduce(\n (result, key) => ({\n ...result,\n [camelCase(key)]: camelize(obj[key])\n }),\n {} as T\n )\n }\n return obj\n}\n\n/**\n * Parses a value for use in transaction building\n *\n * This function converts various value types into the appropriate format\n * for transaction building, handling both primitive types and existing\n * transaction results.\n *\n * @param value - Value to parse (string, number, boolean, or object)\n * @param format - Format function to apply to the value\n * @returns Transaction result in the appropriate format\n */\nexport function parseTxValue(\n value: string | number | boolean | object,\n format: any\n): TransactionResult {\n if (typeof value === 'object') {\n return value as TransactionResult\n }\n return format(value) as TransactionResult\n}\n\n/**\n * Parses a pool value for use in transaction building\n *\n * This function handles different pool representations and converts them\n * to the appropriate transaction object format.\n *\n * @param tx - Transaction object to build\n * @param value - Pool value (string, Pool object, or TransactionResult)\n * @returns Transaction result representing the pool\n */\nexport function parseTxPoolValue(tx: Transaction, value: string | Pool | TransactionResult) {\n if (typeof value === 'string') {\n return tx.object(value)\n }\n if (typeof value === 'object' && (value as TransactionResult).$kind) {\n return value as TransactionResult\n }\n return tx.object((value as Pool).contract.pool)\n}\n\n/**\n * Parses the result of a devInspectTransactionBlock call\n *\n * This function extracts and parses return values from transaction inspection\n * results using BCS (Binary Canonical Serialization) types.\n *\n * @param data - DevInspectResults from transaction inspection\n * @param parseTypes - Array of BCS types to parse the return values\n * @param options - Optional configuration including error handling\n * @returns Parsed result data\n */\nexport function parseDevInspectResult<T>(\n data: DevInspectResults,\n parseTypes: BcsType<any>[],\n options?: {\n throwError?: boolean\n }\n): T {\n if (data.results && data.results.length > 0) {\n if (data.results[0].returnValues && data.results[0].returnValues.length > 0) {\n return data.results[0].returnValues.map((item, index) => {\n const parseType = parseTypes[index] || parseTypes[0]\n return parseType.parse(Uint8Array.from(item[0]))\n }) as T\n }\n } else if (data.error) {\n console.log(`Get an error, msg: ${data.error}`)\n if (options?.throwError) {\n throw new Error(data.error)\n }\n return [] as T\n }\n return [] as T\n}\n\n/**\n * Normalizes a coin type string using Sui's struct tag normalization\n *\n * @param coinType - Coin type string to normalize\n * @returns Normalized coin type string\n */\nexport function normalizeCoinType(coinType: string) {\n return normalizeStructTag(coinType)\n}\n\n/**\n * Processes health factor values from contract format to human-readable format\n *\n * This function converts the raw health factor value from the contract\n * (which is typically a large integer) to a more readable decimal format.\n *\n * @param hf - Raw health factor value from contract\n * @returns Processed health factor value\n */\nexport function processContractHealthFactor(hf: number) {\n const healthFactor = (hf || 0) / Math.pow(10, 27)\n if (healthFactor > Math.pow(10, 5)) {\n return Infinity\n }\n return healthFactor\n}\n\n/**\n * Pyth price service connection for oracle price feeds\n *\n * This connection is used to fetch real-time price data from the Pyth network\n * for various assets in the lending protocol.\n */\nexport const suiPythConnection = new SuiPriceServiceConnection('https://hermes.pyth.network', {\n timeout: 20000\n})\n\nexport const Rate_Decimals = 27\n\nexport const rayMathMulIndex = (amount: string | number, index: string | number) => {\n if (!Number(amount) || !Number(index)) return new BigNumber(0)\n const ray = new BigNumber(1).shiftedBy(1 * Rate_Decimals)\n const halfRay = ray.multipliedBy(new BigNumber(0.5))\n return new BigNumber(amount)\n .multipliedBy(new BigNumber(index))\n .plus(halfRay)\n .dividedBy(ray)\n .integerValue(BigNumber.ROUND_DOWN)\n}\n\nexport const requestHeaders = !!userAgent\n ? {\n 'User-Agent': userAgent\n }\n : ({} as HeadersInit)\n","/**\n * Lending Configuration Management\n *\n * This module provides configuration management for the lending protocol.\n * It handles fetching configuration from the Navi protocol API and provides\n * caching mechanisms for efficient configuration retrieval.\n *\n * @module LendingConfig\n */\n\nimport type { LendingConfig, EnvOption, CacheOption } from './types'\nimport { withCache, withSingleton, requestHeaders } from './utils'\nimport packageJson from '../package.json'\n\n/**\n * Fetches lending protocol configuration from the API\n *\n * This function retrieves the current configuration for the lending protocol\n * from the Navi protocol API. It's wrapped with both caching and singleton\n * behavior to ensure efficient and consistent configuration access.\n *\n * The configuration includes:\n * - Contract addresses for all protocol components\n * - Oracle configuration and price feed information\n * - Pool and incentive contract addresses\n * - Environment-specific settings\n *\n * @param options - Optional environment and caching options\n * @returns Promise<LendingConfig> - Complete lending protocol configuration\n */\nexport const getConfig = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<LendingConfig> => {\n const url = `https://open-api.naviprotocol.io/api/navi/config?env=${options?.env || 'prod'}&sdk=${packageJson.version}`\n\n // Fetch configuration from API\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Default cache time for configuration data\n *\n * Configuration is cached for 5 minutes to reduce API calls\n * while ensuring reasonably fresh configuration data.\n */\nexport const DEFAULT_CACHE_TIME = 1000 * 60 * 5\n","/**\n * Lending Pool Operations\n *\n * This module provides comprehensive pool management functionality for the lending protocol.\n * It handles pool information retrieval, deposit/withdraw operations, borrow/repay operations,\n * and various pool-related utilities and statistics.\n *\n * @module LendingPool\n */\n\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport type {\n EnvOption,\n CacheOption,\n Pool,\n AssetIdentifier,\n PoolStats,\n FeeDetail,\n CoinObject,\n TransactionResult,\n AccountCapOption,\n BorrowFeeOption,\n SuiClientOption\n} from './types'\nimport {\n normalizeCoinType,\n withCache,\n withSingleton,\n parseTxValue,\n suiClient,\n requestHeaders\n} from './utils'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { parseDevInspectResult } from './utils'\nimport { bcs } from '@mysten/sui/bcs'\n\n/**\n * Enumeration of pool operations\n *\n * This enum defines the different types of operations that can be performed\n * on lending pools, used for health factor calculations and operation tracking.\n */\nexport enum PoolOperator {\n /** Supply/deposit operation */\n Supply = 1,\n /** Withdraw operation */\n Withdraw = 2,\n /** Borrow operation */\n Borrow = 3,\n /** Repay operation */\n Repay = 4\n}\n\n/**\n * Fetches all available lending pools\n *\n * This function retrieves the complete list of lending pools from the Navi protocol API.\n * It's wrapped with caching and singleton behavior for efficient data access.\n *\n * @param options - Optional environment and caching options\n * @returns Promise<Pool[]> - Array of all available lending pools\n */\nexport const getPools = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<Pool[]> => {\n const url = `https://open-api.naviprotocol.io/api/navi/pools?env=${options?.env || 'prod'}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Gets information for a specific lending pool\n *\n * This function retrieves pool information based on various identifier types:\n * - Pool object (returns directly)\n * - String (coin type - normalized for comparison)\n * - Number (pool ID)\n *\n * @param identifier - Asset identifier (string, Pool object, or number)\n * @param options - Optional environment options\n * @returns Promise<Pool> - Pool information\n * @throws Error if pool is not found\n */\nexport async function getPool(\n identifier: AssetIdentifier,\n options?: Partial<EnvOption>\n): Promise<Pool> {\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // If identifier is already a pool object, return it directly\n if (typeof identifier === 'object') {\n return identifier\n }\n\n // Find pool by identifier\n const pool = pools.find((p) => {\n if (typeof identifier === 'string') {\n return normalizeCoinType(p.suiCoinType) === normalizeCoinType(identifier)\n }\n if (typeof identifier === 'number') {\n return p.id === identifier\n }\n return false\n })\n\n if (!pool) {\n throw new Error(`Pool not found`)\n }\n\n if (pool.isDeprecated) {\n console.log(`The lending pool for coinType ${pool.suiCoinType} is going to be deprecated.`)\n }\n return pool\n}\n\n/**\n * Fetches protocol statistics\n *\n * This function retrieves overall protocol statistics including TVL,\n * total borrow amounts, and other key metrics.\n *\n * @param options - Optional caching options\n * @returns Promise<PoolStats> - Protocol statistics\n */\nexport const getStats = withCache(\n withSingleton(async (options?: Partial<CacheOption>): Promise<PoolStats> => {\n const url = `https://open-api.naviprotocol.io/api/navi/stats`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Fetches protocol fee information\n *\n * This function retrieves detailed fee information including:\n * - Total fee value\n * - V3 borrow fees\n * - Borrow interest fees\n * - Flash loan and liquidation fees\n *\n * @param options - Optional caching options\n * @returns Promise with detailed fee breakdown\n */\nexport const getFees = withCache(\n withSingleton(\n async (\n options?: Partial<CacheOption>\n ): Promise<{\n totalValue: number\n v3BorrowFee: {\n totalValue: number\n details: FeeDetail[]\n }\n borrowInterestFee: {\n totalValue: number\n details: FeeDetail[]\n }\n flashloanAndLiquidationFee: {\n totalValue: number\n details: FeeDetail[]\n }\n }> => {\n const url = `https://open-api.naviprotocol.io/api/navi/fee`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res\n }\n )\n)\n\n/**\n * Builds a deposit transaction for a lending pool\n *\n * This function creates a transaction block for depositing coins into a lending pool.\n * It handles both regular deposits and deposits with account capabilities,\n * and includes special handling for SUI gas coins.\n *\n * @param tx - Transaction object to build\n * @param identifier - Asset identifier for the pool\n * @param coinObject - Coin object to deposit\n * @param options - Optional parameters including environment, account capability, and amount\n * @returns Promise<Transaction> - Transaction with deposit operation\n */\nexport async function depositCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n coinObject: CoinObject,\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n amount: number | TransactionResult\n }\n >\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n if (pool?.deprecatedAt && Date.now() > pool.deprecatedAt) {\n throw new Error(`The lending pool for coinType ${pool.suiCoinType} has been deprecated.`)\n }\n\n const isGasCoin = typeof coinObject === 'object' && coinObject.$kind === 'GasCoin'\n\n // Handle SUI gas coin deposits\n if (normalizeCoinType(pool.suiCoinType) === normalizeCoinType('0x2::sui::SUI') && isGasCoin) {\n if (!options?.amount) {\n throw new Error('Amount is required for sui coin')\n }\n coinObject = tx.splitCoins(coinObject, [options.amount])\n }\n\n // Determine deposit amount\n let depositAmount: TransactionResult\n\n if (typeof options?.amount !== 'undefined') {\n depositAmount = parseTxValue(options.amount, tx.pure.u64)\n } else {\n depositAmount = tx.moveCall({\n target: '0x2::coin::value',\n arguments: [parseTxValue(coinObject as any, tx.object)],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n // Build deposit transaction based on account capability\n if (options?.accountCap) {\n tx.moveCall({\n target: `${config.package}::incentive_v3::deposit_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n } else {\n tx.moveCall({\n target: `${config.package}::incentive_v3::entry_deposit`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n depositAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n // refresh stake for sui pool to balance the stake after deposit\n if (config.version === 2 && pool.id === 0) {\n tx.moveCall({\n target: `${config.package}::pool::refresh_stake`,\n arguments: [tx.object(pool.contract.pool), tx.object('0x05')]\n })\n }\n\n return tx\n}\n\n/**\n * Builds a withdraw transaction for a lending pool\n *\n * Constructs and adds withdrawal operations to a transaction object.\n * This function supports standard withdrawal and withdrawal using account capability.\n *\n * @param tx - The transaction builder to append operations to\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to withdraw\n * @param options - Optional parameters including environment and account capability\n * @returns Transaction result representing the withdrawn coins\n */\nexport async function withdrawCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption & AccountCapOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const withdrawAmount = parseTxValue(amount, tx.pure.u64)\n\n let withdrawBalance\n\n if (config.version === 1) {\n // Build withdraw transaction based on account capability\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n }\n } else {\n // Build withdraw transaction based on account capability\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_with_account_cap_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n }\n }\n\n const withdrawCoin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [withdrawBalance],\n typeArguments: [pool.suiCoinType]\n })\n\n return withdrawCoin\n}\n\nexport async function borrowCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption & AccountCapOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n if (pool?.deprecatedAt && Date.now() > pool.deprecatedAt) {\n throw new Error(`The lending pool for coinType ${pool.suiCoinType} has been deprecated.`)\n }\n\n const borrowAmount = parseTxValue(amount, tx.pure.u64)\n\n let borrowBalance\n\n if (config.version === 1) {\n if (!options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n }\n } else {\n if (!options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_with_account_cap_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n }\n }\n\n const coin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [tx.object(borrowBalance)],\n typeArguments: [pool.suiCoinType]\n })\n\n return coin\n}\n\n/**\n * Builds a repay transaction for a lending pool debt\n *\n * Constructs and adds repayment operations to an existing transaction object.\n * This function handles loan repayments, supporting both standard user\n * repayments and privileged operations via account capabilities.\n *\n *\n * @param tx - The transaction builder to append repayment operations to\n * @param identifier - Unique identifier for the lending pool asset (e.g., \"USDC\", \"SUI\")\n * @param coinObject - The coin object to use for repayment, or GasCoin for SUI payments\n * @param options - Configuration options for the repayment\n * - `amount` - Specific amount to repay (required for SUI gas coin, otherwise uses value of specified coinObject)\n * - `accountCap` - Optional account capability object for privileged repayments\n * - `env` - Environment configuration\n * - `cacheTime` - Cache duration for configuration data\n *\n * @returns Promise<Transaction | TransactionResult> - The modified transaction object with repayment operations added\n *\n * @throws {Error} When amount is not provided for SUI gas coin repayments\n * @throws Will throw if pool doesn't exist or repayment validation fails\n */\nexport async function repayCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n coinObject: CoinObject,\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n amount: number | TransactionResult\n }\n >\n): Promise<Transaction | TransactionResult> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n const isGasCoin = typeof coinObject === 'object' && coinObject.$kind === 'GasCoin'\n\n if (normalizeCoinType(pool.suiCoinType) === normalizeCoinType('0x2::sui::SUI') && isGasCoin) {\n if (!options?.amount) {\n throw new Error('Amount is required for sui coin')\n }\n coinObject = tx.splitCoins(coinObject, [options.amount])\n }\n\n let repayAmount: TransactionResult\n\n if (typeof options?.amount !== 'undefined') {\n repayAmount = parseTxValue(options.amount, tx.pure.u64)\n } else {\n repayAmount = tx.moveCall({\n target: '0x2::coin::value',\n arguments: [parseTxValue(coinObject as any, tx.object)],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::repay_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n const coin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [ret],\n typeArguments: [pool.suiCoinType]\n })\n return coin\n } else {\n tx.moveCall({\n target: `${config.package}::incentive_v3::entry_repay`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n repayAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n return tx\n }\n}\n\n/**\n * Fetches the current borrow fee rate\n *\n * This function can retrieve borrow fee rates in two ways:\n * - If `address` and `asset` are provided, it calculates the specific borrow fee rate\n * for a given address and asset by calling the on-chain `get_borrow_fee_v2` function\n * - Otherwise, it returns the global borrow fee rate from the incentive V3 contract\n *\n * @param options - Optional configuration options\n * - `address` - User address to calculate specific borrow fee (requires `asset` to be set)\n * - `asset` - Asset identifier to calculate specific borrow fee (requires `address` to be set)\n * - `env` - Environment setting ('dev' or 'prod')\n * - `client` - Sui client instance for on-chain queries\n * - `cacheTime` - Cache expiration time in milliseconds\n * - `disableCache` - Whether to disable caching for this operation\n * @returns Promise<number> - Borrow fee rate as a decimal number\n * - When `address` and `asset` are provided: returns the specific fee rate (divided by 10000)\n * - Otherwise: returns the global fee rate (divided by 100)\n */\nexport const getBorrowFee = withCache(\n withSingleton(\n async (\n options?: Partial<EnvOption & CacheOption & BorrowFeeOption & SuiClientOption>\n ): Promise<number> => {\n const config = await getConfig({\n ...options\n })\n if (options?.address && typeof options?.asset !== 'undefined') {\n try {\n const pool = await getPool(options.asset, options)\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n tx.moveCall({\n target: `${config.package}::incentive_v3::get_borrow_fee_v2`,\n arguments: [\n tx.object(config.incentiveV3),\n tx.pure.address(options.address),\n tx.pure.u8(pool.id),\n tx.pure.u64(10000)\n ],\n typeArguments: []\n })\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: options.address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u64()])\n return (Number(res[0]) || 0) / 100\n } catch (error) {\n console.error(error)\n }\n }\n const rawData: any = await suiClient.getObject({\n id: config.incentiveV3,\n options: { showType: true, showOwner: true, showContent: true }\n })\n const borrowFee = rawData.data.content.fields.borrow_fee_rate\n return Number(borrowFee) / 100\n }\n )\n)\n","/**\n * Lending Account Management\n *\n * This module provides comprehensive account management functionality for the lending protocol.\n * It includes coin merging, health factor calculations, user state management, and various\n * lending operations like supply, borrow, withdraw, and repay.\n *\n * @module LendingAccount\n */\n\nimport type {\n UserLendingInfo,\n SuiClientOption,\n EnvOption,\n Pool,\n Transaction as NAVITransaction,\n AssetIdentifier,\n TransactionResult,\n CacheOption,\n AccountCap\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { UserStateInfo } from './bcs'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n suiClient,\n camelize,\n parseDevInspectResult,\n withSingleton,\n processContractHealthFactor,\n parseTxValue,\n parseTxPoolValue,\n withCache,\n normalizeCoinType,\n rayMathMulIndex,\n requestHeaders\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport { CoinStruct, PaginatedCoins } from '@mysten/sui/client'\nimport { getPool, getPools, PoolOperator } from './pool'\n\n/**\n * Merges multiple coins into a single coin for transaction building\n *\n * This function takes multiple coin objects and merges them into a single coin\n * that can be used in a transaction. It supports optional splitting to create\n * a specific balance amount.\n *\n * @param tx - Transaction object to add merge operations to\n * @param coins - Array of coin objects to merge\n * @param options - Optional parameters for balance splitting and gas coin usage\n * - `balance` - If provided, splits this amount from the resulting coin object\n * - `useGasCoin` - If true, uses the gas coin for the operation\n * @returns Transaction result representing the merged coin\n */\nexport function mergeCoinsPTB(\n tx: Transaction,\n coins: ({\n balance: string | number | bigint\n coinObjectId: string\n coinType: string\n } & CoinStruct)[],\n options?: {\n balance?: number\n useGasCoin?: boolean\n }\n) {\n const needSplit = typeof options?.balance === 'number'\n const splitBalance = needSplit ? options.balance! : 0\n let mergedBalance = 0\n const mergeList: string[] = []\n let coinType = ''\n\n // Sort coins by balance (highest first) and collect valid coins\n coins\n .sort((a, b) => Number(b.balance) - Number(a.balance))\n .forEach((coin) => {\n if (needSplit && mergedBalance >= splitBalance) {\n return\n }\n if (Number(coin.balance) === 0) {\n return\n }\n if (!coinType) {\n coinType = coin.coinType\n }\n if (coinType !== coin.coinType) {\n throw new Error('All coins must be of the same type')\n }\n mergedBalance += Number(coin.balance)\n mergeList.push(coin.coinObjectId)\n })\n\n if (mergeList.length === 0) {\n throw new Error('No coins to merge')\n }\n if (needSplit && mergedBalance < splitBalance) {\n throw new Error(\n `Balance is less than the specified balance: ${mergedBalance} < ${splitBalance}`\n )\n }\n\n // Handle SUI gas coin specially\n if (normalizeCoinType(coinType) === normalizeCoinType('0x2::sui::SUI') && options?.useGasCoin) {\n return needSplit ? tx.splitCoins(tx.gas, [tx.pure.u64(splitBalance)]) : tx.gas\n }\n\n // Merge coins and optionally split\n const coin =\n mergeList.length === 1\n ? tx.object(mergeList[0])\n : tx.mergeCoins(mergeList[0], mergeList.slice(1))\n\n return needSplit ? tx.splitCoins(coin, [tx.pure.u64(splitBalance)]) : coin\n}\n\n/**\n * Calculates dynamic health factor for a user after potential operations\n *\n * This function creates a transaction call to calculate the health factor\n * that would result after performing supply/borrow operations.\n *\n * @param tx - Transaction object to append calculation to\n * @param address - User address or transaction result\n * @param identifier - Asset identifier\n * @param estimatedSupply - Estimated supply amount\n * @param estimatedBorrow - Estimated borrow amount\n * @param isIncrease - Whether this is an increase operation\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getSimulatedHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n identifier: AssetIdentifier,\n estimatedSupply: number | TransactionResult,\n estimatedBorrow: number | TransactionResult,\n isIncrease: boolean | TransactionResult,\n options?: Partial<EnvOption>\n): Promise<TransactionResult> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n return tx.moveCall({\n target: `${config.uiGetter}::calculator_unchecked::dynamic_health_factor`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(config.oracle.priceOracle),\n parseTxPoolValue(tx, pool),\n parseTxValue(address, tx.pure.address),\n parseTxValue(pool.id, tx.pure.u8),\n parseTxValue(estimatedSupply, tx.pure.u64),\n parseTxValue(estimatedBorrow, tx.pure.u64),\n parseTxValue(isIncrease, tx.pure.bool)\n ],\n typeArguments: [pool.suiCoinType]\n })\n}\n\n/**\n * Gets the current health factor for a user\n *\n * @param tx - The transaction object to add health factor query operation to\n * @param address - User address or account cap or transaction result\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n options?: Partial<EnvOption>\n): Promise<TransactionResult> {\n return getSimulatedHealthFactorPTB(tx, address, 0, 0, 0, false, options)\n}\n\n/**\n * Retrieves the current lending state for a user\n *\n * This function fetches all active lending positions for a user, including\n * supply and borrow balances for different assets.\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client, environment, and caching\n * @returns Promise<UserLendingInfo[]> - Array of user lending positions\n */\nexport const getLendingState = withCache(\n async (\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption & CacheOption>\n ): Promise<UserLendingInfo[]> => {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const tx = new Transaction()\n const client = options?.client ?? suiClient\n\n const pools = await getPools(options)\n\n // Create transaction call to get user state\n tx.moveCall({\n target: `${config.uiGetter}::getter_unchecked::get_user_state`,\n arguments: [tx.object(config.storage), tx.pure.address(address!)]\n })\n\n // Execute dry run to get user state\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n\n // Parse the result and filter out zero balances\n const res = parseDevInspectResult<\n {\n supply_balance: string\n borrow_balance: string\n asset_id: number\n }[][]\n >(result, [bcs.vector(UserStateInfo as any)])\n\n const lendingStates = camelize(\n res[0].filter((item) => {\n return item.supply_balance !== '0' || item.borrow_balance !== '0'\n })\n ) as any as {\n supplyBalance: string\n borrowBalance: string\n assetId: number\n }[]\n\n return lendingStates\n .map((lendingState) => {\n const pool = pools.find((pool) => pool.id === lendingState.assetId)\n const supplyBalance = rayMathMulIndex(\n lendingState.supplyBalance,\n pool!.currentSupplyIndex\n ).toString()\n const borrowBalance = rayMathMulIndex(\n lendingState.borrowBalance,\n pool!.currentBorrowIndex\n ).toString()\n return {\n ...lendingState,\n supplyBalance,\n borrowBalance,\n pool\n }\n })\n .filter((lendingState) => !!lendingState.pool) as any\n }\n)\n\n/**\n * Calculates the current health factor for a user\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client and environment\n * @returns Promise<number> - Health factor value\n */\nexport async function getHealthFactor(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n await getHealthFactorPTB(tx, address, options)\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Calculates the health factor after performing lending operations\n *\n * This function simulates the health factor that would result after\n * performing a series of supply, withdraw, borrow, or repay operations.\n *\n * @param address - User wallet address or account cap\n * @param identifier - Asset identifier\n * @param operations - Array of operations to simulate\n * @param options - Options for client and environment\n * @returns Promise<number> - Projected health factor\n */\nexport async function getSimulatedHealthFactor(\n address: string | AccountCap,\n identifier: AssetIdentifier,\n operations: {\n type: PoolOperator\n amount: number\n }[],\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n let estimatedSupply = 0\n let estimatedBorrow = 0\n const pool = await getPool(identifier, options)\n\n // Calculate estimated changes from operations\n operations.forEach((operation) => {\n if (operation.type === PoolOperator.Supply) {\n estimatedSupply += operation.amount\n } else if (operation.type === PoolOperator.Withdraw) {\n estimatedSupply -= operation.amount\n } else if (operation.type === PoolOperator.Borrow) {\n estimatedBorrow += operation.amount\n } else if (operation.type === PoolOperator.Repay) {\n estimatedBorrow -= operation.amount\n }\n })\n\n // Validate operation consistency\n if (estimatedSupply * estimatedBorrow < 0) {\n throw new Error('Invalid operations')\n }\n\n // Determine if this is an increase operation\n const isIncrease = estimatedSupply > 0 || estimatedBorrow > 0\n\n // Calculate the dynamic health factor\n await getSimulatedHealthFactorPTB(\n tx,\n address,\n pool,\n Math.abs(estimatedSupply),\n Math.abs(estimatedBorrow),\n isIncrease,\n options\n )\n\n // Execute dry run to get the result\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Retrieves transaction history for a user from the Navi protocol API\n *\n * This function fetches the transaction history for a specific user address\n * from the Navi protocol's open API. It supports pagination through cursor-based navigation.\n *\n * @param address - User wallet address or account cap\n * @param options - Optional parameters including cursor for pagination\n * @returns Promise with transaction data and optional cursor for next page\n */\nexport const getTransactions = withSingleton(\n async (\n address: string | AccountCap,\n options?: {\n cursor?: string\n }\n ): Promise<{\n data: NAVITransaction[]\n cursor?: string\n }> => {\n // Build query parameters for the API request\n const params = new URLSearchParams()\n if (options?.cursor) {\n params.set('cursor', options.cursor)\n }\n params.set('userAddress', address)\n\n // Fetch transaction history from Navi protocol API\n const url = `https://open-api.naviprotocol.io/api/navi/user/transactions?${params.toString()}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n }\n)\n\n/**\n * Retrieves all coins owned by a user address\n *\n * This function fetches all coin objects owned by a specific address from the Sui blockchain.\n * It supports filtering by coin type and handles pagination automatically to retrieve all coins.\n *\n * @param address - User wallet address\n * @param options - Optional parameters including coin type filter and client options\n * - `coinType` - If specified, retrieves only coins of this type\n * - `client` - If provided, uses this `SuiClient` instance instead of the default client\n * @returns Promise<CoinStruct[]> - Array of coin objects owned by the address\n */\nexport async function getCoins(\n address: string,\n options?: Partial<\n {\n coinType?: string\n } & SuiClientOption\n >\n): Promise<CoinStruct[]> {\n let cursor: string | undefined | null = null\n const allCoinDatas: CoinStruct[] = []\n const client = options?.client ?? suiClient\n\n // Fetch all coins using pagination\n do {\n let res: PaginatedCoins\n\n // Use specific coin type filter if provided, otherwise get all coins\n if (options?.coinType) {\n res = await client.getCoins({\n owner: address,\n coinType: options?.coinType,\n cursor,\n limit: 100\n })\n } else {\n res = await client.getAllCoins({\n owner: address,\n cursor,\n limit: 100\n })\n }\n\n // Break if no more data\n if (!res.data || !res.data.length) {\n break\n }\n\n // Collect coin data and continue with next page\n allCoinDatas.push(...res.data)\n cursor = res.nextCursor\n } while (cursor)\n\n return allCoinDatas\n}\n","/**\n * Oracle Price Feed Management for Lending Protocol\n *\n * This module provides oracle price feed functionality for the lending protocol.\n * It integrates with Pyth Network for real-time price data and manages price updates\n * for various assets used in lending operations.\n */\n\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport type { OraclePriceFeed, EnvOption, UserLendingInfo, Pool, SuiClientOption } from './types'\nimport { SuiPriceServiceConnection, SuiPythClient } from '@pythnetwork/pyth-sui-js'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { suiClient } from './utils'\n\n/**\n * Pyth Network connection for price feed data\n * Connects to the Hermes endpoint for real-time price updates\n */\nconst suiPythConnection = new SuiPriceServiceConnection('https://hermes.pyth.network', {\n timeout: 10000\n})\n\n/**\n * Get stale price feed IDs from Pyth Network\n *\n * Identifies price feeds that have not been updated recently (more than 30 seconds old).\n * This helps ensure that only fresh price data is used for lending operations.\n *\n * @param priceIds - Array of Pyth price feed IDs to check\n * @returns Array of stale price feed IDs that need updating\n * @throws Error if failed to fetch price feed data\n */\nexport async function getPythStalePriceFeedId(priceIds: string[]): Promise<string[]> {\n try {\n const returnData: string[] = []\n const latestPriceFeeds = await suiPythConnection.getLatestPriceFeeds(priceIds)\n if (!latestPriceFeeds) return returnData\n\n const currentTimestamp = Math.floor(new Date().valueOf() / 1000)\n for (const priceFeed of latestPriceFeeds) {\n const uncheckedPrice = priceFeed.getPriceUnchecked()\n if (uncheckedPrice.publishTime > currentTimestamp) {\n console.warn(\n `pyth price feed is invalid, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n continue\n }\n\n // From pyth state is 60, but setting it to 30 makes more sense.\n if (currentTimestamp - priceFeed.getPriceUnchecked().publishTime > 30) {\n console.info(\n `stale price feed, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n returnData.push(priceFeed.id)\n }\n }\n return returnData\n } catch (error) {\n throw new Error(`failed to get pyth stale price feed id, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update Pyth price feeds in a transaction\n *\n * Fetches the latest price update data from Pyth Network and adds the update\n * operations to the transaction block.\n *\n * @param tx - The transaction block to add price feed updates to\n * @param priceFeedIds - Array of Pyth price feed IDs to update\n * @param options - Optional client and environment configuration\n * @returns Promise that resolves when price feeds are updated\n * @throws Error if failed to update price feeds\n */\nexport async function updatePythPriceFeeds(\n tx: Transaction,\n priceFeedIds: string[],\n options?: Partial<SuiClientOption & EnvOption>\n) {\n const client = options?.client ?? suiClient\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n try {\n const priceUpdateData = await suiPythConnection.getPriceFeedsUpdateData(priceFeedIds)\n const suiPythClient = new SuiPythClient(\n client as any,\n config.oracle.pythStateId,\n config.oracle.wormholeStateId\n )\n\n return await suiPythClient.updatePriceFeeds(tx as any, priceUpdateData, priceFeedIds)\n } catch (error) {\n throw new Error(`failed to update pyth price feeds, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update oracle prices in the PTB (Programmable Transaction Block)\n *\n * This function updates price feeds for the lending protocol. It can optionally\n * update Pyth price feeds first if they are stale, then updates individual\n * price feeds in the oracle contract.\n *\n * @param tx - The transaction block to add price update operations to\n * @param priceFeeds - Array of oracle price feeds to update\n * @param options - Optional configuration including whether to update Pyth feeds\n * @returns The updated transaction block\n */\nexport async function updateOraclePricesPTB(\n tx: Transaction,\n priceFeeds: OraclePriceFeed[],\n options?: Partial<\n EnvOption & {\n updatePythPriceFeeds?: boolean\n }\n >\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Optionally update Pyth price feeds if they are stale\n if (options?.updatePythPriceFeeds) {\n const pythPriceFeedIds = priceFeeds\n .filter((feed) => !!feed.pythPriceFeedId)\n .map((feed) => feed.pythPriceFeedId)\n\n try {\n const stalePriceFeedIds = await getPythStalePriceFeedId(pythPriceFeedIds)\n if (stalePriceFeedIds.length > 0) {\n await updatePythPriceFeeds(tx, stalePriceFeedIds, options)\n }\n } catch (e) {}\n }\n\n // Update individual price feeds in the oracle contract\n for (const priceFeed of priceFeeds) {\n tx.moveCall({\n target: `${config.oracle.packageId}::oracle_pro::update_single_price`,\n arguments: [\n tx.object('0x6'), // Clock object\n tx.object(config.oracle.oracleConfig), // Oracle configuration\n tx.object(config.oracle.priceOracle), // Price oracle contract\n tx.object(config.oracle.supraOracleHolder), // Supra oracle holder\n tx.object(priceFeed.pythPriceInfoObject), // Pyth price info object\n tx.pure.address(priceFeed.feedId) // Price feed ID\n ]\n })\n }\n return tx\n}\n\n/**\n * Get all available price feeds from the configuration\n *\n * @param options - Optional environment configuration\n * @returns Array of oracle price feed configurations\n */\nexport async function getPriceFeeds(options?: Partial<EnvOption>): Promise<OraclePriceFeed[]> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n return config.oracle.feeds\n}\n\n/**\n * Filter price feeds based on lending state and pools\n *\n * This function filters price feeds to only include those that are relevant\n * to the current lending state or available pools.\n *\n * @param feeds - Array of price feeds to filter\n * @param filters - Filter criteria including lending state and pools\n * @returns Filtered array of price feeds\n */\nexport function filterPriceFeeds(\n feeds: OraclePriceFeed[],\n filters: {\n lendingState?: UserLendingInfo[]\n pools?: Pool[]\n }\n): OraclePriceFeed[] {\n return feeds.filter((feed) => {\n // Filter by lending state (user's current positions)\n if (filters?.lendingState) {\n const inState = filters.lendingState.find((state) => {\n return state.assetId === feed.assetId\n })\n if (inState) {\n return true\n }\n }\n\n // Filter by available pools\n if (filters?.pools) {\n const inPool = filters.pools.find((pool) => {\n return pool.id === feed.assetId\n })\n if (inPool) {\n return true\n }\n }\n return false\n })\n}\n","/**\n * Flash Loan Functionality for Lending Protocol\n *\n * This module provides flash loan capabilities for the lending protocol.\n * Flash loans allow users to borrow assets without collateral for a single transaction,\n * as long as the borrowed amount is repaid within the same transaction.\n */\n\nimport type { Transaction } from '@mysten/sui/transactions'\nimport type {\n EnvOption,\n AssetIdentifier,\n CoinObject,\n CacheOption,\n FloashloanAsset,\n TransactionResult\n} from './types'\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport { parseTxValue, normalizeCoinType, withCache, withSingleton, requestHeaders } from './utils'\nimport { getPool } from './pool'\n\n/**\n * Get all available flash loan assets from the API\n * Uses caching to avoid repeated API calls\n *\n * @param options - Optional environment and cache configuration\n * @returns Array of flash loan asset configurations\n */\nexport const getAllFlashLoanAssets = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<FloashloanAsset[]> => {\n const url = `https://open-api.naviprotocol.io/api/navi/flashloan?env=${options?.env || 'prod'}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return Object.keys(res.data).map((coinType) => {\n return {\n ...res.data[coinType],\n coinType\n }\n })\n })\n)\n\n/**\n * Get a specific flash loan asset by identifier\n *\n * @param identifier - Asset identifier (string coin type, number asset ID, or object with id)\n * @param options - Optional environment configuration\n * @returns Flash loan asset configuration or null if not found\n */\nexport async function getFlashLoanAsset(\n identifier: AssetIdentifier,\n options?: Partial<EnvOption>\n): Promise<FloashloanAsset | null> {\n const assets = await getAllFlashLoanAssets(options)\n return (\n assets.find((asset) => {\n if (typeof identifier === 'string') {\n return normalizeCoinType(asset.coinType) === normalizeCoinType(identifier)\n }\n if (typeof identifier === 'number') {\n return asset.assetId === identifier\n }\n return asset.assetId === identifier.id\n }) || null\n )\n}\n\n/**\n * Create a flash loan transaction in the PTB (Programmable Transaction Block)\n *\n * This function initiates a flash loan by borrowing the specified amount of assets.\n * The borrowed assets must be repaid within the same transaction using repayFlashLoanPTB.\n *\n * @param tx - The transaction block to add the flash loan operation to\n * @param identifier - Asset identifier to borrow\n * @param amount - Amount to borrow (number or transaction result)\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance, receipt] where receipt is needed for repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function flashloanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n if (config.version === 1) {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64)\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n } else {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx_v2`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n }\n}\n\n/**\n * Repay a flash loan transaction in the PTB\n *\n * This function repays the flash loan using the receipt from the original flash loan\n * and the coin object containing the repayment amount.\n *\n * @param tx - The transaction block to add the repayment operation to\n * @param identifier - Asset identifier being repaid\n * @param receipt - Receipt from the original flash loan transaction\n * @param coinObject - Coin object containing the repayment amount\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance] after repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function repayFlashLoanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n receipt: TransactionResult | string,\n coinObject: CoinObject,\n options?: Partial<EnvOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n // v2 entry is not required to repay\n const [balance] = tx.moveCall({\n target: `${config.package}::lending::flash_repay_with_ctx`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n parseTxValue(receipt, tx.object),\n parseTxValue(coinObject, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n return [balance]\n}\n","/**\n * Liquidation Functionality for Lending Protocol\n *\n * This module provides liquidation capabilities for the lending protocol.\n * Liquidation allows liquidators to repay a borrower's debt in exchange for their collateral\n * when the borrower's health factor falls below the liquidation threshold.\n */\n\nimport { AssetIdentifier, CoinObject, EnvOption, TransactionResult } from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport { getPool } from './pool'\nimport { getAllFlashLoanAssets } from './flashloan'\nimport { normalizeCoinType, parseTxValue } from './utils'\n\n/**\n * Create a liquidation transaction in the PTB (Programmable Transaction Block)\n *\n * This function allows liquidators to liquidate a borrower's position by repaying\n * their debt in exchange for their collateral. The liquidation process uses flash loans\n * to ensure atomic execution of the liquidation transaction.\n *\n * @param tx - The transaction block to add the liquidation operation to\n * @param payAsset - Asset identifier for the debt being repaid\n * @param payCoinObject - Coin object containing the debt repayment amount\n * @param collateralAsset - Asset identifier for the collateral being liquidated\n * @param liquidateAddress - Address of the borrower being liquidated\n * @param options - Optional environment configuration\n * @returns Tuple containing [collateralBalance, remainDebtBalance] where:\n * - collateralBalance: The collateral received from liquidation\n * - remainDebtBalance: Any remaining debt after liquidation\n * @throws Error if either pay asset or collateral asset does not support flash loans\n */\nexport async function liquidatePTB(\n tx: Transaction,\n payAsset: AssetIdentifier,\n payCoinObject: CoinObject,\n collateralAsset: AssetIdentifier,\n liquidateAddress: string | TransactionResult,\n options?: Partial<EnvOption>\n) {\n const commonOptions = {\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n }\n const config = await getConfig(commonOptions)\n const payPool = await getPool(payAsset, commonOptions)\n const collateralPool = await getPool(collateralAsset, commonOptions)\n\n if (config.version === 1) {\n // Execute the liquidation transaction\n const [collateralBalance, remainDebtBalance] = tx.moveCall({\n target: `${config.package}::incentive_v3::liquidation`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.priceOracle), // Price oracle for asset pricing\n tx.object(config.storage), // Protocol storage\n tx.pure.u8(payPool.id), // Pay asset ID\n tx.object(payPool.contract.pool), // Pay asset pool contract\n parseTxValue(payCoinObject, tx.object), // Debt repayment amount\n tx.pure.u8(collateralPool.id), // Collateral asset ID\n tx.object(collateralPool.contract.pool), // Collateral asset pool contract\n parseTxValue(liquidateAddress, tx.pure.address), // Borrower address\n tx.object(config.incentiveV2), // Incentive V2 contract\n tx.object(config.incentiveV3) // Incentive V3 contract\n ],\n typeArguments: [payPool.suiCoinType, collateralPool.suiCoinType]\n })\n\n return [collateralBalance, remainDebtBalance]\n } else {\n // Execute the liquidation transaction\n const [collateralBalance, remainDebtBalance] = tx.moveCall({\n target: `${config.package}::incentive_v3::liquidation_v2`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.priceOracle), // Price oracle for asset pricing\n tx.object(config.storage), // Protocol storage\n tx.pure.u8(payPool.id), // Pay asset ID\n tx.object(payPool.contract.pool), // Pay asset pool contract\n parseTxValue(payCoinObject, tx.object), // Debt repayment amount\n tx.pure.u8(collateralPool.id), // Collateral asset ID\n tx.object(collateralPool.contract.pool), // Collateral asset pool contract\n parseTxValue(liquidateAddress, tx.pure.address), // Borrower address\n tx.object(config.incentiveV2), // Incentive V2 contract\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object('0x05') // SuiSystemState object\n ],\n typeArguments: [payPool.suiCoinType, collateralPool.suiCoinType]\n })\n\n return [collateralBalance, remainDebtBalance]\n }\n}\n","/**\n * Lending Reward Management for Lending Protocol\n *\n * This module provides comprehensive reward functionality for the lending protocol.\n * It handles reward calculations, claiming, and management for users who participate\n * in lending activities such as supplying assets or borrowing.\n */\n\nimport type {\n SuiClientOption,\n EnvOption,\n LendingRewardSummary,\n LendingReward,\n HistoryClaimedReward,\n LendingClaimedReward,\n TransactionResult,\n AccountCapOption,\n AccountCap\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n suiClient,\n camelize,\n parseDevInspectResult,\n normalizeCoinType,\n withSingleton,\n parseTxValue,\n requestHeaders\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport { getPriceFeeds } from './oracle'\nimport { getPools, depositCoinPTB } from './pool'\nimport BigNumber from 'bignumber.js'\n\n/**\n * Get user's available lending rewards\n *\n * This function retrieves all available rewards for a user from the lending protocol.\n * It uses devInspect to simulate the reward calculation and returns detailed\n * information about claimable rewards for each asset and reward type.\n *\n * @param address - User's wallet address or account cap\n * @param options - Optional client and environment configuration\n * @returns Array of lending rewards available for claiming\n */\nexport async function getUserAvailableLendingRewards(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<LendingReward[]> {\n const feeds = await getPriceFeeds(options)\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const client = options?.client ?? suiClient\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Create transaction to simulate reward calculation\n const tx = new Transaction()\n tx.moveCall({\n target: `${config.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.storage), // Protocol storage\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.pure.address(address) // User address\n ]\n })\n\n // Simulate the transaction to get reward data\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n\n // Parse the result using BCS schemas\n const rewardsData = parseDevInspectResult<[string[], string[], number[], string[], number[]]>(\n result,\n [\n bcs.vector(bcs.string()), // Asset coin types\n bcs.vector(bcs.string()), // Reward coin types\n bcs.vector(bcs.u8()), // Reward options\n bcs.vector(bcs.Address), // Rule IDs\n bcs.vector(bcs.u256()) // Claimable amounts\n ]\n )\n\n const rewardsList: {\n userClaimableReward: number\n userClaimedReward?: string\n option: number\n ruleIds: string[]\n assetCoinType: string\n rewardCoinType: string\n assetId: number\n }[] = []\n\n // Process the reward data and match with feeds and pools\n if (rewardsData.length === 5 && Array.isArray(rewardsData[0])) {\n const count = rewardsData[0].length\n for (let i = 0; i < count; i++) {\n const feed = feeds.find(\n (feed) => normalizeCoinType(feed.coinType) === normalizeCoinType(rewardsData[1][i])\n )\n const pool = pools.find(\n (pool) => normalizeCoinType(pool.coinType) === normalizeCoinType(rewardsData[0][i])\n )\n if (!feed || !pool) {\n continue\n }\n rewardsList.push({\n assetId: pool.id,\n assetCoinType: normalizeCoinType(rewardsData[0][i]),\n rewardCoinType: normalizeCoinType(rewardsData[1][i]),\n option: Number(rewardsData[2][i]),\n userClaimableReward: Number(rewardsData[4][i]) / Math.pow(10, feed.priceDecimal),\n ruleIds: Array.isArray(rewardsData[3][i]) ? (rewardsData[3][i] as any) : [rewardsData[3][i]]\n })\n }\n }\n return rewardsList\n}\n\n/**\n * Summarize lending rewards by asset and reward type\n *\n * This function aggregates rewards by asset ID and reward type, providing\n * a summary view of all available rewards for easier display and management.\n *\n * @param rewards - Array of lending rewards to summarize\n * @returns Array of summarized reward information grouped by asset and type\n */\nexport function summaryLendingRewards(rewards: LendingReward[]): LendingRewardSummary[] {\n // Aggregate rewards by asset ID, reward type, and coin type\n const agg = new Map<\n string,\n { assetId: number; rewardType: number; coinType: string; total: number }\n >()\n\n rewards.forEach((reward) => {\n const assetId = reward.assetId\n const rewardType = reward.option\n const key = `${assetId}-${rewardType}-${reward.rewardCoinType}`\n if (agg.has(key)) {\n agg.get(key)!.total += reward.userClaimableReward\n } else {\n agg.set(key, {\n assetId,\n rewardType,\n coinType: reward.rewardCoinType,\n total: Number(reward.userClaimableReward)\n })\n }\n })\n\n // Group rewards by asset ID and reward type\n const groupMap = new Map<\n string,\n { assetId: number; rewardType: number; rewards: Map<string, number> }\n >()\n for (const { assetId, rewardType, coinType, total } of agg.values()) {\n const groupKey = `${assetId}-${rewardType}`\n if (!groupMap.has(groupKey)) {\n groupMap.set(groupKey, { assetId, rewardType, rewards: new Map<string, number>() })\n }\n const rewardMap = groupMap.get(groupKey)!\n rewardMap.rewards.set(coinType, (rewardMap.rewards.get(coinType) || 0) + total)\n }\n\n // Convert to summary format\n return Array.from(groupMap.values()).map((group) => ({\n assetId: group.assetId,\n rewardType: group.rewardType,\n rewards: Array.from(group.rewards.entries()).map(([coinType, available]) => ({\n coinType,\n available: available.toFixed(6)\n }))\n }))\n}\n\n/**\n * Get user's total claimed rewards in USD value\n *\n * Fetches the total amount of rewards that a user has claimed historically,\n * converted to USD value for easy comparison and display.\n *\n * @param address - User's wallet address or account cap\n * @returns Object containing total claimed rewards in USD\n */\nexport const getUserTotalClaimedReward = withSingleton(\n async (\n address: string | AccountCap\n ): Promise<{\n USDValue: number\n }> => {\n const url = `https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${address}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n }\n)\n\n/**\n * Get user's claimed reward history\n *\n * Retrieves a paginated list of all rewards that a user has claimed historically.\n * Useful for tracking reward history and generating reports.\n *\n * @param address - User's wallet address or account cap\n * @param options - Pagination options (page number and size)\n * @returns Object containing claimed reward history and pagination cursor\n */\nexport const getUserClaimedRewardHistory = withSingleton(\n async (\n address: string | AccountCap,\n options?: {\n page?: number\n size?: number\n }\n ): Promise<{\n data: HistoryClaimedReward[]\n cursor?: string\n }> => {\n const endpoint = `https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${address}&page=${options?.page || 1}&pageSize=${options?.size || 400}`\n const res = await fetch(endpoint, { headers: requestHeaders }).then((res) => res.json())\n return camelize({\n data: res.data.rewards\n })\n }\n)\n\n/**\n * Claim lending rewards in the PTB (Programmable Transaction Block)\n *\n * This function adds operations to a transaction block to claim rewards from the lending protocol.\n * It supports different claiming methods including direct claiming, claiming with\n * account capabilities, and custom coin handling (transfer or deposit).\n *\n * @param tx - The transaction block to add reward claiming operations to\n * @param rewards - Array of rewards to claim\n * @param options - Optional configuration including account capabilities and custom coin handling\n * @param options.customCoinReceive.type - The type of custom coin handling, can be 'transfer', 'depositNAVI' or 'skip'\n * @param options.customCoinReceive.transfer - The address to transfer the reward to, only used when options.customCoinReceive.type is 'transfer'\n * @param options.customCoinReceive.depositNAVI.fallbackReceiveAddress - The address to transfer the reward to if the pool is full, only used when options.customCoinReceive.type is 'depositNAVI'\n * @returns Array of claimed reward coins and their identifiers\n * @throws Error if reward fund not found or invalid configuration\n */\nexport async function claimLendingRewardsPTB(\n tx: Transaction,\n rewards: LendingReward[],\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n customCoinReceive?: {\n type: 'transfer' | 'depositNAVI' | 'skip'\n transfer?: string | TransactionResult\n depositNAVI?: {\n fallbackReceiveAddress?: string\n }\n }\n }\n >\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Group rewards by reward coin type and collect asset IDs and rule IDs\n const rewardMap = new Map<string, { assetIds: string[]; ruleIds: string[]; amount: number }>()\n\n for (const reward of rewards) {\n const { rewardCoinType, ruleIds } = reward\n\n for (const ruleId of ruleIds) {\n if (!rewardMap.has(rewardCoinType)) {\n rewardMap.set(rewardCoinType, { assetIds: [], ruleIds: [], amount: 0 })\n }\n\n const group = rewardMap.get(rewardCoinType)!\n group.assetIds.push(reward.assetCoinType.replace('0x', ''))\n group.ruleIds.push(ruleId)\n group.amount += reward.userClaimableReward\n }\n }\n\n const rewardCoins = [] as LendingClaimedReward[]\n\n // Process each reward coin type\n for (const [rewardCoinType, { assetIds, ruleIds, amount }] of rewardMap) {\n const pool = pools.find(\n (p) => normalizeCoinType(p.suiCoinType) === normalizeCoinType(rewardCoinType)\n )\n if (!pool || !pool.contract.rewardFundId) {\n throw new Error(`No matching rewardFund found for reward coin: ${rewardCoinType}`)\n }\n const matchedRewardFund = pool.contract.rewardFundId\n\n // Validate configuration\n if (options?.accountCap && !options.customCoinReceive) {\n throw new Error('customCoinReceive is required when accountCap is provided')\n }\n\n // Handle custom coin receiving logic\n if (options?.customCoinReceive) {\n let rewardBalance\n\n // Claim rewards with or without account capability\n if (options.accountCap) {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_with_account_cap`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds), // Rule IDs\n parseTxValue(options.accountCap, tx.object) // Account capability\n ],\n typeArguments: [rewardCoinType]\n })\n } else {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [rewardCoinType]\n })\n }\n\n // Convert balance to coin object\n const [rewardCoin]: any = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [rewardBalance],\n typeArguments: [rewardCoinType]\n })\n\n // Handle different custom coin receiving types\n if (options?.customCoinReceive.type === 'transfer') {\n if (!options.customCoinReceive.transfer) {\n throw new Error('customCoinReceive.transfer is required')\n }\n tx.transferObjects(\n [rewardCoin],\n parseTxValue(options.customCoinReceive.transfer, tx.pure.address)\n )\n }\n if (options?.customCoinReceive.type === 'depositNAVI') {\n const supplyAmount = BigNumber(pool.totalSupplyAmount).shiftedBy(-9)\n const cap = BigNumber(pool.supplyCapCeiling).shiftedBy(-27)\n\n // if the pool is full, transfer the reward to the fallback receive address\n if (\n supplyAmount.plus(amount).isGreaterThan(cap) &&\n !!options?.customCoinReceive.depositNAVI?.fallbackReceiveAddress\n ) {\n tx.transferObjects(\n [rewardCoin],\n tx.pure.address(options.customCoinReceive.depositNAVI.fallbackReceiveAddress)\n )\n } else {\n await depositCoinPTB(tx, pool, rewardCoin, options)\n }\n } else {\n rewardCoins.push({\n coin: rewardCoin,\n identifier: pool\n })\n }\n } else {\n // Standard reward claiming without custom handling\n tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_entry`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [rewardCoinType]\n })\n }\n }\n return rewardCoins\n}\n","/**\n * Account Capability Management for Lending Protocol\n *\n * This module provides functionality to create account capabilities for the lending protocol.\n * Account capabilities are required to interact with lending pools and manage positions.\n */\n\nimport { getConfig } from './config'\nimport type { EnvOption } from './types'\nimport { Transaction } from '@mysten/sui/transactions'\n\n/**\n * Create an account capability transaction in the PTB (Programmable Transaction Block)\n *\n * This function creates a new account capability for the lending protocol.\n * Account capabilities are required to perform lending operations such as\n * borrowing, repaying, and managing collateral positions.\n *\n * @param tx - The transaction block to add the account creation operation to\n * @param options - Optional environment configuration options\n * @returns The transaction call result for creating an account capability\n */\nexport async function createAccountCapPTB(tx: Transaction, options?: Partial<EnvOption>) {\n const config = await getConfig({\n ...options\n })\n return tx.moveCall({\n target: `${config.package}::lending::create_account`,\n arguments: []\n })\n}\n"],"names":["Address","bcs","val","fromHex","toHex","IncentiveAPYInfo","IncentivePoolInfo","IncentivePoolInfoByPhase","OracleInfo","FlashLoanAssetConfig","ReserveDataInfo","UserStateInfo","sdkVersion","packageJson","getNodeInfo","os","nodeVersion","osType","osArch","getUserAgent","environmentInfo","userAgent","suiClient","SuiClient","getFullnodeUrl","argsKey","args","serializergs","option","index","isLast","client","disableCache","cacheTime","rest","withSingleton","fn","promiseMap","key","withCache","cache","options","cacheData","result","camelize","obj","v","camelCase","parseTxValue","value","format","parseTxPoolValue","tx","parseDevInspectResult","data","parseTypes","item","normalizeCoinType","coinType","normalizeStructTag","processContractHealthFactor","hf","healthFactor","SuiPriceServiceConnection","Rate_Decimals","rayMathMulIndex","amount","BigNumber","ray","halfRay","requestHeaders","getConfig","url","res","DEFAULT_CACHE_TIME","PoolOperator","getPools","getPool","identifier","pools","pool","p","getStats","getFees","depositCoinPTB","coinObject","config","isGasCoin","depositAmount","withdrawCoinPTB","withdrawAmount","withdrawBalance","ret","borrowCoinPTB","borrowAmount","borrowBalance","repayCoinPTB","repayAmount","getBorrowFee","_a","Transaction","error","borrowFee","mergeCoinsPTB","coins","needSplit","splitBalance","mergedBalance","mergeList","a","coin","getSimulatedHealthFactorPTB","address","estimatedSupply","estimatedBorrow","isIncrease","getHealthFactorPTB","getLendingState","lendingState","supplyBalance","getHealthFactor","getSimulatedHealthFactor","operations","operation","getTransactions","params","getCoins","cursor","allCoinDatas","suiPythConnection","getPythStalePriceFeedId","priceIds","returnData","latestPriceFeeds","currentTimestamp","priceFeed","uncheckedPrice","updatePythPriceFeeds","priceFeedIds","priceUpdateData","SuiPythClient","updateOraclePricesPTB","priceFeeds","pythPriceFeedIds","feed","stalePriceFeedIds","getPriceFeeds","filterPriceFeeds","feeds","filters","state","getAllFlashLoanAssets","getFlashLoanAsset","asset","flashloanPTB","balance","receipt","repayFlashLoanPTB","liquidatePTB","payAsset","payCoinObject","collateralAsset","liquidateAddress","commonOptions","payPool","collateralPool","collateralBalance","remainDebtBalance","getUserAvailableLendingRewards","rewardsData","rewardsList","count","i","summaryLendingRewards","rewards","agg","reward","assetId","rewardType","groupMap","total","groupKey","rewardMap","group","available","getUserTotalClaimedReward","getUserClaimedRewardHistory","endpoint","claimLendingRewardsPTB","rewardCoinType","ruleIds","ruleId","rewardCoins","assetIds","matchedRewardFund","rewardBalance","rewardCoin","supplyAmount","cap","createAccountCapPTB"],"mappings":"gVAcaA,EAAUC,EAAAA,IAAI,MAAM,EAAE,EAAE,UAAU,CAE7C,MAAQC,GAAgBC,EAAAA,QAAQD,CAAG,EACnC,OAASA,GAAQE,EAAAA,MAAMF,CAAG,CAC5B,CAAC,EAMYG,GAAmBJ,EAAAA,IAAI,OAAO,mBAAoB,CAE7D,SAAUA,EAAAA,IAAI,GAAA,EAEd,IAAKA,EAAAA,IAAI,KAAA,EAET,WAAYA,EAAAA,IAAI,OAAOA,EAAAA,IAAI,QAAQ,CACrC,CAAC,EAMYK,EAAoBL,EAAAA,IAAI,OAAO,oBAAqB,CAE/D,QAASD,EAET,MAAOA,EAEP,MAAOC,EAAAA,IAAI,IAAA,EAEX,SAAUA,EAAAA,IAAI,IAAA,EAEd,OAAQA,EAAAA,IAAI,IAAA,EAEZ,UAAWA,EAAAA,IAAI,IAAA,EAEf,aAAcA,EAAAA,IAAI,IAAA,EAElB,SAAUA,EAAAA,IAAI,GAAA,EAEd,OAAQA,EAAAA,IAAI,GAAA,EAEZ,OAAQA,EAAAA,IAAI,KAAA,EAEZ,YAAaA,EAAAA,IAAI,IAAA,EAEjB,UAAWA,EAAAA,IAAI,KAAA,EAEf,MAAOA,EAAAA,IAAI,KAAA,CACb,CAAC,EAMYM,GAA2BN,EAAAA,IAAI,OAAO,2BAA4B,CAE7E,MAAOA,EAAAA,IAAI,IAAA,EAEX,MAAOA,EAAAA,IAAI,OAAOK,CAAiB,CACrC,CAAC,EAMYE,G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O,SAAU6I,CAAQ,EACjC7I,EAAG,KAAK,OAAO,UAAW0I,CAAO,CAAA,EAEnC,cAAe,CAACD,CAAc,CAAA,CAC/B,CAEL,CACA,OAAOG,CACT,CC3XA,eAAsBO,GAAoBnJ,EAAiBX,EAA8B,CACvF,MAAM6C,EAAS,MAAMf,EAAU,CAC7B,GAAG9B,CAAA,CACJ,EACD,OAAOW,EAAG,SAAS,CACjB,OAAQ,GAAGkC,EAAO,OAAO,4BACzB,UAAW,CAAA,CAAC,CACb,CACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/bcs.ts","../src/ua.ts","../src/utils.ts","../src/config.ts","../src/pool.ts","../src/account.ts","../src/oracle.ts","../src/flashloan.ts","../src/liquidate.ts","../src/reward.ts","../src/account-cap.ts"],"sourcesContent":["/**\n * BCS (Binary Canonical Serialization) Schemas for Lending Protocol\n *\n * This module defines the BCS schemas for serializing and deserializing\n * lending protocol data structures. BCS is used for efficient binary\n * encoding of complex data types for blockchain transactions and storage.\n */\n\nimport { bcs, fromHex, toHex } from '@mysten/bcs'\n\n/**\n * BCS schema for Sui addresses with hex transformation\n * Converts between hex string representation and byte arrays\n */\nexport const Address = bcs.bytes(32).transform({\n // To change the input type, you need to provide a type definition for the input\n input: (val: string) => fromHex(val),\n output: (val) => toHex(val)\n})\n\n/**\n * BCS schema for incentive APY information\n * Contains asset ID, APY value, and supported coin types\n */\nexport const IncentiveAPYInfo = bcs.struct('IncentiveAPYInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Annual Percentage Yield as a 256-bit integer */\n apy: bcs.u256(),\n /** List of supported coin types for this incentive */\n coin_types: bcs.vector(bcs.string())\n})\n\n/**\n * BCS schema for incentive pool information\n * Contains comprehensive details about a lending incentive pool\n */\nexport const IncentivePoolInfo = bcs.struct('IncentivePoolInfo', {\n /** Unique pool identifier */\n pool_id: Address,\n /** Address holding the incentive funds */\n funds: Address,\n /** Current phase of the incentive program */\n phase: bcs.u64(),\n /** Timestamp when the incentive started */\n start_at: bcs.u64(),\n /** Timestamp when the incentive ends */\n end_at: bcs.u64(),\n /** Timestamp when the incentive was closed */\n closed_at: bcs.u64(),\n /** Total supply of incentive tokens */\n total_supply: bcs.u64(),\n /** Asset identifier for the incentive */\n asset_id: bcs.u8(),\n /** Option type for the incentive */\n option: bcs.u8(),\n /** Factor used in incentive calculations */\n factor: bcs.u256(),\n /** Amount of incentives already distributed */\n distributed: bcs.u64(),\n /** Amount of incentives currently available */\n available: bcs.u256(),\n /** Total amount of incentives */\n total: bcs.u256()\n})\n\n/**\n * BCS schema for incentive pool information grouped by phase\n * Contains phase number and list of pools in that phase\n */\nexport const IncentivePoolInfoByPhase = bcs.struct('IncentivePoolInfoByPhase', {\n /** Phase number */\n phase: bcs.u64(),\n /** List of incentive pools in this phase */\n pools: bcs.vector(IncentivePoolInfo)\n})\n\n/**\n * BCS schema for oracle price information\n * Contains price data from external price feeds\n */\nexport const OracleInfo = bcs.struct('OracleInfo', {\n /** Oracle identifier */\n oracle_id: bcs.u8(),\n /** Current price as a 256-bit integer */\n price: bcs.u256(),\n /** Number of decimal places for the price */\n decimals: bcs.u8(),\n /** Whether the oracle data is valid */\n valid: bcs.bool()\n})\n\n/**\n * BCS schema for flash loan asset configuration\n * Contains parameters for flash loan functionality\n */\nexport const FlashLoanAssetConfig = bcs.struct('FlashLoanAssetConfig', {\n /** Unique identifier for the flash loan asset */\n id: bcs.string(),\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** Coin type for the asset */\n coin_type: bcs.string(),\n /** Pool identifier for the flash loan */\n pool_id: bcs.string(),\n /** Rate paid to suppliers for flash loans */\n rate_to_supplier: bcs.u64(),\n /** Rate paid to treasury for flash loans */\n rate_to_treasury: bcs.u64(),\n /** Maximum flash loan amount */\n max: bcs.u64(),\n /** Minimum flash loan amount */\n min: bcs.u64()\n})\n\n/**\n * BCS schema for reserve data information\n * Contains comprehensive details about a lending reserve\n */\nexport const ReserveDataInfo = bcs.struct('ReserveDataInfo', {\n /** Reserve identifier */\n id: bcs.u8(),\n /** Oracle identifier for price feeds */\n oracle_id: bcs.u8(),\n /** Coin type for the reserve */\n coin_type: bcs.string(),\n /** Maximum supply capacity */\n supply_cap: bcs.u256(),\n /** Maximum borrow capacity */\n borrow_cap: bcs.u256(),\n /** Current supply interest rate */\n supply_rate: bcs.u256(),\n /** Current borrow interest rate */\n borrow_rate: bcs.u256(),\n /** Current supply index for interest calculation */\n supply_index: bcs.u256(),\n /** Current borrow index for interest calculation */\n borrow_index: bcs.u256(),\n /** Total amount supplied to the reserve */\n total_supply: bcs.u256(),\n /** Total amount borrowed from the reserve */\n total_borrow: bcs.u256(),\n /** Timestamp of last update */\n last_update_at: bcs.u64(),\n /** Loan-to-Value ratio for collateral */\n ltv: bcs.u256(),\n /** Treasury factor for fee calculations */\n treasury_factor: bcs.u256(),\n /** Current treasury balance */\n treasury_balance: bcs.u256(),\n /** Base interest rate */\n base_rate: bcs.u256(),\n /** Interest rate multiplier */\n multiplier: bcs.u256(),\n /** Jump rate multiplier for high utilization */\n jump_rate_multiplier: bcs.u256(),\n /** Reserve factor for protocol fees */\n reserve_factor: bcs.u256(),\n /** Optimal utilization rate */\n optimal_utilization: bcs.u256(),\n /** Liquidation ratio threshold */\n liquidation_ratio: bcs.u256(),\n /** Liquidation bonus for liquidators */\n liquidation_bonus: bcs.u256(),\n /** Liquidation threshold */\n liquidation_threshold: bcs.u256()\n})\n\n/**\n * BCS schema for user state information\n * Contains user's borrowing and supplying balances for an asset\n */\nexport const UserStateInfo = bcs.struct('UserStateInfo', {\n /** Asset identifier */\n asset_id: bcs.u8(),\n /** User's current borrow balance */\n borrow_balance: bcs.u256(),\n /** User's current supply balance */\n supply_balance: bcs.u256()\n})\n","import packageJson from '../package.json'\n\nconst sdkVersion = packageJson.version\n\nconst getNodeInfo = (): string => {\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n try {\n const os = require('os')\n const nodeVersion: string = process.version\n const osType: string = os.type()\n const osArch: string = os.arch()\n\n const formattedNodeVersion: string = nodeVersion.startsWith('v')\n ? nodeVersion.substring(1)\n : nodeVersion\n\n return `Node.js ${formattedNodeVersion}; ${osType}/${osArch}`\n } catch (e) {\n return `Node.js ${process.version}; OS/Unknown (Error)`\n }\n }\n return 'Node/Unknown'\n}\n\nexport const getUserAgent = (): string => {\n let environmentInfo: string = ''\n\n const isNode = typeof process !== 'undefined' && process.versions && process.versions.node\n\n if (isNode) {\n environmentInfo = `lending/${sdkVersion} (${getNodeInfo()})`\n }\n\n return environmentInfo\n}\n\nexport const userAgent = getUserAgent()\n","/**\n * Lending Utilities\n *\n * This module provides utility functions for the lending protocol, including\n * caching mechanisms, data transformation, transaction parsing, and blockchain\n * interaction helpers.\n *\n * @module LendingUtils\n */\n\nimport type { CacheOption, Pool, TransactionResult } from './types'\nimport type { DevInspectResults } from '@mysten/sui/client'\nimport { SuiClient, getFullnodeUrl } from '@mysten/sui/client'\nimport camelCase from 'lodash.camelcase'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { BcsType } from '@mysten/sui/bcs'\nimport { normalizeStructTag } from '@mysten/sui/utils'\nimport { SuiPriceServiceConnection } from '@pythnetwork/pyth-sui-js'\nimport BigNumber from 'bignumber.js'\nimport { userAgent } from './ua'\n\n/**\n * Default Sui client instance configured for mainnet\n */\nexport const suiClient = new SuiClient({\n url: getFullnodeUrl('mainnet')\n})\n\n/**\n * Generates a cache key from function arguments\n *\n * This function creates a unique key for caching by serializing the arguments\n * and removing cache-specific options that shouldn't affect the cache key.\n *\n * @param args - Function arguments to generate key from\n * @returns JSON string representing the arguments\n */\nfunction argsKey(args: any[]) {\n const serializergs = [] as any[]\n args.forEach((option: any, index) => {\n const isLast = index === args.length - 1\n if (typeof option === 'object' && isLast) {\n const { client, disableCache, cacheTime, ...rest } = option\n serializergs.push(rest)\n } else {\n serializergs.push(option)\n }\n })\n return JSON.stringify(serializergs)\n}\n\n/**\n * Wraps a function with singleton behavior to prevent duplicate concurrent calls\n *\n * This decorator ensures that if the same function is called with the same arguments\n * while a previous call is still pending, it returns the existing promise instead\n * of making a new call.\n *\n * @param fn - Function to wrap with singleton behavior\n * @returns Wrapped function with singleton behavior\n */\nexport function withSingleton<T extends (...args: any[]) => Promise<any>>(fn: T): T {\n const promiseMap: Record<string, Promise<any> | null> = {}\n\n return ((...args: any[]) => {\n const key = argsKey(args)\n if (!promiseMap[key]) {\n promiseMap[key] = fn(...args).finally(() => {\n promiseMap[key] = null\n })\n }\n return promiseMap[key]\n }) as T\n}\n\n/**\n * Wraps a function with caching behavior\n *\n * This decorator caches function results based on arguments and cache options.\n * It respects cache time settings and can be disabled per call.\n *\n * @param fn - Function to wrap with caching behavior\n * @returns Wrapped function with caching behavior\n */\nexport function withCache<T extends (...args: any[]) => Promise<any>>(fn: T): T {\n let cache: Record<\n string,\n {\n data: undefined\n cacheAt: number\n }\n > = {}\n\n return ((...args: any[]) => {\n const options = args[args.length - 1] as Partial<CacheOption>\n const key = argsKey(args)\n const cacheData = cache[key]\n\n // Check if cache is valid and not disabled\n if (!options?.disableCache && typeof cacheData?.data !== 'undefined') {\n if (\n typeof options?.cacheTime === 'undefined' ||\n options.cacheTime > Date.now() - cacheData.cacheAt\n ) {\n return cacheData.data\n }\n }\n\n // Execute function and cache result\n return fn(...args).then((result) => {\n cache[key] = {\n data: result,\n cacheAt: Date.now()\n }\n return result\n })\n }) as T\n}\n\n/**\n * Converts object keys from snake_case to camelCase recursively\n *\n * This function transforms all keys in an object (including nested objects and arrays)\n * from snake_case format to camelCase format.\n *\n * @param obj - Object to transform\n * @returns Object with camelCase keys\n */\nexport function camelize<T extends Record<string, any>>(obj: T): T {\n if (Array.isArray(obj)) {\n return obj.map((v) => camelize(v)) as unknown as T\n } else if (obj != null && typeof obj === 'object') {\n return Object.keys(obj).reduce(\n (result, key) => ({\n ...result,\n [camelCase(key)]: camelize(obj[key])\n }),\n {} as T\n )\n }\n return obj\n}\n\n/**\n * Parses a value for use in transaction building\n *\n * This function converts various value types into the appropriate format\n * for transaction building, handling both primitive types and existing\n * transaction results.\n *\n * @param value - Value to parse (string, number, boolean, or object)\n * @param format - Format function to apply to the value\n * @returns Transaction result in the appropriate format\n */\nexport function parseTxValue(\n value: string | number | boolean | object,\n format: any\n): TransactionResult {\n if (typeof value === 'object') {\n return value as TransactionResult\n }\n return format(value) as TransactionResult\n}\n\n/**\n * Parses a pool value for use in transaction building\n *\n * This function handles different pool representations and converts them\n * to the appropriate transaction object format.\n *\n * @param tx - Transaction object to build\n * @param value - Pool value (string, Pool object, or TransactionResult)\n * @returns Transaction result representing the pool\n */\nexport function parseTxPoolValue(tx: Transaction, value: string | Pool | TransactionResult) {\n if (typeof value === 'string') {\n return tx.object(value)\n }\n if (typeof value === 'object' && (value as TransactionResult).$kind) {\n return value as TransactionResult\n }\n return tx.object((value as Pool).contract.pool)\n}\n\n/**\n * Parses the result of a devInspectTransactionBlock call\n *\n * This function extracts and parses return values from transaction inspection\n * results using BCS (Binary Canonical Serialization) types.\n *\n * @param data - DevInspectResults from transaction inspection\n * @param parseTypes - Array of BCS types to parse the return values\n * @param options - Optional configuration including error handling\n * @returns Parsed result data\n */\nexport function parseDevInspectResult<T>(\n data: DevInspectResults,\n parseTypes: BcsType<any>[],\n options?: {\n throwError?: boolean\n }\n): T {\n if (data.results && data.results.length > 0) {\n if (data.results[0].returnValues && data.results[0].returnValues.length > 0) {\n return data.results[0].returnValues.map((item, index) => {\n const parseType = parseTypes[index] || parseTypes[0]\n return parseType.parse(Uint8Array.from(item[0]))\n }) as T\n }\n } else if (data.error) {\n console.log(`Get an error, msg: ${data.error}`)\n if (options?.throwError) {\n throw new Error(data.error)\n }\n return [] as T\n }\n return [] as T\n}\n\n/**\n * Normalizes a coin type string using Sui's struct tag normalization\n *\n * @param coinType - Coin type string to normalize\n * @returns Normalized coin type string\n */\nexport function normalizeCoinType(coinType: string) {\n return normalizeStructTag(coinType)\n}\n\n/**\n * Processes health factor values from contract format to human-readable format\n *\n * This function converts the raw health factor value from the contract\n * (which is typically a large integer) to a more readable decimal format.\n *\n * @param hf - Raw health factor value from contract\n * @returns Processed health factor value\n */\nexport function processContractHealthFactor(hf: number) {\n const healthFactor = (hf || 0) / Math.pow(10, 27)\n if (healthFactor > Math.pow(10, 5)) {\n return Infinity\n }\n return healthFactor\n}\n\n/**\n * Pyth price service connection for oracle price feeds\n *\n * This connection is used to fetch real-time price data from the Pyth network\n * for various assets in the lending protocol.\n */\nexport const suiPythConnection = new SuiPriceServiceConnection('https://hermes.pyth.network', {\n timeout: 20000\n})\n\nexport const Rate_Decimals = 27\n\nexport const rayMathMulIndex = (amount: string | number, index: string | number) => {\n if (!Number(amount) || !Number(index)) return new BigNumber(0)\n const ray = new BigNumber(1).shiftedBy(1 * Rate_Decimals)\n const halfRay = ray.multipliedBy(new BigNumber(0.5))\n return new BigNumber(amount)\n .multipliedBy(new BigNumber(index))\n .plus(halfRay)\n .dividedBy(ray)\n .integerValue(BigNumber.ROUND_DOWN)\n}\n\nexport const requestHeaders = !!userAgent\n ? {\n 'User-Agent': userAgent\n }\n : ({} as HeadersInit)\n","/**\n * Lending Configuration Management\n *\n * This module provides configuration management for the lending protocol.\n * It handles fetching configuration from the Navi protocol API and provides\n * caching mechanisms for efficient configuration retrieval.\n *\n * @module LendingConfig\n */\n\nimport type { LendingConfig, EnvOption, CacheOption } from './types'\nimport { withCache, withSingleton, requestHeaders } from './utils'\nimport packageJson from '../package.json'\n\n/**\n * Fetches lending protocol configuration from the API\n *\n * This function retrieves the current configuration for the lending protocol\n * from the Navi protocol API. It's wrapped with both caching and singleton\n * behavior to ensure efficient and consistent configuration access.\n *\n * The configuration includes:\n * - Contract addresses for all protocol components\n * - Oracle configuration and price feed information\n * - Pool and incentive contract addresses\n * - Environment-specific settings\n *\n * @param options - Optional environment and caching options\n * @returns Promise<LendingConfig> - Complete lending protocol configuration\n */\nexport const getConfig = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<LendingConfig> => {\n const url = `https://open-api.naviprotocol.io/api/navi/config?env=${options?.env || 'prod'}&sdk=${packageJson.version}`\n\n // Fetch configuration from API\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Default cache time for configuration data\n *\n * Configuration is cached for 5 minutes to reduce API calls\n * while ensuring reasonably fresh configuration data.\n */\nexport const DEFAULT_CACHE_TIME = 1000 * 60 * 5\n","/**\n * Lending Pool Operations\n *\n * This module provides comprehensive pool management functionality for the lending protocol.\n * It handles pool information retrieval, deposit/withdraw operations, borrow/repay operations,\n * and various pool-related utilities and statistics.\n *\n * @module LendingPool\n */\n\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport type {\n EnvOption,\n CacheOption,\n Pool,\n AssetIdentifier,\n PoolStats,\n FeeDetail,\n CoinObject,\n TransactionResult,\n AccountCapOption,\n BorrowFeeOption,\n SuiClientOption\n} from './types'\nimport {\n normalizeCoinType,\n withCache,\n withSingleton,\n parseTxValue,\n suiClient,\n requestHeaders\n} from './utils'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { parseDevInspectResult } from './utils'\nimport { bcs } from '@mysten/sui/bcs'\n\n/**\n * Enumeration of pool operations\n *\n * This enum defines the different types of operations that can be performed\n * on lending pools, used for health factor calculations and operation tracking.\n */\nexport enum PoolOperator {\n /** Supply/deposit operation */\n Supply = 1,\n /** Withdraw operation */\n Withdraw = 2,\n /** Borrow operation */\n Borrow = 3,\n /** Repay operation */\n Repay = 4\n}\n\n/**\n * Fetches all available lending pools\n *\n * This function retrieves the complete list of lending pools from the Navi protocol API.\n * It's wrapped with caching and singleton behavior for efficient data access.\n *\n * @param options - Optional environment and caching options\n * @returns Promise<Pool[]> - Array of all available lending pools\n */\nexport const getPools = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<Pool[]> => {\n const url = `https://open-api.naviprotocol.io/api/navi/pools?env=${options?.env || 'prod'}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Gets information for a specific lending pool\n *\n * This function retrieves pool information based on various identifier types:\n * - Pool object (returns directly)\n * - String (coin type - normalized for comparison)\n * - Number (pool ID)\n *\n * @param identifier - Asset identifier (string, Pool object, or number)\n * @param options - Optional environment options\n * @returns Promise<Pool> - Pool information\n * @throws Error if pool is not found\n */\nexport async function getPool(\n identifier: AssetIdentifier,\n options?: Partial<EnvOption>\n): Promise<Pool> {\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // If identifier is already a pool object, return it directly\n if (typeof identifier === 'object') {\n return identifier\n }\n\n // Find pool by identifier\n const pool = pools.find((p) => {\n if (typeof identifier === 'string') {\n return normalizeCoinType(p.suiCoinType) === normalizeCoinType(identifier)\n }\n if (typeof identifier === 'number') {\n return p.id === identifier\n }\n return false\n })\n\n if (!pool) {\n throw new Error(`Pool not found`)\n }\n\n if (pool.isDeprecated) {\n console.log(`The lending pool for coinType ${pool.suiCoinType} is going to be deprecated.`)\n }\n return pool\n}\n\n/**\n * Fetches protocol statistics\n *\n * This function retrieves overall protocol statistics including TVL,\n * total borrow amounts, and other key metrics.\n *\n * @param options - Optional caching options\n * @returns Promise<PoolStats> - Protocol statistics\n */\nexport const getStats = withCache(\n withSingleton(async (options?: Partial<CacheOption>): Promise<PoolStats> => {\n const url = `https://open-api.naviprotocol.io/api/navi/stats`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n })\n)\n\n/**\n * Fetches protocol fee information\n *\n * This function retrieves detailed fee information including:\n * - Total fee value\n * - V3 borrow fees\n * - Borrow interest fees\n * - Flash loan and liquidation fees\n *\n * @param options - Optional caching options\n * @returns Promise with detailed fee breakdown\n */\nexport const getFees = withCache(\n withSingleton(\n async (\n options?: Partial<CacheOption>\n ): Promise<{\n totalValue: number\n v3BorrowFee: {\n totalValue: number\n details: FeeDetail[]\n }\n borrowInterestFee: {\n totalValue: number\n details: FeeDetail[]\n }\n flashloanAndLiquidationFee: {\n totalValue: number\n details: FeeDetail[]\n }\n }> => {\n const url = `https://open-api.naviprotocol.io/api/navi/fee`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res\n }\n )\n)\n\n/**\n * Builds a deposit transaction for a lending pool\n *\n * This function creates a transaction block for depositing coins into a lending pool.\n * It handles both regular deposits and deposits with account capabilities,\n * and includes special handling for SUI gas coins.\n *\n * @param tx - Transaction object to build\n * @param identifier - Asset identifier for the pool\n * @param coinObject - Coin object to deposit\n * @param options - Optional parameters including environment, account capability, and amount\n * @returns Promise<Transaction> - Transaction with deposit operation\n */\nexport async function depositCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n coinObject: CoinObject,\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n amount: number | TransactionResult\n }\n >\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n if (pool?.deprecatedAt && Date.now() > pool.deprecatedAt) {\n throw new Error(`The lending pool for coinType ${pool.suiCoinType} has been deprecated.`)\n }\n\n const isGasCoin = typeof coinObject === 'object' && coinObject.$kind === 'GasCoin'\n\n // Handle SUI gas coin deposits\n if (normalizeCoinType(pool.suiCoinType) === normalizeCoinType('0x2::sui::SUI') && isGasCoin) {\n if (!options?.amount) {\n throw new Error('Amount is required for sui coin')\n }\n coinObject = tx.splitCoins(coinObject, [options.amount])\n }\n\n // Determine deposit amount\n let depositAmount: TransactionResult\n\n if (typeof options?.amount !== 'undefined') {\n depositAmount = parseTxValue(options.amount, tx.pure.u64)\n } else {\n depositAmount = tx.moveCall({\n target: '0x2::coin::value',\n arguments: [parseTxValue(coinObject as any, tx.object)],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n // Build deposit transaction based on account capability\n if (options?.accountCap) {\n tx.moveCall({\n target: `${config.package}::incentive_v3::deposit_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n } else {\n tx.moveCall({\n target: `${config.package}::incentive_v3::entry_deposit`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n depositAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n // refresh stake for sui pool to balance the stake after deposit\n if (config.version === 2 && pool.id === 0) {\n tx.moveCall({\n target: `${config.package}::pool::refresh_stake`,\n arguments: [tx.object(pool.contract.pool), tx.object('0x05')]\n })\n }\n\n return tx\n}\n\n/**\n * Builds a withdraw transaction for a lending pool\n *\n * Constructs and adds withdrawal operations to a transaction object.\n * This function supports standard withdrawal and withdrawal using account capability.\n *\n * @param tx - The transaction builder to append operations to\n * @param identifier - Asset identifier for the pool\n * @param amount - Amount to withdraw\n * @param options - Optional parameters including environment and account capability\n * @returns Transaction result representing the withdrawn coins\n */\nexport async function withdrawCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption & AccountCapOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const withdrawAmount = parseTxValue(amount, tx.pure.u64)\n\n let withdrawBalance\n\n if (config.version === 1) {\n // Build withdraw transaction based on account capability\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n }\n } else {\n // Build withdraw transaction based on account capability\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_with_account_cap_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::withdraw_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n withdrawAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n withdrawBalance = ret\n }\n }\n\n const withdrawCoin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [withdrawBalance],\n typeArguments: [pool.suiCoinType]\n })\n\n return withdrawCoin\n}\n\nexport async function borrowCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption & AccountCapOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n if (pool?.deprecatedAt && Date.now() > pool.deprecatedAt) {\n throw new Error(`The lending pool for coinType ${pool.suiCoinType} has been deprecated.`)\n }\n\n const borrowAmount = parseTxValue(amount, tx.pure.u64)\n\n let borrowBalance\n\n if (config.version === 1) {\n if (!options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n }\n } else {\n if (!options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n } else {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::borrow_with_account_cap_v2`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n borrowAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n borrowBalance = ret\n }\n }\n\n const coin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [tx.object(borrowBalance)],\n typeArguments: [pool.suiCoinType]\n })\n\n return coin\n}\n\n/**\n * Builds a repay transaction for a lending pool debt\n *\n * Constructs and adds repayment operations to an existing transaction object.\n * This function handles loan repayments, supporting both standard user\n * repayments and privileged operations via account capabilities.\n *\n *\n * @param tx - The transaction builder to append repayment operations to\n * @param identifier - Unique identifier for the lending pool asset (e.g., \"USDC\", \"SUI\")\n * @param coinObject - The coin object to use for repayment, or GasCoin for SUI payments\n * @param options - Configuration options for the repayment\n * - `amount` - Specific amount to repay (required for SUI gas coin, otherwise uses value of specified coinObject)\n * - `accountCap` - Optional account capability object for privileged repayments\n * - `env` - Environment configuration\n * - `cacheTime` - Cache duration for configuration data\n *\n * @returns Promise<Transaction | TransactionResult> - The modified transaction object with repayment operations added\n *\n * @throws {Error} When amount is not provided for SUI gas coin repayments\n * @throws Will throw if pool doesn't exist or repayment validation fails\n */\nexport async function repayCoinPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n coinObject: CoinObject,\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n amount: number | TransactionResult\n }\n >\n): Promise<Transaction | TransactionResult> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n const isGasCoin = typeof coinObject === 'object' && coinObject.$kind === 'GasCoin'\n\n if (normalizeCoinType(pool.suiCoinType) === normalizeCoinType('0x2::sui::SUI') && isGasCoin) {\n if (!options?.amount) {\n throw new Error('Amount is required for sui coin')\n }\n coinObject = tx.splitCoins(coinObject, [options.amount])\n }\n\n let repayAmount: TransactionResult\n\n if (typeof options?.amount !== 'undefined') {\n repayAmount = parseTxValue(options.amount, tx.pure.u64)\n } else {\n repayAmount = tx.moveCall({\n target: '0x2::coin::value',\n arguments: [parseTxValue(coinObject as any, tx.object)],\n typeArguments: [pool.suiCoinType]\n })\n }\n\n if (options?.accountCap) {\n const [ret] = tx.moveCall({\n target: `${config.package}::incentive_v3::repay_with_account_cap`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3),\n parseTxValue(options.accountCap, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n const coin = tx.moveCall({\n target: `0x2::coin::from_balance`,\n arguments: [ret],\n typeArguments: [pool.suiCoinType]\n })\n return coin\n } else {\n tx.moveCall({\n target: `${config.package}::incentive_v3::entry_repay`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.priceOracle),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n tx.pure.u8(pool.id),\n parseTxValue(coinObject, tx.object),\n repayAmount,\n tx.object(config.incentiveV2),\n tx.object(config.incentiveV3)\n ],\n typeArguments: [pool.suiCoinType]\n })\n return tx\n }\n}\n\n/**\n * Fetches the current borrow fee rate\n *\n * This function can retrieve borrow fee rates in two ways:\n * - If `address` and `asset` are provided, it calculates the specific borrow fee rate\n * for a given address and asset by calling the on-chain `get_borrow_fee_v2` function\n * - Otherwise, it returns the global borrow fee rate from the incentive V3 contract\n *\n * @param options - Optional configuration options\n * - `address` - User address to calculate specific borrow fee (requires `asset` to be set)\n * - `asset` - Asset identifier to calculate specific borrow fee (requires `address` to be set)\n * - `env` - Environment setting ('dev' or 'prod')\n * - `client` - Sui client instance for on-chain queries\n * - `cacheTime` - Cache expiration time in milliseconds\n * - `disableCache` - Whether to disable caching for this operation\n * @returns Promise<number> - Borrow fee rate as a decimal number\n * - When `address` and `asset` are provided: returns the specific fee rate (divided by 10000)\n * - Otherwise: returns the global fee rate (divided by 100)\n */\nexport const getBorrowFee = withCache(\n withSingleton(\n async (\n options?: Partial<EnvOption & CacheOption & BorrowFeeOption & SuiClientOption>\n ): Promise<number> => {\n const config = await getConfig({\n ...options\n })\n if (options?.address && typeof options?.asset !== 'undefined') {\n try {\n const pool = await getPool(options.asset, options)\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n tx.moveCall({\n target: `${config.package}::incentive_v3::get_borrow_fee_v2`,\n arguments: [\n tx.object(config.incentiveV3),\n tx.pure.address(options.address),\n tx.pure.u8(pool.id),\n tx.pure.u64(10000)\n ],\n typeArguments: []\n })\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: options.address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u64()])\n return (Number(res[0]) || 0) / 100\n } catch (error) {\n console.error(error)\n }\n }\n const rawData: any = await suiClient.getObject({\n id: config.incentiveV3,\n options: { showType: true, showOwner: true, showContent: true }\n })\n const borrowFee = rawData.data.content.fields.borrow_fee_rate\n return Number(borrowFee) / 100\n }\n )\n)\n","/**\n * Lending Account Management\n *\n * This module provides comprehensive account management functionality for the lending protocol.\n * It includes coin merging, health factor calculations, user state management, and various\n * lending operations like supply, borrow, withdraw, and repay.\n *\n * @module LendingAccount\n */\n\nimport type {\n UserLendingInfo,\n SuiClientOption,\n EnvOption,\n Pool,\n Transaction as NAVITransaction,\n AssetIdentifier,\n TransactionResult,\n CacheOption,\n AccountCap\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { UserStateInfo } from './bcs'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n suiClient,\n camelize,\n parseDevInspectResult,\n withSingleton,\n processContractHealthFactor,\n parseTxValue,\n parseTxPoolValue,\n withCache,\n normalizeCoinType,\n rayMathMulIndex,\n requestHeaders\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport { CoinStruct, PaginatedCoins } from '@mysten/sui/client'\nimport { getPool, getPools, PoolOperator } from './pool'\n\n/**\n * Merges multiple coins into a single coin for transaction building\n *\n * This function takes multiple coin objects and merges them into a single coin\n * that can be used in a transaction. It supports optional splitting to create\n * a specific balance amount.\n *\n * @param tx - Transaction object to add merge operations to\n * @param coins - Array of coin objects to merge\n * @param options - Optional parameters for balance splitting and gas coin usage\n * - `balance` - If provided, splits this amount from the resulting coin object\n * - `useGasCoin` - If true, uses the gas coin for the operation\n * @returns Transaction result representing the merged coin\n */\nexport function mergeCoinsPTB(\n tx: Transaction,\n coins: ({\n balance: string | number | bigint\n coinObjectId: string\n coinType: string\n } & CoinStruct)[],\n options?: {\n balance?: number\n useGasCoin?: boolean\n }\n) {\n const needSplit = typeof options?.balance === 'number'\n const splitBalance = needSplit ? options.balance! : 0\n let mergedBalance = 0\n const mergeList: string[] = []\n let coinType = ''\n\n // Sort coins by balance (highest first) and collect valid coins\n coins\n .sort((a, b) => Number(b.balance) - Number(a.balance))\n .forEach((coin) => {\n if (needSplit && mergedBalance >= splitBalance) {\n return\n }\n if (Number(coin.balance) === 0) {\n return\n }\n if (!coinType) {\n coinType = coin.coinType\n }\n if (coinType !== coin.coinType) {\n throw new Error('All coins must be of the same type')\n }\n mergedBalance += Number(coin.balance)\n mergeList.push(coin.coinObjectId)\n })\n\n if (mergeList.length === 0) {\n throw new Error('No coins to merge')\n }\n if (needSplit && mergedBalance < splitBalance) {\n throw new Error(\n `Balance is less than the specified balance: ${mergedBalance} < ${splitBalance}`\n )\n }\n\n // Handle SUI gas coin specially\n if (normalizeCoinType(coinType) === normalizeCoinType('0x2::sui::SUI') && options?.useGasCoin) {\n return needSplit ? tx.splitCoins(tx.gas, [tx.pure.u64(splitBalance)]) : tx.gas\n }\n\n // Merge coins and optionally split\n const coin =\n mergeList.length === 1\n ? tx.object(mergeList[0])\n : tx.mergeCoins(mergeList[0], mergeList.slice(1))\n\n return needSplit ? tx.splitCoins(coin, [tx.pure.u64(splitBalance)]) : coin\n}\n\n/**\n * Calculates dynamic health factor for a user after potential operations\n *\n * This function creates a transaction call to calculate the health factor\n * that would result after performing supply/borrow operations.\n *\n * @param tx - Transaction object to append calculation to\n * @param address - User address or transaction result\n * @param identifier - Asset identifier\n * @param estimatedSupply - Estimated supply amount\n * @param estimatedBorrow - Estimated borrow amount\n * @param isIncrease - Whether this is an increase operation\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getSimulatedHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n identifier: AssetIdentifier,\n estimatedSupply: number | TransactionResult,\n estimatedBorrow: number | TransactionResult,\n isIncrease: boolean | TransactionResult,\n options?: Partial<EnvOption>\n): Promise<TransactionResult> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n return tx.moveCall({\n target: `${config.uiGetter}::calculator_unchecked::dynamic_health_factor`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(config.oracle.priceOracle),\n parseTxPoolValue(tx, pool),\n parseTxValue(address, tx.pure.address),\n parseTxValue(pool.id, tx.pure.u8),\n parseTxValue(estimatedSupply, tx.pure.u64),\n parseTxValue(estimatedBorrow, tx.pure.u64),\n parseTxValue(isIncrease, tx.pure.bool)\n ],\n typeArguments: [pool.suiCoinType]\n })\n}\n\n/**\n * Gets the current health factor for a user\n *\n * @param tx - The transaction object to add health factor query operation to\n * @param address - User address or account cap or transaction result\n * @param options - Environment options\n * @returns Transaction result for health factor calculation\n */\nexport async function getHealthFactorPTB(\n tx: Transaction,\n address: string | AccountCap | TransactionResult,\n options?: Partial<EnvOption>\n): Promise<TransactionResult> {\n return getSimulatedHealthFactorPTB(tx, address, 0, 0, 0, false, options)\n}\n\n/**\n * Retrieves the current lending state for a user\n *\n * This function fetches all active lending positions for a user, including\n * supply and borrow balances for different assets.\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client, environment, and caching\n * @returns Promise<UserLendingInfo[]> - Array of user lending positions\n */\nexport const getLendingState = withCache(\n async (\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption & CacheOption>\n ): Promise<UserLendingInfo[]> => {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const tx = new Transaction()\n const client = options?.client ?? suiClient\n\n const pools = await getPools(options)\n\n // Create transaction call to get user state\n tx.moveCall({\n target: `${config.uiGetter}::getter_unchecked::get_user_state`,\n arguments: [tx.object(config.storage), tx.pure.address(address!)]\n })\n\n // Execute dry run to get user state\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n\n // Parse the result and filter out zero balances\n const res = parseDevInspectResult<\n {\n supply_balance: string\n borrow_balance: string\n asset_id: number\n }[][]\n >(result, [bcs.vector(UserStateInfo as any)])\n\n const lendingStates = camelize(\n res[0].filter((item) => {\n return item.supply_balance !== '0' || item.borrow_balance !== '0'\n })\n ) as any as {\n supplyBalance: string\n borrowBalance: string\n assetId: number\n }[]\n\n return lendingStates\n .map((lendingState) => {\n const pool = pools.find((pool) => pool.id === lendingState.assetId)\n const supplyBalance = rayMathMulIndex(\n lendingState.supplyBalance,\n pool!.currentSupplyIndex\n ).toString()\n const borrowBalance = rayMathMulIndex(\n lendingState.borrowBalance,\n pool!.currentBorrowIndex\n ).toString()\n return {\n ...lendingState,\n supplyBalance,\n borrowBalance,\n pool\n }\n })\n .filter((lendingState) => !!lendingState.pool) as any\n }\n)\n\n/**\n * Calculates the current health factor for a user\n *\n * @param address - User wallet address or account cap\n * @param options - Options for client and environment\n * @returns Promise<number> - Health factor value\n */\nexport async function getHealthFactor(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n await getHealthFactorPTB(tx, address, options)\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Calculates the health factor after performing lending operations\n *\n * This function simulates the health factor that would result after\n * performing a series of supply, withdraw, borrow, or repay operations.\n *\n * @param address - User wallet address or account cap\n * @param identifier - Asset identifier\n * @param operations - Array of operations to simulate\n * @param options - Options for client and environment\n * @returns Promise<number> - Projected health factor\n */\nexport async function getSimulatedHealthFactor(\n address: string | AccountCap,\n identifier: AssetIdentifier,\n operations: {\n type: PoolOperator\n amount: number\n }[],\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<number> {\n const client = options?.client ?? suiClient\n const tx = new Transaction()\n let estimatedSupply = 0\n let estimatedBorrow = 0\n const pool = await getPool(identifier, options)\n\n // Calculate estimated changes from operations\n operations.forEach((operation) => {\n if (operation.type === PoolOperator.Supply) {\n estimatedSupply += operation.amount\n } else if (operation.type === PoolOperator.Withdraw) {\n estimatedSupply -= operation.amount\n } else if (operation.type === PoolOperator.Borrow) {\n estimatedBorrow += operation.amount\n } else if (operation.type === PoolOperator.Repay) {\n estimatedBorrow -= operation.amount\n }\n })\n\n // Validate operation consistency\n if (estimatedSupply * estimatedBorrow < 0) {\n throw new Error('Invalid operations')\n }\n\n // Determine if this is an increase operation\n const isIncrease = estimatedSupply > 0 || estimatedBorrow > 0\n\n // Calculate the dynamic health factor\n await getSimulatedHealthFactorPTB(\n tx,\n address,\n pool,\n Math.abs(estimatedSupply),\n Math.abs(estimatedBorrow),\n isIncrease,\n options\n )\n\n // Execute dry run to get the result\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n const res = parseDevInspectResult<number[]>(result, [bcs.u256()])\n return processContractHealthFactor(Number(res[0]) || 0)\n}\n\n/**\n * Retrieves transaction history for a user from the Navi protocol API\n *\n * This function fetches the transaction history for a specific user address\n * from the Navi protocol's open API. It supports pagination through cursor-based navigation.\n *\n * @param address - User wallet address or account cap\n * @param options - Optional parameters including cursor for pagination\n * @returns Promise with transaction data and optional cursor for next page\n */\nexport const getTransactions = withSingleton(\n async (\n address: string | AccountCap,\n options?: {\n cursor?: string\n }\n ): Promise<{\n data: NAVITransaction[]\n cursor?: string\n }> => {\n // Build query parameters for the API request\n const params = new URLSearchParams()\n if (options?.cursor) {\n params.set('cursor', options.cursor)\n }\n params.set('userAddress', address)\n\n // Fetch transaction history from Navi protocol API\n const url = `https://open-api.naviprotocol.io/api/navi/user/transactions?${params.toString()}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n }\n)\n\n/**\n * Retrieves all coins owned by a user address\n *\n * This function fetches all coin objects owned by a specific address from the Sui blockchain.\n * It supports filtering by coin type and handles pagination automatically to retrieve all coins.\n *\n * @param address - User wallet address\n * @param options - Optional parameters including coin type filter and client options\n * - `coinType` - If specified, retrieves only coins of this type\n * - `client` - If provided, uses this `SuiClient` instance instead of the default client\n * @returns Promise<CoinStruct[]> - Array of coin objects owned by the address\n */\nexport async function getCoins(\n address: string,\n options?: Partial<\n {\n coinType?: string\n } & SuiClientOption\n >\n): Promise<CoinStruct[]> {\n let cursor: string | undefined | null = null\n const allCoinDatas: CoinStruct[] = []\n const client = options?.client ?? suiClient\n\n // Fetch all coins using pagination\n do {\n let res: PaginatedCoins\n\n // Use specific coin type filter if provided, otherwise get all coins\n if (options?.coinType) {\n res = await client.getCoins({\n owner: address,\n coinType: options?.coinType,\n cursor,\n limit: 100\n })\n } else {\n res = await client.getAllCoins({\n owner: address,\n cursor,\n limit: 100\n })\n }\n\n // Break if no more data\n if (!res.data || !res.data.length) {\n break\n }\n\n // Collect coin data and continue with next page\n allCoinDatas.push(...res.data)\n cursor = res.nextCursor\n } while (cursor)\n\n return allCoinDatas\n}\n","/**\n * Oracle Price Feed Management for Lending Protocol\n *\n * This module provides oracle price feed functionality for the lending protocol.\n * It integrates with Pyth Network for real-time price data and manages price updates\n * for various assets used in lending operations.\n */\n\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport type { OraclePriceFeed, EnvOption, UserLendingInfo, Pool, SuiClientOption } from './types'\nimport { SuiPriceServiceConnection, SuiPythClient } from '@pythnetwork/pyth-sui-js'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { suiClient } from './utils'\n\n/**\n * Pyth Network connection for price feed data\n * Connects to the Hermes endpoint for real-time price updates\n */\nconst suiPythConnection = new SuiPriceServiceConnection('https://hermes.pyth.network', {\n timeout: 10000\n})\n\n/**\n * Get stale price feed IDs from Pyth Network\n *\n * Identifies price feeds that have not been updated recently (more than 30 seconds old).\n * This helps ensure that only fresh price data is used for lending operations.\n *\n * @param priceIds - Array of Pyth price feed IDs to check\n * @returns Array of stale price feed IDs that need updating\n * @throws Error if failed to fetch price feed data\n */\nexport async function getPythStalePriceFeedId(priceIds: string[]): Promise<string[]> {\n try {\n const returnData: string[] = []\n const latestPriceFeeds = await suiPythConnection.getLatestPriceFeeds(priceIds)\n if (!latestPriceFeeds) return returnData\n\n const currentTimestamp = Math.floor(new Date().valueOf() / 1000)\n for (const priceFeed of latestPriceFeeds) {\n const uncheckedPrice = priceFeed.getPriceUnchecked()\n if (uncheckedPrice.publishTime > currentTimestamp) {\n console.warn(\n `pyth price feed is invalid, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n continue\n }\n\n // From pyth state is 60, but setting it to 30 makes more sense.\n if (currentTimestamp - priceFeed.getPriceUnchecked().publishTime > 30) {\n console.info(\n `stale price feed, id: ${priceFeed.id}, publish time: ${uncheckedPrice.publishTime}, current timestamp: ${currentTimestamp}`\n )\n returnData.push(priceFeed.id)\n }\n }\n return returnData\n } catch (error) {\n throw new Error(`failed to get pyth stale price feed id, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update Pyth price feeds in a transaction\n *\n * Fetches the latest price update data from Pyth Network and adds the update\n * operations to the transaction block.\n *\n * @param tx - The transaction block to add price feed updates to\n * @param priceFeedIds - Array of Pyth price feed IDs to update\n * @param options - Optional client and environment configuration\n * @returns Promise that resolves when price feeds are updated\n * @throws Error if failed to update price feeds\n */\nexport async function updatePythPriceFeeds(\n tx: Transaction,\n priceFeedIds: string[],\n options?: Partial<SuiClientOption & EnvOption>\n) {\n const client = options?.client ?? suiClient\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n try {\n const priceUpdateData = await suiPythConnection.getPriceFeedsUpdateData(priceFeedIds)\n const suiPythClient = new SuiPythClient(\n client as any,\n config.oracle.pythStateId,\n config.oracle.wormholeStateId\n )\n\n return await suiPythClient.updatePriceFeeds(tx as any, priceUpdateData, priceFeedIds)\n } catch (error) {\n throw new Error(`failed to update pyth price feeds, msg: ${(error as Error).message}`)\n }\n}\n\n/**\n * Update oracle prices in the PTB (Programmable Transaction Block)\n *\n * This function updates price feeds for the lending protocol. It can optionally\n * update Pyth price feeds first if they are stale, then updates individual\n * price feeds in the oracle contract.\n *\n * @param tx - The transaction block to add price update operations to\n * @param priceFeeds - Array of oracle price feeds to update\n * @param options - Optional configuration including whether to update Pyth feeds\n * @returns The updated transaction block\n */\nexport async function updateOraclePricesPTB(\n tx: Transaction,\n priceFeeds: OraclePriceFeed[],\n options?: Partial<\n EnvOption & {\n updatePythPriceFeeds?: boolean\n }\n >\n): Promise<Transaction> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Optionally update Pyth price feeds if they are stale\n if (options?.updatePythPriceFeeds) {\n const pythPriceFeedIds = priceFeeds\n .filter((feed) => !!feed.pythPriceFeedId)\n .map((feed) => feed.pythPriceFeedId)\n\n try {\n const stalePriceFeedIds = await getPythStalePriceFeedId(pythPriceFeedIds)\n if (stalePriceFeedIds.length > 0) {\n await updatePythPriceFeeds(tx, stalePriceFeedIds, options)\n }\n } catch (e) {}\n }\n\n // Update individual price feeds in the oracle contract\n for (const priceFeed of priceFeeds) {\n tx.moveCall({\n target: `${config.oracle.packageId}::oracle_pro::update_single_price`,\n arguments: [\n tx.object('0x6'), // Clock object\n tx.object(config.oracle.oracleConfig), // Oracle configuration\n tx.object(config.oracle.priceOracle), // Price oracle contract\n tx.object(config.oracle.supraOracleHolder), // Supra oracle holder\n tx.object(priceFeed.pythPriceInfoObject), // Pyth price info object\n tx.pure.address(priceFeed.feedId) // Price feed ID\n ]\n })\n }\n return tx\n}\n\n/**\n * Get all available price feeds from the configuration\n *\n * @param options - Optional environment configuration\n * @returns Array of oracle price feed configurations\n */\nexport async function getPriceFeeds(options?: Partial<EnvOption>): Promise<OraclePriceFeed[]> {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n return config.oracle.feeds\n}\n\n/**\n * Filter price feeds based on lending state and pools\n *\n * This function filters price feeds to only include those that are relevant\n * to the current lending state or available pools.\n *\n * @param feeds - Array of price feeds to filter\n * @param filters - Filter criteria including lending state and pools\n * @returns Filtered array of price feeds\n */\nexport function filterPriceFeeds(\n feeds: OraclePriceFeed[],\n filters: {\n lendingState?: UserLendingInfo[]\n pools?: Pool[]\n }\n): OraclePriceFeed[] {\n return feeds.filter((feed) => {\n // Filter by lending state (user's current positions)\n if (filters?.lendingState) {\n const inState = filters.lendingState.find((state) => {\n return state.assetId === feed.assetId\n })\n if (inState) {\n return true\n }\n }\n\n // Filter by available pools\n if (filters?.pools) {\n const inPool = filters.pools.find((pool) => {\n return pool.id === feed.assetId\n })\n if (inPool) {\n return true\n }\n }\n return false\n })\n}\n","/**\n * Flash Loan Functionality for Lending Protocol\n *\n * This module provides flash loan capabilities for the lending protocol.\n * Flash loans allow users to borrow assets without collateral for a single transaction,\n * as long as the borrowed amount is repaid within the same transaction.\n */\n\nimport type { Transaction } from '@mysten/sui/transactions'\nimport type {\n EnvOption,\n AssetIdentifier,\n CoinObject,\n CacheOption,\n FloashloanAsset,\n TransactionResult\n} from './types'\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport { parseTxValue, normalizeCoinType, withCache, withSingleton, requestHeaders } from './utils'\nimport { getPool } from './pool'\n\n/**\n * Get all available flash loan assets from the API\n * Uses caching to avoid repeated API calls\n *\n * @param options - Optional environment and cache configuration\n * @returns Array of flash loan asset configurations\n */\nexport const getAllFlashLoanAssets = withCache(\n withSingleton(async (options?: Partial<EnvOption & CacheOption>): Promise<FloashloanAsset[]> => {\n const url = `https://open-api.naviprotocol.io/api/navi/flashloan?env=${options?.env || 'prod'}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return Object.keys(res.data).map((coinType) => {\n return {\n ...res.data[coinType],\n coinType\n }\n })\n })\n)\n\n/**\n * Get a specific flash loan asset by identifier\n *\n * @param identifier - Asset identifier (string coin type, number asset ID, or object with id)\n * @param options - Optional environment configuration\n * @returns Flash loan asset configuration or null if not found\n */\nexport async function getFlashLoanAsset(\n identifier: AssetIdentifier,\n options?: Partial<EnvOption>\n): Promise<FloashloanAsset | null> {\n const assets = await getAllFlashLoanAssets(options)\n return (\n assets.find((asset) => {\n if (typeof identifier === 'string') {\n return normalizeCoinType(asset.coinType) === normalizeCoinType(identifier)\n }\n if (typeof identifier === 'number') {\n return asset.assetId === identifier\n }\n return asset.assetId === identifier.id\n }) || null\n )\n}\n\n/**\n * Create a flash loan transaction in the PTB (Programmable Transaction Block)\n *\n * This function initiates a flash loan by borrowing the specified amount of assets.\n * The borrowed assets must be repaid within the same transaction using repayFlashLoanPTB.\n *\n * @param tx - The transaction block to add the flash loan operation to\n * @param identifier - Asset identifier to borrow\n * @param amount - Amount to borrow (number or transaction result)\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance, receipt] where receipt is needed for repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function flashloanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n amount: number | TransactionResult,\n options?: Partial<EnvOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n if (config.version === 1) {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64)\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n } else {\n const [balance, receipt] = tx.moveCall({\n target: `${config.package}::lending::flash_loan_with_ctx_v2`,\n arguments: [\n tx.object(config.flashloanConfig),\n tx.object(pool.contract.pool),\n parseTxValue(amount, tx.pure.u64),\n tx.object('0x05')\n ],\n typeArguments: [pool.suiCoinType]\n })\n\n return [balance, receipt]\n }\n}\n\n/**\n * Repay a flash loan transaction in the PTB\n *\n * This function repays the flash loan using the receipt from the original flash loan\n * and the coin object containing the repayment amount.\n *\n * @param tx - The transaction block to add the repayment operation to\n * @param identifier - Asset identifier being repaid\n * @param receipt - Receipt from the original flash loan transaction\n * @param coinObject - Coin object containing the repayment amount\n * @param options - Optional environment configuration\n * @returns Tuple containing [balance] after repayment\n * @throws Error if the pool does not support flash loans\n */\nexport async function repayFlashLoanPTB(\n tx: Transaction,\n identifier: AssetIdentifier,\n receipt: TransactionResult | string,\n coinObject: CoinObject,\n options?: Partial<EnvOption>\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const pool = await getPool(identifier, options)\n\n const flashLoanAssets = await getAllFlashLoanAssets({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const isSupport = flashLoanAssets.some(\n (asset) => normalizeCoinType(asset.coinType) === normalizeCoinType(pool.suiCoinType)\n )\n\n if (!isSupport) {\n throw new Error('Pool does not support flashloan')\n }\n\n // v2 entry is not required to repay\n const [balance] = tx.moveCall({\n target: `${config.package}::lending::flash_repay_with_ctx`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.storage),\n tx.object(pool.contract.pool),\n parseTxValue(receipt, tx.object),\n parseTxValue(coinObject, tx.object)\n ],\n typeArguments: [pool.suiCoinType]\n })\n return [balance]\n}\n","/**\n * Liquidation Functionality for Lending Protocol\n *\n * This module provides liquidation capabilities for the lending protocol.\n * Liquidation allows liquidators to repay a borrower's debt in exchange for their collateral\n * when the borrower's health factor falls below the liquidation threshold.\n */\n\nimport { AssetIdentifier, CoinObject, EnvOption, TransactionResult } from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { DEFAULT_CACHE_TIME, getConfig } from './config'\nimport { getPool } from './pool'\nimport { getAllFlashLoanAssets } from './flashloan'\nimport { normalizeCoinType, parseTxValue } from './utils'\n\n/**\n * Create a liquidation transaction in the PTB (Programmable Transaction Block)\n *\n * This function allows liquidators to liquidate a borrower's position by repaying\n * their debt in exchange for their collateral. The liquidation process uses flash loans\n * to ensure atomic execution of the liquidation transaction.\n *\n * @param tx - The transaction block to add the liquidation operation to\n * @param payAsset - Asset identifier for the debt being repaid\n * @param payCoinObject - Coin object containing the debt repayment amount\n * @param collateralAsset - Asset identifier for the collateral being liquidated\n * @param liquidateAddress - Address of the borrower being liquidated\n * @param options - Optional environment configuration\n * @returns Tuple containing [collateralBalance, remainDebtBalance] where:\n * - collateralBalance: The collateral received from liquidation\n * - remainDebtBalance: Any remaining debt after liquidation\n * @throws Error if either pay asset or collateral asset does not support flash loans\n */\nexport async function liquidatePTB(\n tx: Transaction,\n payAsset: AssetIdentifier,\n payCoinObject: CoinObject,\n collateralAsset: AssetIdentifier,\n liquidateAddress: string | TransactionResult,\n options?: Partial<EnvOption>\n) {\n const commonOptions = {\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n }\n const config = await getConfig(commonOptions)\n const payPool = await getPool(payAsset, commonOptions)\n const collateralPool = await getPool(collateralAsset, commonOptions)\n\n if (config.version === 1) {\n // Execute the liquidation transaction\n const [collateralBalance, remainDebtBalance] = tx.moveCall({\n target: `${config.package}::incentive_v3::liquidation`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.priceOracle), // Price oracle for asset pricing\n tx.object(config.storage), // Protocol storage\n tx.pure.u8(payPool.id), // Pay asset ID\n tx.object(payPool.contract.pool), // Pay asset pool contract\n parseTxValue(payCoinObject, tx.object), // Debt repayment amount\n tx.pure.u8(collateralPool.id), // Collateral asset ID\n tx.object(collateralPool.contract.pool), // Collateral asset pool contract\n parseTxValue(liquidateAddress, tx.pure.address), // Borrower address\n tx.object(config.incentiveV2), // Incentive V2 contract\n tx.object(config.incentiveV3) // Incentive V3 contract\n ],\n typeArguments: [payPool.suiCoinType, collateralPool.suiCoinType]\n })\n\n return [collateralBalance, remainDebtBalance]\n } else {\n // Execute the liquidation transaction\n const [collateralBalance, remainDebtBalance] = tx.moveCall({\n target: `${config.package}::incentive_v3::liquidation_v2`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.priceOracle), // Price oracle for asset pricing\n tx.object(config.storage), // Protocol storage\n tx.pure.u8(payPool.id), // Pay asset ID\n tx.object(payPool.contract.pool), // Pay asset pool contract\n parseTxValue(payCoinObject, tx.object), // Debt repayment amount\n tx.pure.u8(collateralPool.id), // Collateral asset ID\n tx.object(collateralPool.contract.pool), // Collateral asset pool contract\n parseTxValue(liquidateAddress, tx.pure.address), // Borrower address\n tx.object(config.incentiveV2), // Incentive V2 contract\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object('0x05') // SuiSystemState object\n ],\n typeArguments: [payPool.suiCoinType, collateralPool.suiCoinType]\n })\n\n return [collateralBalance, remainDebtBalance]\n }\n}\n","/**\n * Lending Reward Management for Lending Protocol\n *\n * This module provides comprehensive reward functionality for the lending protocol.\n * It handles reward calculations, claiming, and management for users who participate\n * in lending activities such as supplying assets or borrowing.\n */\n\nimport type {\n SuiClientOption,\n EnvOption,\n LendingRewardSummary,\n LendingReward,\n HistoryClaimedReward,\n LendingClaimedReward,\n TransactionResult,\n AccountCapOption,\n AccountCap\n} from './types'\nimport { Transaction } from '@mysten/sui/transactions'\nimport { getConfig, DEFAULT_CACHE_TIME } from './config'\nimport {\n suiClient,\n camelize,\n parseDevInspectResult,\n normalizeCoinType,\n withSingleton,\n parseTxValue,\n requestHeaders\n} from './utils'\nimport { bcs } from '@mysten/sui/bcs'\nimport { getPriceFeeds } from './oracle'\nimport { getPools, depositCoinPTB } from './pool'\nimport BigNumber from 'bignumber.js'\n\n/**\n * Get user's available lending rewards\n *\n * This function retrieves all available rewards for a user from the lending protocol.\n * It uses devInspect to simulate the reward calculation and returns detailed\n * information about claimable rewards for each asset and reward type.\n *\n * @param address - User's wallet address or account cap\n * @param options - Optional client and environment configuration\n * @returns Array of lending rewards available for claiming\n */\nexport async function getUserAvailableLendingRewards(\n address: string | AccountCap,\n options?: Partial<SuiClientOption & EnvOption>\n): Promise<LendingReward[]> {\n const feeds = await getPriceFeeds(options)\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n const client = options?.client ?? suiClient\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Create transaction to simulate reward calculation\n const tx = new Transaction()\n tx.moveCall({\n target: `${config.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.storage), // Protocol storage\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.pure.address(address) // User address\n ]\n })\n\n // Simulate the transaction to get reward data\n const result = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: address\n })\n\n // Parse the result using BCS schemas\n const rewardsData = parseDevInspectResult<[string[], string[], number[], string[], number[]]>(\n result,\n [\n bcs.vector(bcs.string()), // Asset coin types\n bcs.vector(bcs.string()), // Reward coin types\n bcs.vector(bcs.u8()), // Reward options\n bcs.vector(bcs.Address), // Rule IDs\n bcs.vector(bcs.u256()) // Claimable amounts\n ]\n )\n\n const rewardsList: {\n userClaimableReward: number\n userClaimedReward?: string\n option: number\n ruleIds: string[]\n assetCoinType: string\n rewardCoinType: string\n assetId: number\n }[] = []\n\n // Process the reward data and match with feeds and pools\n if (rewardsData.length === 5 && Array.isArray(rewardsData[0])) {\n const count = rewardsData[0].length\n for (let i = 0; i < count; i++) {\n const feed = feeds.find(\n (feed) => normalizeCoinType(feed.coinType) === normalizeCoinType(rewardsData[1][i])\n )\n const pool = pools.find(\n (pool) => normalizeCoinType(pool.coinType) === normalizeCoinType(rewardsData[0][i])\n )\n if (!feed || !pool) {\n continue\n }\n rewardsList.push({\n assetId: pool.id,\n assetCoinType: normalizeCoinType(rewardsData[0][i]),\n rewardCoinType: normalizeCoinType(rewardsData[1][i]),\n option: Number(rewardsData[2][i]),\n userClaimableReward: Number(rewardsData[4][i]) / Math.pow(10, feed.priceDecimal),\n ruleIds: Array.isArray(rewardsData[3][i]) ? (rewardsData[3][i] as any) : [rewardsData[3][i]]\n })\n }\n }\n return rewardsList\n}\n\n/**\n * Summarize lending rewards by asset and reward type\n *\n * This function aggregates rewards by asset ID and reward type, providing\n * a summary view of all available rewards for easier display and management.\n *\n * @param rewards - Array of lending rewards to summarize\n * @returns Array of summarized reward information grouped by asset and type\n */\nexport function summaryLendingRewards(rewards: LendingReward[]): LendingRewardSummary[] {\n // Aggregate rewards by asset ID, reward type, and coin type\n const agg = new Map<\n string,\n { assetId: number; rewardType: number; coinType: string; total: number }\n >()\n\n rewards.forEach((reward) => {\n const assetId = reward.assetId\n const rewardType = reward.option\n const key = `${assetId}-${rewardType}-${reward.rewardCoinType}`\n if (agg.has(key)) {\n agg.get(key)!.total += reward.userClaimableReward\n } else {\n agg.set(key, {\n assetId,\n rewardType,\n coinType: reward.rewardCoinType,\n total: Number(reward.userClaimableReward)\n })\n }\n })\n\n // Group rewards by asset ID and reward type\n const groupMap = new Map<\n string,\n { assetId: number; rewardType: number; rewards: Map<string, number> }\n >()\n for (const { assetId, rewardType, coinType, total } of agg.values()) {\n const groupKey = `${assetId}-${rewardType}`\n if (!groupMap.has(groupKey)) {\n groupMap.set(groupKey, { assetId, rewardType, rewards: new Map<string, number>() })\n }\n const rewardMap = groupMap.get(groupKey)!\n rewardMap.rewards.set(coinType, (rewardMap.rewards.get(coinType) || 0) + total)\n }\n\n // Convert to summary format\n return Array.from(groupMap.values()).map((group) => ({\n assetId: group.assetId,\n rewardType: group.rewardType,\n rewards: Array.from(group.rewards.entries()).map(([coinType, available]) => ({\n coinType,\n available: available.toFixed(6)\n }))\n }))\n}\n\n/**\n * Get user's total claimed rewards in USD value\n *\n * Fetches the total amount of rewards that a user has claimed historically,\n * converted to USD value for easy comparison and display.\n *\n * @param address - User's wallet address or account cap\n * @returns Object containing total claimed rewards in USD\n */\nexport const getUserTotalClaimedReward = withSingleton(\n async (\n address: string | AccountCap\n ): Promise<{\n USDValue: number\n }> => {\n const url = `https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${address}`\n const res = await fetch(url, { headers: requestHeaders }).then((res) => res.json())\n return res.data\n }\n)\n\n/**\n * Get user's claimed reward history\n *\n * Retrieves a paginated list of all rewards that a user has claimed historically.\n * Useful for tracking reward history and generating reports.\n *\n * @param address - User's wallet address or account cap\n * @param options - Pagination options (page number and size)\n * @returns Object containing claimed reward history and pagination cursor\n */\nexport const getUserClaimedRewardHistory = withSingleton(\n async (\n address: string | AccountCap,\n options?: {\n page?: number\n size?: number\n }\n ): Promise<{\n data: HistoryClaimedReward[]\n cursor?: string\n }> => {\n const endpoint = `https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${address}&page=${options?.page || 1}&pageSize=${options?.size || 400}`\n const res = await fetch(endpoint, { headers: requestHeaders }).then((res) => res.json())\n return camelize({\n data: res.data.rewards\n })\n }\n)\n\n/**\n * Claim lending rewards in the PTB (Programmable Transaction Block)\n *\n * This function adds operations to a transaction block to claim rewards from the lending protocol.\n * It supports different claiming methods including direct claiming, claiming with\n * account capabilities, and custom coin handling (transfer or deposit).\n *\n * @param tx - The transaction block to add reward claiming operations to\n * @param rewards - Array of rewards to claim\n * @param options - Optional configuration including account capabilities and custom coin handling\n * @param options.customCoinReceive.type - The type of custom coin handling, can be 'transfer', 'depositNAVI' or 'skip'\n * @param options.customCoinReceive.transfer - The address to transfer the reward to, only used when options.customCoinReceive.type is 'transfer'\n * @param options.customCoinReceive.depositNAVI.fallbackReceiveAddress - The address to transfer the reward to if the pool is full, only used when options.customCoinReceive.type is 'depositNAVI'\n * @returns Array of claimed reward coins and their identifiers\n * @throws Error if reward fund not found or invalid configuration\n */\nexport async function claimLendingRewardsPTB(\n tx: Transaction,\n rewards: LendingReward[],\n options?: Partial<\n EnvOption &\n AccountCapOption & {\n customCoinReceive?: {\n type: 'transfer' | 'depositNAVI' | 'skip'\n transfer?: string | TransactionResult\n depositNAVI?: {\n fallbackReceiveAddress?: string\n }\n }\n }\n >\n) {\n const config = await getConfig({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n const pools = await getPools({\n ...options,\n cacheTime: DEFAULT_CACHE_TIME\n })\n\n // Group rewards by reward coin type and collect asset IDs and rule IDs\n const rewardMap = new Map<string, { assetIds: string[]; ruleIds: string[]; amount: number }>()\n\n for (const reward of rewards) {\n const { rewardCoinType, ruleIds } = reward\n\n for (const ruleId of ruleIds) {\n if (!rewardMap.has(rewardCoinType)) {\n rewardMap.set(rewardCoinType, { assetIds: [], ruleIds: [], amount: 0 })\n }\n\n const group = rewardMap.get(rewardCoinType)!\n group.assetIds.push(reward.assetCoinType.replace('0x', ''))\n group.ruleIds.push(ruleId)\n group.amount += reward.userClaimableReward\n }\n }\n\n const rewardCoins = [] as LendingClaimedReward[]\n\n // Process each reward coin type\n for (const [rewardCoinType, { assetIds, ruleIds, amount }] of rewardMap) {\n const pool = pools.find(\n (p) => normalizeCoinType(p.suiCoinType) === normalizeCoinType(rewardCoinType)\n )\n if (!pool || !pool.contract.rewardFundId) {\n throw new Error(`No matching rewardFund found for reward coin: ${rewardCoinType}`)\n }\n const matchedRewardFund = pool.contract.rewardFundId\n\n // Validate configuration\n if (options?.accountCap && !options.customCoinReceive) {\n throw new Error('customCoinReceive is required when accountCap is provided')\n }\n\n // Handle custom coin receiving logic\n if (options?.customCoinReceive) {\n let rewardBalance\n\n // Claim rewards with or without account capability\n if (options.accountCap) {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_with_account_cap`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds), // Rule IDs\n parseTxValue(options.accountCap, tx.object) // Account capability\n ],\n typeArguments: [rewardCoinType]\n })\n } else {\n rewardBalance = tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [rewardCoinType]\n })\n }\n\n // Convert balance to coin object\n const [rewardCoin]: any = tx.moveCall({\n target: '0x2::coin::from_balance',\n arguments: [rewardBalance],\n typeArguments: [rewardCoinType]\n })\n\n // Handle different custom coin receiving types\n if (options?.customCoinReceive.type === 'transfer') {\n if (!options.customCoinReceive.transfer) {\n throw new Error('customCoinReceive.transfer is required')\n }\n tx.transferObjects(\n [rewardCoin],\n parseTxValue(options.customCoinReceive.transfer, tx.pure.address)\n )\n }\n if (options?.customCoinReceive.type === 'depositNAVI') {\n const supplyAmount = BigNumber(pool.totalSupplyAmount).shiftedBy(-9)\n const cap = BigNumber(pool.supplyCapCeiling).shiftedBy(-27)\n\n // if the pool is full, transfer the reward to the fallback receive address\n if (\n supplyAmount.plus(amount).isGreaterThan(cap) &&\n !!options?.customCoinReceive.depositNAVI?.fallbackReceiveAddress\n ) {\n tx.transferObjects(\n [rewardCoin],\n tx.pure.address(options.customCoinReceive.depositNAVI.fallbackReceiveAddress)\n )\n } else {\n await depositCoinPTB(tx, pool, rewardCoin, options)\n }\n } else {\n rewardCoins.push({\n coin: rewardCoin,\n identifier: pool\n })\n }\n } else {\n // Standard reward claiming without custom handling\n tx.moveCall({\n target: `${config.package}::incentive_v3::claim_reward_entry`,\n arguments: [\n tx.object('0x06'), // Clock object\n tx.object(config.incentiveV3), // Incentive V3 contract\n tx.object(config.storage), // Protocol storage\n tx.object(matchedRewardFund), // Reward fund\n tx.pure.vector('string', assetIds), // Asset IDs\n tx.pure.vector('address', ruleIds) // Rule IDs\n ],\n typeArguments: [rewardCoinType]\n })\n }\n }\n return rewardCoins\n}\n","/**\n * Account Capability Management for Lending Protocol\n *\n * This module provides functionality to create account capabilities for the lending protocol.\n * Account capabilities are required to interact with lending pools and manage positions.\n */\n\nimport { getConfig } from './config'\nimport type { EnvOption } from './types'\nimport { Transaction } from '@mysten/sui/transactions'\n\n/**\n * Create an account capability transaction in the PTB (Programmable Transaction Block)\n *\n * This function creates a new account capability for the lending protocol.\n * Account capabilities are required to perform lending operations such as\n * borrowing, repaying, and managing collateral positions.\n *\n * @param tx - The transaction block to add the account creation operation to\n * @param options - Optional environment configuration options\n * @returns The transaction call result for creating an account capability\n */\nexport async function createAccountCapPTB(tx: Transaction, options?: Partial<EnvOption>) {\n const config = await getConfig({\n ...options\n })\n return tx.moveCall({\n target: `${config.package}::lending::create_account`,\n arguments: []\n })\n}\n"],"names":["Address","bcs","val","fromHex","toHex","IncentiveAPYInfo","IncentivePoolInfo","IncentivePoolInfoByPhase","OracleInfo","FlashLoanAssetConfig","ReserveDataInfo","UserStateInfo","sdkVersion","packageJson","getNodeInfo","os","nodeVersion","osType","osArch","getUserAgent","environmentInfo","userAgent","suiClient","SuiClient","getFullnodeUrl","argsKey","args","serializergs","option","index","isLast","client","disableCache","cacheTime","rest","withSingleton","fn","promiseMap","key","withCache","cache","options","cacheData","result","camelize","obj","v","camelCase","parseTxValue","value","format","parseTxPoolValue","tx","parseDevInspectResult","data","parseTypes","item","normalizeCoinType","coinType","normalizeStructTag","processContractHealthFactor","hf","healthFactor","SuiPriceServiceConnection","Rate_Decimals","rayMathMulIndex","amount","BigNumber","ray","halfRay","requestHeaders","getConfig","url","res","DEFAULT_CACHE_TIME","PoolOperator","getPools","getPool","identifier","pools","pool","p","getStats","getFees","depositCoinPTB","coinObject","config","isGasCoin","depositAmount","withdrawCoinPTB","withdrawAmount","withdrawBalance","ret","borrowCoinPTB","borrowAmount","borrowBalance","repayCoinPTB","repayAmount","getBorrowFee","_a","Transaction","error","borrowFee","mergeCoinsPTB","coins","needSplit","splitBalance","mergedBalance","mergeList","a","coin","getSimulatedHealthFactorPTB","address","estimatedSupply","estimatedBorrow","isIncrease","getHealthFactorPTB","getLendingState","lendingState","supplyBalance","getHealthFactor","getSimulatedHealthFactor","operations","operation","getTransactions","params","getCoins","cursor","allCoinDatas","suiPythConnection","getPythStalePriceFeedId","priceIds","returnData","latestPriceFeeds","currentTimestamp","priceFeed","uncheckedPrice","updatePythPriceFeeds","priceFeedIds","priceUpdateData","SuiPythClient","updateOraclePricesPTB","priceFeeds","pythPriceFeedIds","feed","stalePriceFeedIds","getPriceFeeds","filterPriceFeeds","feeds","filters","state","getAllFlashLoanAssets","getFlashLoanAsset","asset","flashloanPTB","balance","receipt","repayFlashLoanPTB","liquidatePTB","payAsset","payCoinObject","collateralAsset","liquidateAddress","commonOptions","payPool","collateralPool","collateralBalance","remainDebtBalance","getUserAvailableLendingRewards","rewardsData","rewardsList","count","i","summaryLendingRewards","rewards","agg","reward","assetId","rewardType","groupMap","total","groupKey","rewardMap","group","available","getUserTotalClaimedReward","getUserClaimedRewardHistory","endpoint","claimLendingRewardsPTB","rewardCoinType","ruleIds","ruleId","rewardCoins","assetIds","matchedRewardFund","rewardBalance","rewardCoin","supplyAmount","cap","createAccountCapPTB"],"mappings":"gVAcaA,EAAUC,EAAAA,IAAI,MAAM,EAAE,EAAE,UAAU,CAE7C,MAAQC,GAAgBC,EAAAA,QAAQD,CAAG,EACnC,OAASA,GAAQE,EAAAA,MAAMF,CAAG,CAC5B,CAAC,EAMYG,GAAmBJ,EAAAA,IAAI,OAAO,mBAAoB,CAE7D,SAAUA,EAAAA,IAAI,GAAA,EAEd,IAAKA,EAAAA,IAAI,KAAA,EAET,WAAYA,EAAAA,IAAI,OAAOA,EAAAA,IAAI,QAAQ,CACrC,CA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AAgB,EAAE,UAAU,GAAG,EAIxDqH,EAAa,KAAKnI,CAAM,EAAE,cAAcoI,CAAG,KACzCnG,EAAA1D,GAAA,YAAAA,EAAS,kBAAkB,cAA3B,MAAA0D,EAAwC,wBAE1C/C,EAAG,gBACD,CAACgJ,CAAU,EACXhJ,EAAG,KAAK,QAAQX,EAAQ,kBAAkB,YAAY,sBAAsB,CAAA,EAG9E,MAAM2C,EAAehC,EAAI4B,EAAMoH,EAAY3J,CAAO,CAEtD,MACEuJ,EAAY,KAAK,CACf,KAAMI,EACN,WAAYpH,CAAA,CACb,CAEL,MAEE5B,EAAG,SAAS,CACV,OAAQ,GAAGkC,EAAO,OAAO,qCACzB,UAAW,CACTlC,EAAG,OAAO,MAAM,EAChBA,EAAG,OAAOkC,EAAO,WAAW,EAC5BlC,EAAG,OAAOkC,EAAO,OAAO,EACxBlC,EAAG,OAAO8I,CAAiB,EAC3B9I,EAAG,KAAK,OAAO,SAAU6I,CAAQ,EACjC7I,EAAG,KAAK,OAAO,UAAW0I,CAAO,CAAA,EAEnC,cAAe,CAACD,CAAc,CAAA,CAC/B,CAEL,CACA,OAAOG,CACT,CC3XA,eAAsBO,GAAoBnJ,EAAiBX,EAA8B,CACvF,MAAM6C,EAAS,MAAMf,EAAU,CAC7B,GAAG9B,CAAA,CACJ,EACD,OAAOW,EAAG,SAAS,CACjB,OAAQ,GAAGkC,EAAO,OAAO,4BACzB,UAAW,CAAA,CAAC,CACb,CACH"}
|
package/dist/index.esm.js
CHANGED
|
@@ -129,7 +129,7 @@ const R = i.bytes(32).transform({
|
|
|
129
129
|
borrow_balance: i.u256(),
|
|
130
130
|
/** User's current supply balance */
|
|
131
131
|
supply_balance: i.u256()
|
|
132
|
-
}), ee = "1.3.4
|
|
132
|
+
}), ee = "1.3.4", U = {
|
|
133
133
|
version: ee
|
|
134
134
|
}, te = U.version, re = () => {
|
|
135
135
|
if (typeof process != "undefined" && process.versions && process.versions.node)
|