@naviprotocol/lending 1.3.7 → 1.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/account.d.ts +7 -5
- package/dist/account.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +209 -212
- package/dist/index.esm.js.map +1 -1
- package/package.json +14 -14
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 NAVI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/account.d.ts
CHANGED
|
@@ -24,11 +24,13 @@ export declare function mergeCoinsPTB(tx: Transaction, coins: ({
|
|
|
24
24
|
} & CoinStruct)[], options?: {
|
|
25
25
|
balance?: number;
|
|
26
26
|
useGasCoin?: boolean;
|
|
27
|
-
}):
|
|
28
|
-
$kind: "
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
}): string | ({
|
|
28
|
+
$kind: "Result";
|
|
29
|
+
Result: number;
|
|
30
|
+
} & [{
|
|
31
|
+
$kind: "NestedResult";
|
|
32
|
+
NestedResult: [number, number];
|
|
33
|
+
}]) | {
|
|
32
34
|
$kind: "GasCoin";
|
|
33
35
|
GasCoin: true;
|
|
34
36
|
};
|
package/dist/account.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,SAAS,EAET,WAAW,IAAI,eAAe,EAC9B,eAAe,EACf,iBAAiB,EACjB,WAAW,EACX,UAAU,EACX,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAiBtD,OAAO,EAAE,UAAU,EAAkB,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAqB,YAAY,EAAE,MAAM,QAAQ,CAAA;AAGxD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAC3B,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,CAAC;IACN,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;IACjC,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;CACjB,GAAG,UAAU,CAAC,EAAE,EACjB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB
|
|
1
|
+
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,SAAS,EAET,WAAW,IAAI,eAAe,EAC9B,eAAe,EACf,iBAAiB,EACjB,WAAW,EACX,UAAU,EACX,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAiBtD,OAAO,EAAE,UAAU,EAAkB,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAqB,YAAY,EAAE,MAAM,QAAQ,CAAA;AAGxD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAC3B,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,CAAC;IACN,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;IACjC,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;CACjB,GAAG,UAAU,CAAC,EAAE,EACjB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;;;;;;;;;EA+CF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,2BAA2B,CAC/C,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,iBAAiB,EAChD,UAAU,EAAE,eAAe,EAC3B,eAAe,EAAE,MAAM,GAAG,iBAAiB,EAC3C,eAAe,EAAE,MAAM,GAAG,iBAAiB,EAC3C,UAAU,EAAE,OAAO,GAAG,iBAAiB,EACvC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAqB5B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,iBAAiB,EAChD,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CAE5B;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,YAEf,MAAM,GAAG,UAAU,YAClB,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,WAAW,CAAC,KAC3D,OAAO,CAAC,eAAe,EAAE,CA6D7B,CAAA;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,MAAM,GAAG,UAAU,EAC5B,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,GAC7C,OAAO,CAAC,MAAM,CAAC,CAUjB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,GAAG,UAAU,EAC5B,UAAU,EAAE,eAAe,EAC3B,UAAU,EAAE;IACV,IAAI,EAAE,YAAY,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;CACf,EAAE,EACH,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,GAC7C,OAAO,CAAC,MAAM,CAAC,CA8CjB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,YAEf,MAAM,GAAG,UAAU,YAClB;IACR,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,KACA,OAAO,CAAC;IACT,IAAI,EAAE,eAAe,EAAE,CAAA;IACvB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAaF,CAAA;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,OAAO,CACf;IACE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GAAG,eAAe,CACpB,GACA,OAAO,CAAC,UAAU,EAAE,CAAC,CAoCvB"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),E=require("@mysten/sui/client"),Z=require("lodash.camelcase"),x=require("@mysten/sui/utils"),N=require("@pythnetwork/pyth-sui-js"),_=require("bignumber.js"),h=require("@mysten/sui/bcs"),R=i.bcs.bytes(32).transform({input:e=>i.fromHex(e),output:e=>i.toHex(e)}),ee=i.bcs.struct("IncentiveAPYInfo",{asset_id:i.bcs.u8(),apy:i.bcs.u256(),coin_types:i.bcs.vector(i.bcs.string())}),q=i.bcs.struct("IncentivePoolInfo",{pool_id:R,funds:R,phase:i.bcs.u64(),start_at:i.bcs.u64(),end_at:i.bcs.u64(),closed_at:i.bcs.u64(),total_supply:i.bcs.u64(),asset_id:i.bcs.u8(),option:i.bcs.u8(),factor:i.bcs.u256(),distributed:i.bcs.u64(),available:i.bcs.u256(),total:i.bcs.u256()}),te=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(q)}),ne=i.bcs.struct("OracleInfo",{oracle_id:i.bcs.u8(),price:i.bcs.u256(),decimals:i.bcs.u8(),valid:i.bcs.bool()}),re=i.bcs.struct("FlashLoanAssetConfig",{id:i.bcs.string(),asset_id:i.bcs.u8(),coin_type:i.bcs.string(),pool_id:i.bcs.string(),rate_to_supplier:i.bcs.u64(),rate_to_treasury:i.bcs.u64(),max:i.bcs.u64(),min:i.bcs.u64()}),oe=i.bcs.struct("ReserveDataInfo",{id:i.bcs.u8(),oracle_id:i.bcs.u8(),coin_type:i.bcs.string(),supply_cap:i.bcs.u256(),borrow_cap:i.bcs.u256(),supply_rate:i.bcs.u256(),borrow_rate:i.bcs.u256(),supply_index:i.bcs.u256(),borrow_index:i.bcs.u256(),total_supply:i.bcs.u256(),total_borrow:i.bcs.u256(),last_update_at:i.bcs.u64(),ltv:i.bcs.u256(),treasury_factor:i.bcs.u256(),treasury_balance:i.bcs.u256(),base_rate:i.bcs.u256(),multiplier:i.bcs.u256(),jump_rate_multiplier:i.bcs.u256(),reserve_factor:i.bcs.u256(),optimal_utilization:i.bcs.u256(),liquidation_ratio:i.bcs.u256(),liquidation_bonus:i.bcs.u256(),liquidation_threshold:i.bcs.u256()}),M=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),ce="1.3.7",j={version:ce},ae=j.version,se=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),r=process.version,c=e.type(),t=e.arch();return`Node.js ${r.startsWith("v")?r.substring(1):r}; ${c}/${t}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},ie=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${ae} (${se()})`),e},D=ie(),A=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function H(e){const r=[];return e.forEach((c,t)=>{const n=t===e.length-1;if(typeof c=="object"&&c!==null&&n){const{client:o,disableCache:s,cacheTime:a,...l}=c;r.push(l)}else r.push(c)}),JSON.stringify(r)}function C(e){const r={};return(...c)=>{const t=H(c);return r[t]||(r[t]=e(...c).finally(()=>{delete r[t]})),r[t]}}function I(e){let r={};return(...c)=>{const t=c[c.length-1],n=H(c),o=r[n];return!t?.disableCache&&typeof o?.data<"u"&&(typeof t?.cacheTime>"u"||t.cacheTime>Date.now()-o.cacheAt)?o.data:e(...c).then(s=>(r[n]={data:s,cacheAt:Date.now()},s))}}function F(e){return Array.isArray(e)?e.map(r=>F(r)):e!=null&&typeof e=="object"?Object.keys(e).reduce((r,c)=>({...r,[Z(c)]:F(e[c])}),{}):e}function p(e,r){return typeof e=="object"?e:r(e)}function ue(e,r){return typeof r=="string"?e.object(r):typeof r=="object"&&r.$kind?r:e.object(r.contract.pool)}function k(e,r,c){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((t,n)=>(r[n]||r[0]).parse(Uint8Array.from(t[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function b(e){return x.normalizeStructTag(e)}function O(e){const r=(e||0)/Math.pow(10,27);return r>Math.pow(10,5)?1/0:r}new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const le=27,U=(e,r)=>{if(!Number(e)||!Number(r))return new _(0);const c=new _(1).shiftedBy(1*le),t=c.multipliedBy(new _(.5));return new _(e).multipliedBy(new _(r)).plus(t).dividedBy(c).integerValue(_.ROUND_DOWN)},P=D?{"User-Agent":D}:{},y=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),g=1e3*60*5;var $=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))($||{});const S=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}));async function w(e,r){const c=await S({...r,cacheTime:g});if(typeof e=="object")return e;const t=c.find(n=>typeof e=="string"?b(n.suiCoinType)===b(e):typeof e=="number"?n.id===e:!1);if(!t)throw new Error("Pool not found");return t.isDeprecated&&console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`),t}const pe=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),de=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${j.version}`;return await fetch(r,{headers:P}).then(t=>t.json())}));async function G(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const s=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&s){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let a;return typeof t?.amount<"u"?a=p(t.amount,e.pure.u64):a=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap?e.moveCall({target:`${n.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]}):e.moveCall({target:`${n.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),n.version===2&&o.id===0&&e.moveCall({target:`${n.package}::pool::refresh_stake`,arguments:[e.object(o.contract.pool),e.object("0x05")]}),e}async function be(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),s=p(c,e.pure.u64);let a;if(n.version===1)if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});a=u}else if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[a],typeArguments:[o.suiCoinType]})}async function ge(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const s=p(c,e.pure.u64);let a;if(n.version===1)if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});a=u}else if(t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}else{const[u]=e.moveCall({target:`${n.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),s,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});a=u}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(a)],typeArguments:[o.suiCoinType]})}async function fe(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),s=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&s){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let a;if(typeof t?.amount<"u"?a=p(t.amount,e.pure.u64):a=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[l],typeArguments:[o.suiCoinType]})}else return e.moveCall({target:`${n.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),e}const me=I(C(async e=>{const r=await y({...e});if(e?.address&&typeof e?.asset<"u")try{const n=await w(e.asset,e),o=e?.client??A,s=new B.Transaction;s.moveCall({target:`${r.package}::incentive_v3::get_borrow_fee_v2`,arguments:[s.object(r.incentiveV3),s.pure.address(e.address),s.pure.u8(n.id),s.pure.u64(1e4)],typeArguments:[]});const a=await o.devInspectTransactionBlock({transactionBlock:s,sender:e.address}),l=k(a,[h.bcs.u64()]);return(Number(l[0])||0)/100}catch(n){console.error(n)}const t=(await A.getObject({id:r.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function ye(e,r,c){const t=typeof c?.balance=="number",n=t?c.balance:0;let o=0;const s=[];let a="";if(r.sort((u,f)=>Number(f.balance)-Number(u.balance)).forEach(u=>{if(!(t&&o>=n)&&Number(u.balance)!==0){if(a||(a=u.coinType),a!==u.coinType)throw new Error("All coins must be of the same type");o+=Number(u.balance),s.push(u.coinObjectId)}}),s.length===0)throw new Error("No coins to merge");if(t&&o<n)throw new Error(`Balance is less than the specified balance: ${o} < ${n}`);if(b(a)===b("0x2::sui::SUI")&&c?.useGasCoin)return t?e.splitCoins(e.gas,[e.pure.u64(n)]):e.gas;const l=s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1));return t?e.splitCoins(l,[e.pure.u64(n)]):l}async function L(e,r,c,t,n,o,s){const a=await y({...s,cacheTime:g}),l=await w(c,s);return e.moveCall({target:`${a.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(a.storage),e.object(a.oracle.priceOracle),ue(e,l),p(r,e.pure.address),p(l.id,e.pure.u8),p(t,e.pure.u64),p(n,e.pure.u64),p(o,e.pure.bool)],typeArguments:[l.suiCoinType]})}async function z(e,r,c){return L(e,r,0,0,0,!1,c)}const he=I(async(e,r)=>{const c=await y({...r,cacheTime:g}),t=new B.Transaction,n=r?.client??A,o=await S(r);t.moveCall({target:`${c.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(c.storage),t.pure.address(e)]});const s=await n.devInspectTransactionBlock({transactionBlock:t,sender:e}),a=k(s,[h.bcs.vector(M)]);return F(a[0].filter(u=>u.supply_balance!=="0"||u.borrow_balance!=="0")).map(u=>{const f=o.find(v=>v.id===u.assetId),d=U(u.supplyBalance,f.currentSupplyIndex).toString(),m=U(u.borrowBalance,f.currentBorrowIndex).toString();return{...u,supplyBalance:d,borrowBalance:m,pool:f}}).filter(u=>!!u.pool)});async function we(e,r){const c=r?.client??A,t=new B.Transaction;await z(t,e,r);const n=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=k(n,[h.bcs.u256()]);return O(Number(o[0])||0)}async function ve(e,r,c,t){const n=t?.client??A,o=new B.Transaction;let s=0,a=0;const l=await w(r,t);if(c.forEach(m=>{m.type===$.Supply?s+=m.amount:m.type===$.Withdraw?s-=m.amount:m.type===$.Borrow?a+=m.amount:m.type===$.Repay&&(a-=m.amount)}),s*a<0)throw new Error("Invalid operations");const u=s>0||a>0;await L(o,e,l,Math.abs(s),Math.abs(a),u,t);const f=await n.devInspectTransactionBlock({transactionBlock:o,sender:e}),d=k(f,[h.bcs.u256()]);return O(Number(d[0])||0)}const Ce=C(async(e,r)=>{const c=new URLSearchParams;r?.cursor&&c.set("cursor",r.cursor),c.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${c.toString()}&sdk=${j.version}`;return(await fetch(t,{headers:P}).then(o=>o.json())).data});async function je(e,r){let c=null;const t=[],n=r?.client??A;do{let o;if(r?.coinType?o=await n.getCoins({owner:e,coinType:r?.coinType,cursor:c,limit:100}):o=await n.getAllCoins({owner:e,cursor:c,limit:100}),!o.data||!o.data.length)break;t.push(...o.data),c=o.nextCursor}while(c);return t}const W=new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function J(e){try{const r=[],c=await W.getLatestPriceFeeds(e);if(!c)return r;const t=Math.floor(new Date().valueOf()/1e3);for(const n of c){const o=n.getPriceUnchecked();if(o.publishTime>t){console.warn(`pyth price feed is invalid, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`);continue}t-n.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`),r.push(n.id))}return r}catch(r){throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`)}}async function Y(e,r,c){const t=c?.client??A,n=await y({...c,cacheTime:g});try{const o=await W.getPriceFeedsUpdateData(r);return await new N.SuiPythClient(t,n.oracle.pythStateId,n.oracle.wormholeStateId).updatePriceFeeds(e,o,r)}catch(o){throw new Error(`failed to update pyth price feeds, msg: ${o.message}`)}}async function Te(e,r,c){const t=await y({...c,cacheTime:g});if(c?.updatePythPriceFeeds){const n=r.filter(o=>!!o.pythPriceFeedId).map(o=>o.pythPriceFeedId);try{const o=await J(n);o.length>0&&await Y(e,o,c)}catch{}}for(const n of r)e.moveCall({target:`${t.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(t.oracle.oracleConfig),e.object(t.oracle.priceOracle),e.object(t.oracle.supraOracleHolder),e.object(n.pythPriceInfoObject),e.pure.address(n.feedId)]});return e}async function K(e){return(await y({...e,cacheTime:g})).oracle.feeds}function _e(e,r){return e.filter(c=>!!(r?.lendingState&&r.lendingState.find(n=>n.assetId===c.assetId)||r?.pools&&r.pools.find(n=>n.id===c.assetId)))}const V=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${j.version}`,c=await fetch(r,{headers:P}).then(t=>t.json());return Object.keys(c.data).map(t=>({...c.data[t],coinType:t}))}));async function Ae(e,r){return(await V(r)).find(t=>typeof e=="string"?b(t.coinType)===b(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function Ie(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(!(await V({...t,cacheTime:g})).some(l=>b(l.coinType)===b(o.suiCoinType)))throw new Error("Pool does not support flashloan");if(n.version===1){const[l,u]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64)],typeArguments:[o.suiCoinType]});return[l,u]}else{const[l,u]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64),e.object("0x05")],typeArguments:[o.suiCoinType]});return[l,u]}}async function Pe(e,r,c,t,n){const o=await y({...n,cacheTime:g}),s=await w(r,n);if(!(await V({...n,cacheTime:g})).some(f=>b(f.coinType)===b(s.suiCoinType)))throw new Error("Pool does not support flashloan");const[u]=e.moveCall({target:`${o.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(o.storage),e.object(s.contract.pool),p(c,e.object),p(t,e.object)],typeArguments:[s.suiCoinType]});return[u]}async function $e(e,r,c,t,n,o){const s={...o,cacheTime:g},a=await y(s),l=await w(r,s),u=await w(t,s);if(a.version===1){const[f,d]=e.moveCall({target:`${a.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(a.priceOracle),e.object(a.storage),e.pure.u8(l.id),e.object(l.contract.pool),p(c,e.object),e.pure.u8(u.id),e.object(u.contract.pool),p(n,e.pure.address),e.object(a.incentiveV2),e.object(a.incentiveV3)],typeArguments:[l.suiCoinType,u.suiCoinType]});return[f,d]}else{const[f,d]=e.moveCall({target:`${a.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(a.priceOracle),e.object(a.storage),e.pure.u8(l.id),e.object(l.contract.pool),p(c,e.object),e.pure.u8(u.id),e.object(u.contract.pool),p(n,e.pure.address),e.object(a.incentiveV2),e.object(a.incentiveV3),e.object("0x05")],typeArguments:[l.suiCoinType,u.suiCoinType]});return[f,d]}}async function Be(e,r){const c=await K(r),t=await S({...r,cacheTime:g}),n=r?.client??A,o=await y({...r,cacheTime:g}),s=new B.Transaction;s.moveCall({target:`${o.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[s.object("0x06"),s.object(o.storage),s.object(o.incentiveV3),s.pure.address(e)]});const a=await n.devInspectTransactionBlock({transactionBlock:s,sender:e}),l=k(a,[h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.u8()),h.bcs.vector(h.bcs.Address),h.bcs.vector(h.bcs.u256())]),u=[];if(l.length===5&&Array.isArray(l[0])){const f=l[0].length;for(let d=0;d<f;d++){const m=c.find(T=>b(T.coinType)===b(l[1][d])),v=t.find(T=>b(T.coinType)===b(l[0][d]));!m||!v||u.push({assetId:v.id,assetCoinType:b(l[0][d]),rewardCoinType:b(l[1][d]),option:Number(l[2][d]),userClaimableReward:Number(l[4][d])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(l[3][d])?l[3][d]:[l[3][d]]})}}return u}function ke(e){const r=new Map;e.forEach(t=>{const n=t.assetId,o=t.option,s=`${n}-${o}-${t.rewardCoinType}`;r.has(s)?r.get(s).total+=t.userClaimableReward:r.set(s,{assetId:n,rewardType:o,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const c=new Map;for(const{assetId:t,rewardType:n,coinType:o,total:s}of r.values()){const a=`${t}-${n}`;c.has(a)||c.set(a,{assetId:t,rewardType:n,rewards:new Map});const l=c.get(a);l.rewards.set(o,(l.rewards.get(o)||0)+s)}return Array.from(c.values()).map(t=>({assetId:t.assetId,rewardType:t.rewardType,rewards:Array.from(t.rewards.entries()).map(([n,o])=>({coinType:n,available:o.toFixed(6)}))}))}const Se=C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}),Fe=C(async(e,r)=>{const c=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${r?.page||1}&pageSize=${r?.size||400}&sdk=${j.version}`,t=await fetch(c,{headers:P}).then(n=>n.json());return F({data:t.data.rewards})});async function Ve(e,r,c){const t=await y({...c,cacheTime:g}),n=await S({...c,cacheTime:g}),o=new Map;for(const a of r){const{rewardCoinType:l,ruleIds:u}=a;for(const f of u){o.has(l)||o.set(l,{assetIds:[],ruleIds:[],amount:0});const d=o.get(l);d.assetIds.push(a.assetCoinType.replace("0x","")),d.ruleIds.push(f),d.amount+=a.userClaimableReward}}const s=[];for(const[a,{assetIds:l,ruleIds:u,amount:f}]of o){const d=n.find(v=>b(v.suiCoinType)===b(a));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${a}`);const m=d.contract.rewardFundId;if(c?.accountCap&&!c.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(c?.customCoinReceive){let v;c.accountCap?v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",u),p(c.accountCap,e.object)],typeArguments:[a]}):v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",u)],typeArguments:[a]});const[T]=e.moveCall({target:"0x2::coin::from_balance",arguments:[v],typeArguments:[a]});if(c?.customCoinReceive.type==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([T],p(c.customCoinReceive.transfer,e.pure.address))}if(c?.customCoinReceive.type==="depositNAVI"){const Q=_(d.totalSupplyAmount).shiftedBy(-9),X=_(d.supplyCapCeiling).shiftedBy(-27);Q.plus(f).isGreaterThan(X)&&c?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([T],e.pure.address(c.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await G(e,d,T,c)}else s.push({coin:T,identifier:d})}else e.moveCall({target:`${t.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",l),e.pure.vector("address",u)],typeArguments:[a]})}return s}async function Re(e,r){const c=await y({...r});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=g;exports.FlashLoanAssetConfig=re;exports.IncentiveAPYInfo=ee;exports.IncentivePoolInfo=q;exports.IncentivePoolInfoByPhase=te;exports.OracleInfo=ne;exports.PoolOperator=$;exports.ReserveDataInfo=oe;exports.UserStateInfo=M;exports.borrowCoinPTB=ge;exports.claimLendingRewardsPTB=Ve;exports.createAccountCapPTB=Re;exports.depositCoinPTB=G;exports.filterPriceFeeds=_e;exports.flashloanPTB=Ie;exports.getAllFlashLoanAssets=V;exports.getBorrowFee=me;exports.getCoins=je;exports.getConfig=y;exports.getFees=de;exports.getFlashLoanAsset=Ae;exports.getHealthFactor=we;exports.getHealthFactorPTB=z;exports.getLendingState=he;exports.getPool=w;exports.getPools=S;exports.getPriceFeeds=K;exports.getPythStalePriceFeedId=J;exports.getSimulatedHealthFactor=ve;exports.getSimulatedHealthFactorPTB=L;exports.getStats=pe;exports.getTransactions=Ce;exports.getUserAvailableLendingRewards=Be;exports.getUserClaimedRewardHistory=Fe;exports.getUserTotalClaimedReward=Se;exports.liquidatePTB=$e;exports.mergeCoinsPTB=ye;exports.normalizeCoinType=b;exports.parseTxValue=p;exports.repayCoinPTB=fe;exports.repayFlashLoanPTB=Pe;exports.summaryLendingRewards=ke;exports.updateOraclePricesPTB=Te;exports.updatePythPriceFeeds=Y;exports.withCache=I;exports.withSingleton=C;exports.withdrawCoinPTB=be;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("@mysten/sui/transactions"),i=require("@mysten/bcs"),E=require("@mysten/sui/client"),Z=require("lodash.camelcase"),x=require("@mysten/sui/utils"),N=require("@pythnetwork/pyth-sui-js"),_=require("bignumber.js"),h=require("@mysten/sui/bcs"),R=i.bcs.bytes(32).transform({input:e=>i.fromHex(e),output:e=>i.toHex(e)}),ee=i.bcs.struct("IncentiveAPYInfo",{asset_id:i.bcs.u8(),apy:i.bcs.u256(),coin_types:i.bcs.vector(i.bcs.string())}),q=i.bcs.struct("IncentivePoolInfo",{pool_id:R,funds:R,phase:i.bcs.u64(),start_at:i.bcs.u64(),end_at:i.bcs.u64(),closed_at:i.bcs.u64(),total_supply:i.bcs.u64(),asset_id:i.bcs.u8(),option:i.bcs.u8(),factor:i.bcs.u256(),distributed:i.bcs.u64(),available:i.bcs.u256(),total:i.bcs.u256()}),te=i.bcs.struct("IncentivePoolInfoByPhase",{phase:i.bcs.u64(),pools:i.bcs.vector(q)}),ne=i.bcs.struct("OracleInfo",{oracle_id:i.bcs.u8(),price:i.bcs.u256(),decimals:i.bcs.u8(),valid:i.bcs.bool()}),re=i.bcs.struct("FlashLoanAssetConfig",{id:i.bcs.string(),asset_id:i.bcs.u8(),coin_type:i.bcs.string(),pool_id:i.bcs.string(),rate_to_supplier:i.bcs.u64(),rate_to_treasury:i.bcs.u64(),max:i.bcs.u64(),min:i.bcs.u64()}),oe=i.bcs.struct("ReserveDataInfo",{id:i.bcs.u8(),oracle_id:i.bcs.u8(),coin_type:i.bcs.string(),supply_cap:i.bcs.u256(),borrow_cap:i.bcs.u256(),supply_rate:i.bcs.u256(),borrow_rate:i.bcs.u256(),supply_index:i.bcs.u256(),borrow_index:i.bcs.u256(),total_supply:i.bcs.u256(),total_borrow:i.bcs.u256(),last_update_at:i.bcs.u64(),ltv:i.bcs.u256(),treasury_factor:i.bcs.u256(),treasury_balance:i.bcs.u256(),base_rate:i.bcs.u256(),multiplier:i.bcs.u256(),jump_rate_multiplier:i.bcs.u256(),reserve_factor:i.bcs.u256(),optimal_utilization:i.bcs.u256(),liquidation_ratio:i.bcs.u256(),liquidation_bonus:i.bcs.u256(),liquidation_threshold:i.bcs.u256()}),M=i.bcs.struct("UserStateInfo",{asset_id:i.bcs.u8(),borrow_balance:i.bcs.u256(),supply_balance:i.bcs.u256()}),ce="1.3.8",j={version:ce},ae=j.version,se=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),r=process.version,c=e.type(),t=e.arch();return`Node.js ${r.startsWith("v")?r.substring(1):r}; ${c}/${t}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},ie=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${ae} (${se()})`),e},D=ie(),A=new E.SuiClient({url:E.getFullnodeUrl("mainnet")});function H(e){const r=[];return e.forEach((c,t)=>{const n=t===e.length-1;if(typeof c=="object"&&c!==null&&n){const{client:o,disableCache:a,cacheTime:s,...u}=c;r.push(u)}else r.push(c)}),JSON.stringify(r)}function C(e){const r={};return(...c)=>{const t=H(c);return r[t]||(r[t]=e(...c).finally(()=>{delete r[t]})),r[t]}}function I(e){let r={};return(...c)=>{const t=c[c.length-1],n=H(c),o=r[n];return!t?.disableCache&&typeof o?.data<"u"&&(typeof t?.cacheTime>"u"||t.cacheTime>Date.now()-o.cacheAt)?o.data:e(...c).then(a=>(r[n]={data:a,cacheAt:Date.now()},a))}}function F(e){return Array.isArray(e)?e.map(r=>F(r)):e!=null&&typeof e=="object"?Object.keys(e).reduce((r,c)=>({...r,[Z(c)]:F(e[c])}),{}):e}function p(e,r){return typeof e=="object"?e:r(e)}function ue(e,r){return typeof r=="string"?e.object(r):typeof r=="object"&&r.$kind?r:e.object(r.contract.pool)}function k(e,r,c){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((t,n)=>(r[n]||r[0]).parse(Uint8Array.from(t[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function b(e){return x.normalizeStructTag(e)}function O(e){const r=(e||0)/Math.pow(10,27);return r>Math.pow(10,5)?1/0:r}new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const le=27,U=(e,r)=>{if(!Number(e)||!Number(r))return new _(0);const c=new _(1).shiftedBy(1*le),t=c.multipliedBy(new _(.5));return new _(e).multipliedBy(new _(r)).plus(t).dividedBy(c).integerValue(_.ROUND_DOWN)},P=D?{"User-Agent":D}:{},y=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),g=1e3*60*5;var $=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))($||{});const S=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}));async function w(e,r){const c=await S({...r,cacheTime:g});if(typeof e=="object")return e;const t=c.find(n=>typeof e=="string"?b(n.suiCoinType)===b(e):typeof e=="number"?n.id===e:!1);if(!t)throw new Error("Pool not found");return t.isDeprecated&&console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`),t}const pe=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data})),de=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${j.version}`;return await fetch(r,{headers:P}).then(t=>t.json())}));async function G(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const a=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&a){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let s;return typeof t?.amount<"u"?s=p(t.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap?e.moveCall({target:`${n.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]}):e.moveCall({target:`${n.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),n.version===2&&o.id===0&&e.moveCall({target:`${n.package}::pool::refresh_stake`,arguments:[e.object(o.contract.pool),e.object("0x05")]}),e}async function be(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),a=p(c,e.pure.u64);let s;if(n.version===1)if(t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});s=l}else{const[l]=e.moveCall({target:`${n.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});s=l}else if(t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});s=l}else{const[l]=e.moveCall({target:`${n.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});s=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[s],typeArguments:[o.suiCoinType]})}async function ge(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(o?.deprecatedAt&&Date.now()>o.deprecatedAt)throw new Error(`The lending pool for coinType ${o.suiCoinType} has been deprecated.`);const a=p(c,e.pure.u64);let s;if(n.version===1)if(t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});s=l}else{const[l]=e.moveCall({target:`${n.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]});s=l}else if(t?.accountCap){const[l]=e.moveCall({target:`${n.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object),e.object("0x05")],typeArguments:[o.suiCoinType]});s=l}else{const[l]=e.moveCall({target:`${n.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),a,e.object(n.incentiveV2),e.object(n.incentiveV3),e.object("0x05")],typeArguments:[o.suiCoinType]});s=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(s)],typeArguments:[o.suiCoinType]})}async function fe(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t),a=typeof c=="object"&&c.$kind==="GasCoin";if(b(o.suiCoinType)===b("0x2::sui::SUI")&&a){if(!t?.amount)throw new Error("Amount is required for sui coin");c=e.splitCoins(c,[t.amount])}let s;if(typeof t?.amount<"u"?s=p(t.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[p(c,e.object)],typeArguments:[o.suiCoinType]}),t?.accountCap){const[u]=e.moveCall({target:`${n.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),e.object(n.incentiveV2),e.object(n.incentiveV3),p(t.accountCap,e.object)],typeArguments:[o.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[u],typeArguments:[o.suiCoinType]})}else return e.moveCall({target:`${n.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(n.priceOracle),e.object(n.storage),e.object(o.contract.pool),e.pure.u8(o.id),p(c,e.object),s,e.object(n.incentiveV2),e.object(n.incentiveV3)],typeArguments:[o.suiCoinType]}),e}const me=I(C(async e=>{const r=await y({...e});if(e?.address&&typeof e?.asset<"u")try{const n=await w(e.asset,e),o=e?.client??A,a=new B.Transaction;a.moveCall({target:`${r.package}::incentive_v3::get_borrow_fee_v2`,arguments:[a.object(r.incentiveV3),a.pure.address(e.address),a.pure.u8(n.id),a.pure.u64(1e4)],typeArguments:[]});const s=await o.devInspectTransactionBlock({transactionBlock:a,sender:e.address}),u=k(s,[h.bcs.u64()]);return(Number(u[0])||0)/100}catch(n){console.error(n)}const t=(await A.getObject({id:r.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(t)/100}));function ye(e,r,c){const t=typeof c?.balance=="number",n=t?c.balance:0;let o=0;const a=[];let s="";if(r.sort((u,l)=>Number(l.balance)-Number(u.balance)).forEach(u=>{if(!(t&&o>=n)&&Number(u.balance)!==0){if(s||(s=u.coinType),s!==u.coinType)throw new Error("All coins must be of the same type");o+=Number(u.balance),a.push(u.coinObjectId)}}),a.length===0)throw new Error("No coins to merge");if(t&&o<n)throw new Error(`Balance is less than the specified balance: ${o} < ${n}`);return b(s)===b("0x2::sui::SUI")&&c?.useGasCoin?t?e.splitCoins(e.gas,[e.pure.u64(n)]):e.gas:(a.length===1?e.object(a[0]):e.mergeCoins(a[0],a.slice(1)),t?e.splitCoins(a[0],[e.pure.u64(n)]):a[0])}async function L(e,r,c,t,n,o,a){const s=await y({...a,cacheTime:g}),u=await w(c,a);return e.moveCall({target:`${s.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(s.storage),e.object(s.oracle.priceOracle),ue(e,u),p(r,e.pure.address),p(u.id,e.pure.u8),p(t,e.pure.u64),p(n,e.pure.u64),p(o,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function z(e,r,c){return L(e,r,0,0,0,!1,c)}const he=I(async(e,r)=>{const c=await y({...r,cacheTime:g}),t=new B.Transaction,n=r?.client??A,o=await S(r);t.moveCall({target:`${c.uiGetter}::getter_unchecked::get_user_state`,arguments:[t.object(c.storage),t.pure.address(e)]});const a=await n.devInspectTransactionBlock({transactionBlock:t,sender:e}),s=k(a,[h.bcs.vector(M)]);return F(s[0].filter(l=>l.supply_balance!=="0"||l.borrow_balance!=="0")).map(l=>{const f=o.find(v=>v.id===l.assetId),d=U(l.supplyBalance,f.currentSupplyIndex).toString(),m=U(l.borrowBalance,f.currentBorrowIndex).toString();return{...l,supplyBalance:d,borrowBalance:m,pool:f}}).filter(l=>!!l.pool)});async function we(e,r){const c=r?.client??A,t=new B.Transaction;await z(t,e,r);const n=await c.devInspectTransactionBlock({transactionBlock:t,sender:e}),o=k(n,[h.bcs.u256()]);return O(Number(o[0])||0)}async function ve(e,r,c,t){const n=t?.client??A,o=new B.Transaction;let a=0,s=0;const u=await w(r,t);if(c.forEach(m=>{m.type===$.Supply?a+=m.amount:m.type===$.Withdraw?a-=m.amount:m.type===$.Borrow?s+=m.amount:m.type===$.Repay&&(s-=m.amount)}),a*s<0)throw new Error("Invalid operations");const l=a>0||s>0;await L(o,e,u,Math.abs(a),Math.abs(s),l,t);const f=await n.devInspectTransactionBlock({transactionBlock:o,sender:e}),d=k(f,[h.bcs.u256()]);return O(Number(d[0])||0)}const Ce=C(async(e,r)=>{const c=new URLSearchParams;r?.cursor&&c.set("cursor",r.cursor),c.set("userAddress",e);const t=`https://open-api.naviprotocol.io/api/navi/user/transactions?${c.toString()}&sdk=${j.version}`;return(await fetch(t,{headers:P}).then(o=>o.json())).data});async function je(e,r){let c=null;const t=[],n=r?.client??A;do{let o;if(r?.coinType?o=await n.getCoins({owner:e,coinType:r?.coinType,cursor:c,limit:100}):o=await n.getAllCoins({owner:e,cursor:c,limit:100}),!o.data||!o.data.length)break;t.push(...o.data),c=o.nextCursor}while(c);return t}const W=new N.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function J(e){try{const r=[],c=await W.getLatestPriceFeeds(e);if(!c)return r;const t=Math.floor(new Date().valueOf()/1e3);for(const n of c){const o=n.getPriceUnchecked();if(o.publishTime>t){console.warn(`pyth price feed is invalid, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`);continue}t-n.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${n.id}, publish time: ${o.publishTime}, current timestamp: ${t}`),r.push(n.id))}return r}catch(r){throw new Error(`failed to get pyth stale price feed id, msg: ${r.message}`)}}async function Y(e,r,c){const t=c?.client??A,n=await y({...c,cacheTime:g});try{const o=await W.getPriceFeedsUpdateData(r);return await new N.SuiPythClient(t,n.oracle.pythStateId,n.oracle.wormholeStateId).updatePriceFeeds(e,o,r)}catch(o){throw new Error(`failed to update pyth price feeds, msg: ${o.message}`)}}async function Te(e,r,c){const t=await y({...c,cacheTime:g});if(c?.updatePythPriceFeeds){const n=r.filter(o=>!!o.pythPriceFeedId).map(o=>o.pythPriceFeedId);try{const o=await J(n);o.length>0&&await Y(e,o,c)}catch{}}for(const n of r)e.moveCall({target:`${t.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(t.oracle.oracleConfig),e.object(t.oracle.priceOracle),e.object(t.oracle.supraOracleHolder),e.object(n.pythPriceInfoObject),e.pure.address(n.feedId)]});return e}async function K(e){return(await y({...e,cacheTime:g})).oracle.feeds}function _e(e,r){return e.filter(c=>!!(r?.lendingState&&r.lendingState.find(n=>n.assetId===c.assetId)||r?.pools&&r.pools.find(n=>n.id===c.assetId)))}const V=I(C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${j.version}`,c=await fetch(r,{headers:P}).then(t=>t.json());return Object.keys(c.data).map(t=>({...c.data[t],coinType:t}))}));async function Ae(e,r){return(await V(r)).find(t=>typeof e=="string"?b(t.coinType)===b(e):typeof e=="number"?t.assetId===e:t.assetId===e.id)||null}async function Ie(e,r,c,t){const n=await y({...t,cacheTime:g}),o=await w(r,t);if(!(await V({...t,cacheTime:g})).some(u=>b(u.coinType)===b(o.suiCoinType)))throw new Error("Pool does not support flashloan");if(n.version===1){const[u,l]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64)],typeArguments:[o.suiCoinType]});return[u,l]}else{const[u,l]=e.moveCall({target:`${n.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(n.flashloanConfig),e.object(o.contract.pool),p(c,e.pure.u64),e.object("0x05")],typeArguments:[o.suiCoinType]});return[u,l]}}async function Pe(e,r,c,t,n){const o=await y({...n,cacheTime:g}),a=await w(r,n);if(!(await V({...n,cacheTime:g})).some(f=>b(f.coinType)===b(a.suiCoinType)))throw new Error("Pool does not support flashloan");const[l]=e.moveCall({target:`${o.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(o.storage),e.object(a.contract.pool),p(c,e.object),p(t,e.object)],typeArguments:[a.suiCoinType]});return[l]}async function $e(e,r,c,t,n,o){const a={...o,cacheTime:g},s=await y(a),u=await w(r,a),l=await w(t,a);if(s.version===1){const[f,d]=e.moveCall({target:`${s.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(s.priceOracle),e.object(s.storage),e.pure.u8(u.id),e.object(u.contract.pool),p(c,e.object),e.pure.u8(l.id),e.object(l.contract.pool),p(n,e.pure.address),e.object(s.incentiveV2),e.object(s.incentiveV3)],typeArguments:[u.suiCoinType,l.suiCoinType]});return[f,d]}else{const[f,d]=e.moveCall({target:`${s.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(s.priceOracle),e.object(s.storage),e.pure.u8(u.id),e.object(u.contract.pool),p(c,e.object),e.pure.u8(l.id),e.object(l.contract.pool),p(n,e.pure.address),e.object(s.incentiveV2),e.object(s.incentiveV3),e.object("0x05")],typeArguments:[u.suiCoinType,l.suiCoinType]});return[f,d]}}async function Be(e,r){const c=await K(r),t=await S({...r,cacheTime:g}),n=r?.client??A,o=await y({...r,cacheTime:g}),a=new B.Transaction;a.moveCall({target:`${o.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[a.object("0x06"),a.object(o.storage),a.object(o.incentiveV3),a.pure.address(e)]});const s=await n.devInspectTransactionBlock({transactionBlock:a,sender:e}),u=k(s,[h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.string()),h.bcs.vector(h.bcs.u8()),h.bcs.vector(h.bcs.Address),h.bcs.vector(h.bcs.u256())]),l=[];if(u.length===5&&Array.isArray(u[0])){const f=u[0].length;for(let d=0;d<f;d++){const m=c.find(T=>b(T.coinType)===b(u[1][d])),v=t.find(T=>b(T.coinType)===b(u[0][d]));!m||!v||l.push({assetId:v.id,assetCoinType:b(u[0][d]),rewardCoinType:b(u[1][d]),option:Number(u[2][d]),userClaimableReward:Number(u[4][d])/Math.pow(10,m.priceDecimal),ruleIds:Array.isArray(u[3][d])?u[3][d]:[u[3][d]]})}}return l}function ke(e){const r=new Map;e.forEach(t=>{const n=t.assetId,o=t.option,a=`${n}-${o}-${t.rewardCoinType}`;r.has(a)?r.get(a).total+=t.userClaimableReward:r.set(a,{assetId:n,rewardType:o,coinType:t.rewardCoinType,total:Number(t.userClaimableReward)})});const c=new Map;for(const{assetId:t,rewardType:n,coinType:o,total:a}of r.values()){const s=`${t}-${n}`;c.has(s)||c.set(s,{assetId:t,rewardType:n,rewards:new Map});const u=c.get(s);u.rewards.set(o,(u.rewards.get(o)||0)+a)}return Array.from(c.values()).map(t=>({assetId:t.assetId,rewardType:t.rewardType,rewards:Array.from(t.rewards.entries()).map(([n,o])=>({coinType:n,available:o.toFixed(6)}))}))}const Se=C(async e=>{const r=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${j.version}`;return(await fetch(r,{headers:P}).then(t=>t.json())).data}),Fe=C(async(e,r)=>{const c=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${r?.page||1}&pageSize=${r?.size||400}&sdk=${j.version}`,t=await fetch(c,{headers:P}).then(n=>n.json());return F({data:t.data.rewards})});async function Ve(e,r,c){const t=await y({...c,cacheTime:g}),n=await S({...c,cacheTime:g}),o=new Map;for(const s of r){const{rewardCoinType:u,ruleIds:l}=s;for(const f of l){o.has(u)||o.set(u,{assetIds:[],ruleIds:[],amount:0});const d=o.get(u);d.assetIds.push(s.assetCoinType.replace("0x","")),d.ruleIds.push(f),d.amount+=s.userClaimableReward}}const a=[];for(const[s,{assetIds:u,ruleIds:l,amount:f}]of o){const d=n.find(v=>b(v.suiCoinType)===b(s));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${s}`);const m=d.contract.rewardFundId;if(c?.accountCap&&!c.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(c?.customCoinReceive){let v;c.accountCap?v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",u),e.pure.vector("address",l),p(c.accountCap,e.object)],typeArguments:[s]}):v=e.moveCall({target:`${t.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[s]});const[T]=e.moveCall({target:"0x2::coin::from_balance",arguments:[v],typeArguments:[s]});if(c?.customCoinReceive.type==="transfer"){if(!c.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([T],p(c.customCoinReceive.transfer,e.pure.address))}if(c?.customCoinReceive.type==="depositNAVI"){const Q=_(d.totalSupplyAmount).shiftedBy(-9),X=_(d.supplyCapCeiling).shiftedBy(-27);Q.plus(f).isGreaterThan(X)&&c?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([T],e.pure.address(c.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await G(e,d,T,c)}else a.push({coin:T,identifier:d})}else e.moveCall({target:`${t.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(t.incentiveV3),e.object(t.storage),e.object(m),e.pure.vector("string",u),e.pure.vector("address",l)],typeArguments:[s]})}return a}async function Re(e,r){const c=await y({...r});return e.moveCall({target:`${c.package}::lending::create_account`,arguments:[]})}exports.Address=R;exports.DEFAULT_CACHE_TIME=g;exports.FlashLoanAssetConfig=re;exports.IncentiveAPYInfo=ee;exports.IncentivePoolInfo=q;exports.IncentivePoolInfoByPhase=te;exports.OracleInfo=ne;exports.PoolOperator=$;exports.ReserveDataInfo=oe;exports.UserStateInfo=M;exports.borrowCoinPTB=ge;exports.claimLendingRewardsPTB=Ve;exports.createAccountCapPTB=Re;exports.depositCoinPTB=G;exports.filterPriceFeeds=_e;exports.flashloanPTB=Ie;exports.getAllFlashLoanAssets=V;exports.getBorrowFee=me;exports.getCoins=je;exports.getConfig=y;exports.getFees=de;exports.getFlashLoanAsset=Ae;exports.getHealthFactor=we;exports.getHealthFactorPTB=z;exports.getLendingState=he;exports.getPool=w;exports.getPools=S;exports.getPriceFeeds=K;exports.getPythStalePriceFeedId=J;exports.getSimulatedHealthFactor=ve;exports.getSimulatedHealthFactorPTB=L;exports.getStats=pe;exports.getTransactions=Ce;exports.getUserAvailableLendingRewards=Be;exports.getUserClaimedRewardHistory=Fe;exports.getUserTotalClaimedReward=Se;exports.liquidatePTB=$e;exports.mergeCoinsPTB=ye;exports.normalizeCoinType=b;exports.parseTxValue=p;exports.repayCoinPTB=fe;exports.repayFlashLoanPTB=Pe;exports.summaryLendingRewards=ke;exports.updateOraclePricesPTB=Te;exports.updatePythPriceFeeds=Y;exports.withCache=I;exports.withSingleton=C;exports.withdrawCoinPTB=be;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|