@naviprotocol/lending 1.4.0-emode.3 → 1.4.0-emode.30
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/account.d.ts +42 -3
- package/dist/account.d.ts.map +1 -1
- package/dist/emode.d.ts +2 -1
- package/dist/emode.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 +1426 -908
- package/dist/index.esm.js.map +1 -1
- package/dist/market.d.ts +18 -3
- package/dist/market.d.ts.map +1 -1
- package/dist/oracle.d.ts +22 -3
- package/dist/oracle.d.ts.map +1 -1
- package/dist/pool.d.ts +2 -2
- package/dist/pool.d.ts.map +1 -1
- package/dist/reward.d.ts +2 -2
- package/dist/reward.d.ts.map +1 -1
- package/dist/types.d.ts +52 -11
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +4 -13
- package/dist/utils.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/account.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UserLendingInfo, SuiClientOption, EnvOption, Transaction as NAVITransaction, AssetIdentifier, TransactionResult, CacheOption, AccountCap, MarketOption, LendingPosition } from './types';
|
|
1
|
+
import { UserLendingInfo, SuiClientOption, EnvOption, Pool, Transaction as NAVITransaction, AssetIdentifier, TransactionResult, CacheOption, AccountCap, MarketOption, LendingPosition, MarketsOption, EModePool } from './types';
|
|
2
2
|
import { Transaction } from '@mysten/sui/transactions';
|
|
3
3
|
import { CoinStruct } from '@mysten/sui/client';
|
|
4
4
|
import { PoolOperator } from './pool';
|
|
@@ -69,7 +69,7 @@ export declare function getHealthFactorPTB(tx: Transaction, address: string | Ac
|
|
|
69
69
|
* @param options - Options for client, environment, and caching
|
|
70
70
|
* @returns Promise<UserLendingInfo[]> - Array of user lending positions
|
|
71
71
|
*/
|
|
72
|
-
export declare const getLendingState: (address: string | AccountCap, options?: Partial<SuiClientOption & EnvOption & CacheOption &
|
|
72
|
+
export declare const getLendingState: (address: string | AccountCap, options?: Partial<SuiClientOption & EnvOption & CacheOption & MarketsOption>) => Promise<UserLendingInfo[]>;
|
|
73
73
|
/**
|
|
74
74
|
* Calculates the current health factor for a user
|
|
75
75
|
*
|
|
@@ -125,5 +125,44 @@ export declare const getTransactions: (address: string | AccountCap, options?: {
|
|
|
125
125
|
export declare function getCoins(address: string, options?: Partial<{
|
|
126
126
|
coinType?: string;
|
|
127
127
|
} & SuiClientOption>): Promise<CoinStruct[]>;
|
|
128
|
-
export declare const getLendingPositions: (address: string
|
|
128
|
+
export declare const getLendingPositions: (address: string, options?: Partial<SuiClientOption & EnvOption & CacheOption & MarketsOption>) => Promise<LendingPosition[]>;
|
|
129
|
+
export declare class UserPositions {
|
|
130
|
+
private _positions;
|
|
131
|
+
private _overview;
|
|
132
|
+
get positions(): LendingPosition[];
|
|
133
|
+
get overview(): {
|
|
134
|
+
hf: number;
|
|
135
|
+
netVaule: string;
|
|
136
|
+
netWorthApr: string;
|
|
137
|
+
totalSupplyValue: string;
|
|
138
|
+
totalBorrowValue: string;
|
|
139
|
+
totalsupplyApy: string;
|
|
140
|
+
totalBorrowApy: string;
|
|
141
|
+
maxLiquidationValue: string;
|
|
142
|
+
maxLoanToVaule: string;
|
|
143
|
+
supply: Record<string, string>;
|
|
144
|
+
borrow: Record<string, string>;
|
|
145
|
+
};
|
|
146
|
+
set positions(positions: LendingPosition[]);
|
|
147
|
+
constructor(positions: LendingPosition[]);
|
|
148
|
+
filterPositionsByPool(pool: Pool | EModePool): UserPositions;
|
|
149
|
+
deposit(pool: Pool | EModePool, amount: number): UserPositions;
|
|
150
|
+
withdraw(pool: Pool | EModePool, amount: number): UserPositions;
|
|
151
|
+
borrow(pool: Pool | EModePool, amount: number): UserPositions;
|
|
152
|
+
repay(pool: Pool | EModePool, amount: number): UserPositions;
|
|
153
|
+
getPositionsOverview(positions: LendingPosition[]): {
|
|
154
|
+
hf: number;
|
|
155
|
+
netVaule: string;
|
|
156
|
+
netWorthApr: string;
|
|
157
|
+
totalSupplyValue: string;
|
|
158
|
+
totalBorrowValue: string;
|
|
159
|
+
totalsupplyApy: string;
|
|
160
|
+
totalBorrowApy: string;
|
|
161
|
+
maxLiquidationValue: string;
|
|
162
|
+
maxLoanToVaule: string;
|
|
163
|
+
supply: Record<string, string>;
|
|
164
|
+
borrow: Record<string, string>;
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
export declare function verifyHealthFactorPTB(tx: Transaction, address: string | AccountCap | TransactionResult, hf: number, options?: Partial<EnvOption>): Promise<void>;
|
|
129
168
|
//# sourceMappingURL=account.d.ts.map
|
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,
|
|
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,EACT,IAAI,EACJ,WAAW,IAAI,eAAe,EAC9B,eAAe,EACf,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,YAAY,EACZ,eAAe,EACf,aAAa,EACb,SAAS,EAEV,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAoBtD,OAAO,EAAE,UAAU,EAAkB,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAW,YAAY,EAAY,MAAM,QAAQ,CAAA;AAMxD;;;;;;;;;;;;;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,GAAG,YAAY,CAAC,GAC1C,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;AAkFD;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,YAEf,MAAM,GAAG,UAAU,YAClB,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,CAAC,KAC3E,OAAO,CAAC,eAAe,EAAE,CAc7B,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;AAED,eAAO,MAAM,mBAAmB,YAEnB,MAAM,YACL,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,CAAC,KAC3E,OAAO,CAAC,eAAe,EAAE,CAoI7B,CAAA;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,UAAU,CAAwB;IAC1C,OAAO,CAAC,SAAS,CAYhB;IAED,IAAI,SAAS,IAQY,eAAe,EAAE,CANzC;IAED,IAAI,QAAQ;;;;;;;;;;gBARI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;gBACtB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;MASrC;IAED,IAAI,SAAS,CAAC,SAAS,EAAE,eAAe,EAAE,EAGzC;gBAEW,SAAS,EAAE,eAAe,EAAE;IAIjC,qBAAqB,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS;IAa5C,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM;IAoC9C,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM;IAoC/C,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM;IAoC7C,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM;IAoCnD,oBAAoB,CAAC,SAAS,EAAE,eAAe,EAAE;;;;;;;;;;;;;CAyHlD;AAED,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,iBAAiB,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,iBAiBtJ"}
|
package/dist/emode.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { CacheOption, EnvOption, EModeCap, AccountCapOption, MarketOption, TransactionResult, SuiClientOption } from './types';
|
|
1
|
+
import { CacheOption, EnvOption, EModeCap, AccountCapOption, MarketOption, TransactionResult, SuiClientOption, EModeIdentity } from './types';
|
|
2
2
|
import { Transaction } from '@mysten/sui/transactions';
|
|
3
3
|
|
|
4
4
|
export declare function enterEModePTB(tx: Transaction, emodeId: number | TransactionResult, options?: Partial<EnvOption & AccountCapOption & MarketOption>): Promise<Transaction>;
|
|
5
5
|
export declare function exitEModePTB(tx: Transaction, options?: Partial<EnvOption & AccountCapOption & MarketOption>): Promise<Transaction>;
|
|
6
6
|
export declare function createEModeCapPTB(tx: Transaction, emodeId: number | TransactionResult, options?: Partial<EnvOption & MarketOption>): Promise<import('@mysten/sui/dist/cjs/transactions').TransactionResult>;
|
|
7
7
|
export declare const getUserEModeCaps: (address: string, options?: Partial<SuiClientOption & EnvOption & CacheOption>) => Promise<EModeCap[]>;
|
|
8
|
+
export declare function emodeIdentityId(identifier: EModeIdentity): string;
|
|
8
9
|
//# sourceMappingURL=emode.d.ts.map
|
package/dist/emode.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emode.d.ts","sourceRoot":"","sources":["../src/emode.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,eAAe,
|
|
1
|
+
{"version":3,"file":"emode.d.ts","sourceRoot":"","sources":["../src/emode.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,aAAa,EACd,MAAM,SAAS,CAAA;AAIhB,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAItD,wBAAsB,aAAa,CACjC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,iBAAiB,EACnC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,GAAG,gBAAgB,GAAG,YAAY,CAAC,GAC7D,OAAO,CAAC,WAAW,CAAC,CAsBtB;AAED,wBAAsB,YAAY,CAChC,EAAE,EAAE,WAAW,EACf,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,GAAG,gBAAgB,GAAG,YAAY,CAAC,GAC7D,OAAO,CAAC,WAAW,CAAC,CAiBtB;AAED,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,MAAM,GAAG,iBAAiB,EACnC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,GAAG,YAAY,CAAC,0EAuB5C;AAED,eAAO,MAAM,gBAAgB,YAGd,MAAM,YACL,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,WAAW,CAAC,KAC3D,OAAO,CAAC,QAAQ,EAAE,CA+BxB,CAAA;AAED,wBAAgB,eAAe,CAAC,UAAU,EAAE,aAAa,UAGxD"}
|
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"),l=require("@mysten/bcs"),L=require("@mysten/sui/client"),pe=require("lodash.camelcase"),de=require("@mysten/sui/utils"),S=require("@pythnetwork/pyth-sui-js"),h=require("bignumber.js"),y=require("@mysten/sui/bcs"),D=l.bcs.bytes(32).transform({input:e=>l.fromHex(e),output:e=>l.toHex(e)}),me=l.bcs.struct("IncentiveAPYInfo",{asset_id:l.bcs.u8(),apy:l.bcs.u256(),coin_types:l.bcs.vector(l.bcs.string())}),W=l.bcs.struct("IncentivePoolInfo",{pool_id:D,funds:D,phase:l.bcs.u64(),start_at:l.bcs.u64(),end_at:l.bcs.u64(),closed_at:l.bcs.u64(),total_supply:l.bcs.u64(),asset_id:l.bcs.u8(),option:l.bcs.u8(),factor:l.bcs.u256(),distributed:l.bcs.u64(),available:l.bcs.u256(),total:l.bcs.u256()}),ge=l.bcs.struct("IncentivePoolInfoByPhase",{phase:l.bcs.u64(),pools:l.bcs.vector(W)}),fe=l.bcs.struct("OracleInfo",{oracle_id:l.bcs.u8(),price:l.bcs.u256(),decimals:l.bcs.u8(),valid:l.bcs.bool()}),be=l.bcs.struct("FlashLoanAssetConfig",{id:l.bcs.string(),asset_id:l.bcs.u8(),coin_type:l.bcs.string(),pool_id:l.bcs.string(),rate_to_supplier:l.bcs.u64(),rate_to_treasury:l.bcs.u64(),max:l.bcs.u64(),min:l.bcs.u64()}),he=l.bcs.struct("ReserveDataInfo",{id:l.bcs.u8(),oracle_id:l.bcs.u8(),coin_type:l.bcs.string(),supply_cap:l.bcs.u256(),borrow_cap:l.bcs.u256(),supply_rate:l.bcs.u256(),borrow_rate:l.bcs.u256(),supply_index:l.bcs.u256(),borrow_index:l.bcs.u256(),total_supply:l.bcs.u256(),total_borrow:l.bcs.u256(),last_update_at:l.bcs.u64(),ltv:l.bcs.u256(),treasury_factor:l.bcs.u256(),treasury_balance:l.bcs.u256(),base_rate:l.bcs.u256(),multiplier:l.bcs.u256(),jump_rate_multiplier:l.bcs.u256(),reserve_factor:l.bcs.u256(),optimal_utilization:l.bcs.u256(),liquidation_ratio:l.bcs.u256(),liquidation_bonus:l.bcs.u256(),liquidation_threshold:l.bcs.u256()}),z=l.bcs.struct("UserStateInfo",{asset_id:l.bcs.u8(),borrow_balance:l.bcs.u256(),supply_balance:l.bcs.u256()}),ye="1.4.0-emode.3",k={version:ye},we=k.version,ve=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),t=process.version,o=e.type(),n=e.arch();return`Node.js ${t.startsWith("v")?t.substring(1):t}; ${o}/${n}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},Ce=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${we} (${ve()})`),e},O=Ce(),j=new L.SuiClient({url:L.getFullnodeUrl("mainnet")});function K(e){const t=[];return e.forEach((o,n)=>{const r=n===e.length-1;if(typeof o=="object"&&o!==null&&r){const{client:c,disableCache:a,cacheTime:s,...u}=o;t.push(u)}else t.push(o)}),JSON.stringify(t)}function v(e){const t={};return(...o)=>{const n=K(o);return t[n]||(t[n]=e(...o).finally(()=>{delete t[n]})),t[n]}}function T(e){let t={};return(...o)=>{const n=o[o.length-1],r=K(o),c=t[r];return!n?.disableCache&&typeof c?.data<"u"&&(typeof n?.cacheTime>"u"||n.cacheTime>Date.now()-c.cacheAt)?c.data:e(...o).then(a=>(t[r]={data:a,cacheAt:Date.now()},a))}}function V(e){return Array.isArray(e)?e.map(t=>V(t)):e!=null&&typeof e=="object"?Object.keys(e).reduce((t,o)=>({...t,[pe(o)]:V(e[o])}),{}):e}function p(e,t){return typeof e=="object"?e:t(e)}function Te(e,t){return typeof t=="string"?e.object(t):typeof t=="object"&&t.$kind?t:e.object(t.contract.pool)}function E(e,t,o){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((n,r)=>(t[r]||t[0]).parse(Uint8Array.from(n[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function f(e){return de.normalizeStructTag(e)}function Y(e){const t=(e||0)/Math.pow(10,27);return t>Math.pow(10,5)?1/0:t}new S.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const _e=27,q=(e,t)=>{if(!Number(e)||!Number(t))return new h(0);const o=new h(1).shiftedBy(1*_e),n=o.multipliedBy(new h(.5));return new h(e).multipliedBy(new h(t)).plus(n).dividedBy(o).integerValue(h.ROUND_DOWN)},I=O?{"User-Agent":O}:{};function je(e){return e.reduce((t,o)=>(t[o.id]=o,t),{})}function H(e){return e.reduce((t,o)=>(t[o.emodeId]=o,t),{})}function G(e,t){const o=e.emodes.find(n=>n.emodeId===t.emodeId);if(!o)throw new Error("EMode not found in pool");return{...e,emode:o,isEMode:!0}}function J(e){const[t,o]=e.split("-");return!t||!o?null:{marketKey:t,poolId:parseInt(o)}}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 M=T(v(async e=>{const t=F(e?.market||P),o=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${k.version}&market=${t?.key||P}`,n=await fetch(o,{headers:I}).then(r=>r.json());return n.data.forEach(r=>{const c=n.meta.emodes.filter(a=>!!a.assets.find(s=>s.assetId===r.id)&&a.isActive);r.emodes=c}),n.data}));async function C(e,t){let o=t?.market;if(typeof e=="string"){const c=J(e);c&&(o=c.marketKey,e=c.poolId)}const n=await M({...t,market:o,cacheTime:m});if(typeof e=="object")return e;const r=n.find(c=>typeof e=="string"?f(c.suiCoinType)===f(e):typeof e=="number"?c.id===e:!1);if(!r)throw new Error("Pool not found");return r.isDeprecated&&console.log(`The lending pool for coinType ${r.suiCoinType} is going to be deprecated.`),r}const ke=T(v(async e=>{const t=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${k.version}`;return(await fetch(t,{headers:I}).then(n=>n.json())).data})),Ae=T(v(async e=>{const t=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${k.version}`;return await fetch(t,{headers:I}).then(n=>n.json())}));async function Q(e,t,o,n){const r=await b({...n,cacheTime:m}),c=await C(t,n);if(c?.deprecatedAt&&Date.now()>c.deprecatedAt)throw new Error(`The lending pool for coinType ${c.suiCoinType} has been deprecated.`);const a=typeof o=="object"&&o.$kind==="GasCoin";if(f(c.suiCoinType)===f("0x2::sui::SUI")&&a){if(!n?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[n.amount])}let s;return typeof n?.amount<"u"?s=p(n.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[p(o,e.object)],typeArguments:[c.suiCoinType]}),n?.accountCap?e.moveCall({target:`${r.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),p(o,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object)],typeArguments:[c.suiCoinType]}):e.moveCall({target:`${r.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),p(o,e.object),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[c.suiCoinType]}),r.version===2&&c.id===0&&e.moveCall({target:`${r.package}::pool::refresh_stake`,arguments:[e.object(c.contract.pool),e.object("0x05")]}),e}async function Pe(e,t,o,n){const r=await b({...n,cacheTime:m}),c=await C(t,n),a=p(o,e.pure.u64);let s;if(r.version===1)if(n?.accountCap){const[i]=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(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object)],typeArguments:[c.suiCoinType]});s=i}else{const[i]=e.moveCall({target:`${r.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[c.suiCoinType]});s=i}else if(n?.accountCap){const[i]=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(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object),e.object("0x05")],typeArguments:[c.suiCoinType]});s=i}else{const[i]=e.moveCall({target:`${r.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),e.object("0x05")],typeArguments:[c.suiCoinType]});s=i}return e.moveCall({target:"0x2::coin::from_balance",arguments:[s],typeArguments:[c.suiCoinType]})}async function Ie(e,t,o,n){const r=await b({...n,cacheTime:m}),c=await C(t,n);if(c?.deprecatedAt&&Date.now()>c.deprecatedAt)throw new Error(`The lending pool for coinType ${c.suiCoinType} has been deprecated.`);const a=p(o,e.pure.u64);let s;if(r.version===1)if(n?.accountCap){const[i]=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(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object)],typeArguments:[c.suiCoinType]});s=i}else{const[i]=e.moveCall({target:`${r.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[c.suiCoinType]});s=i}else if(n?.accountCap){const[i]=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(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object),e.object("0x05")],typeArguments:[c.suiCoinType]});s=i}else{const[i]=e.moveCall({target:`${r.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(r.priceOracle),e.object(r.storage),e.object(c.contract.pool),e.pure.u8(c.id),a,e.object(r.incentiveV2),e.object(r.incentiveV3),e.object("0x05")],typeArguments:[c.suiCoinType]});s=i}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(s)],typeArguments:[c.suiCoinType]})}async function Be(e,t,o,n){const r=await b({...n,cacheTime:m}),c=await C(t,n),a=typeof o=="object"&&o.$kind==="GasCoin";if(f(c.suiCoinType)===f("0x2::sui::SUI")&&a){if(!n?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[n.amount])}let s;if(typeof n?.amount<"u"?s=p(n.amount,e.pure.u64):s=e.moveCall({target:"0x2::coin::value",arguments:[p(o,e.object)],typeArguments:[c.suiCoinType]}),n?.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(c.contract.pool),e.pure.u8(c.id),p(o,e.object),e.object(r.incentiveV2),e.object(r.incentiveV3),p(n.accountCap,e.object)],typeArguments:[c.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[u],typeArguments:[c.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(c.contract.pool),e.pure.u8(c.id),p(o,e.object),s,e.object(r.incentiveV2),e.object(r.incentiveV3)],typeArguments:[c.suiCoinType]}),e}const $e=T(v(async e=>{const t=await b({...e});if(e?.address&&typeof e?.asset<"u")try{const r=await C(e.asset,e),c=e?.client??j,a=new $.Transaction;a.moveCall({target:`${t.package}::incentive_v3::get_borrow_fee_v2`,arguments:[a.object(t.incentiveV3),a.pure.address(e.address),a.pure.u8(r.id),a.pure.u64(1e4)],typeArguments:[]});const s=await c.devInspectTransactionBlock({transactionBlock:a,sender:e.address}),u=E(s,[y.bcs.u64()]);return(Number(u[0])||0)/100}catch(r){console.error(r)}const n=(await j.getObject({id:t.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(n)/100})),P="main",X={main:{id:0,key:"main",name:"Main Market"}};class Z{constructor(t,o){this.pools=[],this.emodes=[],this.config=F(t),this.addPools(o)}addPools(t){const o=je(this.pools),n=H(this.emodes);t.forEach(r=>{if(!this.checkMarket(r.market)){console.warn(`Pool is not in market ${this.config.name}`,r);return}o[r.id]||this.pools.push(r),r.emodes.forEach(a=>{n[a.emodeId]||this.emodes.push(a)})})}getEMode(t){if(!this.checkMarket(t.marketId))return console.warn(`EMode market mismatch ${this.config.id} !== ${t.marketId}`,t),null;const r=H(this.emodes)[t.emodeId];return r||(console.warn(`EMode not found ${t.emodeId} in market ${this.config.name}`,t),null)}getEModePools(t){const o=this.getEMode(t);if(!o)return[];const n=o.assets.map(c=>c.assetId);return this.pools.filter(c=>n.includes(c.id)).map(c=>({...c,emode:o,isEMode:!0}))}checkMarket(t){let o=!1;return typeof t=="number"&&t===this.config.id&&(o=!0),typeof t=="string"&&t===this.config.key&&(o=!0),typeof t=="object"&&t.id===this.config.id&&(o=!0),o}}const F=e=>{const o=Object.values(X).find(n=>typeof e=="number"?n.id===e:typeof e=="string"?n.key===e:n.id===e.id);if(!o)throw new Error("Market not found");return o},x=T(v(async(e,t)=>(await Promise.all(e.map(n=>M({cacheTime:6e4,...t,market:n})))).map(n=>{const r=n[0].market;return new Z(r,n)}))),Me=T(v(async(e,t)=>(await x([e],t))[0])),b=T(v(async e=>{const t=F(e?.market||P),o=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${k.version}&market=${t.key}`;return(await fetch(o,{headers:I}).then(r=>r.json())).data})),m=1e3*60*5;async function ee(e,t){const o=await b({cacheTime:m,...t});return e.moveCall({target:`${o.package}::lending::create_account`,arguments:[]})}async function te(e,t,o){const n=await b({cacheTime:m,...o});return e.moveCall({target:`${n.package}::lending_core::account_owner`,arguments:[t]})}async function oe(e,t,o){const n=await b({...o,cacheTime:m});return o?.accountCap?e.moveCall({target:`${n.package}::lending::enter_emode_with_account_cap`,arguments:[e.object(n.storage),p(t,e.pure.u64),p(o.accountCap,e.object)]}):e.moveCall({target:`${n.package}::lending::enter_emode`,arguments:[e.object(n.storage),p(t,e.pure.u64)]}),e}async function Ee(e,t){const o=await b({...t,cacheTime:m});return t?.accountCap?e.moveCall({target:`${o.package}::lending::exit_emode_with_account_cap`,arguments:[e.object(o.storage),p(t.accountCap,e.object)]}):e.moveCall({target:`${o.package}::lending::exit_emode`,arguments:[e.object(o.storage)]}),e}async function Fe(e,t,o){const n=await b({cacheTime:m,...o}),r=await ee(e,o);await oe(e,t,{...o,accountCap:r});const c=await F(o?.market||P),a=await te(e,r,o);return e.moveCall({target:`${n.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,arguments:[e.object(n.emode.contract.registryObject),a,p(c.id,e.pure.u64),p(t,e.pure.u64)]}),r}const ne=T(v(async(e,t)=>{const o=await b({cacheTime:m,...t}),n=new $.Transaction,r=t?.client??j;n.moveCall({target:`${o.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,arguments:[n.object(o.emode.contract.registryObject),n.pure.address(e)]});const a=(await r.devInspectTransactionBlock({transactionBlock:n,sender:e})).results[0].returnValues,s=y.bcs.vector(y.bcs.u64()).parse(Uint8Array.from(a[0][0])),u=y.bcs.vector(y.bcs.u64()).parse(Uint8Array.from(a[1][0])),i=y.bcs.vector(y.bcs.Address).parse(Uint8Array.from(a[2][0]));return s.map((g,d)=>({marketId:Number(g),emodeId:Number(u[d]),accountCap:i[d].toString()}))}));function Ve(e,t,o){const n=typeof o?.balance=="number",r=n?o.balance:0;let c=0;const a=[];let s="";if(t.sort((u,i)=>Number(i.balance)-Number(u.balance)).forEach(u=>{if(!(n&&c>=r)&&Number(u.balance)!==0){if(s||(s=u.coinType),s!==u.coinType)throw new Error("All coins must be of the same type");c+=Number(u.balance),a.push(u.coinObjectId)}}),a.length===0)throw new Error("No coins to merge");if(n&&c<r)throw new Error(`Balance is less than the specified balance: ${c} < ${r}`);return f(s)===f("0x2::sui::SUI")&&o?.useGasCoin?n?e.splitCoins(e.gas,[e.pure.u64(r)]):e.gas:(a.length===1?e.object(a[0]):e.mergeCoins(a[0],a.slice(1)),n?e.splitCoins(a[0],[e.pure.u64(r)]):a[0])}async function N(e,t,o,n,r,c,a){const s=await b({...a,cacheTime:m}),u=await C(o,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),Te(e,u),p(t,e.pure.address),p(u.id,e.pure.u8),p(n,e.pure.u64),p(r,e.pure.u64),p(c,e.pure.bool)],typeArguments:[u.suiCoinType]})}async function re(e,t,o){return N(e,t,0,0,0,!1,o)}const U=T(async(e,t)=>{const o=await b({...t,cacheTime:m}),n=new $.Transaction,r=t?.client??j,c=await M(t);n.moveCall({target:`${o.uiGetter}::getter_unchecked::get_user_state`,arguments:[n.object(o.storage),n.pure.address(e)]});const a=await r.devInspectTransactionBlock({transactionBlock:n,sender:e}),s=E(a,[y.bcs.vector(z)]);return V(s[0].filter(i=>i.supply_balance!=="0"||i.borrow_balance!=="0")).map(i=>{const g=c.find(_=>_.id===i.assetId),d=q(i.supplyBalance,g.currentSupplyIndex).toString(),w=q(i.borrowBalance,g.currentBorrowIndex).toString();return{...i,supplyBalance:d,borrowBalance:w,pool:g}}).filter(i=>!!i.pool)});async function Re(e,t){const o=t?.client??j,n=new $.Transaction;await re(n,e,t);const r=await o.devInspectTransactionBlock({transactionBlock:n,sender:e}),c=E(r,[y.bcs.u256()]);return Y(Number(c[0])||0)}async function De(e,t,o,n){const r=n?.client??j,c=new $.Transaction;let a=0,s=0;const u=await C(t,n);if(o.forEach(w=>{w.type===B.Supply?a+=w.amount:w.type===B.Withdraw?a-=w.amount:w.type===B.Borrow?s+=w.amount:w.type===B.Repay&&(s-=w.amount)}),a*s<0)throw new Error("Invalid operations");const i=a>0||s>0;await N(c,e,u,Math.abs(a),Math.abs(s),i,n);const g=await r.devInspectTransactionBlock({transactionBlock:c,sender:e}),d=E(g,[y.bcs.u256()]);return Y(Number(d[0])||0)}const Ue=v(async(e,t)=>{const o=new URLSearchParams;t?.cursor&&o.set("cursor",t.cursor),o.set("userAddress",e);const n=`https://open-api.naviprotocol.io/api/navi/user/transactions?${o.toString()}&sdk=${k.version}`;return(await fetch(n,{headers:I}).then(c=>c.json())).data});async function Se(e,t){let o=null;const n=[],r=t?.client??j;do{let c;if(t?.coinType?c=await r.getCoins({owner:e,coinType:t?.coinType,cursor:o,limit:100}):c=await r.getAllCoins({owner:e,cursor:o,limit:100}),!c.data||!c.data.length)break;n.push(...c.data),o=c.nextCursor}while(o);return n}const Ne=T(async(e,t)=>{const o=[],[n,r]=await Promise.all([U(e,t),ne(e,t)]);return n.forEach(a=>{if(h(a.supplyBalance).gt(0)){const s=h(a.supplyBalance).shiftedBy(-9).decimalPlaces(a.pool.token.decimals,h.ROUND_DOWN);o.push({id:a.pool.uniqueId,wallet:e,protocol:"navi",type:"navi-lending-supply","navi-lending-supply":{amount:s.toString(),pool:a.pool,token:a.pool.token,valueUSD:s.multipliedBy(a.pool.oracle.price).toString()}})}if(h(a.borrowBalance).gt(0)){const s=h(a.borrowBalance).shiftedBy(-9).decimalPlaces(a.pool.token.decimals,h.ROUND_DOWN);o.push({id:a.pool.uniqueId,wallet:e,protocol:"navi",type:"navi-lending-borrow","navi-lending-borrow":{amount:s.toString(),pool:a.pool,token:a.pool.token,valueUSD:s.multipliedBy(a.pool.oracle.price).toString()}})}}),(await Promise.all(r.map(async a=>U(a.accountCap,t)))).forEach((a,s)=>{const u=r[s];a.forEach(i=>{if(h(i.supplyBalance).gt(0)){const g=h(i.supplyBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals,h.ROUND_DOWN);o.push({id:i.pool.uniqueId,wallet:e,protocol:"navi",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:g.toString(),pool:G(i.pool,u),token:i.pool.token,valueUSD:g.multipliedBy(i.pool.oracle.price).toString()}})}if(h(i.borrowBalance).gt(0)){const g=h(i.borrowBalance).shiftedBy(-9).decimalPlaces(i.pool.token.decimals,h.ROUND_DOWN);o.push({id:i.pool.uniqueId,wallet:e,protocol:"navi",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:g.toString(),pool:G(i.pool,u),token:i.pool.token,valueUSD:g.multipliedBy(i.pool.oracle.price).toString()}})}})}),o}),ce=new S.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function ae(e){try{const t=[],o=await ce.getLatestPriceFeeds(e);if(!o)return t;const n=Math.floor(new Date().valueOf()/1e3);for(const r of o){const c=r.getPriceUnchecked();if(c.publishTime>n){console.warn(`pyth price feed is invalid, id: ${r.id}, publish time: ${c.publishTime}, current timestamp: ${n}`);continue}n-r.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${r.id}, publish time: ${c.publishTime}, current timestamp: ${n}`),t.push(r.id))}return t}catch(t){throw new Error(`failed to get pyth stale price feed id, msg: ${t.message}`)}}async function se(e,t,o){const n=o?.client??j,r=await b({...o,cacheTime:m});try{const c=await ce.getPriceFeedsUpdateData(t);return await new S.SuiPythClient(n,r.oracle.pythStateId,r.oracle.wormholeStateId).updatePriceFeeds(e,c,t)}catch(c){throw new Error(`failed to update pyth price feeds, msg: ${c.message}`)}}async function Le(e,t,o){const n=await b({...o,cacheTime:m});if(o?.updatePythPriceFeeds){const r=t.filter(c=>!!c.pythPriceFeedId).map(c=>c.pythPriceFeedId);try{const c=await ae(r);c.length>0&&await se(e,c,o)}catch{}}for(const r of t)e.moveCall({target:`${n.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(n.oracle.oracleConfig),e.object(n.oracle.priceOracle),e.object(n.oracle.supraOracleHolder),e.object(r.pythPriceInfoObject),e.pure.address(r.feedId)]});return e}async function ie(e){return(await b({...e,cacheTime:m})).oracle.feeds}function Oe(e,t){return e.filter(o=>!!(t?.lendingState&&t.lendingState.find(r=>r.assetId===o.assetId)||t?.pools&&t.pools.find(r=>r.id===o.assetId)))}const R=T(v(async e=>{const t=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${k.version}&market=${e?.market||P}`,o=await fetch(t,{headers:I}).then(n=>n.json());return Object.keys(o.data).map(n=>({...o.data[n],coinType:n}))}));async function qe(e,t){return(await R(t)).find(n=>typeof e=="string"?f(n.coinType)===f(e):typeof e=="number"?n.assetId===e:n.assetId===e.id)||null}async function He(e,t,o,n){const r=await b({...n,cacheTime:m}),c=await C(t,n);if(!(await R({...n,cacheTime:m})).some(u=>f(u.coinType)===f(c.suiCoinType)))throw new Error("Pool does not support flashloan");if(r.version===1){const[u,i]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx`,arguments:[e.object(r.flashloanConfig),e.object(c.contract.pool),p(o,e.pure.u64)],typeArguments:[c.suiCoinType]});return[u,i]}else{const[u,i]=e.moveCall({target:`${r.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(r.flashloanConfig),e.object(c.contract.pool),p(o,e.pure.u64),e.object("0x05")],typeArguments:[c.suiCoinType]});return[u,i]}}async function Ge(e,t,o,n,r){const c=await b({...r,cacheTime:m}),a=await C(t,r);if(!(await R({...r,cacheTime:m})).some(g=>f(g.coinType)===f(a.suiCoinType)))throw new Error("Pool does not support flashloan");const[i]=e.moveCall({target:`${c.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(c.storage),e.object(a.contract.pool),p(o,e.object),p(n,e.object)],typeArguments:[a.suiCoinType]});return[i]}async function We(e,t,o,n,r,c){const a={...c,cacheTime:m},s=await b(a),u=await C(t,a),i=await C(n,a);if(s.version===1){const[g,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(o,e.object),e.pure.u8(i.id),e.object(i.contract.pool),p(r,e.pure.address),e.object(s.incentiveV2),e.object(s.incentiveV3)],typeArguments:[u.suiCoinType,i.suiCoinType]});return[g,d]}else{const[g,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(o,e.object),e.pure.u8(i.id),e.object(i.contract.pool),p(r,e.pure.address),e.object(s.incentiveV2),e.object(s.incentiveV3),e.object("0x05")],typeArguments:[u.suiCoinType,i.suiCoinType]});return[g,d]}}async function ze(e,t){const o=await ie(t),n=await M({...t,cacheTime:m}),r=t?.client??j,c=await b({...t,cacheTime:m}),a=new $.Transaction;a.moveCall({target:`${c.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[a.object("0x06"),a.object(c.storage),a.object(c.incentiveV3),a.pure.address(e)]});const s=await r.devInspectTransactionBlock({transactionBlock:a,sender:e}),u=E(s,[y.bcs.vector(y.bcs.string()),y.bcs.vector(y.bcs.string()),y.bcs.vector(y.bcs.u8()),y.bcs.vector(y.bcs.Address),y.bcs.vector(y.bcs.u256())]),i=[];if(u.length===5&&Array.isArray(u[0])){const g=u[0].length;for(let d=0;d<g;d++){const w=o.find(A=>f(A.coinType)===f(u[1][d])),_=n.find(A=>f(A.coinType)===f(u[0][d]));!w||!_||i.push({assetId:_.id,assetCoinType:f(u[0][d]),rewardCoinType:f(u[1][d]),option:Number(u[2][d]),userClaimableReward:Number(u[4][d])/Math.pow(10,w.priceDecimal),ruleIds:Array.isArray(u[3][d])?u[3][d]:[u[3][d]]})}}return i}function Ke(e){const t=new Map;e.forEach(n=>{const r=n.assetId,c=n.option,a=`${r}-${c}-${n.rewardCoinType}`;t.has(a)?t.get(a).total+=n.userClaimableReward:t.set(a,{assetId:r,rewardType:c,coinType:n.rewardCoinType,total:Number(n.userClaimableReward)})});const o=new Map;for(const{assetId:n,rewardType:r,coinType:c,total:a}of t.values()){const s=`${n}-${r}`;o.has(s)||o.set(s,{assetId:n,rewardType:r,rewards:new Map});const u=o.get(s);u.rewards.set(c,(u.rewards.get(c)||0)+a)}return Array.from(o.values()).map(n=>({assetId:n.assetId,rewardType:n.rewardType,rewards:Array.from(n.rewards.entries()).map(([r,c])=>({coinType:r,available:c.toFixed(6)}))}))}const Ye=v(async(e,t)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${k.version}&market=${t?.market||P}`;return(await fetch(o,{headers:I}).then(r=>r.json())).data}),Je=v(async(e,t)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${t?.page||1}&pageSize=${t?.size||400}&sdk=${k.version}&market=${t?.market||P}`,n=await fetch(o,{headers:I}).then(r=>r.json());return V({data:n.data.rewards})});async function Qe(e,t,o){const n=await b({...o,cacheTime:m}),r=await M({...o,cacheTime:m}),c=new Map;for(const s of t){const{rewardCoinType:u,ruleIds:i}=s;for(const g of i){c.has(u)||c.set(u,{assetIds:[],ruleIds:[],amount:0});const d=c.get(u);d.assetIds.push(s.assetCoinType.replace("0x","")),d.ruleIds.push(g),d.amount+=s.userClaimableReward}}const a=[];for(const[s,{assetIds:u,ruleIds:i,amount:g}]of c){const d=r.find(_=>f(_.suiCoinType)===f(s));if(!d||!d.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${s}`);const w=d.contract.rewardFundId;if(o?.accountCap&&!o.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(o?.customCoinReceive){let _;o.accountCap?_=e.moveCall({target:`${n.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(n.incentiveV3),e.object(n.storage),e.object(w),e.pure.vector("string",u),e.pure.vector("address",i),p(o.accountCap,e.object)],typeArguments:[s]}):_=e.moveCall({target:`${n.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(n.incentiveV3),e.object(n.storage),e.object(w),e.pure.vector("string",u),e.pure.vector("address",i)],typeArguments:[s]});const[A]=e.moveCall({target:"0x2::coin::from_balance",arguments:[_],typeArguments:[s]});if(o?.customCoinReceive.type==="transfer"){if(!o.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([A],p(o.customCoinReceive.transfer,e.pure.address))}if(o?.customCoinReceive.type==="depositNAVI"){const ue=h(d.totalSupplyAmount).shiftedBy(-9),le=h(d.supplyCapCeiling).shiftedBy(-27);ue.plus(g).isGreaterThan(le)&&o?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([A],e.pure.address(o.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await Q(e,d,A,o)}else a.push({coin:A,identifier:d})}else e.moveCall({target:`${n.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(n.incentiveV3),e.object(n.storage),e.object(w),e.pure.vector("string",u),e.pure.vector("address",i)],typeArguments:[s]})}return a}exports.Address=D;exports.DEFAULT_CACHE_TIME=m;exports.DEFAULT_MARKET_IDENTITY=P;exports.FlashLoanAssetConfig=be;exports.IncentiveAPYInfo=me;exports.IncentivePoolInfo=W;exports.IncentivePoolInfoByPhase=ge;exports.MARKETS=X;exports.Market=Z;exports.OracleInfo=fe;exports.PoolOperator=B;exports.ReserveDataInfo=he;exports.UserStateInfo=z;exports.borrowCoinPTB=Ie;exports.claimLendingRewardsPTB=Qe;exports.createAccountCapPTB=ee;exports.createEModeCapPTB=Fe;exports.depositCoinPTB=Q;exports.enterEModePTB=oe;exports.exitEModePTB=Ee;exports.filterPriceFeeds=Oe;exports.flashloanPTB=He;exports.getAccountCapOwnerPTB=te;exports.getAllFlashLoanAssets=R;exports.getBorrowFee=$e;exports.getCoins=Se;exports.getConfig=b;exports.getFees=Ae;exports.getFlashLoanAsset=qe;exports.getHealthFactor=Re;exports.getHealthFactorPTB=re;exports.getLendingPositions=Ne;exports.getLendingState=U;exports.getMarket=Me;exports.getMarketConfig=F;exports.getMarkets=x;exports.getPool=C;exports.getPools=M;exports.getPriceFeeds=ie;exports.getPythStalePriceFeedId=ae;exports.getSimulatedHealthFactor=De;exports.getSimulatedHealthFactorPTB=N;exports.getStats=ke;exports.getTransactions=Ue;exports.getUserAvailableLendingRewards=ze;exports.getUserClaimedRewardHistory=Je;exports.getUserEModeCaps=ne;exports.getUserTotalClaimedReward=Ye;exports.liquidatePTB=We;exports.mergeCoinsPTB=Ve;exports.normalizeCoinType=f;exports.parsePoolUID=J;exports.parseTxValue=p;exports.repayCoinPTB=Be;exports.repayFlashLoanPTB=Ge;exports.summaryLendingRewards=Ke;exports.updateOraclePricesPTB=Le;exports.updatePythPriceFeeds=se;exports.withCache=T;exports.withSingleton=v;exports.withdrawCoinPTB=Pe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@mysten/sui/transactions"),d=require("@mysten/bcs"),J=require("@mysten/sui/client"),ke=require("lodash.camelcase"),Ce=require("@mysten/sui/utils"),G=require("@pythnetwork/pyth-sui-js"),u=require("bignumber.js"),C=require("@mysten/sui/bcs"),q=d.bcs.bytes(32).transform({input:e=>d.fromHex(e),output:e=>d.toHex(e)}),je=d.bcs.struct("IncentiveAPYInfo",{asset_id:d.bcs.u8(),apy:d.bcs.u256(),coin_types:d.bcs.vector(d.bcs.string())}),ee=d.bcs.struct("IncentivePoolInfo",{pool_id:q,funds:q,phase:d.bcs.u64(),start_at:d.bcs.u64(),end_at:d.bcs.u64(),closed_at:d.bcs.u64(),total_supply:d.bcs.u64(),asset_id:d.bcs.u8(),option:d.bcs.u8(),factor:d.bcs.u256(),distributed:d.bcs.u64(),available:d.bcs.u256(),total:d.bcs.u256()}),_e=d.bcs.struct("IncentivePoolInfoByPhase",{phase:d.bcs.u64(),pools:d.bcs.vector(ee)}),Te=d.bcs.struct("OracleInfo",{oracle_id:d.bcs.u8(),price:d.bcs.u256(),decimals:d.bcs.u8(),valid:d.bcs.bool()}),Ie=d.bcs.struct("FlashLoanAssetConfig",{id:d.bcs.string(),asset_id:d.bcs.u8(),coin_type:d.bcs.string(),pool_id:d.bcs.string(),rate_to_supplier:d.bcs.u64(),rate_to_treasury:d.bcs.u64(),max:d.bcs.u64(),min:d.bcs.u64()}),Be=d.bcs.struct("ReserveDataInfo",{id:d.bcs.u8(),oracle_id:d.bcs.u8(),coin_type:d.bcs.string(),supply_cap:d.bcs.u256(),borrow_cap:d.bcs.u256(),supply_rate:d.bcs.u256(),borrow_rate:d.bcs.u256(),supply_index:d.bcs.u256(),borrow_index:d.bcs.u256(),total_supply:d.bcs.u256(),total_borrow:d.bcs.u256(),last_update_at:d.bcs.u64(),ltv:d.bcs.u256(),treasury_factor:d.bcs.u256(),treasury_balance:d.bcs.u256(),base_rate:d.bcs.u256(),multiplier:d.bcs.u256(),jump_rate_multiplier:d.bcs.u256(),reserve_factor:d.bcs.u256(),optimal_utilization:d.bcs.u256(),liquidation_ratio:d.bcs.u256(),liquidation_bonus:d.bcs.u256(),liquidation_threshold:d.bcs.u256()}),te=d.bcs.struct("UserStateInfo",{asset_id:d.bcs.u8(),borrow_balance:d.bcs.u256(),supply_balance:d.bcs.u256()}),Pe="1.4.0-emode.30",$={version:Pe},Ae=$.version,Se=()=>{if(typeof process<"u"&&process.versions&&process.versions.node)try{const e=require("os"),n=process.version,o=e.type(),r=e.arch();return`Node.js ${n.startsWith("v")?n.substring(1):n}; ${o}/${r}`}catch{return`Node.js ${process.version}; OS/Unknown (Error)`}return"Node/Unknown"},$e=()=>{let e="";return typeof process<"u"&&process.versions&&process.versions.node&&(e=`lending/${Ae} (${Se()})`),e},Q=$e(),S=new J.SuiClient({url:J.getFullnodeUrl("mainnet")});function oe(e){const n=[];return e.forEach((o,r)=>{const t=r===e.length-1;if(typeof o=="object"&&o!==null&&t){const{client:a,disableCache:s,cacheTime:c,...i}=o;n.push(i)}else n.push(o)}),JSON.stringify(n)}function I(e){const n={};return(...o)=>{const r=oe(o);return n[r]||(n[r]=e(...o).finally(()=>{delete n[r]})),n[r]}}function A(e){let n={};return(...o)=>{const r=o[o.length-1],t=oe(o),a=n[t];return!r?.disableCache&&typeof a?.data<"u"&&(typeof r?.cacheTime>"u"||r.cacheTime>Date.now()-a.cacheAt)?a.data:e(...o).then(s=>(n[t]={data:s,cacheAt:Date.now()},s))}}function H(e){return Array.isArray(e)?e.map(n=>H(n)):e!=null&&typeof e=="object"?Object.keys(e).reduce((n,o)=>({...n,[ke(o)]:H(e[o])}),{}):e}function g(e,n){return typeof e=="object"?e:n(e)}function Ee(e,n){return typeof n=="string"?e.object(n):typeof n=="object"&&n.$kind?n:e.object(n.contract.pool)}function R(e,n,o){if(e.results&&e.results.length>0){if(e.results[0].returnValues&&e.results[0].returnValues.length>0)return e.results[0].returnValues.map((r,t)=>(n[t]||n[0]).parse(Uint8Array.from(r[0])))}else if(e.error)return console.log(`Get an error, msg: ${e.error}`),[];return[]}function v(e){return Ce.normalizeStructTag(e)}function ne(e){const n=(e||0)/Math.pow(10,27);return n>Math.pow(10,5)?1/0:n}new G.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:2e4});const Ve=27,X=(e,n)=>{if(!Number(e)||!Number(n))return new u(0);const o=new u(1).shiftedBy(1*Ve),r=o.multipliedBy(new u(.5));return new u(e).multipliedBy(new u(n)).plus(r).dividedBy(o).integerValue(u.ROUND_DOWN)},V=Q?{"User-Agent":Q}:{};function W(e,n="uniqueId"){return e.reduce((o,r)=>(o[r[n]]=r,o),{})}function Z(e,n="uniqueId"){return e.reduce((o,r)=>(o[r[n]]=r,o),{})}function x(e,n){const o=e.emodes.find(t=>t.emodeId===n.emodeId);if(!o)throw new Error("EMode not found in pool");const r=o.assets.find(t=>t.assetId===e.id);return{...e,emode:{...r,emodeId:o.emodeId},isEMode:!0}}function re(e){const[n,o]=e.split("-");return!n||!o?null:{marketKey:n,poolId:parseInt(o)}}function B(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}var D=(e=>(e[e.Supply=1]="Supply",e[e.Withdraw=2]="Withdraw",e[e.Borrow=3]="Borrow",e[e.Repay=4]="Repay",e))(D||{});const N=A(I(async e=>{const n=(e?.markets||[E.main]).map(t=>_(t)),o=`https://open-api.naviprotocol.io/api/navi/pools?env=${e?.env||"prod"}&sdk=${$.version}&market=${n.map(t=>t.key)}`,r=await fetch(o,{headers:V}).then(t=>t.json());return r.data.forEach(t=>{const s=r.meta.emodes.filter(y=>{const T=_(y.marketId);return t.market===T.key&&y.isActive}).filter(y=>!!y.assets.find(T=>T.assetId===t.id));t.emodes=s;const c=u(t.totalSupplyAmount).div(Math.pow(10,9)).decimalPlaces(t.token.decimals,u.ROUND_DOWN).toString(),i=u(t.borrowedAmount).shiftedBy(-9).decimalPlaces(t.token.decimals,u.ROUND_DOWN).toString(),l=u(c).multipliedBy(t.oracle.price).toString(),m=u(i).multipliedBy(t.oracle.price).toString(),f=u(t.supplyCapCeiling).shiftedBy(-27).decimalPlaces(t.token.decimals,u.ROUND_DOWN).toString(),h=u.max(u(t.borrowedAmount),u(t.validBorrowAmount)).shiftedBy(-9).decimalPlaces(t.token.decimals,u.ROUND_DOWN).toString(),b=u(f).multipliedBy(t.oracle.price).toString(),p=u(h).multipliedBy(t.oracle.price).toString();t.poolSupplyAmount=c,t.poolBorrowAmount=i,t.poolSupplyValue=l,t.poolBorrowValue=m,t.poolSupplyCapAmount=f,t.poolBorrowCapAmount=h,t.poolSupplyCapValue=b,t.poolBorrowCapValue=p}),r.data}));async function P(e,n){let o=n?.market;if(typeof e=="string"){const a=re(e);a&&(o=a.marketKey,e=a.poolId)}const r=await N({...n,markets:[o||U],cacheTime:w});if(typeof e=="object")return e;const t=r.find(a=>typeof e=="string"?v(a.suiCoinType)===v(e):typeof e=="number"?a.id===e:!1);if(!t)throw new Error("Pool not found");return t.isDeprecated&&console.log(`The lending pool for coinType ${t.suiCoinType} is going to be deprecated.`),t}const Me=A(I(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/stats?sdk=${$.version}`;return(await fetch(n,{headers:V}).then(r=>r.json())).data})),Ue=A(I(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/fee?sdk=${$.version}`;return await fetch(n,{headers:V}).then(r=>r.json())}));async function ae(e,n,o,r){const t=await k({...r,cacheTime:w}),a=await P(n,r);if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const s=typeof o=="object"&&o.$kind==="GasCoin";if(v(a.suiCoinType)===v("0x2::sui::SUI")&&s){if(!r?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[r.amount])}let c;return typeof r?.amount<"u"?c=g(r.amount,e.pure.u64):c=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),r?.accountCap?e.moveCall({target:`${t.package}::incentive_v3::deposit_with_account_cap`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]}):e.moveCall({target:`${t.package}::incentive_v3::entry_deposit`,arguments:[e.object("0x06"),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),c,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),t.version===2&&a.id===0&&(!r?.env||r?.env==="prod")&&e.moveCall({target:`${t.package}::pool::refresh_stake`,arguments:[e.object(a.contract.pool),e.object("0x05")]}),e}async function Oe(e,n,o,r){const t=await k({...r,cacheTime:w}),a=await P(n,r),s=g(o,e.pure.u64);let c;if(t.version===1)if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=l}else if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::withdraw_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[c],typeArguments:[a.suiCoinType]})}async function De(e,n,o,r){const t=await k({...r,cacheTime:w}),a=await P(n,r);if(a?.deprecatedAt&&Date.now()>a.deprecatedAt)throw new Error(`The lending pool for coinType ${a.suiCoinType} has been deprecated.`);const s=g(o,e.pure.u64);let c;if(t.version===1)if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]});c=l}else if(r?.accountCap){const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_with_account_cap_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}else{const[l]=e.moveCall({target:`${t.package}::incentive_v3::borrow_v2`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),s,e.object(t.incentiveV2),e.object(t.incentiveV3),e.object("0x05")],typeArguments:[a.suiCoinType]});c=l}return e.moveCall({target:"0x2::coin::from_balance",arguments:[e.object(c)],typeArguments:[a.suiCoinType]})}async function Fe(e,n,o,r){const t=await k({...r,cacheTime:w}),a=await P(n,r),s=typeof o=="object"&&o.$kind==="GasCoin";if(v(a.suiCoinType)===v("0x2::sui::SUI")&&s){if(!r?.amount)throw new Error("Amount is required for sui coin");o=e.splitCoins(o,[r.amount])}let c;if(typeof r?.amount<"u"?c=g(r.amount,e.pure.u64):c=e.moveCall({target:"0x2::coin::value",arguments:[g(o,e.object)],typeArguments:[a.suiCoinType]}),r?.accountCap){const[i]=e.moveCall({target:`${t.package}::incentive_v3::repay_with_account_cap`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),e.object(t.incentiveV2),e.object(t.incentiveV3),g(r.accountCap,e.object)],typeArguments:[a.suiCoinType]});return e.moveCall({target:"0x2::coin::from_balance",arguments:[i],typeArguments:[a.suiCoinType]})}else return e.moveCall({target:`${t.package}::incentive_v3::entry_repay`,arguments:[e.object("0x06"),e.object(t.priceOracle),e.object(t.storage),e.object(a.contract.pool),e.pure.u8(a.id),g(o,e.object),c,e.object(t.incentiveV2),e.object(t.incentiveV3)],typeArguments:[a.suiCoinType]}),e}const Ne=A(I(async e=>{const n=await k({...e});if(e?.address&&typeof e?.asset<"u")try{const t=await P(e.asset,e),a=e?.client??S,s=new F.Transaction;s.moveCall({target:`${n.package}::incentive_v3::get_borrow_fee_v2`,arguments:[s.object(n.incentiveV3),s.pure.address(e.address),s.pure.u8(t.id),s.pure.u64(1e4)],typeArguments:[]});const c=await a.devInspectTransactionBlock({transactionBlock:s,sender:e.address}),i=R(c,[C.bcs.u64()]);return(Number(i[0])||0)/100}catch(t){console.error(t)}const r=(await S.getObject({id:n.incentiveV3,options:{showType:!0,showOwner:!0,showContent:!0}})).data.content.fields.borrow_fee_rate;return Number(r)/100})),U="main",E={main:{id:0,key:"main",name:"Main Market"}};class ce{constructor(n,o){this.poolMap={},this.emodeMap={},this.pools=[],this.emodes=[],this.emodePools=[],this.emodeBorrowablePools=[],this.emodeSupplyablePools=[],this._overview={marketTotalSupplyValue:"0",marketTotalBorrowValue:"0"},this.config=_(n),this.addPools(o)}get overview(){return this._overview}addPools(n){const o=W(this.pools),r=Z(this.emodes),t=new Set,a=new Set;let s=u(0),c=u(0);n.forEach(i=>{if(!this.checkMarket(i.market)){console.warn(`Pool is not in market ${this.config.name}`,i);return}o[i.uniqueId]||this.pools.push(i),i?.emodes?.forEach(m=>{r[m.uniqueId]||this.emodes.push(m),m.assets.forEach(f=>{f.isDebt&&t.add(i.uniqueId),f.isCollateral&&a.add(i.uniqueId)})}),c=c.plus(i.poolBorrowValue),s=s.plus(i.poolSupplyValue)}),this.poolMap=W(this.pools,"id"),this.emodeMap=Z(this.emodes,"emodeId"),this.emodes.forEach(i=>{const l=this.getEModePools(i.emodeId);this.emodePools.push(...l)}),this._overview={marketTotalSupplyValue:s.toString(),marketTotalBorrowValue:c.toString()},this.emodeBorrowablePools=this.pools.filter(i=>t.has(i.uniqueId)),this.emodeSupplyablePools=this.pools.filter(i=>a.has(i.uniqueId))}getEMode(n){return this.emodeMap[n]||null}getEModeRelatePools(n,o){const{collateral:r,debt:t,emodeId:a}=o||{},s=[];return n.emodes.forEach(c=>{typeof a=="number"&&a!==c.emodeId||c.assets.forEach(i=>{typeof r=="boolean"&&r&&i.isCollateral&&i.assetId===n.id&&s.push(this.poolMap[i.assetId]),typeof t=="boolean"&&t&&i.isDebt&&i.assetId===n.id&&s.push(this.poolMap[i.assetId])})}),s}getEModePools(n){const o=this.getEMode(n);return o?o.assets.map(t=>t.assetId).map(t=>this.poolMap[t]).filter(t=>!!t).map(t=>{const a=o.assets.find(s=>s.assetId===t.id);return{...t,emode:{...a,emodeId:o.emodeId},isEMode:!0}}):[]}checkMarket(n){let o=!1;return typeof n=="number"&&n===this.config.id&&(o=!0),typeof n=="string"&&n===this.config.key&&(o=!0),typeof n=="object"&&n.id===this.config.id&&(o=!0),o}}const _=e=>{const o=Object.values(E).find(r=>typeof e=="number"?r.id===e:typeof e=="string"?r.key===e:r.id===e.id);if(!o)throw new Error("Market not found");return o},se=A(I(async(e,n)=>{const o=await N({cacheTime:6e4,...n,markets:e});return e.map(r=>{const t=_(r),a=o.filter(s=>s.market===t.key);return new ce(r,a)})})),Re=A(I(async(e,n)=>(await se([e],n))[0])),k=A(I(async e=>{const n=_(e?.market||U),o=`https://open-api.naviprotocol.io/api/navi/config?env=${e?.env||"prod"}&sdk=${$.version}&market=${n.key}`;return(await fetch(o,{headers:V}).then(t=>t.json())).data})),w=1e3*60*5;async function ie(e,n){const o=await k({cacheTime:w,...n});return e.moveCall({target:`${o.package}::lending::create_account`,arguments:[]})}async function le(e,n,o){const r=await k({cacheTime:w,...o});return e.moveCall({target:`${r.package}::account::account_owner`,arguments:[n]})}async function ue(e,n,o){const r=await k({...o,cacheTime:w});return o?.accountCap?e.moveCall({target:`${r.package}::lending::enter_emode_with_account_cap`,arguments:[e.object(r.storage),g(n,e.pure.u64),g(o.accountCap,e.object)]}):e.moveCall({target:`${r.package}::lending::enter_emode`,arguments:[e.object(r.storage),g(n,e.pure.u64)]}),e}async function Le(e,n){const o=await k({...n,cacheTime:w});return n?.accountCap?e.moveCall({target:`${o.package}::lending::exit_emode_with_account_cap`,arguments:[e.object(o.storage),g(n.accountCap,e.object)]}):e.moveCall({target:`${o.package}::lending::exit_emode`,arguments:[e.object(o.storage)]}),e}async function qe(e,n,o){const r=await k({cacheTime:w,...o}),t=await ie(e,o);await ue(e,n,{...o,accountCap:t});const a=await _(o?.market||U),s=await le(e,t,o);return e.moveCall({target:`${r.emode.contract.registryPackage}::registry::register_emode_for_account_cap`,arguments:[e.object(r.emode.contract.registryObject),s,g(a.id,e.pure.u64),g(n,e.pure.u64)]}),t}const z=A(I(async(e,n)=>{const o=await k({cacheTime:w,...n}),r=new F.Transaction,t=n?.client??S;r.moveCall({target:`${o.emode.contract.registryPackage}::registry::find_user_emode_account_caps`,arguments:[r.object(o.emode.contract.registryObject),r.pure.address(e)]});const s=(await t.devInspectTransactionBlock({transactionBlock:r,sender:e})).results[0].returnValues,c=C.bcs.vector(C.bcs.u64()).parse(Uint8Array.from(s[0][0])),i=C.bcs.vector(C.bcs.u64()).parse(Uint8Array.from(s[1][0])),l=C.bcs.vector(C.bcs.Address).parse(Uint8Array.from(s[2][0]));return c.map((m,f)=>({marketId:Number(m),emodeId:Number(i[f]),accountCap:l[f].toString()}))}));function He(e){return`${_(e.marketId).key}-${e.emodeId}`}function We(e,n,o){const r=typeof o?.balance=="number",t=r?o.balance:0;let a=0;const s=[];let c="";if(n.sort((i,l)=>Number(l.balance)-Number(i.balance)).forEach(i=>{if(!(r&&a>=t)&&Number(i.balance)!==0){if(c||(c=i.coinType),c!==i.coinType)throw new Error("All coins must be of the same type");a+=Number(i.balance),s.push(i.coinObjectId)}}),s.length===0)throw new Error("No coins to merge");if(r&&a<t)throw new Error(`Balance is less than the specified balance: ${a} < ${t}`);return v(c)===v("0x2::sui::SUI")&&o?.useGasCoin?r?e.splitCoins(e.gas,[e.pure.u64(t)]):e.gas:(s.length===1?e.object(s[0]):e.mergeCoins(s[0],s.slice(1)),r?e.splitCoins(s[0],[e.pure.u64(t)]):s[0])}async function K(e,n,o,r,t,a,s){const c=await k({...s,cacheTime:w}),i=await P(o,s);return e.moveCall({target:`${c.uiGetter}::calculator_unchecked::dynamic_health_factor`,arguments:[e.object("0x06"),e.object(c.storage),e.object(c.oracle.priceOracle),Ee(e,i),g(n,e.pure.address),g(i.id,e.pure.u8),g(r,e.pure.u64),g(t,e.pure.u64),g(a,e.pure.bool)],typeArguments:[i.suiCoinType]})}async function pe(e,n,o){return K(e,n,0,0,0,!1,o)}async function de(e,n,o){const r=new F.Transaction,t=o?.client??S,a=await N({...o,markets:Object.values(E)}),s=W(a);for(let m of n){const f=await k({...o,cacheTime:w,market:m.market});r.moveCall({target:`${f.uiGetter}::getter_unchecked::get_user_state`,arguments:[r.object(f.storage),r.pure.address(m.address)]})}const i=((await t.devInspectTransactionBlock({transactionBlock:r,sender:e})).results||[]).map(m=>m.returnValues?.map(f=>C.bcs.vector(te).parse(Uint8Array.from(f[0])))[0]||[]),l=[];return i.forEach((m,f)=>{const h=n[f],b=_(h.market);m.forEach(p=>{if(p.supply_balance==="0"&&p.borrow_balance==="0")return;const y=s[`${b.key}-${p.asset_id}`];if(!y)return;const T=X(p.supply_balance,y.currentSupplyIndex).toString(),j=X(p.borrow_balance,y.currentBorrowIndex).toString();l.push({supplyBalance:T,borrowBalance:j,assetId:p.asset_id,market:b.key,pool:y,emodeId:h.emodeId})})}),l}const Ge=A(async(e,n)=>{const r=(n?.markets||Object.keys(E)).map(t=>_(t)).map(t=>({address:e,market:t.key}));return await de(e,r,n)});async function ze(e,n){const o=n?.client??S,r=new F.Transaction;await pe(r,e,n);const t=await o.devInspectTransactionBlock({transactionBlock:r,sender:e}),a=R(t,[C.bcs.u256()]);return ne(Number(a[0])||0)}async function Ke(e,n,o,r){const t=r?.client??S,a=new F.Transaction;let s=0,c=0;const i=await P(n,r);if(o.forEach(h=>{h.type===D.Supply?s+=h.amount:h.type===D.Withdraw?s-=h.amount:h.type===D.Borrow?c+=h.amount:h.type===D.Repay&&(c-=h.amount)}),s*c<0)throw new Error("Invalid operations");const l=s>0||c>0;await K(a,e,i,Math.abs(s),Math.abs(c),l,r);const m=await t.devInspectTransactionBlock({transactionBlock:a,sender:e}),f=R(m,[C.bcs.u256()]);return ne(Number(f[0])||0)}const Ye=I(async(e,n)=>{const o=new URLSearchParams;n?.cursor&&o.set("cursor",n.cursor),o.set("userAddress",e);const r=`https://open-api.naviprotocol.io/api/navi/user/transactions?${o.toString()}&sdk=${$.version}`;return(await fetch(r,{headers:V}).then(a=>a.json())).data});async function Je(e,n){let o=null;const r=[],t=n?.client??S;do{let a;if(n?.coinType?a=await t.getCoins({owner:e,coinType:n?.coinType,cursor:o,limit:100}):a=await t.getAllCoins({owner:e,cursor:o,limit:100}),!a.data||!a.data.length)break;r.push(...a.data),o=a.nextCursor}while(o);return r}const me=A(async(e,n)=>{const o=[],r=(n?.markets||Object.keys(E)).map(c=>_(c));let t=[];try{t=await z(e,n)}catch(c){console.error(c)}const a=r.map(c=>({address:e,market:c.key})).concat(t.filter(c=>!!r.find(i=>i.id===c.marketId)).map(c=>({address:c.accountCap,market:_(c.marketId).key,emodeId:c.emodeId})));return(await de(e,a,n)).forEach(c=>{const i=typeof c.emodeId=="number"?t.find(l=>{const m=_(c.market);return l.emodeId===c.emodeId&&l.marketId===m.id}):void 0;if(i){if(u(c.supplyBalance).gt(0)){const l=u(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,u.ROUND_DOWN);try{o.push({id:`${c.pool.uniqueId}_${i.emodeId}_navi-lending-emode-supply-${B()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:l.toString(),pool:x(c.pool,i),token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString(),emodeCap:i}})}catch(m){console.error(m)}}if(u(c.borrowBalance).gt(0)){const l=u(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,u.ROUND_DOWN);try{o.push({id:`${c.pool.uniqueId}_${i.emodeId}_navi-lending-emode-borrow-${B()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:l.toString(),pool:x(c.pool,i),token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString(),emodeCap:i}})}catch(m){console.error(m)}}}else{if(u(c.supplyBalance).gt(0)){const l=u(c.supplyBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,u.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-supply-${B()}`,wallet:e,protocol:"navi",type:"navi-lending-supply",market:c.market,"navi-lending-supply":{amount:l.toString(),pool:c.pool,token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString()}})}if(u(c.borrowBalance).gt(0)){const l=u(c.borrowBalance).shiftedBy(-9).decimalPlaces(c.pool.token.decimals,u.ROUND_DOWN);o.push({id:`${c.pool.uniqueId}_navi-lending-borrow-${B()}`,wallet:e,protocol:"navi",market:c.market,type:"navi-lending-borrow","navi-lending-borrow":{amount:l.toString(),pool:c.pool,token:c.pool.token,valueUSD:l.multipliedBy(c.pool.oracle.price).toString()}})}}}),o});class M{constructor(n){this._positions=[],this._overview={hf:1/0,netVaule:"0",netWorthApr:"0",totalSupplyValue:"0",totalBorrowValue:"0",totalsupplyApy:"0",totalBorrowApy:"0",maxLiquidationValue:"0",maxLoanToVaule:"0",supply:{},borrow:{}},this.positions=n}get positions(){return this._positions}get overview(){return this._overview}set positions(n){this._positions=n,this._overview=this.getPositionsOverview(n)}filterPositionsByPool(n){const r=!!n.isEMode?["navi-lending-emode-supply","navi-lending-emode-borrow"]:["navi-lending-supply","navi-lending-borrow"];return new M(this.positions.filter(t=>{const a=t[t.type];return r.includes(t.type)&&a.pool.uniqueId===n.uniqueId}))}deposit(n,o){const r=!!n.isEMode;let t;return r?t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:o.toString(),valueUSD:u(o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n,emodeCap:{}}}:t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:o.toString(),valueUSD:u(o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n}},new M([...this.positions,t])}withdraw(n,o){const r=!!n.isEMode;let t;return r?t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-supply","navi-lending-emode-supply":{amount:(-o).toString(),valueUSD:u(-o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n,emodeCap:{}}}:t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-supply","navi-lending-supply":{amount:(-o).toString(),valueUSD:u(-o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n}},new M([...this.positions,t])}borrow(n,o){const r=!!n.isEMode;let t;return r?t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:o.toString(),valueUSD:u(o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n,emodeCap:{}}}:t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:o.toString(),valueUSD:u(o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n}},new M([...this.positions,t])}repay(n,o){const r=!!n.isEMode;let t;return r?t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-emode-borrow","navi-lending-emode-borrow":{amount:(-o).toString(),valueUSD:u(-o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n,emodeCap:{}}}:t={id:B(),wallet:"",protocol:"navi",market:"",type:"navi-lending-borrow","navi-lending-borrow":{amount:(-o).toString(),valueUSD:u(-o).multipliedBy(n.oracle.price).toString(),token:n.token,pool:n}},new M([...this.positions,t])}getPositionsOverview(n){const o={},r={};let t=new u(0),a=new u(0),s=new u(0),c=new u(0),i=new u(0),l=new u(0);n.forEach(b=>{if(b.type==="navi-lending-supply"){const p=b["navi-lending-supply"];t=t.plus(p.valueUSD),i=i.plus(new u(p.valueUSD).multipliedBy(p.pool.liquidationFactor.threshold)),l=l.plus(new u(p.valueUSD).multipliedBy(p.pool.ltvValue))}else if(b.type==="navi-lending-borrow")a=a.plus(b["navi-lending-borrow"].valueUSD);else if(b.type==="navi-lending-emode-supply"){const p=b["navi-lending-emode-supply"];t=t.plus(p.valueUSD);const y=p.pool.emode;i=i.plus(new u(p.valueUSD).multipliedBy(y.lt)),l=l.plus(new u(p.valueUSD).multipliedBy(y.ltv))}else b.type==="navi-lending-emode-borrow"&&(a=a.plus(b["navi-lending-emode-borrow"].valueUSD))}),a=u.max(a,0),t=u.max(t,0),i=u.max(i,0),l=u.max(l,0),n.forEach(b=>{if(b.type==="navi-lending-supply"){const p=b["navi-lending-supply"],y=p.pool.supplyIncentiveApyInfo.apy;s=s.plus(new u(p.valueUSD).dividedBy(t).multipliedBy(new u(y).dividedBy(100))),o[p.pool.suiCoinType]=u(o[p.pool.suiCoinType]||0).plus(p.amount).toString()}else if(b.type==="navi-lending-borrow"){const p=b["navi-lending-borrow"],y=p.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new u(p.valueUSD).dividedBy(a).multipliedBy(new u(y).dividedBy(100)))),r[p.pool.suiCoinType]=u(r[p.pool.suiCoinType]||0).plus(p.amount).toString()}else if(b.type==="navi-lending-emode-supply"){const p=b["navi-lending-emode-supply"],y=p.pool.supplyIncentiveApyInfo.apy;t.gt(0)&&(s=s.plus(new u(p.valueUSD).dividedBy(t).multipliedBy(new u(y).dividedBy(100)))),o[p.pool.suiCoinType]=u(o[p.pool.suiCoinType]||0).plus(p.amount).toString()}else if(b.type==="navi-lending-emode-borrow"){const p=b["navi-lending-emode-borrow"],y=p.pool.borrowIncentiveApyInfo.apy;a.gt(0)&&(c=c.plus(new u(p.valueUSD).dividedBy(a).multipliedBy(new u(y).dividedBy(100)))),r[p.pool.suiCoinType]=u(r[p.pool.suiCoinType]||0).plus(p.amount).toString()}});const m=t.minus(a),f=t.minus(a).eq(0)?new u(0):t.multipliedBy(s).minus(a.multipliedBy(c)).div(t.minus(a));return{hf:a.toNumber()!==0?i.dividedBy(a).toNumber():1/0,netVaule:m.toString(),netWorthApr:f.toString(),totalSupplyValue:t.toString(),totalBorrowValue:a.toString(),totalsupplyApy:s.toString(),totalBorrowApy:c.toString(),maxLiquidationValue:i.toString(),maxLoanToVaule:l.toString(),supply:o,borrow:r}}}async function Qe(e,n,o,r){const t=await k({...r,cacheTime:w});t.limter&&e.moveCall({target:`${t.limter}::navi_adaptor::verify_navi_position_healthy`,arguments:[e.object("0x06"),e.object(t.storage),e.object(t.priceOracle),g(n,e.pure.address),e.pure.u256(new u(o).shiftedBy(27).toNumber())]})}const ge=new G.SuiPriceServiceConnection("https://hermes.pyth.network",{timeout:1e4});async function Xe(e){try{const n=[],o=await ge.getLatestPriceFeeds(e);if(!o)return n;const r=Math.floor(new Date().valueOf()/1e3);for(const t of o){const a=t.getPriceUnchecked();if(a.publishTime>r){console.warn(`pyth price feed is invalid, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${r}`);continue}r-t.getPriceUnchecked().publishTime>30&&(console.info(`stale price feed, id: ${t.id}, publish time: ${a.publishTime}, current timestamp: ${r}`),n.push(t.id))}return n}catch(n){throw new Error(`failed to get pyth stale price feed id, msg: ${n.message}`)}}async function Ze(e,n){try{const o=[],r=n?.client??S,t=e.map(s=>s.priceInfoObject),a=await r.multiGetObjects({ids:Array.from(new Set(t)),options:{showContent:!0}});for(const s of a){const c=s.data;if(!c||!c.content||c.content.dataType!=="moveObject"){console.warn(`fetched object ${c?.objectId} datatype should be moveObject`);continue}const i=e.find(p=>p.priceInfoObject==c.objectId);if(!i){console.warn(`unable to find pyth info from array, priceInfoObject: ${c.objectId}`);continue}const l=c.content.fields.price_info.fields.price_feed.fields.price.fields,{magnitude:m,negative:f}=l.price.fields,h=l.conf,b=l.timestamp;o.push({priceFeedId:i.priceFeedId,priceInfoObject:i.priceInfoObject,price:f?"-"+m:m,conf:h,publishTime:Number(b),expiration:i.expiration})}return o}catch(o){console.error(o,`Polling Sui on-chain price for ${e} failed.`);return}}async function fe(e,n){try{const o=[],r=await Ze(e,n);if(!r)return o;const t=Math.floor(new Date().valueOf()/1e3);for(const a of r){if(a.publishTime>t){console.warn(`pyth price feed is invalid, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`);continue}const s=a.expiration||60;t-a.publishTime>s&&(console.info(`stale price feed, id: ${a.priceFeedId}, publish time: ${a.publishTime}, current timestamp: ${t}`),o.push(a.priceFeedId))}return o}catch(o){throw new Error(`failed to get pyth stale price feed id, msg: ${o.message}`)}}async function ye(e,n,o){const r=o?.client??S,t=await k({...o,cacheTime:w});try{const a=await ge.getPriceFeedsUpdateData(n);return await new G.SuiPythClient(r,t.oracle.pythStateId,t.oracle.wormholeStateId).updatePriceFeeds(e,a,n)}catch(a){throw new Error(`failed to update pyth price feeds, msg: ${a.message}`)}}async function be(e,n,o){const r=await k({...o,cacheTime:w});if(o?.updatePythPriceFeeds){const t=n.filter(a=>!!a.pythPriceFeedId&&!!a.pythPriceInfoObject).map(a=>({priceFeedId:a.pythPriceFeedId,priceInfoObject:a.pythPriceInfoObject,expiration:30}));try{const a=await fe(t,o);a.length>0&&await ye(e,a,o)}catch{console.error("Failed to update Pyth price feeds")}}for(const t of n)o?.env==="dev"?e.moveCall({target:`${r.oracle.packageId}::oracle_pro::update_single_price`,arguments:[e.object("0x6"),e.object(r.oracle.oracleConfig),e.object(r.oracle.priceOracle),e.object(r.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.pure.address(t.feedId)]}):e.moveCall({target:`${r.oracle.packageId}::oracle_pro::update_single_price_v2`,arguments:[e.object("0x6"),e.object(r.oracle.oracleConfig),e.object(r.oracle.priceOracle),e.object(r.oracle.supraOracleHolder),e.object(t.pythPriceInfoObject),e.object(r.oracle.switchboardAggregator),e.pure.address(t.feedId)]});return e}async function Y(e){return(await k({...e,cacheTime:w})).oracle.feeds}function he(e,n){return e.filter(o=>!!(n?.lendingState&&n.lendingState.find(t=>t.assetId===o.assetId)||n?.lendingPositions&&n.lendingPositions.find(t=>["navi-lending-supply","navi-lending-borrow","navi-lending-emode-supply","navi-lending-emode-borrow"].includes(t.type)?t[t.type]?.pool?.id===o.assetId:!1)||n?.pools&&n.pools.find(t=>t.id===o.assetId)))}async function xe(e,n,o,r){try{const t=await Y({...r}),a=[];o.forEach(l=>{a.includes(l.market)||a.push(l.market)});const s=await me(n,{...r,markets:a}),c=he(t,{lendingPositions:s,pools:o});return await be(e,c,{updatePythPriceFeeds:!0,...r})}catch(t){if(r?.throws)throw t;return console.error(t),e}}const L=A(I(async e=>{const n=`https://open-api.naviprotocol.io/api/navi/flashloan?env=${e?.env||"prod"}&sdk=${$.version}&market=${e?.market||U}`,o=await fetch(n,{headers:V}).then(r=>r.json());return Object.keys(o.data).map(r=>({...o.data[r],coinType:r}))}));async function et(e,n){return(await L(n)).find(r=>typeof e=="string"?v(r.coinType)===v(e):typeof e=="number"?r.assetId===e:r.assetId===e.id)||null}async function tt(e,n,o,r){const t=await k({...r,cacheTime:w}),a=await P(n,r);if(!(await L({...r,cacheTime:w})).some(i=>v(i.coinType)===v(a.suiCoinType)))throw new Error("Pool does not support flashloan");if(t.version===1){const[i,l]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64)],typeArguments:[a.suiCoinType]});return[i,l]}else{const[i,l]=e.moveCall({target:`${t.package}::lending::flash_loan_with_ctx_v2`,arguments:[e.object(t.flashloanConfig),e.object(a.contract.pool),g(o,e.pure.u64),e.object("0x05")],typeArguments:[a.suiCoinType]});return[i,l]}}async function ot(e,n,o,r,t){const a=await k({...t,cacheTime:w}),s=await P(n,t);if(!(await L({...t,cacheTime:w})).some(m=>v(m.coinType)===v(s.suiCoinType)))throw new Error("Pool does not support flashloan");const[l]=e.moveCall({target:`${a.package}::lending::flash_repay_with_ctx`,arguments:[e.object("0x06"),e.object(a.storage),e.object(s.contract.pool),g(o,e.object),g(r,e.object)],typeArguments:[s.suiCoinType]});return[l]}async function nt(e,n,o,r,t,a){const s={...a,cacheTime:w},c=await k(s),i=await P(n,s),l=await P(r,s);if(c.version===1){const[m,f]=e.moveCall({target:`${c.package}::incentive_v3::liquidation`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(i.id),e.object(i.contract.pool),g(o,e.object),e.pure.u8(l.id),e.object(l.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3)],typeArguments:[i.suiCoinType,l.suiCoinType]});return[m,f]}else{const[m,f]=e.moveCall({target:`${c.package}::incentive_v3::liquidation_v2`,arguments:[e.object("0x06"),e.object(c.priceOracle),e.object(c.storage),e.pure.u8(i.id),e.object(i.contract.pool),g(o,e.object),e.pure.u8(l.id),e.object(l.contract.pool),g(t,e.pure.address),e.object(c.incentiveV2),e.object(c.incentiveV3),e.object("0x05")],typeArguments:[i.suiCoinType,l.suiCoinType]});return[m,f]}}async function rt(e,n,o){const r=o?.client??S,t=new F.Transaction,a=await N({...o,markets:Object.values(E),cacheTime:w}),s=await Y(o);for(let m of n){const f=await k({...o,cacheTime:w,market:m.market});t.moveCall({target:`${f.uiGetter}::incentive_v3_getter::get_user_atomic_claimable_rewards`,arguments:[t.object("0x06"),t.object(f.storage),t.object(f.incentiveV3),t.pure.address(m.address)]})}const c=await r.devInspectTransactionBlock({transactionBlock:t,sender:e}),i=[];c?.results?.forEach(m=>{i.push(R({results:[m]},[C.bcs.vector(C.bcs.string()),C.bcs.vector(C.bcs.string()),C.bcs.vector(C.bcs.u8()),C.bcs.vector(C.bcs.Address),C.bcs.vector(C.bcs.u256())]))});const l=[];return i.forEach((m,f)=>{const h=n[f];if(m.length===5&&Array.isArray(m[0])){const b=m[0].length;for(let p=0;p<b;p++){const y=s.find(j=>v(j.coinType)===v(m[1][p])),T=a.find(j=>v(j.coinType)===v(m[0][p]));!y||!T||l.push({assetId:T.id,assetCoinType:v(m[0][p]),rewardCoinType:v(m[1][p]),option:Number(m[2][p]),userClaimableReward:Number(m[4][p])/Math.pow(10,y.priceDecimal),ruleIds:Array.isArray(m[3][p])?m[3][p]:[m[3][p]],market:h.market,owner:h.address,emodeId:h.emodeId})}}}),l}async function at(e,n){const o=(n?.markets||[E.main]).map(a=>_(a)),r=await z(e,n),t=o.map(a=>({address:e,market:a.key})).concat(r.filter(a=>!!o.find(s=>s.id===a.marketId)).map(a=>{const s=_(a.marketId);return{address:e,market:s.key,emodeId:a.emodeId}}));return await rt(e,t,n)}function ct(e){const n=new Map;e.forEach(r=>{const t=r.assetId,a=r.option,s=`${t}-${a}-${r.rewardCoinType}-${r.market}`;n.has(s)?n.get(s).total+=r.userClaimableReward:n.set(s,{assetId:t,rewardType:a,coinType:r.rewardCoinType,total:Number(r.userClaimableReward),market:r.market})});const o=new Map;for(const{assetId:r,rewardType:t,coinType:a,total:s,market:c}of n.values()){const i=`${r}-${t}-${c}`;o.has(i)||o.set(i,{assetId:r,rewardType:t,market:c,rewards:new Map});const l=o.get(i);l.rewards.set(a,(l.rewards.get(a)||0)+s)}return Array.from(o.values()).map(r=>({assetId:r.assetId,rewardType:r.rewardType,market:r.market,rewards:Array.from(r.rewards.entries()).map(([t,a])=>({coinType:t,available:a.toFixed(6)}))}))}const st=I(async(e,n)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/total_claimed_reward?userAddress=${e}&sdk=${$.version}&market=${n?.market||U}`;return(await fetch(o,{headers:V}).then(t=>t.json())).data}),it=I(async(e,n)=>{const o=`https://open-api.naviprotocol.io/api/navi/user/rewards?userAddress=${e}&page=${n?.page||1}&pageSize=${n?.size||400}&sdk=${$.version}&market=${n?.market||U}`,r=await fetch(o,{headers:V}).then(t=>t.json());return H({data:r.data.rewards})});async function lt(e,n,o){const r=await k({...o,cacheTime:w}),t=await N({...o,markets:Object.values(E),cacheTime:w}),a=new Map;for(const c of n){const{rewardCoinType:i,ruleIds:l,market:m,owner:f,emodeId:h}=c,b=`${i}___${f}`;for(const p of l){a.has(b)||a.set(b,{assetIds:[],ruleIds:[],amount:0,market:m,owner:f,isEMode:typeof h<"u"});const y=a.get(b);y.assetIds.push(c.assetCoinType.replace("0x","")),y.ruleIds.push(p),y.amount+=c.userClaimableReward}}const s=[];for(const[c,{assetIds:i,ruleIds:l,amount:m,market:f,owner:h,isEMode:b}]of a){const p=c.split("___")[0],y=t.find(j=>v(j.suiCoinType)===v(p)&&j.market===f);if(!y||!y.contract.rewardFundId)throw new Error(`No matching rewardFund found for reward coin: ${p} ${f}`);const T=y.contract.rewardFundId;if(o?.accountCap&&!o.customCoinReceive)throw new Error("customCoinReceive is required when accountCap is provided");if(o?.customCoinReceive){let j;o.accountCap?j=e.moveCall({target:`${r.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(r.incentiveV3),e.object(r.storage),e.object(T),e.pure.vector("string",i),e.pure.vector("address",l),g(o.accountCap,e.object)],typeArguments:[p]}):b?j=e.moveCall({target:`${r.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(r.incentiveV3),e.object(r.storage),e.object(T),e.pure.vector("string",i),e.pure.vector("address",l),g(h,e.object)],typeArguments:[p]}):j=e.moveCall({target:`${r.package}::incentive_v3::claim_reward`,arguments:[e.object("0x06"),e.object(r.incentiveV3),e.object(r.storage),e.object(T),e.pure.vector("string",i),e.pure.vector("address",l)],typeArguments:[p]});const[O]=e.moveCall({target:"0x2::coin::from_balance",arguments:[j],typeArguments:[p]});if(o?.customCoinReceive.type==="transfer"){if(!o.customCoinReceive.transfer)throw new Error("customCoinReceive.transfer is required");e.transferObjects([O],g(o.customCoinReceive.transfer,e.pure.address))}if(o?.customCoinReceive.type==="depositNAVI"){const we=u(y.totalSupplyAmount).shiftedBy(-9),ve=u(y.supplyCapCeiling).shiftedBy(-27);we.plus(m).isGreaterThan(ve)&&o?.customCoinReceive.depositNAVI?.fallbackReceiveAddress?e.transferObjects([O],e.pure.address(o.customCoinReceive.depositNAVI.fallbackReceiveAddress)):await ae(e,y,O,o)}else s.push({coin:O,identifier:y,owner:h,isEMode:b})}else if(o?.accountCap||b){const j=e.moveCall({target:`${r.package}::incentive_v3::claim_reward_with_account_cap`,arguments:[e.object("0x06"),e.object(r.incentiveV3),e.object(r.storage),e.object(T),e.pure.vector("string",i),e.pure.vector("address",l),g(o?.accountCap||h,e.object)],typeArguments:[p]}),[O]=e.moveCall({target:"0x2::coin::from_balance",arguments:[j],typeArguments:[p]});e.transferObjects([O],g(o?.accountCap||h,e.pure.address))}else e.moveCall({target:`${r.package}::incentive_v3::claim_reward_entry`,arguments:[e.object("0x06"),e.object(r.incentiveV3),e.object(r.storage),e.object(T),e.pure.vector("string",i),e.pure.vector("address",l)],typeArguments:[p]})}return s}exports.Address=q;exports.DEFAULT_CACHE_TIME=w;exports.DEFAULT_MARKET_IDENTITY=U;exports.FlashLoanAssetConfig=Ie;exports.IncentiveAPYInfo=je;exports.IncentivePoolInfo=ee;exports.IncentivePoolInfoByPhase=_e;exports.MARKETS=E;exports.Market=ce;exports.OracleInfo=Te;exports.PoolOperator=D;exports.ReserveDataInfo=Be;exports.UserPositions=M;exports.UserStateInfo=te;exports.borrowCoinPTB=De;exports.claimLendingRewardsPTB=lt;exports.createAccountCapPTB=ie;exports.createEModeCapPTB=qe;exports.depositCoinPTB=ae;exports.emodeIdentityId=He;exports.enterEModePTB=ue;exports.exitEModePTB=Le;exports.filterPriceFeeds=he;exports.flashloanPTB=tt;exports.getAccountCapOwnerPTB=le;exports.getAllFlashLoanAssets=L;exports.getBorrowFee=Ne;exports.getCoins=Je;exports.getConfig=k;exports.getFees=Ue;exports.getFlashLoanAsset=et;exports.getHealthFactor=ze;exports.getHealthFactorPTB=pe;exports.getLendingPositions=me;exports.getLendingState=Ge;exports.getMarket=Re;exports.getMarketConfig=_;exports.getMarkets=se;exports.getPool=P;exports.getPools=N;exports.getPriceFeeds=Y;exports.getPythStalePriceFeedId=Xe;exports.getPythStalePriceFeedIdV2=fe;exports.getSimulatedHealthFactor=Ke;exports.getSimulatedHealthFactorPTB=K;exports.getStats=Me;exports.getTransactions=Ye;exports.getUserAvailableLendingRewards=at;exports.getUserClaimedRewardHistory=it;exports.getUserEModeCaps=z;exports.getUserTotalClaimedReward=st;exports.liquidatePTB=nt;exports.mergeCoinsPTB=We;exports.normalizeCoinType=v;exports.parsePoolUID=re;exports.parseTxValue=g;exports.repayCoinPTB=Fe;exports.repayFlashLoanPTB=ot;exports.summaryLendingRewards=ct;exports.updateOraclePriceBeforeUserOperationPTB=xe;exports.updateOraclePricesPTB=be;exports.updatePythPriceFeeds=ye;exports.verifyHealthFactorPTB=Qe;exports.withCache=A;exports.withSingleton=I;exports.withdrawCoinPTB=Oe;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|