@cetusprotocol/deepbook-utils 1.5.5 → 1.5.6

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
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 T3=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];var iW=jl("mainnet"),oW=jl("testnet");var aW=A.struct("Table<ID, bool>",{id:A.Address,size:A.u64()}),k3=A.struct("TypeName",{name:A.string()}),cW=A.struct("OptionU64",{is_none:A.bool(),v:A.u64()}),E3=A.struct("UID",{id:A.Address}),uW=A.struct("TableSuiRaw",{id:E3,size:A.u64()});var S3=class{constructor(t,e,n,r){this._cache={},this._env="mainnet",this._client=t,this._env=n||"mainnet",this._graphQLClient=e,this._jsonRpcClient=r}async fetchCoinMetadata(t){let e=`coin_metadata_${t}`,n=this.getCache(e);if(n)return n;let r=await this._client.getCoinMetadata({coinType:t});return this.updateCache(e,r.coinMetadata),r.coinMetadata}async fetchCoinMetadataId(t){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let e=`coin_metadata_id_${t}`,n=this.getCache(e);if(n)return n;let r=(await this._graphQLClient.query({query:y3,variables:{coinType:`0x2::coin::CoinMetadata<${t}>`}})).data?.objects?.nodes?.[0]?.address??null;return r&&this.updateCache(e,r),r}async getSuiTransactionResponse(t){try{return await this._client.getTransaction({digest:t,include:{effects:!0,events:!0,balanceChanges:!0,transaction:!0,objectTypes:!0}})}catch(e){throw console.log("getSuiTransactionResponse error",e),e}}async getTransactionByGraphQL(t){try{return await this._graphQLClient.query({query:b3,variables:{digest:t}})}catch(e){throw console.log("getTransactionByGraphQL error",e),e}}async queryEventsByGraphQL(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:v3,variables:{type:t,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(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");if(!(t.sentAddress!=null||t.affectedAddress!=null||t.affectedObject!=null||t.function!=null))throw new Error("At least one of sentAddress, affectedAddress, affectedObject, function is required");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0,a={};t.sentAddress&&(a.sentAddress=Q(t.sentAddress)),t.affectedAddress&&(a.affectedAddress=Q(t.affectedAddress)),t.affectedObject&&(a.affectedObject=Q(t.affectedObject)),t.function&&(a.function=t.function);do{let c=(await this._graphQLClient.query({query:_3,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(t,e="all"){let n=[],r=!0,s=e==="all",i=s?null:e.cursor;do{let o=await this._jsonRpcClient.queryEvents({query:t,cursor:i,limit:s?null:e.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(t,e,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:t,type:e,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 T3)try{let c=Em(new Ja({baseUrl:a,network:o}),this._graphQLClient,this._env);return await r(c._client)}catch(c){i=c;continue}throw i}}async getAllDynamicFields(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:w3,variables:{id:Q(t),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(t,e="all"){let n=[],r=!0,s=e==="all",i=s?null:e.cursor;do{let o=await this._client.listDynamicFields({parentId:t,cursor:i??void 0,limit:s?1e3:e.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(t,e,n,r,s){let i=e.map(o=>g3(t,o,n,r));return i.length===0?[]:this.batchGetObjects(i,s)}async batchGetObjects(t,e,n=1e3){let r=[];try{for(let s=0;s<Math.ceil(t.length/n);s++){let i=t.slice(s*n,n*(s+1)),o=await this._client.getObjects({objectIds:i,include:e});r=[...r,...o.objects]}}catch(s){console.log(s)}return r}async calculationTxGas(t){let e=t.getData?.()?.sender??t.blockData?.sender;if(e==null)throw Error("sdk sender is empty");t.setSender(e);let n=await this._client.simulateTransaction({transaction:t,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(t,e){try{return await this._client.signAndExecuteTransaction({transaction:e,signer:t,include:{effects:!0,events:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(t,e,n=!0){try{return t.setSender(e),await this._client.simulateTransaction({transaction:t,include:{events:!0,balanceChanges:!0,effects:!0,objectChanges:!0,commandResults:!0},checksEnabled:n})}catch(r){throw console.log("simulateTransaction error",r),r}}async executeTx(t,e,n){try{if(n){let r=typeof t=="string"?Q(t):Q(t.getPublicKey().toSuiAddress());return await this.sendSimulationTransaction(e,r)}else{if(typeof t=="string")throw new Error("Cannot send transaction with string address - keypair required for signing");return await this.sendTransaction(t,e)}}catch(r){return r}}async getOwnerCoinAssets(t,e){let n=[],r=null;if(e)for(;;){let s=await this._client.listCoins({owner:t,coinType:e,cursor:r??void 0});for(let i of s.objects)BigInt(i.balance)>0&&n.push({coin_type:go(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:t,cursor:s??void 0,include:{json:!0}});if(i.objects.forEach(o=>{let a=go(o.type);o.type.includes('"0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin')&&BigInt(o.balance)>0&&n.push({coin_type:Tm(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(t,e){if(e)return[(await this._client.getBalance({owner:t,coinType:e})).balance];let n=[],r=null;do{let s=await this._client.listBalances({owner:t,cursor:r??void 0});if(n.push(...s.balances),r=s.cursor??null,!s.hasNextPage)break}while(!0);return n}updateCache(t,e,n=864e5){let r=this._cache[t];r?(r.overdue_time=S_(n),r.value=e):r=new bC(e,S_(n)),this._cache[t]=r}getCache(t,e=!1){let n=this._cache[t],r=n?.isValid();if(!e&&r)return n.value;r||delete this._cache[t]}};function Em(t,e,n,r){let s=new S3(t,e,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 x3=Uc(Pc(),1);var pW=new x3.default(1e6),O3=(t=>(t[t.BelowRange=0]="BelowRange",t[t.InRange=1]="InRange",t[t.AboveRange=2]="AboveRange",t))(O3||{}),ym=10n,I3={pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",hermes_service_urls:[]},A3={"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 C3(t,e){if(!ym)throw new Error("oraclePriceMultiplierDecimal is required");if(t===0n)throw new Error("Invalid oracle price");if(e<0n){let n=10n**(ym- -e);return t*n}return t/10n**(e+ym)}var N_=16*1024,z_=class{constructor(t,e=I3){this.hasChangeConnection=!1,this.pythConfigs=e,this.fullClient=t;let n=[...e.hermes_service_urls];n.includes("https://hermes.pyth.network")||n.push("https://hermes.pyth.network"),this.hermesClients=n.map(r=>new Zl(r,{timeout:3e3}))}async getFeedInfoList(t){let e=t.map(n=>this.getFeedInfo(n,!1));return await Promise.all(e)}priceCheck(t,e=60){let n=Math.floor(Date.now()/1e3);if(!(Math.abs(n-t.last_update_time)>e))return t}async getPackageId(t){let e=(await this.fullClient.getObject({objectId:t,include:{json:!0}}))?.object?.json;if(e?.upgrade_cap?.package)return e.upgrade_cap.package;throw new Error("upgrade_cap not found")}async getWormholePackageId(){let{wormhole_state_id:t}=this.pythConfigs,e=`getWormholePackageId_${t}`,n=this.fullClient.getCache(e);if(n)return n;let r=await this.getPackageId(this.pythConfigs.wormhole_state_id);return this.fullClient.updateCache(e,r),r}async getLatestPrice(t,e=!1){let n={},r=[];if(e?t.forEach(i=>{let o=this.fullClient.getCache(`getLatestPrice_${i}`);o&&this.priceCheck(o,60)?n[i]=o:r.push(i)}):r=[...t],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=Yl(a).mul(Yl(10).pow(Yl(c))).toString(),f=s[o],p={coin_type:f.coin_type,price:d,coin_decimals:f.coin_decimals,oracle_price:0n,last_update_time:u};p.oracle_price=C3(BigInt(a),BigInt(c)),n[r[o]]=p,this.fullClient.updateCache(`getLatestPrice_${p.coin_type}`,p)}}),n}async getPriceFeedsUpdateData(t){let e=null;for(let n of this.hermesClients)try{return(await n.getLatestPriceUpdates(t,{encoding:"hex"})).binary.data.map(r=>Buffer.from(r,"hex"))}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getPriceFeedsUpdateData ~ e:",r),e=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getPriceFeedsUpdateData Detailed error: ${e?.message}`)}async getLatestPriceFeeds(t){let e=null;for(let n of this.hermesClients)try{return await n.getLatestPriceUpdates(t,{parsed:!0})}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getLatestPriceFeeds ~ error:",r),e=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getLatestPriceFeeds Detailed error: ${e?.message}`)}extractVaaBytesFromAccumulatorMessage(t){let e=7+t.readUint8(6)+1,n=t.readUint16BE(e),r=e+2;return t.subarray(r,r+n)}async verifyVaas(t,e){let n=await this.getWormholePackageId(),r=[];for(let s of t){let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.pythConfigs.wormhole_state_id),e.pure(A.vector(A.u8()).serialize(Array.from(s),{maxSize:N_}).toBytes()),e.object(he)]});r.push(i)}return r}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=null,e=!0;for(;e;){let n=await this.fullClient.listDynamicFields({parentId:this.pythConfigs.pyth_state_id,cursor:t});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}}e=n.hasNextPage,t=n.cursor}}if(this.priceTableInfo===void 0)throw new Error(" getPriceTableInfo Price table not found");return this.priceTableInfo}async getPriceFeedObjectId(t){let e=t.replace("0x",""),n=`getPriceFeedObjectId_${e}`,r=this.fullClient.getCache(n);if(r)return r;let{id:s,fieldType:i}=await this.getPriceTableInfo(),o=A.struct("PriceIdentifier",{bytes:A.vector(A.u8())}).serialize({bytes:Array.from(Buffer.from(e,"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(t,e,n){if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([r],t),[i]=t.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythConfigs.pyth_state_id),t.pure(A.vector(A.u8()).serialize(Array.from(e[0]),{maxSize:N_}).toBytes()),s[0],t.object(he)]});return i}async buildUpdatePythPricePayload(t,e,n){let{pyth_state_id:r,pyth_published_at:s,pyth_package_id:i}=this.pythConfigs,o=(await this.getFeedInfoList(t)).map(d=>d.price_feed_id);if(t.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(e,a,s),u=0;for(let d of o){let f=await this.getPriceFeedObjectId(d);if(!f)throw new Error(`Price feed ${d} not found, please create it first`);c=n({tx:e,coinType:t[u],priceUpdatesHotPotato:c,priceInfoObjectId:f}),u+=1}return e.moveCall({target:`${s}::hot_potato_vector::destroy`,arguments:[c],typeArguments:[`${i}::price_info::PriceInfo`]}),e}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=(await this.fullClient.getObject({objectId:this.pythConfigs.pyth_state_id,include:{json:!0}}))?.object?.json;if(!t)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=Number(t.base_update_fee)}return this.baseUpdateFee}async updatePriceFeeds(t,e,n){let r=this.pythConfigs.pyth_package_id,s=await this.verifyVaasAndGetHotPotato(t,e,r),i=await this.getBaseUpdateFee(),o=t.splitCoins(t.gas,n.map(()=>t.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]=t.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[t.object(this.pythConfigs.pyth_state_id),s,t.object(d),o[c],t.object(he)]}),c++}return t.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[s],typeArguments:[`${r}::price_info::PriceInfo`]}),a}async buildUpdatePythPricePayloadV2(t,e,n){if(t.length===0)return e;let r=(await this.getFeedInfoList(t)).map(a=>a.price_feed_id);if(t.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(e,s,r),o=0;for(let a of i)n({tx:e,coinType:t[o],priceUpdatesHotPotato:{},priceInfoObjectId:a}),o+=1;return e}getFeedInfoByJson(t){let e=Tm(t,!1);return A3[e]}async getFeedInfo(t,e){let n=`getFeedInfo_${t}`,r=this.fullClient.getCache(n,e);if(r)return r;let s=this.getFeedInfoByJson(t);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:k3.serialize({name:Tm(t,!0)}).toBytes()}}),o=A.struct("OracleInfo",{price_feed_id:A.vector(A.U8),price_info_object_id:A.Address,last_update_time:A.u64(),coin_decimals:A.u8()}).parse(i.dynamicField.value.bcs),a={coin_type:t,price_feed_id:m3(o.price_feed_id),coin_decimals:o.coin_decimals};return console.log("\u{1F680} ~ PythPriceModule ~ getFeedInfo ~ info:",a),this.fullClient.updateCache(n,a),a}},ma=Uc(Pc(),1),mW=new ma.default(0),W_=new ma.default(1),Sm=new ma.default(2),gW=Sm.pow(new ma.default(128)),yW=Sm.pow(new ma.default(64)).sub(W_),bW=Sm.pow(new ma.default(128)).sub(W_);td.config({precision:64,rounding:td.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var wW=Uc(Pc(),1),vW=Uc(Pc(),1);var _W=Uc(Pc(),1);import{DeepBookClient as H3}from"@mysten/deepbook-v3";import{Base64 as z3}from"js-base64";var N3={REQUEST_PARAMS:"requestParams",METHOD_NAME:"methodName"},xm=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 xm&&n.code===r}},Vc=xm;An(Vc,"DETAILS_KEYS",N3);var Om=class extends Vc{constructor(e,n,r){super(e,n||"UnknownError",r)}static isCommonErrorCode(e,n){return this.isErrorCode(e,n)}};var Im=(t,e,n)=>{throw new Om(e,t,n)};var R3=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function Z_(t){return t.startsWith("0x")?t:`0x${t}`}function Am(t){return t.startsWith("0x")?`${t.slice(2)}`:t}function B3(t,e=4,n=4){let r=Math.max(e,1),s=Math.max(n,1);return`${t.slice(0,r+2)} ... ${t.slice(-s)}`}function RW(t,e=4,n=4){return B3(Z_(t),e,n)}function BW(t,e={leadingZero:!0}){if(typeof t!="string")return!1;let n=t;if(e.leadingZero){if(!t.startsWith("0x"))return!1;n=n.substring(2)}return R3.test(n)}function M3(t){if(!Buffer.isBuffer(t))if(Array.isArray(t))t=Buffer.from(t);else if(typeof t=="string")exports.isHexString(t)?t=Buffer.from(exports.padToEven(exports.stripHexPrefix(t)),"hex"):t=Buffer.from(t);else if(typeof t=="number")t=exports.intToBuffer(t);else if(t==null)t=Buffer.allocUnsafe(0);else if(t.toArray)t=Buffer.from(t.toArray());else throw new Error("invalid type");return t}function MW(t){return Z_(M3(t).toString("hex"))}function jW(t){let e=new ArrayBuffer(4),n=new DataView(e);for(let s=0;s<t.length;s++)n.setUint8(s,t.charCodeAt(s));return n.getUint32(0,!0)}function j3(t){let e,n,r,s,i;e="";let o=t.length;for(n=0;n<o;)switch(r=t.charCodeAt(n++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=t.charAt(n-1);break;case 12:case 13:s=t.charCodeAt(n++),e+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=t.charCodeAt(n++),i=t.charCodeAt(n++),e+=String.fromCharCode((r&15)<<12|(s&63)<<6|(i&63)<<0);break}return e}function DW(t){let e="",n=Am(t),r=n.length/2;for(let s=0;s<r;s++)e+=String.fromCharCode(Number.parseInt(n.substr(s*2,2),16));return j3(e)}var D3=0,Y_=1,U3=2;function J_(t,e){return t===e?D3:t<e?Y_:U3}function P3(t,e){let n=0,r=t.length<=e.length?t.length:e.length,s=J_(t.length,e.length);for(;n<r;){let i=J_(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,i!==0)return i}return s}function FW(t,e){return P3(t,e)===Y_}function K_(t,...e){let n=Array.isArray(e[e.length-1])?e.pop():[],s=[t,...e].filter(Boolean).join("::");return n&&n.length&&(s+=`<${n.join(", ")}>`),s}function qW(t){return t.split("::")[0]}function gi(t){try{let e=t.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let c={...gi(e),type_arguments:r.map(u=>gi(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>Wt.isSuiCoin(u)?u:gi(u).source_address),c.source_address=K_(c.full_address,c.type_arguments),c}let s=e.split("::"),o={full_address:e,address:e===Rm||e===X_?"0x2":$t(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=K_(o.full_address,o.type_arguments),o}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function Cm(t){return gi(t).source_address}function L3(t){return t.toLowerCase().startsWith("0x")?$t(t):t}var $W=(t,e=!0)=>{let n=t.split("::"),r=n.shift(),s=$t(r);return e&&(s=Am(s)),`${s}::${n.join("::")}`};function Nm(t){for(let e in t){let n=typeof t[e];if(n==="object")Nm(t[e]);else if(n==="string"){let r=t[e];t[e]=L3(r)}}}var GW=ye(Qn);import id from"decimal.js";function M(t){return id.isDecimal(t)?t:new id(t===void 0?0:t)}function Bm(t){return M(10).pow(M(t).abs())}var yo=(t,e)=>{try{return M(t).toDP(e,id.ROUND_DOWN).toString()}catch{return t}},Mm=(t,e)=>id.max(M(t),M(e));var QW=1e3,eZ=500,tZ=100,nZ=100,rZ=1e3,Rm="0x2::sui::SUI",X_="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",sZ="SUI",iZ=450,oZ="0x0000000000000000000000000000000000000005",at=class{static totalBalance(e,n){let r=BigInt(0);return e.forEach(s=>{n===s.coin_type&&(r+=BigInt(s.balance))}),r}static getCoinAssets(e,n){let r=[];return n.forEach(s=>{Cm(s.coin_type)===Cm(e)&&r.push(s)}),r}static isSuiCoin(e){return gi(e).full_address===Rm}static selectCoinObjectIdGreaterThanOrEqual(e,n,r=[]){let s=at.selectCoinAssetGreaterThanOrEqual(e,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(e,n,r=[]){let s=at.sortByBalance(e.filter(u=>!r.includes(u.coin_object_id))),i=at.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(p=>p.balance>=u);if(d!==-1){a.push(c[d]),c.splice(d,1);break}let f=c.pop();f.balance>0&&(a.push(f),o+=f.balance)}return{selected_coins:at.sortByBalance(a),remain_coins:at.sortByBalance(c)}}static sortByBalance(e){return e.sort((n,r)=>n.balance<r.balance?-1:n.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((n,r)=>n.balance>r.balance?-1:n.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((n,r)=>n+r.balance,BigInt(0))}static buildCoinForAmount(e,n,r,s,i=!0,o=!0){let a=at.getCoinAssets(s,n);if(r===BigInt(0))return this.buildZeroValueCoin(n,e,s,i);let c=at.calculateTotalBalance(a);if(c<r)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r} `);return this.buildCoin(e,n,a,r,s,i,o)}static buildCoinWithBalance(e,n,r){return e===BigInt(0)&&at.isSuiCoin(n)?r.add(or({balance:e,useGasCoin:!1})):r.add(or({balance:e,type:n}))}static buildVectorCoin(e,n,r,s,i,o=!0){if(at.isSuiCoin(i)){let p=e.splitCoins(e.gas,[e.pure.u64(s)]);return{selected_coins:[],target_coin:p,remain_coins:n,target_coin_amount:s.toString(),is_mint_zero_coin:!1,original_spited_coin:e.gas}}let{original_spited_coin:a,target_coin:c,target_coin_amount:u,remain_coins:d,selected_coins:f}=this.buildSpitTargeCoin(e,s,r,o);return o?{target_coin:e.makeMoveVec({elements:[c]}),selected_coins:f,remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1,original_spited_coin:a}:{selected_coins:f,target_coin:e.makeMoveVec({elements:f.map(p=>e.object(p))}),remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1}}static buildOneCoin(e,n,r,s,i=!0){if(at.isSuiCoin(s)){if(r===0n&&n.length>1){let c=at.selectCoinObjectIdGreaterThanOrEqual(n,r);return{selected_coins:c.object_array,target_coin:e.object(c.object_array[0]),remain_coins:c.remain_coins,target_coin_amount:c.amount_array[0],is_mint_zero_coin:!1}}let o=at.selectCoinObjectIdGreaterThanOrEqual(n,r),a=e.splitCoins(e.gas,[e.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:e.gas}}return this.buildSpitTargeCoin(e,r,n,i)}static buildSpitTargeCoin(e,n,r,s){let i=at.selectCoinObjectIdGreaterThanOrEqual(r,n),o=i.amount_array.reduce((b,v)=>Number(b)+Number(v),0).toString(),a=i.object_array,[c,...u]=a,d=e.object(c),f=d,p=i.amount_array.reduce((b,v)=>Number(b)+Number(v),0).toString(),m;return u.length>0&&e.mergeCoins(d,u.map(b=>e.object(b))),s&&Number(o)>Number(n)&&(f=e.splitCoins(d,[e.pure.u64(n)]),m=d),{original_spited_coin:m,target_coin:f,target_coin_amount:p,remain_coins:i.remain_coins,selected_coins:i.object_array,is_mint_zero_coin:!1}}static buildCoin(e,n,r,s,i,o=!0,a=!0){return o?this.buildVectorCoin(e,n,r,s,i,a):this.buildOneCoin(e,r,s,i,a)}static buildZeroValueCoin(e,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:e,selected_coins:[],is_mint_zero_coin:!0,target_coin_amount:"0"}}static buildCoinForAmountInterval(e,n,r,s,i=!0,o=!0){let a=at.getCoinAssets(s,n);if(r.amount_first===BigInt(0))return a.length>0?this.buildCoin(e,[...n],[...a],r.amount_first,s,i,o):this.buildZeroValueCoin(n,e,s,i);let c=at.calculateTotalBalance(a);if(c>=r.amount_first)return this.buildCoin(e,[...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(e,[...n],[...a],r.amount_second,s,i,o)}static fromBalance(e,n,r){return r.moveCall({target:"0x2::coin::from_balance",typeArguments:[n],arguments:[e]})}static intoBalance(e,n,r){return r.moveCall({target:"0x2::coin::into_balance",typeArguments:[n],arguments:[typeof e=="string"?r.object(e):e]})}static mintBalanceZero(e,n){return n.moveCall({target:"0x2::balance::zero",typeArguments:[e],arguments:[]})}static destroyBalanceZero(e,n,r){return r.moveCall({target:"0x2::balance::destroy_zero",typeArguments:[n],arguments:[e]})}static getCoinAmountObjId(e,n){let r=e.amount_coin_array.find(s=>!s.used&&M(s.amount).eq(n)?(s.used=!0,!0):!1);return r?r.coin_object_id:Im("CoinNotFound",`Coin not found for ${n} ${e.coin_type}`)}static buildMultiCoinInput(e,n,r,s){let i=at.getCoinAssets(r,n);if(at.isSuiCoin(r)){let p=e.splitCoins(e.gas,s.map(b=>e.pure.u64(b)));return{amount_coin_array:s.map((b,v)=>({coin_object_id:p[v],amount:b.toString(),used:!1})),coin_type:r,remain_coins:i}}let o=s.reduce((p,m)=>p+m,BigInt(0)),a=at.selectCoinObjectIdGreaterThanOrEqual(i,o);if(a.object_array.length===0)return Im("InsufficientBalance",`No enough coins for ${r} expect ${o} actual ${at.calculateTotalBalance(i)}`);let[c,...u]=a.object_array;u.length>0&&e.mergeCoins(c,[...u]);let d=e.splitCoins(c,s.map(p=>e.pure.u64(p)));return{amount_coin_array:s.map((p,m)=>({coin_object_id:d[m],amount:p.toString(),used:!1})),remain_coins:a.remain_coins,coin_type:r}}},Wt=at;An(Wt,"callMintZeroValueCoin",(e,n)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[n]}));var Q_=6e4,eT=3e5,ga=864e5;function jm(t){return Date.parse(new Date().toString())+t}var od=class{overdueTime;value;constructor(e,n=0){this.overdueTime=n,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};function yi(t,e){let n=Bm(M(e));return Number(M(t).mul(n))}function hZ(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function mZ(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function bo(t,e){let n=Bm(M(e));return Number(M(t).div(n))}function gZ(t,e="hex"){if(t instanceof Uint8Array){let r=Buffer.from(t);return hl.fromSecretKey(new Uint8Array(r))}let n=e==="hex"?hn(t):ce(t);return hl.fromSecretKey(n)}function yZ(t,e="hex"){if(t instanceof Uint8Array){let r=Buffer.from(t);return xl.fromSecretKey(new Uint8Array(r))}let n=e==="hex"?hn(t):ce(t);return xl.fromSecretKey(n)}var tT=async t=>new Promise(e=>{setTimeout(()=>{e(1)},t)});async function nT(t,e=!0){t.getData().commands.forEach((n,r)=>{e&&console.log(`transaction ${r}: `,n)})}var rT={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},sT={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function iT(...t){console.log("DeepbookV3_Utils_Sdk###",...t)}function oT(t){return t.data}function V3(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let{error:e}=t;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function F3(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function q3(t){if("reference"in t)return t.reference;let e=oT(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:V3(t)}function aT(t){return"objectId"in t?t.objectId:q3(t)?.objectId??F3(t)}function _Z(t){return t.data!==void 0}function $3(t){return t.content!==void 0}function G3(t){let e="data"in t?oT(t):t;if(!(!e||!$3(e)||e.content.dataType!=="moveObject"))return e.content}function cT(t){let e=G3(t)?.fields;if(e)return"fields"in e?e.fields:e}var uT=A.struct("GetCetusBalanceManagerList",{owner:A.Address,cetus_balance_managers:A.vector(A.Address),deepbook_balance_managers:A.vector(A.Address)}),lT=A.struct("Account",{epoch:A.u64(),open_orders:A.vector(A.u128()),taker_volume:A.u128(),maker_volume:A.u128(),active_stake:A.u64(),inactive_stake:A.u64(),created_proposal:A.bool(),voted_proposal:A.option(A.Address),unclaimed_rebates:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()}),settled_balances:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()}),owed_balances:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()})});var Dm=1e6,Cr=1e9,W3={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Z3={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},ad=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?Z3:W3}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new Y,n=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),n],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[n],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:n,amountToDeposit:r}){let s=new Y;s.setSenderIfNotSet(e);let i=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=or({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:e,balanceManager:n,coin:r,amountToDeposit:s,tx:i}){let o=i||new Y;if(n){o.setSenderIfNotSet(e);let a=or({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:e,balanceManager:n,coin:r,amountToWithdraw:s,returnAssets:i,txb:o}){let a=o||new Y,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(Wt.isSuiCoin(r.coinType))a.transferObjects([c],e);else{let u=await this._sdk.fullClient.getOwnerCoinAssets(e,r.coinType),d=Wt.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],e)):a.transferObjects([c],e)}return a}withdrawManagersFreeBalance({account:e,balanceManagers:n,tx:r=new Y}){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],e)});return r}async getBalanceManager(e,n=!0){let r=`getBalanceManager_${e}`,s=this.getCache(r,n);if(!n&&s!==void 0)return s;try{let i=new Y;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(e)],typeArguments:[]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,e),c=(o?.Transaction??o?.FailedTransaction)?.events?.find(T=>T.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=uT.parse(new Uint8Array(c.bcs))?.deepbook_balance_managers||[],f=await this._sdk.fullClient.batchGetObjects(d,{json:!0}),p={};for(let T=0;T<f.length;T++){let O=f[T],B=O?.data?.objectId??O?.objectId,C=O?.json??O?.data?.content?.fields,U=C?.allow_listed?.fields?.contents??C?.allow_listed?.contents??C?.balance_manager?.allow_listed?.contents;B&&Array.isArray(U)&&U.length>0&&(p[B]=U)}let m=await this.batchGetObjectsByIdMap(p),b=Q(e),v=[];return d.forEach(T=>{let O=m[T]??[],B=O.filter(U=>{let L=this.getSuiObjectOwnerAddress(U);return L!==void 0&&Q(L)===b});O.length===0||B.length===O.length?v.push({balanceManager:T,cetusBalanceManager:"",capOk:!0}):v.push({balanceManager:T,cetusBalanceManager:"",capOk:!1})}),this.updateCache(r,v,864e5),v||[]}catch(i){throw i instanceof Error?i:new Error(String(i))}}async batchGetObjectsByIdMap(e){let n=Object.entries(e).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(e){let r=e?.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=e.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:e,balanceManager:n},r=new Y){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(e.address),r.object(n),s],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:n,coins:r}){try{let s=new Y;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,e),o={};return i?.commandResults?.forEach((a,c)=>{let u=r[c],d=a.returnValues[0]?.bcs,f=A.U64.parse(new Uint8Array(d)),p=M(f),m=p.eq(0)?"0":p.div(Math.pow(10,u.decimals)).toString();o[u.coinType]={adjusted_balance:m,balance:p.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:e,coins:n}){try{let r=new Y,s=await this.getBalanceManager(e,!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,e),o={};return s.forEach((a,c)=>{let u={},d=c*n.length;n.forEach((f,p)=>{let m=d+p,b=i.commandResults?.[m];if(b){let v=b.returnValues[0].bcs,T=A.U64.parse(new Uint8Array(v)),O=M(T),B=O.eq(0)?"0":O.div(Math.pow(10,f.decimals)).toString();u[f.coinType]={adjusted_balance:B,balance:O.toString()}}}),o[a.balanceManager]=u}),o}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let n=new Y;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[n.object(e.address),n.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=(await this._sdk.fullClient.sendSimulationTransaction(n,this._sdk.sdkOptions.simulationAccount.address)).commandResults[0]?.returnValues[0]?.bcs,i=Number(A.U64.parse(new Uint8Array(s))),o=Math.pow(10,e.baseCoin.decimals).toString(),a=Math.pow(10,e.quoteCoin.decimals).toString();return M(i).mul(o).div(a).div(Cr).toString()}catch(n){return iT("getMarketPrice ~ error:",n),"0"}}async getPools(e=!1){let n="Deepbook_getPools",r=this.getCache(n,e);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 f=u[1].split(", ");o.push({...c,baseCoinType:f[0],quoteCoinType:f[1]})}}),this.updateCache(n,o,864e5),o}async getQuoteQuantityOut(e,n,r){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(e.address),s.pure.u64(n),s.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:M(n).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:M(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(c).div(Dm).toString(),baseQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getBaseQuantityOut(e,n,r){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(e.address),s.pure.u64(n),s.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{quoteQuantityDisplay:M(n).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:M(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(c).div(Dm).toString(),quoteQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getQuantityOut(e,n,r,s){let i=new Y;i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[i.object(e.address),i.pure.u64(n),i.pure.u64(r),i.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.sendSimulationTransaction(i,s),a=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs))),c=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs))),u=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:M(n).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:M(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:M(a).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(u).div(Dm).toString(),baseQuantity:n,quoteQuantity:r,baseOut:a,quoteOut:c,deepRequired:u}}async getReferencePool(e){let n=await this.getPools(),r=e.baseCoin.coinType,s=e.quoteCoin.coinType,i=this._deep.coinType;for(let o=0;o<n.length;o++){let a=n[o];if(a.address===e.address)continue;let c=[a.baseCoinType,a.quoteCoinType];if(a.baseCoinType===i&&(c.includes(r)||c.includes(s)))return a}return null}async updateDeepPrice(e,n){let r=await this.getReferencePool(e);return r?(n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[n.object(e.address),n.object(r.pool_id),n.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),n):null}async estimatedMaxFee(e,n,r,s,i,o,a){let c=this.deepCoin;try{let{taker_fee:u,maker_fee:d}=e,f=M(u).div(Cr).toString(),p=M(d).div(Cr).toString(),m=await this.getMarketPrice(e);console.log("\u{1F680} ~ DeepbookUtilsModule ~ estimatedMaxFee ~ marketPrice:",m);let b=o?r:m!=="0"?m:a;if(b==="0")throw new Error("Cannot get market price");let v=Math.pow(10,e.baseCoin.decimals).toString(),T=Math.pow(10,e.quoteCoin.decimals).toString(),O=M(b).div(v).mul(T).mul(Cr).toString();if(s){let U=await this.getMarketPrice(e),P=M(o?r:U!=="0"?U:a).div(v).mul(T).mul(Cr).toString(),q=await this.getOrderDeepPrice(e);if(!q)throw new Error("Cannot get deep price");let V=Mm(P,r),F=M(n).mul(M(f)).mul(M(q.deep_per_asset)).div(M(Cr)),X=M(n).mul(M(p)).mul(M(q.deep_per_asset)).div(M(Cr));q.asset_is_base||(F=F.mul(V).div(M(Cr)),X=X.mul(V).div(M(Cr)));let ee=F.ceil().toString(),j=X.ceil().toString();return{takerFee:ee,makerFee:j,takerFeeDisplay:bo(ee,c.decimals).toString(),makerFeeDisplay:bo(j,c.decimals).toString(),feeType:c.coinType}}if(i){let U=Mm(O,o?r:m),L=M(n).mul(U).mul(M(f).mul(1.25)).div(M(Cr)).ceil().toFixed(0),P=M(n).mul(U).mul(M(p).mul(1.25)).div(M(Cr)).ceil().toFixed(0);return{takerFee:L,makerFee:P,takerFeeDisplay:bo(L,e.quoteCoin.decimals).toString(),makerFeeDisplay:bo(P,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let B=M(n).mul(M(f).mul(1.25)).ceil().toFixed(0),C=M(n).mul(M(p).mul(1.25)).ceil().toFixed(0);return{takerFee:B,makerFee:C,takerFeeDisplay:bo(B,e.baseCoin.decimals).toString(),makerFeeDisplay:bo(C,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(e,n=!0){let r=`getOrderDeepPrice_${e.address}}`,s=this.getCache(r);if(s!==void 0)return s;try{let i=new Y,o=!1;n&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,i)&&(o=!0),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[i.object(e.address)],typeArguments:[e.baseCoin.coinType,e.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 tT(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let n=new DataView(e.buffer),r=n.getUint8(0)!==0,s=Number(n.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:s}}getCoinAssets(e,n,r){return Wt.buildCoinWithBalance(BigInt(M(n).abs().ceil().toString()),e,r)}async getTransactionRelatedBalance(e,n,r,s,i,o,a){let c=this.deepCoin;if(!a)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];s&&u.push(c);let d=await this.getManagerBalance({account:i,balanceManager:a,coins:u}),f=d?.[n]?.balance||"0",p=d?.[r]?.balance||"0",m=o&&d?.[c.coinType]?.balance||"0";return{baseManagerBlance:f,quoteManagerBlance:p,feeManaerBalance:m}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(e,n,r,s,i,o,a,c,u){let d=M(e).gt(0)&&c,f="0";if(!d)return{feeAsset:this.getEmptyCoin(u,n),haveDepositFee:"0"};if(o||a){let p=M(i).sub(o?s:r);f=p.lte(0)?e:p.sub(e).lt(0)?p.sub(e).toString():"0"}else f=M(i).sub(e).lt("0")?M(i).sub(e).abs().toString():"0";return{feeAsset:M(f).gt("0")?this.getCoinAssets(n,f,u):this.getEmptyCoin(u,n),haveDepositFee:f}}async getTransactionRelatedAssets(e,n,r,s,i,o,a,c,u){try{let d=this.deepCoin,f=ye(e.baseCoin.coinType),p=ye(e.quoteCoin.coinType),m=f===d.coinType,b=p===d.coinType,v=!m&&!b,{baseManagerBlance:T,quoteManagerBlance:O,feeManaerBalance:B}=await this.getTransactionRelatedBalance(e,f,p,v,o,a,c);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:T,quoteManagerBlance:O});let C,U,L=!1;if(i){a||(r=M(r).add(M(s)).toString());let q=M(O).sub(r).toString();M(q).lt(0)?(L=!0,U=this.getCoinAssets(p,q,u)):U=this.getEmptyCoin(u,p),C=this.getEmptyCoin(u,f)}else{a||(n=M(n).add(M(s)).toString());let q=M(T).sub(n).toString();M(q).lt(0)?(L=!0,C=this.getCoinAssets(f,q,u)):C=this.getEmptyCoin(u,f),U=this.getEmptyCoin(u,p)}let P=this.getFeeAsset(s,d.coinType,n,r,B,b,m,a,u);return{baseAsset:C,quoteAsset:U,feeAsset:P,haveDeposit:L}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getMarketTransactionRelatedAssets(e,n,r,s,i,o,a,c,u,d){try{let f=this.deepCoin,p=ye(e.baseCoin.coinType),m=ye(e.quoteCoin.coinType),b=p===f.coinType,v=m===f.coinType,T=!b&&!v,O=await this.getTransactionRelatedBalance(e,p,m,T,o,a,c),{feeManaerBalance:B}=O,C=M(O.baseManagerBlance).add(M(d?.base||"0")).toString(),U=M(O.quoteManagerBlance).add(M(d?.quote||"0")).toString(),L;a&&M(B).lt(s)?L=this.getCoinAssets(f.coinType,M(s).sub(B).toString(),u):L=this.getEmptyCoin(u,f.coinType);let P,q;if(i){a||(r=M(r).add(M(s)).toString());let V=M(U).sub(r).toString();if(M(V).lt(0)){let F;M(U).gt(0)&&(F=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.quoteCoin,amountToWithdraw:U,returnAssets:!0,txb:u}));let X=this.getCoinAssets(m,V,u);F&&u.mergeCoins(X,[F]),q=X}else q=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});P=this.getEmptyCoin(u,p)}else{a||(n=M(n).add(M(s)).toString());let V=M(C).sub(n).toString();if(M(V).lt(0)){let F;M(C).gt(0)&&(F=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.baseCoin,amountToWithdraw:C,returnAssets:!0,txb:u}));let X=this.getCoinAssets(p,V,u);F&&u.mergeCoins(X,[F]),P=X}else P=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.baseCoin,amountToWithdraw:n,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,m)}return{baseAsset:P,quoteAsset:q,feeAsset:L}}catch(f){throw f instanceof Error?f:new Error(String(f))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:n,quantity:r,orderType:s,isBid:i,maxFee:o,account:a,payWithDeep:c,expirationTimestamp:u=Date.now()+31536e8}){try{let d=this.deepCoin,f=e.address,p=e.baseCoin.decimals,m=e.quoteCoin.decimals,b=e.baseCoin.coinType,v=e.quoteCoin.coinType,T=M(n).mul(10**(m-p+9)).toString(),O=ye(b),B=ye(v),C=new Y,U,L;if(i){let F=M(n).mul(M(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();c||(F=M(F).add(M(o)).toString()),L=Wt.buildCoinWithBalance(BigInt(F),B,C)}else{let F=r;c||(F=M(r).abs().add(M(o)).toString()),U=Wt.buildCoinWithBalance(BigInt(F),O,C)}let P=c?M(o).gt(0)?Wt.buildCoinWithBalance(BigInt(M(o).abs().ceil().toString()),d.coinType,C):this.getEmptyCoin(C,d.coinType):this.getEmptyCoin(C,d.coinType),q=C.moveCall({typeArguments:[i?b:v],target:"0x2::coin::zero",arguments:[]}),V=[C.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),C.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),C.object(f),i?q:U,i?L:q,P,C.pure.u8(s),C.pure.u8(0),C.pure.u64(T),C.pure.u64(r),C.pure.bool(i),C.pure.bool(!1),C.pure.u64(u),C.object(he)];return C.moveCall({typeArguments:[O,B],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:V}),C}catch(d){throw d instanceof Error?d:new Error(String(d))}}getEmptyCoin(e,n){return Wt.buildCoinWithBalance(BigInt(0),n,e)}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:n,isBid:r,maxFee:s,account:i,payWithDeep:o,slippage:a=.01}){try{let c=e.address,u=e.baseCoin.coinType,d=e.quoteCoin.coinType,f=ye(u),p=ye(d),m=new Y,b,v,T=n,O,B=await this.getOrderBook(e,"all",6);if(r){let L=B?.ask?.[0]?.price||"0",P=M(L).mul(M(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();O=M(P).plus(M(P).mul(a)).ceil().toString()}else{let L=await B?.bid?.[0]?.price||"0",P=M(L).mul(M(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();O=M(P).minus(M(P).mul(a)).floor().toString()}r?(o||(O=M(O).add(M(s)).toString()),v=this.getCoinAssets(p,O,m),b=this.getEmptyCoin(m,f)):(o||(T=M(T).add(M(s)).toString()),v=this.getEmptyCoin(m,p),b=this.getCoinAssets(f,T,m));let C=o?M(s).gt(0)?Wt.buildCoinWithBalance(BigInt(M(s).abs().ceil().toString()),this.deepCoin.coinType,m):this.getEmptyCoin(m,this.deepCoin.coinType):this.getEmptyCoin(m,this.deepCoin.coinType),U=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(c),b,v,C,m.pure.u8(0),m.pure.u64(n),m.pure.bool(r),m.pure.bool(o),m.pure.u64(O),m.object(he)];return m.moveCall({typeArguments:[f,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:U}),m}catch(c){throw c instanceof Error?c:new Error(String(c))}}async placeLimitOrder({balanceManager:e,poolInfo:n,priceInput:r,quantity:s,isBid:i,orderType:o,maxFee:a,account:c,payWithDeep:u,expirationTimestamp:d=Date.now()+31536e8}){try{let f=this.deepCoin,p=M(r).mul(10**(n.quoteCoin.decimals-n.baseCoin.decimals+9)).toString(),m=n.baseCoin.coinType,b=n.quoteCoin.coinType,v=new Y,T=i?M(r).mul(M(s).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString():"0",O=i?"0":s,{baseAsset:B,quoteAsset:C,feeAsset:U,haveDeposit:L}=await this.getTransactionRelatedAssets(n,O,T,a,i,c,u,e,v);if(L){let V=[v.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),v.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),v.object(n.address),v.object(e),B,C,U.feeAsset,v.pure.u8(o),v.pure.u8(0),v.pure.u64(p),v.pure.u64(s),v.pure.bool(i),v.pure.bool(u),v.pure.u64(d),v.object(he)];return v.moveCall({typeArguments:[m,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:V}),v}let P=new Y;M(U.haveDepositFee).gt(0)&&this.depositIntoManager({account:c,balanceManager:e,coin:f,amountToDeposit:U.haveDepositFee,tx:P});let q=[P.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),P.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),P.object(n.address),P.object(e),P.pure.u8(o),P.pure.u8(0),P.pure.u64(p),P.pure.u64(s),P.pure.bool(i),P.pure.bool(u),P.pure.u64(d),P.object(he)];return P.moveCall({typeArguments:[m,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:q}),P}catch(f){throw f instanceof Error?f:new Error(String(f))}}modifyOrder({balanceManager:e,poolInfo:n,orderId:r,newOrderQuantity:s}){let i=new Y;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(e),i.object(n.address),i.pure.u128(r),i.pure.u64(s),i.object(he)]}),i}async getBestAskprice(e){try{let{baseCoin:n,quoteCoin:r}=e,s=new Y,i=await this.getMarketPrice(e),o=M(i).gt(0)?i:Math.pow(10,-1),a=Math.pow(10,6),c=M(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=M(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(e.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,f=await this._sdk.fullClient.sendSimulationTransaction(s,d),p=[],m=f.commandResults[0].returnValues[0].bcs,b=A.vector(A.u64()).parse(new Uint8Array(m)),v=f.commandResults[0].returnValues[1].bcs,T=A.vector(A.u64()).parse(new Uint8Array(v));return b.forEach((O,B)=>{let C=M(O).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),U=M(T[B]).div(Math.pow(10,n.decimals)).toString();p.push({price:C,quantity:U})}),p?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:n,quoteCoin:r}=e,s=new Y,i=await this.getMarketPrice(e),o=M(i).gt(0)?M(i).div(3).toNumber():Math.pow(10,-6),a=M(i).gt(0)?i:Math.pow(10,6),c=M(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=M(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(e.address),s.pure.u64(yo(c,0)),s.pure.u64(yo(u,0)),s.pure.bool(!0),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(s,d),p=[],m=f.commandResults[0].returnValues[0].bcs,b=A.vector(A.u64()).parse(new Uint8Array(m)),v=f.commandResults[0].returnValues[1].bcs,T=A.vector(A.u64()).parse(new Uint8Array(v));return b.forEach((O,B)=>{let C=M(O).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),U=M(T[B]).div(Math.pow(10,n.decimals)).toString();p.push({price:C,quantity:U})}),p?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,n){try{let{baseCoin:r,quoteCoin:s}=e,i=new Y,o=await this.getMarketPrice(e),a,c;n?(a=M(o).gt(0)?M(o).div(3).toNumber():Math.pow(10,-6),c=M(o).gt(0)?o:Math.pow(10,6)):(a=M(o).gt(0)?o:Math.pow(10,-1),c=M(o).gt(0)?M(o).mul(3).toNumber():Math.pow(10,6));let u=M(a).mul(Math.pow(10,9+s.decimals-r.decimals)).toString(),d=M(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(e.address),i.pure.u64(yo(u,0)),i.pure.u64(yo(d,0)),i.pure.bool(n),i.object(he)],typeArguments:[r.coinType,s.coinType]});let f=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(i,f),m=[],b=p.commandResults[0].returnValues[0].bcs,v=A.vector(A.u64()).parse(new Uint8Array(b)),T=p.commandResults[0].returnValues[1].bcs,O=A.vector(A.u64()).parse(new Uint8Array(T));return v.forEach((B,C)=>{let U=M(B).div(Math.pow(10,9+s.decimals-r.decimals)).toString(),L=M(O[C]).div(Math.pow(10,r.decimals)).toString();m.push({price:U,quantity:L})}),m?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,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 f=ye(n.baseCoin.coinType),p=ye(n.quoteCoin.coinType),m=new Y;d&&(M(d.base).gt(0)||M(d.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:n,balanceManager:e},m);let{baseAsset:b,quoteAsset:v,feeAsset:T}=await this.getMarketTransactionRelatedAssets(n,r,s,o,i,a,c,e,m,d),O=await this.getOrderBook(n,"all",6);if(i){let U=O?.ask?.[0]?.price||"0",L=M(U).mul(M(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=M(L).plus(M(L).mul(u)).ceil().toString()}else{let U=await O?.bid?.[0]?.price||"0",L=M(U).mul(M(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=M(L).minus(M(L).mul(u)).floor().toString()}let B=s,C=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(n.address),m.object(e),b,v,T,m.pure.u8(0),m.pure.u64(r),m.pure.bool(i),m.pure.bool(c),m.pure.u64(B),m.object(he)];return m.setSenderIfNotSet(a),m.moveCall({typeArguments:[f,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),m}catch(f){throw f instanceof Error?f:new Error(String(f))}}async getOrderInfoList(e,n){try{let r=new Y;e.forEach(u=>{let d=u?.pool,f=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(d.pool_id),r.pure.u128(BigInt(f))],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let s=await this._sdk.fullClient.sendSimulationTransaction(r,n),i=A.struct("ID",{bytes:A.Address}),o=A.struct("OrderDeepPrice",{asset_is_base:A.bool(),deep_per_asset:A.u64()}),a=A.struct("Order",{balance_manager_id:i,order_id:A.u128(),client_order_id:A.u64(),quantity:A.u64(),filled_quantity:A.u64(),fee_is_deep:A.bool(),order_deep_price:o,epoch:A.u64(),status:A.u8(),expire_timestamp:A.u64()}),c=[];return s?.commandResults?.forEach(u=>{let d=u.returnValues[0].bcs,f=a.parse(new Uint8Array(d));c.push(f)}),c}catch{return[]}}decodeOrderId(e){let n=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:n,price:r,orderId:s}}async getOpenOrder(e,n,r,s,i=!1,o=new Y){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(e.address),i?r:o.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let f=await this._sdk.fullClient.sendSimulationTransaction(o,n);console.log("\u{1F680} ~ DeepbookUtilsModule ~ getOpenOrder ~ res:",f?.FailedTransaction?.status);let p=f.commandResults[i?1:0].returnValues[0].bcs;a=A.struct("VecSet",{constants:A.vector(A.U128)}).parse(new Uint8Array(p)).constants}if(a.length===0)return[];let c=a.map(f=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:f})),u=await this.getOrderInfoList(c,n)||[],d=[];return u.forEach(f=>{let p=this.decodeOrderId(BigInt(f.order_id));d.push({...f,price:p.price,isBid:p.isBid,pool:e})}),d}async getAllMarketsOpenOrders(e,n){try{let r=await this.getPools(),s=new Y;r.forEach(f=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(f.pool_id),s.object(n)],typeArguments:[f.baseCoinType,f.quoteCoinType]})});let o=(await this._sdk.fullClient.sendSimulationTransaction(s,e)).commandResults?.map(f=>f.returnValues?.[0]?.bcs)||[],a=A.struct("VecSet",{constants:A.vector(A.U128)}),c=[];o.forEach((f,p)=>{let m=a.parse(new Uint8Array(f)).constants;m.length>0&&m.forEach(b=>{c.push({pool:r[p],orderId:b})})});let u=await this.getOrderInfoList(c,e)||[],d=[];return c.forEach((f,p)=>{let m=this.decodeOrderId(BigInt(f.orderId)),b=u.find(v=>v.order_id===f.orderId)||{};d.push({...f,...b,price:m.price,isBid:m.isBid})}),d}catch(r){return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getAllMarketsOpenOrders ~ error:",r),[]}}cancelOrders(e,n,r=new Y){return e.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(e,n,r,s,i,o){let a=this._sdk.fullClient,u=await new H3({client:a,address:i,network:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,n,r,s)}processOrderBookData(e,n,r,s){let i=e.returnValues[0].bcs,o=A.vector(A.u64()).parse(new Uint8Array(i)),a=e.returnValues[1].bcs,c=A.vector(A.u64()).parse(new Uint8Array(a)),u={};return o.forEach((f,p)=>{let m=M(f).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),b=M(c[p]).div(Math.pow(10,n.decimals)).toString();u[m]?u[m]={price:m,quantity:M(u[m].quantity).add(b).toString()}:u[m]={price:m,quantity:b}}),Object.values(u)}getLevel2RangeTx(e,n,r,s,i=new Y){let{baseCoin:o,quoteCoin:a}=e,c=yo(M(r).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0),u=yo(M(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(e.address),i.pure.u64(c),i.pure.u64(u),i.pure.bool(n),i.object(he)],typeArguments:[o.coinType,a.coinType]}),i}async fetchOrderBook(e,n,r,s,i,o){let a=new Y,{baseCoin:c,quoteCoin:u}=e;try{if(n==="bid"||n==="all"){let b=s,v=r==="0"?i:r;a=this.getLevel2RangeTx(e,!0,b,v,a)}if(n==="ask"||n==="all"){let b=r==="0"?s:r,v=i;a=this.getLevel2RangeTx(e,!1,b,v,a)}let d=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(a,d),p=[];(n==="bid"||n==="all")&&(p=f.commandResults?.[0]?this.processOrderBookData(f.commandResults[0],c,u,o):[]);let m=[];if(n==="ask"||n==="all"){let b=n==="ask"?0:1;m=f.commandResults?.[b]?this.processOrderBookData(f.commandResults[b],c,u,o):[]}return{bid:p.sort((b,v)=>v.price-b.price),ask:m.sort((b,v)=>b.price-v.price)}}catch{let f=this._sdk.sdkOptions.simulationAccount.address,p=[],m=[];try{let b=this.getLevel2RangeTx(e,!0,s,r),v=await this._sdk.fullClient.sendSimulationTransaction(b,f);p=v.commandResults?.[0]?this.processOrderBookData(v.commandResults[0],c,u,o):[]}catch{p=[]}try{let b=this.getLevel2RangeTx(e,!1,s,r),v=await this._sdk.fullClient.sendSimulationTransaction(b,f);m=v.commandResults?.[0]?this.processOrderBookData(v.commandResults[0],c,u,o):[]}catch{m=[]}return{bid:p,ask:m}}}async getOrderBook(e,n,r){let s={bid:[],ask:[]};try{let i=await this.getMarketPrice(e),o=n,a=Math.pow(10,-r),c=Math.pow(10,r),u=await this.fetchOrderBook(e,o,i,a,c,r);return{bid:u?.bid,ask:u?.ask}}catch{return s}}async getOrderBookOrigin(e,n){try{let r=new Y,s=await this.getMarketPrice(e),{baseCoin:i,quoteCoin:o}=e;if(n==="bid"||n==="all"){let f=Math.pow(10,-6),p=s,m=M(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=M(p).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(e.address),r.pure.u64(m),r.pure.u64(b),r.pure.bool(!0),r.object(he)],typeArguments:[i.coinType,o.coinType]})}if(n==="ask"||n==="all"){let f=s,p=Math.pow(10,6),m=M(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=M(p).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(e.address),r.pure.u64(m),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 f=c.commandResults[0]?.returnValues[0]?.bcs,p=A.vector(A.u64()).parse(new Uint8Array(f)),m=c.commandResults[0]?.returnValues[1]?.bcs,b=A.vector(A.u64()).parse(new Uint8Array(m));p.forEach((v,T)=>{let O=M(v).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),B=M(b[T]).div(Math.pow(10,i.decimals)).toString();u.push({price:O,quantity:B})})}let d=[];if(n==="ask"||n==="all"){let f=n==="ask"?0:1,p=c.results[f]?.returnValues[0]?.[0],m=A.vector(A.u64()).parse(new Uint8Array(p)),b=c.results[f]?.returnValues[1]?.[0],v=A.vector(A.u64()).parse(new Uint8Array(b));m.forEach((T,O)=>{let B=M(T).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),C=M(v[O]).div(Math.pow(10,i.decimals)).toString();d.push({price:B,quantity:C})})}return{bid:u,ask:d}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let n=await this._sdk.fullClient?.getOwnerCoinBalances(e);return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getWalletBalance ~ result:",n),Object.fromEntries(n.map((s,i)=>[ye(s.coinType),{coinType:s.coinType,totalBalance:s.balance,coinBalance:s.coinBalance,addressBalance:s.addressBalance}]))}async getAccount(e,n,r=new Y){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 e=="string"?r.object(e):e],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=lT.parse(c),d=u.open_orders,f=u.owed_balances,p=u.settled_balances,m=u.unclaimed_rebates,b=u.taker_volume;i.push({balance_manager_id:e,open_orders:d,owed_balances:f,settled_balances:p,unclaimed_rebates:m,taker_volume:b,poolInfo:n[a]})}),i}async getSuiTransactionResponse(e,n=!1){let r=`${e}_getSuiTransactionResponse`,s=this.getCache(r,n);if(s!==void 0)return s;let i;try{i=await this._sdk.fullClient.getTransaction({digest:e,include:{events:!0,effects:!0,balanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransaction({digest:e,include:{events:!0,effects:!0}})}return this.updateCache(r,i,864e5),i}transformExtensions(e,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(z3.decode(a)))}catch{}r&&(e[o]=a),s.push({key:o,value:a})}delete e.extension_fields,r||(e.extensions=s)}async getCoinConfigs(e=!1,n=!0){let r=this.sdk.sdkOptions.coinlist.handle,s=`${r}_getCoinConfigs`,i=this.getCache(s,e);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 f=this.buildCoinConfig(d,n);this.updateCache(`${r}_${f.address}_getCoinConfig`,f,864e5),u.push({...f})}),this.updateCache(s,u,864e5),u}buildCoinConfig(e,n=!0){let r=cT(e);r=r.value.fields;let s={...r};return s.id=aT(e),s.address=gi(r.coin_type.fields.name).full_address,r.pyth_id&&(s.pyth_id=$t(r.pyth_id)),this.transformExtensions(s,r.extension_fields.fields.contents,n),delete s.coin_type,s}updateCache(e,n,r=3e5){let s=this._cache[e];s?(s.overdueTime=jm(r),s.value=n):s=new od(n,jm(r)),this._cache[e]=s}getCache(e,n=!1){let r=this._cache[e],s=r?.isValid();if(!n&&s)return r.value;s||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:n,minSize:r,baseCoinType:s,quoteCoinType:i}){let o=new Y,a=Wt.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(e),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:e,appType:n}){let r=new Y,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(e)],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],e),r}};var cd="0x0000000000000000000000000000000000000000000000000000000000000006",FZ="pool_script",qZ="pool_script_v2",$Z="router",GZ="router_with_partner",HZ="fetcher_script",zZ="expect_swap",WZ="utils",ZZ="0x1::coin::CoinInfo",JZ="0x1::coin::CoinStore",KZ="custodian_v2",YZ="clob_v2",XZ="endpoints_v2",QZ=t=>{if(typeof t=="string"&&t.startsWith("0x"))return"object";if(typeof t=="number"||typeof t=="bigint")return"u64";if(typeof t=="boolean")return"bool";throw new Error(`Unknown type for value: ${t}`)},eJ=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];import dT from"decimal.js";dT.config({precision:64,rounding:dT.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var iJ=({totalAssetsValue:t,totalDebtValue:e})=>M(e).eq(0)||M(t).eq(0)?"0":M(t).div(M(e)).toString(),fT=t=>{let{base_margin_pool_id:e,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i}=t.value.fields,{liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}=t.value.fields.risk_ratios.fields;return{id:t.id.id,name:t.name,base_margin_pool_id:e,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}},pT=(t,e)=>{let{deposit_coin_type:n}=e,r=t.id,{max_utilization_rate:s,min_borrow:i,protocol_spread:o,supply_cap:a}=t.config.margin_pool_config,{maintainer_fees:c,protocol_fees:u}=t.protocol_fees,{total_supply:d,total_borrow:f}=t.state,p=M(a).sub(d).toString();return{deposit_coin_type:n,id:r,supply_cap:a,total_supply:d,total_borrow:f,available_supply:p,max_utilization_rate:s,min_borrow:i,protocol_spread:o,maintainer_fees:c,protocol_fees:u}};var es=1000000000n,J3=365n*24n*60n*60n*1000n;function K3(t,e){return e===0n?0n:t*es/e}function Y3(t,e){let{base_rate:n,base_slope:r,optimal_utilization:s,excess_slope:i}=e;if(t<s)return n+t*r/es;{let o=t-s,a=s*r/es,c=o*i/es;return n+a+c}}function hT(t,e){let n=t*e,r=n/es;return n%es>0n?r+1n:r}function X3(t,e,n,r){let s=e.borrow_shares===0n?es:e.total_borrow*es/e.borrow_shares,i=hT(t,s),o=K3(e.total_borrow,e.total_supply),a=Y3(o,n),c=r-e.last_update_timestamp,u=e.total_borrow*a/es*c/J3,d=e.borrow_shares===0n?0n:hT(u,t*es/e.borrow_shares),f=i+d;return{confirmedDebt:i,estimatedInterest:d,totalDebt:f,annualInterestRate:a}}function aJ(t,e,n,r,s=60000n){let i=r+s,{totalDebt:o}=X3(t,e,n,i);return o}var Um=10n;function Q3(t,e){if(!Um)throw new Error("oraclePriceMultiplierDecimal is required");if(t===0n)throw new Error("Invalid oracle price");if(e<0n){let n=10n**(Um- -e);return t*n}return t/10n**(e+Um)}var ya=class{_sdk;hasChangeConnection=!1;_commonPythPrice;_cache={};constructor(e){this._sdk=e,this._commonPythPrice=new z_(e.fullClient)}get sdk(){return this._sdk}async updatePythPriceIDs(e,n){let r=null,s=null;try{r=await this._commonPythPrice.getPriceFeedsUpdateData(e)}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,e)}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<e.length;a++)o.set(e[a],i[a]);return o}priceCheck(e,n=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>n))return e}async getLatestPrice(e,n=!1){let r={},s=[];if(n?e.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=e.map(a=>a.coinType),s.length===0)return r;let i=e.map(a=>a.feed);return(await this._commonPythPrice.getLatestPriceFeeds(i))?.parsed?.forEach((a,c)=>{let u=a.price;if(u){let{price:d,expo:f}=u,p=M(d).mul(M(10).pow(M(f))).toString(),b={coin_type:e[c].coinType,price:p,oracle_price:0n,last_update_time:u.publish_time};b.oracle_price=Q3(BigInt(d),BigInt(f)),r[s[c]]=b,this._sdk.fullClient.updateCache(`getLatestPrice_${b.coin_type}`,b)}}),r}};var ud=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new ya(e),this._deep=e.sdkOptions.network==="mainnet"?sT:rT}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,n=new Y){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:s}=e;try{let{margin_manager:i,initializer:o}=this.createMarginManager(e,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(e,n=new Y){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:s,quoteCoin:i}=e;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:e,initializer:n,baseCoin:r,quoteCoin:s},i=new Y){try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,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 getMarginManagerByAccount(e){if(!e||typeof e!="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(f=>f.parsedJson?.owner===e);if(!s.length)return[];let i=s.map(f=>f.parsedJson?.margin_manager_id),a=(await this.sdk.fullClient.batchGetObjects(i,{json:!0})).map((f,p)=>{let m=f.json,v=(m?.balance_manager?.allow_listed?.contents).map(O=>O),T=v.includes(m?.deposit_cap?.id)&&v.includes(m?.withdraw_cap?.id)&&v.includes(m?.trade_cap?.id);return{balanceManagerId:m?.balance_manager?.id,marginManagerId:i[p],capOk:T}}),c=await Promise.all(a.map(({balanceManagerId:f})=>this.sdk.fullClient.listDynamicFields({parentId:f}))),u=new Map;return c.forEach((f,p)=>{let m=f?.dynamicFields??[];if(m.length>0){let b=A.struct("ReferralKey",{pos0:A.Address}).parse(m[0].name.bcs);u.set(a[p].marginManagerId,b.pos0)}}),{finalResult:s.map(f=>{let p=f.parsedJson?.margin_manager_id;return{...f.parsedJson,referralKey:u.get(p)}}),referralMap:u}}catch(n){throw new Error(`Failed to get margin managers by account: ${n instanceof Error?n.message:String(n)}`)}}async getBaseBalance({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let i=new Y,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,e);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=A.U64.parse(new Uint8Array(u.commandResults[0].returnValues[0].bcs)),f=A.U64.parse(new Uint8Array(u.commandResults[1].returnValues[0].bcs)),p=c?o?d:f:A.U64.parse(new Uint8Array(u.commandResults[2].returnValues[0].bcs));return{[r]:d.toString(),[s]:f.toString(),[this.deepCoin.coinType]:p.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.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:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:c=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:d})=>f=>{f.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[f.object(n),f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(u),f.object(d),f.object(i),f.object(o),f.object(a),f.object.clock()],typeArguments:[r.coinType,s.coinType]})};async getManagerState(e,n=new Y){let{account:r,marginManager:s,baseCoin:i,quoteCoin:o,pool:a,baseMarginPool:c,quoteMarginPool:u,decimals:d=6}=e;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 f=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],n),p=f.get(i.feed),m=f.get(o.feed);if(!p||!m)throw new Error("Failed to get price feed object IDs");n.add(this.managerState({...e,basePriceFeedObjectId:p,quotePriceFeedObjectId:m}));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 v=Q(A.Address.parse(new Uint8Array(b.commandResults[0].returnValues[0].bcs))),T=Q(A.Address.parse(new Uint8Array(b.commandResults[0].returnValues[1].bcs))),O=Number(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[2].bcs)))/1e9,B=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[3].bcs))),i.scalar,d),C=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[4].bcs))),o.scalar,d),U=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[5].bcs))),i.scalar,d),L=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[6].bcs))),o.scalar,d),P=A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[7].bcs)),q=Number(A.u8().parse(new Uint8Array(b.commandResults[0].returnValues[8].bcs))),V=A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[9].bcs)),F=Number(A.u8().parse(new Uint8Array(b.commandResults[0].returnValues[10].bcs))),X=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[11].bcs))),ee=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[12].bcs))),j=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[13].bcs)));return{managerId:v,deepbookPoolId:T,riskRatio:O,baseAsset:B,quoteAsset:C,baseDebt:U,quoteDebt:L,basePythPrice:P.toString(),basePythDecimals:q,quotePythPrice:V.toString(),quotePythDecimals:F,currentPrice:X,lowestTriggerAbovePrice:ee,highestTriggerBelowPrice:j}}catch(f){throw new Error(`Failed to get manager state: ${f instanceof Error?f.message:String(f)}`)}}async detectPriceBoundary({account:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,price:c,is_bid:u,decimals:d=6}){if(!e||!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 f=typeof c=="bigint"?c:BigInt(c),p=await this.getManagerState({account:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:d},new Y),m=p.highestTriggerBelowPrice,b=p.lowestTriggerAbovePrice,v=u?f<=b:f>=m;return{is_bid:u,price:f,lower_bound:m,upper_bound:b,is_within:v,is_boundary:u?f===b:f===m}}async calculateAssets({account:e,marginManager:n,pool:r,baseCoin:s,quoteCoin:i,tx:o=new Y}){if(!e||!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,e);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=A.U64.parse(new Uint8Array(c)),f=A.U64.parse(new Uint8Array(u));return{baseAsset:d.toString(),quoteAsset:f.toString(),tx:o}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){if(!e||!n||!r||!s||!i||!o)throw new Error("All parameters are required");try{let{baseBorrowedShare:a,quoteBorrowedShare:c}=await this.getBorrowedShares({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}),u=!!M(a).gt(M(c)),d=u?i:o,f=u?a:c,p=new Y;p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[p.object(d),p.pure.u64(BigInt(f)),p.object.clock()],typeArguments:[u?r:s]});let m=await this.sdk.fullClient.simulateTransaction({transaction:p,checksEnabled:!1,include:{commandResults:!0,json:!0}}),b=A.U64.parse(m?.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:e,baseCoin:n,quoteCoin:r,amount:s,depositCoinType:i},o=new Y){if(!e)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=Wt.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 e=="string"?o.object(e):e,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:e,marginManager:n,baseMarginPool:r,quoteMarginPool:s,baseCoin:i,quoteCoin:o,pool:a,amount:c,withdrawCoinType:u},d=new Y){if(!e||!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 f=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],d),p=f.get(i.feed),m=f.get(o.feed);if(!p||!m)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(p),d.object(m),d.object(a),d.pure.u64(BigInt(c)),d.object(he)],typeArguments:[i.coinType,o.coinType,u]});if(Wt.isSuiCoin(u))d.transferObjects([b],e);else{let v=await this._sdk.fullClient.getOwnerCoinAssets(e,u),T=Wt.buildCoinForAmount(d,v,BigInt(0),u,!1);T.target_coin?(d.mergeCoins(T.target_coin,[b]),T.is_mint_zero_coin&&d.transferObjects([T.target_coin],e)):d.transferObjects([b],e)}return d}catch(f){throw new Error(`Failed to withdraw: ${f instanceof Error?f.message:String(f)}`)}}async borrowBase({marginManager:e,baseMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new Y){if(!e||!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(e),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:e,quoteMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new Y){if(!e||!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 e=="string"?a.object(e):e,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:e,baseMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new Y){if(!e||!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:e,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(e),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:e,quoteMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new Y){if(!e||!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:e,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(e),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:e,baseMarginPool:n,quoteMarginPool:r,baseCoin:s,quoteCoin:i,isBase:o,amount:a},c=new Y){try{let u=this.sdk.senderAddress,d,f=a;a||(d=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType,baseMarginPool:n,quoteMarginPool:r}),f=o?d.baseBorrowedAmount:d.quoteBorrowedAmount);let p,m={marginManager:e,baseCoin:s,quoteCoin:i,depositCoinType:o?s.coinType:i.coinType};if(o){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});p=M(f).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});p=M(f).sub(b).toString()}M(p).gt(0)&&await this.deposit({...m,amount:p},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(e),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=(e,n,r,s,i=new Y)=>{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 e=="string"?i.object(e):e,o]})};async#e(e,n,r){if(!e.feed||!n.feed)throw new Error("Base and quote coin feeds are required");let s=await this.pythPrice.updatePythPriceIDs([e.feed,n.feed],r),i=s.get(e.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:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u,exactBase:d,referralKey:f},p=new Y){if(!e||!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(yi(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(yi(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:m,baseCoin:b,quoteCoin:v}=n;if(b.decimals===void 0||v.decimals===void 0)throw new Error("Base and quote coin decimals are required");f&&this.removeReferralKey(e,m,b.coinType,v.coinType,p);try{let{baseOracle:T,quoteOracle:O}=await this.#e(b,v,p);return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order_v2`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?p.object(e):e,p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(m),p.object(r),p.object(s),p.object(T),p.object(O),p.pure.u8(i),p.pure.u64(o),p.pure.bool(c),p.pure.bool(u),p.pure.bool(d===void 0?!c:d),p.pure.u64(a),p.object(he)],typeArguments:[b.coinType,v.coinType]}),p}catch(T){throw new Error(`Failed to place market order: ${T instanceof Error?T.message:String(T)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:f=Date.now()+31536e8,referralKey:p},m=new Y){if(!e||!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:v,quoteCoin:T}=n;if(v.decimals===void 0||T.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let O=BigInt(M(a).mul(10**(T.decimals-v.decimals+9)).toString()),B=BigInt(yi(c,v.decimals));if(O<=0n||B<=0n)throw new Error("Price and quantity must be greater than zero");p&&this.removeReferralKey(e,b,v.coinType,T.coinType,m);let{baseOracle:C,quoteOracle:U}=await this.#e(v,T,m);return m.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order_v2`,arguments:[m.object(this.sdk.sdkOptions.margin_utils.global_config_id),m.object(this.sdk.sdkOptions.margin_utils.versioned_id),m.object(e),m.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),m.object(b),m.object(r),m.object(s),m.object(C),m.object(U),m.pure.u8(i),m.pure.u8(o),m.pure.u64(O),m.pure.u64(B),m.pure.bool(u),m.pure.bool(d),m.pure.u64(f),m.object(he)],typeArguments:[v.coinType,T.coinType]}),m}catch(O){throw new Error(`Failed to place limit order: ${O instanceof Error?O.message:String(O)}`)}}modifyMarginOrder({marginManager:e,poolInfo:n,orderId:r,newQuantity:s},i=new Y){if(!e||!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(yi(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(e),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:e,poolInfo:n,orderId:r},s=new Y){if(!e||!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(e),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:e,poolInfo:n},r=new Y){if(!e||!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(e),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:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:f=Date.now()+31536e8},p=new Y){if(!e||!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:m,quoteCoin:b}=n;if(m.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let v=BigInt(M(a).mul(10**(b.decimals-m.decimals+9)).toString()),T=BigInt(yi(c,m.decimals));if(v<=0n||T<=0n)throw new Error("Price and quantity must be greater than zero");let{baseOracle:O,quoteOracle:B}=await this.#e(m,b,p);return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order_v2`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(n.id),p.object(r),p.object(s),p.object(O),p.object(B),p.pure.u8(i),p.pure.u8(o),p.pure.u64(v),p.pure.u64(T),p.pure.bool(u),p.pure.bool(d),p.pure.u64(f),p.object(he)],typeArguments:[m.coinType,b.coinType]}),p}catch(v){throw new Error(`Failed to place reduce only limit order: ${v instanceof Error?v.message:String(v)}`)}}async placeReduceOnlyMarketOrder({marginManager:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u},d=new Y){if(!e||!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(yi(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(yi(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{baseCoin:f,quoteCoin:p}=n;if(f.decimals===void 0||p.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let{baseOracle:m,quoteOracle:b}=await this.#e(f,p,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(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(n.id),d.object(r),d.object(s),d.object(m),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:[f.coinType,p.coinType]}),d}catch(m){throw new Error(`Failed to place reduce only market order: ${m instanceof Error?m.message:String(m)}`)}}async getOpenOrder(e,n,r,s,i=!1,o=new Y){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::account_open_orders`,arguments:[o.object(e.address),i?r:o.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.simulateTransaction({transaction:o,include:{commandResults:!0,json:!0},checksEnabled:!1})).commandResults[i?1:0].returnValues[0].bcs;a=A.struct("VecSet",{constants:A.vector(A.U128)}).parse(new Uint8Array(p)).constants}if(a.length===0)return[];let c=a.map(f=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:f})),u=await this.sdk.DeepbookUtils.getOrderInfoList(c,n)||[],d=[];return u.forEach(f=>{let p=this.sdk.DeepbookUtils.decodeOrderId(BigInt(f.order_id));d.push({...f,price:p.price,isBid:p.isBid,pool:e})}),d}async getAccountOpenOrders({poolInfo:e,marginManager:n}){try{let r=new Y,s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(n)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.getOpenOrder(e,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(e,n){try{if(!e||!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 Y,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(e=new Y,n){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(he)]});return n&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:n,amount:r}){let s=new Y,{supplierCap:i}=this.mintSupplierCap(s,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:n,amount:r,tx:s}),s.transferObjects([i],this.sdk.senderAddress),s}supply({marginPool:e,supplierCap:n,supplyCoinType:r,amount:s,tx:i}){let o=i??new Y;if(!n)throw new Error("Either supplierCap must be provided");let a=Wt.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(e),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:e,withdrawCoinType:n,amount:r,supplierCapId:s,hasSwap:i,withdrawAll:o,tx:a=new Y}){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(e),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:e}){let n=new Y,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(e),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:e,supplyCoin:n,supplierCapId:r}){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[n.coinType],arguments:[s.object(e),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(A.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:A.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:e}=await this.sdk.fullClient.listDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),n=e.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(fT(o))}return s}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFieldsByPage(this.sdk.sdkOptions.margin_utils.margin_pool_table_id),n=e.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(pT(u,s[c]))}return a}async getBaseQuantityIn(e,n,r,s=.01){let i=new Y;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_base_quantity_in`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[i.object(e.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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:c.toString(),quantityInLeft:M(a.toString()).mul(M(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(e,n,r,s=.01){let i=new Y;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_in`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[i.object(e.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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:a.toString(),quantityInLeft:M(c.toString()).mul(M(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(e,n,r){let s=new Y;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.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=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=A.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(e,n,r){let s=new Y;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.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=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=A.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(e,n,r=new Y){let s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i=[n];for(let d=0;d<i.length;d++){let f=i[d];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(f.address),typeof s=="string"?r.object(s):s],typeArguments:[f.baseCoin.coinType,f.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,f)=>{c=d?.json;let p=c.account.open_orders.contents,m=c.account.owed_balances,b=c.account.settled_balances,v=c.account.unclaimed_rebates,T=c.account.taker_volume;u.push({balance_manager_id:s,open_orders:p,owed_balances:m,settled_balances:b,unclaimed_rebates:v,taker_volume:T,poolInfo:i[f]})}),u}async withdrawSettledAmounts({poolInfo:e,marginManager:n},r=new Y){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(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#t(e,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=e/s,o=e%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(e){if(!e)throw new Error("marginPoolId is required");let n=await this.sdk.fullClient.getObject({objectId:e,include:{json:!0}});if(!n?.object?.json)throw new Error(`Failed to fetch margin pool: ${e}`);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(e){if(!e||e.length===0)throw new Error("marginPoolIds is required");let n=await this.sdk.fullClient.batchGetObjects(e,{json:!0}),r=[];return e.forEach((i,o)=>{let a=n[o];if(a){let c=a.json.state,u=a.json.config,d=u.interest_config,f=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(f.protocol_spread),max_utilization_rate:BigInt(f.max_utilization_rate),min_borrow:BigInt(f.min_borrow),supply_cap:BigInt(f.supply_cap)}})}}),{poolStateObj:Object.fromEntries(e.map((i,o)=>[i,r[o]])),poolStateList:r}}async getChainTimestamp(){let{response:e}=await this.sdk.fullClient.ledgerService.getServiceInfo({}),n=e.timestamp;if(!n)throw new Error("No timestamp in service info");return BigInt(n.seconds)*1000n+BigInt(n.nanos)/1000000n}async batchGetBorrowedShares({account:e,marginManagerList:n}){let r=new Y;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,e)).commandResults.map((i,o)=>{let a=A.U64.parse(new Uint8Array(i.returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(i.returnValues[1].bcs));return{marginManagerId:n[o].marginManagerId,baseBorrowedShare:a,quoteBorrowedShare:c}})}async betchGetOpenOrders({account:e,marginManagerList:n},r=new Y,s=!1){n.forEach(m=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(b)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let i=await this.sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,commandResults:!0,json:!0}}),o=i.Transaction?.events.map((m,b)=>({marginManagerId:n[b].marginManagerId,...m?.json?.account?.settled_balances||{}})),a=i.commandResults.filter((m,b)=>(b-1)%4===0),c=A.struct("VecSet",{constants:A.vector(A.U128)}),u=[];a.forEach((m,b)=>{let v=c.parse(m.returnValues[0].bcs).constants;v.length>0&&v.forEach(T=>{u.push({pool:{pool_id:n[b].poolId,baseCoinType:n[b].baseCoinType,quoteCoinType:n[b].quoteCoinType},marginManagerId:n[b].marginManagerId,orderId:T})})});let d=i.commandResults.filter((m,b)=>(b-3)%4===0),f=[];d.forEach((m,b)=>{f.push({marginManagerId:n[b].marginManagerId,base:A.U64.parse(m.returnValues[0].bcs),quote:A.U64.parse(m.returnValues[1].bcs),deep:A.U64.parse(m.returnValues[2].bcs)})});let p=[];return u.forEach((m,b)=>{let v=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId));p.push({...m,price:v.price.toString(),isBid:v.isBid})}),{openOrders:p,settledBalances:o,lockedBalances:f}}async getAllPosRelevantData({account:e,marginManagerList:n}){try{let{openOrders:r,settledBalances:s,lockedBalances:i}=await this.betchGetOpenOrders({account:e,marginManagerList:n}),o=await this.batchGetBorrowedShares({account:e,marginManagerList:n}),a=new Y,c=0,u=[];n.forEach(p=>{a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"base_balance",marginManagerId:p.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"quote_balance",marginManagerId:p.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"deep_balance",marginManagerId:p.marginManagerId},c++;let m=o?.find(b=>b.marginManagerId===p.marginManagerId);if(m&&(Number(m.baseBorrowedShare)>0||Number(m.quoteBorrowedShare)>0)){let b=m.baseBorrowedShare,v=m.quoteBorrowedShare,T=!!M(b).gt(M(v)),O=T?p.baseMarginPool:p.quoteMarginPool,B=T?b:v;a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_pool::borrow_shares_to_amount`,arguments:[a.object(O),a.pure.u64(BigInt(B)),a.object.clock()],typeArguments:[T?p?.baseCoinType:p?.quoteCoinType]}),u[c]={type:T?"borrow_base_amount":"borrow_quote_amount",marginManagerId:p.marginManagerId},c++}}),nT(a);let d=await this.sdk.fullClient.simulateTransaction({transaction:a,checksEnabled:!1,include:{commandResults:!0,events:!0,json:!0}}),f=Object.fromEntries(n.map(p=>[p.marginManagerId,{...p,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((p,m)=>{let b=u[m],v=A.U64.parse(new Uint8Array(p.returnValues[0].bcs));f[b.marginManagerId]={...f[b.marginManagerId],[b.type]:v}}),r?.forEach(p=>{f[p.marginManagerId].open_orders.push(p)}),s?.forEach(p=>{f[p.marginManagerId].settled_balances=p}),i?.forEach(p=>{f[p.marginManagerId].locked_balances=p}),Object.values(f)?.forEach(p=>{p.locked_balances&&p.settled_balances&&(p.locked_balances={...p.locked_balances,base:M(p.locked_balances.base||"0").minus(M(p.settled_balances.base||"0")).toString(),quote:M(p.locked_balances.quote||"0").minus(M(p.settled_balances.quote||"0")).toString(),deep:M(p.locked_balances.deep||"0").minus(M(p.settled_balances.deep||"0")).toString()})}),f}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(e,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:f,pending_order:p,is_trigger_below_price:m,trigger_price:b}=e,v=await this.pythPrice.updatePythPriceIDs([u.feed,d.feed],n),T=v.get(u.feed),O=v.get(d.feed);if(!T||!O)throw new Error("Failed to get price feed object IDs");let B=n.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[n.pure.bool(m),n.pure.u64(b)]}),C=this.newPendingOrder(p,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(T),n.object(O),n.object(o),typeof f=="string"?n.pure.u64(BigInt(f)):f,B,C,n.object(cd)],typeArguments:[u.coinType,d.coinType]})}newPendingOrder(e,n){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in e){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:f}=e;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(f)]})}else{let{client_order_id:s,self_matching_option:i,quantity:o,is_bid:a,pay_with_deep:c}=e;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(e,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}=e;n.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[n.object(s),n.object(i),n.object(o),n.object(cd)],typeArguments:[a,c]})}cancelConditionalOrders(e,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}=e;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(cd)],typeArguments:[a,c]})}async getConditionalOrders(e,n){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(u=>{let{margin_manager_id:d,base_coin_type:f,quote_coin_type:p,conditional_order_ids:m}=u;m.forEach(b=>{n.moveCall({target:`${r.margin_published_at}::margin_manager::conditional_order`,arguments:[n.object(d),n.pure.u64(b)],typeArguments:[f,p]})})});let s=await this.sdk.fullClient.sendSimulationTransaction(n,Q("0x0"));if(!s?.commandResults)return[];let i=A.struct("Condition",{trigger_below_price:A.bool(),trigger_price:A.u64()}),o=A.struct("PendingOrder",{is_limit_order:A.bool(),client_order_id:A.u64(),order_type:A.option(A.u8()),self_matching_option:A.u8(),price:A.option(A.u64()),quantity:A.u64(),is_bid:A.bool(),pay_with_deep:A.bool(),expire_timestamp:A.option(A.u64())}),a=A.struct("ConditionalOrder",{conditional_order_id:A.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,f=c(d);if(!f)return null;let p=this.normalizeConditionalOrder(f);return e.forEach(m=>{m.conditional_order_ids.find(v=>v===p.conditional_order_id)&&(p.margin_manager_id=m.margin_manager_id,p.base_coin_type=m.base_coin_type,p.quote_coin_type=m.quote_coin_type)}),p}catch{return null}})}async getConditionalOrderIds(e,n){n=n||new Y;let{deepbook:r}=this.sdk.sdkOptions,s={};return e.forEach(o=>{let{margin_manager_id:a,base_coin_type:c,quote_coin_type:u}=o;n.moveCall({target:`${r.margin_published_at}::margin_manager::conditional_order_ids`,arguments:[n.object(a)],typeArguments:[c,u]})}),(await this.sdk.fullClient.sendSimulationTransaction(n,Q("0x0"))).commandResults.forEach((o,a)=>{if(o?.returnValues?.[0]?.bcs){let c=new Uint8Array(o.returnValues[0].bcs),u=A.vector(A.u64()).parse(c),d={margin_manager_id:e[a].margin_manager_id,base_coin_type:e[a].base_coin_type,quote_coin_type:e[a].quote_coin_type,conditional_order_ids:u.map(f=>f.toString())};s[e[a].margin_manager_id]=d}}),s}normalizeConditionalOrder(e){let n=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",conditional_order_id:n(e.conditional_order_id),condition:{trigger_below_price:e.condition.trigger_below_price,trigger_price:n(e.condition.trigger_price)},pending_order:{is_limit_order:e.pending_order.is_limit_order,client_order_id:n(e.pending_order.client_order_id),order_type:e.pending_order.order_type,self_matching_option:e.pending_order.self_matching_option,price:e.pending_order.price,quantity:n(e.pending_order.quantity),is_bid:e.pending_order.is_bid,pay_with_deep:e.pending_order.pay_with_deep,expire_timestamp:e.pending_order.expire_timestamp}}}async getPoolsPriceBounds(e){if(!e?.length)throw new Error("poolInfos is required");for(let p of e){if(!p.poolId||!p.baseCoin?.coinType||!p.quoteCoin?.coinType)throw new Error("poolId, baseCoin.coinType and quoteCoin.coinType are required");if(!p.baseCoin?.feed||!p.quoteCoin?.feed)throw new Error("baseCoin.feed and quoteCoin.feed are required to refresh pool price")}let n=new Y,r=[...new Set(e.flatMap(p=>[p.baseCoin.feed,p.quoteCoin.feed]))],s=await this.pythPrice.updatePythPriceIDs(r,n),i=this.sdk.sdkOptions.margin_utils.margin_registry_id,o=this.sdk.sdkOptions.deepbook.margin_published_at;for(let p of e){let m=s.get(p.baseCoin.feed),b=s.get(p.quoteCoin.feed);if(!m||!b)throw new Error(`Failed to get price feed object IDs for pool ${p.poolId}`);n.moveCall({target:`${o}::pool_proxy::update_current_price`,arguments:[n.object(i),n.object(p.poolId),n.object(m),n.object(b),n.object(he)],typeArguments:[p.baseCoin.coinType,p.quoteCoin.coinType]}),n.moveCall({target:`${o}::margin_registry::get_price_bounds`,arguments:[n.object(i),n.pure.id(p.poolId),n.object(he)]})}let a=await this.sdk.fullClient.simulateTransaction({transaction:n,checksEnabled:!1,include:{commandResults:!0,json:!0}});if(a?.$kind==="FailedTransaction"||!a?.commandResults?.length){let p=a?.FailedTransaction?.status?.error;throw new Error(`Failed to get pools price bounds: ${p?.message??JSON.stringify(p??"Unknown error")}`)}let c=a.commandResults.filter(p=>p?.returnValues?.length===2);if(c.length<e.length)throw new Error(`Failed to get pools price bounds: expected ${e.length} results, got ${c.length}`);let u=[],d=c.slice(-e.length);for(let p=0;p<e.length;p++){let m=d[p],b=m?.returnValues?.[0]?.bcs??m?.returnValues?.[0]?.[0],v=m?.returnValues?.[1]?.bcs??m?.returnValues?.[1]?.[0];if(!b||!v)throw new Error(`Failed to parse price bounds for pool ${e[p].poolId}`);let T=9-e[p].baseDecimals+e[p].quoteDecimals,O=A.U64.parse(new Uint8Array(b)),B=A.U64.parse(new Uint8Array(v));u.push({pool_id:e[p].poolId,lower_bound:M(O).div(10**T).toString(),upper_bound:M(B).div(10**T).toString()})}let f=new Map;return u.forEach(p=>{f.set(p.pool_id,p)}),{priceBounds:u,priceBoundsMap:f}}};var tN="https://graphql.mainnet.sui.io/graphql",nN="https://graphql.testnet.sui.io/graphql",ld=class{_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=Em(new Ja({baseUrl:e.fullRpcUrl,network:e.network==="testnet"?"testnet":"mainnet"}),new em({network:e.network,url:e.network==="testnet"?nN:tN}),e.network==="testnet"?"testnet":"mainnet",new Lh({url:e.fullRpcUrl,network:e.network})),this._deepbookUtils=new ad(this),this._marginUtils=new ud(this),this._pythPrice=new ya(this),Nm(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}};var rN=(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))(rN||{}),sN=(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))(sN||{});var tK=ld;export{cd as CLOCK_ADDRESS,od as CachedContent,ld as CetusClmmSDK,zZ as ClmmExpectSwapModule,HZ as ClmmFetcherModule,FZ as ClmmIntegratePoolModule,qZ as ClmmIntegratePoolV2Module,$Z as ClmmIntegrateRouterModule,GZ as ClmmIntegrateRouterWithPartnerModule,WZ as ClmmIntegrateUtilsModule,Wt as CoinAssist,ZZ as CoinInfoAddress,JZ as CoinStoreAddress,Dm as DEEP_SCALAR,eZ as DEFAULT_GAS_BUDGET_FOR_MERGE,QW as DEFAULT_GAS_BUDGET_FOR_SPLIT,rZ as DEFAULT_GAS_BUDGET_FOR_STAKE,tZ as DEFAULT_GAS_BUDGET_FOR_TRANSFER,nZ as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,iZ as DEFAULT_NFT_TRANSFER_GAS_FEE,YZ as DeepbookClobV2Moudle,KZ as DeepbookCustodianV2Moudle,XZ as DeepbookEndpointsV2Moudle,ad as DeepbookUtilsModule,eJ as ERROR_HANDLING_RPC_LIST,Cr as FLOAT_SCALAR,es as FLOAT_SCALING,sZ as GAS_SYMBOL,Rm as GAS_TYPE_ARG,X_ as GAS_TYPE_ARG_LONG,ud as MarginUtilsModule,GW as NORMALIZED_SUI_COIN_TYPE,rN as OrderType,oZ as SUI_SYSTEM_STATE_OBJECT_ID,sN as SelfMatchingOption,J3 as YEAR_MS,Z_ as addHexPrefix,mZ as asIntN,hZ as asUintN,MW as bufferToHex,Q_ as cacheTime1min,ga as cacheTime24h,eT as cacheTime5min,aJ as calc100PercentRepay,X3 as calcDebtDetail,Y3 as calcInterestRate,K3 as calcUtilizationRate,iJ as calculateRiskRatio,BW as checkAddress,K_ as composeType,M as d,Bm as decimalsMultiplier,tK as default,qW as extractAddressFromType,gi as extractStructTagFromType,$W as fixCoinType,yo as fixDown,L3 as fixSuiObjectId,bo as fromDecimalsAmount,QZ as getDefaultSuiInputType,jm as getFutureTime,G3 as getMoveObject,V3 as getObjectDeletedResponse,cT as getObjectFields,aT as getObjectId,F3 as getObjectNotExistsResponse,q3 as getObjectReference,oT as getSuiObjectData,jW as hexToNumber,DW as hexToString,FW as isSortedSymbols,_Z as isSuiObjectResponse,Mm as maxDecimal,hT as mulRoundUp,Cm as normalizeCoinType,Nm as patchFixSuiObjectId,nT as printTransaction,Am as removeHexPrefix,gZ as secretKeyToEd25519Keypair,yZ as secretKeyToSecp256k1Keypair,RW as shortAddress,B3 as shortString,tT as sleepTime,M3 as toBuffer,yi as toDecimalsAmount,j3 as utf8to16,pT as wrapDeepBookMarginPoolInfo,fT as wrapDeepBookPoolInfo};
1024
+ `);var T3=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];var iW=jl("mainnet"),oW=jl("testnet");var aW=A.struct("Table<ID, bool>",{id:A.Address,size:A.u64()}),k3=A.struct("TypeName",{name:A.string()}),cW=A.struct("OptionU64",{is_none:A.bool(),v:A.u64()}),E3=A.struct("UID",{id:A.Address}),uW=A.struct("TableSuiRaw",{id:E3,size:A.u64()});var S3=class{constructor(t,e,n,r){this._cache={},this._env="mainnet",this._client=t,this._env=n||"mainnet",this._graphQLClient=e,this._jsonRpcClient=r}async fetchCoinMetadata(t){let e=`coin_metadata_${t}`,n=this.getCache(e);if(n)return n;let r=await this._client.getCoinMetadata({coinType:t});return this.updateCache(e,r.coinMetadata),r.coinMetadata}async fetchCoinMetadataId(t){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let e=`coin_metadata_id_${t}`,n=this.getCache(e);if(n)return n;let r=(await this._graphQLClient.query({query:y3,variables:{coinType:`0x2::coin::CoinMetadata<${t}>`}})).data?.objects?.nodes?.[0]?.address??null;return r&&this.updateCache(e,r),r}async getSuiTransactionResponse(t){try{return await this._client.getTransaction({digest:t,include:{effects:!0,events:!0,balanceChanges:!0,transaction:!0,objectTypes:!0}})}catch(e){throw console.log("getSuiTransactionResponse error",e),e}}async getTransactionByGraphQL(t){try{return await this._graphQLClient.query({query:b3,variables:{digest:t}})}catch(e){throw console.log("getTransactionByGraphQL error",e),e}}async queryEventsByGraphQL(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:v3,variables:{type:t,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(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");if(!(t.sentAddress!=null||t.affectedAddress!=null||t.affectedObject!=null||t.function!=null))throw new Error("At least one of sentAddress, affectedAddress, affectedObject, function is required");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0,a={};t.sentAddress&&(a.sentAddress=Q(t.sentAddress)),t.affectedAddress&&(a.affectedAddress=Q(t.affectedAddress)),t.affectedObject&&(a.affectedObject=Q(t.affectedObject)),t.function&&(a.function=t.function);do{let c=(await this._graphQLClient.query({query:_3,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(t,e="all"){let n=[],r=!0,s=e==="all",i=s?null:e.cursor;do{let o=await this._jsonRpcClient.queryEvents({query:t,cursor:i,limit:s?null:e.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(t,e,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:t,type:e,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 T3)try{let c=Em(new Ja({baseUrl:a,network:o}),this._graphQLClient,this._env);return await r(c._client)}catch(c){i=c;continue}throw i}}async getAllDynamicFields(t,e="all"){if(!this._graphQLClient)throw new Error("graphQLClient is not set");let n=e==="all",r=n?50:e.limit??50,s=[],i=n?null:e.cursor??null,o=!0;do{let a=(await this._graphQLClient.query({query:w3,variables:{id:Q(t),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(t,e="all"){let n=[],r=!0,s=e==="all",i=s?null:e.cursor;do{let o=await this._client.listDynamicFields({parentId:t,cursor:i??void 0,limit:s?1e3:e.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(t,e,n,r,s){let i=e.map(o=>g3(t,o,n,r));return i.length===0?[]:this.batchGetObjects(i,s)}async batchGetObjects(t,e,n=1e3){let r=[];try{for(let s=0;s<Math.ceil(t.length/n);s++){let i=t.slice(s*n,n*(s+1)),o=await this._client.getObjects({objectIds:i,include:e});r=[...r,...o.objects]}}catch(s){console.log(s)}return r}async calculationTxGas(t){let e=t.getData?.()?.sender??t.blockData?.sender;if(e==null)throw Error("sdk sender is empty");t.setSender(e);let n=await this._client.simulateTransaction({transaction:t,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(t,e){try{return await this._client.signAndExecuteTransaction({transaction:e,signer:t,include:{effects:!0,events:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(t,e,n=!0){try{return t.setSender(e),await this._client.simulateTransaction({transaction:t,include:{events:!0,balanceChanges:!0,effects:!0,objectChanges:!0,commandResults:!0},checksEnabled:n})}catch(r){throw console.log("simulateTransaction error",r),r}}async executeTx(t,e,n){try{if(n){let r=typeof t=="string"?Q(t):Q(t.getPublicKey().toSuiAddress());return await this.sendSimulationTransaction(e,r)}else{if(typeof t=="string")throw new Error("Cannot send transaction with string address - keypair required for signing");return await this.sendTransaction(t,e)}}catch(r){return r}}async getOwnerCoinAssets(t,e){let n=[],r=null;if(e)for(;;){let s=await this._client.listCoins({owner:t,coinType:e,cursor:r??void 0});for(let i of s.objects)BigInt(i.balance)>0&&n.push({coin_type:go(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:t,cursor:s??void 0,include:{json:!0}});if(i.objects.forEach(o=>{let a=go(o.type);o.type.includes('"0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin')&&BigInt(o.balance)>0&&n.push({coin_type:Tm(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(t,e){if(e)return[(await this._client.getBalance({owner:t,coinType:e})).balance];let n=[],r=null;do{let s=await this._client.listBalances({owner:t,cursor:r??void 0});if(n.push(...s.balances),r=s.cursor??null,!s.hasNextPage)break}while(!0);return n}updateCache(t,e,n=864e5){let r=this._cache[t];r?(r.overdue_time=S_(n),r.value=e):r=new bC(e,S_(n)),this._cache[t]=r}getCache(t,e=!1){let n=this._cache[t],r=n?.isValid();if(!e&&r)return n.value;r||delete this._cache[t]}};function Em(t,e,n,r){let s=new S3(t,e,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 x3=Uc(Pc(),1);var pW=new x3.default(1e6),O3=(t=>(t[t.BelowRange=0]="BelowRange",t[t.InRange=1]="InRange",t[t.AboveRange=2]="AboveRange",t))(O3||{}),ym=10n,I3={pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",hermes_service_urls:[]},A3={"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 C3(t,e){if(!ym)throw new Error("oraclePriceMultiplierDecimal is required");if(t===0n)throw new Error("Invalid oracle price");if(e<0n){let n=10n**(ym- -e);return t*n}return t/10n**(e+ym)}var N_=16*1024,z_=class{constructor(t,e=I3){this.hasChangeConnection=!1,this.pythConfigs=e,this.fullClient=t;let n=[...e.hermes_service_urls];n.includes("https://hermes.pyth.network")||n.push("https://hermes.pyth.network"),this.hermesClients=n.map(r=>new Zl(r,{timeout:3e3}))}async getFeedInfoList(t){let e=t.map(n=>this.getFeedInfo(n,!1));return await Promise.all(e)}priceCheck(t,e=60){let n=Math.floor(Date.now()/1e3);if(!(Math.abs(n-t.last_update_time)>e))return t}async getPackageId(t){let e=(await this.fullClient.getObject({objectId:t,include:{json:!0}}))?.object?.json;if(e?.upgrade_cap?.package)return e.upgrade_cap.package;throw new Error("upgrade_cap not found")}async getWormholePackageId(){let{wormhole_state_id:t}=this.pythConfigs,e=`getWormholePackageId_${t}`,n=this.fullClient.getCache(e);if(n)return n;let r=await this.getPackageId(this.pythConfigs.wormhole_state_id);return this.fullClient.updateCache(e,r),r}async getLatestPrice(t,e=!1){let n={},r=[];if(e?t.forEach(i=>{let o=this.fullClient.getCache(`getLatestPrice_${i}`);o&&this.priceCheck(o,60)?n[i]=o:r.push(i)}):r=[...t],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=Yl(a).mul(Yl(10).pow(Yl(c))).toString(),f=s[o],p={coin_type:f.coin_type,price:d,coin_decimals:f.coin_decimals,oracle_price:0n,last_update_time:u};p.oracle_price=C3(BigInt(a),BigInt(c)),n[r[o]]=p,this.fullClient.updateCache(`getLatestPrice_${p.coin_type}`,p)}}),n}async getPriceFeedsUpdateData(t){let e=null;for(let n of this.hermesClients)try{return(await n.getLatestPriceUpdates(t,{encoding:"hex"})).binary.data.map(r=>Buffer.from(r,"hex"))}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getPriceFeedsUpdateData ~ e:",r),e=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getPriceFeedsUpdateData Detailed error: ${e?.message}`)}async getLatestPriceFeeds(t){let e=null;for(let n of this.hermesClients)try{return await n.getLatestPriceUpdates(t,{parsed:!0})}catch(r){console.log("\u{1F680} ~ PythPriceModule ~ getLatestPriceFeeds ~ error:",r),e=r;continue}throw new Error(`All Pyth Hermes endpoints are unavailable. getLatestPriceFeeds Detailed error: ${e?.message}`)}extractVaaBytesFromAccumulatorMessage(t){let e=7+t.readUint8(6)+1,n=t.readUint16BE(e),r=e+2;return t.subarray(r,r+n)}async verifyVaas(t,e){let n=await this.getWormholePackageId(),r=[];for(let s of t){let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.pythConfigs.wormhole_state_id),e.pure(A.vector(A.u8()).serialize(Array.from(s),{maxSize:N_}).toBytes()),e.object(he)]});r.push(i)}return r}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=null,e=!0;for(;e;){let n=await this.fullClient.listDynamicFields({parentId:this.pythConfigs.pyth_state_id,cursor:t});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}}e=n.hasNextPage,t=n.cursor}}if(this.priceTableInfo===void 0)throw new Error(" getPriceTableInfo Price table not found");return this.priceTableInfo}async getPriceFeedObjectId(t){let e=t.replace("0x",""),n=`getPriceFeedObjectId_${e}`,r=this.fullClient.getCache(n);if(r)return r;let{id:s,fieldType:i}=await this.getPriceTableInfo(),o=A.struct("PriceIdentifier",{bytes:A.vector(A.u8())}).serialize({bytes:Array.from(Buffer.from(e,"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(t,e,n){if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([r],t),[i]=t.moveCall({target:`${n}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythConfigs.pyth_state_id),t.pure(A.vector(A.u8()).serialize(Array.from(e[0]),{maxSize:N_}).toBytes()),s[0],t.object(he)]});return i}async buildUpdatePythPricePayload(t,e,n){let{pyth_state_id:r,pyth_published_at:s,pyth_package_id:i}=this.pythConfigs,o=(await this.getFeedInfoList(t)).map(d=>d.price_feed_id);if(t.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(e,a,s),u=0;for(let d of o){let f=await this.getPriceFeedObjectId(d);if(!f)throw new Error(`Price feed ${d} not found, please create it first`);c=n({tx:e,coinType:t[u],priceUpdatesHotPotato:c,priceInfoObjectId:f}),u+=1}return e.moveCall({target:`${s}::hot_potato_vector::destroy`,arguments:[c],typeArguments:[`${i}::price_info::PriceInfo`]}),e}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=(await this.fullClient.getObject({objectId:this.pythConfigs.pyth_state_id,include:{json:!0}}))?.object?.json;if(!t)throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=Number(t.base_update_fee)}return this.baseUpdateFee}async updatePriceFeeds(t,e,n){let r=this.pythConfigs.pyth_package_id,s=await this.verifyVaasAndGetHotPotato(t,e,r),i=await this.getBaseUpdateFee(),o=t.splitCoins(t.gas,n.map(()=>t.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]=t.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[t.object(this.pythConfigs.pyth_state_id),s,t.object(d),o[c],t.object(he)]}),c++}return t.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[s],typeArguments:[`${r}::price_info::PriceInfo`]}),a}async buildUpdatePythPricePayloadV2(t,e,n){if(t.length===0)return e;let r=(await this.getFeedInfoList(t)).map(a=>a.price_feed_id);if(t.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(e,s,r),o=0;for(let a of i)n({tx:e,coinType:t[o],priceUpdatesHotPotato:{},priceInfoObjectId:a}),o+=1;return e}getFeedInfoByJson(t){let e=Tm(t,!1);return A3[e]}async getFeedInfo(t,e){let n=`getFeedInfo_${t}`,r=this.fullClient.getCache(n,e);if(r)return r;let s=this.getFeedInfoByJson(t);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:k3.serialize({name:Tm(t,!0)}).toBytes()}}),o=A.struct("OracleInfo",{price_feed_id:A.vector(A.U8),price_info_object_id:A.Address,last_update_time:A.u64(),coin_decimals:A.u8()}).parse(i.dynamicField.value.bcs),a={coin_type:t,price_feed_id:m3(o.price_feed_id),coin_decimals:o.coin_decimals};return console.log("\u{1F680} ~ PythPriceModule ~ getFeedInfo ~ info:",a),this.fullClient.updateCache(n,a),a}},ma=Uc(Pc(),1),mW=new ma.default(0),W_=new ma.default(1),Sm=new ma.default(2),gW=Sm.pow(new ma.default(128)),yW=Sm.pow(new ma.default(64)).sub(W_),bW=Sm.pow(new ma.default(128)).sub(W_);td.config({precision:64,rounding:td.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var wW=Uc(Pc(),1),vW=Uc(Pc(),1);var _W=Uc(Pc(),1);import{DeepBookClient as H3}from"@mysten/deepbook-v3";import{Base64 as z3}from"js-base64";var N3={REQUEST_PARAMS:"requestParams",METHOD_NAME:"methodName"},xm=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 xm&&n.code===r}},Vc=xm;An(Vc,"DETAILS_KEYS",N3);var Om=class extends Vc{constructor(e,n,r){super(e,n||"UnknownError",r)}static isCommonErrorCode(e,n){return this.isErrorCode(e,n)}};var Im=(t,e,n)=>{throw new Om(e,t,n)};var R3=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function Z_(t){return t.startsWith("0x")?t:`0x${t}`}function Am(t){return t.startsWith("0x")?`${t.slice(2)}`:t}function B3(t,e=4,n=4){let r=Math.max(e,1),s=Math.max(n,1);return`${t.slice(0,r+2)} ... ${t.slice(-s)}`}function RW(t,e=4,n=4){return B3(Z_(t),e,n)}function BW(t,e={leadingZero:!0}){if(typeof t!="string")return!1;let n=t;if(e.leadingZero){if(!t.startsWith("0x"))return!1;n=n.substring(2)}return R3.test(n)}function M3(t){if(!Buffer.isBuffer(t))if(Array.isArray(t))t=Buffer.from(t);else if(typeof t=="string")exports.isHexString(t)?t=Buffer.from(exports.padToEven(exports.stripHexPrefix(t)),"hex"):t=Buffer.from(t);else if(typeof t=="number")t=exports.intToBuffer(t);else if(t==null)t=Buffer.allocUnsafe(0);else if(t.toArray)t=Buffer.from(t.toArray());else throw new Error("invalid type");return t}function MW(t){return Z_(M3(t).toString("hex"))}function jW(t){let e=new ArrayBuffer(4),n=new DataView(e);for(let s=0;s<t.length;s++)n.setUint8(s,t.charCodeAt(s));return n.getUint32(0,!0)}function j3(t){let e,n,r,s,i;e="";let o=t.length;for(n=0;n<o;)switch(r=t.charCodeAt(n++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=t.charAt(n-1);break;case 12:case 13:s=t.charCodeAt(n++),e+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=t.charCodeAt(n++),i=t.charCodeAt(n++),e+=String.fromCharCode((r&15)<<12|(s&63)<<6|(i&63)<<0);break}return e}function DW(t){let e="",n=Am(t),r=n.length/2;for(let s=0;s<r;s++)e+=String.fromCharCode(Number.parseInt(n.substr(s*2,2),16));return j3(e)}var D3=0,Y_=1,U3=2;function J_(t,e){return t===e?D3:t<e?Y_:U3}function P3(t,e){let n=0,r=t.length<=e.length?t.length:e.length,s=J_(t.length,e.length);for(;n<r;){let i=J_(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,i!==0)return i}return s}function FW(t,e){return P3(t,e)===Y_}function K_(t,...e){let n=Array.isArray(e[e.length-1])?e.pop():[],s=[t,...e].filter(Boolean).join("::");return n&&n.length&&(s+=`<${n.join(", ")}>`),s}function qW(t){return t.split("::")[0]}function gi(t){try{let e=t.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let c={...gi(e),type_arguments:r.map(u=>gi(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>Wt.isSuiCoin(u)?u:gi(u).source_address),c.source_address=K_(c.full_address,c.type_arguments),c}let s=e.split("::"),o={full_address:e,address:e===Rm||e===X_?"0x2":$t(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=K_(o.full_address,o.type_arguments),o}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function Cm(t){return gi(t).source_address}function L3(t){return t.toLowerCase().startsWith("0x")?$t(t):t}var $W=(t,e=!0)=>{let n=t.split("::"),r=n.shift(),s=$t(r);return e&&(s=Am(s)),`${s}::${n.join("::")}`};function Nm(t){for(let e in t){let n=typeof t[e];if(n==="object")Nm(t[e]);else if(n==="string"){let r=t[e];t[e]=L3(r)}}}var GW=ye(Qn);import id from"decimal.js";function M(t){return id.isDecimal(t)?t:new id(t===void 0?0:t)}function Bm(t){return M(10).pow(M(t).abs())}var yo=(t,e)=>{try{return M(t).toDP(e,id.ROUND_DOWN).toString()}catch{return t}},Mm=(t,e)=>id.max(M(t),M(e));var QW=1e3,eZ=500,tZ=100,nZ=100,rZ=1e3,Rm="0x2::sui::SUI",X_="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",sZ="SUI",iZ=450,oZ="0x0000000000000000000000000000000000000005",at=class{static totalBalance(e,n){let r=BigInt(0);return e.forEach(s=>{n===s.coin_type&&(r+=BigInt(s.balance))}),r}static getCoinAssets(e,n){let r=[];return n.forEach(s=>{Cm(s.coin_type)===Cm(e)&&r.push(s)}),r}static isSuiCoin(e){return gi(e).full_address===Rm}static selectCoinObjectIdGreaterThanOrEqual(e,n,r=[]){let s=at.selectCoinAssetGreaterThanOrEqual(e,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(e,n,r=[]){let s=at.sortByBalance(e.filter(u=>!r.includes(u.coin_object_id))),i=at.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(p=>p.balance>=u);if(d!==-1){a.push(c[d]),c.splice(d,1);break}let f=c.pop();f.balance>0&&(a.push(f),o+=f.balance)}return{selected_coins:at.sortByBalance(a),remain_coins:at.sortByBalance(c)}}static sortByBalance(e){return e.sort((n,r)=>n.balance<r.balance?-1:n.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((n,r)=>n.balance>r.balance?-1:n.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((n,r)=>n+r.balance,BigInt(0))}static buildCoinForAmount(e,n,r,s,i=!0,o=!0){let a=at.getCoinAssets(s,n);if(r===BigInt(0))return this.buildZeroValueCoin(n,e,s,i);let c=at.calculateTotalBalance(a);if(c<r)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${r} `);return this.buildCoin(e,n,a,r,s,i,o)}static buildCoinWithBalance(e,n,r){return e===BigInt(0)&&at.isSuiCoin(n)?r.add(or({balance:e,useGasCoin:!1})):r.add(or({balance:e,type:n}))}static buildVectorCoin(e,n,r,s,i,o=!0){if(at.isSuiCoin(i)){let p=e.splitCoins(e.gas,[e.pure.u64(s)]);return{selected_coins:[],target_coin:p,remain_coins:n,target_coin_amount:s.toString(),is_mint_zero_coin:!1,original_spited_coin:e.gas}}let{original_spited_coin:a,target_coin:c,target_coin_amount:u,remain_coins:d,selected_coins:f}=this.buildSpitTargeCoin(e,s,r,o);return o?{target_coin:e.makeMoveVec({elements:[c]}),selected_coins:f,remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1,original_spited_coin:a}:{selected_coins:f,target_coin:e.makeMoveVec({elements:f.map(p=>e.object(p))}),remain_coins:d,target_coin_amount:u,is_mint_zero_coin:!1}}static buildOneCoin(e,n,r,s,i=!0){if(at.isSuiCoin(s)){if(r===0n&&n.length>1){let c=at.selectCoinObjectIdGreaterThanOrEqual(n,r);return{selected_coins:c.object_array,target_coin:e.object(c.object_array[0]),remain_coins:c.remain_coins,target_coin_amount:c.amount_array[0],is_mint_zero_coin:!1}}let o=at.selectCoinObjectIdGreaterThanOrEqual(n,r),a=e.splitCoins(e.gas,[e.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:e.gas}}return this.buildSpitTargeCoin(e,r,n,i)}static buildSpitTargeCoin(e,n,r,s){let i=at.selectCoinObjectIdGreaterThanOrEqual(r,n),o=i.amount_array.reduce((b,v)=>Number(b)+Number(v),0).toString(),a=i.object_array,[c,...u]=a,d=e.object(c),f=d,p=i.amount_array.reduce((b,v)=>Number(b)+Number(v),0).toString(),m;return u.length>0&&e.mergeCoins(d,u.map(b=>e.object(b))),s&&Number(o)>Number(n)&&(f=e.splitCoins(d,[e.pure.u64(n)]),m=d),{original_spited_coin:m,target_coin:f,target_coin_amount:p,remain_coins:i.remain_coins,selected_coins:i.object_array,is_mint_zero_coin:!1}}static buildCoin(e,n,r,s,i,o=!0,a=!0){return o?this.buildVectorCoin(e,n,r,s,i,a):this.buildOneCoin(e,r,s,i,a)}static buildZeroValueCoin(e,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:e,selected_coins:[],is_mint_zero_coin:!0,target_coin_amount:"0"}}static buildCoinForAmountInterval(e,n,r,s,i=!0,o=!0){let a=at.getCoinAssets(s,n);if(r.amount_first===BigInt(0))return a.length>0?this.buildCoin(e,[...n],[...a],r.amount_first,s,i,o):this.buildZeroValueCoin(n,e,s,i);let c=at.calculateTotalBalance(a);if(c>=r.amount_first)return this.buildCoin(e,[...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(e,[...n],[...a],r.amount_second,s,i,o)}static fromBalance(e,n,r){return r.moveCall({target:"0x2::coin::from_balance",typeArguments:[n],arguments:[e]})}static intoBalance(e,n,r){return r.moveCall({target:"0x2::coin::into_balance",typeArguments:[n],arguments:[typeof e=="string"?r.object(e):e]})}static mintBalanceZero(e,n){return n.moveCall({target:"0x2::balance::zero",typeArguments:[e],arguments:[]})}static destroyBalanceZero(e,n,r){return r.moveCall({target:"0x2::balance::destroy_zero",typeArguments:[n],arguments:[e]})}static getCoinAmountObjId(e,n){let r=e.amount_coin_array.find(s=>!s.used&&M(s.amount).eq(n)?(s.used=!0,!0):!1);return r?r.coin_object_id:Im("CoinNotFound",`Coin not found for ${n} ${e.coin_type}`)}static buildMultiCoinInput(e,n,r,s){let i=at.getCoinAssets(r,n);if(at.isSuiCoin(r)){let p=e.splitCoins(e.gas,s.map(b=>e.pure.u64(b)));return{amount_coin_array:s.map((b,v)=>({coin_object_id:p[v],amount:b.toString(),used:!1})),coin_type:r,remain_coins:i}}let o=s.reduce((p,m)=>p+m,BigInt(0)),a=at.selectCoinObjectIdGreaterThanOrEqual(i,o);if(a.object_array.length===0)return Im("InsufficientBalance",`No enough coins for ${r} expect ${o} actual ${at.calculateTotalBalance(i)}`);let[c,...u]=a.object_array;u.length>0&&e.mergeCoins(c,[...u]);let d=e.splitCoins(c,s.map(p=>e.pure.u64(p)));return{amount_coin_array:s.map((p,m)=>({coin_object_id:d[m],amount:p.toString(),used:!1})),remain_coins:a.remain_coins,coin_type:r}}},Wt=at;An(Wt,"callMintZeroValueCoin",(e,n)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[n]}));var Q_=6e4,eT=3e5,ga=864e5;function jm(t){return Date.parse(new Date().toString())+t}var od=class{overdueTime;value;constructor(e,n=0){this.overdueTime=n,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};function yi(t,e){let n=Bm(M(e));return Number(M(t).mul(n))}function hZ(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function mZ(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function bo(t,e){let n=Bm(M(e));return Number(M(t).div(n))}function gZ(t,e="hex"){if(t instanceof Uint8Array){let r=Buffer.from(t);return hl.fromSecretKey(new Uint8Array(r))}let n=e==="hex"?hn(t):ce(t);return hl.fromSecretKey(n)}function yZ(t,e="hex"){if(t instanceof Uint8Array){let r=Buffer.from(t);return xl.fromSecretKey(new Uint8Array(r))}let n=e==="hex"?hn(t):ce(t);return xl.fromSecretKey(n)}var tT=async t=>new Promise(e=>{setTimeout(()=>{e(1)},t)});async function nT(t,e=!0){t.getData().commands.forEach((n,r)=>{e&&console.log(`transaction ${r}: `,n)})}var rT={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},sT={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function iT(...t){console.log("DeepbookV3_Utils_Sdk###",...t)}function oT(t){return t.data}function V3(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let{error:e}=t;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function F3(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function q3(t){if("reference"in t)return t.reference;let e=oT(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:V3(t)}function aT(t){return"objectId"in t?t.objectId:q3(t)?.objectId??F3(t)}function _Z(t){return t.data!==void 0}function $3(t){return t.content!==void 0}function G3(t){let e="data"in t?oT(t):t;if(!(!e||!$3(e)||e.content.dataType!=="moveObject"))return e.content}function cT(t){let e=G3(t)?.fields;if(e)return"fields"in e?e.fields:e}var uT=A.struct("GetCetusBalanceManagerList",{owner:A.Address,cetus_balance_managers:A.vector(A.Address),deepbook_balance_managers:A.vector(A.Address)}),lT=A.struct("Account",{epoch:A.u64(),open_orders:A.vector(A.u128()),taker_volume:A.u128(),maker_volume:A.u128(),active_stake:A.u64(),inactive_stake:A.u64(),created_proposal:A.bool(),voted_proposal:A.option(A.Address),unclaimed_rebates:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()}),settled_balances:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()}),owed_balances:A.struct("Balances",{base:A.u64(),quote:A.u64(),deep:A.u64()})});var Dm=1e6,Cr=1e9,W3={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Z3={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},ad=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?Z3:W3}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new Y,n=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),n],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[n],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:n,amountToDeposit:r}){let s=new Y;s.setSenderIfNotSet(e);let i=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=or({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:e,balanceManager:n,coin:r,amountToDeposit:s,tx:i}){let o=i||new Y;if(n){o.setSenderIfNotSet(e);let a=or({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:e,balanceManager:n,coin:r,amountToWithdraw:s,returnAssets:i,txb:o}){let a=o||new Y,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(Wt.isSuiCoin(r.coinType))a.transferObjects([c],e);else{let u=await this._sdk.fullClient.getOwnerCoinAssets(e,r.coinType),d=Wt.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],e)):a.transferObjects([c],e)}return a}withdrawManagersFreeBalance({account:e,balanceManagers:n,tx:r=new Y}){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],e)});return r}async getBalanceManager(e,n=!0){let r=`getBalanceManager_${e}`,s=this.getCache(r,n);if(!n&&s!==void 0)return s;try{let i=new Y;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(e)],typeArguments:[]});let o=await this.sdk.fullClient.sendSimulationTransaction(i,e),c=(o?.Transaction??o?.FailedTransaction)?.events?.find(T=>T.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=uT.parse(new Uint8Array(c.bcs))?.deepbook_balance_managers||[],f=await this._sdk.fullClient.batchGetObjects(d,{json:!0}),p={};for(let T=0;T<f.length;T++){let O=f[T],B=O?.data?.objectId??O?.objectId,C=O?.json??O?.data?.content?.fields,U=C?.allow_listed?.fields?.contents??C?.allow_listed?.contents??C?.balance_manager?.allow_listed?.contents;B&&Array.isArray(U)&&U.length>0&&(p[B]=U)}let m=await this.batchGetObjectsByIdMap(p),b=Q(e),v=[];return d.forEach(T=>{let O=m[T]??[],B=O.filter(U=>{let L=this.getSuiObjectOwnerAddress(U);return L!==void 0&&Q(L)===b});O.length===0||B.length===O.length?v.push({balanceManager:T,cetusBalanceManager:"",capOk:!0}):v.push({balanceManager:T,cetusBalanceManager:"",capOk:!1})}),this.updateCache(r,v,864e5),v||[]}catch(i){throw i instanceof Error?i:new Error(String(i))}}async batchGetObjectsByIdMap(e){let n=Object.entries(e).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(e){let r=e?.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=e.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:e,balanceManager:n},r=new Y){let s=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::generate_proof_as_owner`,arguments:[r.object(n)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::withdraw_settled_amounts`,arguments:[r.object(e.address),r.object(n),s],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:n,coins:r}){try{let s=new Y;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,e),o={};return i?.commandResults?.forEach((a,c)=>{let u=r[c],d=a.returnValues[0]?.bcs,f=A.U64.parse(new Uint8Array(d)),p=M(f),m=p.eq(0)?"0":p.div(Math.pow(10,u.decimals)).toString();o[u.coinType]={adjusted_balance:m,balance:p.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:e,coins:n}){try{let r=new Y,s=await this.getBalanceManager(e,!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,e),o={};return s.forEach((a,c)=>{let u={},d=c*n.length;n.forEach((f,p)=>{let m=d+p,b=i.commandResults?.[m];if(b){let v=b.returnValues[0].bcs,T=A.U64.parse(new Uint8Array(v)),O=M(T),B=O.eq(0)?"0":O.div(Math.pow(10,f.decimals)).toString();u[f.coinType]={adjusted_balance:B,balance:O.toString()}}}),o[a.balanceManager]=u}),o}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let n=new Y;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[n.object(e.address),n.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=(await this._sdk.fullClient.sendSimulationTransaction(n,this._sdk.sdkOptions.simulationAccount.address)).commandResults[0]?.returnValues[0]?.bcs,i=Number(A.U64.parse(new Uint8Array(s))),o=Math.pow(10,e.baseCoin.decimals).toString(),a=Math.pow(10,e.quoteCoin.decimals).toString();return M(i).mul(o).div(a).div(Cr).toString()}catch(n){return iT("getMarketPrice ~ error:",n),"0"}}async getPools(e=!1){let n="Deepbook_getPools",r=this.getCache(n,e);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 f=u[1].split(", ");o.push({...c,baseCoinType:f[0],quoteCoinType:f[1]})}}),this.updateCache(n,o,864e5),o}async getQuoteQuantityOut(e,n,r){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(e.address),s.pure.u64(n),s.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:M(n).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:M(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(c).div(Dm).toString(),baseQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getBaseQuantityOut(e,n,r){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(e.address),s.pure.u64(n),s.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.sendSimulationTransaction(s,r),o=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs))),a=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs))),c=String(A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[2].bcs)));return{quoteQuantityDisplay:M(n).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:M(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(c).div(Dm).toString(),quoteQuantity:n,baseOut:o,quoteOut:a,deepRequired:c}}async getQuantityOut(e,n,r,s){let i=new Y;i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[i.object(e.address),i.pure.u64(n),i.pure.u64(r),i.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.sendSimulationTransaction(i,s),a=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs))),c=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs))),u=Number(A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs)));return{baseQuantityDisplay:M(n).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:M(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:M(a).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:M(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:M(u).div(Dm).toString(),baseQuantity:n,quoteQuantity:r,baseOut:a,quoteOut:c,deepRequired:u}}async getReferencePool(e){let n=await this.getPools(),r=e.baseCoin.coinType,s=e.quoteCoin.coinType,i=this._deep.coinType;for(let o=0;o<n.length;o++){let a=n[o];if(a.address===e.address)continue;let c=[a.baseCoinType,a.quoteCoinType];if(a.baseCoinType===i&&(c.includes(r)||c.includes(s)))return a}return null}async updateDeepPrice(e,n){let r=await this.getReferencePool(e);return r?(n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[n.object(e.address),n.object(r.pool_id),n.object(he)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),n):null}async estimatedMaxFee(e,n,r,s,i,o,a){let c=this.deepCoin;try{let{taker_fee:u,maker_fee:d}=e,f=M(u).div(Cr).toString(),p=M(d).div(Cr).toString(),m=await this.getMarketPrice(e);console.log("\u{1F680} ~ DeepbookUtilsModule ~ estimatedMaxFee ~ marketPrice:",m);let b=o?r:m!=="0"?m:a;if(b==="0")throw new Error("Cannot get market price");let v=Math.pow(10,e.baseCoin.decimals).toString(),T=Math.pow(10,e.quoteCoin.decimals).toString(),O=M(b).div(v).mul(T).mul(Cr).toString();if(s){let U=await this.getMarketPrice(e),P=M(o?r:U!=="0"?U:a).div(v).mul(T).mul(Cr).toString(),q=await this.getOrderDeepPrice(e);if(!q)throw new Error("Cannot get deep price");let V=Mm(P,r),F=M(n).mul(M(f)).mul(M(q.deep_per_asset)).div(M(Cr)),X=M(n).mul(M(p)).mul(M(q.deep_per_asset)).div(M(Cr));q.asset_is_base||(F=F.mul(V).div(M(Cr)),X=X.mul(V).div(M(Cr)));let ee=F.ceil().toString(),j=X.ceil().toString();return{takerFee:ee,makerFee:j,takerFeeDisplay:bo(ee,c.decimals).toString(),makerFeeDisplay:bo(j,c.decimals).toString(),feeType:c.coinType}}if(i){let U=Mm(O,o?r:m),L=M(n).mul(U).mul(M(f).mul(1.25)).div(M(Cr)).ceil().toFixed(0),P=M(n).mul(U).mul(M(p).mul(1.25)).div(M(Cr)).ceil().toFixed(0);return{takerFee:L,makerFee:P,takerFeeDisplay:bo(L,e.quoteCoin.decimals).toString(),makerFeeDisplay:bo(P,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let B=M(n).mul(M(f).mul(1.25)).ceil().toFixed(0),C=M(n).mul(M(p).mul(1.25)).ceil().toFixed(0);return{takerFee:B,makerFee:C,takerFeeDisplay:bo(B,e.baseCoin.decimals).toString(),makerFeeDisplay:bo(C,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(e,n=!0){let r=`getOrderDeepPrice_${e.address}}`,s=this.getCache(r);if(s!==void 0)return s;try{let i=new Y,o=!1;n&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,i)&&(o=!0),i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[i.object(e.address)],typeArguments:[e.baseCoin.coinType,e.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 tT(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let n=new DataView(e.buffer),r=n.getUint8(0)!==0,s=Number(n.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:s}}getCoinAssets(e,n,r){return Wt.buildCoinWithBalance(BigInt(M(n).abs().ceil().toString()),e,r)}async getTransactionRelatedBalance(e,n,r,s,i,o,a){let c=this.deepCoin;if(!a)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];s&&u.push(c);let d=await this.getManagerBalance({account:i,balanceManager:a,coins:u}),f=d?.[n]?.balance||"0",p=d?.[r]?.balance||"0",m=o&&d?.[c.coinType]?.balance||"0";return{baseManagerBlance:f,quoteManagerBlance:p,feeManaerBalance:m}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(e,n,r,s,i,o,a,c,u){let d=M(e).gt(0)&&c,f="0";if(!d)return{feeAsset:this.getEmptyCoin(u,n),haveDepositFee:"0"};if(o||a){let p=M(i).sub(o?s:r);f=p.lte(0)?e:p.sub(e).lt(0)?p.sub(e).toString():"0"}else f=M(i).sub(e).lt("0")?M(i).sub(e).abs().toString():"0";return{feeAsset:M(f).gt("0")?this.getCoinAssets(n,f,u):this.getEmptyCoin(u,n),haveDepositFee:f}}async getTransactionRelatedAssets(e,n,r,s,i,o,a,c,u){try{let d=this.deepCoin,f=ye(e.baseCoin.coinType),p=ye(e.quoteCoin.coinType),m=f===d.coinType,b=p===d.coinType,v=!m&&!b,{baseManagerBlance:T,quoteManagerBlance:O,feeManaerBalance:B}=await this.getTransactionRelatedBalance(e,f,p,v,o,a,c);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:T,quoteManagerBlance:O});let C,U,L=!1;if(i){a||(r=M(r).add(M(s)).toString());let q=M(O).sub(r).toString();M(q).lt(0)?(L=!0,U=this.getCoinAssets(p,q,u)):U=this.getEmptyCoin(u,p),C=this.getEmptyCoin(u,f)}else{a||(n=M(n).add(M(s)).toString());let q=M(T).sub(n).toString();M(q).lt(0)?(L=!0,C=this.getCoinAssets(f,q,u)):C=this.getEmptyCoin(u,f),U=this.getEmptyCoin(u,p)}let P=this.getFeeAsset(s,d.coinType,n,r,B,b,m,a,u);return{baseAsset:C,quoteAsset:U,feeAsset:P,haveDeposit:L}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getMarketTransactionRelatedAssets(e,n,r,s,i,o,a,c,u,d){try{let f=this.deepCoin,p=ye(e.baseCoin.coinType),m=ye(e.quoteCoin.coinType),b=p===f.coinType,v=m===f.coinType,T=!b&&!v,O=await this.getTransactionRelatedBalance(e,p,m,T,o,a,c),{feeManaerBalance:B}=O,C=M(O.baseManagerBlance).add(M(d?.base||"0")).toString(),U=M(O.quoteManagerBlance).add(M(d?.quote||"0")).toString(),L;a&&M(B).lt(s)?L=this.getCoinAssets(f.coinType,M(s).sub(B).toString(),u):L=this.getEmptyCoin(u,f.coinType);let P,q;if(i){a||(r=M(r).add(M(s)).toString());let V=M(U).sub(r).toString();if(M(V).lt(0)){let F;M(U).gt(0)&&(F=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.quoteCoin,amountToWithdraw:U,returnAssets:!0,txb:u}));let X=this.getCoinAssets(m,V,u);F&&u.mergeCoins(X,[F]),q=X}else q=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});P=this.getEmptyCoin(u,p)}else{a||(n=M(n).add(M(s)).toString());let V=M(C).sub(n).toString();if(M(V).lt(0)){let F;M(C).gt(0)&&(F=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.baseCoin,amountToWithdraw:C,returnAssets:!0,txb:u}));let X=this.getCoinAssets(p,V,u);F&&u.mergeCoins(X,[F]),P=X}else P=await this.withdrawFromManager({account:o,balanceManager:c,coin:e.baseCoin,amountToWithdraw:n,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,m)}return{baseAsset:P,quoteAsset:q,feeAsset:L}}catch(f){throw f instanceof Error?f:new Error(String(f))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:n,quantity:r,orderType:s,isBid:i,maxFee:o,account:a,payWithDeep:c,expirationTimestamp:u=Date.now()+31536e8}){try{let d=this.deepCoin,f=e.address,p=e.baseCoin.decimals,m=e.quoteCoin.decimals,b=e.baseCoin.coinType,v=e.quoteCoin.coinType,T=M(n).mul(10**(m-p+9)).toString(),O=ye(b),B=ye(v),C=new Y,U,L;if(i){let F=M(n).mul(M(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();c||(F=M(F).add(M(o)).toString()),L=Wt.buildCoinWithBalance(BigInt(F),B,C)}else{let F=r;c||(F=M(r).abs().add(M(o)).toString()),U=Wt.buildCoinWithBalance(BigInt(F),O,C)}let P=c?M(o).gt(0)?Wt.buildCoinWithBalance(BigInt(M(o).abs().ceil().toString()),d.coinType,C):this.getEmptyCoin(C,d.coinType):this.getEmptyCoin(C,d.coinType),q=C.moveCall({typeArguments:[i?b:v],target:"0x2::coin::zero",arguments:[]}),V=[C.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),C.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),C.object(f),i?q:U,i?L:q,P,C.pure.u8(s),C.pure.u8(0),C.pure.u64(T),C.pure.u64(r),C.pure.bool(i),C.pure.bool(!1),C.pure.u64(u),C.object(he)];return C.moveCall({typeArguments:[O,B],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:V}),C}catch(d){throw d instanceof Error?d:new Error(String(d))}}getEmptyCoin(e,n){return Wt.buildCoinWithBalance(BigInt(0),n,e)}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:n,isBid:r,maxFee:s,account:i,payWithDeep:o,slippage:a=.01}){try{let c=e.address,u=e.baseCoin.coinType,d=e.quoteCoin.coinType,f=ye(u),p=ye(d),m=new Y,b,v,T=n,O,B=await this.getOrderBook(e,"all",6);if(r){let L=B?.ask?.[0]?.price||"0",P=M(L).mul(M(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();O=M(P).plus(M(P).mul(a)).ceil().toString()}else{let L=await B?.bid?.[0]?.price||"0",P=M(L).mul(M(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();O=M(P).minus(M(P).mul(a)).floor().toString()}r?(o||(O=M(O).add(M(s)).toString()),v=this.getCoinAssets(p,O,m),b=this.getEmptyCoin(m,f)):(o||(T=M(T).add(M(s)).toString()),v=this.getEmptyCoin(m,p),b=this.getCoinAssets(f,T,m));let C=o?M(s).gt(0)?Wt.buildCoinWithBalance(BigInt(M(s).abs().ceil().toString()),this.deepCoin.coinType,m):this.getEmptyCoin(m,this.deepCoin.coinType):this.getEmptyCoin(m,this.deepCoin.coinType),U=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(c),b,v,C,m.pure.u8(0),m.pure.u64(n),m.pure.bool(r),m.pure.bool(o),m.pure.u64(O),m.object(he)];return m.moveCall({typeArguments:[f,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:U}),m}catch(c){throw c instanceof Error?c:new Error(String(c))}}async placeLimitOrder({balanceManager:e,poolInfo:n,priceInput:r,quantity:s,isBid:i,orderType:o,maxFee:a,account:c,payWithDeep:u,expirationTimestamp:d=Date.now()+31536e8}){try{let f=this.deepCoin,p=M(r).mul(10**(n.quoteCoin.decimals-n.baseCoin.decimals+9)).toString(),m=n.baseCoin.coinType,b=n.quoteCoin.coinType,v=new Y,T=i?M(r).mul(M(s).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString():"0",O=i?"0":s,{baseAsset:B,quoteAsset:C,feeAsset:U,haveDeposit:L}=await this.getTransactionRelatedAssets(n,O,T,a,i,c,u,e,v);if(L){let V=[v.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),v.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),v.object(n.address),v.object(e),B,C,U.feeAsset,v.pure.u8(o),v.pure.u8(0),v.pure.u64(p),v.pure.u64(s),v.pure.bool(i),v.pure.bool(u),v.pure.u64(d),v.object(he)];return v.moveCall({typeArguments:[m,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:V}),v}let P=new Y;M(U.haveDepositFee).gt(0)&&this.depositIntoManager({account:c,balanceManager:e,coin:f,amountToDeposit:U.haveDepositFee,tx:P});let q=[P.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),P.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),P.object(n.address),P.object(e),P.pure.u8(o),P.pure.u8(0),P.pure.u64(p),P.pure.u64(s),P.pure.bool(i),P.pure.bool(u),P.pure.u64(d),P.object(he)];return P.moveCall({typeArguments:[m,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:q}),P}catch(f){throw f instanceof Error?f:new Error(String(f))}}modifyOrder({balanceManager:e,poolInfo:n,orderId:r,newOrderQuantity:s}){let i=new Y;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(e),i.object(n.address),i.pure.u128(r),i.pure.u64(s),i.object(he)]}),i}async getBestAskprice(e){try{let{baseCoin:n,quoteCoin:r}=e,s=new Y,i=await this.getMarketPrice(e),o=M(i).gt(0)?i:Math.pow(10,-1),a=Math.pow(10,6),c=M(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=M(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(e.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,f=await this._sdk.fullClient.sendSimulationTransaction(s,d),p=[],m=f.commandResults[0].returnValues[0].bcs,b=A.vector(A.u64()).parse(new Uint8Array(m)),v=f.commandResults[0].returnValues[1].bcs,T=A.vector(A.u64()).parse(new Uint8Array(v));return b.forEach((O,B)=>{let C=M(O).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),U=M(T[B]).div(Math.pow(10,n.decimals)).toString();p.push({price:C,quantity:U})}),p?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:n,quoteCoin:r}=e,s=new Y,i=await this.getMarketPrice(e),o=M(i).gt(0)?M(i).div(3).toNumber():Math.pow(10,-6),a=M(i).gt(0)?i:Math.pow(10,6),c=M(o).mul(Math.pow(10,9+r.decimals-n.decimals)).toString(),u=M(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(e.address),s.pure.u64(yo(c,0)),s.pure.u64(yo(u,0)),s.pure.bool(!0),s.object(he)],typeArguments:[n.coinType,r.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(s,d),p=[],m=f.commandResults[0].returnValues[0].bcs,b=A.vector(A.u64()).parse(new Uint8Array(m)),v=f.commandResults[0].returnValues[1].bcs,T=A.vector(A.u64()).parse(new Uint8Array(v));return b.forEach((O,B)=>{let C=M(O).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),U=M(T[B]).div(Math.pow(10,n.decimals)).toString();p.push({price:C,quantity:U})}),p?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,n){try{let{baseCoin:r,quoteCoin:s}=e,i=new Y,o=await this.getMarketPrice(e),a,c;n?(a=M(o).gt(0)?M(o).div(3).toNumber():Math.pow(10,-6),c=M(o).gt(0)?o:Math.pow(10,6)):(a=M(o).gt(0)?o:Math.pow(10,-1),c=M(o).gt(0)?M(o).mul(3).toNumber():Math.pow(10,6));let u=M(a).mul(Math.pow(10,9+s.decimals-r.decimals)).toString(),d=M(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(e.address),i.pure.u64(yo(u,0)),i.pure.u64(yo(d,0)),i.pure.bool(n),i.object(he)],typeArguments:[r.coinType,s.coinType]});let f=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.sendSimulationTransaction(i,f),m=[],b=p.commandResults[0].returnValues[0].bcs,v=A.vector(A.u64()).parse(new Uint8Array(b)),T=p.commandResults[0].returnValues[1].bcs,O=A.vector(A.u64()).parse(new Uint8Array(T));return v.forEach((B,C)=>{let U=M(B).div(Math.pow(10,9+s.decimals-r.decimals)).toString(),L=M(O[C]).div(Math.pow(10,r.decimals)).toString();m.push({price:U,quantity:L})}),m?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,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 f=ye(n.baseCoin.coinType),p=ye(n.quoteCoin.coinType),m=new Y;d&&(M(d.base).gt(0)||M(d.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:n,balanceManager:e},m);let{baseAsset:b,quoteAsset:v,feeAsset:T}=await this.getMarketTransactionRelatedAssets(n,r,s,o,i,a,c,e,m,d),O=await this.getOrderBook(n,"all",6);if(i){let U=O?.ask?.[0]?.price||"0",L=M(U).mul(M(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=M(L).plus(M(L).mul(u)).ceil().toString()}else{let U=await O?.bid?.[0]?.price||"0",L=M(U).mul(M(r).div(Math.pow(10,n.baseCoin.decimals))).mul(Math.pow(10,n.quoteCoin.decimals)).toString();s=M(L).minus(M(L).mul(u)).floor().toString()}let B=s,C=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(n.address),m.object(e),b,v,T,m.pure.u8(0),m.pure.u64(r),m.pure.bool(i),m.pure.bool(c),m.pure.u64(B),m.object(he)];return m.setSenderIfNotSet(a),m.moveCall({typeArguments:[f,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),m}catch(f){throw f instanceof Error?f:new Error(String(f))}}async getOrderInfoList(e,n){try{let r=new Y;e.forEach(u=>{let d=u?.pool,f=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(d.pool_id),r.pure.u128(BigInt(f))],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let s=await this._sdk.fullClient.sendSimulationTransaction(r,n),i=A.struct("ID",{bytes:A.Address}),o=A.struct("OrderDeepPrice",{asset_is_base:A.bool(),deep_per_asset:A.u64()}),a=A.struct("Order",{balance_manager_id:i,order_id:A.u128(),client_order_id:A.u64(),quantity:A.u64(),filled_quantity:A.u64(),fee_is_deep:A.bool(),order_deep_price:o,epoch:A.u64(),status:A.u8(),expire_timestamp:A.u64()}),c=[];return s?.commandResults?.forEach(u=>{let d=u.returnValues[0].bcs,f=a.parse(new Uint8Array(d));c.push(f)}),c}catch{return[]}}decodeOrderId(e){let n=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:n,price:r,orderId:s}}async getOpenOrder(e,n,r,s,i=!1,o=new Y){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[o.object(e.address),i?r:o.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let f=await this._sdk.fullClient.sendSimulationTransaction(o,n);console.log("\u{1F680} ~ DeepbookUtilsModule ~ getOpenOrder ~ res:",f?.FailedTransaction?.status);let p=f.commandResults[i?1:0].returnValues[0].bcs;a=A.struct("VecSet",{constants:A.vector(A.U128)}).parse(new Uint8Array(p)).constants}if(a.length===0)return[];let c=a.map(f=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:f})),u=await this.getOrderInfoList(c,n)||[],d=[];return u.forEach(f=>{let p=this.decodeOrderId(BigInt(f.order_id));d.push({...f,price:p.price,isBid:p.isBid,pool:e})}),d}async getAllMarketsOpenOrders(e,n){try{let r=await this.getPools(),s=new Y;r.forEach(f=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(f.pool_id),s.object(n)],typeArguments:[f.baseCoinType,f.quoteCoinType]})});let o=(await this._sdk.fullClient.sendSimulationTransaction(s,e)).commandResults?.map(f=>f.returnValues?.[0]?.bcs)||[],a=A.struct("VecSet",{constants:A.vector(A.U128)}),c=[];o.forEach((f,p)=>{let m=a.parse(new Uint8Array(f)).constants;m.length>0&&m.forEach(b=>{c.push({pool:r[p],orderId:b})})});let u=await this.getOrderInfoList(c,e)||[],d=[];return c.forEach((f,p)=>{let m=this.decodeOrderId(BigInt(f.orderId)),b=u.find(v=>v.order_id===f.orderId)||{};d.push({...f,...b,price:m.price,isBid:m.isBid})}),d}catch(r){return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getAllMarketsOpenOrders ~ error:",r),[]}}cancelOrders(e,n,r=new Y){return e.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(e,n,r,s,i,o){let a=this._sdk.fullClient,u=await new H3({client:a,address:i,network:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,n,r,s)}processOrderBookData(e,n,r,s){let i=e.returnValues[0].bcs,o=A.vector(A.u64()).parse(new Uint8Array(i)),a=e.returnValues[1].bcs,c=A.vector(A.u64()).parse(new Uint8Array(a)),u={};return o.forEach((f,p)=>{let m=M(f).div(Math.pow(10,9+r.decimals-n.decimals)).toString(),b=M(c[p]).div(Math.pow(10,n.decimals)).toString();u[m]?u[m]={price:m,quantity:M(u[m].quantity).add(b).toString()}:u[m]={price:m,quantity:b}}),Object.values(u)}getLevel2RangeTx(e,n,r,s,i=new Y){let{baseCoin:o,quoteCoin:a}=e,c=yo(M(r).mul(Math.pow(10,9+a.decimals-o.decimals)).toString(),0),u=yo(M(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(e.address),i.pure.u64(c),i.pure.u64(u),i.pure.bool(n),i.object(he)],typeArguments:[o.coinType,a.coinType]}),i}async fetchOrderBook(e,n,r,s,i,o){let a=new Y,{baseCoin:c,quoteCoin:u}=e;try{if(n==="bid"||n==="all"){let b=s,v=r==="0"?i:r;a=this.getLevel2RangeTx(e,!0,b,v,a)}if(n==="ask"||n==="all"){let b=r==="0"?s:r,v=i;a=this.getLevel2RangeTx(e,!1,b,v,a)}let d=this._sdk.sdkOptions.simulationAccount.address,f=await this._sdk.fullClient.sendSimulationTransaction(a,d),p=[];(n==="bid"||n==="all")&&(p=f.commandResults?.[0]?this.processOrderBookData(f.commandResults[0],c,u,o):[]);let m=[];if(n==="ask"||n==="all"){let b=n==="ask"?0:1;m=f.commandResults?.[b]?this.processOrderBookData(f.commandResults[b],c,u,o):[]}return{bid:p.sort((b,v)=>v.price-b.price),ask:m.sort((b,v)=>b.price-v.price)}}catch{let f=this._sdk.sdkOptions.simulationAccount.address,p=[],m=[];try{let b=this.getLevel2RangeTx(e,!0,s,r),v=await this._sdk.fullClient.sendSimulationTransaction(b,f);p=v.commandResults?.[0]?this.processOrderBookData(v.commandResults[0],c,u,o):[]}catch{p=[]}try{let b=this.getLevel2RangeTx(e,!1,s,r),v=await this._sdk.fullClient.sendSimulationTransaction(b,f);m=v.commandResults?.[0]?this.processOrderBookData(v.commandResults[0],c,u,o):[]}catch{m=[]}return{bid:p,ask:m}}}async getOrderBook(e,n,r){let s={bid:[],ask:[]};try{let i=await this.getMarketPrice(e),o=n,a=Math.pow(10,-r),c=Math.pow(10,r),u=await this.fetchOrderBook(e,o,i,a,c,r);return{bid:u?.bid,ask:u?.ask}}catch{return s}}async getOrderBookOrigin(e,n){try{let r=new Y,s=await this.getMarketPrice(e),{baseCoin:i,quoteCoin:o}=e;if(n==="bid"||n==="all"){let f=Math.pow(10,-6),p=s,m=M(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=M(p).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(e.address),r.pure.u64(m),r.pure.u64(b),r.pure.bool(!0),r.object(he)],typeArguments:[i.coinType,o.coinType]})}if(n==="ask"||n==="all"){let f=s,p=Math.pow(10,6),m=M(f).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),b=M(p).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(e.address),r.pure.u64(m),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 f=c.commandResults[0]?.returnValues[0]?.bcs,p=A.vector(A.u64()).parse(new Uint8Array(f)),m=c.commandResults[0]?.returnValues[1]?.bcs,b=A.vector(A.u64()).parse(new Uint8Array(m));p.forEach((v,T)=>{let O=M(v).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),B=M(b[T]).div(Math.pow(10,i.decimals)).toString();u.push({price:O,quantity:B})})}let d=[];if(n==="ask"||n==="all"){let f=n==="ask"?0:1,p=c.results[f]?.returnValues[0]?.[0],m=A.vector(A.u64()).parse(new Uint8Array(p)),b=c.results[f]?.returnValues[1]?.[0],v=A.vector(A.u64()).parse(new Uint8Array(b));m.forEach((T,O)=>{let B=M(T).div(Math.pow(10,9+o.decimals-i.decimals)).toString(),C=M(v[O]).div(Math.pow(10,i.decimals)).toString();d.push({price:B,quantity:C})})}return{bid:u,ask:d}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let n=await this._sdk.fullClient?.getOwnerCoinBalances(e);return console.log("\u{1F680} ~ DeepbookUtilsModule ~ getWalletBalance ~ result:",n),Object.fromEntries(n.map((s,i)=>[ye(s.coinType),{coinType:s.coinType,totalBalance:s.balance,coinBalance:s.coinBalance,addressBalance:s.addressBalance}]))}async getAccount(e,n,r=new Y){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 e=="string"?r.object(e):e],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=lT.parse(c),d=u.open_orders,f=u.owed_balances,p=u.settled_balances,m=u.unclaimed_rebates,b=u.taker_volume;i.push({balance_manager_id:e,open_orders:d,owed_balances:f,settled_balances:p,unclaimed_rebates:m,taker_volume:b,poolInfo:n[a]})}),i}async getSuiTransactionResponse(e,n=!1){let r=`${e}_getSuiTransactionResponse`,s=this.getCache(r,n);if(s!==void 0)return s;let i;try{i=await this._sdk.fullClient.getTransaction({digest:e,include:{events:!0,effects:!0,balanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransaction({digest:e,include:{events:!0,effects:!0}})}return this.updateCache(r,i,864e5),i}transformExtensions(e,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(z3.decode(a)))}catch{}r&&(e[o]=a),s.push({key:o,value:a})}delete e.extension_fields,r||(e.extensions=s)}async getCoinConfigs(e=!1,n=!0){let r=this.sdk.sdkOptions.coinlist.handle,s=`${r}_getCoinConfigs`,i=this.getCache(s,e);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 f=this.buildCoinConfig(d,n);this.updateCache(`${r}_${f.address}_getCoinConfig`,f,864e5),u.push({...f})}),this.updateCache(s,u,864e5),u}buildCoinConfig(e,n=!0){let r=cT(e);r=r.value.fields;let s={...r};return s.id=aT(e),s.address=gi(r.coin_type.fields.name).full_address,r.pyth_id&&(s.pyth_id=$t(r.pyth_id)),this.transformExtensions(s,r.extension_fields.fields.contents,n),delete s.coin_type,s}updateCache(e,n,r=3e5){let s=this._cache[e];s?(s.overdueTime=jm(r),s.value=n):s=new od(n,jm(r)),this._cache[e]=s}getCache(e,n=!1){let r=this._cache[e],s=r?.isValid();if(!n&&s)return r.value;s||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:n,minSize:r,baseCoinType:s,quoteCoinType:i}){let o=new Y,a=Wt.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(e),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:e,appType:n}){let r=new Y,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(e)],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],e),r}};var cd="0x0000000000000000000000000000000000000000000000000000000000000006",FZ="pool_script",qZ="pool_script_v2",$Z="router",GZ="router_with_partner",HZ="fetcher_script",zZ="expect_swap",WZ="utils",ZZ="0x1::coin::CoinInfo",JZ="0x1::coin::CoinStore",KZ="custodian_v2",YZ="clob_v2",XZ="endpoints_v2",QZ=t=>{if(typeof t=="string"&&t.startsWith("0x"))return"object";if(typeof t=="number"||typeof t=="bigint")return"u64";if(typeof t=="boolean")return"bool";throw new Error(`Unknown type for value: ${t}`)},eJ=["https://rpc-mainnet.suiscan.xyz:443","https://cetus-mainnet-endpoint.blockvision.org","https://cetus-suimain-e31f.mainnet.sui.rpcpool.com"];import dT from"decimal.js";dT.config({precision:64,rounding:dT.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var iJ=({totalAssetsValue:t,totalDebtValue:e})=>M(e).eq(0)||M(t).eq(0)?"0":M(t).div(M(e)).toString(),fT=t=>{let{base_margin_pool_id:e,quote_margin_pool_id:n,enabled:r,pool_liquidation_reward:s,user_liquidation_reward:i}=t.value.fields,{liquidation_risk_ratio:o,min_borrow_risk_ratio:a,min_withdraw_risk_ratio:c,target_liquidation_risk_ratio:u}=t.value.fields.risk_ratios.fields;return{id:t.id.id,name:t.name,base_margin_pool_id:e,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}},pT=(t,e)=>{let{deposit_coin_type:n}=e,r=t.id,{max_utilization_rate:s,min_borrow:i,protocol_spread:o,supply_cap:a}=t.config.margin_pool_config,{maintainer_fees:c,protocol_fees:u}=t.protocol_fees,{total_supply:d,total_borrow:f}=t.state,p=M(a).sub(d).toString();return{deposit_coin_type:n,id:r,supply_cap:a,total_supply:d,total_borrow:f,available_supply:p,max_utilization_rate:s,min_borrow:i,protocol_spread:o,maintainer_fees:c,protocol_fees:u}};var es=1000000000n,J3=365n*24n*60n*60n*1000n;function K3(t,e){return e===0n?0n:t*es/e}function Y3(t,e){let{base_rate:n,base_slope:r,optimal_utilization:s,excess_slope:i}=e;if(t<s)return n+t*r/es;{let o=t-s,a=s*r/es,c=o*i/es;return n+a+c}}function hT(t,e){let n=t*e,r=n/es;return n%es>0n?r+1n:r}function X3(t,e,n,r){let s=e.borrow_shares===0n?es:e.total_borrow*es/e.borrow_shares,i=hT(t,s),o=K3(e.total_borrow,e.total_supply),a=Y3(o,n),c=r-e.last_update_timestamp,u=e.total_borrow*a/es*c/J3,d=e.borrow_shares===0n?0n:hT(u,t*es/e.borrow_shares),f=i+d;return{confirmedDebt:i,estimatedInterest:d,totalDebt:f,annualInterestRate:a}}function aJ(t,e,n,r,s=60000n){let i=r+s,{totalDebt:o}=X3(t,e,n,i);return o}var Um=10n;function Q3(t,e){if(!Um)throw new Error("oraclePriceMultiplierDecimal is required");if(t===0n)throw new Error("Invalid oracle price");if(e<0n){let n=10n**(Um- -e);return t*n}return t/10n**(e+Um)}var ya=class{_sdk;hasChangeConnection=!1;_commonPythPrice;_cache={};constructor(e){this._sdk=e,this._commonPythPrice=new z_(e.fullClient)}get sdk(){return this._sdk}async updatePythPriceIDs(e,n){let r=null,s=null;try{r=await this._commonPythPrice.getPriceFeedsUpdateData(e)}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,e)}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<e.length;a++)o.set(e[a],i[a]);return o}priceCheck(e,n=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>n))return e}async getLatestPrice(e,n=!1){let r={},s=[];if(n?e.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=e.map(a=>a.coinType),s.length===0)return r;let i=e.map(a=>a.feed);return(await this._commonPythPrice.getLatestPriceFeeds(i))?.parsed?.forEach((a,c)=>{let u=a.price;if(u){let{price:d,expo:f}=u,p=M(d).mul(M(10).pow(M(f))).toString(),b={coin_type:e[c].coinType,price:p,oracle_price:0n,last_update_time:u.publish_time};b.oracle_price=Q3(BigInt(d),BigInt(f)),r[s[c]]=b,this._sdk.fullClient.updateCache(`getLatestPrice_${b.coin_type}`,b)}}),r}};var ud=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new ya(e),this._deep=e.sdkOptions.network==="mainnet"?sT:rT}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,n=new Y){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:s}=e;try{let{margin_manager:i,initializer:o}=this.createMarginManager(e,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(e,n=new Y){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:s,quoteCoin:i}=e;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:e,initializer:n,baseCoin:r,quoteCoin:s},i=new Y){try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,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 getMarginManagerByAccount(e){if(!e||typeof e!="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(f=>f.parsedJson?.owner===e);if(!s.length)return[];let i=s.map(f=>f.parsedJson?.margin_manager_id),a=(await this.sdk.fullClient.batchGetObjects(i,{json:!0})).map((f,p)=>{let m=f.json,v=(m?.balance_manager?.allow_listed?.contents).map(O=>O),T=v.includes(m?.deposit_cap?.id)&&v.includes(m?.withdraw_cap?.id)&&v.includes(m?.trade_cap?.id);return{balanceManagerId:m?.balance_manager?.id,marginManagerId:i[p],capOk:T}}),c=await Promise.all(a.map(({balanceManagerId:f})=>this.sdk.fullClient.listDynamicFields({parentId:f}))),u=new Map;return c.forEach((f,p)=>{let m=f?.dynamicFields??[];if(m.length>0){let b=A.struct("ReferralKey",{pos0:A.Address}).parse(m[0].name.bcs);u.set(a[p].marginManagerId,b.pos0)}}),{finalResult:s.map(f=>{let p=f.parsedJson?.margin_manager_id;return{...f.parsedJson,referralKey:u.get(p)}}),referralMap:u}}catch(n){throw new Error(`Failed to get margin managers by account: ${n instanceof Error?n.message:String(n)}`)}}async getBaseBalance({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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 A.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:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let i=new Y,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,e);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=A.U64.parse(new Uint8Array(u.commandResults[0].returnValues[0].bcs)),f=A.U64.parse(new Uint8Array(u.commandResults[1].returnValues[0].bcs)),p=c?o?d:f:A.U64.parse(new Uint8Array(u.commandResults[2].returnValues[0].bcs));return{[r]:d.toString(),[s]:f.toString(),[this.deepCoin.coinType]:p.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}){if(!e||!n||!r||!s)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let i=new Y;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,e);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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.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:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:c=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:d})=>f=>{f.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[f.object(n),f.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),f.object(u),f.object(d),f.object(i),f.object(o),f.object(a),f.object.clock()],typeArguments:[r.coinType,s.coinType]})};async getManagerState(e,n=new Y){let{account:r,marginManager:s,baseCoin:i,quoteCoin:o,pool:a,baseMarginPool:c,quoteMarginPool:u,decimals:d=6}=e;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 f=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],n),p=f.get(i.feed),m=f.get(o.feed);if(!p||!m)throw new Error("Failed to get price feed object IDs");n.add(this.managerState({...e,basePriceFeedObjectId:p,quotePriceFeedObjectId:m}));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 v=Q(A.Address.parse(new Uint8Array(b.commandResults[0].returnValues[0].bcs))),T=Q(A.Address.parse(new Uint8Array(b.commandResults[0].returnValues[1].bcs))),O=Number(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[2].bcs)))/1e9,B=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[3].bcs))),i.scalar,d),C=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[4].bcs))),o.scalar,d),U=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[5].bcs))),i.scalar,d),L=this.#t(BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[6].bcs))),o.scalar,d),P=A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[7].bcs)),q=Number(A.u8().parse(new Uint8Array(b.commandResults[0].returnValues[8].bcs))),V=A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[9].bcs)),F=Number(A.u8().parse(new Uint8Array(b.commandResults[0].returnValues[10].bcs))),X=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[11].bcs))),ee=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[12].bcs))),j=BigInt(A.U64.parse(new Uint8Array(b.commandResults[0].returnValues[13].bcs)));return{managerId:v,deepbookPoolId:T,riskRatio:O,baseAsset:B,quoteAsset:C,baseDebt:U,quoteDebt:L,basePythPrice:P.toString(),basePythDecimals:q,quotePythPrice:V.toString(),quotePythDecimals:F,currentPrice:X,lowestTriggerAbovePrice:ee,highestTriggerBelowPrice:j}}catch(f){throw new Error(`Failed to get manager state: ${f instanceof Error?f.message:String(f)}`)}}async detectPriceBoundary({account:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,price:c,is_bid:u,decimals:d=6}){if(!e||!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 f=typeof c=="bigint"?c:BigInt(c),p=await this.getManagerState({account:e,marginManager:n,baseCoin:r,quoteCoin:s,pool:i,baseMarginPool:o,quoteMarginPool:a,decimals:d},new Y),m=p.highestTriggerBelowPrice,b=p.lowestTriggerAbovePrice,v=u?f<=b:f>=m;return{is_bid:u,price:f,lower_bound:m,upper_bound:b,is_within:v,is_boundary:u?f===b:f===m}}async calculateAssets({account:e,marginManager:n,pool:r,baseCoin:s,quoteCoin:i,tx:o=new Y}){if(!e||!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,e);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=A.U64.parse(new Uint8Array(c)),f=A.U64.parse(new Uint8Array(u));return{baseAsset:d.toString(),quoteAsset:f.toString(),tx:o}}catch(a){throw new Error(`Failed to calculate assets: ${a instanceof Error?a.message:String(a)}`)}}async getBorrowedAmount({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){if(!e||!n||!r||!s||!i||!o)throw new Error("All parameters are required");try{let{baseBorrowedShare:a,quoteBorrowedShare:c}=await this.getBorrowedShares({account:e,marginManager:n,baseCoinType:r,quoteCoinType:s}),u=!!M(a).gt(M(c)),d=u?i:o,f=u?a:c,p=new Y;p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[p.object(d),p.pure.u64(BigInt(f)),p.object.clock()],typeArguments:[u?r:s]});let m=await this.sdk.fullClient.simulateTransaction({transaction:p,checksEnabled:!1,include:{commandResults:!0,json:!0}}),b=A.U64.parse(m?.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:e,baseCoin:n,quoteCoin:r,amount:s,depositCoinType:i},o=new Y){if(!e)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=Wt.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 e=="string"?o.object(e):e,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:e,marginManager:n,baseMarginPool:r,quoteMarginPool:s,baseCoin:i,quoteCoin:o,pool:a,amount:c,withdrawCoinType:u},d=new Y){if(!e||!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 f=await this.pythPrice.updatePythPriceIDs([i.feed,o.feed],d),p=f.get(i.feed),m=f.get(o.feed);if(!p||!m)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(p),d.object(m),d.object(a),d.pure.u64(BigInt(c)),d.object(he)],typeArguments:[i.coinType,o.coinType,u]});if(Wt.isSuiCoin(u))d.transferObjects([b],e);else{let v=await this._sdk.fullClient.getOwnerCoinAssets(e,u),T=Wt.buildCoinForAmount(d,v,BigInt(0),u,!1);T.target_coin?(d.mergeCoins(T.target_coin,[b]),T.is_mint_zero_coin&&d.transferObjects([T.target_coin],e)):d.transferObjects([b],e)}return d}catch(f){throw new Error(`Failed to withdraw: ${f instanceof Error?f.message:String(f)}`)}}async borrowBase({marginManager:e,baseMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new Y){if(!e||!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(e),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:e,quoteMarginPool:n,baseCoin:r,quoteCoin:s,pool:i,amount:o},a=new Y){if(!e||!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 e=="string"?a.object(e):e,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:e,baseMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new Y){if(!e||!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:e,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(e),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:e,quoteMarginPool:n,baseCoin:r,quoteCoin:s,amount:i},o=new Y){if(!e||!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:e,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(e),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:e,baseMarginPool:n,quoteMarginPool:r,baseCoin:s,quoteCoin:i,isBase:o,amount:a},c=new Y){try{let u=this.sdk.senderAddress,d,f=a;a||(d=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType,baseMarginPool:n,quoteMarginPool:r}),f=o?d.baseBorrowedAmount:d.quoteBorrowedAmount);let p,m={marginManager:e,baseCoin:s,quoteCoin:i,depositCoinType:o?s.coinType:i.coinType};if(o){let b=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});p=M(f).sub(b).toString()}else{let b=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:s?.coinType,quoteCoinType:i?.coinType});p=M(f).sub(b).toString()}M(p).gt(0)&&await this.deposit({...m,amount:p},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(e),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=(e,n,r,s,i=new Y)=>{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 e=="string"?i.object(e):e,o]})};async#e(e,n,r){if(!e.feed||!n.feed)throw new Error("Base and quote coin feeds are required");let s=await this.pythPrice.updatePythPriceIDs([e.feed,n.feed],r),i=s.get(e.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:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u,exactBase:d,referralKey:f},p=new Y){if(!e||!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(yi(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(yi(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:m,baseCoin:b,quoteCoin:v}=n;if(b.decimals===void 0||v.decimals===void 0)throw new Error("Base and quote coin decimals are required");f&&this.removeReferralKey(e,m,b.coinType,v.coinType,p);try{let{baseOracle:T,quoteOracle:O}=await this.#e(b,v,p);return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order_v2`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?p.object(e):e,p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(m),p.object(r),p.object(s),p.object(T),p.object(O),p.pure.u8(i),p.pure.u64(o),p.pure.bool(c),p.pure.bool(u),p.pure.bool(d===void 0?!c:d),p.pure.u64(a),p.object(he)],typeArguments:[b.coinType,v.coinType]}),p}catch(T){throw new Error(`Failed to place market order: ${T instanceof Error?T.message:String(T)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:f=Date.now()+31536e8,referralKey:p},m=new Y){if(!e||!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:v,quoteCoin:T}=n;if(v.decimals===void 0||T.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let O=BigInt(M(a).mul(10**(T.decimals-v.decimals+9)).toString()),B=BigInt(yi(c,v.decimals));if(O<=0n||B<=0n)throw new Error("Price and quantity must be greater than zero");p&&this.removeReferralKey(e,b,v.coinType,T.coinType,m);let{baseOracle:C,quoteOracle:U}=await this.#e(v,T,m);return m.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order_v2`,arguments:[m.object(this.sdk.sdkOptions.margin_utils.global_config_id),m.object(this.sdk.sdkOptions.margin_utils.versioned_id),m.object(e),m.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),m.object(b),m.object(r),m.object(s),m.object(C),m.object(U),m.pure.u8(i),m.pure.u8(o),m.pure.u64(O),m.pure.u64(B),m.pure.bool(u),m.pure.bool(d),m.pure.u64(f),m.object(he)],typeArguments:[v.coinType,T.coinType]}),m}catch(O){throw new Error(`Failed to place limit order: ${O instanceof Error?O.message:String(O)}`)}}modifyMarginOrder({marginManager:e,poolInfo:n,orderId:r,newQuantity:s},i=new Y){if(!e||!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(yi(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(e),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:e,poolInfo:n,orderId:r},s=new Y){if(!e||!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(e),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:e,poolInfo:n},r=new Y){if(!e||!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(e),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:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,orderType:i,selfMatchingOption:o,priceInput:a,quantity:c,isBid:u,payWithDeep:d,expirationTimestamp:f=Date.now()+31536e8},p=new Y){if(!e||!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:m,quoteCoin:b}=n;if(m.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let v=BigInt(M(a).mul(10**(b.decimals-m.decimals+9)).toString()),T=BigInt(yi(c,m.decimals));if(v<=0n||T<=0n)throw new Error("Price and quantity must be greater than zero");let{baseOracle:O,quoteOracle:B}=await this.#e(m,b,p);return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order_v2`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(n.id),p.object(r),p.object(s),p.object(O),p.object(B),p.pure.u8(i),p.pure.u8(o),p.pure.u64(v),p.pure.u64(T),p.pure.bool(u),p.pure.bool(d),p.pure.u64(f),p.object(he)],typeArguments:[m.coinType,b.coinType]}),p}catch(v){throw new Error(`Failed to place reduce only limit order: ${v instanceof Error?v.message:String(v)}`)}}async placeReduceOnlyMarketOrder({marginManager:e,poolInfo:n,baseMarginPool:r,quoteMarginPool:s,selfMatchingOption:i,quantity:o,amountLimit:a,isBid:c,payWithDeep:u},d=new Y){if(!e||!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(yi(o,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!a||BigInt(yi(a,n.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{baseCoin:f,quoteCoin:p}=n;if(f.decimals===void 0||p.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let{baseOracle:m,quoteOracle:b}=await this.#e(f,p,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(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(n.id),d.object(r),d.object(s),d.object(m),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:[f.coinType,p.coinType]}),d}catch(m){throw new Error(`Failed to place reduce only market order: ${m instanceof Error?m.message:String(m)}`)}}async getOpenOrder(e,n,r,s,i=!1,o=new Y){let a;if(s)a=s;else{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::account_open_orders`,arguments:[o.object(e.address),i?r:o.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.simulateTransaction({transaction:o,include:{commandResults:!0,json:!0},checksEnabled:!1})).commandResults[i?1:0].returnValues[0].bcs;a=A.struct("VecSet",{constants:A.vector(A.U128)}).parse(new Uint8Array(p)).constants}if(a.length===0)return[];let c=a.map(f=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:f})),u=await this.sdk.DeepbookUtils.getOrderInfoList(c,n)||[],d=[];return u.forEach(f=>{let p=this.sdk.DeepbookUtils.decodeOrderId(BigInt(f.order_id));d.push({...f,price:p.price,isBid:p.isBid,pool:e})}),d}async getAccountOpenOrders({poolInfo:e,marginManager:n}){try{let r=new Y,s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(n)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.getOpenOrder(e,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(e,n){try{if(!e||!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 Y,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(e=new Y,n){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(he)]});return n&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:n,amount:r}){let s=new Y,{supplierCap:i}=this.mintSupplierCap(s,!1);return this.supply({marginPool:e,supplierCap:i,supplyCoinType:n,amount:r,tx:s}),s.transferObjects([i],this.sdk.senderAddress),s}supply({marginPool:e,supplierCap:n,supplyCoinType:r,amount:s,tx:i}){let o=i??new Y;if(!n)throw new Error("Either supplierCap must be provided");let a=Wt.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(e),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:e,withdrawCoinType:n,amount:r,supplierCapId:s,hasSwap:i,withdrawAll:o,tx:a=new Y}){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(e),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:e}){let n=new Y,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(e),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:e,supplyCoin:n,supplierCapId:r}){let s=new Y;s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[n.coinType],arguments:[s.object(e),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(A.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:A.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:e}=await this.sdk.fullClient.listDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),n=e.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(fT(o))}return s}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFieldsByPage(this.sdk.sdkOptions.margin_utils.margin_pool_table_id),n=e.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(pT(u,s[c]))}return a}async getBaseQuantityIn(e,n,r,s=.01){let i=new Y;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_base_quantity_in`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[i.object(e.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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:c.toString(),quantityInLeft:M(a.toString()).mul(M(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(e,n,r,s=.01){let i=new Y;i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::get_quote_quantity_in`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[i.object(e.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=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[1].bcs)),u=A.U64.parse(new Uint8Array(o.commandResults[0].returnValues[2].bcs));return{quantityOut:a.toString(),quantityInLeft:M(c.toString()).mul(M(1+s)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(e,n,r){let s=new Y;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.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=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=A.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(e,n,r){let s=new Y;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.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=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[0].bcs)),a=A.U64.parse(new Uint8Array(i.commandResults[0].returnValues[1].bcs)),c=A.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(e,n,r=new Y){let s=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[n.baseCoin.coinType,n.quoteCoin.coinType]}),i=[n];for(let d=0;d<i.length;d++){let f=i[d];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(f.address),typeof s=="string"?r.object(s):s],typeArguments:[f.baseCoin.coinType,f.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,f)=>{c=d?.json;let p=c.account.open_orders.contents,m=c.account.owed_balances,b=c.account.settled_balances,v=c.account.unclaimed_rebates,T=c.account.taker_volume;u.push({balance_manager_id:s,open_orders:p,owed_balances:m,settled_balances:b,unclaimed_rebates:v,taker_volume:T,poolInfo:i[f]})}),u}async withdrawSettledAmounts({poolInfo:e,marginManager:n},r=new Y){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(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#t(e,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=e/s,o=e%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(e){if(!e)throw new Error("marginPoolId is required");let n=await this.sdk.fullClient.getObject({objectId:e,include:{json:!0}});if(!n?.object?.json)throw new Error(`Failed to fetch margin pool: ${e}`);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(e){if(!e||e.length===0)throw new Error("marginPoolIds is required");let n=await this.sdk.fullClient.batchGetObjects(e,{json:!0}),r=[];return e.forEach((i,o)=>{let a=n[o];if(a){let c=a.json.state,u=a.json.config,d=u.interest_config,f=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(f.protocol_spread),max_utilization_rate:BigInt(f.max_utilization_rate),min_borrow:BigInt(f.min_borrow),supply_cap:BigInt(f.supply_cap)}})}}),{poolStateObj:Object.fromEntries(e.map((i,o)=>[i,r[o]])),poolStateList:r}}async getChainTimestamp(){let{response:e}=await this.sdk.fullClient.ledgerService.getServiceInfo({}),n=e.timestamp;if(!n)throw new Error("No timestamp in service info");return BigInt(n.seconds)*1000n+BigInt(n.nanos)/1000000n}async batchGetBorrowedShares({account:e,marginManagerList:n}){let r=new Y;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,e)).commandResults.map((i,o)=>{let a=A.U64.parse(new Uint8Array(i.returnValues[0].bcs)),c=A.U64.parse(new Uint8Array(i.returnValues[1].bcs));return{marginManagerId:n[o].marginManagerId,baseBorrowedShare:a,quoteBorrowedShare:c}})}async betchGetOpenOrders({account:e,marginManagerList:n},r=new Y,s=!1){n.forEach(m=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(b)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let i=await this.sdk.fullClient.simulateTransaction({transaction:r,checksEnabled:!1,include:{events:!0,commandResults:!0,json:!0}}),o=i.Transaction?.events.map((m,b)=>({marginManagerId:n[b].marginManagerId,...m?.json?.account?.settled_balances||{}})),a=i.commandResults.filter((m,b)=>(b-1)%4===0),c=A.struct("VecSet",{constants:A.vector(A.U128)}),u=[];a.forEach((m,b)=>{let v=c.parse(m.returnValues[0].bcs).constants;v.length>0&&v.forEach(T=>{u.push({pool:{pool_id:n[b].poolId,baseCoinType:n[b].baseCoinType,quoteCoinType:n[b].quoteCoinType},marginManagerId:n[b].marginManagerId,orderId:T})})});let d=i.commandResults.filter((m,b)=>(b-3)%4===0),f=[];d.forEach((m,b)=>{f.push({marginManagerId:n[b].marginManagerId,base:A.U64.parse(m.returnValues[0].bcs),quote:A.U64.parse(m.returnValues[1].bcs),deep:A.U64.parse(m.returnValues[2].bcs)})});let p=[];return u.forEach((m,b)=>{let v=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId));p.push({...m,price:v.price.toString(),isBid:v.isBid})}),{openOrders:p,settledBalances:o,lockedBalances:f}}async getAllPosRelevantData({account:e,marginManagerList:n}){try{let{openOrders:r,settledBalances:s,lockedBalances:i}=await this.betchGetOpenOrders({account:e,marginManagerList:n}),o=await this.batchGetBorrowedShares({account:e,marginManagerList:n}),a=new Y,c=0,u=[];n.forEach(p=>{a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"base_balance",marginManagerId:p.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"quote_balance",marginManagerId:p.marginManagerId},c++,a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[a.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[c]={type:"deep_balance",marginManagerId:p.marginManagerId},c++;let m=o?.find(b=>b.marginManagerId===p.marginManagerId);if(m&&(Number(m.baseBorrowedShare)>0||Number(m.quoteBorrowedShare)>0)){let b=m.baseBorrowedShare,v=m.quoteBorrowedShare,T=!!M(b).gt(M(v)),O=T?p.baseMarginPool:p.quoteMarginPool,B=T?b:v;a.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_pool::borrow_shares_to_amount`,arguments:[a.object(O),a.pure.u64(BigInt(B)),a.object.clock()],typeArguments:[T?p?.baseCoinType:p?.quoteCoinType]}),u[c]={type:T?"borrow_base_amount":"borrow_quote_amount",marginManagerId:p.marginManagerId},c++}}),nT(a);let d=await this.sdk.fullClient.simulateTransaction({transaction:a,checksEnabled:!1,include:{commandResults:!0,events:!0,json:!0}}),f=Object.fromEntries(n.map(p=>[p.marginManagerId,{...p,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((p,m)=>{let b=u[m],v=A.U64.parse(new Uint8Array(p.returnValues[0].bcs));f[b.marginManagerId]={...f[b.marginManagerId],[b.type]:v}}),r?.forEach(p=>{f[p.marginManagerId].open_orders.push(p)}),s?.forEach(p=>{f[p.marginManagerId].settled_balances=p}),i?.forEach(p=>{f[p.marginManagerId].locked_balances=p}),Object.values(f)?.forEach(p=>{p.locked_balances&&p.settled_balances&&(p.locked_balances={...p.locked_balances,base:M(p.locked_balances.base||"0").minus(M(p.settled_balances.base||"0")).toString(),quote:M(p.locked_balances.quote||"0").minus(M(p.settled_balances.quote||"0")).toString(),deep:M(p.locked_balances.deep||"0").minus(M(p.settled_balances.deep||"0")).toString()})}),f}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(e,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:f,pending_order:p,is_trigger_below_price:m,trigger_price:b}=e,v=await this.pythPrice.updatePythPriceIDs([u.feed,d.feed],n),T=v.get(u.feed),O=v.get(d.feed);if(!T||!O)throw new Error("Failed to get price feed object IDs");let B=n.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[n.pure.bool(m),n.pure.u64(b)]}),C=this.newPendingOrder(p,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(T),n.object(O),n.object(o),typeof f=="string"?n.pure.u64(BigInt(f)):f,B,C,n.object(cd)],typeArguments:[u.coinType,d.coinType]})}newPendingOrder(e,n){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in e){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:f}=e;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(f)]})}else{let{client_order_id:s,self_matching_option:i,quantity:o,is_bid:a,pay_with_deep:c}=e;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(e,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}=e;n.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[n.object(s),n.object(i),n.object(o),n.object(cd)],typeArguments:[a,c]})}cancelConditionalOrders(e,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}=e;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(cd)],typeArguments:[a,c]})}async getConditionalOrders(e,n){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(u=>{let{margin_manager_id:d,base_coin_type:f,quote_coin_type:p,conditional_order_ids:m}=u;m.forEach(b=>{n.moveCall({target:`${r.margin_published_at}::margin_manager::conditional_order`,arguments:[n.object(d),n.pure.u64(b)],typeArguments:[f,p]})})});let s=await this.sdk.fullClient.sendSimulationTransaction(n,Q("0x0"));if(!s?.commandResults)return[];let i=A.struct("Condition",{trigger_below_price:A.bool(),trigger_price:A.u64()}),o=A.struct("PendingOrder",{is_limit_order:A.bool(),client_order_id:A.u64(),order_type:A.option(A.u8()),self_matching_option:A.u8(),price:A.option(A.u64()),quantity:A.u64(),is_bid:A.bool(),pay_with_deep:A.bool(),expire_timestamp:A.option(A.u64())}),a=A.struct("ConditionalOrder",{conditional_order_id:A.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,f=c(d);if(!f)return null;let p=this.normalizeConditionalOrder(f);return e.forEach(m=>{m.conditional_order_ids.find(v=>v===p.conditional_order_id)&&(p.margin_manager_id=m.margin_manager_id,p.base_coin_type=m.base_coin_type,p.quote_coin_type=m.quote_coin_type)}),p}catch{return null}})}async getConditionalOrderIds(e,n){n=n||new Y;let{deepbook:r}=this.sdk.sdkOptions,s={};return e.forEach(o=>{let{margin_manager_id:a,base_coin_type:c,quote_coin_type:u}=o;n.moveCall({target:`${r.margin_published_at}::margin_manager::conditional_order_ids`,arguments:[n.object(a)],typeArguments:[c,u]})}),(await this.sdk.fullClient.sendSimulationTransaction(n,Q("0x0"))).commandResults.forEach((o,a)=>{if(o?.returnValues?.[0]?.bcs){let c=new Uint8Array(o.returnValues[0].bcs),u=A.vector(A.u64()).parse(c),d={margin_manager_id:e[a].margin_manager_id,base_coin_type:e[a].base_coin_type,quote_coin_type:e[a].quote_coin_type,conditional_order_ids:u.map(f=>f.toString())};s[e[a].margin_manager_id]=d}}),s}normalizeConditionalOrder(e){let n=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",conditional_order_id:n(e.conditional_order_id),condition:{trigger_below_price:e.condition.trigger_below_price,trigger_price:n(e.condition.trigger_price)},pending_order:{is_limit_order:e.pending_order.is_limit_order,client_order_id:n(e.pending_order.client_order_id),order_type:e.pending_order.order_type,self_matching_option:e.pending_order.self_matching_option,price:e.pending_order.price,quantity:n(e.pending_order.quantity),is_bid:e.pending_order.is_bid,pay_with_deep:e.pending_order.pay_with_deep,expire_timestamp:e.pending_order.expire_timestamp}}}async getPoolsPriceBounds(e){if(!e?.length)throw new Error("poolInfos is required");for(let p of e){if(!p.poolId||!p.baseCoin?.coinType||!p.quoteCoin?.coinType)throw new Error("poolId, baseCoin.coinType and quoteCoin.coinType are required");if(!p.baseCoin?.feed||!p.quoteCoin?.feed)throw new Error("baseCoin.feed and quoteCoin.feed are required to refresh pool price")}let n=new Y,r=[...new Set(e.flatMap(p=>[p.baseCoin.feed,p.quoteCoin.feed]))],s=await this.pythPrice.updatePythPriceIDs(r,n),i=this.sdk.sdkOptions.margin_utils.margin_registry_id,o=this.sdk.sdkOptions.deepbook.margin_published_at;for(let p of e){let m=s.get(p.baseCoin.feed),b=s.get(p.quoteCoin.feed);if(!m||!b)throw new Error(`Failed to get price feed object IDs for pool ${p.poolId}`);n.moveCall({target:`${o}::pool_proxy::update_current_price`,arguments:[n.object(i),n.object(p.poolId),n.object(m),n.object(b),n.object(he)],typeArguments:[p.baseCoin.coinType,p.quoteCoin.coinType]}),n.moveCall({target:`${o}::margin_registry::get_price_bounds`,arguments:[n.object(i),n.pure.id(p.poolId),n.object(he)]})}let a=await this.sdk.fullClient.simulateTransaction({transaction:n,checksEnabled:!1,include:{commandResults:!0,json:!0}});if(a?.$kind==="FailedTransaction"||!a?.commandResults?.length){let p=a?.FailedTransaction?.status?.error;throw new Error(`Failed to get pools price bounds: ${p?.message??JSON.stringify(p??"Unknown error")}`)}let c=a.commandResults.filter(p=>p?.returnValues?.length===2);if(c.length<e.length)throw new Error(`Failed to get pools price bounds: expected ${e.length} results, got ${c.length}`);let u=[],d=c.slice(-e.length);for(let p=0;p<e.length;p++){let m=d[p],b=m?.returnValues?.[0]?.bcs??m?.returnValues?.[0]?.[0],v=m?.returnValues?.[1]?.bcs??m?.returnValues?.[1]?.[0];if(!b||!v)throw new Error(`Failed to parse price bounds for pool ${e[p].poolId}`);let T=9-e[p].baseDecimals+e[p].quoteDecimals,O=A.U64.parse(new Uint8Array(b)),B=A.U64.parse(new Uint8Array(v));u.push({pool_id:e[p].poolId,lower_bound:M(O).div(10**T).toString(),upper_bound:M(B).div(10**T).toString()})}let f=new Map;return u.forEach(p=>{f.set(p.pool_id,p)}),{priceBounds:u,priceBoundsMap:f}}};var tN="https://graphql.mainnet.sui.io/graphql",nN="https://graphql.testnet.sui.io/graphql",ld=class{_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=Em(new Ja({baseUrl:e.fullRpcUrl,network:e.network==="testnet"?"testnet":"mainnet"}),new em({network:e.network,url:e.network==="testnet"?nN:tN}),e.network==="testnet"?"testnet":"mainnet",new Lh({url:e.fullRpcUrl,network:e.network})),this._deepbookUtils=new ad(this),this._marginUtils=new ud(this),this._pythPrice=new ya(this),Nm(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}};var rN=(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))(rN||{}),sN=(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))(sN||{});var tK=ld;export{cd as CLOCK_ADDRESS,od as CachedContent,ld as CetusClmmSDK,zZ as ClmmExpectSwapModule,HZ as ClmmFetcherModule,FZ as ClmmIntegratePoolModule,qZ as ClmmIntegratePoolV2Module,$Z as ClmmIntegrateRouterModule,GZ as ClmmIntegrateRouterWithPartnerModule,WZ as ClmmIntegrateUtilsModule,Wt as CoinAssist,ZZ as CoinInfoAddress,JZ as CoinStoreAddress,Dm as DEEP_SCALAR,eZ as DEFAULT_GAS_BUDGET_FOR_MERGE,QW as DEFAULT_GAS_BUDGET_FOR_SPLIT,rZ as DEFAULT_GAS_BUDGET_FOR_STAKE,tZ as DEFAULT_GAS_BUDGET_FOR_TRANSFER,nZ as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,iZ as DEFAULT_NFT_TRANSFER_GAS_FEE,YZ as DeepbookClobV2Moudle,KZ as DeepbookCustodianV2Moudle,XZ as DeepbookEndpointsV2Moudle,ad as DeepbookUtilsModule,eJ as ERROR_HANDLING_RPC_LIST,Cr as FLOAT_SCALAR,es as FLOAT_SCALING,sZ as GAS_SYMBOL,Rm as GAS_TYPE_ARG,X_ as GAS_TYPE_ARG_LONG,ud as MarginUtilsModule,GW as NORMALIZED_SUI_COIN_TYPE,rN as OrderType,oZ as SUI_SYSTEM_STATE_OBJECT_ID,sN as SelfMatchingOption,J3 as YEAR_MS,Z_ as addHexPrefix,mZ as asIntN,hZ as asUintN,MW as bufferToHex,Q_ as cacheTime1min,ga as cacheTime24h,eT as cacheTime5min,aJ as calc100PercentRepay,X3 as calcDebtDetail,Y3 as calcInterestRate,K3 as calcUtilizationRate,iJ as calculateRiskRatio,BW as checkAddress,K_ as composeType,M as d,Bm as decimalsMultiplier,tK as default,qW as extractAddressFromType,gi as extractStructTagFromType,$W as fixCoinType,yo as fixDown,L3 as fixSuiObjectId,bo as fromDecimalsAmount,QZ as getDefaultSuiInputType,jm as getFutureTime,G3 as getMoveObject,V3 as getObjectDeletedResponse,cT as getObjectFields,aT as getObjectId,F3 as getObjectNotExistsResponse,q3 as getObjectReference,oT as getSuiObjectData,jW as hexToNumber,DW as hexToString,FW as isSortedSymbols,_Z as isSuiObjectResponse,Mm as maxDecimal,hT as mulRoundUp,Cm as normalizeCoinType,Nm as patchFixSuiObjectId,nT as printTransaction,Am as removeHexPrefix,gZ as secretKeyToEd25519Keypair,yZ as secretKeyToSecp256k1Keypair,RW as shortAddress,B3 as shortString,tT as sleepTime,M3 as toBuffer,yi as toDecimalsAmount,j3 as utf8to16,pT as wrapDeepBookMarginPoolInfo,fT as wrapDeepBookPoolInfo};
1025
1025
  /*! Bundled license information:
1026
1026
 
1027
1027
  @scure/base/index.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cetusprotocol/deepbook-utils",
3
- "version": "1.5.5",
3
+ "version": "1.5.6",
4
4
  "description": "cetus deepbook utils sdk",
5
5
  "typings": "dist/index.d.ts",
6
6
  "main": "dist/index.js",