@cetusprotocol/deepbook-utils 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -916,16 +916,17 @@ declare class MarginUtilsModule implements IModule {
|
|
|
916
916
|
* @returns {Promise<{baseAsset: string, quoteAsset: string}>} Object containing asset amounts
|
|
917
917
|
* @throws {Error} If parameters are invalid, scalars are missing, or transaction fails
|
|
918
918
|
*/
|
|
919
|
-
calculateAssets({ account, marginManager, pool, baseCoin, quoteCoin,
|
|
919
|
+
calculateAssets({ account, marginManager, pool, baseCoin, quoteCoin, tx, }: {
|
|
920
920
|
account: string;
|
|
921
921
|
marginManager: string;
|
|
922
922
|
pool: string;
|
|
923
923
|
baseCoin: MarginCoinInfo;
|
|
924
924
|
quoteCoin: MarginCoinInfo;
|
|
925
|
-
|
|
925
|
+
tx?: Transaction;
|
|
926
926
|
}): Promise<{
|
|
927
927
|
baseAsset: string;
|
|
928
928
|
quoteAsset: string;
|
|
929
|
+
tx: Transaction;
|
|
929
930
|
}>;
|
|
930
931
|
/**
|
|
931
932
|
* Gets the borrowed amount (in tokens, not shares) for a margin manager.
|
|
@@ -1110,7 +1111,7 @@ declare class MarginUtilsModule implements IModule {
|
|
|
1110
1111
|
* @returns {Promise<Transaction>} The transaction object with market order operation
|
|
1111
1112
|
* @throws {Error} If parameters are invalid or decimals are missing
|
|
1112
1113
|
*/
|
|
1113
|
-
placeMarginMarketOrder({ marginManager, poolInfo, selfMatchingOption, quantity, amountLimit, isBid, payWithDeep, exactBase }: {
|
|
1114
|
+
placeMarginMarketOrder({ marginManager, poolInfo, selfMatchingOption, quantity, amountLimit, isBid, payWithDeep, exactBase, }: {
|
|
1114
1115
|
marginManager: string | TransactionArgument;
|
|
1115
1116
|
poolInfo: MarginPoolInfo;
|
|
1116
1117
|
selfMatchingOption: SelfMatchingOption;
|
package/dist/index.js
CHANGED
|
@@ -12,4 +12,4 @@
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
`,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(s=>s?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(i=>i.parsedJson?.owner===e).map(i=>i?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get quote balance: ${s instanceof Error?s.message:String(s)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||s.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let o=j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),a=j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(s){throw new Error(`Failed to get borrowed shares: ${s instanceof Error?s.message:String(s)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:i,baseMarginPool:s,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:p})=>l=>{l.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.object(p),l.object(i),l.object(s),l.object(o),l.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new C.Transaction){let{account:r,marginManager:n,baseCoin:i,quoteCoin:s,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:p=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],t),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!b.results||!b.results[0]||!b.results[0].returnValues||b.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.effects?.status?.error||"Unknown error"}`);let _=(0,v.normalizeSuiAddress)(j.bcs.Address.parse(new Uint8Array(b.results[0].returnValues[0][0]))),O=(0,v.normalizeSuiAddress)(j.bcs.Address.parse(new Uint8Array(b.results[0].returnValues[1][0]))),f=Number(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[2][0])))/1e9,w=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[3][0]))),i.scalar,p),y=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[4][0]))),s.scalar,p),A=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[5][0]))),i.scalar,p),E=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[6][0]))),s.scalar,p),k=j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[7][0])),M=Number(j.bcs.u8().parse(new Uint8Array(b.results[0].returnValues[8][0]))),P=j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[9][0])),D=Number(j.bcs.u8().parse(new Uint8Array(b.results[0].returnValues[10][0]))),q=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[11][0]))),I=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[12][0]))),ne=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:O,riskRatio:f,baseAsset:w,quoteAsset:y,baseDebt:A,quoteDebt:E,basePythPrice:k.toString(),basePythDecimals:M,quotePythPrice:P.toString(),quotePythDecimals:D,currentPrice:q,lowestTriggerAbovePrice:I,highestTriggerBelowPrice:ne}}catch(l){throw new Error(`Failed to get manager state: ${l instanceof Error?l.message:String(l)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:i,decimals:s=6}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");let o=new C.Transaction;try{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[o.object(t),o.object(r)],typeArguments:[n.coinType,i.coinType]});let a=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o});if(!a.results||!a.results[0]||!a.results[0].returnValues||a.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${a.effects?.status?.error||"Unknown error"}`);let u=a.results[0].returnValues[0][0],p=a.results[0].returnValues[1][0];if(!n.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let l=j.bcs.U64.parse(new Uint8Array(u)),m=j.bcs.U64.parse(new Uint8Array(p));return{baseAsset:l.toString(),quoteAsset:m.toString()}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:i,quoteMarginPool:s}){if(!e||!t||!r||!n||!i||!s)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!d(o).gt(d(a)),p=u?i:s,l=u?o:a,m=new C.Transaction;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(p),m.pure.u64(BigInt(l)),m.object.clock()],typeArguments:[u?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let b=j.bcs.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:i},s=new C.Transaction){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Be.CoinAssist.buildCoinWithBalance(BigInt(n),i,s),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],s),u=a.get(t.feed),p=a.get(r.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?s.object(e):e,s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(u),s.object(p),o,s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType,i]}),s}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:i,quoteCoin:s,pool:o,amount:a,withdrawCoinType:u},p=new C.Transaction){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!i?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],p),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let b=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(m),p.object(g),p.object(o),p.pure.u64(BigInt(a)),p.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[i.coinType,s.coinType,u]});return p.transferObjects([b],e),p}catch(l){throw new Error(`Failed to withdraw: ${l instanceof Error?l.message:String(l)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C.Transaction){if(!e||!t||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C.Transaction){if(!e||!t||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:r.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:n.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:i,isBase:s,amount:o},a=new C.Transaction){try{let u=this.sdk.senderAddress,p,l=o;o||(p=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType,baseMarginPool:t,quoteMarginPool:r}),l=s?p.baseBorrowedAmount:p.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:i,depositCoinType:s?n.coinType:i.coinType};if(s){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}d(m).gt(0)&&await this.deposit({...g,amount:m},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${s?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,i.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:i,isBid:s,payWithDeep:o,exactBase:a},u=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!i||BigInt(W(i,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:l,quoteCoin:m}=t;if(l.decimals===void 0||m.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(p),u.pure.u8(r),u.pure.u64(n),u.pure.bool(s),u.pure.bool(o),u.pure.bool(a===void 0?!s:a),u.pure.u64(i),u.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[l.coinType,m.coinType]}),u}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:i,quantity:s,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},p=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!i||!s)throw new Error("Price and quantity are required");let{id:l,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let b=BigInt(d(i).mul(10**(g.decimals-m.decimals+9)).toString()),_=BigInt(W(s,m.decimals));if(b<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(l),p.pure.u8(r),p.pure.u8(n),p.pure.u64(b),p.pure.u64(_),p.pure.bool(o),p.pure.bool(a),p.pure.u64(u),p.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[m.coinType,g.coinType]}),p}catch(b){throw new Error(`Failed to place limit order: ${b instanceof Error?b.message:String(b)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},i=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let s=BigInt(W(n,t.baseCoin.decimals));if(s<=0n)throw new Error("New quantity must be greater than zero");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[i.object(this.sdk.sdkOptions.margin_utils.global_config_id),i.object(this.sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t.id),i.pure.u128(r),i.pure.u64(s),i.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),i}catch(s){throw new Error(`Failed to modify order: ${s instanceof Error?s.message:String(s)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new C.Transaction){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:i,priceInput:s,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:p},l=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(t.id),l.object(r),l.pure.u8(n),l.pure.u8(i),l.pure.u64(s),l.pure.u64(o),l.pure.bool(a),l.pure.bool(u),l.pure.u64(p),l.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),l}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:i,isBid:s,payWithDeep:o},a=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(i),a.pure.bool(s),a.pure.bool(o),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,s?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new C.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let i=new C.Transaction,s=t[n];if(s.margin_manager_id){let o=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(s.margin_manager_id)],typeArguments:[s.baseCoin.coinType,s.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(s,this.sdk.senderAddress,o,void 0,!0,i);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new C.Transaction,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v.SUI_CLOCK_OBJECT_ID)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new C.Transaction,{supplierCap:i}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([i],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:i}){let s=i??new C.Transaction;if(!t)throw new Error("Either supplierCap must be provided");let o=Be.CoinAssist.buildCoinWithBalance(BigInt(n),r,s);return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),o,s.pure.option("address","0x0"),s.object(v.SUI_CLOCK_OBJECT_ID)]}),s}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:i,withdrawAll:s,tx:o=new C.Transaction}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:s?null:o.pure.u64(r)}),o.object(v.SUI_CLOCK_OBJECT_ID)]});return i?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new C.Transaction,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new C.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,i=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:i}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let i=0;i<r.length;i++){let s=r[i].data.content.fields;n.push(Se(s))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],i=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;i.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let s=await this.sdk.fullClient.batchGetObjects(i,{showContent:!0}),o=[];for(let a=0;a<s.length;a++){let u=s[a].data.content.fields;o.push(je(u,n[a]))}return o}async getBaseQuantityOutInput(e,t,r){let n=new C.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let s=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),o=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),a=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0]));return{base_amount:s.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t){let r=new C.Transaction;r.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_out`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[r.object(e.address),r.pure.u64(t),r.object(v.SUI_CLOCK_OBJECT_ID)]});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:r});if(!n.results||!n.results[0]||!n.results[0].returnValues||!n.results[0].returnValues[0])throw new Error(`Transaction failed: ${n.effects?.status?.error||"Unknown error"}`);let i=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[0][0])),s=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[1][0])),o=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:s.toString(),deep_fee_amount:o.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new C.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new C.Transaction){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),i=e/n,s=e%n;if(s===0n)return i.toString();let o=t.toString().length-1,p=s.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${i}.${p}`:i.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,i=r.config.fields,s=i.interest_config.fields,o=i.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(s.base_rate),base_slope:BigInt(s.base_slope),optimal_utilization:BigInt(s.optimal_utilization),excess_slope:BigInt(s.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}};var Je=require("@mysten/sui/client"),te=class extends Je.SuiClient{async queryEventsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],i=!0,s=r==="all",o=s?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:s?null:r.limit});a.data?(n=[...n,...a.data],i=a.hasNextPage,o=a.nextCursor):i=!1}while(s&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let i=0;i<Math.ceil(e.length/r);i++){let s=await this.multiGetObjects({ids:e.slice(i*r,r*(i+1)),options:t});n=[...n,...s]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};var ve=qe(require("decimal.js"));ve.default.config({precision:64,rounding:ve.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var $=1000000000n,Ye=365n*24n*60n*60n*1000n;function Xe(c,e){return e===0n?0n:c*$/e}function et(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:i}=e;if(c<n)return t+c*r/$;{let s=c-n,o=n*r/$,a=s*i/$;return t+o+a}}function Me(c,e){let t=c*e,r=t/$;return t%$>0n?r+1n:r}function tt(c,e,t,r){let n=e.borrow_shares===0n?$:e.total_borrow*$/e.borrow_shares,i=Me(c,n),s=Xe(e.total_borrow,e.total_supply),o=et(s,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/$*a/Ye,p=e.borrow_shares===0n?0n:Me(u,c*$/e.borrow_shares),l=i+p;return{confirmedDebt:i,estimatedInterest:p,totalDebt:l,annualInterestRate:o}}function er(c,e,t,r,n=60000n){let i=r+n,{totalDebt:s}=tt(c,e,t,i);return s}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new Z(this),this._graphqlClient=new rt.SuiGraphQLClient({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],i=null,s=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(s,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:i}):this.fullClient.getAllCoins({owner:e,cursor:i}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:R(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),i=a.nextCursor,!a.hasNextPage)break}return this.updateCache(s,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var tr="0x0000000000000000000000000000000000000000000000000000000000000006",rr="pool_script",nr="pool_script_v2",sr="router",ir="router_with_partner",or="fetcher_script",ar="expect_swap",cr="utils",ur="0x1::coin::CoinInfo",dr="0x1::coin::CoinStore",lr="custodian_v2",pr="clob_v2",gr="endpoints_v2",mr=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var nt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(nt||{}),st=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(st||{});var br=re;0&&(module.exports={CLOCK_ADDRESS,CachedContent,CetusClmmSDK,ClmmExpectSwapModule,ClmmFetcherModule,ClmmIntegratePoolModule,ClmmIntegratePoolV2Module,ClmmIntegrateRouterModule,ClmmIntegrateRouterWithPartnerModule,ClmmIntegrateUtilsModule,CoinAssist,CoinInfoAddress,CoinStoreAddress,DEEP_SCALAR,DEFAULT_GAS_BUDGET_FOR_MERGE,DEFAULT_GAS_BUDGET_FOR_SPLIT,DEFAULT_GAS_BUDGET_FOR_STAKE,DEFAULT_GAS_BUDGET_FOR_TRANSFER,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,DEFAULT_NFT_TRANSFER_GAS_FEE,DeepbookClobV2Moudle,DeepbookCustodianV2Moudle,DeepbookEndpointsV2Moudle,DeepbookUtilsModule,FLOAT_SCALAR,FLOAT_SCALING,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,MarginUtilsModule,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,SelfMatchingOption,TransactionUtil,YEAR_MS,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime1min,cacheTime24h,cacheTime5min,calc100PercentRepay,calcDebtDetail,calcInterestRate,calcUtilizationRate,calculateRiskRatio,checkAddress,composeType,d,decimalsMultiplier,extractAddressFromType,extractStructTagFromType,fixCoinType,fixDown,fixSuiObjectId,fromDecimalsAmount,getDefaultSuiInputType,getFutureTime,getMoveObject,getMoveObjectType,getMovePackageContent,getObjectDeletedResponse,getObjectDisplay,getObjectFields,getObjectId,getObjectNotExistsResponse,getObjectOwner,getObjectPreviousTransactionDigest,getObjectReference,getObjectType,getObjectVersion,getSuiObjectData,hasPublicTransfer,hexToNumber,hexToString,isSortedSymbols,isSuiObjectResponse,maxDecimal,mulRoundUp,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,sleepTime,toBuffer,toDecimalsAmount,utf8to16,wrapDeepBookMarginPoolInfo,wrapDeepBookPoolInfo});
|
|
15
|
+
`,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(s=>s?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(i=>i.parsedJson?.owner===e).map(i=>i?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get quote balance: ${s instanceof Error?s.message:String(s)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C.Transaction;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||s.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let o=j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),a=j.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(s){throw new Error(`Failed to get borrowed shares: ${s instanceof Error?s.message:String(s)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:i,baseMarginPool:s,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:p})=>l=>{l.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.object(p),l.object(i),l.object(s),l.object(o),l.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new C.Transaction){let{account:r,marginManager:n,baseCoin:i,quoteCoin:s,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:p=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],t),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!b.results||!b.results[0]||!b.results[0].returnValues||b.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.effects?.status?.error||"Unknown error"}`);let _=(0,v.normalizeSuiAddress)(j.bcs.Address.parse(new Uint8Array(b.results[0].returnValues[0][0]))),O=(0,v.normalizeSuiAddress)(j.bcs.Address.parse(new Uint8Array(b.results[0].returnValues[1][0]))),f=Number(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[2][0])))/1e9,w=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[3][0]))),i.scalar,p),y=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[4][0]))),s.scalar,p),A=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[5][0]))),i.scalar,p),E=this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[6][0]))),s.scalar,p),k=j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[7][0])),M=Number(j.bcs.u8().parse(new Uint8Array(b.results[0].returnValues[8][0]))),P=j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[9][0])),D=Number(j.bcs.u8().parse(new Uint8Array(b.results[0].returnValues[10][0]))),q=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[11][0]))),I=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[12][0]))),ne=BigInt(j.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:O,riskRatio:f,baseAsset:w,quoteAsset:y,baseDebt:A,quoteDebt:E,basePythPrice:k.toString(),basePythDecimals:M,quotePythPrice:P.toString(),quotePythDecimals:D,currentPrice:q,lowestTriggerAbovePrice:I,highestTriggerBelowPrice:ne}}catch(l){throw new Error(`Failed to get manager state: ${l instanceof Error?l.message:String(l)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:i,tx:s=new C.Transaction}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[s.object(t),s.object(r)],typeArguments:[n.coinType,i.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],u=o.results[0].returnValues[1][0];if(!n.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let p=j.bcs.U64.parse(new Uint8Array(a)),l=j.bcs.U64.parse(new Uint8Array(u));return{baseAsset:p.toString(),quoteAsset:l.toString(),tx:s}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:i,quoteMarginPool:s}){if(!e||!t||!r||!n||!i||!s)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!d(o).gt(d(a)),p=u?i:s,l=u?o:a,m=new C.Transaction;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(p),m.pure.u64(BigInt(l)),m.object.clock()],typeArguments:[u?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let b=j.bcs.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:i},s=new C.Transaction){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Be.CoinAssist.buildCoinWithBalance(BigInt(n),i,s),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],s),u=a.get(t.feed),p=a.get(r.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?s.object(e):e,s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(u),s.object(p),o,s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType,i]}),s}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:i,quoteCoin:s,pool:o,amount:a,withdrawCoinType:u},p=new C.Transaction){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!i?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],p),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let b=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(m),p.object(g),p.object(o),p.pure.u64(BigInt(a)),p.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[i.coinType,s.coinType,u]});return p.transferObjects([b],e),p}catch(l){throw new Error(`Failed to withdraw: ${l instanceof Error?l.message:String(l)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C.Transaction){if(!e||!t||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C.Transaction){if(!e||!t||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:r.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:n.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:i,isBase:s,amount:o},a=new C.Transaction){try{let u=this.sdk.senderAddress,p,l=o;o||(p=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType,baseMarginPool:t,quoteMarginPool:r}),l=s?p.baseBorrowedAmount:p.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:i,depositCoinType:s?n.coinType:i.coinType};if(s){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}d(m).gt(0)&&await this.deposit({...g,amount:m},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${s?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,i.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:i,isBid:s,payWithDeep:o,exactBase:a},u=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!i||BigInt(W(i,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:l,quoteCoin:m}=t;if(l.decimals===void 0||m.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(p),u.pure.u8(r),u.pure.u64(n),u.pure.bool(s),u.pure.bool(o),u.pure.bool(a===void 0?!s:a),u.pure.u64(i),u.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[l.coinType,m.coinType]}),u}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:i,quantity:s,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},p=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!i||!s)throw new Error("Price and quantity are required");let{id:l,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let b=BigInt(d(i).mul(10**(g.decimals-m.decimals+9)).toString()),_=BigInt(W(s,m.decimals));if(b<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(l),p.pure.u8(r),p.pure.u8(n),p.pure.u64(b),p.pure.u64(_),p.pure.bool(o),p.pure.bool(a),p.pure.u64(u),p.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[m.coinType,g.coinType]}),p}catch(b){throw new Error(`Failed to place limit order: ${b instanceof Error?b.message:String(b)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},i=new C.Transaction){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let s=BigInt(W(n,t.baseCoin.decimals));if(s<=0n)throw new Error("New quantity must be greater than zero");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[i.object(this.sdk.sdkOptions.margin_utils.global_config_id),i.object(this.sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t.id),i.pure.u128(r),i.pure.u64(s),i.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),i}catch(s){throw new Error(`Failed to modify order: ${s instanceof Error?s.message:String(s)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new C.Transaction){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:i,priceInput:s,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:p},l=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(t.id),l.object(r),l.pure.u8(n),l.pure.u8(i),l.pure.u64(s),l.pure.u64(o),l.pure.bool(a),l.pure.bool(u),l.pure.u64(p),l.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),l}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:i,isBid:s,payWithDeep:o},a=new C.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(i),a.pure.bool(s),a.pure.bool(o),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,s?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new C.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let i=new C.Transaction,s=t[n];if(s.margin_manager_id){let o=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(s.margin_manager_id)],typeArguments:[s.baseCoin.coinType,s.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(s,this.sdk.senderAddress,o,void 0,!0,i);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new C.Transaction,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v.SUI_CLOCK_OBJECT_ID)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new C.Transaction,{supplierCap:i}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([i],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:i}){let s=i??new C.Transaction;if(!t)throw new Error("Either supplierCap must be provided");let o=Be.CoinAssist.buildCoinWithBalance(BigInt(n),r,s);return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),o,s.pure.option("address","0x0"),s.object(v.SUI_CLOCK_OBJECT_ID)]}),s}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:i,withdrawAll:s,tx:o=new C.Transaction}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:s?null:o.pure.u64(r)}),o.object(v.SUI_CLOCK_OBJECT_ID)]});return i?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new C.Transaction,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new C.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,i=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:i}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let i=0;i<r.length;i++){let s=r[i].data.content.fields;n.push(Se(s))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],i=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;i.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let s=await this.sdk.fullClient.batchGetObjects(i,{showContent:!0}),o=[];for(let a=0;a<s.length;a++){let u=s[a].data.content.fields;o.push(je(u,n[a]))}return o}async getBaseQuantityOutInput(e,t,r){let n=new C.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let s=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),o=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),a=j.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0]));return{base_amount:s.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t){let r=new C.Transaction;r.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_out`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[r.object(e.address),r.pure.u64(t),r.object(v.SUI_CLOCK_OBJECT_ID)]});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:r});if(!n.results||!n.results[0]||!n.results[0].returnValues||!n.results[0].returnValues[0])throw new Error(`Transaction failed: ${n.effects?.status?.error||"Unknown error"}`);let i=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[0][0])),s=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[1][0])),o=j.bcs.U64.parse(new Uint8Array(n.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:s.toString(),deep_fee_amount:o.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new C.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new C.Transaction){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),i=e/n,s=e%n;if(s===0n)return i.toString();let o=t.toString().length-1,p=s.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${i}.${p}`:i.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,i=r.config.fields,s=i.interest_config.fields,o=i.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(s.base_rate),base_slope:BigInt(s.base_slope),optimal_utilization:BigInt(s.optimal_utilization),excess_slope:BigInt(s.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}};var Je=require("@mysten/sui/client"),te=class extends Je.SuiClient{async queryEventsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],i=!0,s=r==="all",o=s?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:s?null:r.limit});a.data?(n=[...n,...a.data],i=a.hasNextPage,o=a.nextCursor):i=!1}while(s&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let i=0;i<Math.ceil(e.length/r);i++){let s=await this.multiGetObjects({ids:e.slice(i*r,r*(i+1)),options:t});n=[...n,...s]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};var ve=qe(require("decimal.js"));ve.default.config({precision:64,rounding:ve.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var $=1000000000n,Ye=365n*24n*60n*60n*1000n;function Xe(c,e){return e===0n?0n:c*$/e}function et(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:i}=e;if(c<n)return t+c*r/$;{let s=c-n,o=n*r/$,a=s*i/$;return t+o+a}}function Me(c,e){let t=c*e,r=t/$;return t%$>0n?r+1n:r}function tt(c,e,t,r){let n=e.borrow_shares===0n?$:e.total_borrow*$/e.borrow_shares,i=Me(c,n),s=Xe(e.total_borrow,e.total_supply),o=et(s,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/$*a/Ye,p=e.borrow_shares===0n?0n:Me(u,c*$/e.borrow_shares),l=i+p;return{confirmedDebt:i,estimatedInterest:p,totalDebt:l,annualInterestRate:o}}function er(c,e,t,r,n=60000n){let i=r+n,{totalDebt:s}=tt(c,e,t,i);return s}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new Z(this),this._graphqlClient=new rt.SuiGraphQLClient({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],i=null,s=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(s,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:i}):this.fullClient.getAllCoins({owner:e,cursor:i}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:R(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),i=a.nextCursor,!a.hasNextPage)break}return this.updateCache(s,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var tr="0x0000000000000000000000000000000000000000000000000000000000000006",rr="pool_script",nr="pool_script_v2",sr="router",ir="router_with_partner",or="fetcher_script",ar="expect_swap",cr="utils",ur="0x1::coin::CoinInfo",dr="0x1::coin::CoinStore",lr="custodian_v2",pr="clob_v2",gr="endpoints_v2",mr=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var nt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(nt||{}),st=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(st||{});var br=re;0&&(module.exports={CLOCK_ADDRESS,CachedContent,CetusClmmSDK,ClmmExpectSwapModule,ClmmFetcherModule,ClmmIntegratePoolModule,ClmmIntegratePoolV2Module,ClmmIntegrateRouterModule,ClmmIntegrateRouterWithPartnerModule,ClmmIntegrateUtilsModule,CoinAssist,CoinInfoAddress,CoinStoreAddress,DEEP_SCALAR,DEFAULT_GAS_BUDGET_FOR_MERGE,DEFAULT_GAS_BUDGET_FOR_SPLIT,DEFAULT_GAS_BUDGET_FOR_STAKE,DEFAULT_GAS_BUDGET_FOR_TRANSFER,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,DEFAULT_NFT_TRANSFER_GAS_FEE,DeepbookClobV2Moudle,DeepbookCustodianV2Moudle,DeepbookEndpointsV2Moudle,DeepbookUtilsModule,FLOAT_SCALAR,FLOAT_SCALING,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,MarginUtilsModule,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,SelfMatchingOption,TransactionUtil,YEAR_MS,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime1min,cacheTime24h,cacheTime5min,calc100PercentRepay,calcDebtDetail,calcInterestRate,calcUtilizationRate,calculateRiskRatio,checkAddress,composeType,d,decimalsMultiplier,extractAddressFromType,extractStructTagFromType,fixCoinType,fixDown,fixSuiObjectId,fromDecimalsAmount,getDefaultSuiInputType,getFutureTime,getMoveObject,getMoveObjectType,getMovePackageContent,getObjectDeletedResponse,getObjectDisplay,getObjectFields,getObjectId,getObjectNotExistsResponse,getObjectOwner,getObjectPreviousTransactionDigest,getObjectReference,getObjectType,getObjectVersion,getSuiObjectData,hasPublicTransfer,hexToNumber,hexToString,isSortedSymbols,isSuiObjectResponse,maxDecimal,mulRoundUp,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,sleepTime,toBuffer,toDecimalsAmount,utf8to16,wrapDeepBookMarginPoolInfo,wrapDeepBookPoolInfo});
|
package/dist/index.mjs
CHANGED
|
@@ -12,4 +12,4 @@ var Ve=Object.defineProperty;var Ne=(c,e,t)=>e in c?Ve(c,e,{enumerable:!0,config
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
`,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(s=>s?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(i=>i.parsedJson?.owner===e).map(i=>i?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get quote balance: ${s instanceof Error?s.message:String(s)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||s.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let o=S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),a=S.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(s){throw new Error(`Failed to get borrowed shares: ${s instanceof Error?s.message:String(s)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:i,baseMarginPool:s,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:p})=>l=>{l.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.object(p),l.object(i),l.object(s),l.object(o),l.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new C){let{account:r,marginManager:n,baseCoin:i,quoteCoin:s,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:p=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],t),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!b.results||!b.results[0]||!b.results[0].returnValues||b.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.effects?.status?.error||"Unknown error"}`);let _=Re(S.Address.parse(new Uint8Array(b.results[0].returnValues[0][0]))),A=Re(S.Address.parse(new Uint8Array(b.results[0].returnValues[1][0]))),f=Number(S.U64.parse(new Uint8Array(b.results[0].returnValues[2][0])))/1e9,w=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[3][0]))),i.scalar,p),y=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[4][0]))),s.scalar,p),T=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[5][0]))),i.scalar,p),j=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[6][0]))),s.scalar,p),k=S.U64.parse(new Uint8Array(b.results[0].returnValues[7][0])),B=Number(S.u8().parse(new Uint8Array(b.results[0].returnValues[8][0]))),M=S.U64.parse(new Uint8Array(b.results[0].returnValues[9][0])),D=Number(S.u8().parse(new Uint8Array(b.results[0].returnValues[10][0]))),P=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[11][0]))),I=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[12][0]))),Z=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:A,riskRatio:f,baseAsset:w,quoteAsset:y,baseDebt:T,quoteDebt:j,basePythPrice:k.toString(),basePythDecimals:B,quotePythPrice:M.toString(),quotePythDecimals:D,currentPrice:P,lowestTriggerAbovePrice:I,highestTriggerBelowPrice:Z}}catch(l){throw new Error(`Failed to get manager state: ${l instanceof Error?l.message:String(l)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:i,decimals:s=6}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");let o=new C;try{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[o.object(t),o.object(r)],typeArguments:[n.coinType,i.coinType]});let a=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o});if(!a.results||!a.results[0]||!a.results[0].returnValues||a.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${a.effects?.status?.error||"Unknown error"}`);let u=a.results[0].returnValues[0][0],p=a.results[0].returnValues[1][0];if(!n.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let l=S.U64.parse(new Uint8Array(u)),m=S.U64.parse(new Uint8Array(p));return{baseAsset:l.toString(),quoteAsset:m.toString()}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:i,quoteMarginPool:s}){if(!e||!t||!r||!n||!i||!s)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!d(o).gt(d(a)),p=u?i:s,l=u?o:a,m=new C;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(p),m.pure.u64(BigInt(l)),m.object.clock()],typeArguments:[u?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let b=S.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:i},s=new C){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Ue.buildCoinWithBalance(BigInt(n),i,s),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],s),u=a.get(t.feed),p=a.get(r.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?s.object(e):e,s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(u),s.object(p),o,s.object(v)],typeArguments:[t.coinType,r.coinType,i]}),s}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:i,quoteCoin:s,pool:o,amount:a,withdrawCoinType:u},p=new C){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!i?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],p),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let b=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(m),p.object(g),p.object(o),p.pure.u64(BigInt(a)),p.object(v)],typeArguments:[i.coinType,s.coinType,u]});return p.transferObjects([b],e),p}catch(l){throw new Error(`Failed to withdraw: ${l instanceof Error?l.message:String(l)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C){if(!e||!t||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C){if(!e||!t||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:r.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:n.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:i,isBase:s,amount:o},a=new C){try{let u=this.sdk.senderAddress,p,l=o;o||(p=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType,baseMarginPool:t,quoteMarginPool:r}),l=s?p.baseBorrowedAmount:p.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:i,depositCoinType:s?n.coinType:i.coinType};if(s){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}d(m).gt(0)&&await this.deposit({...g,amount:m},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${s?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v)],typeArguments:[n.coinType,i.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:i,isBid:s,payWithDeep:o,exactBase:a},u=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!i||BigInt(W(i,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:l,quoteCoin:m}=t;if(l.decimals===void 0||m.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(p),u.pure.u8(r),u.pure.u64(n),u.pure.bool(s),u.pure.bool(o),u.pure.bool(a===void 0?!s:a),u.pure.u64(i),u.object(v)],typeArguments:[l.coinType,m.coinType]}),u}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:i,quantity:s,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},p=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!i||!s)throw new Error("Price and quantity are required");let{id:l,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let b=BigInt(d(i).mul(10**(g.decimals-m.decimals+9)).toString()),_=BigInt(W(s,m.decimals));if(b<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(l),p.pure.u8(r),p.pure.u8(n),p.pure.u64(b),p.pure.u64(_),p.pure.bool(o),p.pure.bool(a),p.pure.u64(u),p.object(v)],typeArguments:[m.coinType,g.coinType]}),p}catch(b){throw new Error(`Failed to place limit order: ${b instanceof Error?b.message:String(b)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},i=new C){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let s=BigInt(W(n,t.baseCoin.decimals));if(s<=0n)throw new Error("New quantity must be greater than zero");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[i.object(this.sdk.sdkOptions.margin_utils.global_config_id),i.object(this.sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t.id),i.pure.u128(r),i.pure.u64(s),i.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),i}catch(s){throw new Error(`Failed to modify order: ${s instanceof Error?s.message:String(s)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new C){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:i,priceInput:s,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:p},l=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(t.id),l.object(r),l.pure.u8(n),l.pure.u8(i),l.pure.u64(s),l.pure.u64(o),l.pure.bool(a),l.pure.bool(u),l.pure.u64(p),l.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),l}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:i,isBid:s,payWithDeep:o},a=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(i),a.pure.bool(s),a.pure.bool(o),a.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,s?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new C,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let i=new C,s=t[n];if(s.margin_manager_id){let o=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(s.margin_manager_id)],typeArguments:[s.baseCoin.coinType,s.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(s,this.sdk.senderAddress,o,void 0,!0,i);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new C,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new C,{supplierCap:i}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([i],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:i}){let s=i??new C;if(!t)throw new Error("Either supplierCap must be provided");let o=Ue.buildCoinWithBalance(BigInt(n),r,s);return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),o,s.pure.option("address","0x0"),s.object(v)]}),s}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:i,withdrawAll:s,tx:o=new C}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:s?null:o.pure.u64(r)}),o.object(v)]});return i?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new C,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new C;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(S.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,i=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:i}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let i=0;i<r.length;i++){let s=r[i].data.content.fields;n.push(De(s))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],i=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;i.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let s=await this.sdk.fullClient.batchGetObjects(i,{showContent:!0}),o=[];for(let a=0;a<s.length;a++){let u=s[a].data.content.fields;o.push(Ie(u,n[a]))}return o}async getBaseQuantityOutInput(e,t,r){let n=new C;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let s=S.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),o=S.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),a=S.U64.parse(new Uint8Array(i.results[0].returnValues[2][0]));return{base_amount:s.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t){let r=new C;r.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_out`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[r.object(e.address),r.pure.u64(t),r.object(v)]});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:r});if(!n.results||!n.results[0]||!n.results[0].returnValues||!n.results[0].returnValues[0])throw new Error(`Transaction failed: ${n.effects?.status?.error||"Unknown error"}`);let i=S.U64.parse(new Uint8Array(n.results[0].returnValues[0][0])),s=S.U64.parse(new Uint8Array(n.results[0].returnValues[1][0])),o=S.U64.parse(new Uint8Array(n.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:s.toString(),deep_fee_amount:o.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new C,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new C){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),i=e/n,s=e%n;if(s===0n)return i.toString();let o=t.toString().length-1,p=s.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${i}.${p}`:i.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,i=r.config.fields,s=i.interest_config.fields,o=i.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(s.base_rate),base_slope:BigInt(s.base_slope),optimal_utilization:BigInt(s.optimal_utilization),excess_slope:BigInt(s.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}};import{SuiClient as bt}from"@mysten/sui/client";var te=class extends bt{async queryEventsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],i=!0,s=r==="all",o=s?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:s?null:r.limit});a.data?(n=[...n,...a.data],i=a.hasNextPage,o=a.nextCursor):i=!1}while(s&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let i=0;i<Math.ceil(e.length/r);i++){let s=await this.multiGetObjects({ids:e.slice(i*r,r*(i+1)),options:t});n=[...n,...s]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};import $e from"decimal.js";$e.config({precision:64,rounding:$e.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var F=1000000000n,_t=365n*24n*60n*60n*1000n;function ht(c,e){return e===0n?0n:c*F/e}function yt(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:i}=e;if(c<n)return t+c*r/F;{let s=c-n,o=n*r/F,a=s*i/F;return t+o+a}}function Fe(c,e){let t=c*e,r=t/F;return t%F>0n?r+1n:r}function ft(c,e,t,r){let n=e.borrow_shares===0n?F:e.total_borrow*F/e.borrow_shares,i=Fe(c,n),s=ht(e.total_borrow,e.total_supply),o=yt(s,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/F*a/_t,p=e.borrow_shares===0n?0n:Fe(u,c*F/e.borrow_shares),l=i+p;return{confirmedDebt:i,estimatedInterest:p,totalDebt:l,annualInterestRate:o}}function sn(c,e,t,r,n=60000n){let i=r+n,{totalDebt:s}=ft(c,e,t,i);return s}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new H(this),this._graphqlClient=new wt({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],i=null,s=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(s,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:i}):this.fullClient.getAllCoins({owner:e,cursor:i}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:$(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),i=a.nextCursor,!a.hasNextPage)break}return this.updateCache(s,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var jn="0x0000000000000000000000000000000000000000000000000000000000000006",En="pool_script",Bn="pool_script_v2",vn="router",Mn="router_with_partner",Pn="fetcher_script",qn="expect_swap",Dn="utils",In="0x1::coin::CoinInfo",Un="0x1::coin::CoinStore",Rn="custodian_v2",$n="clob_v2",Fn="endpoints_v2",Vn=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var kt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(kt||{}),Ct=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(Ct||{});var es=re;export{jn as CLOCK_ADDRESS,K as CachedContent,re as CetusClmmSDK,qn as ClmmExpectSwapModule,Pn as ClmmFetcherModule,En as ClmmIntegratePoolModule,Bn as ClmmIntegratePoolV2Module,vn as ClmmIntegrateRouterModule,Mn as ClmmIntegrateRouterWithPartnerModule,Dn as ClmmIntegrateUtilsModule,E as CoinAssist,In as CoinInfoAddress,Un as CoinStoreAddress,le as DEEP_SCALAR,Nt as DEFAULT_GAS_BUDGET_FOR_MERGE,Vt as DEFAULT_GAS_BUDGET_FOR_SPLIT,Gt as DEFAULT_GAS_BUDGET_FOR_STAKE,xt as DEFAULT_GAS_BUDGET_FOR_TRANSFER,Lt as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,zt as DEFAULT_NFT_TRANSFER_GAS_FEE,$n as DeepbookClobV2Moudle,Rn as DeepbookCustodianV2Moudle,Fn as DeepbookEndpointsV2Moudle,X as DeepbookUtilsModule,R as FLOAT_SCALAR,F as FLOAT_SCALING,Kt as GAS_SYMBOL,ae as GAS_TYPE_ARG,ye as GAS_TYPE_ARG_LONG,ee as MarginUtilsModule,Ut as NORMALIZED_SUI_COIN_TYPE,kt as OrderType,te as RpcModule,Qt as SUI_SYSTEM_STATE_OBJECT_ID,Ct as SelfMatchingOption,N as TransactionUtil,_t as YEAR_MS,me as addHexPrefix,nr as asIntN,rr as asUintN,St as bufferToHex,we as cacheTime1min,x as cacheTime24h,ke as cacheTime5min,sn as calc100PercentRepay,ft as calcDebtDetail,yt as calcInterestRate,ht as calcUtilizationRate,Fr as calculateRiskRatio,Ot as checkAddress,_e as composeType,d,ce as decimalsMultiplier,es as default,Dt as extractAddressFromType,$ as extractStructTagFromType,It as fixCoinType,L as fixDown,Je as fixSuiObjectId,G as fromDecimalsAmount,Vn as getDefaultSuiInputType,z as getFutureTime,de as getMoveObject,st as getMoveObjectType,dr as getMovePackageContent,et as getObjectDeletedResponse,mr as getObjectDisplay,Pe as getObjectFields,Me as getObjectId,tt as getObjectNotExistsResponse,gr as getObjectOwner,pr as getObjectPreviousTransactionDigest,ve as getObjectReference,lr as getObjectType,ur as getObjectVersion,Q as getSuiObjectData,br as hasPublicTransfer,jt as hexToNumber,Et as hexToString,qt as isSortedSymbols,rt as isSuiObjectResponse,ue as maxDecimal,Fe as mulRoundUp,ie as normalizeCoinType,oe as patchFixSuiObjectId,fr as printTransaction,ne as removeHexPrefix,sr as secretKeyToEd25519Keypair,ir as secretKeyToSecp256k1Keypair,At as shortAddress,Le as shortString,Se as sleepTime,Ge as toBuffer,W as toDecimalsAmount,Ke as utf8to16,Ie as wrapDeepBookMarginPoolInfo,De as wrapDeepBookPoolInfo};
|
|
15
|
+
`,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(s=>s?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(i=>i.parsedJson?.owner===e).map(i=>i?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get quote balance: ${s instanceof Error?s.message:String(s)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])).toString()}catch(s){throw new Error(`Failed to get base balance: ${s instanceof Error?s.message:String(s)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new C;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(t)],typeArguments:[r,n]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!s.results||!s.results[0]||!s.results[0].returnValues||s.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let o=S.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),a=S.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(s){throw new Error(`Failed to get borrowed shares: ${s instanceof Error?s.message:String(s)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:i,baseMarginPool:s,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:p})=>l=>{l.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.object(p),l.object(i),l.object(s),l.object(o),l.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new C){let{account:r,marginManager:n,baseCoin:i,quoteCoin:s,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:p=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],t),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!b.results||!b.results[0]||!b.results[0].returnValues||b.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.effects?.status?.error||"Unknown error"}`);let _=Re(S.Address.parse(new Uint8Array(b.results[0].returnValues[0][0]))),A=Re(S.Address.parse(new Uint8Array(b.results[0].returnValues[1][0]))),f=Number(S.U64.parse(new Uint8Array(b.results[0].returnValues[2][0])))/1e9,w=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[3][0]))),i.scalar,p),y=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[4][0]))),s.scalar,p),T=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[5][0]))),i.scalar,p),j=this.#e(BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[6][0]))),s.scalar,p),k=S.U64.parse(new Uint8Array(b.results[0].returnValues[7][0])),B=Number(S.u8().parse(new Uint8Array(b.results[0].returnValues[8][0]))),M=S.U64.parse(new Uint8Array(b.results[0].returnValues[9][0])),D=Number(S.u8().parse(new Uint8Array(b.results[0].returnValues[10][0]))),P=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[11][0]))),I=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[12][0]))),Z=BigInt(S.U64.parse(new Uint8Array(b.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:A,riskRatio:f,baseAsset:w,quoteAsset:y,baseDebt:T,quoteDebt:j,basePythPrice:k.toString(),basePythDecimals:B,quotePythPrice:M.toString(),quotePythDecimals:D,currentPrice:P,lowestTriggerAbovePrice:I,highestTriggerBelowPrice:Z}}catch(l){throw new Error(`Failed to get manager state: ${l instanceof Error?l.message:String(l)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:i,tx:s=new C}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[s.object(t),s.object(r)],typeArguments:[n.coinType,i.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],u=o.results[0].returnValues[1][0];if(!n.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let p=S.U64.parse(new Uint8Array(a)),l=S.U64.parse(new Uint8Array(u));return{baseAsset:p.toString(),quoteAsset:l.toString(),tx:s}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:i,quoteMarginPool:s}){if(!e||!t||!r||!n||!i||!s)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!d(o).gt(d(a)),p=u?i:s,l=u?o:a,m=new C;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(p),m.pure.u64(BigInt(l)),m.object.clock()],typeArguments:[u?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let b=S.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:i},s=new C){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Ue.buildCoinWithBalance(BigInt(n),i,s),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],s),u=a.get(t.feed),p=a.get(r.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?s.object(e):e,s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(u),s.object(p),o,s.object(v)],typeArguments:[t.coinType,r.coinType,i]}),s}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:i,quoteCoin:s,pool:o,amount:a,withdrawCoinType:u},p=new C){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!i?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let l=await this.pythPrice.updatePythPriceIDs([i.feed,s.feed],p),m=l.get(i.feed),g=l.get(s.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let b=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(m),p.object(g),p.object(o),p.pure.u64(BigInt(a)),p.object(v)],typeArguments:[i.coinType,s.coinType,u]});return p.transferObjects([b],e),p}catch(l){throw new Error(`Failed to withdraw: ${l instanceof Error?l.message:String(l)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C){if(!e||!t||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:i,amount:s},o=new C){if(!e||!t||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(i),o.pure.u64(BigInt(s)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:r.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:i},s=new C){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(i&&BigInt(i)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:i,depositCoinType:n.coinType};await this.deposit(o,s);try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),s.object.option({type:"u64",value:i?s.pure.u64(i):null}),s.object(v)],typeArguments:[r.coinType,n.coinType]}),s}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:i,isBase:s,amount:o},a=new C){try{let u=this.sdk.senderAddress,p,l=o;o||(p=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType,baseMarginPool:t,quoteMarginPool:r}),l=s?p.baseBorrowedAmount:p.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:i,depositCoinType:s?n.coinType:i.coinType};if(s){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:i?.coinType});m=d(l).sub(b).toString()}d(m).gt(0)&&await this.deposit({...g,amount:m},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${s?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v)],typeArguments:[n.coinType,i.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:i,isBid:s,payWithDeep:o,exactBase:a},u=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!i||BigInt(W(i,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:l,quoteCoin:m}=t;if(l.decimals===void 0||m.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(p),u.pure.u8(r),u.pure.u64(n),u.pure.bool(s),u.pure.bool(o),u.pure.bool(a===void 0?!s:a),u.pure.u64(i),u.object(v)],typeArguments:[l.coinType,m.coinType]}),u}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:i,quantity:s,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},p=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!i||!s)throw new Error("Price and quantity are required");let{id:l,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let b=BigInt(d(i).mul(10**(g.decimals-m.decimals+9)).toString()),_=BigInt(W(s,m.decimals));if(b<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(l),p.pure.u8(r),p.pure.u8(n),p.pure.u64(b),p.pure.u64(_),p.pure.bool(o),p.pure.bool(a),p.pure.u64(u),p.object(v)],typeArguments:[m.coinType,g.coinType]}),p}catch(b){throw new Error(`Failed to place limit order: ${b instanceof Error?b.message:String(b)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},i=new C){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let s=BigInt(W(n,t.baseCoin.decimals));if(s<=0n)throw new Error("New quantity must be greater than zero");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[i.object(this.sdk.sdkOptions.margin_utils.global_config_id),i.object(this.sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t.id),i.pure.u128(r),i.pure.u64(s),i.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),i}catch(s){throw new Error(`Failed to modify order: ${s instanceof Error?s.message:String(s)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new C){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:i,priceInput:s,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:p},l=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(t.id),l.object(r),l.pure.u8(n),l.pure.u8(i),l.pure.u64(s),l.pure.u64(o),l.pure.bool(a),l.pure.bool(u),l.pure.u64(p),l.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),l}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:i,isBid:s,payWithDeep:o},a=new C){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(i),a.pure.bool(s),a.pure.bool(o),a.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,s?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new C,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let i=new C,s=t[n];if(s.margin_manager_id){let o=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(s.margin_manager_id)],typeArguments:[s.baseCoin.coinType,s.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(s,this.sdk.senderAddress,o,void 0,!0,i);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new C,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new C,{supplierCap:i}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([i],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:i}){let s=i??new C;if(!t)throw new Error("Either supplierCap must be provided");let o=Ue.buildCoinWithBalance(BigInt(n),r,s);return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[s.object(this._sdk.sdkOptions.margin_utils.global_config_id),s.object(this._sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t),o,s.pure.option("address","0x0"),s.object(v)]}),s}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:i,withdrawAll:s,tx:o=new C}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:s?null:o.pure.u64(r)}),o.object(v)]});return i?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new C,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new C;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(S.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,i=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:i}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let i=0;i<r.length;i++){let s=r[i].data.content.fields;n.push(De(s))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],i=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;i.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let s=await this.sdk.fullClient.batchGetObjects(i,{showContent:!0}),o=[];for(let a=0;a<s.length;a++){let u=s[a].data.content.fields;o.push(Ie(u,n[a]))}return o}async getBaseQuantityOutInput(e,t,r){let n=new C;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let s=S.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),o=S.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),a=S.U64.parse(new Uint8Array(i.results[0].returnValues[2][0]));return{base_amount:s.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t){let r=new C;r.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_out`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[r.object(e.address),r.pure.u64(t),r.object(v)]});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:r});if(!n.results||!n.results[0]||!n.results[0].returnValues||!n.results[0].returnValues[0])throw new Error(`Transaction failed: ${n.effects?.status?.error||"Unknown error"}`);let i=S.U64.parse(new Uint8Array(n.results[0].returnValues[0][0])),s=S.U64.parse(new Uint8Array(n.results[0].returnValues[1][0])),o=S.U64.parse(new Uint8Array(n.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:s.toString(),deep_fee_amount:o.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new C,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new C){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),i=e/n,s=e%n;if(s===0n)return i.toString();let o=t.toString().length-1,p=s.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${i}.${p}`:i.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,i=r.config.fields,s=i.interest_config.fields,o=i.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(s.base_rate),base_slope:BigInt(s.base_slope),optimal_utilization:BigInt(s.optimal_utilization),excess_slope:BigInt(s.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}};import{SuiClient as bt}from"@mysten/sui/client";var te=class extends bt{async queryEventsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],i=!0,s=r==="all",o=s?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:s?null:r.limit});a.data?(n=[...n,...a.data],i=a.hasNextPage,o=a.nextCursor):i=!1}while(s&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,i=t==="all",s=i?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:s,limit:i?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,s=o.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:s,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let i=0;i<Math.ceil(e.length/r);i++){let s=await this.multiGetObjects({ids:e.slice(i*r,r*(i+1)),options:t});n=[...n,...s]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};import $e from"decimal.js";$e.config({precision:64,rounding:$e.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var F=1000000000n,_t=365n*24n*60n*60n*1000n;function ht(c,e){return e===0n?0n:c*F/e}function yt(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:i}=e;if(c<n)return t+c*r/F;{let s=c-n,o=n*r/F,a=s*i/F;return t+o+a}}function Fe(c,e){let t=c*e,r=t/F;return t%F>0n?r+1n:r}function ft(c,e,t,r){let n=e.borrow_shares===0n?F:e.total_borrow*F/e.borrow_shares,i=Fe(c,n),s=ht(e.total_borrow,e.total_supply),o=yt(s,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/F*a/_t,p=e.borrow_shares===0n?0n:Fe(u,c*F/e.borrow_shares),l=i+p;return{confirmedDebt:i,estimatedInterest:p,totalDebt:l,annualInterestRate:o}}function sn(c,e,t,r,n=60000n){let i=r+n,{totalDebt:s}=ft(c,e,t,i);return s}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new H(this),this._graphqlClient=new wt({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],i=null,s=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(s,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:i}):this.fullClient.getAllCoins({owner:e,cursor:i}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:$(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),i=a.nextCursor,!a.hasNextPage)break}return this.updateCache(s,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var jn="0x0000000000000000000000000000000000000000000000000000000000000006",En="pool_script",Bn="pool_script_v2",vn="router",Mn="router_with_partner",Pn="fetcher_script",qn="expect_swap",Dn="utils",In="0x1::coin::CoinInfo",Un="0x1::coin::CoinStore",Rn="custodian_v2",$n="clob_v2",Fn="endpoints_v2",Vn=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var kt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(kt||{}),Ct=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(Ct||{});var es=re;export{jn as CLOCK_ADDRESS,K as CachedContent,re as CetusClmmSDK,qn as ClmmExpectSwapModule,Pn as ClmmFetcherModule,En as ClmmIntegratePoolModule,Bn as ClmmIntegratePoolV2Module,vn as ClmmIntegrateRouterModule,Mn as ClmmIntegrateRouterWithPartnerModule,Dn as ClmmIntegrateUtilsModule,E as CoinAssist,In as CoinInfoAddress,Un as CoinStoreAddress,le as DEEP_SCALAR,Nt as DEFAULT_GAS_BUDGET_FOR_MERGE,Vt as DEFAULT_GAS_BUDGET_FOR_SPLIT,Gt as DEFAULT_GAS_BUDGET_FOR_STAKE,xt as DEFAULT_GAS_BUDGET_FOR_TRANSFER,Lt as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,zt as DEFAULT_NFT_TRANSFER_GAS_FEE,$n as DeepbookClobV2Moudle,Rn as DeepbookCustodianV2Moudle,Fn as DeepbookEndpointsV2Moudle,X as DeepbookUtilsModule,R as FLOAT_SCALAR,F as FLOAT_SCALING,Kt as GAS_SYMBOL,ae as GAS_TYPE_ARG,ye as GAS_TYPE_ARG_LONG,ee as MarginUtilsModule,Ut as NORMALIZED_SUI_COIN_TYPE,kt as OrderType,te as RpcModule,Qt as SUI_SYSTEM_STATE_OBJECT_ID,Ct as SelfMatchingOption,N as TransactionUtil,_t as YEAR_MS,me as addHexPrefix,nr as asIntN,rr as asUintN,St as bufferToHex,we as cacheTime1min,x as cacheTime24h,ke as cacheTime5min,sn as calc100PercentRepay,ft as calcDebtDetail,yt as calcInterestRate,ht as calcUtilizationRate,Fr as calculateRiskRatio,Ot as checkAddress,_e as composeType,d,ce as decimalsMultiplier,es as default,Dt as extractAddressFromType,$ as extractStructTagFromType,It as fixCoinType,L as fixDown,Je as fixSuiObjectId,G as fromDecimalsAmount,Vn as getDefaultSuiInputType,z as getFutureTime,de as getMoveObject,st as getMoveObjectType,dr as getMovePackageContent,et as getObjectDeletedResponse,mr as getObjectDisplay,Pe as getObjectFields,Me as getObjectId,tt as getObjectNotExistsResponse,gr as getObjectOwner,pr as getObjectPreviousTransactionDigest,ve as getObjectReference,lr as getObjectType,ur as getObjectVersion,Q as getSuiObjectData,br as hasPublicTransfer,jt as hexToNumber,Et as hexToString,qt as isSortedSymbols,rt as isSuiObjectResponse,ue as maxDecimal,Fe as mulRoundUp,ie as normalizeCoinType,oe as patchFixSuiObjectId,fr as printTransaction,ne as removeHexPrefix,sr as secretKeyToEd25519Keypair,ir as secretKeyToSecp256k1Keypair,At as shortAddress,Le as shortString,Se as sleepTime,Ge as toBuffer,W as toDecimalsAmount,Ke as utf8to16,Ie as wrapDeepBookMarginPoolInfo,De as wrapDeepBookPoolInfo};
|