@cetusprotocol/deepbook-utils 1.4.9 → 1.5.1
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 -0
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1522,6 +1522,10 @@ declare class MarginUtilsModule implements IModule {
|
|
|
1522
1522
|
supply_cap: bigint;
|
|
1523
1523
|
};
|
|
1524
1524
|
}>;
|
|
1525
|
+
getMarginPoolStateForInterestList(marginPoolIds: string[]): Promise<{
|
|
1526
|
+
poolStateObj: any;
|
|
1527
|
+
poolStateList: any;
|
|
1528
|
+
}>;
|
|
1525
1529
|
/**
|
|
1526
1530
|
* Gets the current chain timestamp from the Sui network.
|
|
1527
1531
|
* Use this timestamp for interest calculations instead of local Date.now().
|
package/dist/index.js
CHANGED
|
@@ -1021,7 +1021,7 @@ Clients should implement reconnection logic to maintain continuous price updates
|
|
|
1021
1021
|
}
|
|
1022
1022
|
}
|
|
1023
1023
|
}
|
|
1024
|
-
`);var _x=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];var u$=ru("mainnet"),l$=ru("testnet");var d$=E.struct("Table<ID, bool>",{id:E.Address,size:E.u64()}),wx=E.struct("TypeName",{name:E.string()}),p$=E.struct("OptionU64",{is_none:E.bool(),v:E.u64()}),Tx=E.struct("UID",{id:E.Address}),f$=E.struct("TableSuiRaw",{id:Tx,size:E.u64()});var kx=class{constructor(e,t,n,r){this._cache={},this._env="mainnet",this._client=e,this._env=n||"mainnet",this._graphQLClient=t,this._jsonRpcClient=r}async fetchCoinMetadata(e){let t=`coin_metadata_${e}`,n=this.getCache(t);if(n)return n;let r=await this._client.getCoinMetadata({coinType:e});return this.updateCache(t,r.coinMetadata),r.coinMetadata}async fetchCoinMetadataId(e){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let t=`coin_metadata_id_${e}`,n=this.getCache(t);if(n)return n;let r=(await this._graphQLClient.query({query:hx,variables:{coinType:`0x2::coin::CoinMetadata<${e}>`}})).data?.objects?.nodes?.[0]?.address??null;return r&&this.updateCache(t,r),r}async getSuiTransactionResponse(e){try{return await this._client.getTransaction({digest:e,include:{effects:!0,events:!0,balanceChanges:!0,transaction:!0,objectTypes:!0}})}catch(t){throw console.log("getSuiTransactionResponse error",t),t}}async getTransactionByGraphQL(e){try{return await this._graphQLClient.query({query:gx,variables:{digest:e}})}catch(t){throw console.log("getTransactionByGraphQL error",t),t}}async queryEventsByGraphQL(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:bx,variables:{type:e,first:r,...i?{after:i}:{}}})).data?.events,c=a?.nodes??[],u=a?.pageInfo;s=[...s,...c],o=u?.hasNextPage??!1,i=u?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async queryTransactionBlocksByPage(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");if(!(e.sentAddress!=null||e.affectedAddress!=null||e.affectedObject!=null||e.function!=null))throw new Error("At least one of sentAddress, affectedAddress, affectedObject, function is required");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0,a={};e.sentAddress&&(a.sentAddress=X(e.sentAddress)),e.affectedAddress&&(a.affectedAddress=X(e.affectedAddress)),e.affectedObject&&(a.affectedObject=X(e.affectedObject)),e.function&&(a.function=e.function);do{let c=(await this._graphQLClient.query({query:vx,variables:{filter:a,first:r,...i?{after:i}:{}}})).data?.transactions,u=c?.nodes??[],d=c?.pageInfo;s=[...s,...u],o=d?.hasNextPage??!1,i=d?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async queryEventsByPage(e,t="all"){let n=[],r=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this._jsonRpcClient.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(n=[...n,...o.data],r=o.hasNextPage,i=o.nextCursor):r=!1}while(s&&r);return{data:n,next_cursor:i,has_next_page:r}}async getOwnedObjectsByPage(e,t,n="all"){let r=async s=>{let i=[],o=!0,a=n==="all",c=a?null:n.cursor;do{let u=await s.listOwnedObjects({owner:e,type:t,cursor:c??void 0,limit:a?1e3:n.limit??void 0,include:{content:!0,previousTransaction:!0,json:!0}});i=[...i,...u.objects],o=u.hasNextPage,c=u.cursor??null}while(a&&o);return{data:i,next_cursor:c,has_next_page:o}};try{return await r(this._client)}catch(s){let i=s,o=this._env==="testnet"?"testnet":"mainnet";for(let a of _x)try{let c=af(new Ko({baseUrl:a,network:o}),this._graphQLClient,this._env);return await r(c._client)}catch(c){i=c;continue}throw i}}async getAllDynamicFields(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:yx,variables:{id:X(e),first:r,...i?{after:i}:{}}})).data?.address?.dynamicFields,c=a?.nodes??[],u=a?.pageInfo;s=[...s,...c],o=u?.hasNextPage??!1,i=u?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async getDynamicFieldsByPage(e,t="all"){let n=[],r=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this._client.listDynamicFields({parentId:e,cursor:i??void 0,limit:s?1e3:t.limit??void 0});n=[...n,...o.dynamicFields],r=o.hasNextPage,i=o.cursor??null}while(s&&r);return{data:n,next_cursor:i,has_next_page:r}}async getDynamicFieldObjects(e,t,n,r,s){let i=t.map(o=>mx(e,o,n,r));return i.length===0?[]:this.batchGetObjects(i,s)}async batchGetObjects(e,t,n=1e3){let r=[];try{for(let s=0;s<Math.ceil(e.length/n);s++){let i=e.slice(s*n,n*(s+1)),o=await this._client.getObjects({objectIds:i,include:t});r=[...r,...o.objects]}}catch(s){console.log(s)}return r}async calculationTxGas(e){let t=e.getData?.()?.sender??e.blockData?.sender;if(t==null)throw Error("sdk sender is empty");e.setSender(t);let n=await this._client.simulateTransaction({transaction:e,include:{effects:!0}}),r=n.Transaction??n.FailedTransaction;if(!r?.effects?.gasUsed)throw new Error("Simulation did not return effects");let{gasUsed:s}=r.effects;return Number(s.computationCost)+Number(s.storageCost)-Number(s.storageRebate)}async sendTransaction(e,t){try{return await this._client.signAndExecuteTransaction({transaction:t,signer:e,include:{effects:!0,events:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(e,t,n=!0){try{return e.setSender(t),await this._client.simulateTransaction({transaction:e,include:{events:!0,balanceChanges:!0,effects:!0,objectChanges:!0,commandResults:!0},checksEnabled:n})}catch(r){throw console.log("simulateTransaction error",r),r}}async executeTx(e,t,n){try{if(n){let r=typeof e=="string"?X(e):X(e.getPublicKey().toSuiAddress());return await this.sendSimulationTransaction(t,r)}else{if(typeof e=="string")throw new Error("Cannot send transaction with string address - keypair required for signing");return await this.sendTransaction(e,t)}}catch(r){return r}}async getOwnerCoinAssets(e,t){let n=[],r=null;if(t)for(;;){let s=await this._client.listCoins({owner:e,coinType:t,cursor:r??void 0});for(let i of s.objects)BigInt(i.balance)>0&&n.push({coin_type:Ai(i.type).type_arguments[0],coin_object_id:i.objectId,balance:BigInt(i.balance)});if(r=s.cursor??null,!s.hasNextPage)break}else{let s=null;do{let i=await this._client.listOwnedObjects({owner:e,cursor:s??void 0,include:{json:!0}});if(i.objects.forEach(o=>{let a=Ai(o.type);o.type.includes('"0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin')&&BigInt(o.balance)>0&&n.push({coin_type:sf(a.type_arguments[0],!1),coin_object_id:o.json.id,balance:BigInt(o.json.balance)})}),s=i.cursor??null,!i.hasNextPage)break}while(!0)}return n}async getOwnerCoinBalances(e,t){if(t)return[(await this._client.getBalance({owner:e,coinType:t})).balance];let n=[],r=null;do{let s=await this._client.listBalances({owner:e,cursor:r??void 0});if(n.push(...s.balances),r=s.cursor??null,!s.hasNextPage)break}while(!0);return n}updateCache(e,t,n=864e5){let r=this._cache[e];r?(r.overdue_time=nb(n),r.value=t):r=new gA(t,nb(n)),this._cache[e]=r}getCache(e,t=!1){let n=this._cache[e],r=n?.isValid();if(!t&&r)return n.value;r||delete this._cache[e]}};function af(e,t,n,r){let s=new kx(e,t,n,r);return new Proxy(s,{get(i,o,a){if(o in i)return Reflect.get(i,o,a);if(o in i._client){let c=Reflect.get(i._client,o);return typeof c=="function"?c.bind(i._client):c}throw new Error(`Property or method "${String(o)}" does not exist on FullClient or its client.`)}})}var Sx=Ta(ka(),1);var y$=new Sx.default(1e6),Ex=(e=>(e[e.BelowRange=0]="BelowRange",e[e.InRange=1]="InRange",e[e.AboveRange=2]="AboveRange",e))(Ex||{}),Qp=10n,Ox={pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",hermes_service_urls:[]},Ix={"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{coin_type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",price_feed_id:"0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",coin_decimals:6},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",price_feed_id:"0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",coin_decimals:9},"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS":{coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",price_feed_id:"0xe5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",coin_decimals:9},"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP":{coin_type:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",price_feed_id:"0x29bdd5248234e33bd93d3b81100b5fa32eaa5997843847e2c2cb16d7c6d9f7ff",coin_decimals:6},"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX":{coin_type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",price_feed_id:"0x88250f854c019ef4f88a5c073d52a18bb1c6ac437033f5932cd017d24917ab46",coin_decimals:9},"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN":{coin_type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",price_feed_id:"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",coin_decimals:9},"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI":{coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",price_feed_id:"0x6120ffcf96395c70aa77e72dcb900bf9d40dccab228efca59a17b90ce423d5e8",coin_decimals:9},"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH":{coin_type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",price_feed_id:"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",coin_decimals:8},"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL":{coin_type:"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL",price_feed_id:"0xeba0732395fae9dec4bae12e52760b35fc1c5671e2da8b449c9af4efe5d54341",coin_decimals:9},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{coin_type:"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC",price_feed_id:"0x8f257aab6e7698bb92b15511915e593d6f8eae914452f781874754b03d0c612b",coin_decimals:8},"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL":{coin_type:"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL",price_feed_id:"0xe67d98cc1fbd94f569d5ba6c3c3c759eb3ffc5d2b28e64538a53ae13efad8fd1",coin_decimals:9}};function Ax(e,t){if(!Qp)throw new Error("oraclePriceMultiplierDecimal is required");if(e===0n)throw new Error("Invalid oracle price");if(t<0n){let n=10n**(Qp- -t);return e*n}return e/10n**(t+Qp)}var cb=16*1024,kb=class{constructor(e,t=Ox){this.hasChangeConnection=!1,this.pythConfigs=t,this.fullClient=e;let n=[...t.hermes_service_urls];n.includes("https://hermes.pyth.network")||n.push("https://hermes.pyth.network"),this.hermesClients=n.map(r=>new gu(r,{timeout:3e3}))}async getFeedInfoList(e){let t=e.map(n=>this.getFeedInfo(n,!1));return await Promise.all(t)}priceCheck(e,t=60){let n=Math.floor(Date.now()/1e3);if(!(Math.abs(n-e.last_update_time)>t))return e}async getPackageId(e){let t=(await this.fullClient.getObject({objectId:e,include:{json:!0}}))?.object?.json;if(t?.upgrade_cap?.package)return t.upgrade_cap.package;throw new Error("upgrade_cap not found")}async getWormholePackageId(){let{wormhole_state_id:e}=this.pythConfigs,t=`getWormholePackageId_${e}`,n=this.fullClient.getCache(t);if(n)return n;let r=await this.getPackageId(this.pythConfigs.wormhole_state_id);return this.fullClient.updateCache(t,r),r}async getLatestPrice(e,t=!1){let n={},r=[];if(t?e.forEach(i=>{let o=this.fullClient.getCache(`getLatestPrice_${i}`);o&&this.priceCheck(o,60)?n[i]=o:r.push(i)}):r=[...e],r.length===0)return n;let s=await this.getFeedInfoList(r);return(await this.getLatestPriceFeeds(s.map(i=>i.price_feed_id)))?.parsed?.forEach((i,o)=>{if(i){let{price:a,expo:c,publish_time:u}=i.price,d=vu(a).mul(vu(10).pow(vu(c))).toString(),p=s[o],f={coin_type:p.coin_type,price:d,coin_decimals:p.coin_decimals,oracle_price:0n,last_update_time:u};f.oracle_price=Ax(BigInt(a),BigInt(c)),n[r[o]]=f,this.fullClient.updateCache(`getLatestPrice_${f.coin_type}`,f)}}),n}async getPriceFeedsUpdateData(e){let t=null;for(let n of this.hermesClients)try{return(await n.getLatestPriceUpdates(e,{encoding:"hex"})).binary.data.map(r=>Buffer.from(r,"hex"))}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getPriceFeedsUpdateData ~ e:",r),t=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getPriceFeedsUpdateData Detailed error: ${t?.message}`)}async getLatestPriceFeeds(e){let t=null;for(let n of this.hermesClients)try{return await n.getLatestPriceUpdates(e,{parsed:!0})}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getLatestPriceFeeds ~ error:",r),t=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getLatestPriceFeeds Detailed error: ${t?.message}`)}extractVaaBytesFromAccumulatorMessage(e){let t=7+e.readUint8(6)+1,n=e.readUint16BE(t),r=t+2;return e.subarray(r,r+n)}async verifyVaas(e,t){let n=await this.getWormholePackageId(),r=[];for(let s of e){let[i]=t.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[t.object(this.pythConfigs.wormhole_state_id),t.pure(E.vector(E.u8()).serialize(Array.from(s),{maxSize:cb}).toBytes()),t.object(he)]});r.push(i)}return r}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let e=null,t=!0;for(;t;){let n=await this.fullClient.listDynamicFields({parentId:this.pythConfigs.pyth_state_id,cursor:e});for(let r of n.dynamicFields)if(r.name.type==="vector<u8>"){let s=r.$kind==="DynamicObject"&&r.childId?r.childId:r.fieldId,i=await this.fullClient.getObject({objectId:s,include:{json:!0}}),o=i.object.type;if(o.includes("table::Table")){let a=o.replace(/.*table::Table</,"").replace(/>$/,"").split(",")[0].trim();return this.priceTableInfo={id:i.object.objectId,fieldType:a},this.priceTableInfo}}t=n.hasNextPage,e=n.cursor}}if(this.priceTableInfo===void 0)throw new Error(" getPriceTableInfo Price table not found");return this.priceTableInfo}async getPriceFeedObjectId(e){let t=e.replace("0x",""),n=`getPriceFeedObjectId_${t}`,r=this.fullClient.getCache(n);if(r)return r;let{id:s,fieldType:i}=await this.getPriceTableInfo(),o=E.struct("PriceIdentifier",{bytes:E.vector(E.u8())}).serialize({bytes:Array.from(Buffer.from(t,"hex"))}).toBytes(),a=(await this.fullClient.getDynamicField({parentId:s,name:{type:i,bcs:o}})).dynamicField.value.bcs,c=a instanceof Uint8Array?a:new Uint8Array(Object.values(a)),u="0x"+Array.from(c).map(d=>d.toString(16).padStart(2,"0")).join("");return this.fullClient.updateCache(n,u),u}async verifyVaasAndGetHotPotato(e,t,n){if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e),[i]=e.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[e.object(this.pythConfigs.pyth_state_id),e.pure(E.vector(E.u8()).serialize(Array.from(t[0]),{maxSize:cb}).toBytes()),s[0],e.object(he)]});return i}async buildUpdatePythPricePayload(e,t,n){let{pyth_state_id:r,pyth_published_at:s,pyth_package_id:i}=this.pythConfigs,o=(await this.getFeedInfoList(e)).map(d=>d.price_feed_id);if(e.length!==o.length)throw Error("find feed id fail");let a=await this.getPriceFeedsUpdateData(o);if(!a)throw new Error("get price update data fail");if(a.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let c=await this.verifyVaasAndGetHotPotato(t,a,s),u=0;for(let d of o){let p=await this.getPriceFeedObjectId(d);if(!p)throw new Error(`Price feed ${d} not found, please create it first`);c=n({tx:t,coinType:e[u],priceUpdatesHotPotato:c,priceInfoObjectId:p}),u+=1}return t.moveCall({target:`${s}::hot_potato_vector::destroy`,arguments:[c],typeArguments:[`${i}::price_info::PriceInfo`]}),t}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let e=(await this.fullClient.getObject({objectId:this.pythConfigs.pyth_state_id,include:{json:!0}}))?.object?.json;if(!e)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=Number(e.base_update_fee)}return this.baseUpdateFee}async updatePriceFeeds(e,t,n){let r=this.pythConfigs.pyth_package_id,s=await this.verifyVaasAndGetHotPotato(e,t,r),i=await this.getBaseUpdateFee(),o=e.splitCoins(e.gas,n.map(()=>e.pure.u64(i))),a=[],c=0;for(let u of n){let d=await this.getPriceFeedObjectId(u);if(!d)throw new Error(`Price feed ${u} not found, please create it first`);a.push(d),[s]=e.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[e.object(this.pythConfigs.pyth_state_id),s,e.object(d),o[c],e.object(he)]}),c++}return e.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[s],typeArguments:[`${r}::price_info::PriceInfo`]}),a}async buildUpdatePythPricePayloadV2(e,t,n){if(e.length===0)return t;let r=(await this.getFeedInfoList(e)).map(a=>a.price_feed_id);if(e.length!==r.length)throw Error("find feed id fail");let s=await this.getPriceFeedsUpdateData(r);if(!s)throw new Error("get price update data fail");if(s.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=await this.updatePriceFeeds(t,s,r),o=0;for(let a of i)n({tx:t,coinType:e[o],priceUpdatesHotPotato:{},priceInfoObjectId:a}),o+=1;return t}getFeedInfoByJson(e){let t=sf(e,!1);return Ix[t]}async getFeedInfo(e,t){let n=`getFeedInfo_${e}`,r=this.fullClient.getCache(n,t);if(r)return r;let s=this.getFeedInfoByJson(e);if(s)return s;if(!this.pythConfigs.feed_info_handle)throw new Error("feed_info_handle is not set");let i=await this.fullClient.getDynamicField({parentId:this.pythConfigs.feed_info_handle,name:{type:"0x1::type_name::TypeName",bcs:wx.serialize({name:sf(e,!0)}).toBytes()}}),o=E.struct("OracleInfo",{price_feed_id:E.vector(E.U8),price_info_object_id:E.Address,last_update_time:E.u64(),coin_decimals:E.u8()}).parse(i.dynamicField.value.bcs),a={coin_type:e,price_feed_id:fx(o.price_feed_id),coin_decimals:o.coin_decimals};return console.log("\u{1F680} ~ PythPriceModule ~ getFeedInfo ~ info:",a),this.fullClient.updateCache(n,a),a}},vo=Ta(ka(),1),v$=new vo.default(0),Sb=new vo.default(1),cf=new vo.default(2),_$=cf.pow(new vo.default(128)),w$=cf.pow(new vo.default(64)).sub(Sb),T$=cf.pow(new vo.default(128)).sub(Sb);ku.config({precision:64,rounding:ku.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var k$=Ta(ka(),1),S$=Ta(ka(),1);var E$=Ta(ka(),1);import{DeepBookClient as qx}from"@mysten/deepbook-v3";import{Base64 as Gx}from"js-base64";var xx={REQUEST_PARAMS:"requestParams",METHOD_NAME:"methodName"},uf=class extends Error{constructor(n,r,s){super(n);this.code=r;this.details=s;this.name=this.constructor.name}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details}}toString(){return JSON.stringify(this.toJSON())}static isErrorCode(n,r){return n instanceof uf&&n.code===r}},Ea=uf;Ni(Ea,"DETAILS_KEYS",xx);var lf=class extends Ea{constructor(t,n,r){super(t,n||"UnknownError",r)}static isCommonErrorCode(t,n){return this.isErrorCode(t,n)}};var df=(e,t,n)=>{throw new lf(t,e,n)};var Cx=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function Eb(e){return e.startsWith("0x")?e:`0x${e}`}function pf(e){return e.startsWith("0x")?`${e.slice(2)}`:e}function Nx(e,t=4,n=4){let r=Math.max(t,1),s=Math.max(n,1);return`${e.slice(0,r+2)} ... ${e.slice(-s)}`}function D$(e,t=4,n=4){return Nx(Eb(e),t,n)}function U$(e,t={leadingZero:!0}){if(typeof e!="string")return!1;let n=e;if(t.leadingZero){if(!e.startsWith("0x"))return!1;n=n.substring(2)}return Cx.test(n)}function Rx(e){if(!Buffer.isBuffer(e))if(Array.isArray(e))e=Buffer.from(e);else if(typeof e=="string")exports.isHexString(e)?e=Buffer.from(exports.padToEven(exports.stripHexPrefix(e)),"hex"):e=Buffer.from(e);else if(typeof e=="number")e=exports.intToBuffer(e);else if(e==null)e=Buffer.allocUnsafe(0);else if(e.toArray)e=Buffer.from(e.toArray());else throw new Error("invalid type");return e}function P$(e){return Eb(Rx(e).toString("hex"))}function L$(e){let t=new ArrayBuffer(4),n=new DataView(t);for(let s=0;s<e.length;s++)n.setUint8(s,e.charCodeAt(s));return n.getUint32(0,!0)}function Mx(e){let t,n,r,s,i;t="";let o=e.length;for(n=0;n<o;)switch(r=e.charCodeAt(n++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=e.charAt(n-1);break;case 12:case 13:s=e.charCodeAt(n++),t+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=e.charCodeAt(n++),i=e.charCodeAt(n++),t+=String.fromCharCode((r&15)<<12|(s&63)<<6|(i&63)<<0);break}return t}function V$(e){let t="",n=pf(e),r=n.length/2;for(let s=0;s<r;s++)t+=String.fromCharCode(Number.parseInt(n.substr(s*2,2),16));return Mx(t)}var Bx=0,Ab=1,jx=2;function Ob(e,t){return e===t?Bx:e<t?Ab:jx}function Dx(e,t){let n=0,r=e.length<=t.length?e.length:t.length,s=Ob(e.length,t.length);for(;n<r;){let i=Ob(e.charCodeAt(n),t.charCodeAt(n));if(n+=1,i!==0)return i}return s}function z$(e,t){return Dx(e,t)===Ab}function Ib(e,...t){let n=Array.isArray(t[t.length-1])?t.pop():[],s=[e,...t].filter(Boolean).join("::");return n&&n.length&&(s+=`<${n.join(", ")}>`),s}function W$(e){return e.split("::")[0]}function Ls(e){try{let t=e.replace(/\s/g,""),r=t.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){t=t.slice(0,t.indexOf("<"));let c={...Ls(t),type_arguments:r.map(u=>Ls(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>Gt.isSuiCoin(u)?u:Ls(u).source_address),c.source_address=Ib(c.full_address,c.type_arguments),c}let s=t.split("::"),o={full_address:t,address:t===hf||t===xb?"0x2":Ft(s[0]),module:s[1],name:s[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=Ib(o.full_address,o.type_arguments),o}catch{return{full_address:e,address:"",module:"",name:"",type_arguments:[],source_address:e}}}function ff(e){return Ls(e).source_address}function Ux(e){return e.toLowerCase().startsWith("0x")?Ft(e):e}var H$=(e,t=!0)=>{let n=e.split("::"),r=n.shift(),s=Ft(r);return t&&(s=pf(s)),`${s}::${n.join("::")}`};function mf(e){for(let t in e){let n=typeof e[t];if(n==="object")mf(e[t]);else if(n==="string"){let r=e[t];e[t]=Ux(r)}}}var J$=be(zn);import Iu from"decimal.js";function R(e){return Iu.isDecimal(e)?e:new Iu(e===void 0?0:e)}function gf(e){return R(10).pow(R(e).abs())}var xi=(e,t)=>{try{return R(e).toDP(t,Iu.ROUND_DOWN).toString()}catch{return e}},yf=(e,t)=>Iu.max(R(e),R(t));var rq=1e3,sq=500,iq=100,oq=100,aq=1e3,hf="0x2::sui::SUI",xb="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",cq="SUI",uq=450,lq="0x0000000000000000000000000000000000000005",it=class{static totalBalance(t,n){let r=BigInt(0);return t.forEach(s=>{n===s.coin_type&&(r+=BigInt(s.balance))}),r}static getCoinAssets(t,n){let r=[];return n.forEach(s=>{ff(s.coin_type)===ff(t)&&r.push(s)}),r}static isSuiCoin(t){return Ls(t).full_address===hf}static selectCoinObjectIdGreaterThanOrEqual(t,n,r=[]){let s=it.selectCoinAssetGreaterThanOrEqual(t,n,r),i=s.selected_coins.map(c=>c.coin_object_id),o=s.remain_coins,a=s.selected_coins.map(c=>c.balance.toString());return{object_array:i,remain_coins:o,amount_array:a}}static selectCoinAssetGreaterThanOrEqual(t,n,r=[]){let s=it.sortByBalance(t.filter(u=>!r.includes(u.coin_object_id))),i=it.calculateTotalBalance(s);if(i<n)return{selected_coins:[],remain_coins:s};if(i===n)return{selected_coins:s,remain_coins:[]};let o=BigInt(0),a=[],c=[...s];for(;o<i;){let u=n-o,d=c.findIndex(f=>f.balance>=u);if(d!==-1){a.push(c[d]),c.splice(d,1);break}let p=c.pop();p.balance>0&&(a.push(p),o+=p.balance)}return{selected_coins:it.sortByBalance(a),remain_coins:it.sortByBalance(c)}}static sortByBalance(t){return t.sort((n,r)=>n.balance<r.balance?-1:n.balance>r.balance?1:0)}static sortByBalanceDes(t){return t.sort((n,r)=>n.balance>r.balance?-1:n.balance<r.balance?0:1)}static calculateTotalBalance(t){return t.reduce((n,r)=>n+r.balance,BigInt(0))}static buildCoinForAmount(t,n,r,s,i=!0,o=!0){let a=it.getCoinAssets(s,n);if(r===BigInt(0))return this.buildZeroValueCoin(n,t,s,i);let c=it.calculateTotalBalance(a);if(c<r)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r} `);return this.buildCoin(t,n,a,r,s,i,o)}static buildCoinWithBalance(t,n,r){return t===BigInt(0)&&it.isSuiCoin(n)?r.add(Kn({balance:t,useGasCoin:!1})):r.add(Kn({balance:t,type:n}))}static buildVectorCoin(t,n,r,s,i,o=!0){if(it.isSuiCoin(i)){let f=t.splitCoins(t.gas,[t.pure.u64(s)]);return{selected_coins:[],target_coin:f,remain_coins:n,target_coin_amount:s.toString(),is_mint_zero_coin:!1,original_spited_coin:t.gas}}let{original_spited_coin:a,target_coin:c,target_coin_amount:u,remain_coins:d,selected_coins:p}=this.buildSpitTargeCoin(t,s,r,o);return o?{target_coin:t.makeMoveVec({elements:[c]}),selected_coins:p,remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1,original_spited_coin:a}:{selected_coins:p,target_coin:t.makeMoveVec({elements:p.map(f=>t.object(f))}),remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1}}static buildOneCoin(t,n,r,s,i=!0){if(it.isSuiCoin(s)){if(r===0n&&n.length>1){let c=it.selectCoinObjectIdGreaterThanOrEqual(n,r);return{selected_coins:c.object_array,target_coin:t.object(c.object_array[0]),remain_coins:c.remain_coins,target_coin_amount:c.amount_array[0],is_mint_zero_coin:!1}}let o=it.selectCoinObjectIdGreaterThanOrEqual(n,r),a=t.splitCoins(t.gas,[t.pure.u64(r)]);return{selected_coins:[],target_coin:a,remain_coins:o.remain_coins,target_coin_amount:r.toString(),is_mint_zero_coin:!1,original_spited_coin:t.gas}}return this.buildSpitTargeCoin(t,r,n,i)}static buildSpitTargeCoin(t,n,r,s){let i=it.selectCoinObjectIdGreaterThanOrEqual(r,n),o=i.amount_array.reduce((b,_)=>Number(b)+Number(_),0).toString(),a=i.object_array,[c,...u]=a,d=t.object(c),p=d,f=i.amount_array.reduce((b,_)=>Number(b)+Number(_),0).toString(),g;return u.length>0&&t.mergeCoins(d,u.map(b=>t.object(b))),s&&Number(o)>Number(n)&&(p=t.splitCoins(d,[t.pure.u64(n)]),g=d),{original_spited_coin:g,target_coin:p,target_coin_amount:f,remain_coins:i.remain_coins,selected_coins:i.object_array,is_mint_zero_coin:!1}}static buildCoin(t,n,r,s,i,o=!0,a=!0){return o?this.buildVectorCoin(t,n,r,s,i,a):this.buildOneCoin(t,r,s,i,a)}static buildZeroValueCoin(t,n,r,s=!0){let i=this.callMintZeroValueCoin(n,r),o;return s?o=n.makeMoveVec({elements:[i]}):o=i,{target_coin:o,remain_coins:t,selected_coins:[],is_mint_zero_coin:!0,target_coin_amount:"0"}}static buildCoinForAmountInterval(t,n,r,s,i=!0,o=!0){let a=it.getCoinAssets(s,n);if(r.amount_first===BigInt(0))return a.length>0?this.buildCoin(t,[...n],[...a],r.amount_first,s,i,o):this.buildZeroValueCoin(n,t,s,i);let c=it.calculateTotalBalance(a);if(c>=r.amount_first)return this.buildCoin(t,[...n],[...a],r.amount_first,s,i,o);if(c<r.amount_second)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r.amount_second} `);return this.buildCoin(t,[...n],[...a],r.amount_second,s,i,o)}static fromBalance(t,n,r){return r.moveCall({target:"0x2::coin::from_balance",typeArguments:[n],arguments:[t]})}static intoBalance(t,n,r){return r.moveCall({target:"0x2::coin::into_balance",typeArguments:[n],arguments:[typeof t=="string"?r.object(t):t]})}static mintBalanceZero(t,n){return n.moveCall({target:"0x2::balance::zero",typeArguments:[t],arguments:[]})}static destroyBalanceZero(t,n,r){return r.moveCall({target:"0x2::balance::destroy_zero",typeArguments:[n],arguments:[t]})}static getCoinAmountObjId(t,n){let r=t.amount_coin_array.find(s=>!s.used&&R(s.amount).eq(n)?(s.used=!0,!0):!1);return r?r.coin_object_id:df("CoinNotFound",`Coin not found for ${n} ${t.coin_type}`)}static buildMultiCoinInput(t,n,r,s){let i=it.getCoinAssets(r,n);if(it.isSuiCoin(r)){let f=t.splitCoins(t.gas,s.map(b=>t.pure.u64(b)));return{amount_coin_array:s.map((b,_)=>({coin_object_id:f[_],amount:b.toString(),used:!1})),coin_type:r,remain_coins:i}}let o=s.reduce((f,g)=>f+g,BigInt(0)),a=it.selectCoinObjectIdGreaterThanOrEqual(i,o);if(a.object_array.length===0)return df("InsufficientBalance",`No enough coins for ${r} expect ${o} actual ${it.calculateTotalBalance(i)}`);let[c,...u]=a.object_array;u.length>0&&t.mergeCoins(c,[...u]);let d=t.splitCoins(c,s.map(f=>t.pure.u64(f)));return{amount_coin_array:s.map((f,g)=>({coin_object_id:d[g],amount:f.toString(),used:!1})),remain_coins:a.remain_coins,coin_type:r}}},Gt=it;Ni(Gt,"callMintZeroValueCoin",(t,n)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[n]}));var Cb=6e4,Nb=3e5,_o=864e5;function bf(e){return Date.parse(new Date().toString())+e}var Au=class{overdueTime;value;constructor(t,n=0){this.overdueTime=n,this.value=t}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};function Vs(e,t){let n=gf(R(t));return Number(R(e).mul(n))}function bq(e,t=32){return BigInt.asUintN(t,BigInt(e)).toString()}function vq(e,t=32){return Number(BigInt.asIntN(t,BigInt(e)))}function Ci(e,t){let n=gf(R(t));return Number(R(e).div(n))}function _q(e,t="hex"){if(e instanceof Uint8Array){let r=Buffer.from(e);return zc.fromSecretKey(new Uint8Array(r))}let n=t==="hex"?dn(e):ie(e);return zc.fromSecretKey(n)}function wq(e,t="hex"){if(e instanceof Uint8Array){let r=Buffer.from(e);return Jc.fromSecretKey(new Uint8Array(r))}let n=t==="hex"?dn(e):ie(e);return Jc.fromSecretKey(n)}var Rb=async e=>new Promise(t=>{setTimeout(()=>{t(1)},e)});async function Tq(e,t=!0){e.getData().commands.forEach((n,r)=>{t&&console.log(`transaction ${r}: `,n)})}var Mb={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Bb={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function jb(...e){console.log("DeepbookV3_Utils_Sdk###",...e)}function Db(e){return e.data}function Px(e){if(e.error&&"object_id"in e.error&&"version"in e.error&&"digest"in e.error){let{error:t}=e;return{objectId:t.object_id,version:t.version,digest:t.digest}}}function Lx(e){if(e.error&&"object_id"in e.error&&!("version"in e.error)&&!("digest"in e.error))return e.error.object_id}function Vx(e){if("reference"in e)return e.reference;let t=Db(e);return t?{objectId:t.objectId,version:t.version,digest:t.digest}:Px(e)}function Ub(e){return"objectId"in e?e.objectId:Vx(e)?.objectId??Lx(e)}function Oq(e){return e.data!==void 0}function Fx(e){return e.content!==void 0}function $x(e){let t="data"in e?Db(e):e;if(!(!t||!Fx(t)||t.content.dataType!=="moveObject"))return t.content}function Pb(e){let t=$x(e)?.fields;if(t)return"fields"in t?t.fields:t}var Lb=E.struct("GetCetusBalanceManagerList",{owner:E.Address,cetus_balance_managers:E.vector(E.Address),deepbook_balance_managers:E.vector(E.Address)}),Vb=E.struct("Account",{epoch:E.u64(),open_orders:E.vector(E.u128()),taker_volume:E.u128(),maker_volume:E.u128(),active_stake:E.u64(),inactive_stake:E.u64(),created_proposal:E.bool(),voted_proposal:E.option(E.Address),unclaimed_rebates:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()}),settled_balances:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()}),owed_balances:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()})});var vf=1e6,gr=1e9,zx={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Wx={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},xu=class{_sdk;_deep;_cache={};constructor(t){this._sdk=t,this._deep=t.sdkOptions.network==="mainnet"?Wx:zx}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let t=new J,n=t.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return t.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[t.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),n],typeArguments:[]}),t.moveCall({target:"0x2::transfer::public_share_object",arguments:[n],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),t}createAndDepsit({account:t,coin:n,amountToDeposit:r}){let s=new J;s.setSenderIfNotSet(t);let i=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=Kn({type:n.coinType,balance:BigInt(r)});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i,o],typeArguments:[n.coinType]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i],typeArguments:[]}),s.moveCall({target:"0x2::transfer::public_share_object",arguments:[i],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),s}depositIntoManager({account:t,balanceManager:n,coin:r,amountToDeposit:s,tx:i}){let o=i||new J;if(n){o.setSenderIfNotSet(t);let a=Kn({type:r.coinType,balance:BigInt(s)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(n),a],typeArguments:[r.coinType]}),o}return null}async withdrawFromManager({account:t,balanceManager:n,coin:r,amountToWithdraw:s,returnAssets:i,txb:o}){let a=o||new J,c=a.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[a.object(n),a.pure.u64(s)],typeArguments:[r.coinType]});if(i)return c;if(Gt.isSuiCoin(r.coinType))a.transferObjects([c],t);else{let u=await this._sdk.fullClient.getOwnerCoinAssets(t,r.coinType),d=Gt.buildCoinForAmount(a,u,BigInt(0),r.coinType,!1);d.target_coin?(a.mergeCoins(d.target_coin,[c]),d.is_mint_zero_coin&&a.transferObjects([d.target_coin],t)):a.transferObjects([c],t)}return a}withdrawManagersFreeBalance({account:t,balanceManagers:n,tx:r=new J}){for(let s in n)n[s].forEach(o=>{let a=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(s),r.pure.u64(o.amount)],typeArguments:[o.coinType]});r.transferObjects([a],t)});return r}async getBalanceManager(t,n=!0){let r=`getBalanceManager_${t}`,s=this.getCache(r,n);if(!n&&s!==void 0)return s;try{let i=new J;i.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[i.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i.pure.address(t)],typeArguments:[]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t),c=(o?.Transaction??o?.FailedTransaction)?.events?.find(I=>I.eventType===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`);if(c?.bcs==null)throw new Error("GetCetusBalanceManagerList event not found or missing BCS payload (check simulation / RPC transport)");let d=Lb.parse(new Uint8Array(c.bcs))?.deepbook_balance_managers||[],p=await this._sdk.fullClient.batchGetObjects(d,{json:!0}),f={};for(let I=0;I<p.length;I++){let A=p[I],M=A?.data?.objectId??A?.objectId,C=A?.json??A?.data?.content?.fields,B=C?.allow_listed?.fields?.contents??C?.allow_listed?.contents??C?.balance_manager?.allow_listed?.contents;M&&Array.isArray(B)&&B.length>0&&(f[M]=B)}let g=await this.batchGetObjectsByIdMap(f),b=X(t),_=[];return d.forEach(I=>{let A=g[I]??[],M=A.filter(B=>{let L=this.getSuiObjectOwnerAddress(B);return L!==void 0&&X(L)===b});(A.length===0||M.length===A.length)&&_.push({balanceManager:I,cetusBalanceManager:""})}),this.updateCache(r,_,864e5),_||[]}catch(i){throw i instanceof Error?i:new Error(String(i))}}async batchGetObjectsByIdMap(t){let n=Object.entries(t).filter(([,o])=>Array.isArray(o)&&o.length>0);if(n.length===0)return{};let r=[...new Set(n.flatMap(([,o])=>o))],s=await this._sdk.fullClient.batchGetObjects(r,{json:!0}),i=new Map;return s.forEach(o=>{let a=o?.data?.objectId??o?.objectId;a&&i.set(a,o)}),Object.fromEntries(n.map(([o,a])=>[o,a.map(c=>i.get(c)).filter(Boolean)]))}getSuiObjectOwnerAddress(t){let r=t?.owner;if(r&&typeof r=="object"){if(r.$kind==="AddressOwner"&&typeof r.AddressOwner=="string")return r.AddressOwner;if(r.$kind==="ObjectOwner"&&typeof r.ObjectOwner=="string")return r.ObjectOwner;if(typeof r.AddressOwner=="string")return r.AddressOwner;if(typeof r.ObjectOwner=="string")return r.ObjectOwner}let s=t.data?.owner;if(!(!s||typeof s!="object")){if(typeof s.AddressOwner=="string")return s.AddressOwner;if(typeof s.ObjectOwner=="string")return s.ObjectOwner}}withdrawSettledAmounts({poolInfo:t,balanceManager:n},r=new J){let s=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(n)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(t.address),r.object(n),s],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}async getManagerBalance({account:t,balanceManager:n,coins:r}){try{let s=new J;r.forEach(a=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(n)],typeArguments:[a.coinType]})});let i=await this.sdk.fullClient.sendSimulationTransaction(s,t),o={};return i?.commandResults?.forEach((a,c)=>{let u=r[c],d=a.returnValues[0]?.bcs,p=E.U64.parse(new Uint8Array(d)),f=R(p),g=f.eq(0)?"0":f.div(Math.pow(10,u.decimals)).toString();o[u.coinType]={adjusted_balance:g,balance:f.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:t,coins:n}){try{let r=new J,s=await this.getBalanceManager(t,!0);if(!Array.isArray(s)||s.length===0)return{};s.forEach(a=>{n.forEach(c=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(a.balanceManager)],typeArguments:[c.coinType]})})});let i=await this.sdk.fullClient.sendSimulationTransaction(r,t),o={};return s.forEach((a,c)=>{let u={},d=c*n.length;n.forEach((p,f)=>{let g=d+f,b=i.commandResults?.[g];if(b){let _=b.returnValues[0].bcs,I=E.U64.parse(new Uint8Array(_)),A=R(I),M=A.eq(0)?"0":A.div(Math.pow(10,p.decimals)).toString();u[p.coinType]={adjusted_balance:M,balance:A.toString()}}}),o[a.balanceManager]=u}),o}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(t){try{let n=new J;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[n.object(t.address),n.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let s=(await this._sdk.fullClient.sendSimulationTransaction(n,this._sdk.sdkOptions.simulationAccount.address)).commandResults[0]?.returnValues[0]?.bcs,i=Number(E.U64.parse(new Uint8Array(s))),o=Math.pow(10,t.baseCoin.decimals).toString(),a=Math.pow(10,t.quoteCoin.decimals).toString();return R(i).mul(o).div(a).div(gr).toString()}catch(n){return jb("getMarketPrice ~ error:",n),"0"}}async getPools(t=!1){let n="Deepbook_getPools",r=this.getCache(n,t);if(r!==void 0)return r;let s=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),i=/<([^>]+)>/,o=[];return s?.data?.forEach(a=>{let c=a?.parsedJson,u=a.type.match(i);if(u){let p=u[1].split(", ");o.push({...c,baseCoinType:p[0],quoteCoinType:p[1]})}}),this.updateCache(n,o,864e5),o}async getQuoteQuantityOut(t,n,r){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(t.address),s.pure.u64(n),s.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:R(n).div(Math.pow(10,t.baseCoin.decimals)).toString(),baseOutDisplay:R(o).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(a).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(c).div(vf).toString(),baseQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getBaseQuantityOut(t,n,r){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(t.address),s.pure.u64(n),s.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{quoteQuantityDisplay:R(n).div(Math.pow(10,t.quoteCoin.decimals)).toString(),baseOutDisplay:R(o).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(a).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(c).div(vf).toString(),quoteQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getQuantityOut(t,n,r,s){let i=new J;i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[i.object(t.address),i.pure.u64(n),i.pure.u64(r),i.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let o=await this._sdk.fullClient.sendSimulationTransaction(i,s),a=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs))),c=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs))),u=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:R(n).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteQuantityDisplay:R(r).div(Math.pow(10,t.quoteCoin.decimals)).toString(),baseOutDisplay:R(a).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(c).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(u).div(vf).toString(),baseQuantity:n,quoteQuantity:r,baseOut:a,quoteOut:c,deepRequired:u}}async getReferencePool(t){let n=await this.getPools(),r=t.baseCoin.coinType,s=t.quoteCoin.coinType,i=this._deep.coinType;for(let o=0;o<n.length;o++){let a=n[o];if(a.address===t.address)continue;let c=[a.baseCoinType,a.quoteCoinType];if(a.baseCoinType===i&&(c.includes(r)||c.includes(s)))return a}return null}async updateDeepPrice(t,n){let r=await this.getReferencePool(t);return r?(n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[n.object(t.address),n.object(r.pool_id),n.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),n):null}async estimatedMaxFee(t,n,r,s,i,o,a){let c=this.deepCoin;try{let{taker_fee:u,maker_fee:d}=t,p=R(u).div(gr).toString(),f=R(d).div(gr).toString(),g=await this.getMarketPrice(t);console.log("\u{1F680} ~ DeepbookUtilsModule ~ estimatedMaxFee ~ marketPrice:",g);let b=o?r:g!=="0"?g:a;if(b==="0")throw new Error("Cannot get market price");let _=Math.pow(10,t.baseCoin.decimals).toString(),I=Math.pow(10,t.quoteCoin.decimals).toString(),A=R(b).div(_).mul(I).mul(gr).toString();if(s){let B=await this.getMarketPrice(t),j=R(o?r:B!=="0"?B:a).div(_).mul(I).mul(gr).toString(),q=await this.getOrderDeepPrice(t);if(!q)throw new Error("Cannot get deep price");let P=yf(j,r),D=R(n).mul(R(p)).mul(R(q.deep_per_asset)).div(R(gr)),Z=R(n).mul(R(f)).mul(R(q.deep_per_asset)).div(R(gr));q.asset_is_base||(D=D.mul(P).div(R(gr)),Z=Z.mul(P).div(R(gr)));let ce=D.ceil().toString(),te=Z.ceil().toString();return{takerFee:ce,makerFee:te,takerFeeDisplay:Ci(ce,c.decimals).toString(),makerFeeDisplay:Ci(te,c.decimals).toString(),feeType:c.coinType}}if(i){let B=yf(A,o?r:g),L=R(n).mul(B).mul(R(p).mul(1.25)).div(R(gr)).ceil().toFixed(0),j=R(n).mul(B).mul(R(f).mul(1.25)).div(R(gr)).ceil().toFixed(0);return{takerFee:L,makerFee:j,takerFeeDisplay:Ci(L,t.quoteCoin.decimals).toString(),makerFeeDisplay:Ci(j,t.quoteCoin.decimals).toString(),feeType:t.quoteCoin.coinType}}let M=R(n).mul(R(p).mul(1.25)).ceil().toFixed(0),C=R(n).mul(R(f).mul(1.25)).ceil().toFixed(0);return{takerFee:M,makerFee:C,takerFeeDisplay:Ci(M,t.baseCoin.decimals).toString(),makerFeeDisplay:Ci(C,t.baseCoin.decimals).toString(),feeType:t.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(t,n=!0){let r=`getOrderDeepPrice_${t.address}}`,s=this.getCache(r);if(s!==void 0)return s;try{let i=new J,o=!1;n&&t?.baseCoin?.coinType!==this._deep.coinType&&t?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(t,i)&&(o=!0),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[i.object(t.address)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let a=await this._sdk.fullClient.sendSimulationTransaction(i,this._sdk.sdkOptions.simulationAccount.address),c=o?a.commandResults[1]?.returnValues[0]?.bcs:a.commandResults[0]?.returnValues[0]?.bcs,u=this.parseOrderDeepPrice(new Uint8Array(c));return this.updateCache(r,u,6e4),u}catch{return await Rb(2e3),this.getOrderDeepPrice(t,!1)}}parseOrderDeepPrice(t){let n=new DataView(t.buffer),r=n.getUint8(0)!==0,s=Number(n.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:s}}getCoinAssets(t,n,r){return Gt.buildCoinWithBalance(BigInt(R(n).abs().ceil().toString()),t,r)}async getTransactionRelatedBalance(t,n,r,s,i,o,a){let c=this.deepCoin;if(!a)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:t.baseCoin.coinType,decimals:t.baseCoin.decimals},{coinType:t.quoteCoin.coinType,decimals:t.quoteCoin.decimals}];s&&u.push(c);let d=await this.getManagerBalance({account:i,balanceManager:a,coins:u}),p=d?.[n]?.balance||"0",f=d?.[r]?.balance||"0",g=o&&d?.[c.coinType]?.balance||"0";return{baseManagerBlance:p,quoteManagerBlance:f,feeManaerBalance:g}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(t,n,r,s,i,o,a,c,u){let d=R(t).gt(0)&&c,p="0";if(!d)return{feeAsset:this.getEmptyCoin(u,n),haveDepositFee:"0"};if(o||a){let f=R(i).sub(o?s:r);p=f.lte(0)?t:f.sub(t).lt(0)?f.sub(t).toString():"0"}else p=R(i).sub(t).lt("0")?R(i).sub(t).abs().toString():"0";return{feeAsset:R(p).gt("0")?this.getCoinAssets(n,p,u):this.getEmptyCoin(u,n),haveDepositFee:p}}async getTransactionRelatedAssets(t,n,r,s,i,o,a,c,u){try{let d=this.deepCoin,p=be(t.baseCoin.coinType),f=be(t.quoteCoin.coinType),g=p===d.coinType,b=f===d.coinType,_=!g&&!b,{baseManagerBlance:I,quoteManagerBlance:A,feeManaerBalance:M}=await this.getTransactionRelatedBalance(t,p,f,_,o,a,c);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:I,quoteManagerBlance:A});let C,B,L=!1;if(i){a||(r=R(r).add(R(s)).toString());let q=R(A).sub(r).toString();R(q).lt(0)?(L=!0,B=this.getCoinAssets(f,q,u)):B=this.getEmptyCoin(u,f),C=this.getEmptyCoin(u,p)}else{a||(n=R(n).add(R(s)).toString());let q=R(I).sub(n).toString();R(q).lt(0)?(L=!0,C=this.getCoinAssets(p,q,u)):C=this.getEmptyCoin(u,p),B=this.getEmptyCoin(u,f)}let j=this.getFeeAsset(s,d.coinType,n,r,M,b,g,a,u);return{baseAsset:C,quoteAsset:B,feeAsset:j,haveDeposit:L}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getMarketTransactionRelatedAssets(t,n,r,s,i,o,a,c,u,d){try{let p=this.deepCoin,f=be(t.baseCoin.coinType),g=be(t.quoteCoin.coinType),b=f===p.coinType,_=g===p.coinType,I=!b&&!_,A=await this.getTransactionRelatedBalance(t,f,g,I,o,a,c),{feeManaerBalance:M}=A,C=R(A.baseManagerBlance).add(R(d?.base||"0")).toString(),B=R(A.quoteManagerBlance).add(R(d?.quote||"0")).toString(),L;a&&R(M).lt(s)?L=this.getCoinAssets(p.coinType,R(s).sub(M).toString(),u):L=this.getEmptyCoin(u,p.coinType);let j,q;if(i){a||(r=R(r).add(R(s)).toString());let P=R(B).sub(r).toString();if(R(P).lt(0)){let D;R(B).gt(0)&&(D=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.quoteCoin,amountToWithdraw:B,returnAssets:!0,txb:u}));let Z=this.getCoinAssets(g,P,u);D&&u.mergeCoins(Z,[D]),q=Z}else q=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});j=this.getEmptyCoin(u,f)}else{a||(n=R(n).add(R(s)).toString());let P=R(C).sub(n).toString();if(R(P).lt(0)){let D;R(C).gt(0)&&(D=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.baseCoin,amountToWithdraw:C,returnAssets:!0,txb:u}));let Z=this.getCoinAssets(f,P,u);D&&u.mergeCoins(Z,[D]),j=Z}else j=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.baseCoin,amountToWithdraw:n,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,g)}return{baseAsset:j,quoteAsset:q,feeAsset:L}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async createDepositThenPlaceLimitOrder({poolInfo:t,priceInput:n,quantity:r,orderType:s,isBid:i,maxFee:o,account:a,payWithDeep:c,expirationTimestamp:u=Date.now()+31536e8}){try{let d=this.deepCoin,p=t.address,f=t.baseCoin.decimals,g=t.quoteCoin.decimals,b=t.baseCoin.coinType,_=t.quoteCoin.coinType,I=R(n).mul(10**(g-f+9)).toString(),A=be(b),M=be(_),C=new J,B,L;if(i){let D=R(n).mul(R(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();c||(D=R(D).add(R(o)).toString()),L=Gt.buildCoinWithBalance(BigInt(D),M,C)}else{let D=r;c||(D=R(r).abs().add(R(o)).toString()),B=Gt.buildCoinWithBalance(BigInt(D),A,C)}let j=c?R(o).gt(0)?Gt.buildCoinWithBalance(BigInt(R(o).abs().ceil().toString()),d.coinType,C):this.getEmptyCoin(C,d.coinType):this.getEmptyCoin(C,d.coinType),q=C.moveCall({typeArguments:[i?b:_],target:"0x2::coin::zero",arguments:[]}),P=[C.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),C.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),C.object(p),i?q:B,i?L:q,j,C.pure.u8(s),C.pure.u8(0),C.pure.u64(I),C.pure.u64(r),C.pure.bool(i),C.pure.bool(!1),C.pure.u64(u),C.object(he)];return C.moveCall({typeArguments:[A,M],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:P}),C}catch(d){throw d instanceof Error?d:new Error(String(d))}}getEmptyCoin(t,n){return Gt.buildCoinWithBalance(BigInt(0),n,t)}async createDepositThenPlaceMarketOrder({poolInfo:t,quantity:n,isBid:r,maxFee:s,account:i,payWithDeep:o,slippage:a=.01}){try{let c=t.address,u=t.baseCoin.coinType,d=t.quoteCoin.coinType,p=be(u),f=be(d),g=new J,b,_,I=n,A,M=await this.getOrderBook(t,"all",6);if(r){let L=M?.ask?.[0]?.price||"0",j=R(L).mul(R(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();A=R(j).plus(R(j).mul(a)).ceil().toString()}else{let L=await M?.bid?.[0]?.price||"0",j=R(L).mul(R(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();A=R(j).minus(R(j).mul(a)).floor().toString()}r?(o||(A=R(A).add(R(s)).toString()),_=this.getCoinAssets(f,A,g),b=this.getEmptyCoin(g,p)):(o||(I=R(I).add(R(s)).toString()),_=this.getEmptyCoin(g,f),b=this.getCoinAssets(p,I,g));let C=o?R(s).gt(0)?Gt.buildCoinWithBalance(BigInt(R(s).abs().ceil().toString()),this.deepCoin.coinType,g):this.getEmptyCoin(g,this.deepCoin.coinType):this.getEmptyCoin(g,this.deepCoin.coinType),B=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(c),b,_,C,g.pure.u8(0),g.pure.u64(n),g.pure.bool(r),g.pure.bool(o),g.pure.u64(A),g.object(he)];return g.moveCall({typeArguments:[p,f],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:B}),g}catch(c){throw c instanceof Error?c:new Error(String(c))}}async placeLimitOrder({balanceManager:t,poolInfo:n,priceInput:r,quantity:s,isBid:i,orderType:o,maxFee:a,account:c,payWithDeep:u,expirationTimestamp:d=Date.now()+31536e8}){try{let p=this.deepCoin,f=R(r).mul(10**(n.quoteCoin.decimals-n.baseCoin.decimals+9)).toString(),g=n.baseCoin.coinType,b=n.quoteCoin.coinType,_=new J,I=i?R(r).mul(R(s).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString():"0",A=i?"0":s,{baseAsset:M,quoteAsset:C,feeAsset:B,haveDeposit:L}=await this.getTransactionRelatedAssets(n,A,I,a,i,c,u,t,_);if(L){let P=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(n.address),_.object(t),M,C,B.feeAsset,_.pure.u8(o),_.pure.u8(0),_.pure.u64(f),_.pure.u64(s),_.pure.bool(i),_.pure.bool(u),_.pure.u64(d),_.object(he)];return _.moveCall({typeArguments:[g,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:P}),_}let j=new J;R(B.haveDepositFee).gt(0)&&this.depositIntoManager({account:c,balanceManager:t,coin:p,amountToDeposit:B.haveDepositFee,tx:j});let q=[j.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),j.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),j.object(n.address),j.object(t),j.pure.u8(o),j.pure.u8(0),j.pure.u64(f),j.pure.u64(s),j.pure.bool(i),j.pure.bool(u),j.pure.u64(d),j.object(he)];return j.moveCall({typeArguments:[g,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:q}),j}catch(p){throw p instanceof Error?p:new Error(String(p))}}modifyOrder({balanceManager:t,poolInfo:n,orderId:r,newOrderQuantity:s}){let i=new J;return i.moveCall({typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[i.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),i.object(t),i.object(n.address),i.pure.u128(r),i.pure.u64(s),i.object(he)]}),i}async getBestAskprice(t){try{let{baseCoin:n,quoteCoin:r}=t,s=new J,i=await this.getMarketPrice(t),o=R(i).gt(0)?i:Math.pow(10,-1),a=Math.pow(10,6),c=R(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=R(a).mul(Math.pow(10,9+r.decimals-n.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(t.address),s.pure.u64(c),s.pure.u64(u),s.pure.bool(!1),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(s,d),f=[],g=p.commandResults[0].returnValues[0].bcs,b=E.vector(E.u64()).parse(new Uint8Array(g)),_=p.commandResults[0].returnValues[1].bcs,I=E.vector(E.u64()).parse(new Uint8Array(_));return b.forEach((A,M)=>{let C=R(A).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),B=R(I[M]).div(Math.pow(10,n.decimals)).toString();f.push({price:C,quantity:B})}),f?.[0]?.price||0}catch{return 0}}async getBestBidprice(t){try{let{baseCoin:n,quoteCoin:r}=t,s=new J,i=await this.getMarketPrice(t),o=R(i).gt(0)?R(i).div(3).toNumber():Math.pow(10,-6),a=R(i).gt(0)?i:Math.pow(10,6),c=R(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=R(a).mul(Math.pow(10,9+r.decimals-n.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(t.address),s.pure.u64(xi(c,0)),s.pure.u64(xi(u,0)),s.pure.bool(!0),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(s,d),f=[],g=p.commandResults[0].returnValues[0].bcs,b=E.vector(E.u64()).parse(new Uint8Array(g)),_=p.commandResults[0].returnValues[1].bcs,I=E.vector(E.u64()).parse(new Uint8Array(_));return b.forEach((A,M)=>{let C=R(A).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),B=R(I[M]).div(Math.pow(10,n.decimals)).toString();f.push({price:C,quantity:B})}),f?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(t,n){try{let{baseCoin:r,quoteCoin:s}=t,i=new J,o=await this.getMarketPrice(t),a,c;n?(a=R(o).gt(0)?R(o).div(3).toNumber():Math.pow(10,-6),c=R(o).gt(0)?o:Math.pow(10,6)):(a=R(o).gt(0)?o:Math.pow(10,-1),c=R(o).gt(0)?R(o).mul(3).toNumber():Math.pow(10,6));let u=R(a).mul(Math.pow(10,9+s.decimals-r.decimals)).toString(),d=R(c).mul(Math.pow(10,9+s.decimals-r.decimals)).toString();i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[i.object(t.address),i.pure.u64(xi(u,0)),i.pure.u64(xi(d,0)),i.pure.bool(n),i.object(he)],typeArguments:[r.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(i,p),g=[],b=f.commandResults[0].returnValues[0].bcs,_=E.vector(E.u64()).parse(new Uint8Array(b)),I=f.commandResults[0].returnValues[1].bcs,A=E.vector(E.u64()).parse(new Uint8Array(I));return _.forEach((M,C)=>{let B=R(M).div(Math.pow(10,9+s.decimals-r.decimals)).toString(),L=R(A[C]).div(Math.pow(10,r.decimals)).toString();g.push({price:B,quantity:L})}),g?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:t,poolInfo:n,baseQuantity:r,quoteQuantity:s,isBid:i,maxFee:o,account:a,payWithDeep:c,slippage:u=.01,settled_balances:d={base:"0",quote:"0"}}){try{let p=be(n.baseCoin.coinType),f=be(n.quoteCoin.coinType),g=new J;d&&(R(d.base).gt(0)||R(d.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:n,balanceManager:t},g);let{baseAsset:b,quoteAsset:_,feeAsset:I}=await this.getMarketTransactionRelatedAssets(n,r,s,o,i,a,c,t,g,d),A=await this.getOrderBook(n,"all",6);if(i){let B=A?.ask?.[0]?.price||"0",L=R(B).mul(R(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=R(L).plus(R(L).mul(u)).ceil().toString()}else{let B=await A?.bid?.[0]?.price||"0",L=R(B).mul(R(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=R(L).minus(R(L).mul(u)).floor().toString()}let M=s,C=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(n.address),g.object(t),b,_,I,g.pure.u8(0),g.pure.u64(r),g.pure.bool(i),g.pure.bool(c),g.pure.u64(M),g.object(he)];return g.setSenderIfNotSet(a),g.moveCall({typeArguments:[p,f],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),g}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getOrderInfoList(t,n){try{let r=new J;t.forEach(u=>{let d=u?.pool,p=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(d.pool_id),r.pure.u128(BigInt(p))],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let s=await this._sdk.fullClient.sendSimulationTransaction(r,n),i=E.struct("ID",{bytes:E.Address}),o=E.struct("OrderDeepPrice",{asset_is_base:E.bool(),deep_per_asset:E.u64()}),a=E.struct("Order",{balance_manager_id:i,order_id:E.u128(),client_order_id:E.u64(),quantity:E.u64(),filled_quantity:E.u64(),fee_is_deep:E.bool(),order_deep_price:o,epoch:E.u64(),status:E.u8(),expire_timestamp:E.u64()}),c=[];return s?.commandResults?.forEach(u=>{let d=u.returnValues[0].bcs,p=a.parse(new Uint8Array(d));c.push(p)}),c}catch{return[]}}decodeOrderId(t){let n=t>>BigInt(127)===BigInt(0),r=t>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=t&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:n,price:r,orderId:s}}async getOpenOrder(t,n,r,s,i=!1,o=new J){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(t.address),i?r:o.object(r)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let p=await this._sdk.fullClient.sendSimulationTransaction(o,n);console.log("\u{1F680} ~ DeepbookUtilsModule ~ getOpenOrder ~ res:",p?.FailedTransaction?.status);let f=p.commandResults[i?1:0].returnValues[0].bcs;a=E.struct("VecSet",{constants:E.vector(E.U128)}).parse(new Uint8Array(f)).constants}if(a.length===0)return[];let c=a.map(p=>({pool:{pool_id:t.address,baseCoinType:t.baseCoin.coinType,quoteCoinType:t.quoteCoin.coinType},orderId:p})),u=await this.getOrderInfoList(c,n)||[],d=[];return u.forEach(p=>{let f=this.decodeOrderId(BigInt(p.order_id));d.push({...p,price:f.price,isBid:f.isBid,pool:t})}),d}async getAllMarketsOpenOrders(t,n){try{let r=await this.getPools(),s=new J;r.forEach(p=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(p.pool_id),s.object(n)],typeArguments:[p.baseCoinType,p.quoteCoinType]})});let o=(await this._sdk.fullClient.sendSimulationTransaction(s,t)).commandResults?.map(p=>p.returnValues?.[0]?.bcs)||[],a=E.struct("VecSet",{constants:E.vector(E.U128)}),c=[];o.forEach((p,f)=>{let g=a.parse(new Uint8Array(p)).constants;g.length>0&&g.forEach(b=>{c.push({pool:r[f],orderId:b})})});let u=await this.getOrderInfoList(c,t)||[],d=[];return c.forEach((p,f)=>{let g=this.decodeOrderId(BigInt(p.orderId)),b=u.find(_=>_.order_id===p.orderId)||{};d.push({...p,...b,price:g.price,isBid:g.isBid})}),d}catch(r){return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getAllMarketsOpenOrders ~ error:",r),[]}}cancelOrders(t,n,r=new J){return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(n),r.object(s.poolInfo.address),r.pure.u128(s.orderId),r.object(he)],typeArguments:[s.poolInfo.baseCoin.coinType,s.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(t,n,r,s,i,o){let a=this._sdk.fullClient,u=await new qx({client:a,address:i,network:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(t,n,r,s)}processOrderBookData(t,n,r,s){let i=t.returnValues[0].bcs,o=E.vector(E.u64()).parse(new Uint8Array(i)),a=t.returnValues[1].bcs,c=E.vector(E.u64()).parse(new Uint8Array(a)),u={};return o.forEach((p,f)=>{let g=R(p).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),b=R(c[f]).div(Math.pow(10,n.decimals)).toString();u[g]?u[g]={price:g,quantity:R(u[g].quantity).add(b).toString()}:u[g]={price:g,quantity:b}}),Object.values(u)}getLevel2RangeTx(t,n,r,s,i=new J){let{baseCoin:o,quoteCoin:a}=t,c=xi(R(r).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0),u=xi(R(s).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0);return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[i.object(t.address),i.pure.u64(c),i.pure.u64(u),i.pure.bool(n),i.object(he)],typeArguments:[o.coinType,a.coinType]}),i}async fetchOrderBook(t,n,r,s,i,o){let a=new J,{baseCoin:c,quoteCoin:u}=t;try{if(n==="bid"||n==="all"){let b=s,_=r==="0"?i:r;a=this.getLevel2RangeTx(t,!0,b,_,a)}if(n==="ask"||n==="all"){let b=r==="0"?s:r,_=i;a=this.getLevel2RangeTx(t,!1,b,_,a)}let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(a,d),f=[];(n==="bid"||n==="all")&&(f=p.commandResults?.[0]?this.processOrderBookData(p.commandResults[0],c,u,o):[]);let g=[];if(n==="ask"||n==="all"){let b=n==="ask"?0:1;g=p.commandResults?.[b]?this.processOrderBookData(p.commandResults[b],c,u,o):[]}return{bid:f.sort((b,_)=>_.price-b.price),ask:g.sort((b,_)=>b.price-_.price)}}catch{let p=this._sdk.sdkOptions.simulationAccount.address,f=[],g=[];try{let b=this.getLevel2RangeTx(t,!0,s,r),_=await this._sdk.fullClient.sendSimulationTransaction(b,p);f=_.commandResults?.[0]?this.processOrderBookData(_.commandResults[0],c,u,o):[]}catch{f=[]}try{let b=this.getLevel2RangeTx(t,!1,s,r),_=await this._sdk.fullClient.sendSimulationTransaction(b,p);g=_.commandResults?.[0]?this.processOrderBookData(_.commandResults[0],c,u,o):[]}catch{g=[]}return{bid:f,ask:g}}}async getOrderBook(t,n,r){let s={bid:[],ask:[]};try{let i=await this.getMarketPrice(t),o=n,a=Math.pow(10,-r),c=Math.pow(10,r),u=await this.fetchOrderBook(t,o,i,a,c,r);return{bid:u?.bid,ask:u?.ask}}catch{return s}}async getOrderBookOrigin(t,n){try{let r=new J,s=await this.getMarketPrice(t),{baseCoin:i,quoteCoin:o}=t;if(n==="bid"||n==="all"){let p=Math.pow(10,-6),f=s,g=R(p).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=R(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(t.address),r.pure.u64(g),r.pure.u64(b),r.pure.bool(!0),r.object(he)],typeArguments:[i.coinType,o.coinType]})}if(n==="ask"||n==="all"){let p=s,f=Math.pow(10,6),g=R(p).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=R(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(t.address),r.pure.u64(g),r.pure.u64(b),r.pure.bool(!1),r.object(he)],typeArguments:[i.coinType,o.coinType]})}let a=this._sdk.sdkOptions.simulationAccount.address,c=await this._sdk.fullClient.sendSimulationTransaction(r,a),u=[];if(n==="bid"||n==="all"){let p=c.commandResults[0]?.returnValues[0]?.bcs,f=E.vector(E.u64()).parse(new Uint8Array(p)),g=c.commandResults[0]?.returnValues[1]?.bcs,b=E.vector(E.u64()).parse(new Uint8Array(g));f.forEach((_,I)=>{let A=R(_).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),M=R(b[I]).div(Math.pow(10,i.decimals)).toString();u.push({price:A,quantity:M})})}let d=[];if(n==="ask"||n==="all"){let p=n==="ask"?0:1,f=c.results[p]?.returnValues[0]?.[0],g=E.vector(E.u64()).parse(new Uint8Array(f)),b=c.results[p]?.returnValues[1]?.[0],_=E.vector(E.u64()).parse(new Uint8Array(b));g.forEach((I,A)=>{let M=R(I).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),C=R(_[A]).div(Math.pow(10,i.decimals)).toString();d.push({price:M,quantity:C})})}return{bid:u,ask:d}}catch{return{bids:[],asks:[]}}}async getWalletBalance(t){let n=await this._sdk.fullClient?.getOwnerCoinBalances(t);return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getWalletBalance ~ result:",n),Object.fromEntries(n.map((s,i)=>[be(s.coinType),{coinType:s.coinType,totalBalance:s.balance,coinBalance:s.coinBalance,addressBalance:s.addressBalance}]))}async getAccount(t,n,r=new J){for(let o=0;o<n.length;o++){let a=n[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof t=="string"?r.object(t):t],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let s=await this._sdk.fullClient.sendSimulationTransaction(r,this._sdk.senderAddress);if(s?.Transaction?.events?.length===0)return null;let i=[];return s?.Transaction?.events?.forEach((o,a)=>{let c=o?.bcs,u=Vb.parse(c),d=u.open_orders,p=u.owed_balances,f=u.settled_balances,g=u.unclaimed_rebates,b=u.taker_volume;i.push({balance_manager_id:t,open_orders:d,owed_balances:p,settled_balances:f,unclaimed_rebates:g,taker_volume:b,poolInfo:n[a]})}),i}async getSuiTransactionResponse(t,n=!1){let r=`${t}_getSuiTransactionResponse`,s=this.getCache(r,n);if(s!==void 0)return s;let i;try{i=await this._sdk.fullClient.getTransaction({digest:t,include:{events:!0,effects:!0,balanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransaction({digest:t,include:{events:!0,effects:!0}})}return this.updateCache(r,i,864e5),i}transformExtensions(t,n,r=!0){let s=[];for(let i of n){let{key:o}=i.fields,{value:a}=i.fields;if(o==="labels")try{a=JSON.parse(decodeURIComponent(Gx.decode(a)))}catch{}r&&(t[o]=a),s.push({key:o,value:a})}delete t.extension_fields,r||(t.extensions=s)}async getCoinConfigs(t=!1,n=!0){let r=this.sdk.sdkOptions.coinlist.handle,s=`${r}_getCoinConfigs`,i=this.getCache(s,t);if(i)return i;let a=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),c=await this._sdk.fullClient.batchGetObjects(a,{json:!0}),u=[];return c.forEach(d=>{let p=this.buildCoinConfig(d,n);this.updateCache(`${r}_${p.address}_getCoinConfig`,p,864e5),u.push({...p})}),this.updateCache(s,u,864e5),u}buildCoinConfig(t,n=!0){let r=Pb(t);r=r.value.fields;let s={...r};return s.id=Ub(t),s.address=Ls(r.coin_type.fields.name).full_address,r.pyth_id&&(s.pyth_id=Ft(r.pyth_id)),this.transformExtensions(s,r.extension_fields.fields.contents,n),delete s.coin_type,s}updateCache(t,n,r=3e5){let s=this._cache[t];s?(s.overdueTime=bf(r),s.value=n):s=new Au(n,bf(r)),this._cache[t]=s}getCache(t,n=!1){let r=this._cache[t],s=r?.isValid();if(!n&&s)return r.value;s||delete this._cache[t]}async createPermissionlessPool({tickSize:t,lotSize:n,minSize:r,baseCoinType:s,quoteCoinType:i}){let o=new J,a=Gt.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",o);o.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[s,i],arguments:[o.object(this.sdk.sdkOptions.deepbook.registry_id),o.pure.u64(t),o.pure.u64(n),o.pure.u64(r),a]});try{let c=await this._sdk.fullClient.sendSimulationTransaction(o,this.sdk.senderAddress);if(c?.Transaction?.effects?.status?.success)return o;if(c?.Transaction?.effects?.status?.error&&c.Transaction.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(c){throw c instanceof Error?c:new Error(String(c))}return o}newWithCustomOwnerCaps({owner:t,appType:n}){let r=new J,s=n||`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::MarginApp`,[i,o,a,c]=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new_with_custom_owner_caps`,arguments:[r.object(this._sdk.sdkOptions.deepbook.registry_id),r.pure.address(t)],typeArguments:[s]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i],typeArguments:[]}),r.moveCall({target:"0x2::transfer::public_share_object",arguments:[i],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),r.transferObjects([o,a,c],t),r}};var Cu="0x0000000000000000000000000000000000000000000000000000000000000006",Wq="pool_script",Hq="pool_script_v2",Jq="router",Zq="router_with_partner",Kq="fetcher_script",Xq="expect_swap",Yq="utils",Qq="0x1::coin::CoinInfo",eG="0x1::coin::CoinStore",tG="custodian_v2",nG="clob_v2",rG="endpoints_v2",sG=e=>{if(typeof e=="string"&&e.startsWith("0x"))return"object";if(typeof e=="number"||typeof e=="bigint")return"u64";if(typeof e=="boolean")return"bool";throw new Error(`Unknown type for value: ${e}`)},iG=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];import Fb from"decimal.js";Fb.config({precision:64,rounding:Fb.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var lG=({totalAssetsValue:e,totalDebtValue:t})=>R(t).eq(0)||R(e).eq(0)?"0":R(e).div(R(t)).toString(),$b=e=>{let{base_margin_pool_id:t,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i}=e.value.fields,{liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}=e.value.fields.risk_ratios.fields;return{id:e.id.id,name:e.name,base_margin_pool_id:t,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i,liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}},qb=(e,t)=>{let{deposit_coin_type:n}=t,r=e.id,{max_utilization_rate:s,min_borrow:i,protocol_spread:o,supply_cap:a}=e.config.margin_pool_config,{maintainer_fees:c,protocol_fees:u}=e.protocol_fees,{total_supply:d,total_borrow:p}=e.state,f=R(a).sub(d).toString();return{deposit_coin_type:n,id:r,supply_cap:a,total_supply:d,total_borrow:p,available_supply:f,max_utilization_rate:s,min_borrow:i,protocol_spread:o,maintainer_fees:c,protocol_fees:u}};var jr=1000000000n,Hx=365n*24n*60n*60n*1000n;function Jx(e,t){return t===0n?0n:e*jr/t}function Zx(e,t){let{base_rate:n,base_slope:r,optimal_utilization:s,excess_slope:i}=t;if(e<s)return n+e*r/jr;{let o=e-s,a=s*r/jr,c=o*i/jr;return n+a+c}}function Gb(e,t){let n=e*t,r=n/jr;return n%jr>0n?r+1n:r}function Kx(e,t,n,r){let s=t.borrow_shares===0n?jr:t.total_borrow*jr/t.borrow_shares,i=Gb(e,s),o=Jx(t.total_borrow,t.total_supply),a=Zx(o,n),c=r-t.last_update_timestamp,u=t.total_borrow*a/jr*c/Hx,d=t.borrow_shares===0n?0n:Gb(u,e*jr/t.borrow_shares),p=i+d;return{confirmedDebt:i,estimatedInterest:d,totalDebt:p,annualInterestRate:a}}function pG(e,t,n,r,s=60000n){let i=r+s,{totalDebt:o}=Kx(e,t,n,i);return o}var _f=10n;function Xx(e,t){if(!_f)throw new Error("oraclePriceMultiplierDecimal is required");if(e===0n)throw new Error("Invalid oracle price");if(t<0n){let n=10n**(_f- -t);return e*n}return e/10n**(t+_f)}var wo=class{_sdk;hasChangeConnection=!1;_commonPythPrice;_cache={};constructor(t){this._sdk=t,this._commonPythPrice=new kb(t.fullClient)}get sdk(){return this._sdk}async updatePythPriceIDs(t,n){let r=null,s=null;try{r=await this._commonPythPrice.getPriceFeedsUpdateData(t)}catch(a){s=a,console.log("Error: ",a)}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${s?.message}`);let i=[];try{i=await this._commonPythPrice.updatePriceFeeds(n,r,t)}catch(a){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${a}`)}let o=new Map;for(let a=0;a<t.length;a++)o.set(t[a],i[a]);return o}priceCheck(t,n=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-t.last_update_time)>n))return t}async getLatestPrice(t,n=!1){let r={},s=[];if(n?t.forEach(a=>{let c=this._sdk.fullClient.getCache(`getLatestPrice_${a.coinType}`);c&&this.priceCheck(c,60)?r[a.coinType]=c:s.push(a.coinType)}):s=t.map(a=>a.coinType),s.length===0)return r;let i=t.map(a=>a.feed);return(await this._commonPythPrice.getLatestPriceFeeds(i))?.parsed?.forEach((a,c)=>{let u=a.price;if(u){let{price:d,expo:p}=u,f=R(d).mul(R(10).pow(R(p))).toString(),b={coin_type:t[c].coinType,price:f,oracle_price:0n,last_update_time:u.publish_time};b.oracle_price=Xx(BigInt(d),BigInt(p)),r[s[c]]=b,this._sdk.fullClient.updateCache(`getLatestPrice_${b.coin_type}`,b)}}),r}};var Nu=class{_sdk;pythPrice;_deep;_cache={};constructor(t){if(!t)throw new Error("SDK instance is required");this._sdk=t,this.pythPrice=new wo(t),this._deep=t.sdkOptions.network==="mainnet"?Bb:Mb}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(t,n=new J){if(!t)throw new Error("Pool info is required");if(!t.id)throw new Error("Pool ID is required");if(!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:s}=t;try{let{margin_manager:i,initializer:o}=this.createMarginManager(t,n);return this.shareMarginManager({marginManager:i,initializer:o,baseCoin:r,quoteCoin:s},n),{tx:n,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create and share margin manager: ${i instanceof Error?i.message:String(i)}`)}}createMarginManager(t,n=new J){if(!t)throw new Error("Pool info is required");if(!t.id)throw new Error("Pool ID is required");let{id:r,baseCoin:s,quoteCoin:i}=t;try{let[o,a]=n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(r),n.object(this._sdk.sdkOptions.margin_utils.registry_id),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(he)],typeArguments:[s.coinType,i.coinType]});return{tx:n,margin_manager:o,initializer:a}}catch(o){throw new Error(`Failed to create margin manager: ${o instanceof Error?o.message:String(o)}`)}}shareMarginManager({marginManager:t,initializer:n,baseCoin:r,quoteCoin:s},i=new J){try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[t,n],typeArguments:[r.coinType,s.coinType]}),i}catch(o){throw new Error(`Failed to share margin manager: ${o instanceof Error?o.message:String(o)}`)}}async getBalanceManagerByMarginManager(t){if(!t||typeof t!="string")throw new Error("Valid account address is required");let n=`
|
|
1024
|
+
`);var _x=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];var u$=ru("mainnet"),l$=ru("testnet");var d$=E.struct("Table<ID, bool>",{id:E.Address,size:E.u64()}),wx=E.struct("TypeName",{name:E.string()}),p$=E.struct("OptionU64",{is_none:E.bool(),v:E.u64()}),Tx=E.struct("UID",{id:E.Address}),f$=E.struct("TableSuiRaw",{id:Tx,size:E.u64()});var kx=class{constructor(e,t,n,r){this._cache={},this._env="mainnet",this._client=e,this._env=n||"mainnet",this._graphQLClient=t,this._jsonRpcClient=r}async fetchCoinMetadata(e){let t=`coin_metadata_${e}`,n=this.getCache(t);if(n)return n;let r=await this._client.getCoinMetadata({coinType:e});return this.updateCache(t,r.coinMetadata),r.coinMetadata}async fetchCoinMetadataId(e){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let t=`coin_metadata_id_${e}`,n=this.getCache(t);if(n)return n;let r=(await this._graphQLClient.query({query:hx,variables:{coinType:`0x2::coin::CoinMetadata<${e}>`}})).data?.objects?.nodes?.[0]?.address??null;return r&&this.updateCache(t,r),r}async getSuiTransactionResponse(e){try{return await this._client.getTransaction({digest:e,include:{effects:!0,events:!0,balanceChanges:!0,transaction:!0,objectTypes:!0}})}catch(t){throw console.log("getSuiTransactionResponse error",t),t}}async getTransactionByGraphQL(e){try{return await this._graphQLClient.query({query:gx,variables:{digest:e}})}catch(t){throw console.log("getTransactionByGraphQL error",t),t}}async queryEventsByGraphQL(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:bx,variables:{type:e,first:r,...i?{after:i}:{}}})).data?.events,c=a?.nodes??[],u=a?.pageInfo;s=[...s,...c],o=u?.hasNextPage??!1,i=u?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async queryTransactionBlocksByPage(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");if(!(e.sentAddress!=null||e.affectedAddress!=null||e.affectedObject!=null||e.function!=null))throw new Error("At least one of sentAddress, affectedAddress, affectedObject, function is required");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0,a={};e.sentAddress&&(a.sentAddress=X(e.sentAddress)),e.affectedAddress&&(a.affectedAddress=X(e.affectedAddress)),e.affectedObject&&(a.affectedObject=X(e.affectedObject)),e.function&&(a.function=e.function);do{let c=(await this._graphQLClient.query({query:vx,variables:{filter:a,first:r,...i?{after:i}:{}}})).data?.transactions,u=c?.nodes??[],d=c?.pageInfo;s=[...s,...u],o=d?.hasNextPage??!1,i=d?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async queryEventsByPage(e,t="all"){let n=[],r=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this._jsonRpcClient.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(n=[...n,...o.data],r=o.hasNextPage,i=o.nextCursor):r=!1}while(s&&r);return{data:n,next_cursor:i,has_next_page:r}}async getOwnedObjectsByPage(e,t,n="all"){let r=async s=>{let i=[],o=!0,a=n==="all",c=a?null:n.cursor;do{let u=await s.listOwnedObjects({owner:e,type:t,cursor:c??void 0,limit:a?1e3:n.limit??void 0,include:{content:!0,previousTransaction:!0,json:!0}});i=[...i,...u.objects],o=u.hasNextPage,c=u.cursor??null}while(a&&o);return{data:i,next_cursor:c,has_next_page:o}};try{return await r(this._client)}catch(s){let i=s,o=this._env==="testnet"?"testnet":"mainnet";for(let a of _x)try{let c=af(new Ko({baseUrl:a,network:o}),this._graphQLClient,this._env);return await r(c._client)}catch(c){i=c;continue}throw i}}async getAllDynamicFields(e,t="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=t==="all",r=n?50:t.limit??50,s=[],i=n?null:t.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:yx,variables:{id:X(e),first:r,...i?{after:i}:{}}})).data?.address?.dynamicFields,c=a?.nodes??[],u=a?.pageInfo;s=[...s,...c],o=u?.hasNextPage??!1,i=u?.endCursor??null}while(n&&o);return{data:s,next_cursor:i,has_next_page:o}}async getDynamicFieldsByPage(e,t="all"){let n=[],r=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this._client.listDynamicFields({parentId:e,cursor:i??void 0,limit:s?1e3:t.limit??void 0});n=[...n,...o.dynamicFields],r=o.hasNextPage,i=o.cursor??null}while(s&&r);return{data:n,next_cursor:i,has_next_page:r}}async getDynamicFieldObjects(e,t,n,r,s){let i=t.map(o=>mx(e,o,n,r));return i.length===0?[]:this.batchGetObjects(i,s)}async batchGetObjects(e,t,n=1e3){let r=[];try{for(let s=0;s<Math.ceil(e.length/n);s++){let i=e.slice(s*n,n*(s+1)),o=await this._client.getObjects({objectIds:i,include:t});r=[...r,...o.objects]}}catch(s){console.log(s)}return r}async calculationTxGas(e){let t=e.getData?.()?.sender??e.blockData?.sender;if(t==null)throw Error("sdk sender is empty");e.setSender(t);let n=await this._client.simulateTransaction({transaction:e,include:{effects:!0}}),r=n.Transaction??n.FailedTransaction;if(!r?.effects?.gasUsed)throw new Error("Simulation did not return effects");let{gasUsed:s}=r.effects;return Number(s.computationCost)+Number(s.storageCost)-Number(s.storageRebate)}async sendTransaction(e,t){try{return await this._client.signAndExecuteTransaction({transaction:t,signer:e,include:{effects:!0,events:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(e,t,n=!0){try{return e.setSender(t),await this._client.simulateTransaction({transaction:e,include:{events:!0,balanceChanges:!0,effects:!0,objectChanges:!0,commandResults:!0},checksEnabled:n})}catch(r){throw console.log("simulateTransaction error",r),r}}async executeTx(e,t,n){try{if(n){let r=typeof e=="string"?X(e):X(e.getPublicKey().toSuiAddress());return await this.sendSimulationTransaction(t,r)}else{if(typeof e=="string")throw new Error("Cannot send transaction with string address - keypair required for signing");return await this.sendTransaction(e,t)}}catch(r){return r}}async getOwnerCoinAssets(e,t){let n=[],r=null;if(t)for(;;){let s=await this._client.listCoins({owner:e,coinType:t,cursor:r??void 0});for(let i of s.objects)BigInt(i.balance)>0&&n.push({coin_type:Ai(i.type).type_arguments[0],coin_object_id:i.objectId,balance:BigInt(i.balance)});if(r=s.cursor??null,!s.hasNextPage)break}else{let s=null;do{let i=await this._client.listOwnedObjects({owner:e,cursor:s??void 0,include:{json:!0}});if(i.objects.forEach(o=>{let a=Ai(o.type);o.type.includes('"0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin')&&BigInt(o.balance)>0&&n.push({coin_type:sf(a.type_arguments[0],!1),coin_object_id:o.json.id,balance:BigInt(o.json.balance)})}),s=i.cursor??null,!i.hasNextPage)break}while(!0)}return n}async getOwnerCoinBalances(e,t){if(t)return[(await this._client.getBalance({owner:e,coinType:t})).balance];let n=[],r=null;do{let s=await this._client.listBalances({owner:e,cursor:r??void 0});if(n.push(...s.balances),r=s.cursor??null,!s.hasNextPage)break}while(!0);return n}updateCache(e,t,n=864e5){let r=this._cache[e];r?(r.overdue_time=nb(n),r.value=t):r=new gA(t,nb(n)),this._cache[e]=r}getCache(e,t=!1){let n=this._cache[e],r=n?.isValid();if(!t&&r)return n.value;r||delete this._cache[e]}};function af(e,t,n,r){let s=new kx(e,t,n,r);return new Proxy(s,{get(i,o,a){if(o in i)return Reflect.get(i,o,a);if(o in i._client){let c=Reflect.get(i._client,o);return typeof c=="function"?c.bind(i._client):c}throw new Error(`Property or method "${String(o)}" does not exist on FullClient or its client.`)}})}var Sx=Ta(ka(),1);var y$=new Sx.default(1e6),Ex=(e=>(e[e.BelowRange=0]="BelowRange",e[e.InRange=1]="InRange",e[e.AboveRange=2]="AboveRange",e))(Ex||{}),Qp=10n,Ox={pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",hermes_service_urls:[]},Ix={"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{coin_type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",price_feed_id:"0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",coin_decimals:6},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",price_feed_id:"0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",coin_decimals:9},"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS":{coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",price_feed_id:"0xe5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",coin_decimals:9},"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP":{coin_type:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",price_feed_id:"0x29bdd5248234e33bd93d3b81100b5fa32eaa5997843847e2c2cb16d7c6d9f7ff",coin_decimals:6},"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX":{coin_type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",price_feed_id:"0x88250f854c019ef4f88a5c073d52a18bb1c6ac437033f5932cd017d24917ab46",coin_decimals:9},"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN":{coin_type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",price_feed_id:"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",coin_decimals:9},"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI":{coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",price_feed_id:"0x6120ffcf96395c70aa77e72dcb900bf9d40dccab228efca59a17b90ce423d5e8",coin_decimals:9},"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH":{coin_type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",price_feed_id:"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",coin_decimals:8},"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL":{coin_type:"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL",price_feed_id:"0xeba0732395fae9dec4bae12e52760b35fc1c5671e2da8b449c9af4efe5d54341",coin_decimals:9},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{coin_type:"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC",price_feed_id:"0x8f257aab6e7698bb92b15511915e593d6f8eae914452f781874754b03d0c612b",coin_decimals:8},"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL":{coin_type:"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL",price_feed_id:"0xe67d98cc1fbd94f569d5ba6c3c3c759eb3ffc5d2b28e64538a53ae13efad8fd1",coin_decimals:9}};function Ax(e,t){if(!Qp)throw new Error("oraclePriceMultiplierDecimal is required");if(e===0n)throw new Error("Invalid oracle price");if(t<0n){let n=10n**(Qp- -t);return e*n}return e/10n**(t+Qp)}var cb=16*1024,kb=class{constructor(e,t=Ox){this.hasChangeConnection=!1,this.pythConfigs=t,this.fullClient=e;let n=[...t.hermes_service_urls];n.includes("https://hermes.pyth.network")||n.push("https://hermes.pyth.network"),this.hermesClients=n.map(r=>new gu(r,{timeout:3e3}))}async getFeedInfoList(e){let t=e.map(n=>this.getFeedInfo(n,!1));return await Promise.all(t)}priceCheck(e,t=60){let n=Math.floor(Date.now()/1e3);if(!(Math.abs(n-e.last_update_time)>t))return e}async getPackageId(e){let t=(await this.fullClient.getObject({objectId:e,include:{json:!0}}))?.object?.json;if(t?.upgrade_cap?.package)return t.upgrade_cap.package;throw new Error("upgrade_cap not found")}async getWormholePackageId(){let{wormhole_state_id:e}=this.pythConfigs,t=`getWormholePackageId_${e}`,n=this.fullClient.getCache(t);if(n)return n;let r=await this.getPackageId(this.pythConfigs.wormhole_state_id);return this.fullClient.updateCache(t,r),r}async getLatestPrice(e,t=!1){let n={},r=[];if(t?e.forEach(i=>{let o=this.fullClient.getCache(`getLatestPrice_${i}`);o&&this.priceCheck(o,60)?n[i]=o:r.push(i)}):r=[...e],r.length===0)return n;let s=await this.getFeedInfoList(r);return(await this.getLatestPriceFeeds(s.map(i=>i.price_feed_id)))?.parsed?.forEach((i,o)=>{if(i){let{price:a,expo:c,publish_time:u}=i.price,d=vu(a).mul(vu(10).pow(vu(c))).toString(),p=s[o],f={coin_type:p.coin_type,price:d,coin_decimals:p.coin_decimals,oracle_price:0n,last_update_time:u};f.oracle_price=Ax(BigInt(a),BigInt(c)),n[r[o]]=f,this.fullClient.updateCache(`getLatestPrice_${f.coin_type}`,f)}}),n}async getPriceFeedsUpdateData(e){let t=null;for(let n of this.hermesClients)try{return(await n.getLatestPriceUpdates(e,{encoding:"hex"})).binary.data.map(r=>Buffer.from(r,"hex"))}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getPriceFeedsUpdateData ~ e:",r),t=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getPriceFeedsUpdateData Detailed error: ${t?.message}`)}async getLatestPriceFeeds(e){let t=null;for(let n of this.hermesClients)try{return await n.getLatestPriceUpdates(e,{parsed:!0})}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getLatestPriceFeeds ~ error:",r),t=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getLatestPriceFeeds Detailed error: ${t?.message}`)}extractVaaBytesFromAccumulatorMessage(e){let t=7+e.readUint8(6)+1,n=e.readUint16BE(t),r=t+2;return e.subarray(r,r+n)}async verifyVaas(e,t){let n=await this.getWormholePackageId(),r=[];for(let s of e){let[i]=t.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[t.object(this.pythConfigs.wormhole_state_id),t.pure(E.vector(E.u8()).serialize(Array.from(s),{maxSize:cb}).toBytes()),t.object(he)]});r.push(i)}return r}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let e=null,t=!0;for(;t;){let n=await this.fullClient.listDynamicFields({parentId:this.pythConfigs.pyth_state_id,cursor:e});for(let r of n.dynamicFields)if(r.name.type==="vector<u8>"){let s=r.$kind==="DynamicObject"&&r.childId?r.childId:r.fieldId,i=await this.fullClient.getObject({objectId:s,include:{json:!0}}),o=i.object.type;if(o.includes("table::Table")){let a=o.replace(/.*table::Table</,"").replace(/>$/,"").split(",")[0].trim();return this.priceTableInfo={id:i.object.objectId,fieldType:a},this.priceTableInfo}}t=n.hasNextPage,e=n.cursor}}if(this.priceTableInfo===void 0)throw new Error(" getPriceTableInfo Price table not found");return this.priceTableInfo}async getPriceFeedObjectId(e){let t=e.replace("0x",""),n=`getPriceFeedObjectId_${t}`,r=this.fullClient.getCache(n);if(r)return r;let{id:s,fieldType:i}=await this.getPriceTableInfo(),o=E.struct("PriceIdentifier",{bytes:E.vector(E.u8())}).serialize({bytes:Array.from(Buffer.from(t,"hex"))}).toBytes(),a=(await this.fullClient.getDynamicField({parentId:s,name:{type:i,bcs:o}})).dynamicField.value.bcs,c=a instanceof Uint8Array?a:new Uint8Array(Object.values(a)),u="0x"+Array.from(c).map(d=>d.toString(16).padStart(2,"0")).join("");return this.fullClient.updateCache(n,u),u}async verifyVaasAndGetHotPotato(e,t,n){if(t.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.extractVaaBytesFromAccumulatorMessage(t[0]),s=await this.verifyVaas([r],e),[i]=e.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[e.object(this.pythConfigs.pyth_state_id),e.pure(E.vector(E.u8()).serialize(Array.from(t[0]),{maxSize:cb}).toBytes()),s[0],e.object(he)]});return i}async buildUpdatePythPricePayload(e,t,n){let{pyth_state_id:r,pyth_published_at:s,pyth_package_id:i}=this.pythConfigs,o=(await this.getFeedInfoList(e)).map(d=>d.price_feed_id);if(e.length!==o.length)throw Error("find feed id fail");let a=await this.getPriceFeedsUpdateData(o);if(!a)throw new Error("get price update data fail");if(a.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let c=await this.verifyVaasAndGetHotPotato(t,a,s),u=0;for(let d of o){let p=await this.getPriceFeedObjectId(d);if(!p)throw new Error(`Price feed ${d} not found, please create it first`);c=n({tx:t,coinType:e[u],priceUpdatesHotPotato:c,priceInfoObjectId:p}),u+=1}return t.moveCall({target:`${s}::hot_potato_vector::destroy`,arguments:[c],typeArguments:[`${i}::price_info::PriceInfo`]}),t}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let e=(await this.fullClient.getObject({objectId:this.pythConfigs.pyth_state_id,include:{json:!0}}))?.object?.json;if(!e)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=Number(e.base_update_fee)}return this.baseUpdateFee}async updatePriceFeeds(e,t,n){let r=this.pythConfigs.pyth_package_id,s=await this.verifyVaasAndGetHotPotato(e,t,r),i=await this.getBaseUpdateFee(),o=e.splitCoins(e.gas,n.map(()=>e.pure.u64(i))),a=[],c=0;for(let u of n){let d=await this.getPriceFeedObjectId(u);if(!d)throw new Error(`Price feed ${u} not found, please create it first`);a.push(d),[s]=e.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[e.object(this.pythConfigs.pyth_state_id),s,e.object(d),o[c],e.object(he)]}),c++}return e.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[s],typeArguments:[`${r}::price_info::PriceInfo`]}),a}async buildUpdatePythPricePayloadV2(e,t,n){if(e.length===0)return t;let r=(await this.getFeedInfoList(e)).map(a=>a.price_feed_id);if(e.length!==r.length)throw Error("find feed id fail");let s=await this.getPriceFeedsUpdateData(r);if(!s)throw new Error("get price update data fail");if(s.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=await this.updatePriceFeeds(t,s,r),o=0;for(let a of i)n({tx:t,coinType:e[o],priceUpdatesHotPotato:{},priceInfoObjectId:a}),o+=1;return t}getFeedInfoByJson(e){let t=sf(e,!1);return Ix[t]}async getFeedInfo(e,t){let n=`getFeedInfo_${e}`,r=this.fullClient.getCache(n,t);if(r)return r;let s=this.getFeedInfoByJson(e);if(s)return s;if(!this.pythConfigs.feed_info_handle)throw new Error("feed_info_handle is not set");let i=await this.fullClient.getDynamicField({parentId:this.pythConfigs.feed_info_handle,name:{type:"0x1::type_name::TypeName",bcs:wx.serialize({name:sf(e,!0)}).toBytes()}}),o=E.struct("OracleInfo",{price_feed_id:E.vector(E.U8),price_info_object_id:E.Address,last_update_time:E.u64(),coin_decimals:E.u8()}).parse(i.dynamicField.value.bcs),a={coin_type:e,price_feed_id:fx(o.price_feed_id),coin_decimals:o.coin_decimals};return console.log("\u{1F680} ~ PythPriceModule ~ getFeedInfo ~ info:",a),this.fullClient.updateCache(n,a),a}},vo=Ta(ka(),1),v$=new vo.default(0),Sb=new vo.default(1),cf=new vo.default(2),_$=cf.pow(new vo.default(128)),w$=cf.pow(new vo.default(64)).sub(Sb),T$=cf.pow(new vo.default(128)).sub(Sb);ku.config({precision:64,rounding:ku.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var k$=Ta(ka(),1),S$=Ta(ka(),1);var E$=Ta(ka(),1);import{DeepBookClient as qx}from"@mysten/deepbook-v3";import{Base64 as Gx}from"js-base64";var xx={REQUEST_PARAMS:"requestParams",METHOD_NAME:"methodName"},uf=class extends Error{constructor(n,r,s){super(n);this.code=r;this.details=s;this.name=this.constructor.name}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details}}toString(){return JSON.stringify(this.toJSON())}static isErrorCode(n,r){return n instanceof uf&&n.code===r}},Ea=uf;Ni(Ea,"DETAILS_KEYS",xx);var lf=class extends Ea{constructor(t,n,r){super(t,n||"UnknownError",r)}static isCommonErrorCode(t,n){return this.isErrorCode(t,n)}};var df=(e,t,n)=>{throw new lf(t,e,n)};var Cx=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function Eb(e){return e.startsWith("0x")?e:`0x${e}`}function pf(e){return e.startsWith("0x")?`${e.slice(2)}`:e}function Nx(e,t=4,n=4){let r=Math.max(t,1),s=Math.max(n,1);return`${e.slice(0,r+2)} ... ${e.slice(-s)}`}function D$(e,t=4,n=4){return Nx(Eb(e),t,n)}function U$(e,t={leadingZero:!0}){if(typeof e!="string")return!1;let n=e;if(t.leadingZero){if(!e.startsWith("0x"))return!1;n=n.substring(2)}return Cx.test(n)}function Rx(e){if(!Buffer.isBuffer(e))if(Array.isArray(e))e=Buffer.from(e);else if(typeof e=="string")exports.isHexString(e)?e=Buffer.from(exports.padToEven(exports.stripHexPrefix(e)),"hex"):e=Buffer.from(e);else if(typeof e=="number")e=exports.intToBuffer(e);else if(e==null)e=Buffer.allocUnsafe(0);else if(e.toArray)e=Buffer.from(e.toArray());else throw new Error("invalid type");return e}function P$(e){return Eb(Rx(e).toString("hex"))}function L$(e){let t=new ArrayBuffer(4),n=new DataView(t);for(let s=0;s<e.length;s++)n.setUint8(s,e.charCodeAt(s));return n.getUint32(0,!0)}function Mx(e){let t,n,r,s,i;t="";let o=e.length;for(n=0;n<o;)switch(r=e.charCodeAt(n++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=e.charAt(n-1);break;case 12:case 13:s=e.charCodeAt(n++),t+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=e.charCodeAt(n++),i=e.charCodeAt(n++),t+=String.fromCharCode((r&15)<<12|(s&63)<<6|(i&63)<<0);break}return t}function V$(e){let t="",n=pf(e),r=n.length/2;for(let s=0;s<r;s++)t+=String.fromCharCode(Number.parseInt(n.substr(s*2,2),16));return Mx(t)}var Bx=0,Ab=1,jx=2;function Ob(e,t){return e===t?Bx:e<t?Ab:jx}function Dx(e,t){let n=0,r=e.length<=t.length?e.length:t.length,s=Ob(e.length,t.length);for(;n<r;){let i=Ob(e.charCodeAt(n),t.charCodeAt(n));if(n+=1,i!==0)return i}return s}function z$(e,t){return Dx(e,t)===Ab}function Ib(e,...t){let n=Array.isArray(t[t.length-1])?t.pop():[],s=[e,...t].filter(Boolean).join("::");return n&&n.length&&(s+=`<${n.join(", ")}>`),s}function W$(e){return e.split("::")[0]}function Ls(e){try{let t=e.replace(/\s/g,""),r=t.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){t=t.slice(0,t.indexOf("<"));let c={...Ls(t),type_arguments:r.map(u=>Ls(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>Gt.isSuiCoin(u)?u:Ls(u).source_address),c.source_address=Ib(c.full_address,c.type_arguments),c}let s=t.split("::"),o={full_address:t,address:t===hf||t===xb?"0x2":Ft(s[0]),module:s[1],name:s[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=Ib(o.full_address,o.type_arguments),o}catch{return{full_address:e,address:"",module:"",name:"",type_arguments:[],source_address:e}}}function ff(e){return Ls(e).source_address}function Ux(e){return e.toLowerCase().startsWith("0x")?Ft(e):e}var H$=(e,t=!0)=>{let n=e.split("::"),r=n.shift(),s=Ft(r);return t&&(s=pf(s)),`${s}::${n.join("::")}`};function mf(e){for(let t in e){let n=typeof e[t];if(n==="object")mf(e[t]);else if(n==="string"){let r=e[t];e[t]=Ux(r)}}}var J$=be(zn);import Iu from"decimal.js";function R(e){return Iu.isDecimal(e)?e:new Iu(e===void 0?0:e)}function gf(e){return R(10).pow(R(e).abs())}var xi=(e,t)=>{try{return R(e).toDP(t,Iu.ROUND_DOWN).toString()}catch{return e}},yf=(e,t)=>Iu.max(R(e),R(t));var rq=1e3,sq=500,iq=100,oq=100,aq=1e3,hf="0x2::sui::SUI",xb="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",cq="SUI",uq=450,lq="0x0000000000000000000000000000000000000005",it=class{static totalBalance(t,n){let r=BigInt(0);return t.forEach(s=>{n===s.coin_type&&(r+=BigInt(s.balance))}),r}static getCoinAssets(t,n){let r=[];return n.forEach(s=>{ff(s.coin_type)===ff(t)&&r.push(s)}),r}static isSuiCoin(t){return Ls(t).full_address===hf}static selectCoinObjectIdGreaterThanOrEqual(t,n,r=[]){let s=it.selectCoinAssetGreaterThanOrEqual(t,n,r),i=s.selected_coins.map(c=>c.coin_object_id),o=s.remain_coins,a=s.selected_coins.map(c=>c.balance.toString());return{object_array:i,remain_coins:o,amount_array:a}}static selectCoinAssetGreaterThanOrEqual(t,n,r=[]){let s=it.sortByBalance(t.filter(u=>!r.includes(u.coin_object_id))),i=it.calculateTotalBalance(s);if(i<n)return{selected_coins:[],remain_coins:s};if(i===n)return{selected_coins:s,remain_coins:[]};let o=BigInt(0),a=[],c=[...s];for(;o<i;){let u=n-o,d=c.findIndex(f=>f.balance>=u);if(d!==-1){a.push(c[d]),c.splice(d,1);break}let p=c.pop();p.balance>0&&(a.push(p),o+=p.balance)}return{selected_coins:it.sortByBalance(a),remain_coins:it.sortByBalance(c)}}static sortByBalance(t){return t.sort((n,r)=>n.balance<r.balance?-1:n.balance>r.balance?1:0)}static sortByBalanceDes(t){return t.sort((n,r)=>n.balance>r.balance?-1:n.balance<r.balance?0:1)}static calculateTotalBalance(t){return t.reduce((n,r)=>n+r.balance,BigInt(0))}static buildCoinForAmount(t,n,r,s,i=!0,o=!0){let a=it.getCoinAssets(s,n);if(r===BigInt(0))return this.buildZeroValueCoin(n,t,s,i);let c=it.calculateTotalBalance(a);if(c<r)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r} `);return this.buildCoin(t,n,a,r,s,i,o)}static buildCoinWithBalance(t,n,r){return t===BigInt(0)&&it.isSuiCoin(n)?r.add(Kn({balance:t,useGasCoin:!1})):r.add(Kn({balance:t,type:n}))}static buildVectorCoin(t,n,r,s,i,o=!0){if(it.isSuiCoin(i)){let f=t.splitCoins(t.gas,[t.pure.u64(s)]);return{selected_coins:[],target_coin:f,remain_coins:n,target_coin_amount:s.toString(),is_mint_zero_coin:!1,original_spited_coin:t.gas}}let{original_spited_coin:a,target_coin:c,target_coin_amount:u,remain_coins:d,selected_coins:p}=this.buildSpitTargeCoin(t,s,r,o);return o?{target_coin:t.makeMoveVec({elements:[c]}),selected_coins:p,remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1,original_spited_coin:a}:{selected_coins:p,target_coin:t.makeMoveVec({elements:p.map(f=>t.object(f))}),remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1}}static buildOneCoin(t,n,r,s,i=!0){if(it.isSuiCoin(s)){if(r===0n&&n.length>1){let c=it.selectCoinObjectIdGreaterThanOrEqual(n,r);return{selected_coins:c.object_array,target_coin:t.object(c.object_array[0]),remain_coins:c.remain_coins,target_coin_amount:c.amount_array[0],is_mint_zero_coin:!1}}let o=it.selectCoinObjectIdGreaterThanOrEqual(n,r),a=t.splitCoins(t.gas,[t.pure.u64(r)]);return{selected_coins:[],target_coin:a,remain_coins:o.remain_coins,target_coin_amount:r.toString(),is_mint_zero_coin:!1,original_spited_coin:t.gas}}return this.buildSpitTargeCoin(t,r,n,i)}static buildSpitTargeCoin(t,n,r,s){let i=it.selectCoinObjectIdGreaterThanOrEqual(r,n),o=i.amount_array.reduce((b,_)=>Number(b)+Number(_),0).toString(),a=i.object_array,[c,...u]=a,d=t.object(c),p=d,f=i.amount_array.reduce((b,_)=>Number(b)+Number(_),0).toString(),g;return u.length>0&&t.mergeCoins(d,u.map(b=>t.object(b))),s&&Number(o)>Number(n)&&(p=t.splitCoins(d,[t.pure.u64(n)]),g=d),{original_spited_coin:g,target_coin:p,target_coin_amount:f,remain_coins:i.remain_coins,selected_coins:i.object_array,is_mint_zero_coin:!1}}static buildCoin(t,n,r,s,i,o=!0,a=!0){return o?this.buildVectorCoin(t,n,r,s,i,a):this.buildOneCoin(t,r,s,i,a)}static buildZeroValueCoin(t,n,r,s=!0){let i=this.callMintZeroValueCoin(n,r),o;return s?o=n.makeMoveVec({elements:[i]}):o=i,{target_coin:o,remain_coins:t,selected_coins:[],is_mint_zero_coin:!0,target_coin_amount:"0"}}static buildCoinForAmountInterval(t,n,r,s,i=!0,o=!0){let a=it.getCoinAssets(s,n);if(r.amount_first===BigInt(0))return a.length>0?this.buildCoin(t,[...n],[...a],r.amount_first,s,i,o):this.buildZeroValueCoin(n,t,s,i);let c=it.calculateTotalBalance(a);if(c>=r.amount_first)return this.buildCoin(t,[...n],[...a],r.amount_first,s,i,o);if(c<r.amount_second)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r.amount_second} `);return this.buildCoin(t,[...n],[...a],r.amount_second,s,i,o)}static fromBalance(t,n,r){return r.moveCall({target:"0x2::coin::from_balance",typeArguments:[n],arguments:[t]})}static intoBalance(t,n,r){return r.moveCall({target:"0x2::coin::into_balance",typeArguments:[n],arguments:[typeof t=="string"?r.object(t):t]})}static mintBalanceZero(t,n){return n.moveCall({target:"0x2::balance::zero",typeArguments:[t],arguments:[]})}static destroyBalanceZero(t,n,r){return r.moveCall({target:"0x2::balance::destroy_zero",typeArguments:[n],arguments:[t]})}static getCoinAmountObjId(t,n){let r=t.amount_coin_array.find(s=>!s.used&&R(s.amount).eq(n)?(s.used=!0,!0):!1);return r?r.coin_object_id:df("CoinNotFound",`Coin not found for ${n} ${t.coin_type}`)}static buildMultiCoinInput(t,n,r,s){let i=it.getCoinAssets(r,n);if(it.isSuiCoin(r)){let f=t.splitCoins(t.gas,s.map(b=>t.pure.u64(b)));return{amount_coin_array:s.map((b,_)=>({coin_object_id:f[_],amount:b.toString(),used:!1})),coin_type:r,remain_coins:i}}let o=s.reduce((f,g)=>f+g,BigInt(0)),a=it.selectCoinObjectIdGreaterThanOrEqual(i,o);if(a.object_array.length===0)return df("InsufficientBalance",`No enough coins for ${r} expect ${o} actual ${it.calculateTotalBalance(i)}`);let[c,...u]=a.object_array;u.length>0&&t.mergeCoins(c,[...u]);let d=t.splitCoins(c,s.map(f=>t.pure.u64(f)));return{amount_coin_array:s.map((f,g)=>({coin_object_id:d[g],amount:f.toString(),used:!1})),remain_coins:a.remain_coins,coin_type:r}}},Gt=it;Ni(Gt,"callMintZeroValueCoin",(t,n)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[n]}));var Cb=6e4,Nb=3e5,_o=864e5;function bf(e){return Date.parse(new Date().toString())+e}var Au=class{overdueTime;value;constructor(t,n=0){this.overdueTime=n,this.value=t}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};function Vs(e,t){let n=gf(R(t));return Number(R(e).mul(n))}function bq(e,t=32){return BigInt.asUintN(t,BigInt(e)).toString()}function vq(e,t=32){return Number(BigInt.asIntN(t,BigInt(e)))}function Ci(e,t){let n=gf(R(t));return Number(R(e).div(n))}function _q(e,t="hex"){if(e instanceof Uint8Array){let r=Buffer.from(e);return zc.fromSecretKey(new Uint8Array(r))}let n=t==="hex"?dn(e):ie(e);return zc.fromSecretKey(n)}function wq(e,t="hex"){if(e instanceof Uint8Array){let r=Buffer.from(e);return Jc.fromSecretKey(new Uint8Array(r))}let n=t==="hex"?dn(e):ie(e);return Jc.fromSecretKey(n)}var Rb=async e=>new Promise(t=>{setTimeout(()=>{t(1)},e)});async function Tq(e,t=!0){e.getData().commands.forEach((n,r)=>{t&&console.log(`transaction ${r}: `,n)})}var Mb={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Bb={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function jb(...e){console.log("DeepbookV3_Utils_Sdk###",...e)}function Db(e){return e.data}function Px(e){if(e.error&&"object_id"in e.error&&"version"in e.error&&"digest"in e.error){let{error:t}=e;return{objectId:t.object_id,version:t.version,digest:t.digest}}}function Lx(e){if(e.error&&"object_id"in e.error&&!("version"in e.error)&&!("digest"in e.error))return e.error.object_id}function Vx(e){if("reference"in e)return e.reference;let t=Db(e);return t?{objectId:t.objectId,version:t.version,digest:t.digest}:Px(e)}function Ub(e){return"objectId"in e?e.objectId:Vx(e)?.objectId??Lx(e)}function Oq(e){return e.data!==void 0}function Fx(e){return e.content!==void 0}function $x(e){let t="data"in e?Db(e):e;if(!(!t||!Fx(t)||t.content.dataType!=="moveObject"))return t.content}function Pb(e){let t=$x(e)?.fields;if(t)return"fields"in t?t.fields:t}var Lb=E.struct("GetCetusBalanceManagerList",{owner:E.Address,cetus_balance_managers:E.vector(E.Address),deepbook_balance_managers:E.vector(E.Address)}),Vb=E.struct("Account",{epoch:E.u64(),open_orders:E.vector(E.u128()),taker_volume:E.u128(),maker_volume:E.u128(),active_stake:E.u64(),inactive_stake:E.u64(),created_proposal:E.bool(),voted_proposal:E.option(E.Address),unclaimed_rebates:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()}),settled_balances:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()}),owed_balances:E.struct("Balances",{base:E.u64(),quote:E.u64(),deep:E.u64()})});var vf=1e6,gr=1e9,zx={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Wx={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},xu=class{_sdk;_deep;_cache={};constructor(t){this._sdk=t,this._deep=t.sdkOptions.network==="mainnet"?Wx:zx}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let t=new J,n=t.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return t.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[t.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),n],typeArguments:[]}),t.moveCall({target:"0x2::transfer::public_share_object",arguments:[n],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),t}createAndDepsit({account:t,coin:n,amountToDeposit:r}){let s=new J;s.setSenderIfNotSet(t);let i=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=Kn({type:n.coinType,balance:BigInt(r)});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i,o],typeArguments:[n.coinType]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i],typeArguments:[]}),s.moveCall({target:"0x2::transfer::public_share_object",arguments:[i],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),s}depositIntoManager({account:t,balanceManager:n,coin:r,amountToDeposit:s,tx:i}){let o=i||new J;if(n){o.setSenderIfNotSet(t);let a=Kn({type:r.coinType,balance:BigInt(s)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(n),a],typeArguments:[r.coinType]}),o}return null}async withdrawFromManager({account:t,balanceManager:n,coin:r,amountToWithdraw:s,returnAssets:i,txb:o}){let a=o||new J,c=a.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[a.object(n),a.pure.u64(s)],typeArguments:[r.coinType]});if(i)return c;if(Gt.isSuiCoin(r.coinType))a.transferObjects([c],t);else{let u=await this._sdk.fullClient.getOwnerCoinAssets(t,r.coinType),d=Gt.buildCoinForAmount(a,u,BigInt(0),r.coinType,!1);d.target_coin?(a.mergeCoins(d.target_coin,[c]),d.is_mint_zero_coin&&a.transferObjects([d.target_coin],t)):a.transferObjects([c],t)}return a}withdrawManagersFreeBalance({account:t,balanceManagers:n,tx:r=new J}){for(let s in n)n[s].forEach(o=>{let a=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(s),r.pure.u64(o.amount)],typeArguments:[o.coinType]});r.transferObjects([a],t)});return r}async getBalanceManager(t,n=!0){let r=`getBalanceManager_${t}`,s=this.getCache(r,n);if(!n&&s!==void 0)return s;try{let i=new J;i.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[i.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i.pure.address(t)],typeArguments:[]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t),c=(o?.Transaction??o?.FailedTransaction)?.events?.find(I=>I.eventType===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`);if(c?.bcs==null)throw new Error("GetCetusBalanceManagerList event not found or missing BCS payload (check simulation / RPC transport)");let d=Lb.parse(new Uint8Array(c.bcs))?.deepbook_balance_managers||[],p=await this._sdk.fullClient.batchGetObjects(d,{json:!0}),f={};for(let I=0;I<p.length;I++){let A=p[I],M=A?.data?.objectId??A?.objectId,C=A?.json??A?.data?.content?.fields,B=C?.allow_listed?.fields?.contents??C?.allow_listed?.contents??C?.balance_manager?.allow_listed?.contents;M&&Array.isArray(B)&&B.length>0&&(f[M]=B)}let g=await this.batchGetObjectsByIdMap(f),b=X(t),_=[];return d.forEach(I=>{let A=g[I]??[],M=A.filter(B=>{let L=this.getSuiObjectOwnerAddress(B);return L!==void 0&&X(L)===b});A.length===0||M.length===A.length?_.push({balanceManager:I,cetusBalanceManager:"",capOk:!0}):_.push({balanceManager:I,cetusBalanceManager:"",capOk:!1})}),this.updateCache(r,_,864e5),_||[]}catch(i){throw i instanceof Error?i:new Error(String(i))}}async batchGetObjectsByIdMap(t){let n=Object.entries(t).filter(([,o])=>Array.isArray(o)&&o.length>0);if(n.length===0)return{};let r=[...new Set(n.flatMap(([,o])=>o))],s=await this._sdk.fullClient.batchGetObjects(r,{json:!0}),i=new Map;return s.forEach(o=>{let a=o?.data?.objectId??o?.objectId;a&&i.set(a,o)}),Object.fromEntries(n.map(([o,a])=>[o,a.map(c=>i.get(c)).filter(Boolean)]))}getSuiObjectOwnerAddress(t){let r=t?.owner;if(r&&typeof r=="object"){if(r.$kind==="AddressOwner"&&typeof r.AddressOwner=="string")return r.AddressOwner;if(r.$kind==="ObjectOwner"&&typeof r.ObjectOwner=="string")return r.ObjectOwner;if(typeof r.AddressOwner=="string")return r.AddressOwner;if(typeof r.ObjectOwner=="string")return r.ObjectOwner}let s=t.data?.owner;if(!(!s||typeof s!="object")){if(typeof s.AddressOwner=="string")return s.AddressOwner;if(typeof s.ObjectOwner=="string")return s.ObjectOwner}}withdrawSettledAmounts({poolInfo:t,balanceManager:n},r=new J){let s=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(n)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(t.address),r.object(n),s],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}async getManagerBalance({account:t,balanceManager:n,coins:r}){try{let s=new J;r.forEach(a=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(n)],typeArguments:[a.coinType]})});let i=await this.sdk.fullClient.sendSimulationTransaction(s,t),o={};return i?.commandResults?.forEach((a,c)=>{let u=r[c],d=a.returnValues[0]?.bcs,p=E.U64.parse(new Uint8Array(d)),f=R(p),g=f.eq(0)?"0":f.div(Math.pow(10,u.decimals)).toString();o[u.coinType]={adjusted_balance:g,balance:f.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:t,coins:n}){try{let r=new J,s=await this.getBalanceManager(t,!0);if(!Array.isArray(s)||s.length===0)return{};s.forEach(a=>{n.forEach(c=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(a.balanceManager)],typeArguments:[c.coinType]})})});let i=await this.sdk.fullClient.sendSimulationTransaction(r,t),o={};return s.forEach((a,c)=>{let u={},d=c*n.length;n.forEach((p,f)=>{let g=d+f,b=i.commandResults?.[g];if(b){let _=b.returnValues[0].bcs,I=E.U64.parse(new Uint8Array(_)),A=R(I),M=A.eq(0)?"0":A.div(Math.pow(10,p.decimals)).toString();u[p.coinType]={adjusted_balance:M,balance:A.toString()}}}),o[a.balanceManager]=u}),o}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(t){try{let n=new J;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[n.object(t.address),n.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let s=(await this._sdk.fullClient.sendSimulationTransaction(n,this._sdk.sdkOptions.simulationAccount.address)).commandResults[0]?.returnValues[0]?.bcs,i=Number(E.U64.parse(new Uint8Array(s))),o=Math.pow(10,t.baseCoin.decimals).toString(),a=Math.pow(10,t.quoteCoin.decimals).toString();return R(i).mul(o).div(a).div(gr).toString()}catch(n){return jb("getMarketPrice ~ error:",n),"0"}}async getPools(t=!1){let n="Deepbook_getPools",r=this.getCache(n,t);if(r!==void 0)return r;let s=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),i=/<([^>]+)>/,o=[];return s?.data?.forEach(a=>{let c=a?.parsedJson,u=a.type.match(i);if(u){let p=u[1].split(", ");o.push({...c,baseCoinType:p[0],quoteCoinType:p[1]})}}),this.updateCache(n,o,864e5),o}async getQuoteQuantityOut(t,n,r){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(t.address),s.pure.u64(n),s.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:R(n).div(Math.pow(10,t.baseCoin.decimals)).toString(),baseOutDisplay:R(o).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(a).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(c).div(vf).toString(),baseQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getBaseQuantityOut(t,n,r){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(t.address),s.pure.u64(n),s.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{quoteQuantityDisplay:R(n).div(Math.pow(10,t.quoteCoin.decimals)).toString(),baseOutDisplay:R(o).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(a).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(c).div(vf).toString(),quoteQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getQuantityOut(t,n,r,s){let i=new J;i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[i.object(t.address),i.pure.u64(n),i.pure.u64(r),i.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let o=await this._sdk.fullClient.sendSimulationTransaction(i,s),a=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs))),c=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs))),u=Number(E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:R(n).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteQuantityDisplay:R(r).div(Math.pow(10,t.quoteCoin.decimals)).toString(),baseOutDisplay:R(a).div(Math.pow(10,t.baseCoin.decimals)).toString(),quoteOutDisplay:R(c).div(Math.pow(10,t.quoteCoin.decimals)).toString(),deepRequiredDisplay:R(u).div(vf).toString(),baseQuantity:n,quoteQuantity:r,baseOut:a,quoteOut:c,deepRequired:u}}async getReferencePool(t){let n=await this.getPools(),r=t.baseCoin.coinType,s=t.quoteCoin.coinType,i=this._deep.coinType;for(let o=0;o<n.length;o++){let a=n[o];if(a.address===t.address)continue;let c=[a.baseCoinType,a.quoteCoinType];if(a.baseCoinType===i&&(c.includes(r)||c.includes(s)))return a}return null}async updateDeepPrice(t,n){let r=await this.getReferencePool(t);return r?(n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[n.object(t.address),n.object(r.pool_id),n.object(he)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),n):null}async estimatedMaxFee(t,n,r,s,i,o,a){let c=this.deepCoin;try{let{taker_fee:u,maker_fee:d}=t,p=R(u).div(gr).toString(),f=R(d).div(gr).toString(),g=await this.getMarketPrice(t);console.log("\u{1F680} ~ DeepbookUtilsModule ~ estimatedMaxFee ~ marketPrice:",g);let b=o?r:g!=="0"?g:a;if(b==="0")throw new Error("Cannot get market price");let _=Math.pow(10,t.baseCoin.decimals).toString(),I=Math.pow(10,t.quoteCoin.decimals).toString(),A=R(b).div(_).mul(I).mul(gr).toString();if(s){let B=await this.getMarketPrice(t),j=R(o?r:B!=="0"?B:a).div(_).mul(I).mul(gr).toString(),q=await this.getOrderDeepPrice(t);if(!q)throw new Error("Cannot get deep price");let P=yf(j,r),D=R(n).mul(R(p)).mul(R(q.deep_per_asset)).div(R(gr)),Z=R(n).mul(R(f)).mul(R(q.deep_per_asset)).div(R(gr));q.asset_is_base||(D=D.mul(P).div(R(gr)),Z=Z.mul(P).div(R(gr)));let ce=D.ceil().toString(),te=Z.ceil().toString();return{takerFee:ce,makerFee:te,takerFeeDisplay:Ci(ce,c.decimals).toString(),makerFeeDisplay:Ci(te,c.decimals).toString(),feeType:c.coinType}}if(i){let B=yf(A,o?r:g),L=R(n).mul(B).mul(R(p).mul(1.25)).div(R(gr)).ceil().toFixed(0),j=R(n).mul(B).mul(R(f).mul(1.25)).div(R(gr)).ceil().toFixed(0);return{takerFee:L,makerFee:j,takerFeeDisplay:Ci(L,t.quoteCoin.decimals).toString(),makerFeeDisplay:Ci(j,t.quoteCoin.decimals).toString(),feeType:t.quoteCoin.coinType}}let M=R(n).mul(R(p).mul(1.25)).ceil().toFixed(0),C=R(n).mul(R(f).mul(1.25)).ceil().toFixed(0);return{takerFee:M,makerFee:C,takerFeeDisplay:Ci(M,t.baseCoin.decimals).toString(),makerFeeDisplay:Ci(C,t.baseCoin.decimals).toString(),feeType:t.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(t,n=!0){let r=`getOrderDeepPrice_${t.address}}`,s=this.getCache(r);if(s!==void 0)return s;try{let i=new J,o=!1;n&&t?.baseCoin?.coinType!==this._deep.coinType&&t?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(t,i)&&(o=!0),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[i.object(t.address)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let a=await this._sdk.fullClient.sendSimulationTransaction(i,this._sdk.sdkOptions.simulationAccount.address),c=o?a.commandResults[1]?.returnValues[0]?.bcs:a.commandResults[0]?.returnValues[0]?.bcs,u=this.parseOrderDeepPrice(new Uint8Array(c));return this.updateCache(r,u,6e4),u}catch{return await Rb(2e3),this.getOrderDeepPrice(t,!1)}}parseOrderDeepPrice(t){let n=new DataView(t.buffer),r=n.getUint8(0)!==0,s=Number(n.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:s}}getCoinAssets(t,n,r){return Gt.buildCoinWithBalance(BigInt(R(n).abs().ceil().toString()),t,r)}async getTransactionRelatedBalance(t,n,r,s,i,o,a){let c=this.deepCoin;if(!a)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:t.baseCoin.coinType,decimals:t.baseCoin.decimals},{coinType:t.quoteCoin.coinType,decimals:t.quoteCoin.decimals}];s&&u.push(c);let d=await this.getManagerBalance({account:i,balanceManager:a,coins:u}),p=d?.[n]?.balance||"0",f=d?.[r]?.balance||"0",g=o&&d?.[c.coinType]?.balance||"0";return{baseManagerBlance:p,quoteManagerBlance:f,feeManaerBalance:g}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(t,n,r,s,i,o,a,c,u){let d=R(t).gt(0)&&c,p="0";if(!d)return{feeAsset:this.getEmptyCoin(u,n),haveDepositFee:"0"};if(o||a){let f=R(i).sub(o?s:r);p=f.lte(0)?t:f.sub(t).lt(0)?f.sub(t).toString():"0"}else p=R(i).sub(t).lt("0")?R(i).sub(t).abs().toString():"0";return{feeAsset:R(p).gt("0")?this.getCoinAssets(n,p,u):this.getEmptyCoin(u,n),haveDepositFee:p}}async getTransactionRelatedAssets(t,n,r,s,i,o,a,c,u){try{let d=this.deepCoin,p=be(t.baseCoin.coinType),f=be(t.quoteCoin.coinType),g=p===d.coinType,b=f===d.coinType,_=!g&&!b,{baseManagerBlance:I,quoteManagerBlance:A,feeManaerBalance:M}=await this.getTransactionRelatedBalance(t,p,f,_,o,a,c);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:I,quoteManagerBlance:A});let C,B,L=!1;if(i){a||(r=R(r).add(R(s)).toString());let q=R(A).sub(r).toString();R(q).lt(0)?(L=!0,B=this.getCoinAssets(f,q,u)):B=this.getEmptyCoin(u,f),C=this.getEmptyCoin(u,p)}else{a||(n=R(n).add(R(s)).toString());let q=R(I).sub(n).toString();R(q).lt(0)?(L=!0,C=this.getCoinAssets(p,q,u)):C=this.getEmptyCoin(u,p),B=this.getEmptyCoin(u,f)}let j=this.getFeeAsset(s,d.coinType,n,r,M,b,g,a,u);return{baseAsset:C,quoteAsset:B,feeAsset:j,haveDeposit:L}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getMarketTransactionRelatedAssets(t,n,r,s,i,o,a,c,u,d){try{let p=this.deepCoin,f=be(t.baseCoin.coinType),g=be(t.quoteCoin.coinType),b=f===p.coinType,_=g===p.coinType,I=!b&&!_,A=await this.getTransactionRelatedBalance(t,f,g,I,o,a,c),{feeManaerBalance:M}=A,C=R(A.baseManagerBlance).add(R(d?.base||"0")).toString(),B=R(A.quoteManagerBlance).add(R(d?.quote||"0")).toString(),L;a&&R(M).lt(s)?L=this.getCoinAssets(p.coinType,R(s).sub(M).toString(),u):L=this.getEmptyCoin(u,p.coinType);let j,q;if(i){a||(r=R(r).add(R(s)).toString());let P=R(B).sub(r).toString();if(R(P).lt(0)){let D;R(B).gt(0)&&(D=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.quoteCoin,amountToWithdraw:B,returnAssets:!0,txb:u}));let Z=this.getCoinAssets(g,P,u);D&&u.mergeCoins(Z,[D]),q=Z}else q=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});j=this.getEmptyCoin(u,f)}else{a||(n=R(n).add(R(s)).toString());let P=R(C).sub(n).toString();if(R(P).lt(0)){let D;R(C).gt(0)&&(D=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.baseCoin,amountToWithdraw:C,returnAssets:!0,txb:u}));let Z=this.getCoinAssets(f,P,u);D&&u.mergeCoins(Z,[D]),j=Z}else j=await this.withdrawFromManager({account:o,balanceManager:c,coin:t.baseCoin,amountToWithdraw:n,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,g)}return{baseAsset:j,quoteAsset:q,feeAsset:L}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async createDepositThenPlaceLimitOrder({poolInfo:t,priceInput:n,quantity:r,orderType:s,isBid:i,maxFee:o,account:a,payWithDeep:c,expirationTimestamp:u=Date.now()+31536e8}){try{let d=this.deepCoin,p=t.address,f=t.baseCoin.decimals,g=t.quoteCoin.decimals,b=t.baseCoin.coinType,_=t.quoteCoin.coinType,I=R(n).mul(10**(g-f+9)).toString(),A=be(b),M=be(_),C=new J,B,L;if(i){let D=R(n).mul(R(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();c||(D=R(D).add(R(o)).toString()),L=Gt.buildCoinWithBalance(BigInt(D),M,C)}else{let D=r;c||(D=R(r).abs().add(R(o)).toString()),B=Gt.buildCoinWithBalance(BigInt(D),A,C)}let j=c?R(o).gt(0)?Gt.buildCoinWithBalance(BigInt(R(o).abs().ceil().toString()),d.coinType,C):this.getEmptyCoin(C,d.coinType):this.getEmptyCoin(C,d.coinType),q=C.moveCall({typeArguments:[i?b:_],target:"0x2::coin::zero",arguments:[]}),P=[C.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),C.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),C.object(p),i?q:B,i?L:q,j,C.pure.u8(s),C.pure.u8(0),C.pure.u64(I),C.pure.u64(r),C.pure.bool(i),C.pure.bool(!1),C.pure.u64(u),C.object(he)];return C.moveCall({typeArguments:[A,M],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:P}),C}catch(d){throw d instanceof Error?d:new Error(String(d))}}getEmptyCoin(t,n){return Gt.buildCoinWithBalance(BigInt(0),n,t)}async createDepositThenPlaceMarketOrder({poolInfo:t,quantity:n,isBid:r,maxFee:s,account:i,payWithDeep:o,slippage:a=.01}){try{let c=t.address,u=t.baseCoin.coinType,d=t.quoteCoin.coinType,p=be(u),f=be(d),g=new J,b,_,I=n,A,M=await this.getOrderBook(t,"all",6);if(r){let L=M?.ask?.[0]?.price||"0",j=R(L).mul(R(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();A=R(j).plus(R(j).mul(a)).ceil().toString()}else{let L=await M?.bid?.[0]?.price||"0",j=R(L).mul(R(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();A=R(j).minus(R(j).mul(a)).floor().toString()}r?(o||(A=R(A).add(R(s)).toString()),_=this.getCoinAssets(f,A,g),b=this.getEmptyCoin(g,p)):(o||(I=R(I).add(R(s)).toString()),_=this.getEmptyCoin(g,f),b=this.getCoinAssets(p,I,g));let C=o?R(s).gt(0)?Gt.buildCoinWithBalance(BigInt(R(s).abs().ceil().toString()),this.deepCoin.coinType,g):this.getEmptyCoin(g,this.deepCoin.coinType):this.getEmptyCoin(g,this.deepCoin.coinType),B=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(c),b,_,C,g.pure.u8(0),g.pure.u64(n),g.pure.bool(r),g.pure.bool(o),g.pure.u64(A),g.object(he)];return g.moveCall({typeArguments:[p,f],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:B}),g}catch(c){throw c instanceof Error?c:new Error(String(c))}}async placeLimitOrder({balanceManager:t,poolInfo:n,priceInput:r,quantity:s,isBid:i,orderType:o,maxFee:a,account:c,payWithDeep:u,expirationTimestamp:d=Date.now()+31536e8}){try{let p=this.deepCoin,f=R(r).mul(10**(n.quoteCoin.decimals-n.baseCoin.decimals+9)).toString(),g=n.baseCoin.coinType,b=n.quoteCoin.coinType,_=new J,I=i?R(r).mul(R(s).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString():"0",A=i?"0":s,{baseAsset:M,quoteAsset:C,feeAsset:B,haveDeposit:L}=await this.getTransactionRelatedAssets(n,A,I,a,i,c,u,t,_);if(L){let P=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(n.address),_.object(t),M,C,B.feeAsset,_.pure.u8(o),_.pure.u8(0),_.pure.u64(f),_.pure.u64(s),_.pure.bool(i),_.pure.bool(u),_.pure.u64(d),_.object(he)];return _.moveCall({typeArguments:[g,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:P}),_}let j=new J;R(B.haveDepositFee).gt(0)&&this.depositIntoManager({account:c,balanceManager:t,coin:p,amountToDeposit:B.haveDepositFee,tx:j});let q=[j.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),j.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),j.object(n.address),j.object(t),j.pure.u8(o),j.pure.u8(0),j.pure.u64(f),j.pure.u64(s),j.pure.bool(i),j.pure.bool(u),j.pure.u64(d),j.object(he)];return j.moveCall({typeArguments:[g,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:q}),j}catch(p){throw p instanceof Error?p:new Error(String(p))}}modifyOrder({balanceManager:t,poolInfo:n,orderId:r,newOrderQuantity:s}){let i=new J;return i.moveCall({typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[i.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),i.object(t),i.object(n.address),i.pure.u128(r),i.pure.u64(s),i.object(he)]}),i}async getBestAskprice(t){try{let{baseCoin:n,quoteCoin:r}=t,s=new J,i=await this.getMarketPrice(t),o=R(i).gt(0)?i:Math.pow(10,-1),a=Math.pow(10,6),c=R(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=R(a).mul(Math.pow(10,9+r.decimals-n.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(t.address),s.pure.u64(c),s.pure.u64(u),s.pure.bool(!1),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(s,d),f=[],g=p.commandResults[0].returnValues[0].bcs,b=E.vector(E.u64()).parse(new Uint8Array(g)),_=p.commandResults[0].returnValues[1].bcs,I=E.vector(E.u64()).parse(new Uint8Array(_));return b.forEach((A,M)=>{let C=R(A).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),B=R(I[M]).div(Math.pow(10,n.decimals)).toString();f.push({price:C,quantity:B})}),f?.[0]?.price||0}catch{return 0}}async getBestBidprice(t){try{let{baseCoin:n,quoteCoin:r}=t,s=new J,i=await this.getMarketPrice(t),o=R(i).gt(0)?R(i).div(3).toNumber():Math.pow(10,-6),a=R(i).gt(0)?i:Math.pow(10,6),c=R(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=R(a).mul(Math.pow(10,9+r.decimals-n.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(t.address),s.pure.u64(xi(c,0)),s.pure.u64(xi(u,0)),s.pure.bool(!0),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(s,d),f=[],g=p.commandResults[0].returnValues[0].bcs,b=E.vector(E.u64()).parse(new Uint8Array(g)),_=p.commandResults[0].returnValues[1].bcs,I=E.vector(E.u64()).parse(new Uint8Array(_));return b.forEach((A,M)=>{let C=R(A).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),B=R(I[M]).div(Math.pow(10,n.decimals)).toString();f.push({price:C,quantity:B})}),f?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(t,n){try{let{baseCoin:r,quoteCoin:s}=t,i=new J,o=await this.getMarketPrice(t),a,c;n?(a=R(o).gt(0)?R(o).div(3).toNumber():Math.pow(10,-6),c=R(o).gt(0)?o:Math.pow(10,6)):(a=R(o).gt(0)?o:Math.pow(10,-1),c=R(o).gt(0)?R(o).mul(3).toNumber():Math.pow(10,6));let u=R(a).mul(Math.pow(10,9+s.decimals-r.decimals)).toString(),d=R(c).mul(Math.pow(10,9+s.decimals-r.decimals)).toString();i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[i.object(t.address),i.pure.u64(xi(u,0)),i.pure.u64(xi(d,0)),i.pure.bool(n),i.object(he)],typeArguments:[r.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(i,p),g=[],b=f.commandResults[0].returnValues[0].bcs,_=E.vector(E.u64()).parse(new Uint8Array(b)),I=f.commandResults[0].returnValues[1].bcs,A=E.vector(E.u64()).parse(new Uint8Array(I));return _.forEach((M,C)=>{let B=R(M).div(Math.pow(10,9+s.decimals-r.decimals)).toString(),L=R(A[C]).div(Math.pow(10,r.decimals)).toString();g.push({price:B,quantity:L})}),g?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:t,poolInfo:n,baseQuantity:r,quoteQuantity:s,isBid:i,maxFee:o,account:a,payWithDeep:c,slippage:u=.01,settled_balances:d={base:"0",quote:"0"}}){try{let p=be(n.baseCoin.coinType),f=be(n.quoteCoin.coinType),g=new J;d&&(R(d.base).gt(0)||R(d.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:n,balanceManager:t},g);let{baseAsset:b,quoteAsset:_,feeAsset:I}=await this.getMarketTransactionRelatedAssets(n,r,s,o,i,a,c,t,g,d),A=await this.getOrderBook(n,"all",6);if(i){let B=A?.ask?.[0]?.price||"0",L=R(B).mul(R(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=R(L).plus(R(L).mul(u)).ceil().toString()}else{let B=await A?.bid?.[0]?.price||"0",L=R(B).mul(R(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=R(L).minus(R(L).mul(u)).floor().toString()}let M=s,C=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(n.address),g.object(t),b,_,I,g.pure.u8(0),g.pure.u64(r),g.pure.bool(i),g.pure.bool(c),g.pure.u64(M),g.object(he)];return g.setSenderIfNotSet(a),g.moveCall({typeArguments:[p,f],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),g}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getOrderInfoList(t,n){try{let r=new J;t.forEach(u=>{let d=u?.pool,p=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(d.pool_id),r.pure.u128(BigInt(p))],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let s=await this._sdk.fullClient.sendSimulationTransaction(r,n),i=E.struct("ID",{bytes:E.Address}),o=E.struct("OrderDeepPrice",{asset_is_base:E.bool(),deep_per_asset:E.u64()}),a=E.struct("Order",{balance_manager_id:i,order_id:E.u128(),client_order_id:E.u64(),quantity:E.u64(),filled_quantity:E.u64(),fee_is_deep:E.bool(),order_deep_price:o,epoch:E.u64(),status:E.u8(),expire_timestamp:E.u64()}),c=[];return s?.commandResults?.forEach(u=>{let d=u.returnValues[0].bcs,p=a.parse(new Uint8Array(d));c.push(p)}),c}catch{return[]}}decodeOrderId(t){let n=t>>BigInt(127)===BigInt(0),r=t>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=t&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:n,price:r,orderId:s}}async getOpenOrder(t,n,r,s,i=!1,o=new J){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(t.address),i?r:o.object(r)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let p=await this._sdk.fullClient.sendSimulationTransaction(o,n);console.log("\u{1F680} ~ DeepbookUtilsModule ~ getOpenOrder ~ res:",p?.FailedTransaction?.status);let f=p.commandResults[i?1:0].returnValues[0].bcs;a=E.struct("VecSet",{constants:E.vector(E.U128)}).parse(new Uint8Array(f)).constants}if(a.length===0)return[];let c=a.map(p=>({pool:{pool_id:t.address,baseCoinType:t.baseCoin.coinType,quoteCoinType:t.quoteCoin.coinType},orderId:p})),u=await this.getOrderInfoList(c,n)||[],d=[];return u.forEach(p=>{let f=this.decodeOrderId(BigInt(p.order_id));d.push({...p,price:f.price,isBid:f.isBid,pool:t})}),d}async getAllMarketsOpenOrders(t,n){try{let r=await this.getPools(),s=new J;r.forEach(p=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(p.pool_id),s.object(n)],typeArguments:[p.baseCoinType,p.quoteCoinType]})});let o=(await this._sdk.fullClient.sendSimulationTransaction(s,t)).commandResults?.map(p=>p.returnValues?.[0]?.bcs)||[],a=E.struct("VecSet",{constants:E.vector(E.U128)}),c=[];o.forEach((p,f)=>{let g=a.parse(new Uint8Array(p)).constants;g.length>0&&g.forEach(b=>{c.push({pool:r[f],orderId:b})})});let u=await this.getOrderInfoList(c,t)||[],d=[];return c.forEach((p,f)=>{let g=this.decodeOrderId(BigInt(p.orderId)),b=u.find(_=>_.order_id===p.orderId)||{};d.push({...p,...b,price:g.price,isBid:g.isBid})}),d}catch(r){return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getAllMarketsOpenOrders ~ error:",r),[]}}cancelOrders(t,n,r=new J){return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(n),r.object(s.poolInfo.address),r.pure.u128(s.orderId),r.object(he)],typeArguments:[s.poolInfo.baseCoin.coinType,s.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(t,n,r,s,i,o){let a=this._sdk.fullClient,u=await new qx({client:a,address:i,network:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(t,n,r,s)}processOrderBookData(t,n,r,s){let i=t.returnValues[0].bcs,o=E.vector(E.u64()).parse(new Uint8Array(i)),a=t.returnValues[1].bcs,c=E.vector(E.u64()).parse(new Uint8Array(a)),u={};return o.forEach((p,f)=>{let g=R(p).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),b=R(c[f]).div(Math.pow(10,n.decimals)).toString();u[g]?u[g]={price:g,quantity:R(u[g].quantity).add(b).toString()}:u[g]={price:g,quantity:b}}),Object.values(u)}getLevel2RangeTx(t,n,r,s,i=new J){let{baseCoin:o,quoteCoin:a}=t,c=xi(R(r).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0),u=xi(R(s).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0);return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[i.object(t.address),i.pure.u64(c),i.pure.u64(u),i.pure.bool(n),i.object(he)],typeArguments:[o.coinType,a.coinType]}),i}async fetchOrderBook(t,n,r,s,i,o){let a=new J,{baseCoin:c,quoteCoin:u}=t;try{if(n==="bid"||n==="all"){let b=s,_=r==="0"?i:r;a=this.getLevel2RangeTx(t,!0,b,_,a)}if(n==="ask"||n==="all"){let b=r==="0"?s:r,_=i;a=this.getLevel2RangeTx(t,!1,b,_,a)}let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(a,d),f=[];(n==="bid"||n==="all")&&(f=p.commandResults?.[0]?this.processOrderBookData(p.commandResults[0],c,u,o):[]);let g=[];if(n==="ask"||n==="all"){let b=n==="ask"?0:1;g=p.commandResults?.[b]?this.processOrderBookData(p.commandResults[b],c,u,o):[]}return{bid:f.sort((b,_)=>_.price-b.price),ask:g.sort((b,_)=>b.price-_.price)}}catch{let p=this._sdk.sdkOptions.simulationAccount.address,f=[],g=[];try{let b=this.getLevel2RangeTx(t,!0,s,r),_=await this._sdk.fullClient.sendSimulationTransaction(b,p);f=_.commandResults?.[0]?this.processOrderBookData(_.commandResults[0],c,u,o):[]}catch{f=[]}try{let b=this.getLevel2RangeTx(t,!1,s,r),_=await this._sdk.fullClient.sendSimulationTransaction(b,p);g=_.commandResults?.[0]?this.processOrderBookData(_.commandResults[0],c,u,o):[]}catch{g=[]}return{bid:f,ask:g}}}async getOrderBook(t,n,r){let s={bid:[],ask:[]};try{let i=await this.getMarketPrice(t),o=n,a=Math.pow(10,-r),c=Math.pow(10,r),u=await this.fetchOrderBook(t,o,i,a,c,r);return{bid:u?.bid,ask:u?.ask}}catch{return s}}async getOrderBookOrigin(t,n){try{let r=new J,s=await this.getMarketPrice(t),{baseCoin:i,quoteCoin:o}=t;if(n==="bid"||n==="all"){let p=Math.pow(10,-6),f=s,g=R(p).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=R(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(t.address),r.pure.u64(g),r.pure.u64(b),r.pure.bool(!0),r.object(he)],typeArguments:[i.coinType,o.coinType]})}if(n==="ask"||n==="all"){let p=s,f=Math.pow(10,6),g=R(p).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=R(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(t.address),r.pure.u64(g),r.pure.u64(b),r.pure.bool(!1),r.object(he)],typeArguments:[i.coinType,o.coinType]})}let a=this._sdk.sdkOptions.simulationAccount.address,c=await this._sdk.fullClient.sendSimulationTransaction(r,a),u=[];if(n==="bid"||n==="all"){let p=c.commandResults[0]?.returnValues[0]?.bcs,f=E.vector(E.u64()).parse(new Uint8Array(p)),g=c.commandResults[0]?.returnValues[1]?.bcs,b=E.vector(E.u64()).parse(new Uint8Array(g));f.forEach((_,I)=>{let A=R(_).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),M=R(b[I]).div(Math.pow(10,i.decimals)).toString();u.push({price:A,quantity:M})})}let d=[];if(n==="ask"||n==="all"){let p=n==="ask"?0:1,f=c.results[p]?.returnValues[0]?.[0],g=E.vector(E.u64()).parse(new Uint8Array(f)),b=c.results[p]?.returnValues[1]?.[0],_=E.vector(E.u64()).parse(new Uint8Array(b));g.forEach((I,A)=>{let M=R(I).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),C=R(_[A]).div(Math.pow(10,i.decimals)).toString();d.push({price:M,quantity:C})})}return{bid:u,ask:d}}catch{return{bids:[],asks:[]}}}async getWalletBalance(t){let n=await this._sdk.fullClient?.getOwnerCoinBalances(t);return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getWalletBalance ~ result:",n),Object.fromEntries(n.map((s,i)=>[be(s.coinType),{coinType:s.coinType,totalBalance:s.balance,coinBalance:s.coinBalance,addressBalance:s.addressBalance}]))}async getAccount(t,n,r=new J){for(let o=0;o<n.length;o++){let a=n[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof t=="string"?r.object(t):t],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let s=await this._sdk.fullClient.sendSimulationTransaction(r,this._sdk.senderAddress);if(s?.Transaction?.events?.length===0)return null;let i=[];return s?.Transaction?.events?.forEach((o,a)=>{let c=o?.bcs,u=Vb.parse(c),d=u.open_orders,p=u.owed_balances,f=u.settled_balances,g=u.unclaimed_rebates,b=u.taker_volume;i.push({balance_manager_id:t,open_orders:d,owed_balances:p,settled_balances:f,unclaimed_rebates:g,taker_volume:b,poolInfo:n[a]})}),i}async getSuiTransactionResponse(t,n=!1){let r=`${t}_getSuiTransactionResponse`,s=this.getCache(r,n);if(s!==void 0)return s;let i;try{i=await this._sdk.fullClient.getTransaction({digest:t,include:{events:!0,effects:!0,balanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransaction({digest:t,include:{events:!0,effects:!0}})}return this.updateCache(r,i,864e5),i}transformExtensions(t,n,r=!0){let s=[];for(let i of n){let{key:o}=i.fields,{value:a}=i.fields;if(o==="labels")try{a=JSON.parse(decodeURIComponent(Gx.decode(a)))}catch{}r&&(t[o]=a),s.push({key:o,value:a})}delete t.extension_fields,r||(t.extensions=s)}async getCoinConfigs(t=!1,n=!0){let r=this.sdk.sdkOptions.coinlist.handle,s=`${r}_getCoinConfigs`,i=this.getCache(s,t);if(i)return i;let a=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),c=await this._sdk.fullClient.batchGetObjects(a,{json:!0}),u=[];return c.forEach(d=>{let p=this.buildCoinConfig(d,n);this.updateCache(`${r}_${p.address}_getCoinConfig`,p,864e5),u.push({...p})}),this.updateCache(s,u,864e5),u}buildCoinConfig(t,n=!0){let r=Pb(t);r=r.value.fields;let s={...r};return s.id=Ub(t),s.address=Ls(r.coin_type.fields.name).full_address,r.pyth_id&&(s.pyth_id=Ft(r.pyth_id)),this.transformExtensions(s,r.extension_fields.fields.contents,n),delete s.coin_type,s}updateCache(t,n,r=3e5){let s=this._cache[t];s?(s.overdueTime=bf(r),s.value=n):s=new Au(n,bf(r)),this._cache[t]=s}getCache(t,n=!1){let r=this._cache[t],s=r?.isValid();if(!n&&s)return r.value;s||delete this._cache[t]}async createPermissionlessPool({tickSize:t,lotSize:n,minSize:r,baseCoinType:s,quoteCoinType:i}){let o=new J,a=Gt.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",o);o.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[s,i],arguments:[o.object(this.sdk.sdkOptions.deepbook.registry_id),o.pure.u64(t),o.pure.u64(n),o.pure.u64(r),a]});try{let c=await this._sdk.fullClient.sendSimulationTransaction(o,this.sdk.senderAddress);if(c?.Transaction?.effects?.status?.success)return o;if(c?.Transaction?.effects?.status?.error&&c.Transaction.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(c){throw c instanceof Error?c:new Error(String(c))}return o}newWithCustomOwnerCaps({owner:t,appType:n}){let r=new J,s=n||`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::MarginApp`,[i,o,a,c]=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new_with_custom_owner_caps`,arguments:[r.object(this._sdk.sdkOptions.deepbook.registry_id),r.pure.address(t)],typeArguments:[s]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),i],typeArguments:[]}),r.moveCall({target:"0x2::transfer::public_share_object",arguments:[i],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),r.transferObjects([o,a,c],t),r}};var Cu="0x0000000000000000000000000000000000000000000000000000000000000006",Wq="pool_script",Hq="pool_script_v2",Jq="router",Zq="router_with_partner",Kq="fetcher_script",Xq="expect_swap",Yq="utils",Qq="0x1::coin::CoinInfo",eG="0x1::coin::CoinStore",tG="custodian_v2",nG="clob_v2",rG="endpoints_v2",sG=e=>{if(typeof e=="string"&&e.startsWith("0x"))return"object";if(typeof e=="number"||typeof e=="bigint")return"u64";if(typeof e=="boolean")return"bool";throw new Error(`Unknown type for value: ${e}`)},iG=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];import Fb from"decimal.js";Fb.config({precision:64,rounding:Fb.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var lG=({totalAssetsValue:e,totalDebtValue:t})=>R(t).eq(0)||R(e).eq(0)?"0":R(e).div(R(t)).toString(),$b=e=>{let{base_margin_pool_id:t,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i}=e.value.fields,{liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}=e.value.fields.risk_ratios.fields;return{id:e.id.id,name:e.name,base_margin_pool_id:t,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i,liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}},qb=(e,t)=>{let{deposit_coin_type:n}=t,r=e.id,{max_utilization_rate:s,min_borrow:i,protocol_spread:o,supply_cap:a}=e.config.margin_pool_config,{maintainer_fees:c,protocol_fees:u}=e.protocol_fees,{total_supply:d,total_borrow:p}=e.state,f=R(a).sub(d).toString();return{deposit_coin_type:n,id:r,supply_cap:a,total_supply:d,total_borrow:p,available_supply:f,max_utilization_rate:s,min_borrow:i,protocol_spread:o,maintainer_fees:c,protocol_fees:u}};var jr=1000000000n,Hx=365n*24n*60n*60n*1000n;function Jx(e,t){return t===0n?0n:e*jr/t}function Zx(e,t){let{base_rate:n,base_slope:r,optimal_utilization:s,excess_slope:i}=t;if(e<s)return n+e*r/jr;{let o=e-s,a=s*r/jr,c=o*i/jr;return n+a+c}}function Gb(e,t){let n=e*t,r=n/jr;return n%jr>0n?r+1n:r}function Kx(e,t,n,r){let s=t.borrow_shares===0n?jr:t.total_borrow*jr/t.borrow_shares,i=Gb(e,s),o=Jx(t.total_borrow,t.total_supply),a=Zx(o,n),c=r-t.last_update_timestamp,u=t.total_borrow*a/jr*c/Hx,d=t.borrow_shares===0n?0n:Gb(u,e*jr/t.borrow_shares),p=i+d;return{confirmedDebt:i,estimatedInterest:d,totalDebt:p,annualInterestRate:a}}function pG(e,t,n,r,s=60000n){let i=r+s,{totalDebt:o}=Kx(e,t,n,i);return o}var _f=10n;function Xx(e,t){if(!_f)throw new Error("oraclePriceMultiplierDecimal is required");if(e===0n)throw new Error("Invalid oracle price");if(t<0n){let n=10n**(_f- -t);return e*n}return e/10n**(t+_f)}var wo=class{_sdk;hasChangeConnection=!1;_commonPythPrice;_cache={};constructor(t){this._sdk=t,this._commonPythPrice=new kb(t.fullClient)}get sdk(){return this._sdk}async updatePythPriceIDs(t,n){let r=null,s=null;try{r=await this._commonPythPrice.getPriceFeedsUpdateData(t)}catch(a){s=a,console.log("Error: ",a)}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${s?.message}`);let i=[];try{i=await this._commonPythPrice.updatePriceFeeds(n,r,t)}catch(a){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${a}`)}let o=new Map;for(let a=0;a<t.length;a++)o.set(t[a],i[a]);return o}priceCheck(t,n=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-t.last_update_time)>n))return t}async getLatestPrice(t,n=!1){let r={},s=[];if(n?t.forEach(a=>{let c=this._sdk.fullClient.getCache(`getLatestPrice_${a.coinType}`);c&&this.priceCheck(c,60)?r[a.coinType]=c:s.push(a.coinType)}):s=t.map(a=>a.coinType),s.length===0)return r;let i=t.map(a=>a.feed);return(await this._commonPythPrice.getLatestPriceFeeds(i))?.parsed?.forEach((a,c)=>{let u=a.price;if(u){let{price:d,expo:p}=u,f=R(d).mul(R(10).pow(R(p))).toString(),b={coin_type:t[c].coinType,price:f,oracle_price:0n,last_update_time:u.publish_time};b.oracle_price=Xx(BigInt(d),BigInt(p)),r[s[c]]=b,this._sdk.fullClient.updateCache(`getLatestPrice_${b.coin_type}`,b)}}),r}};var Nu=class{_sdk;pythPrice;_deep;_cache={};constructor(t){if(!t)throw new Error("SDK instance is required");this._sdk=t,this.pythPrice=new wo(t),this._deep=t.sdkOptions.network==="mainnet"?Bb:Mb}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(t,n=new J){if(!t)throw new Error("Pool info is required");if(!t.id)throw new Error("Pool ID is required");if(!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:s}=t;try{let{margin_manager:i,initializer:o}=this.createMarginManager(t,n);return this.shareMarginManager({marginManager:i,initializer:o,baseCoin:r,quoteCoin:s},n),{tx:n,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create and share margin manager: ${i instanceof Error?i.message:String(i)}`)}}createMarginManager(t,n=new J){if(!t)throw new Error("Pool info is required");if(!t.id)throw new Error("Pool ID is required");let{id:r,baseCoin:s,quoteCoin:i}=t;try{let[o,a]=n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(r),n.object(this._sdk.sdkOptions.margin_utils.registry_id),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(he)],typeArguments:[s.coinType,i.coinType]});return{tx:n,margin_manager:o,initializer:a}}catch(o){throw new Error(`Failed to create margin manager: ${o instanceof Error?o.message:String(o)}`)}}shareMarginManager({marginManager:t,initializer:n,baseCoin:r,quoteCoin:s},i=new J){try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[t,n],typeArguments:[r.coinType,s.coinType]}),i}catch(o){throw new Error(`Failed to share margin manager: ${o instanceof Error?o.message:String(o)}`)}}async getBalanceManagerByMarginManager(t){if(!t||typeof t!="string")throw new Error("Valid account address is required");let n=`
|
|
1025
1025
|
query Events($filter: EventFilter) {
|
|
1026
1026
|
events(filter: $filter) {
|
|
1027
1027
|
nodes {
|
|
@@ -1035,7 +1035,7 @@ Clients should implement reconnection logic to maintain continuous price updates
|
|
|
1035
1035
|
}
|
|
1036
1036
|
}
|
|
1037
1037
|
}
|
|
1038
|
-
`,r={filter:{sender:t,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let s=await this.sdk.fullClient._graphQLClient.query({query:n,variables:r});return s?.data?.events?.nodes?s.data.events.nodes.map(o=>o?.contents?.json):[]}catch(s){throw new Error(`Failed to query balance managers: ${s instanceof Error?s.message:String(s)}`)}}async getMarginManagerByAccount(t){if(!t||typeof t!="string")throw new Error("Valid account address is required");try{let s=((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data??[]).filter(p=>p.parsedJson?.owner===t);if(!s.length)return[];let i=s.map(p=>p.parsedJson?.margin_manager_id),a=(await this.sdk.fullClient.batchGetObjects(i,{json:!0})).map((p,f)=>{let g=p.json,_=(g?.balance_manager?.allow_listed?.contents).map(A=>A),I=_.includes(g?.deposit_cap?.id)&&_.includes(g?.withdraw_cap?.id)&&_.includes(g?.trade_cap?.id);return{balanceManagerId:g?.balance_manager?.id,marginManagerId:i[f],capOk:I}}).filter(p=>p.capOk),c=await Promise.all(a.map(({balanceManagerId:p})=>this.sdk.fullClient.listDynamicFields({parentId:p}))),u=new Map;return c.forEach((p,f)=>{let g=p?.dynamicFields??[];if(g.length>0){let b=E.struct("ReferralKey",{pos0:E.Address}).parse(g[0].name.bcs);u.set(a[f].marginManagerId,b.pos0)}}),{finalResult:s.map(p=>{let f=p.parsedJson?.margin_manager_id;return{...p.parsedJson,referralKey:u.get(f)}}),referralMap:u}}catch(n){throw new Error(`Failed to get margin managers by account: ${n instanceof Error?n.message:String(n)}`)}}async getBaseBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get base balance: ${o instanceof Error?o.message:String(o)}`)}}async getQuoteBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get quote balance: ${o instanceof Error?o.message:String(o)}`)}}async getDeepBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get base balance: ${o instanceof Error?o.message:String(o)}`)}}async getPoolMarginManagerBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let i=new J,o=r===this.deepCoin.coinType,a=s===this.deepCoin.coinType,c=o||a;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(n)],typeArguments:[r,s]}),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(n)],typeArguments:[r,s]}),c||i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let u=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!u.commandResults||!u.commandResults[0]||!u.commandResults[0].returnValues||!u.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${u.effects?.status?.error||"Unknown error"}`);let d=E.U64.parse(new Uint8Array(u.commandResults[0].returnValues[0].bcs)),p=E.U64.parse(new Uint8Array(u.commandResults[1].returnValues[0].bcs)),f=c?o?d:p:E.U64.parse(new Uint8Array(u.commandResults[2].returnValues[0].bcs));return{[r]:d.toString(),[s]:p.toString(),[this.deepCoin.coinType]:f.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||o.commandResults[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs));return{baseBorrowedShare:a,quoteBorrowedShare:c}}catch(o){throw new Error(`Failed to get borrowed shares: ${o instanceof Error?o.message:String(o)}`)}}managerState=({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:c=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:d})=>p=>{p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[p.object(n),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(u),p.object(d),p.object(i),p.object(o),p.object(a),p.object.clock()],typeArguments:[r.coinType,s.coinType]})};async getManagerState(t,n=new J){let{account:r,marginManager:s,baseCoin:i,quoteCoin:o,pool:a,baseMarginPool:c,quoteMarginPool:u,decimals:d=6}=t;if(!r||!s||!a||!c||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!o?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!o.scalar)throw new Error("Base and quote coin scalars are required");try{let p=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],n),f=p.get(i.feed),g=p.get(o.feed);if(!f||!g)throw new Error("Failed to get price feed object IDs");n.add(this.managerState({...t,basePriceFeedObjectId:f,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.sendSimulationTransaction(n,r);if(!b.commandResults||!b.commandResults[0]||!b.commandResults[0].returnValues||b.commandResults[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.Transaction?.effects?.status?.error||"Unknown error"}`);let _=X(E.Address.parse(new Uint8Array(b.commandResults[0].returnValues[0].bcs))),I=X(E.Address.parse(new Uint8Array(b.commandResults[0].returnValues[1].bcs))),A=Number(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[2].bcs)))/1e9,M=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[3].bcs))),i.scalar,d),C=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[4].bcs))),o.scalar,d),B=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[5].bcs))),i.scalar,d),L=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[6].bcs))),o.scalar,d),j=E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[7].bcs)),q=Number(E.u8().parse(new Uint8Array(b.commandResults[0].returnValues[8].bcs))),P=E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[9].bcs)),D=Number(E.u8().parse(new Uint8Array(b.commandResults[0].returnValues[10].bcs))),Z=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[11].bcs))),ce=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[12].bcs))),te=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[13].bcs)));return{managerId:_,deepbookPoolId:I,riskRatio:A,baseAsset:M,quoteAsset:C,baseDebt:B,quoteDebt:L,basePythPrice:j.toString(),basePythDecimals:q,quotePythPrice:P.toString(),quotePythDecimals:D,currentPrice:Z,lowestTriggerAbovePrice:ce,highestTriggerBelowPrice:te}}catch(p){throw new Error(`Failed to get manager state: ${p instanceof Error?p.message:String(p)}`)}}async detectPriceBoundary({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,price:c,is_bid:u,decimals:d=6}){if(!t||!n||!i||!o||!a)throw new Error("All required parameters must be provided");if(!r?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!r.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let p=typeof c=="bigint"?c:BigInt(c),f=await this.getManagerState({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:d},new J),g=f.highestTriggerBelowPrice,b=f.lowestTriggerAbovePrice,_=u?p<=b:p>=g;return{is_bid:u,price:p,lower_bound:g,upper_bound:b,is_within:_,is_boundary:u?p===b:p===g}}async calculateAssets({account:t,marginManager:n,pool:r,baseCoin:s,quoteCoin:i,tx:o=new J}){if(!t||!n||!r)throw new Error("Account, marginManager, and pool are required");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");try{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[o.object(n),o.object(r)],typeArguments:[s.coinType,i.coinType]});let a=await this.sdk.fullClient.sendSimulationTransaction(o,t);if(!a.commandResults||!a.commandResults[0]||!a.commandResults[0].returnValues||a.commandResults[0].returnValues.length<2)throw new Error(`Transaction failed: ${a.effects?.status?.error||"Unknown error"}`);let c=a.commandResults[0].returnValues[0].bcs,u=a.commandResults[0].returnValues[1].bcs;if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let d=E.U64.parse(new Uint8Array(c)),p=E.U64.parse(new Uint8Array(u));return{baseAsset:d.toString(),quoteAsset:p.toString(),tx:o}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){if(!t||!n||!r||!s||!i||!o)throw new Error("All parameters are required");try{let{baseBorrowedShare:a,quoteBorrowedShare:c}=await this.getBorrowedShares({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}),u=!!R(a).gt(R(c)),d=u?i:o,p=u?a:c,f=new J;f.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[f.object(d),f.pure.u64(BigInt(p)),f.object.clock()],typeArguments:[u?r:s]});let g=await this.sdk.fullClient.simulateTransaction({transaction:f,checksEnabled:!1,include:{commandResults:!0,json:!0}}),b=E.U64.parse(g?.commandResults?.[0]?.returnValues?.[0]?.bcs);return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(a){throw new Error(`Failed to get borrowed amount: ${a instanceof Error?a.message:String(a)}`)}}async deposit({marginManager:t,baseCoin:n,quoteCoin:r,amount:s,depositCoinType:i},o=new J){if(!t)throw new Error("Margin manager is required");if(!n?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid deposit amount is required");if(!n.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let a=Gt.buildCoinWithBalance(BigInt(s),i,o),c=await this.pythPrice.updatePythPriceIDs([n.feed,r.feed],o),u=c.get(n.feed),d=c.get(r.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?o.object(t):t,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(u),o.object(d),a,o.object(he)],typeArguments:[n.coinType,r.coinType,i]}),o}catch(a){throw new Error(`Failed to deposit: ${a instanceof Error?a.message:String(a)}`)}}async withdraw({account:t,marginManager:n,baseMarginPool:r,quoteMarginPool:s,baseCoin:i,quoteCoin:o,pool:a,amount:c,withdrawCoinType:u},d=new J){if(!t||!n||!r||!s||!a)throw new Error("All required parameters must be provided");if(!i?.coinType||!o?.coinType)throw new Error("Base and quote coin types are required");if(!c||BigInt(c)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!o.feed)throw new Error("Base and quote coin feeds are required");try{let p=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],d),f=p.get(i.feed),g=p.get(o.feed);if(!f||!g)throw new Error("Failed to get price feed object IDs");let b=d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[d.object(this._sdk.sdkOptions.margin_utils.global_config_id),d.object(this._sdk.sdkOptions.margin_utils.versioned_id),d.object(n),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(r),d.object(s),d.object(f),d.object(g),d.object(a),d.pure.u64(BigInt(c)),d.object(he)],typeArguments:[i.coinType,o.coinType,u]});if(Gt.isSuiCoin(u))d.transferObjects([b],t);else{let _=await this._sdk.fullClient.getOwnerCoinAssets(t,u),I=Gt.buildCoinForAmount(d,_,BigInt(0),u,!1);I.target_coin?(d.mergeCoins(I.target_coin,[b]),I.is_mint_zero_coin&&d.transferObjects([I.target_coin],t)):d.transferObjects([b],t)}return d}catch(p){throw new Error(`Failed to withdraw: ${p instanceof Error?p.message:String(p)}`)}}async borrowBase({marginManager:t,baseMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new J){if(!t||!n||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!o||BigInt(o)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let c=await this.pythPrice.updatePythPriceIDs([r.feed,s.feed],a),u=c.get(r.feed),d=c.get(s.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(t),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(n),a.object(u),a.object(d),a.object(i),a.pure.u64(BigInt(o)),a.object(he)],typeArguments:[r.coinType,s.coinType]}),a}catch(c){throw new Error(`Failed to borrow base: ${c instanceof Error?c.message:String(c)}`)}}async borrowQuote({marginManager:t,quoteMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new J){if(!t||!n||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!o||BigInt(o)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let c=await this.pythPrice.updatePythPriceIDs([r.feed,s.feed],a),u=c.get(r.feed),d=c.get(s.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?a.object(t):t,a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(n),a.object(u),a.object(d),a.object(i),a.pure.u64(BigInt(o)),a.object(he)],typeArguments:[r.coinType,s.coinType]}),a}catch(c){throw new Error(`Failed to borrow quote: ${c instanceof Error?c.message:String(c)}`)}}async repayBase({marginManager:t,baseMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new J){if(!t||!n||!r||!s)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 a={marginManager:t,baseCoin:r,quoteCoin:s,amount:i,depositCoinType:r.coinType};await this.deposit(a,o);try{return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?o.pure.u64(i):null}),o.object(he)],typeArguments:[r.coinType,s.coinType]}),o}catch(c){throw new Error(`Failed to repay base: ${c instanceof Error?c.message:String(c)}`)}}async repayQuote({marginManager:t,quoteMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new J){if(!t||!n||!r||!s)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 a={marginManager:t,baseCoin:r,quoteCoin:s,amount:i,depositCoinType:s.coinType};await this.deposit(a,o);try{return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?o.pure.u64(i):null}),o.object(he)],typeArguments:[r.coinType,s.coinType]}),o}catch(c){throw new Error(`Failed to repay quote: ${c instanceof Error?c.message:String(c)}`)}}async repay({marginManager:t,baseMarginPool:n,quoteMarginPool:r,baseCoin:s,quoteCoin:i,isBase:o,amount:a},c=new J){try{let u=this.sdk.senderAddress,d,p=a;a||(d=await this.getBorrowedAmount({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType,baseMarginPool:n,quoteMarginPool:r}),p=o?d.baseBorrowedAmount:d.quoteBorrowedAmount);let f,g={marginManager:t,baseCoin:s,quoteCoin:i,depositCoinType:o?s.coinType:i.coinType};if(o){let b=await this.getBaseBalance({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});f=R(p).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});f=R(p).sub(b).toString()}R(f).gt(0)&&await this.deposit({...g,amount:f},c),c.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${o?"repay_base":"repay_quote"}`,arguments:[c.object(this._sdk.sdkOptions.margin_utils.global_config_id),c.object(this._sdk.sdkOptions.margin_utils.versioned_id),c.object(t),c.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),c.object(o?n:r),c.object.option({type:"u64",value:a?c.pure.u64(a):null}),c.object(he)],typeArguments:[s.coinType,i.coinType]})}catch(u){console.log("\u{1F680} ~ MarginUtilsModule ~ repay ~ error:",u)}return c}removeReferralKey=(t,n,r,s,i=new J)=>{let o=i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::id`,typeArguments:[r,s],arguments:[i.object(n)]});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::unset_margin_manager_referral`,typeArguments:[r,s],arguments:[typeof t=="string"?i.object(t):t,o]})};async#e(t,n,r){if(!t.feed||!n.feed)throw new Error("Base and quote coin feeds are required");let s=await this.pythPrice.updatePythPriceIDs([t.feed,n.feed],r),i=s.get(t.feed),o=s.get(n.feed);if(!i||!o)throw new Error("Failed to get price feed object IDs");return{baseOracle:i,quoteOracle:o}}async placeMarginMarketOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u,exactBase:d,referralKey:p},f=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!o||BigInt(Vs(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(Vs(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:g,baseCoin:b,quoteCoin:_}=n;if(b.decimals===void 0||_.decimals===void 0)throw new Error("Base and quote coin decimals are required");p&&this.removeReferralKey(t,g,b.coinType,_.coinType,f);try{let{baseOracle:I,quoteOracle:A}=await this.#e(b,_,f);return f.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order_v2`,arguments:[f.object(this.sdk.sdkOptions.margin_utils.global_config_id),f.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?f.object(t):t,f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(g),f.object(r),f.object(s),f.object(I),f.object(A),f.pure.u8(i),f.pure.u64(o),f.pure.bool(c),f.pure.bool(u),f.pure.bool(d===void 0?!c:d),f.pure.u64(a),f.object(he)],typeArguments:[b.coinType,_.coinType]}),f}catch(I){throw new Error(`Failed to place market order: ${I instanceof Error?I.message:String(I)}`)}}async placeMarginLimitOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:p=Date.now()+31536e8,referralKey:f},g=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!a||!c)throw new Error("Price and quantity are required");let{id:b,baseCoin:_,quoteCoin:I}=n;if(_.decimals===void 0||I.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let A=BigInt(R(a).mul(10**(I.decimals-_.decimals+9)).toString()),M=BigInt(Vs(c,_.decimals));if(A<=0n||M<=0n)throw new Error("Price and quantity must be greater than zero");f&&this.removeReferralKey(t,b,_.coinType,I.coinType,g);let{baseOracle:C,quoteOracle:B}=await this.#e(_,I,g);return g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order_v2`,arguments:[g.object(this.sdk.sdkOptions.margin_utils.global_config_id),g.object(this.sdk.sdkOptions.margin_utils.versioned_id),g.object(t),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(b),g.object(r),g.object(s),g.object(C),g.object(B),g.pure.u8(i),g.pure.u8(o),g.pure.u64(A),g.pure.u64(M),g.pure.bool(u),g.pure.bool(d),g.pure.u64(p),g.object(he)],typeArguments:[_.coinType,I.coinType]}),g}catch(A){throw new Error(`Failed to place limit order: ${A instanceof Error?A.message:String(A)}`)}}modifyMarginOrder({marginManager:t,poolInfo:n,orderId:r,newQuantity:s},i=new J){if(!t||!n||!r||!s)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(n.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let o=BigInt(Vs(s,n.baseCoin.decimals));if(o<=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(t),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(n.id),i.pure.u128(r),i.pure.u64(o),i.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i}catch(o){throw new Error(`Failed to modify order: ${o instanceof Error?o.message:String(o)}`)}}cancelMarginOrder({marginManager:t,poolInfo:n,orderId:r},s=new J){if(!t||!n||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(t),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(n.id),s.pure.u128(r),s.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:t,poolInfo:n},r=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.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(t),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(n.id),r.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),r}catch(s){throw new Error(`Failed to cancel all orders: ${s instanceof Error?s.message:String(s)}`)}}async placeReduceOnlyLimitOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:p=Date.now()+31536e8},f=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!a||!c)throw new Error("Price and quantity are required");let{baseCoin:g,quoteCoin:b}=n;if(g.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let _=BigInt(R(a).mul(10**(b.decimals-g.decimals+9)).toString()),I=BigInt(Vs(c,g.decimals));if(_<=0n||I<=0n)throw new Error("Price and quantity must be greater than zero");let{baseOracle:A,quoteOracle:M}=await this.#e(g,b,f);return f.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order_v2`,arguments:[f.object(this.sdk.sdkOptions.margin_utils.global_config_id),f.object(this.sdk.sdkOptions.margin_utils.versioned_id),f.object(t),f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(n.id),f.object(r),f.object(s),f.object(A),f.object(M),f.pure.u8(i),f.pure.u8(o),f.pure.u64(_),f.pure.u64(I),f.pure.bool(u),f.pure.bool(d),f.pure.u64(p),f.object(he)],typeArguments:[g.coinType,b.coinType]}),f}catch(_){throw new Error(`Failed to place reduce only limit order: ${_ instanceof Error?_.message:String(_)}`)}}async placeReduceOnlyMarketOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u},d=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!o||BigInt(Vs(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(Vs(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{baseCoin:p,quoteCoin:f}=n;if(p.decimals===void 0||f.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let{baseOracle:g,quoteOracle:b}=await this.#e(p,f,d);return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order_v2`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(n.id),d.object(r),d.object(s),d.object(g),d.object(b),d.pure.u8(i),d.pure.u64(o),d.pure.bool(c),d.pure.bool(u),d.pure.u64(a),d.object(he)],typeArguments:[p.coinType,f.coinType]}),d}catch(g){throw new Error(`Failed to place reduce only market order: ${g instanceof Error?g.message:String(g)}`)}}async getOpenOrder(t,n,r,s,i=!1,o=new J){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(t.address),i?r:o.object(r)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let f=(await this._sdk.fullClient.simulateTransaction({transaction:o,include:{commandResults:!0,json:!0},checksEnabled:!1})).commandResults[i?1:0].returnValues[0].bcs;a=E.struct("VecSet",{constants:E.vector(E.U128)}).parse(new Uint8Array(f)).constants}if(a.length===0)return[];let c=a.map(p=>({pool:{pool_id:t.address,baseCoinType:t.baseCoin.coinType,quoteCoinType:t.quoteCoin.coinType},orderId:p})),u=await this.sdk.DeepbookUtils.getOrderInfoList(c,n)||[],d=[];return u.forEach(p=>{let f=this.sdk.DeepbookUtils.decodeOrderId(BigInt(p.order_id));d.push({...p,price:f.price,isBid:f.isBid,pool:t})}),d}async getAccountOpenOrders({poolInfo:t,marginManager:n}){try{let r=new J,s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(n)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.getOpenOrder(t,this.sdk.senderAddress,s,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(t,n){try{if(!t||!n||n.length===0)throw new Error("Account or pools are required");let r=[];for(let s=0;s<n.length;s++){let i=new J,o=n[s];if(o.margin_manager_id){let a=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(o.margin_manager_id)],typeArguments:[o.baseCoin.coinType,o.quoteCoin.coinType]}),c=await this.getOpenOrder(o,this.sdk.senderAddress,a,void 0,!0,i);r.push(...c)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(t=new J,n){let r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(he)]});return n&&t.transferObjects([r],this.sdk.senderAddress),{tx:t,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(t){throw new Error(`Failed to get account supplyCap: ${t instanceof Error?t.message:String(t)}`)}}mintSupplierCapAndSupply({marginPool:t,supplyCoinType:n,amount:r}){let s=new J,{supplierCap:i}=this.mintSupplierCap(s,!1);return this.supply({marginPool:t,supplierCap:i,supplyCoinType:n,amount:r,tx:s}),s.transferObjects([i],this.sdk.senderAddress),s}supply({marginPool:t,supplierCap:n,supplyCoinType:r,amount:s,tx:i}){let o=i??new J;if(!n)throw new Error("Either supplierCap must be provided");let a=Gt.buildCoinWithBalance(BigInt(s),r,o);return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),a,o.pure.option("address","0x0"),o.object(he)]}),o}supplierWithdraw({marginPool:t,withdrawCoinType:n,amount:r,supplierCapId:s,hasSwap:i,withdrawAll:o,tx:a=new J}){let c=a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[n],arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(t),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s),a.object.option({type:"u64",value:o?null:a.pure.u64(r)}),a.object(he)]});return i?c:(a.transferObjects([c],this.sdk.senderAddress),a)}withdrawReferralFees({marginPool:t}){let n=new J,r=n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[n.object(this._sdk.sdkOptions.margin_utils.versioned_id),n.object(t),n.object(this._sdk.sdkOptions.margin_utils.registry_id),n.object.option({type:"0x1",value:null}),n.object(he)],typeArguments:[this.deepCoin.coinType]});return n.transferObjects([r],this.sdk.senderAddress),n}async getUserSupplyAmount({marginPool:t,supplyCoin:n,supplierCapId:r}){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[n.coinType],arguments:[s.object(t),s.object(r),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#t(BigInt(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),n.scalar,n.decimals)}async getDeepBookMarginRegistry(){let n=(await this.sdk.fullClient.getObject({objectId:this._sdk.sdkOptions.margin_utils.margin_registry_id,include:{json:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicField({parentId:n,name:{type:"u64",bcs:E.u64().serialize(1).toBytes()}}),s=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:s,margin_pool_table_id:i}}async getDeepBookPool(){let{data:t}=await this.sdk.fullClient.listDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),n=t.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(n,{json:!0}),s=[];for(let i=0;i<r.length;i++){let o=r[i].json;s.push($b(o))}return s}async getDeepBookMarginPool(){let{data:t}=await this.sdk.fullClient.getDynamicFieldsByPage(this.sdk.sdkOptions.margin_utils.margin_pool_table_id),n=t.map(c=>c.fieldId),r=await this.sdk.fullClient.batchGetObjects(n,{json:!0}),s=[],i=[];for(let c=0;c<r.length;c++){let u=r[c].json;i.push(u.value),s.push({deposit_coin_type:u.name.name,id:u.id})}let o=await this.sdk.fullClient.batchGetObjects(i,{json:!0}),a=[];for(let c=0;c<o.length;c++){let u=o[c].json;a.push(qb(u,s[c]))}return a}async getBaseQuantityIn(t,n,r,s=.01){let i=new J;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_base_quantity_in`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[i.object(t.address),i.pure.u64(n),i.pure.bool(r),i.object(he)]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,this.sdk.senderAddress);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:c.toString(),quantityInLeft:R(a.toString()).mul(R(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(t,n,r,s=.01){let i=new J;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_in`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[i.object(t.address),i.pure.u64(n),i.pure.bool(r),i.object(he)]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,this.sdk.senderAddress);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:a.toString(),quantityInLeft:R(c.toString()).mul(R(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(t,n,r){let s=new J;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[s.object(t.address),s.pure.u64(n),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs));return{base_amount:o.toString(),quote_amount:a.toString(),deep_fee_amount:c.toString()}}async getQuoteQuantityOutInput(t,n,r){let s=new J;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[s.object(t.address),s.pure.u64(n),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs));return{base_amount:o.toString(),quote_amount:a.toString(),deep_fee_amount:c.toString()}}async getAccount(t,n,r=new J){let s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i=[n];for(let d=0;d<i.length;d++){let p=i[d];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(p.address),typeof s=="string"?r.object(s):s],typeArguments:[p.baseCoin.coinType,p.quoteCoin.coinType]})}let o=await this._sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,json:!0}}),a=o.Transaction??o.FailedTransaction;if(!a?.events?.length)return null;let c,u=[];return a.events.forEach((d,p)=>{c=d?.json;let f=c.account.open_orders.contents,g=c.account.owed_balances,b=c.account.settled_balances,_=c.account.unclaimed_rebates,I=c.account.taker_volume;u.push({balance_manager_id:s,open_orders:f,owed_balances:g,settled_balances:b,unclaimed_rebates:_,taker_volume:I,poolInfo:i[p]})}),u}async withdrawSettledAmounts({poolInfo:t,marginManager:n},r=new J){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(n),r.object(t.address)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}#t(t,n,r){if(n<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let s=BigInt(n),i=t/s,o=t%s;if(o===0n)return i.toString();let a=n.toString().length-1,d=o.toString().padStart(a,"0").slice(0,r).replace(/0+$/,"");return d?`${i}.${d}`:i.toString()}async getMarginPoolStateForInterest(t){if(!t)throw new Error("marginPoolId is required");let n=await this.sdk.fullClient.getObject({objectId:t,include:{json:!0}});if(!n?.object?.json)throw new Error(`Failed to fetch margin pool: ${t}`);let r=n.object.json,s=r.state,i=r.config,o=i.interest_config,a=i.margin_pool_config;return{poolState:{total_supply:BigInt(s.total_supply),total_borrow:BigInt(s.total_borrow),supply_shares:BigInt(s.supply_shares),borrow_shares:BigInt(s.borrow_shares),last_update_timestamp:BigInt(s.last_update_timestamp)},interestConfig:{base_rate:BigInt(o.base_rate),base_slope:BigInt(o.base_slope),optimal_utilization:BigInt(o.optimal_utilization),excess_slope:BigInt(o.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(a.protocol_spread),max_utilization_rate:BigInt(a.max_utilization_rate),min_borrow:BigInt(a.min_borrow),supply_cap:BigInt(a.supply_cap)}}}async getChainTimestamp(){let{response:t}=await this.sdk.fullClient.ledgerService.getServiceInfo({}),n=t.timestamp;if(!n)throw new Error("No timestamp in service info");return BigInt(n.seconds)*1000n+BigInt(n.nanos)/1000000n}async batchGetBorrowedShares({account:t,marginManagerList:n}){let r=new J;return n.forEach(i=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(i.marginManagerId)],typeArguments:[i.baseCoinType,i.quoteCoinType]})}),(await this.sdk.fullClient.sendSimulationTransaction(r,t)).commandResults.map((i,o)=>{let a=E.U64.parse(new Uint8Array(i.returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(i.returnValues[1].bcs));return{marginManagerId:n[o].marginManagerId,baseBorrowedShare:a,quoteBorrowedShare:c}})}async betchGetOpenOrders({account:t,marginManagerList:n},r=new J,s=!1){n.forEach(g=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(g.poolId),r.object(b)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let i=await this.sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,commandResults:!0,json:!0}}),o=i.Transaction?.events.map((g,b)=>({marginManagerId:n[b].marginManagerId,...g?.json?.account?.settled_balances||{}})),a=i.commandResults.filter((g,b)=>(b-1)%4===0),c=E.struct("VecSet",{constants:E.vector(E.U128)}),u=[];a.forEach((g,b)=>{let _=c.parse(g.returnValues[0].bcs).constants;_.length>0&&_.forEach(I=>{u.push({pool:{pool_id:n[b].poolId,baseCoinType:n[b].baseCoinType,quoteCoinType:n[b].quoteCoinType},marginManagerId:n[b].marginManagerId,orderId:I})})});let d=i.commandResults.filter((g,b)=>(b-3)%4===0),p=[];d.forEach((g,b)=>{p.push({marginManagerId:n[b].marginManagerId,base:E.U64.parse(g.returnValues[0].bcs),quote:E.U64.parse(g.returnValues[1].bcs),deep:E.U64.parse(g.returnValues[2].bcs)})});let f=[];return u.forEach((g,b)=>{let _=this.sdk.DeepbookUtils.decodeOrderId(BigInt(g.orderId));f.push({...g,price:_.price.toString(),isBid:_.isBid})}),{openOrders:f,settledBalances:o,lockedBalances:p}}async getSingleMarginManagerOpenOrders({account:t,marginManagerId:n,poolId:r,baseCoinType:s,quoteCoinType:i,baseMarginPool:o,quoteMarginPool:a}){let c=new J,u=c.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[c.object(n)],typeArguments:[s,i]});c.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[c.object(r),u],typeArguments:[s,i]});let d=E.struct("VecSet",{constants:E.vector(E.U128)}),f=(await this.sdk.fullClient.simulateTransaction({transaction:c,checksEnabled:!1,include:{commandResults:!0,json:!0}})).commandResults.find(C=>C?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),g=d.parse(new Uint8Array(f.returnValues[0].bcs)).constants,b=[];g.forEach(C=>{b.push({pool:{pool_id:r,baseCoinType:s,quoteCoinType:i},marginManagerId:n,orderId:C})});let _=b?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(b,t)||[]:[],I=[];b.forEach((C,B)=>{let L=this.sdk.DeepbookUtils.decodeOrderId(BigInt(C.orderId)),j=_.find(q=>q.order_id===C.orderId)||{};I.push({...C,...j,price:L.price.toString(),isBid:L.isBid})});let A={marginManagerId:n,base:"0",quote:"0",deep:"0"};if(_?.length>0){let C=new J,B=C.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[C.object(n)],typeArguments:[s,i]});C.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[C.object(r),B],typeArguments:[s,i]});let j=(await this.sdk.fullClient.simulateTransaction({transaction:C,checksEnabled:!1,include:{commandResults:!0,json:!0}})).commandResults.find(q=>q?.returnValues?.length===3);A={...A,base:E.U64.parse(new Uint8Array(j.returnValues[0].bcs)),quote:E.U64.parse(new Uint8Array(j.returnValues[1].bcs)),deep:E.U64.parse(new Uint8Array(j.returnValues[2].bcs))}}let M={base:"0",quote:"0",deep:"0"};try{let C=new J,B=C.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[C.object(n)],typeArguments:[s,i]});C.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[C.object(r),B],typeArguments:[s,i]});let L=await this.sdk.fullClient.simulateTransaction({transaction:C,checksEnabled:!1,include:{events:!0,json:!0}});M={marginManagerId:n,...M,...L?.Transaction?.events?.json?.account?.settled_balances||{}}}catch(C){console.log("\u{1F680} ~ MarginUtilsModule ~ getSingleMarginManagerPosRelevantData ~ error:",C)}return{openOrders:I,settledBalances:[M],lockedBalances:[A]}}async getAllPosRelevantData({account:t,marginManagerList:n}){try{let{openOrders:r,settledBalances:s,lockedBalances:i}=await this.betchGetOpenOrders({account:t,marginManagerList:n}),o=await this.batchGetBorrowedShares({account:t,marginManagerList:n}),a=new J,c=0,u=[];n.forEach(f=>{a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"base_balance",marginManagerId:f.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"quote_balance",marginManagerId:f.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"deep_balance",marginManagerId:f.marginManagerId},c++;let g=o?.find(b=>b.marginManagerId===f.marginManagerId);if(g&&(Number(g.baseBorrowedShare)>0||Number(g.quoteBorrowedShare)>0)){let b=g.baseBorrowedShare,_=g.quoteBorrowedShare,I=!!R(b).gt(R(_)),A=I?f.baseMarginPool:f.quoteMarginPool,M=I?b:_;a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[a.object(A),a.pure.u64(BigInt(M)),a.object.clock()],typeArguments:[I?f?.baseCoinType:f?.quoteCoinType]}),u[c]={type:I?"borrow_base_amount":"borrow_quote_amount",marginManagerId:f.marginManagerId},c++}});let d=await this.sdk.fullClient.simulateTransaction({transaction:a,checksEnabled:!1,include:{commandResults:!0,events:!0,json:!0}}),p=Object.fromEntries(n.map(f=>[f.marginManagerId,{...f,quote_balance:"0",base_balance:"0",deep_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return d?.commandResults?.forEach((f,g)=>{let b=u[g],_=E.U64.parse(new Uint8Array(f.returnValues[0].bcs));p[b.marginManagerId]={...p[b.marginManagerId],[b.type]:_}}),r.forEach(f=>{p[f.marginManagerId].open_orders.push(f)}),s.forEach(f=>{p[f.marginManagerId].settled_balances=f}),i.forEach(f=>{p[f.marginManagerId].locked_balances=f}),Object.values(p).forEach(f=>{f.locked_balances&&f.settled_balances&&(f.locked_balances={...f.locked_balances,base:R(f.locked_balances.base||"0").minus(R(f.settled_balances.base||"0")).toString(),quote:R(f.locked_balances.quote||"0").minus(R(f.settled_balances.quote||"0")).toString(),deep:R(f.locked_balances.deep||"0").minus(R(f.settled_balances.deep||"0")).toString()})}),p}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i,margin_registry_id:o}=r,{margin_manager_id:a,pool_id:c,base_coin:u,quote_coin:d,conditional_order_id:p,pending_order:f,is_trigger_below_price:g,trigger_price:b}=t,_=await this.pythPrice.updatePythPriceIDs([u.feed,d.feed],n),I=_.get(u.feed),A=_.get(d.feed);if(!I||!A)throw new Error("Failed to get price feed object IDs");let M=n.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[n.pure.bool(g),n.pure.u64(b)]}),C=this.newPendingOrder(f,n);n.moveCall({target:`${r.published_at}::margin_utils::add_conditional_order`,arguments:[n.object(s),n.object(i),n.object(a),n.object(c),n.object(I),n.object(A),n.object(o),typeof p=="string"?n.pure.u64(BigInt(p)):p,M,C,n.object(Cu)],typeArguments:[u.coinType,d.coinType]})}newPendingOrder(t,n){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in t){let{client_order_id:s,order_type:i,self_matching_option:o,price:a,quantity:c,is_bid:u,pay_with_deep:d,expire_timestamp:p}=t;return n.moveCall({target:`${r.published_at}::margin_utils::new_pending_limit_order`,arguments:[n.pure.u64(s),n.pure.u8(i),n.pure.u8(o),n.pure.u64(a),n.pure.u64(c),n.pure.bool(u),n.pure.bool(d),n.pure.u64(p)]})}else{let{client_order_id:s,self_matching_option:i,quantity:o,is_bid:a,pay_with_deep:c}=t;return n.moveCall({target:`${r.published_at}::margin_utils::new_pending_market_order`,arguments:[n.pure.u64(s),n.pure.u8(i),n.pure.u64(o),n.pure.bool(a),n.pure.bool(c)]})}}cancelAllConditionalOrders(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i}=r,{margin_manager_id:o,base_coin_type:a,quote_coin_type:c}=t;n.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[n.object(s),n.object(i),n.object(o),n.object(Cu)],typeArguments:[a,c]})}cancelConditionalOrders(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i}=r,{margin_manager_id:o,base_coin_type:a,quote_coin_type:c,conditional_order_id:u}=t;n.moveCall({target:`${r.published_at}::margin_utils::cancel_conditional_order`,arguments:[n.object(s),n.object(i),n.object(o),n.pure.u64(u),n.object(Cu)],typeArguments:[a,c]})}async getConditionalOrders(t,n){let{deepbook:r}=this.sdk.sdkOptions;t.forEach(u=>{let{margin_manager_id:d,base_coin_type:p,quote_coin_type:f,conditional_order_ids:g}=u;g.forEach(b=>{n.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[n.object(d),n.pure.u64(b)],typeArguments:[p,f]})})});let s=await this.sdk.fullClient.sendSimulationTransaction(n,X("0x0"));if(!s?.commandResults)return[];let i=E.struct("Condition",{trigger_below_price:E.bool(),trigger_price:E.u64()}),o=E.struct("PendingOrder",{is_limit_order:E.bool(),client_order_id:E.u64(),order_type:E.option(E.u8()),self_matching_option:E.u8(),price:E.option(E.u64()),quantity:E.u64(),is_bid:E.bool(),pay_with_deep:E.bool(),expire_timestamp:E.option(E.u64())}),a=E.struct("ConditionalOrder",{conditional_order_id:E.u64(),condition:i,pending_order:o}),c=u=>{if(u.length===0||u.length===1&&u[0]===0)return null;try{return a.parse(u)}catch{if(u[0]===1&&u.length>1)try{return a.parse(u.subarray(1))}catch{return null}return null}};return s.commandResults.map(u=>{if(!u?.returnValues?.[0]?.bcs)return null;try{let d=u.returnValues[0].bcs,p=c(d);if(!p)return null;let f=this.normalizeConditionalOrder(p);return t.forEach(g=>{g.conditional_order_ids.find(_=>_===f.conditional_order_id)&&(f.margin_manager_id=g.margin_manager_id,f.base_coin_type=g.base_coin_type,f.quote_coin_type=g.quote_coin_type)}),f}catch{return null}})}async getConditionalOrderIds(t,n){n=n||new J;let{deepbook:r}=this.sdk.sdkOptions,s={};return t.forEach(o=>{let{margin_manager_id:a,base_coin_type:c,quote_coin_type:u}=o;n.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order_ids`,arguments:[n.object(a)],typeArguments:[c,u]})}),(await this.sdk.fullClient.sendSimulationTransaction(n,X("0x0"))).commandResults.forEach((o,a)=>{if(o?.returnValues?.[0]?.bcs){let c=new Uint8Array(o.returnValues[0].bcs),u=E.vector(E.u64()).parse(c),d={margin_manager_id:t[a].margin_manager_id,base_coin_type:t[a].base_coin_type,quote_coin_type:t[a].quote_coin_type,conditional_order_ids:u.map(p=>p.toString())};s[t[a].margin_manager_id]=d}}),s}normalizeConditionalOrder(t){let n=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",conditional_order_id:n(t.conditional_order_id),condition:{trigger_below_price:t.condition.trigger_below_price,trigger_price:n(t.condition.trigger_price)},pending_order:{is_limit_order:t.pending_order.is_limit_order,client_order_id:n(t.pending_order.client_order_id),order_type:t.pending_order.order_type,self_matching_option:t.pending_order.self_matching_option,price:t.pending_order.price,quantity:n(t.pending_order.quantity),is_bid:t.pending_order.is_bid,pay_with_deep:t.pending_order.pay_with_deep,expire_timestamp:t.pending_order.expire_timestamp}}}async getPoolsPriceBounds(t){let n=new J;for(let o=0;o<t.length;o++)n.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_registry::get_price_bounds`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),n.pure.id(t[o].poolId),n.object(he)]});let r=await this.sdk.fullClient.simulateTransaction({transaction:n,checksEnabled:!1,include:{commandResults:!0,json:!0}}),s=[];for(let o=0;o<t.length;o++){let a=9-t[o].baseDecimals+t[o].quoteDecimals,c=E.U64.parse(r?.commandResults?.[o]?.returnValues?.[0]?.bcs),u=E.U64.parse(r?.commandResults?.[o]?.returnValues?.[1]?.bcs);s.push({pool_id:t[o].poolId,lower_bound:R(c).div(10**a).toString(),upper_bound:R(u).div(10**a).toString()})}let i=new Map;return s.forEach(o=>{i.set(o.pool_id,o)}),{priceBounds:s,priceBoundsMap:i}}};var Qx="https://graphql.mainnet.sui.io/graphql",eC="https://graphql.testnet.sui.io/graphql",Ru=class{_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=af(new Ko({baseUrl:t.fullRpcUrl,network:t.network==="testnet"?"testnet":"mainnet"}),new Dp({network:t.network,url:t.network==="testnet"?eC:Qx}),t.network==="testnet"?"testnet":"mainnet",new wp({url:t.fullRpcUrl,network:t.network})),this._deepbookUtils=new xu(this),this._marginUtils=new Nu(this),this._pythPrice=new wo(this),mf(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(t){this._senderAddress=t}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}};var tC=(s=>(s[s.NO_RESTRICTION=0]="NO_RESTRICTION",s[s.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",s[s.FILL_OR_KILL=2]="FILL_OR_KILL",s[s.POST_ONLY=3]="POST_ONLY",s))(tC||{}),nC=(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))(nC||{});var oz=Ru;export{Cu as CLOCK_ADDRESS,Au as CachedContent,Ru as CetusClmmSDK,Xq as ClmmExpectSwapModule,Kq as ClmmFetcherModule,Wq as ClmmIntegratePoolModule,Hq as ClmmIntegratePoolV2Module,Jq as ClmmIntegrateRouterModule,Zq as ClmmIntegrateRouterWithPartnerModule,Yq as ClmmIntegrateUtilsModule,Gt as CoinAssist,Qq as CoinInfoAddress,eG as CoinStoreAddress,vf as DEEP_SCALAR,sq as DEFAULT_GAS_BUDGET_FOR_MERGE,rq as DEFAULT_GAS_BUDGET_FOR_SPLIT,aq as DEFAULT_GAS_BUDGET_FOR_STAKE,iq as DEFAULT_GAS_BUDGET_FOR_TRANSFER,oq as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,uq as DEFAULT_NFT_TRANSFER_GAS_FEE,nG as DeepbookClobV2Moudle,tG as DeepbookCustodianV2Moudle,rG as DeepbookEndpointsV2Moudle,xu as DeepbookUtilsModule,iG as ERROR_HANDLING_RPC_LIST,gr as FLOAT_SCALAR,jr as FLOAT_SCALING,cq as GAS_SYMBOL,hf as GAS_TYPE_ARG,xb as GAS_TYPE_ARG_LONG,Nu as MarginUtilsModule,J$ as NORMALIZED_SUI_COIN_TYPE,tC as OrderType,lq as SUI_SYSTEM_STATE_OBJECT_ID,nC as SelfMatchingOption,Hx as YEAR_MS,Eb as addHexPrefix,vq as asIntN,bq as asUintN,P$ as bufferToHex,Cb as cacheTime1min,_o as cacheTime24h,Nb as cacheTime5min,pG as calc100PercentRepay,Kx as calcDebtDetail,Zx as calcInterestRate,Jx as calcUtilizationRate,lG as calculateRiskRatio,U$ as checkAddress,Ib as composeType,R as d,gf as decimalsMultiplier,oz as default,W$ as extractAddressFromType,Ls as extractStructTagFromType,H$ as fixCoinType,xi as fixDown,Ux as fixSuiObjectId,Ci as fromDecimalsAmount,sG as getDefaultSuiInputType,bf as getFutureTime,$x as getMoveObject,Px as getObjectDeletedResponse,Pb as getObjectFields,Ub as getObjectId,Lx as getObjectNotExistsResponse,Vx as getObjectReference,Db as getSuiObjectData,L$ as hexToNumber,V$ as hexToString,z$ as isSortedSymbols,Oq as isSuiObjectResponse,yf as maxDecimal,Gb as mulRoundUp,ff as normalizeCoinType,mf as patchFixSuiObjectId,Tq as printTransaction,pf as removeHexPrefix,_q as secretKeyToEd25519Keypair,wq as secretKeyToSecp256k1Keypair,D$ as shortAddress,Nx as shortString,Rb as sleepTime,Rx as toBuffer,Vs as toDecimalsAmount,Mx as utf8to16,qb as wrapDeepBookMarginPoolInfo,$b as wrapDeepBookPoolInfo};
|
|
1038
|
+
`,r={filter:{sender:t,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let s=await this.sdk.fullClient._graphQLClient.query({query:n,variables:r});return s?.data?.events?.nodes?s.data.events.nodes.map(o=>o?.contents?.json):[]}catch(s){throw new Error(`Failed to query balance managers: ${s instanceof Error?s.message:String(s)}`)}}async getMarginManagerByAccount(t){if(!t||typeof t!="string")throw new Error("Valid account address is required");try{let s=((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data??[]).filter(p=>p.parsedJson?.owner===t);if(!s.length)return[];let i=s.map(p=>p.parsedJson?.margin_manager_id),a=(await this.sdk.fullClient.batchGetObjects(i,{json:!0})).map((p,f)=>{let g=p.json,_=(g?.balance_manager?.allow_listed?.contents).map(A=>A),I=_.includes(g?.deposit_cap?.id)&&_.includes(g?.withdraw_cap?.id)&&_.includes(g?.trade_cap?.id);return{balanceManagerId:g?.balance_manager?.id,marginManagerId:i[f],capOk:I}}),c=await Promise.all(a.map(({balanceManagerId:p})=>this.sdk.fullClient.listDynamicFields({parentId:p}))),u=new Map;return c.forEach((p,f)=>{let g=p?.dynamicFields??[];if(g.length>0){let b=E.struct("ReferralKey",{pos0:E.Address}).parse(g[0].name.bcs);u.set(a[f].marginManagerId,b.pos0)}}),{finalResult:s.map(p=>{let f=p.parsedJson?.margin_manager_id;return{...p.parsedJson,referralKey:u.get(f)}}),referralMap:u}}catch(n){throw new Error(`Failed to get margin managers by account: ${n instanceof Error?n.message:String(n)}`)}}async getBaseBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get base balance: ${o instanceof Error?o.message:String(o)}`)}}async getQuoteBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get quote balance: ${o instanceof Error?o.message:String(o)}`)}}async getDeepBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.status?.error||"Unknown error"}`);return E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)).toString()}catch(o){throw new Error(`Failed to get base balance: ${o instanceof Error?o.message:String(o)}`)}}async getPoolMarginManagerBalance({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let i=new J,o=r===this.deepCoin.coinType,a=s===this.deepCoin.coinType,c=o||a;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[i.object(n)],typeArguments:[r,s]}),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[i.object(n)],typeArguments:[r,s]}),c||i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[i.object(n)],typeArguments:[r,s]});let u=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!u.commandResults||!u.commandResults[0]||!u.commandResults[0].returnValues||!u.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${u.effects?.status?.error||"Unknown error"}`);let d=E.U64.parse(new Uint8Array(u.commandResults[0].returnValues[0].bcs)),p=E.U64.parse(new Uint8Array(u.commandResults[1].returnValues[0].bcs)),f=c?o?d:p:E.U64.parse(new Uint8Array(u.commandResults[2].returnValues[0].bcs));return{[r]:d.toString(),[s]:p.toString(),[this.deepCoin.coinType]:f.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!t||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new J;try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[i.object(n)],typeArguments:[r,s]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,t);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||o.commandResults[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs));return{baseBorrowedShare:a,quoteBorrowedShare:c}}catch(o){throw new Error(`Failed to get borrowed shares: ${o instanceof Error?o.message:String(o)}`)}}managerState=({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:c=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:d})=>p=>{p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[p.object(n),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(u),p.object(d),p.object(i),p.object(o),p.object(a),p.object.clock()],typeArguments:[r.coinType,s.coinType]})};async getManagerState(t,n=new J){let{account:r,marginManager:s,baseCoin:i,quoteCoin:o,pool:a,baseMarginPool:c,quoteMarginPool:u,decimals:d=6}=t;if(!r||!s||!a||!c||!u)throw new Error("All required parameters must be provided");if(!i?.feed||!o?.feed)throw new Error("Base and quote coin feeds are required");if(!i.scalar||!o.scalar)throw new Error("Base and quote coin scalars are required");try{let p=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],n),f=p.get(i.feed),g=p.get(o.feed);if(!f||!g)throw new Error("Failed to get price feed object IDs");n.add(this.managerState({...t,basePriceFeedObjectId:f,quotePriceFeedObjectId:g}));let b=await this.sdk.fullClient.sendSimulationTransaction(n,r);if(!b.commandResults||!b.commandResults[0]||!b.commandResults[0].returnValues||b.commandResults[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${b.Transaction?.effects?.status?.error||"Unknown error"}`);let _=X(E.Address.parse(new Uint8Array(b.commandResults[0].returnValues[0].bcs))),I=X(E.Address.parse(new Uint8Array(b.commandResults[0].returnValues[1].bcs))),A=Number(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[2].bcs)))/1e9,M=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[3].bcs))),i.scalar,d),C=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[4].bcs))),o.scalar,d),B=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[5].bcs))),i.scalar,d),L=this.#t(BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[6].bcs))),o.scalar,d),j=E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[7].bcs)),q=Number(E.u8().parse(new Uint8Array(b.commandResults[0].returnValues[8].bcs))),P=E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[9].bcs)),D=Number(E.u8().parse(new Uint8Array(b.commandResults[0].returnValues[10].bcs))),Z=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[11].bcs))),ce=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[12].bcs))),te=BigInt(E.U64.parse(new Uint8Array(b.commandResults[0].returnValues[13].bcs)));return{managerId:_,deepbookPoolId:I,riskRatio:A,baseAsset:M,quoteAsset:C,baseDebt:B,quoteDebt:L,basePythPrice:j.toString(),basePythDecimals:q,quotePythPrice:P.toString(),quotePythDecimals:D,currentPrice:Z,lowestTriggerAbovePrice:ce,highestTriggerBelowPrice:te}}catch(p){throw new Error(`Failed to get manager state: ${p instanceof Error?p.message:String(p)}`)}}async detectPriceBoundary({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,price:c,is_bid:u,decimals:d=6}){if(!t||!n||!i||!o||!a)throw new Error("All required parameters must be provided");if(!r?.feed||!s?.feed)throw new Error("Base and quote coin feeds are required");if(!r.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let p=typeof c=="bigint"?c:BigInt(c),f=await this.getManagerState({account:t,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:d},new J),g=f.highestTriggerBelowPrice,b=f.lowestTriggerAbovePrice,_=u?p<=b:p>=g;return{is_bid:u,price:p,lower_bound:g,upper_bound:b,is_within:_,is_boundary:u?p===b:p===g}}async calculateAssets({account:t,marginManager:n,pool:r,baseCoin:s,quoteCoin:i,tx:o=new J}){if(!t||!n||!r)throw new Error("Account, marginManager, and pool are required");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");try{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[o.object(n),o.object(r)],typeArguments:[s.coinType,i.coinType]});let a=await this.sdk.fullClient.sendSimulationTransaction(o,t);if(!a.commandResults||!a.commandResults[0]||!a.commandResults[0].returnValues||a.commandResults[0].returnValues.length<2)throw new Error(`Transaction failed: ${a.effects?.status?.error||"Unknown error"}`);let c=a.commandResults[0].returnValues[0].bcs,u=a.commandResults[0].returnValues[1].bcs;if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");let d=E.U64.parse(new Uint8Array(c)),p=E.U64.parse(new Uint8Array(u));return{baseAsset:d.toString(),quoteAsset:p.toString(),tx:o}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){if(!t||!n||!r||!s||!i||!o)throw new Error("All parameters are required");try{let{baseBorrowedShare:a,quoteBorrowedShare:c}=await this.getBorrowedShares({account:t,marginManager:n,baseCoinType:r,quoteCoinType:s}),u=!!R(a).gt(R(c)),d=u?i:o,p=u?a:c,f=new J;f.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[f.object(d),f.pure.u64(BigInt(p)),f.object.clock()],typeArguments:[u?r:s]});let g=await this.sdk.fullClient.simulateTransaction({transaction:f,checksEnabled:!1,include:{commandResults:!0,json:!0}}),b=E.U64.parse(g?.commandResults?.[0]?.returnValues?.[0]?.bcs);return u?{baseBorrowedAmount:b.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:b.toString()}}catch(a){throw new Error(`Failed to get borrowed amount: ${a instanceof Error?a.message:String(a)}`)}}async deposit({marginManager:t,baseCoin:n,quoteCoin:r,amount:s,depositCoinType:i},o=new J){if(!t)throw new Error("Margin manager is required");if(!n?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!s||BigInt(s)<=0n)throw new Error("Valid deposit amount is required");if(!n.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let a=Gt.buildCoinWithBalance(BigInt(s),i,o),c=await this.pythPrice.updatePythPriceIDs([n.feed,r.feed],o),u=c.get(n.feed),d=c.get(r.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?o.object(t):t,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(u),o.object(d),a,o.object(he)],typeArguments:[n.coinType,r.coinType,i]}),o}catch(a){throw new Error(`Failed to deposit: ${a instanceof Error?a.message:String(a)}`)}}async withdraw({account:t,marginManager:n,baseMarginPool:r,quoteMarginPool:s,baseCoin:i,quoteCoin:o,pool:a,amount:c,withdrawCoinType:u},d=new J){if(!t||!n||!r||!s||!a)throw new Error("All required parameters must be provided");if(!i?.coinType||!o?.coinType)throw new Error("Base and quote coin types are required");if(!c||BigInt(c)<=0n)throw new Error("Valid withdraw amount is required");if(!i.feed||!o.feed)throw new Error("Base and quote coin feeds are required");try{let p=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],d),f=p.get(i.feed),g=p.get(o.feed);if(!f||!g)throw new Error("Failed to get price feed object IDs");let b=d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[d.object(this._sdk.sdkOptions.margin_utils.global_config_id),d.object(this._sdk.sdkOptions.margin_utils.versioned_id),d.object(n),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(r),d.object(s),d.object(f),d.object(g),d.object(a),d.pure.u64(BigInt(c)),d.object(he)],typeArguments:[i.coinType,o.coinType,u]});if(Gt.isSuiCoin(u))d.transferObjects([b],t);else{let _=await this._sdk.fullClient.getOwnerCoinAssets(t,u),I=Gt.buildCoinForAmount(d,_,BigInt(0),u,!1);I.target_coin?(d.mergeCoins(I.target_coin,[b]),I.is_mint_zero_coin&&d.transferObjects([I.target_coin],t)):d.transferObjects([b],t)}return d}catch(p){throw new Error(`Failed to withdraw: ${p instanceof Error?p.message:String(p)}`)}}async borrowBase({marginManager:t,baseMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new J){if(!t||!n||!i)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!o||BigInt(o)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let c=await this.pythPrice.updatePythPriceIDs([r.feed,s.feed],a),u=c.get(r.feed),d=c.get(s.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(t),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(n),a.object(u),a.object(d),a.object(i),a.pure.u64(BigInt(o)),a.object(he)],typeArguments:[r.coinType,s.coinType]}),a}catch(c){throw new Error(`Failed to borrow base: ${c instanceof Error?c.message:String(c)}`)}}async borrowQuote({marginManager:t,quoteMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new J){if(!t||!n||!i)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");if(!o||BigInt(o)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!s.feed)throw new Error("Base and quote coin feeds are required");try{let c=await this.pythPrice.updatePythPriceIDs([r.feed,s.feed],a),u=c.get(r.feed),d=c.get(s.feed);if(!u||!d)throw new Error("Failed to get price feed object IDs");return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?a.object(t):t,a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(n),a.object(u),a.object(d),a.object(i),a.pure.u64(BigInt(o)),a.object(he)],typeArguments:[r.coinType,s.coinType]}),a}catch(c){throw new Error(`Failed to borrow quote: ${c instanceof Error?c.message:String(c)}`)}}async repayBase({marginManager:t,baseMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new J){if(!t||!n||!r||!s)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 a={marginManager:t,baseCoin:r,quoteCoin:s,amount:i,depositCoinType:r.coinType};await this.deposit(a,o);try{return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?o.pure.u64(i):null}),o.object(he)],typeArguments:[r.coinType,s.coinType]}),o}catch(c){throw new Error(`Failed to repay base: ${c instanceof Error?c.message:String(c)}`)}}async repayQuote({marginManager:t,quoteMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new J){if(!t||!n||!r||!s)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 a={marginManager:t,baseCoin:r,quoteCoin:s,amount:i,depositCoinType:s.coinType};await this.deposit(a,o);try{return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?o.pure.u64(i):null}),o.object(he)],typeArguments:[r.coinType,s.coinType]}),o}catch(c){throw new Error(`Failed to repay quote: ${c instanceof Error?c.message:String(c)}`)}}async repay({marginManager:t,baseMarginPool:n,quoteMarginPool:r,baseCoin:s,quoteCoin:i,isBase:o,amount:a},c=new J){try{let u=this.sdk.senderAddress,d,p=a;a||(d=await this.getBorrowedAmount({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType,baseMarginPool:n,quoteMarginPool:r}),p=o?d.baseBorrowedAmount:d.quoteBorrowedAmount);let f,g={marginManager:t,baseCoin:s,quoteCoin:i,depositCoinType:o?s.coinType:i.coinType};if(o){let b=await this.getBaseBalance({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});f=R(p).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:t,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});f=R(p).sub(b).toString()}R(f).gt(0)&&await this.deposit({...g,amount:f},c),c.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${o?"repay_base":"repay_quote"}`,arguments:[c.object(this._sdk.sdkOptions.margin_utils.global_config_id),c.object(this._sdk.sdkOptions.margin_utils.versioned_id),c.object(t),c.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),c.object(o?n:r),c.object.option({type:"u64",value:a?c.pure.u64(a):null}),c.object(he)],typeArguments:[s.coinType,i.coinType]})}catch(u){console.log("\u{1F680} ~ MarginUtilsModule ~ repay ~ error:",u)}return c}removeReferralKey=(t,n,r,s,i=new J)=>{let o=i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::id`,typeArguments:[r,s],arguments:[i.object(n)]});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::unset_margin_manager_referral`,typeArguments:[r,s],arguments:[typeof t=="string"?i.object(t):t,o]})};async#e(t,n,r){if(!t.feed||!n.feed)throw new Error("Base and quote coin feeds are required");let s=await this.pythPrice.updatePythPriceIDs([t.feed,n.feed],r),i=s.get(t.feed),o=s.get(n.feed);if(!i||!o)throw new Error("Failed to get price feed object IDs");return{baseOracle:i,quoteOracle:o}}async placeMarginMarketOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u,exactBase:d,referralKey:p},f=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!o||BigInt(Vs(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(Vs(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:g,baseCoin:b,quoteCoin:_}=n;if(b.decimals===void 0||_.decimals===void 0)throw new Error("Base and quote coin decimals are required");p&&this.removeReferralKey(t,g,b.coinType,_.coinType,f);try{let{baseOracle:I,quoteOracle:A}=await this.#e(b,_,f);return f.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order_v2`,arguments:[f.object(this.sdk.sdkOptions.margin_utils.global_config_id),f.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof t=="string"?f.object(t):t,f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(g),f.object(r),f.object(s),f.object(I),f.object(A),f.pure.u8(i),f.pure.u64(o),f.pure.bool(c),f.pure.bool(u),f.pure.bool(d===void 0?!c:d),f.pure.u64(a),f.object(he)],typeArguments:[b.coinType,_.coinType]}),f}catch(I){throw new Error(`Failed to place market order: ${I instanceof Error?I.message:String(I)}`)}}async placeMarginLimitOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:p=Date.now()+31536e8,referralKey:f},g=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!a||!c)throw new Error("Price and quantity are required");let{id:b,baseCoin:_,quoteCoin:I}=n;if(_.decimals===void 0||I.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let A=BigInt(R(a).mul(10**(I.decimals-_.decimals+9)).toString()),M=BigInt(Vs(c,_.decimals));if(A<=0n||M<=0n)throw new Error("Price and quantity must be greater than zero");f&&this.removeReferralKey(t,b,_.coinType,I.coinType,g);let{baseOracle:C,quoteOracle:B}=await this.#e(_,I,g);return g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order_v2`,arguments:[g.object(this.sdk.sdkOptions.margin_utils.global_config_id),g.object(this.sdk.sdkOptions.margin_utils.versioned_id),g.object(t),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(b),g.object(r),g.object(s),g.object(C),g.object(B),g.pure.u8(i),g.pure.u8(o),g.pure.u64(A),g.pure.u64(M),g.pure.bool(u),g.pure.bool(d),g.pure.u64(p),g.object(he)],typeArguments:[_.coinType,I.coinType]}),g}catch(A){throw new Error(`Failed to place limit order: ${A instanceof Error?A.message:String(A)}`)}}modifyMarginOrder({marginManager:t,poolInfo:n,orderId:r,newQuantity:s},i=new J){if(!t||!n||!r||!s)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(n.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let o=BigInt(Vs(s,n.baseCoin.decimals));if(o<=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(t),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(n.id),i.pure.u128(r),i.pure.u64(o),i.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i}catch(o){throw new Error(`Failed to modify order: ${o instanceof Error?o.message:String(o)}`)}}cancelMarginOrder({marginManager:t,poolInfo:n,orderId:r},s=new J){if(!t||!n||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(t),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(n.id),s.pure.u128(r),s.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to cancel order: ${i instanceof Error?i.message:String(i)}`)}}cancelAllMarginOrders({marginManager:t,poolInfo:n},r=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.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(t),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(n.id),r.object(he)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),r}catch(s){throw new Error(`Failed to cancel all orders: ${s instanceof Error?s.message:String(s)}`)}}async placeReduceOnlyLimitOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:p=Date.now()+31536e8},f=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!a||!c)throw new Error("Price and quantity are required");let{baseCoin:g,quoteCoin:b}=n;if(g.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let _=BigInt(R(a).mul(10**(b.decimals-g.decimals+9)).toString()),I=BigInt(Vs(c,g.decimals));if(_<=0n||I<=0n)throw new Error("Price and quantity must be greater than zero");let{baseOracle:A,quoteOracle:M}=await this.#e(g,b,f);return f.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order_v2`,arguments:[f.object(this.sdk.sdkOptions.margin_utils.global_config_id),f.object(this.sdk.sdkOptions.margin_utils.versioned_id),f.object(t),f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(n.id),f.object(r),f.object(s),f.object(A),f.object(M),f.pure.u8(i),f.pure.u8(o),f.pure.u64(_),f.pure.u64(I),f.pure.bool(u),f.pure.bool(d),f.pure.u64(p),f.object(he)],typeArguments:[g.coinType,b.coinType]}),f}catch(_){throw new Error(`Failed to place reduce only limit order: ${_ instanceof Error?_.message:String(_)}`)}}async placeReduceOnlyMarketOrder({marginManager:t,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u},d=new J){if(!t||!n)throw new Error("Margin manager and pool info are required");if(!n.id||!n.baseCoin?.coinType||!n.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r||!s)throw new Error("Base and quote margin pool ids are required");if(!o||BigInt(Vs(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(Vs(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{baseCoin:p,quoteCoin:f}=n;if(p.decimals===void 0||f.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let{baseOracle:g,quoteOracle:b}=await this.#e(p,f,d);return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order_v2`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(n.id),d.object(r),d.object(s),d.object(g),d.object(b),d.pure.u8(i),d.pure.u64(o),d.pure.bool(c),d.pure.bool(u),d.pure.u64(a),d.object(he)],typeArguments:[p.coinType,f.coinType]}),d}catch(g){throw new Error(`Failed to place reduce only market order: ${g instanceof Error?g.message:String(g)}`)}}async getOpenOrder(t,n,r,s,i=!1,o=new J){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(t.address),i?r:o.object(r)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});let f=(await this._sdk.fullClient.simulateTransaction({transaction:o,include:{commandResults:!0,json:!0},checksEnabled:!1})).commandResults[i?1:0].returnValues[0].bcs;a=E.struct("VecSet",{constants:E.vector(E.U128)}).parse(new Uint8Array(f)).constants}if(a.length===0)return[];let c=a.map(p=>({pool:{pool_id:t.address,baseCoinType:t.baseCoin.coinType,quoteCoinType:t.quoteCoin.coinType},orderId:p})),u=await this.sdk.DeepbookUtils.getOrderInfoList(c,n)||[],d=[];return u.forEach(p=>{let f=this.sdk.DeepbookUtils.decodeOrderId(BigInt(p.order_id));d.push({...p,price:f.price,isBid:f.isBid,pool:t})}),d}async getAccountOpenOrders({poolInfo:t,marginManager:n}){try{let r=new J,s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(n)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.getOpenOrder(t,this.sdk.senderAddress,s,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(t,n){try{if(!t||!n||n.length===0)throw new Error("Account or pools are required");let r=[];for(let s=0;s<n.length;s++){let i=new J,o=n[s];if(o.margin_manager_id){let a=await i.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[i.object(o.margin_manager_id)],typeArguments:[o.baseCoin.coinType,o.quoteCoin.coinType]}),c=await this.getOpenOrder(o,this.sdk.senderAddress,a,void 0,!0,i);r.push(...c)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(t=new J,n){let r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(he)]});return n&&t.transferObjects([r],this.sdk.senderAddress),{tx:t,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(t){throw new Error(`Failed to get account supplyCap: ${t instanceof Error?t.message:String(t)}`)}}mintSupplierCapAndSupply({marginPool:t,supplyCoinType:n,amount:r}){let s=new J,{supplierCap:i}=this.mintSupplierCap(s,!1);return this.supply({marginPool:t,supplierCap:i,supplyCoinType:n,amount:r,tx:s}),s.transferObjects([i],this.sdk.senderAddress),s}supply({marginPool:t,supplierCap:n,supplyCoinType:r,amount:s,tx:i}){let o=i??new J;if(!n)throw new Error("Either supplierCap must be provided");let a=Gt.buildCoinWithBalance(BigInt(s),r,o);return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(t),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),a,o.pure.option("address","0x0"),o.object(he)]}),o}supplierWithdraw({marginPool:t,withdrawCoinType:n,amount:r,supplierCapId:s,hasSwap:i,withdrawAll:o,tx:a=new J}){let c=a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[n],arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(t),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(s),a.object.option({type:"u64",value:o?null:a.pure.u64(r)}),a.object(he)]});return i?c:(a.transferObjects([c],this.sdk.senderAddress),a)}withdrawReferralFees({marginPool:t}){let n=new J,r=n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[n.object(this._sdk.sdkOptions.margin_utils.versioned_id),n.object(t),n.object(this._sdk.sdkOptions.margin_utils.registry_id),n.object.option({type:"0x1",value:null}),n.object(he)],typeArguments:[this.deepCoin.coinType]});return n.transferObjects([r],this.sdk.senderAddress),n}async getUserSupplyAmount({marginPool:t,supplyCoin:n,supplierCapId:r}){let s=new J;s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[n.coinType],arguments:[s.object(t),s.object(r),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return this.#t(BigInt(E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),n.scalar,n.decimals)}async getDeepBookMarginRegistry(){let n=(await this.sdk.fullClient.getObject({objectId:this._sdk.sdkOptions.margin_utils.margin_registry_id,include:{json:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicField({parentId:n,name:{type:"u64",bcs:E.u64().serialize(1).toBytes()}}),s=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:s,margin_pool_table_id:i}}async getDeepBookPool(){let{data:t}=await this.sdk.fullClient.listDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),n=t.map(i=>i.objectId),r=await this.sdk.fullClient.batchGetObjects(n,{json:!0}),s=[];for(let i=0;i<r.length;i++){let o=r[i].json;s.push($b(o))}return s}async getDeepBookMarginPool(){let{data:t}=await this.sdk.fullClient.getDynamicFieldsByPage(this.sdk.sdkOptions.margin_utils.margin_pool_table_id),n=t.map(c=>c.fieldId),r=await this.sdk.fullClient.batchGetObjects(n,{json:!0}),s=[],i=[];for(let c=0;c<r.length;c++){let u=r[c].json;i.push(u.value),s.push({deposit_coin_type:u.name.name,id:u.id})}let o=await this.sdk.fullClient.batchGetObjects(i,{json:!0}),a=[];for(let c=0;c<o.length;c++){let u=o[c].json;a.push(qb(u,s[c]))}return a}async getBaseQuantityIn(t,n,r,s=.01){let i=new J;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_base_quantity_in`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[i.object(t.address),i.pure.u64(n),i.pure.bool(r),i.object(he)]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,this.sdk.senderAddress);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:c.toString(),quantityInLeft:R(a.toString()).mul(R(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(t,n,r,s=.01){let i=new J;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_in`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[i.object(t.address),i.pure.u64(n),i.pure.bool(r),i.object(he)]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,this.sdk.senderAddress);if(!o.commandResults||!o.commandResults[0]||!o.commandResults[0].returnValues||!o.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=E.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:a.toString(),quantityInLeft:R(c.toString()).mul(R(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(t,n,r){let s=new J;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[s.object(t.address),s.pure.u64(n),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs));return{base_amount:o.toString(),quote_amount:a.toString(),deep_fee_amount:c.toString()}}async getQuoteQuantityOutInput(t,n,r){let s=new J;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],arguments:[s.object(t.address),s.pure.u64(n),s.object(he)]});let i=await this.sdk.fullClient.sendSimulationTransaction(s,this.sdk.senderAddress);if(!i.commandResults||!i.commandResults[0]||!i.commandResults[0].returnValues||!i.commandResults[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=E.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs));return{base_amount:o.toString(),quote_amount:a.toString(),deep_fee_amount:c.toString()}}async getAccount(t,n,r=new J){let s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i=[n];for(let d=0;d<i.length;d++){let p=i[d];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(p.address),typeof s=="string"?r.object(s):s],typeArguments:[p.baseCoin.coinType,p.quoteCoin.coinType]})}let o=await this._sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,json:!0}}),a=o.Transaction??o.FailedTransaction;if(!a?.events?.length)return null;let c,u=[];return a.events.forEach((d,p)=>{c=d?.json;let f=c.account.open_orders.contents,g=c.account.owed_balances,b=c.account.settled_balances,_=c.account.unclaimed_rebates,I=c.account.taker_volume;u.push({balance_manager_id:s,open_orders:f,owed_balances:g,settled_balances:b,unclaimed_rebates:_,taker_volume:I,poolInfo:i[p]})}),u}async withdrawSettledAmounts({poolInfo:t,marginManager:n},r=new J){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(n),r.object(t.address)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}#t(t,n,r){if(n<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let s=BigInt(n),i=t/s,o=t%s;if(o===0n)return i.toString();let a=n.toString().length-1,d=o.toString().padStart(a,"0").slice(0,r).replace(/0+$/,"");return d?`${i}.${d}`:i.toString()}async getMarginPoolStateForInterest(t){if(!t)throw new Error("marginPoolId is required");let n=await this.sdk.fullClient.getObject({objectId:t,include:{json:!0}});if(!n?.object?.json)throw new Error(`Failed to fetch margin pool: ${t}`);let r=n.object.json,s=r.state,i=r.config,o=i.interest_config,a=i.margin_pool_config;return{poolState:{total_supply:BigInt(s.total_supply),total_borrow:BigInt(s.total_borrow),supply_shares:BigInt(s.supply_shares),borrow_shares:BigInt(s.borrow_shares),last_update_timestamp:BigInt(s.last_update_timestamp)},interestConfig:{base_rate:BigInt(o.base_rate),base_slope:BigInt(o.base_slope),optimal_utilization:BigInt(o.optimal_utilization),excess_slope:BigInt(o.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(a.protocol_spread),max_utilization_rate:BigInt(a.max_utilization_rate),min_borrow:BigInt(a.min_borrow),supply_cap:BigInt(a.supply_cap)}}}async getMarginPoolStateForInterestList(t){if(!t||t.length===0)throw new Error("marginPoolIds is required");let n=await this.sdk.fullClient.batchGetObjects(t,{json:!0}),r=[];return t.forEach((i,o)=>{let a=n[o];if(a){let c=a.json.state,u=a.json.config,d=u.interest_config,p=u.margin_pool_config;r.push({poolState:{total_supply:BigInt(c.total_supply),total_borrow:BigInt(c.total_borrow),supply_shares:BigInt(c.supply_shares),borrow_shares:BigInt(c.borrow_shares),last_update_timestamp:BigInt(c.last_update_timestamp)},interestConfig:{base_rate:BigInt(d.base_rate),base_slope:BigInt(d.base_slope),optimal_utilization:BigInt(d.optimal_utilization),excess_slope:BigInt(d.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(p.protocol_spread),max_utilization_rate:BigInt(p.max_utilization_rate),min_borrow:BigInt(p.min_borrow),supply_cap:BigInt(p.supply_cap)}})}}),{poolStateObj:Object.fromEntries(t.map((i,o)=>[i,r[o]])),poolStateList:r}}async getChainTimestamp(){let{response:t}=await this.sdk.fullClient.ledgerService.getServiceInfo({}),n=t.timestamp;if(!n)throw new Error("No timestamp in service info");return BigInt(n.seconds)*1000n+BigInt(n.nanos)/1000000n}async batchGetBorrowedShares({account:t,marginManagerList:n}){let r=new J;return n.forEach(i=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(i.marginManagerId)],typeArguments:[i.baseCoinType,i.quoteCoinType]})}),(await this.sdk.fullClient.sendSimulationTransaction(r,t)).commandResults.map((i,o)=>{let a=E.U64.parse(new Uint8Array(i.returnValues[0].bcs)),c=E.U64.parse(new Uint8Array(i.returnValues[1].bcs));return{marginManagerId:n[o].marginManagerId,baseBorrowedShare:a,quoteBorrowedShare:c}})}async betchGetOpenOrders({account:t,marginManagerList:n},r=new J,s=!1){n.forEach(g=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(g.poolId),r.object(b)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let i=await this.sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,commandResults:!0,json:!0}}),o=i.Transaction?.events.map((g,b)=>({marginManagerId:n[b].marginManagerId,...g?.json?.account?.settled_balances||{}})),a=i.commandResults.filter((g,b)=>(b-1)%4===0),c=E.struct("VecSet",{constants:E.vector(E.U128)}),u=[];a.forEach((g,b)=>{let _=c.parse(g.returnValues[0].bcs).constants;_.length>0&&_.forEach(I=>{u.push({pool:{pool_id:n[b].poolId,baseCoinType:n[b].baseCoinType,quoteCoinType:n[b].quoteCoinType},marginManagerId:n[b].marginManagerId,orderId:I})})});let d=i.commandResults.filter((g,b)=>(b-3)%4===0),p=[];d.forEach((g,b)=>{p.push({marginManagerId:n[b].marginManagerId,base:E.U64.parse(g.returnValues[0].bcs),quote:E.U64.parse(g.returnValues[1].bcs),deep:E.U64.parse(g.returnValues[2].bcs)})});let f=[];return u.forEach((g,b)=>{let _=this.sdk.DeepbookUtils.decodeOrderId(BigInt(g.orderId));f.push({...g,price:_.price.toString(),isBid:_.isBid})}),{openOrders:f,settledBalances:o,lockedBalances:p}}async getSingleMarginManagerOpenOrders({account:t,marginManagerId:n,poolId:r,baseCoinType:s,quoteCoinType:i,baseMarginPool:o,quoteMarginPool:a}){let c=new J,u=c.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[c.object(n)],typeArguments:[s,i]});c.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[c.object(r),u],typeArguments:[s,i]});let d=E.struct("VecSet",{constants:E.vector(E.U128)}),f=(await this.sdk.fullClient.simulateTransaction({transaction:c,checksEnabled:!1,include:{commandResults:!0,json:!0}})).commandResults.find(C=>C?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),g=d.parse(new Uint8Array(f.returnValues[0].bcs)).constants,b=[];g.forEach(C=>{b.push({pool:{pool_id:r,baseCoinType:s,quoteCoinType:i},marginManagerId:n,orderId:C})});let _=b?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(b,t)||[]:[],I=[];b.forEach((C,B)=>{let L=this.sdk.DeepbookUtils.decodeOrderId(BigInt(C.orderId)),j=_.find(q=>q.order_id===C.orderId)||{};I.push({...C,...j,price:L.price.toString(),isBid:L.isBid})});let A={marginManagerId:n,base:"0",quote:"0",deep:"0"};if(_?.length>0){let C=new J,B=C.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[C.object(n)],typeArguments:[s,i]});C.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[C.object(r),B],typeArguments:[s,i]});let j=(await this.sdk.fullClient.simulateTransaction({transaction:C,checksEnabled:!1,include:{commandResults:!0,json:!0}})).commandResults.find(q=>q?.returnValues?.length===3);A={...A,base:E.U64.parse(new Uint8Array(j.returnValues[0].bcs)),quote:E.U64.parse(new Uint8Array(j.returnValues[1].bcs)),deep:E.U64.parse(new Uint8Array(j.returnValues[2].bcs))}}let M={base:"0",quote:"0",deep:"0"};try{let C=new J,B=C.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[C.object(n)],typeArguments:[s,i]});C.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[C.object(r),B],typeArguments:[s,i]});let L=await this.sdk.fullClient.simulateTransaction({transaction:C,checksEnabled:!1,include:{events:!0,json:!0}});M={marginManagerId:n,...M,...L?.Transaction?.events?.json?.account?.settled_balances||{}}}catch(C){console.log("\u{1F680} ~ MarginUtilsModule ~ getSingleMarginManagerPosRelevantData ~ error:",C)}return{openOrders:I,settledBalances:[M],lockedBalances:[A]}}async getAllPosRelevantData({account:t,marginManagerList:n}){try{let{openOrders:r,settledBalances:s,lockedBalances:i}=await this.betchGetOpenOrders({account:t,marginManagerList:n}),o=await this.batchGetBorrowedShares({account:t,marginManagerList:n}),a=new J,c=0,u=[];n.forEach(f=>{a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"base_balance",marginManagerId:f.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"quote_balance",marginManagerId:f.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[a.object(f.marginManagerId)],typeArguments:[f.baseCoinType,f.quoteCoinType]}),u[c]={type:"deep_balance",marginManagerId:f.marginManagerId},c++;let g=o?.find(b=>b.marginManagerId===f.marginManagerId);if(g&&(Number(g.baseBorrowedShare)>0||Number(g.quoteBorrowedShare)>0)){let b=g.baseBorrowedShare,_=g.quoteBorrowedShare,I=!!R(b).gt(R(_)),A=I?f.baseMarginPool:f.quoteMarginPool,M=I?b:_;a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[a.object(A),a.pure.u64(BigInt(M)),a.object.clock()],typeArguments:[I?f?.baseCoinType:f?.quoteCoinType]}),u[c]={type:I?"borrow_base_amount":"borrow_quote_amount",marginManagerId:f.marginManagerId},c++}});let d=await this.sdk.fullClient.simulateTransaction({transaction:a,checksEnabled:!1,include:{commandResults:!0,events:!0,json:!0}}),p=Object.fromEntries(n.map(f=>[f.marginManagerId,{...f,quote_balance:"0",base_balance:"0",deep_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return d?.commandResults?.forEach((f,g)=>{let b=u[g],_=E.U64.parse(new Uint8Array(f.returnValues[0].bcs));p[b.marginManagerId]={...p[b.marginManagerId],[b.type]:_}}),r.forEach(f=>{p[f.marginManagerId].open_orders.push(f)}),s.forEach(f=>{p[f.marginManagerId].settled_balances=f}),i.forEach(f=>{p[f.marginManagerId].locked_balances=f}),Object.values(p).forEach(f=>{f.locked_balances&&f.settled_balances&&(f.locked_balances={...f.locked_balances,base:R(f.locked_balances.base||"0").minus(R(f.settled_balances.base||"0")).toString(),quote:R(f.locked_balances.quote||"0").minus(R(f.settled_balances.quote||"0")).toString(),deep:R(f.locked_balances.deep||"0").minus(R(f.settled_balances.deep||"0")).toString()})}),p}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i,margin_registry_id:o}=r,{margin_manager_id:a,pool_id:c,base_coin:u,quote_coin:d,conditional_order_id:p,pending_order:f,is_trigger_below_price:g,trigger_price:b}=t,_=await this.pythPrice.updatePythPriceIDs([u.feed,d.feed],n),I=_.get(u.feed),A=_.get(d.feed);if(!I||!A)throw new Error("Failed to get price feed object IDs");let M=n.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[n.pure.bool(g),n.pure.u64(b)]}),C=this.newPendingOrder(f,n);n.moveCall({target:`${r.published_at}::margin_utils::add_conditional_order`,arguments:[n.object(s),n.object(i),n.object(a),n.object(c),n.object(I),n.object(A),n.object(o),typeof p=="string"?n.pure.u64(BigInt(p)):p,M,C,n.object(Cu)],typeArguments:[u.coinType,d.coinType]})}newPendingOrder(t,n){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in t){let{client_order_id:s,order_type:i,self_matching_option:o,price:a,quantity:c,is_bid:u,pay_with_deep:d,expire_timestamp:p}=t;return n.moveCall({target:`${r.published_at}::margin_utils::new_pending_limit_order`,arguments:[n.pure.u64(s),n.pure.u8(i),n.pure.u8(o),n.pure.u64(a),n.pure.u64(c),n.pure.bool(u),n.pure.bool(d),n.pure.u64(p)]})}else{let{client_order_id:s,self_matching_option:i,quantity:o,is_bid:a,pay_with_deep:c}=t;return n.moveCall({target:`${r.published_at}::margin_utils::new_pending_market_order`,arguments:[n.pure.u64(s),n.pure.u8(i),n.pure.u64(o),n.pure.bool(a),n.pure.bool(c)]})}}cancelAllConditionalOrders(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i}=r,{margin_manager_id:o,base_coin_type:a,quote_coin_type:c}=t;n.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[n.object(s),n.object(i),n.object(o),n.object(Cu)],typeArguments:[a,c]})}cancelConditionalOrders(t,n){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:s,versioned_id:i}=r,{margin_manager_id:o,base_coin_type:a,quote_coin_type:c,conditional_order_id:u}=t;n.moveCall({target:`${r.published_at}::margin_utils::cancel_conditional_order`,arguments:[n.object(s),n.object(i),n.object(o),n.pure.u64(u),n.object(Cu)],typeArguments:[a,c]})}async getConditionalOrders(t,n){let{deepbook:r}=this.sdk.sdkOptions;t.forEach(u=>{let{margin_manager_id:d,base_coin_type:p,quote_coin_type:f,conditional_order_ids:g}=u;g.forEach(b=>{n.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[n.object(d),n.pure.u64(b)],typeArguments:[p,f]})})});let s=await this.sdk.fullClient.sendSimulationTransaction(n,X("0x0"));if(!s?.commandResults)return[];let i=E.struct("Condition",{trigger_below_price:E.bool(),trigger_price:E.u64()}),o=E.struct("PendingOrder",{is_limit_order:E.bool(),client_order_id:E.u64(),order_type:E.option(E.u8()),self_matching_option:E.u8(),price:E.option(E.u64()),quantity:E.u64(),is_bid:E.bool(),pay_with_deep:E.bool(),expire_timestamp:E.option(E.u64())}),a=E.struct("ConditionalOrder",{conditional_order_id:E.u64(),condition:i,pending_order:o}),c=u=>{if(u.length===0||u.length===1&&u[0]===0)return null;try{return a.parse(u)}catch{if(u[0]===1&&u.length>1)try{return a.parse(u.subarray(1))}catch{return null}return null}};return s.commandResults.map(u=>{if(!u?.returnValues?.[0]?.bcs)return null;try{let d=u.returnValues[0].bcs,p=c(d);if(!p)return null;let f=this.normalizeConditionalOrder(p);return t.forEach(g=>{g.conditional_order_ids.find(_=>_===f.conditional_order_id)&&(f.margin_manager_id=g.margin_manager_id,f.base_coin_type=g.base_coin_type,f.quote_coin_type=g.quote_coin_type)}),f}catch{return null}})}async getConditionalOrderIds(t,n){n=n||new J;let{deepbook:r}=this.sdk.sdkOptions,s={};return t.forEach(o=>{let{margin_manager_id:a,base_coin_type:c,quote_coin_type:u}=o;n.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order_ids`,arguments:[n.object(a)],typeArguments:[c,u]})}),(await this.sdk.fullClient.sendSimulationTransaction(n,X("0x0"))).commandResults.forEach((o,a)=>{if(o?.returnValues?.[0]?.bcs){let c=new Uint8Array(o.returnValues[0].bcs),u=E.vector(E.u64()).parse(c),d={margin_manager_id:t[a].margin_manager_id,base_coin_type:t[a].base_coin_type,quote_coin_type:t[a].quote_coin_type,conditional_order_ids:u.map(p=>p.toString())};s[t[a].margin_manager_id]=d}}),s}normalizeConditionalOrder(t){let n=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",conditional_order_id:n(t.conditional_order_id),condition:{trigger_below_price:t.condition.trigger_below_price,trigger_price:n(t.condition.trigger_price)},pending_order:{is_limit_order:t.pending_order.is_limit_order,client_order_id:n(t.pending_order.client_order_id),order_type:t.pending_order.order_type,self_matching_option:t.pending_order.self_matching_option,price:t.pending_order.price,quantity:n(t.pending_order.quantity),is_bid:t.pending_order.is_bid,pay_with_deep:t.pending_order.pay_with_deep,expire_timestamp:t.pending_order.expire_timestamp}}}async getPoolsPriceBounds(t){let n=new J;for(let o=0;o<t.length;o++)n.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_registry::get_price_bounds`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),n.pure.id(t[o].poolId),n.object(he)]});let r=await this.sdk.fullClient.simulateTransaction({transaction:n,checksEnabled:!1,include:{commandResults:!0,json:!0}}),s=[];for(let o=0;o<t.length;o++){let a=9-t[o].baseDecimals+t[o].quoteDecimals,c=E.U64.parse(r?.commandResults?.[o]?.returnValues?.[0]?.bcs),u=E.U64.parse(r?.commandResults?.[o]?.returnValues?.[1]?.bcs);s.push({pool_id:t[o].poolId,lower_bound:R(c).div(10**a).toString(),upper_bound:R(u).div(10**a).toString()})}let i=new Map;return s.forEach(o=>{i.set(o.pool_id,o)}),{priceBounds:s,priceBoundsMap:i}}};var Qx="https://graphql.mainnet.sui.io/graphql",eC="https://graphql.testnet.sui.io/graphql",Ru=class{_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=af(new Ko({baseUrl:t.fullRpcUrl,network:t.network==="testnet"?"testnet":"mainnet"}),new Dp({network:t.network,url:t.network==="testnet"?eC:Qx}),t.network==="testnet"?"testnet":"mainnet",new wp({url:t.fullRpcUrl,network:t.network})),this._deepbookUtils=new xu(this),this._marginUtils=new Nu(this),this._pythPrice=new wo(this),mf(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(t){this._senderAddress=t}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}};var tC=(s=>(s[s.NO_RESTRICTION=0]="NO_RESTRICTION",s[s.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",s[s.FILL_OR_KILL=2]="FILL_OR_KILL",s[s.POST_ONLY=3]="POST_ONLY",s))(tC||{}),nC=(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))(nC||{});var oz=Ru;export{Cu as CLOCK_ADDRESS,Au as CachedContent,Ru as CetusClmmSDK,Xq as ClmmExpectSwapModule,Kq as ClmmFetcherModule,Wq as ClmmIntegratePoolModule,Hq as ClmmIntegratePoolV2Module,Jq as ClmmIntegrateRouterModule,Zq as ClmmIntegrateRouterWithPartnerModule,Yq as ClmmIntegrateUtilsModule,Gt as CoinAssist,Qq as CoinInfoAddress,eG as CoinStoreAddress,vf as DEEP_SCALAR,sq as DEFAULT_GAS_BUDGET_FOR_MERGE,rq as DEFAULT_GAS_BUDGET_FOR_SPLIT,aq as DEFAULT_GAS_BUDGET_FOR_STAKE,iq as DEFAULT_GAS_BUDGET_FOR_TRANSFER,oq as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,uq as DEFAULT_NFT_TRANSFER_GAS_FEE,nG as DeepbookClobV2Moudle,tG as DeepbookCustodianV2Moudle,rG as DeepbookEndpointsV2Moudle,xu as DeepbookUtilsModule,iG as ERROR_HANDLING_RPC_LIST,gr as FLOAT_SCALAR,jr as FLOAT_SCALING,cq as GAS_SYMBOL,hf as GAS_TYPE_ARG,xb as GAS_TYPE_ARG_LONG,Nu as MarginUtilsModule,J$ as NORMALIZED_SUI_COIN_TYPE,tC as OrderType,lq as SUI_SYSTEM_STATE_OBJECT_ID,nC as SelfMatchingOption,Hx as YEAR_MS,Eb as addHexPrefix,vq as asIntN,bq as asUintN,P$ as bufferToHex,Cb as cacheTime1min,_o as cacheTime24h,Nb as cacheTime5min,pG as calc100PercentRepay,Kx as calcDebtDetail,Zx as calcInterestRate,Jx as calcUtilizationRate,lG as calculateRiskRatio,U$ as checkAddress,Ib as composeType,R as d,gf as decimalsMultiplier,oz as default,W$ as extractAddressFromType,Ls as extractStructTagFromType,H$ as fixCoinType,xi as fixDown,Ux as fixSuiObjectId,Ci as fromDecimalsAmount,sG as getDefaultSuiInputType,bf as getFutureTime,$x as getMoveObject,Px as getObjectDeletedResponse,Pb as getObjectFields,Ub as getObjectId,Lx as getObjectNotExistsResponse,Vx as getObjectReference,Db as getSuiObjectData,L$ as hexToNumber,V$ as hexToString,z$ as isSortedSymbols,Oq as isSuiObjectResponse,yf as maxDecimal,Gb as mulRoundUp,ff as normalizeCoinType,mf as patchFixSuiObjectId,Tq as printTransaction,pf as removeHexPrefix,_q as secretKeyToEd25519Keypair,wq as secretKeyToSecp256k1Keypair,D$ as shortAddress,Nx as shortString,Rb as sleepTime,Rx as toBuffer,Vs as toDecimalsAmount,Mx as utf8to16,qb as wrapDeepBookMarginPoolInfo,$b as wrapDeepBookPoolInfo};
|
|
1039
1039
|
/*! Bundled license information:
|
|
1040
1040
|
|
|
1041
1041
|
@scure/base/index.js:
|