@msafe/sui-app-store 0.0.170 → 0.0.172
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -5
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Ql=Object.create;var Ee=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var Hl=Object.getOwnPropertyNames;var Kl=Object.getPrototypeOf,Gl=Object.prototype.hasOwnProperty;var $a=(o,t)=>{for(var e in t)Ee(o,e,{get:t[e],enumerable:!0})},qr=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Hl(t))!Gl.call(o,a)&&a!==e&&Ee(o,a,{get:()=>t[a],enumerable:!(n=Vl(t,a))||n.enumerable});return o};var N=(o,t,e)=>(e=o!=null?Ql(Kl(o)):{},qr(t||!o||!o.__esModule?Ee(e,"default",{value:o,enumerable:!0}):e,o)),zl=o=>qr(Ee({},"__esModule",{value:!0}),o);var fu={};$a(fu,{appHelpers:()=>mu});module.exports=zl(fu);var zr=require("@msafe/sui3-utils");var $r=N(require("sort-keys-recursive")),b=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,$r.default)(this.data))}};var Qr=require("@alphafi/alphafi-sdk"),We=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r,isAmountA:i}=this.data;return await(0,Qr.depositDoubleAssetTxb)(a,n.address,r,i)}static fromData(e){return new o(e)}};var Vr=require("@alphafi/alphafi-sdk"),Le=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r}=this.data;return await(0,Vr.depositSingleAssetTxb)(a,n.address,r)}static fromData(e){return new o(e)}};var Hr=require("@alphafi/alphafi-sdk"),Ue=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{withdrawFromLocked:a,xTokensAmount:r}=this.data;return await(0,Hr.withdrawAlphaTxb)(r,a,n.address)}static fromData(e){return new o(e)}};var Kr=require("@alphafi/alphafi-sdk"),Fe=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,xTokensAmount:r}=this.data;return await(0,Kr.withdrawTxb)(r,a,n.address)}static fromData(e){return new o(e)}};var Gr=require("@alphafi/alphafi-sdk"),qe=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e;return await(0,Gr.claimRewardTxb)(n.address)}static fromData(e){return new o(e)}};var $e=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(t){let{txbParams:e,action:n}=t.appContext;return{txType:zr.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{account:e}=t,n;switch(t.txSubType){case"depositSingleAsset":n=Le.fromData(t.intentionData);break;case"depositDoubleAsset":n=We.fromData(t.intentionData);break;case"withdraw":n=Fe.fromData(t.intentionData);break;case"withdrawAlpha":n=Ue.fromData(t.intentionData);break;case"claimReward":n=qe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({account:e})}};var ni=require("@msafe/sui3-utils");var Zr=require("@msafe/sui3-utils");var Yr=require("@mysten/sui/transactions");var Jr=require("bucket-protocol-sdk"),Xr=(o,t)=>{let e=o==="sui:mainnet"?"mainnet":"testnet";return new Jr.BucketClient(e,t.address)};var Qe=async(o,t,e,n)=>{let{coinType:a,amount:r}=o,i=new Yr.Transaction;return await Xr(e,t).getPsmTx(i,a,r,n,t.address),i};var Ve=class o extends b{constructor(e){super(e);this.data=e}txType=Zr.TransactionType.Other;txSubType="psm-in";async build(e){let{account:n,network:a}=e;return await Qe(this.data,n,a,!1)}static fromData(e){return new o(e)}};var ti=require("@msafe/sui3-utils");var He=class o extends b{constructor(e){super(e);this.data=e}txType=ti.TransactionType.Other;txSubType="psm-out";async build(e){let{account:n,network:a}=e;return await Qe(this.data,n,a,!0)}static fromData(e){return new o(e)}};var Va=require("@msafe/sui3-utils");var ei=require("@mysten/sui/bcs"),Ke=class{constructor(t){this.transaction=t}decode(){if(this.isPsmInTransaction())return this.decodePsmIn();if(this.isPsmOutTransaction())return this.decodePsmOut();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(t=>t.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(t=>t.$kind==="TransferObjects")}isPsmInTransaction(){return!!this.getMoveCallCommand("charge_reservoir")}isPsmOutTransaction(){return!!this.getMoveCallCommand("discharge_reservoir")}decodePsmIn(){let t="0",e=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];e.$kind=="Input"&&(t=this.getPureInputU64(e.Input));let a=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments[0];return console.log("Decoder.decodePsmIn",a,t),{txType:Va.TransactionType.Other,type:"psm-in",intentionData:{coinType:a,amount:t}}}decodePsmOut(){let t="0",e=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];e.$kind=="Input"&&(t=this.getPureInputU64(e.Input));let a=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments[0];return console.log("Decoder.decodePsmOut",a,t),{txType:Va.TransactionType.Other,type:"psm-out",intentionData:{coinType:a,amount:t}}}getPureInputU64(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return ei.bcs.U64.fromBase64(e.Pure.bytes)}};var Ge=class{application="bucket";supportSDK="@mysten/sui";async deserialize(t){console.log("Bucket helper deserialize input: ",t);let{transaction:e}=t,a=new Ke(e).decode();return{txType:ni.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"psm-in":r=Ve.fromData(t.intentionData);break;case"psm-out":r=He.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var ts=require("@msafe/sui3-utils");var pi=require("@msafe/sui3-utils");var ze=require("@cetusprotocol/aggregator-sdk"),oi=require("@cetusprotocol/cetus-periphery-sdk"),ai=require("@cetusprotocol/cetus-sui-clmm-sdk"),ri=require("@mysten/sui/client"),Jl={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0x70968826ad1b4ba895753f634b0aea68d0672908ca1075a2abdf0fc9e0b2fc6a",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x8faab90228e4c4df91c41626bbaefa19fc25c514405ac64de54578dec9e6f5ee",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},Xl={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0xabbd278f738affe762e9df4765b3409bb1e86a355a4f611ad82b278c18108918",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0xd817d90368dafcbf3b051e96546dea6209bffad23289d66025beef80354dcd6b",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Yl={fullRpcUrl:"https://fullnode.testnet.sui.io/",simulationAccount:{address:"0xcd0247d0b67e53dde69b285e7a748e3dc390e8a5244eb9dd9c5c53d95e4cf0aa"},cetus_config:{package_id:"0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca",published_at:"0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca",config:{coin_list_id:"0x257eb2ba592a5480bba0a97d05338fab17cc3283f8df6998a0e12e4ab9b84478",launchpad_pools_id:"0xdc3a7bd66a6dcff73c77c866e87d73826e446e9171f34e1c1b656377314f94da",clmm_pools_id:"0x26c85500f5dd2983bf35123918a144de24e18936d0b234ef2b49fbb2d3d6307d",admin_cap_id:"0x1a496f6c67668eb2c27c99e07e1d61754715c1acf86dac45020c886ac601edb8",global_config_id:"0xe1f3db327e75f7ec30585fa52241edf66f7e359ef550b533f89aa1528dd1be52",coin_list_handle:"0x3204350fc603609c91675e07b8f9ac0999b9607d83845086321fca7f469de235",launchpad_pools_handle:"0xae67ff87c34aceea4d28107f9c6c62e297a111e9f8e70b9abbc2f4c9f5ec20fd",clmm_pools_handle:"0xd28736923703342b4752f5ed8c2f2a5c0cb2336c30e1fed42b387234ce8408ec"}},clmm_pool:{package_id:"0x0868b71c0cba55bf0faf6c40df8c179c67a4d0ba0e79965b68b3d72d7dfbf666",published_at:"0x1c29d658882c40eeb39a8bb8fe58f71a216a918acb3e3eb3b47d24efd07257f2",config:{pools_id:"0xc090b101978bd6370def2666b7a31d7d07704f84e833e108a969eda86150e8cf",global_config_id:"0x6f4149091a5aea0e818e7243a13adcfb403842d670b9a2089de058512620687a",global_vault_id:"0xf3114a74d54cbe56b3e68f9306661c043ede8c6615f0351b0c3a93ce895e1699",admin_cap_id:""}},integrate:{package_id:"0x8627c5cdcd8b63bc3daa09a6ab7ed81a829a90cafce6003ae13372d611fbb1a9",published_at:"0xf1a5d0c5b0593e41d13f9684ca91365bdfe54a98836c1d33c90e361a031fac74",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6",published_at:"0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6"},aggregatorUrl:"https://api-sui.devcetus.com/router",swapCountUrl:"https://api-sui.devcetus.com/v2/sui/swap/count"},Zl={launchpad:{package_id:"0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335",published_at:"0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335",config:{pools_id:"0xccc10403ab3da4ae943847908e0e674fe1fdab81c6383e4c6dcd0eea0edade3d",admin_cap_id:"0x8a72713049dbcfc40902ff209dc5e6066fe455d152baa235957c84d7a3b875ed",config_cap_id:"0x16492b4252b01debb60f8a825334020d7fdb9d895b52f8139c98618de30817fc"}},ido:{package_id:"0x1352bf18ef20458f7cc773852d4a90b240015a6a54479dda3a1debfc500bf044",published_at:"0xbd09a0889ea9970b821512428bab3e2fd01e16809a90a325cd3b3d3573eab6a4",config:{pools_id:"0x346bee25ab4d15bcfa9484ef5ebd4d7c94eb665ebaa745ff4094936a7f59a8b1",admin_cap_id:"0xc1bb19a24d3bb65dfd4f3835637b63347c223c67cde4b0888f1a857974f33cbb",package_version_id:"0x3ccf1b38e3259e638b980d4e6b49eac8c5aa94d3cb2ace5e75f0a551c8e67e5e"}},xcetus:{package_id:"0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966",published_at:"0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966",config:{xcetus_manager_id:"0x3be34cbad122c8b100ed7157d762b9610e68b3c65734e08bc3c3baf857da807d",lock_manager_id:"0x7c67e805182e3fecd098bd68a6b06c317f28f8c6249bd771e07904a10b424e60",lock_handle_id:"0xc5f3bbfefe9a45c13da7a34bc72cac122ee45d633690476a8ac56bd2c4e78c86"}},xcetus_dividends:{package_id:"0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828",published_at:"0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828",config:{dividend_manager_id:"0x13b7facb704fae1d199ff0038b8acabc253415a77d142b39189dee97d457e442",dividend_admin_id:"0x5eb78463007422d4130b21f61c180bcd190819b7792f56e00a61df3b8fb928ef",dividend_settle_id:"0x495095e13a170ff494d242ae44ac2c7453011ca6c33cff27498010105e10e4b4",venft_dividends_id:"",venft_dividends_id_v2:""}},cetus_faucet:{package_id:"0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7",published_at:"0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9",published_at:"0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9",config:{admin_cap_id:"0x9b2d6f5be2650d16d27cd630c4539a76d7793970343ed3cbb023e13f1637c07c",vaults_manager_id:"0xc0a1a937df08880e395d85014ff40c74f13abe7a53abdbffea36f51adaaaf79e",vaults_pool_handle:"0x3ab02203de753de9c8198cc0ce7594dc960878f2c34c5c5a4b7742082241860a"}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0",published_at:"0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0",config:{global_config_id:"0x5082c7a5ee9a758025d7b0a5e8aa08b56625c7cd535b8909d2b7993991e229cc",rewarder_manager_id:"0xe789e092dbd9dceadbe89350c4761a6f2e11647aab97f09746a01b151926cc0e",rewarder_manager_handle:"0x7e7dd42392b5d82564dc9ad5093a111c5f0598cc9f806cff257d7dacb71f7837",admin_cap_id:"0x4ec248bca2d1fc05f39fd7491ab490464a46d128624caa4d3c2a66d957ef40b0"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Dt=(o,t)=>{let e=o==="sui:mainnet"?Jl:Yl,n=new ai.CetusClmmSDK(e);return n.senderAddress=t.address,n},j=(o,t)=>{let e=Dt(o,t),n=o==="sui:mainnet"?Xl:Zl;return new oi.CetusPeripherySDK(n,e)},td="https://api-sui.cetus.zone/router_v2/find_routes",ii=(o,t)=>{let e=new ri.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new ze.AggregatorClient(td,t.address,e,ze.Env.Mainnet)};var si=async(o,t,e)=>await Dt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),ci=async(o,t,e)=>await Dt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),li=async(o,t,e)=>await Dt(e,t).Position.closePositionTransactionPayload(o),di=async(o,t,e)=>await Dt(e,t).Position.removeLiquidityTransactionPayload(o),ui=async(o,t,e)=>await Dt(e,t).Rewarder.collectRewarderTransactionPayload(o);var Je=class o extends b{constructor(e){super(e);this.data=e}txType=pi.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await si(r,n,a)}static fromData(e){return new o(e)}};var mi=require("@msafe/sui3-utils");var Xe=class o extends b{constructor(e){super(e);this.data=e}txType=mi.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ui(r,n,a)}static fromData(e){return new o(e)}};var fi=require("@msafe/sui3-utils");var Ye=class o extends b{constructor(e){super(e);this.data=e}txType=fi.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await di(r,n,a)}static fromData(e){return new o(e)}};var ki=require("@msafe/sui3-utils");var bi=async(o,t,e)=>await j(e,t).Farms.openPositionAddLiquidityStakePaylod(o),gi=async(o,t,e)=>await j(e,t).Farms.addLiquidityFixCoinPayload(o),hi=async(o,t,e)=>await j(e,t).Farms.removeLiquidityPayload(o),yi=async(o,t,e)=>await j(e,t).Farms.removeLiquidityPayload(o),Si=async(o,t,e)=>await j(e,t).Farms.claimFeeAndClmmReward(o),wi=async(o,t,e)=>await j(e,t).Farms.harvestPayload(o),Ti=async(o,t,e)=>{let n=j(e,t),a=Object.values(o);return await n.Farms.batchHarvestPayload(a)},Ii=async(o,t,e)=>await j(e,t).Farms.depositPayload(o),Ci=async(o,t,e)=>await j(e,t).Farms.withdrawPayload(o);var Ze=class o extends b{constructor(e){super(e);this.data=e}txType=ki.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await bi(r,n,a)}static fromData(e){return new o(e)}};var xi=require("@msafe/sui3-utils");var tn=class o extends b{constructor(e){super(e);this.data=e}txType=xi.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ti(r,n,a)}static fromData(e){return new o(e)}};var vi=require("@msafe/sui3-utils");var en=class o extends b{constructor(e){super(e);this.data=e}txType=vi.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Si(r,n,a)}static fromData(e){return new o(e)}};var Di=require("@msafe/sui3-utils");var nn=class o extends b{constructor(e){super(e);this.data=e}txType=Di.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await hi(r,n,a)}static fromData(e){return new o(e)}};var Ai=require("@msafe/sui3-utils");var on=class o extends b{constructor(e){super(e);this.data=e}txType=Ai.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await wi(r,n,a)}static fromData(e){return new o(e)}};var Oi=require("@msafe/sui3-utils");var an=class o extends b{constructor(e){super(e);this.data=e}txType=Oi.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await gi(r,n,a)}static fromData(e){return new o(e)}};var Pi=require("@msafe/sui3-utils");var rn=class o extends b{constructor(e){super(e);this.data=e}txType=Pi.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await yi(r,n,a)}static fromData(e){return new o(e)}};var _i=require("@msafe/sui3-utils");var sn=class o extends b{constructor(e){super(e);this.data=e}txType=_i.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ii(r,n,a)}static fromData(e){return new o(e)}};var Ri=require("@msafe/sui3-utils");var cn=class o extends b{constructor(e){super(e);this.data=e}txType=Ri.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ci(r,n,a)}static fromData(e){return new o(e)}};var Bi=require("@msafe/sui3-utils");var ln=class o extends b{constructor(e){super(e);this.data=e}txType=Bi.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ci(r,n,a)}static fromData(e){return new o(e)}};var ji=require("@msafe/sui3-utils");var dn=class o extends b{constructor(e){super(e);this.data=e}txType=ji.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await li(r,n,a)}static fromData(e){return new o(e)}};var Wi=require("@msafe/sui3-utils");var Mi=require("@cetusprotocol/aggregator-sdk"),Ni=require("@mysten/sui/transactions");var Ei=async(o,t,e)=>{let n=ii(e,t),a=new Ni.Transaction;return await n.fastRouterSwap({...o,routers:(0,Mi.restituteMsafeFastRouterSwapParams)(o.routers),txb:a}),a};var un=class o extends b{constructor(e){super(e);this.data=e}txType=Wi.TransactionType.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ei(r,n,a)}static fromData(e){return new o(e)}};var qi=require("@msafe/sui3-utils");var Ui=require("@mysten/sui/transactions"),Li={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Fi=async(o,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",o),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:a,periods:r,CLOCK_ADDRESS:i}=o,s=new Ui.Transaction;return r.forEach(c=>{s.moveCall({target:`${Li.published_at}::router::redeem`,typeArguments:[Li.cetus_coin_type],arguments:[s.object(n),s.object(a),s.pure(c),s.object(i)]})}),s};var pn=class o extends b{constructor(e){super(e);this.data=e}txType=qi.TransactionType.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Fi(r,n,a)}static fromData(e){return new o(e)}};var zi=require("@msafe/sui3-utils");var $i=require("@mysten/sui/transactions");var Qi=async(o,t,e)=>{let n=j(e,t),a=new $i.Transaction;return await n.XCetusModule.convertPayload(o,a)},Vi=async(o,t,e)=>await j(e,t).XCetusModule.redeemLockPayload(o),Hi=async(o,t,e)=>await j(e,t).XCetusModule.redeemDividendV3Payload(o.phases,o.venft_id,o.bonus_types,o.bonus_types_v2,o.xTokenType),Ki=async(o,t,e)=>await j(e,t).XCetusModule.cancelRedeemPayload(o),Gi=async(o,t,e)=>await j(e,t).XCetusModule.redeemPayload(o);var mn=class o extends b{constructor(e){super(e);this.data=e}txType=zi.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ki(r,n,a)}static fromData(e){return new o(e)}};var Ji=require("@msafe/sui3-utils");var fn=class o extends b{constructor(e){super(e);this.data=e}txType=Ji.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Hi(r,n,a)}static fromData(e){return new o(e)}};var Xi=require("@msafe/sui3-utils");var bn=class o extends b{constructor(e){super(e);this.data=e}txType=Xi.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Qi(r,n,a)}static fromData(e){return new o(e)}};var Yi=require("@msafe/sui3-utils");var gn=class o extends b{constructor(e){super(e);this.data=e}txType=Yi.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Gi(r,n,a)}static fromData(e){return new o(e)}};var Zi=require("@msafe/sui3-utils");var hn=class o extends b{constructor(e){super(e);this.data=e}txType=Zi.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Vi(r,n,a)}static fromData(e){return new o(e)}};var yn=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:ts.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=Je.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ln.fromData(t.intentionData);break;case"DecreaseLiquidity":r=Ye.fromData(t.intentionData);break;case"RemoveLiquidity":r=dn.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=Xe.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=Ze.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=an.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=nn.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=rn.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=en.fromData(t.intentionData);break;case"FarmingHarvest":r=on.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=tn.fromData(t.intentionData);break;case"FarmingStake":r=sn.fromData(t.intentionData);break;case"FarmingUnstake":r=cn.fromData(t.intentionData);break;case"xCETUSConvert":r=bn.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=hn.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=fn.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=mn.fromData(t.intentionData);break;case"xCETUSRedeem":r=gn.fromData(t.intentionData);break;case"VestingRedeem":r=pn.fromData(t.intentionData);break;case"AggregatorSwap":r=un.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Cs=require("@msafe/sui3-utils");var es=N(require("sort-keys-recursive")),y=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,es.default)(this.data))}};var oe=require("@mysten/sui.js/client");var Ha={};$a(Ha,{contractId:()=>od,default:()=>cd,feeObjId:()=>id,roleObjId:()=>ad,status:()=>nd,transaction:()=>ed,upgradeCapObjId:()=>sd,vaultObjId:()=>rd});var ed="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",nd="success",od="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",ad="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",rd="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",id="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",sd="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",cd={transaction:ed,status:nd,contractId:od,roleObjId:ad,vaultObjId:rd,feeObjId:id,upgradeCapObjId:sd};var Ka={};$a(Ka,{contractId:()=>ud,default:()=>gd,feeObjId:()=>fd,roleObjId:()=>pd,status:()=>dd,transaction:()=>ld,upgradeCapObjId:()=>bd,vaultObjId:()=>md});var ld="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",dd="success",ud="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",pd="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",md="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",fd="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",bd="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",gd={transaction:ld,status:dd,contractId:ud,roleObjId:pd,vaultObjId:md,feeObjId:fd,upgradeCapObjId:bd};var hd=(0,oe.getFullnodeUrl)("testnet"),yd=(0,oe.getFullnodeUrl)("testnet"),Sd=(0,oe.getFullnodeUrl)("mainnet"),wd=(0,oe.getFullnodeUrl)("mainnet"),Td="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Id="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Cd="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",kd="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",ns=Ha,os=Ka,xd=new Map([["dev",{env:"dev",rpc:{url:hd},backend:{url:Td},contract:ns}],["stg",{env:"stg",rpc:{url:yd},backend:{url:Id},contract:ns}],["prev",{env:"prev",rpc:{url:Sd},backend:{url:Cd},contract:os}],["prod",{env:"prod",rpc:{url:wd},backend:{url:kd},contract:os}]]);function as(o,t){let e=xd.get(o);if(!e)throw new Error(`Env not supported: ${o}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}var rs=require("@mysten/sui.js/client");var k=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:a,context:r}=n;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var Sn=class extends k{constructor(){super(11,"Backend is not specified")}};var wn=class extends k{constructor(){super(1,"Wallet not connected")}};var Y=N(require("axios"));var Mt=class extends k{constructor(t,e){super(10,t,{context:e})}};var Tn=class o{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Y.AxiosError)throw new Mt(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new Mt(t.data.code)}throw new Mt(t.status.toString())}async getIncomingStreams(t,e){let n=await Y.default.post(`${this.apiURL}/stream`,{recipient:t,...e});return o.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await Y.default.post(`${this.apiURL}/stream`,{sender:t,...e});return o.parseResponseData(n)}async getStreamHistory(t){let e=await Y.default.post(`${this.apiURL}/stream-events`,t),n=o.parseResponseData(e);return n.data.forEach(a=>{let r=a;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await Y.default.post(`${this.apiURL}/stream-info`,{address:t});return o.parseResponseData(e)}async getAllRecipients(t,e){let n=await Y.default.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return o.parseResponseData(n)}async getAllSenders(t,e){let n=await Y.default.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return o.parseResponseData(n)}};var Nt=class o{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new rs.SuiClient({url:t.rpc.url}),t.backend&&(this._backend=new Tn(t.backend.url))}static new(t,e){let n=as(t,e);return new o(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Sn;return this._backend}set backend(t){this._backend=t}connectWallet(t){this.signer=t}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new wn;return this.signer}async walletAddress(){return this.wallet.address()}};var Ot=require("@mysten/sui.js/utils");var le=require("@mysten/sui.js/transactions");var Ya=require("@mysten/sui.js/transactions"),ce=require("@mysten/sui.js/utils");var Ga=50n,In=10000n,is=25n,za=100000000n;var z=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},ae=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},it=class o{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);let a=i=>new o(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return a(r)}})}moveArg(){return this.result}};var Ja=require("buffer"),ss=require("@mysten/sui.js/utils");var re=class extends k{constructor(t,e){super(3,t,{context:e})}};var Cn=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="address")throw new re("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return(0,ss.normalizeSuiAddress)(Ja.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="u64")throw new re("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return Ja.Buffer.from(n).readBigInt64LE()}};var Xa=require("@mysten/sui.js/bcs");var D=class extends k{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var ls={groupId:"string",name:"string"},vd=64;function ds(o){return us(o),Xa.bcs.ser(ls,o).toString("base64")}function ie(o){let t=Xa.bcs.de(ls,o,"base64");return us(t),t}function us(o){if(!cs(o.name))throw new D("Invalid metadata: Name contains unknown character");if(!cs(o.groupId))throw new D("Invalid metadata: Group ID contains unknown character");if(o.name.length>vd)throw new D("Invalid metadata: Name exceed max length 64")}function cs(o){return/^[\x00-\x7F]+$/.test(o)}var se=require("@mysten/sui.js/utils");function kn(o,t){return(0,se.normalizeStructTag)(o)===(0,se.normalizeStructTag)(t)}function st(o,t){return(0,se.normalizeStructTag)(o)===(0,se.normalizeStructTag)(t)}var xn="txn.gas";var ps=require("nanoid");function ms(){return(0,ps.nanoid)()}var At=class o{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:ds({name:t.name,groupId:ms()}),coinType:(0,ce.normalizeStructTag)(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new Ya.TransactionBlock,n=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,r[0]),s;a.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let l=t.recipients[c],d=this.amountForRecipient(l,t.numberEpoch),u=this.getStreamFeeLocal(d),[p]=e.splitCoins(i,[e.pure(d+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new it(p),flatFeeCoin:new it(m),metadata:t.metadata,recipient:l.address,timeStart:t.startTime,cliff:l.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=o.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:Ga,denominator:In},claimFeePercent:{numerator:is,denominator:In},flatFeePerStream:za}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),n=t.object(e.primaryCoin)):e.primaryCoin===xn?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return kn(n,ce.SUI_TYPE_ARG)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:ce.SUI_TYPE_ARG,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:a.totalAmount+i,streamFeeAmount:a.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(t.recipients.length)*this.flatSuiFee,...e}}amountForRecipient(t,e){return BigInt(t.amountPerEpoch)*BigInt(e)+BigInt(t.cliffAmount)}get flatSuiFee(){return za}getStreamFeeLocal(t){return t*Ga/In}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Ya.TransactionBlock,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Cn(n).getU64()}get wallet(){return this.globals.wallet}};var Za=require("@mysten/sui.js/transactions");var fs="0x0000000000000000000000000000000000000000000000000000000000000006";var Et=class{constructor(t,e,n){this.moduleName=t;this.config=e;this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Za.Transactions.MoveCall({target:n,arguments:e.arguments.map(a=>a instanceof ae?a.moveArgs(t):a instanceof z?a.moveArg(t):a instanceof it?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],a=[]){t.add(Za.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof ae?r.moveArgs(t):r instanceof z?r.moveArg(t):r instanceof it?r.moveArg():t.pure(r)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new z(t):t}vaultObject(){return new z(this.config.vaultObjId)}roleObject(){return new z(this.config.roleObjId)}feeObject(){return new z(this.config.feeObjId)}clockObject(){return new z(fs)}};var Wt=class o extends Et{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_fee,arguments:[a,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_flat_fee,arguments:[a,r,n],typeArgs:[]})}setClaimFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_claim_fee,arguments:[a,r,n],typeArgs:[]})}streamingFee(e,n){let a=this.feeObject();return this.addContractCall(e,{method:o.MethodName.streaming_fee,arguments:[a,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:o.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:o.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var J=class o extends Et{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,n){let a=this.feeObject(),r=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:o.MethodName.create_stream,arguments:[a,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let a=this.makeObject(n.streamId);return this.addContractCall(e,{method:o.MethodName.set_auto_claim,arguments:[a,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.cancel_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let a=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream_by_proxy,arguments:[a,r,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream_by_proxy}`}};var Lt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Wt(e,t),this.streamContract=new J(e,t)}feeContract;streamContract;async createStreams(t){let e=At.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new At(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let a=new le.TransactionBlock;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new le.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new le.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new le.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var P=class extends k{constructor(t,e={}){super(0,t,e)}};async function er(o){let t=[];for(;await o.hasNext();){let e=await o.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var tr=class{constructor(t){this.requester=t;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},Ut=class{constructor(t){this.requester=t;this.pager=new tr(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var vn=class extends k{constructor(e,n,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:a}});this.coinType=e;this.requestAmount=n;this.gotAmount=a}};var Dd=25;async function bs(o,t,e,n="0x2::sui::SUI",a=Dd){let r=new nr(o,t,n,a),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new vn(n,e,i);return s}var nr=class extends Ut{constructor(e,n,a,r){super(new or(e,n,a,r));this.suiClient=e;this.owner=n;this.coinType=a;this.reqPageSize=r}},or=class{constructor(t,e,n,a){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=a;if(a<=0)throw new P("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var pe=require("@mysten/sui.js/transactions"),me=require("@mysten/sui.js/utils"),hs=require("luxon");var Dn=class extends k{constructor(){super(7,"Connected wallet is not creator")}};var de=class extends k{constructor(){super(8,"Connected wallet is not recipient")}};var ue=class extends k{constructor(t,e){super(6,t,{context:e})}};var An=class extends k{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};var Pn=require("luxon"),gs=(1n<<64n)-1n,On=1e3;function ar(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/On);return Pn.DateTime.fromMillis(e*On)}function rr(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/On);return Pn.Duration.fromMillis(e*On)}var ct=class o{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new J(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await o.fetchStreamData(t,e);return new o(t,e,n)}static fromObjectData(t,e,n){let a=o.parseRawStreamData(e,n);return new o(t,e,a)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await o.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new P("Object Id does not align");this.rawData=o.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new Dn;let t=new pe.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new de;let t=new pe.TransactionBlock;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new de;let e=new pe.TransactionBlock;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new pe.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,me.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return rr(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return ie(t).groupId}get name(){let{metadata:t}=this.rawData.config;return ie(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ar(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return rr(e)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:ar((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let t=this.rawData.status.status;return t===16?"CANCELED":t===17?"SETTLED":t===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===gs?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=hs.DateTime.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let n=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let n=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return o.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new An(t):new ue(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new ue("Unexpected object type",{gotType:n.dataType});let{typeParams:a}=(0,me.parseStructTag)(n.type),r=(0,me.normalizeStructTag)(a[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};var Ft=require("@mysten/sui.js/utils"),ir=require("luxon");var _n=class extends k{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Ad=1e3,Rn=class{constructor(t){this.globals=t;this.coinMetaHelper=new sr(t.suiClient),this.createStreamHelper=new Lt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new _n(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-n)/t.steps,i={realTotalAmount:a*t.steps+n,cliffAmount:n,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(ir.Duration.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:n,interval:ir.Duration.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...n,coinType:(0,Ft.normalizeStructTag)(n.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,r)=>({...a,coinType:(0,Ft.normalizeStructTag)(a.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new D("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new D("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Ad)throw new D("Interval shall be at least 1 second","interval",t.interval)}},sr=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ft.normalizeStructTag)(t||Ft.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};var lt=require("@mysten/sui.js/utils"),dr=require("luxon");var qt=class extends k{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var Od=25;async function lr(o,t,e){let n=new fe(t),a=new be(o,n,e);return await er(a)}var fe=class{constructor(t){this.ids=t;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},be=class extends Ut{constructor(e,n,a){super(new cr(e,n,a));this.suiClient=e;this.idIter=n;this.options=a}},cr=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||Od,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:a}=this;n=e.filter(r=>a?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Bn=class o{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new qt("stream size 0");let n=e.map(r=>r.groupId);if(new Set(n).size!==1)throw new D("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await lr(t.suiClient,e);return n.forEach(a=>{if(!a)throw new P("stream group object data undefined")}),o.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let a=await o.parseGroupStreams(t,e,n);return new o(t,a)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],a=!0;return e.forEach(r=>{Pd(n,r)||(a=!1)}),a}async refresh(){let t=await lr(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,n)=>{e.refreshWithData(t[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(t=>t.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((t,e)=>t+e.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((t,e)=>t+e.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((t,e)=>e.nextReleaseAmount===null?t:t+e.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((t,e)=>t+e.totalAmount,0n),streamed:this.streams.reduce((t,e)=>t+e.streamedAmount,0n),claimed:this.streams.reduce((t,e)=>t+e.claimedAmount,0n),claimable:this.streams.reduce((t,e)=>t+e.claimable,0n),canceled:this.streams.reduce((t,e)=>t+e.canceledAmount,0n)}}async historyEvents(t){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:t})}static async parseGroupStreams(t,e,n){let a=n.map((r,i)=>ct.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(a.map(r=>r.groupId)).size!==1)throw new qt("Not same group ID");if(!this.checkStreamGroup(a))throw new qt("Not same stream settings");return a}};function Pd(o,t){return o.name===t.name&&o.groupId===t.groupId&&o.creator===t.creator&&o.start.toMillis()===t.start.toMillis()&&o.interval.toMillis()===t.interval.toMillis()&&o.steps===t.steps&&o.cancelable===t.cancelable}var ge=class o{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await jn.newIncoming(t);return new o(e,t.pageSize)}static async newOutgoing(t){let e=await jn.newOutgoing(t);return new o(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},jn=class o{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Mn.newIncomingQuery(t);return new o(e)}static async newOutgoing(t){let e=await Mn.newOutgoingQuery(t);return new o(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new P("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new P("No more results");return t}},Mn=class o{constructor(t,e,n,a){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=a;this.current=0;let r=new fe(n.flat().map(i=>i.streamId));this.objectIter=new be(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=Md(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>(0,lt.normalizeSuiAddress)(s.recipient)===(0,lt.normalizeSuiAddress)(n)),i=ys(r);return new o(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=Nd(t.query),n=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(n,e),r=ys(a);return new o(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Bd(this.globals,t[0].streamId,this.objectIter);return this.current++,Ss(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await jd(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,Rd(e,this.query)?e:this.doNextRequest()}throw new P("Stream group with no stream")}};function ys(o){let t=new Map;return o.forEach(e=>{let n=t.get(e.groupId);n?(n.push(e),t.set(e.groupId,n)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,n)=>dr.DateTime.fromISO(n[0].createDate).toMillis()-dr.DateTime.fromISO(e[0].createDate).toMillis())}function Ss(o,t){if(t===void 0)return!0;let e=_d(o,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?o.progress.claimable!==0n:o.progress.claimable===0n;return e&&n}return e}function _d(o,t){return t===void 0?!0:Array.isArray(t)?t.includes(o.progress.status):o.progress.status===t}function Rd(o,t){if(!t)return!0;let e=!1;return o.streams.forEach(n=>{Ss(n,t)&&(e=!0)}),e}async function Bd(o,t,e){let n=await ws(e,t);return ct.fromObjectData(o,t,n)}async function jd(o,t,e){let n=[];for(;n.length<t.length;){let a=await ws(e,t[n.length]);n.push(a)}return Bn.newFromObjectResponse(o,t,n)}async function ws(o,t){if(!await o.hasNext())throw new P("object iterator has been consumed");let e=await o.next();if(!e||e.error||e.data===void 0||e.data===null)throw new P("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new P("stream id not aligned");return e}function Md(o){return{status:ur(o?.status),coinType:Ts(o?.coinType),sender:Is(o?.sender)}}function Nd(o){return{status:ur(o?.status),coinType:Ts(o?.coinType),recipient:Is(o?.recipient)}}function ur(o){return o===void 0||o.length===0?"all":Array.isArray(o)?o.reduce((t,e)=>{let n=ur(e);return!t||t===n?n:"all"},void 0):Ed(o)}function Ed(o){switch(o){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new D("Unknown stream filtered status")}}function Ts(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,lt.normalizeStructTag)(t)):void 0:(0,lt.normalizeStructTag)(o)}function Is(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,lt.normalizeSuiAddress)(t)):void 0:(0,lt.normalizeSuiAddress)(o)}var pr=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Nn=class{constructor(t){this.account=t}async address(){return this.account.address}},mr=class{constructor(t,e){this.singleWallet=t;this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(kn(t.coinType,Ot.SUI_TYPE_ARG))return{primaryCoin:xn};if(t.amount<=0)throw new D("Invalid coin request","coinAmount",t.amount);let e=await bs(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new P("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},En=class{globals;helper;constructor(t,e){this.globals=Nt.new(t,e),this.helper=new Rn(this.globals)}connectSingleWallet(t){let e=new mr(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new pr(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ct.new(this.globals,t)}async getIncomingStreams(t,e=10){return ge.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return ge.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(n=>(0,Ot.normalizeStructTag)(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>(0,Ot.normalizeSuiAddress)(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>(0,Ot.normalizeSuiAddress)(a))}get wallet(){return this.globals.wallet}builder(){return new Lt(this.globals)}};var H=class extends y{application="mpay";getClient(t,e){let n=new En(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Nn(e)),n}};var he=class extends H{constructor(e){super(e);this.data=e}txType=Cs.TransactionType.Stream;txSubType="Cancel";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).cancel()}};var ks=require("@msafe/sui3-utils");var ye=class extends H{constructor(e){super(e);this.data=e}txType=ks.TransactionType.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claimByProxy()}};var xs=require("@msafe/sui3-utils");var Se=class extends H{constructor(e){super(e);this.data=e}txType=xs.TransactionType.Stream;txSubType="Claim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claim()}};var vs=require("@msafe/sui3-utils");var we=class extends H{constructor(e){super(e);this.data=e}txType=vs.TransactionType.Stream;txSubType="CreateStream";async build(e){let{network:n,account:a}=e;return this.getClient(n,a).createStream(this.data)}};var fr=require("@mysten/sui.js/bcs"),dt=require("@mysten/sui.js/utils"),$t=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,dt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return fr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,dt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,dt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,dt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,dt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return fr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,dt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Wn=class{constructor(t,e){this.globals=t;this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let e=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&st(e.target,this.contract.createStreamTarget));if(t.length===0)throw new P("No create stream transactions");return t.map(e=>new $t(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:a}=ie(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:a,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(a=>JSON.stringify({name:a.name,groupId:a.groupId,timeStart:String(a.timeStart),epochInterval:String(a.epochInterval),totalEpoch:String(a.totalEpoch),cancelable:a.cancelable,coinType:a.coinType}))).size!==1)throw new D("Stream group not have common info");let n=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:n,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new J(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Wt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new At(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}};var Ln=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new J(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(e=>e.kind==="MoveCall"&&st(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Wn(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:t}}decodeClaimByProxyTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:t}}decodeCancelStreamTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:t}}get helper(){let t=this.transactions[0];return new $t(t,this.txb)}};var Ds=require("@msafe/sui3-utils");var Te=class extends H{constructor(e){super(e);this.data=e}txType=Ds.TransactionType.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Un=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,a=Nt.new(e==="sui:mainnet"?"prod":"dev"),i=new Ln(a,n).decode(),s;switch(i.type){case"CreateStream":s=new we(i.info);break;case"SetAutoClaim":s=new Te({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Se({streamId:i.streamId});break;case"ClaimByProxy":s=new ye({streamId:i.streamId});break;case"Cancel":s=new he({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:s.txType,txSubType:s.txSubType,intentionData:s.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new we(e);break;case"Claim":n=new Se(e);break;case"ClaimByProxy":n=new ye(e);break;case"SetAutoClaim":n=new Te(e);break;case"Cancel":n=new he(e);break;default:throw new Error("not implemented")}return n.build({...t})}};var Qt=require("@msafe/sui3-utils");var As=require("@msafe/sui3-utils");var Fn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,As.buildCoinTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var Os=require("@msafe/sui3-utils");var qn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,Os.buildObjectTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var Ps=require("@msafe/sui3-utils"),_s=require("@mysten/sui.js/transactions");var $n=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,a=_s.TransactionBlock.from(this.data.content);if(!(0,Ps.isSameAddress)(a.blockData.sender,n.address))throw new Error("Invalid sender address");return a}static fromData(e){return new o(e)}};var Qn=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Qt.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case Qt.TransactionSubTypes.assets.coin.send:a=Fn.fromData(t.intentionData);break;case Qt.TransactionSubTypes.assets.object.send:a=qn.fromData(t.intentionData);break;case Qt.TransactionSubTypes.others.plain:a=$n.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var qs=require("@msafe/sui3-utils");var Rs=!1,Ie={ProtocolPackage:"0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function br(){if(!Rs)try{let o=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n,pool:a}=o;t&&(Ie.ProtocolPackage=t),e&&(Ie.borrowFee=e),n&&(Ie.borrowFeeAddress=n),a&&(Ie.pool=a),Rs=!0}catch(o){console.error(o.message)}}var h=Ie;var _t=require("@msafe/sui3-utils"),gr=require("@mysten/sui.js/bcs"),ut=require("@mysten/sui.js/utils");var Vn=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::borrow`)}isEntryMultiDepositTransaction(){let t=`${h.ProtocolPackage}::incentive_v2::entry_deposit`,e=this.transactions.filter(a=>a.kind==="MoveCall"&&a.target===t);return this.transactions.find(a=>a.kind==="MoveCall"&&a.target===`${h.ProtocolPackage}::incentive_v2::claim_reward_non_entry`)?!1:e.length>1}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(h.pool).find(n=>n.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${h.ProtocolPackage}::incentive_v2::claim_reward`){let n=new Ce(e,this.txb),a=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(a),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:a,poolId:i})}}),console.log("decode claims",t),{txType:_t.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:_t.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryMultiDeposit(){let t=[],e=`${h.ProtocolPackage}::incentive_v2::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===e){let a=new Ce(n,this.txb),r=a.decodeInputU8(3),i=a.decodeInputU64(5),s=this.findPoolByAssetId(r);t.push({coinType:s.coinType,amount:i})}}),{txType:_t.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:t}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:_t.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:_t.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:_t.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(h.ProtocolPackage));return new Ce(t,this.txb)}},Ce=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,ut.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return gr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,ut.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,ut.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,ut.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,ut.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return gr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,ut.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Ns=require("@mysten/sui.js/transactions");function Vt(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[o.object("0x06"),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Bs(o,t,e){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function js(o,t,e,n){let a=o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.IncentiveV2)],typeArguments:[t.type]}),[r]=o.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[a]});if(h.borrowFee>0){let[i]=o.splitCoins(r,[o.pure(Math.floor(e*h.borrowFee))]);o.transferObjects([r],o.pure(n)),o.transferObjects([i],o.pure(h.borrowFeeAddress))}else o.transferObjects([r],o.pure(n));return o}function hr(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Ms(o,t,e,n,a){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[o.object("0x06"),o.object(h.IncentiveV2),o.object(e),o.object(h.StorageId),o.pure(t),o.pure(n)],typeArguments:a}),o}var Hn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Ns.TransactionBlock;return e.forEach(a=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=a;Ms(n,r,i,s,c)}),n}static fromData(e){return new o(e)}};var Es=require("@mysten/sui.js/transactions");var Kn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:a}=this.data,r=new Es.TransactionBlock;console.log("build",this.data);let i=h.pool[n];if(!i)throw new Error(`${n} not support, please use ${Object.keys(h.pool).join(", ")}.`);return js(r,i,a,e.account.address)}static fromData(e){return new o(e)}};var Ws=require("@mysten/sui.js/transactions");async function Ht(o,t,e){let n=await o.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var Gn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new Ws.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Vt(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await Ht(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return Vt(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var Ls=require("@mysten/sui.js/transactions");var zn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new Ls.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return hr(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await Ht(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return hr(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var Us=require("@mysten/sui.js/transactions");var Jn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,a=new Us.TransactionBlock;console.log("build",this.data);let r=h.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return Bs(a,r,n)}static fromData(e){return new o(e)}};var Fs=require("@mysten/sui.js/transactions");var Xn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{list:r}=this.data,i=new Fs.TransactionBlock;console.log("build",this.data);for(let s=0;s<r.length;s++){let{coinType:c,amount:l}=r[s];if(c==="sui"){let[m]=i.splitCoins(i.gas,[l]);Vt(i,h.pool.sui,m,l);continue}let d=h.pool[c];if(!d)throw new Error(`${c} not support, please use ${Object.keys(h.pool).join(", ")}.`);let u=await Ht(n,a.address,d.type);if(!u.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let p=u.data[0].coinObjectId;if(u.data.length>=2){let m=1;for(;m<u.data.length;)i.mergeCoins(p,[u.data[s].coinObjectId]),m++}Vt(i,d,i.object(p),l)}return i}static fromData(e){return new o(e)}};var Yn=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await br();let{transactionBlock:e}=t,a=new Vn(e).decode();return{txType:qs.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(await br(),t.txSubType){case"EntryDeposit":a=Gn.fromData(t.intentionData);break;case"EntryBorrow":a=Kn.fromData(t.intentionData);break;case"EntryRepay":a=zn.fromData(t.intentionData);break;case"EntryWithdraw":a=Jn.fromData(t.intentionData);break;case"EntryMultiDeposit":a=Xn.fromData(t.intentionData);break;case"ClaimReward":a=Hn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var ke=require("@msafe/sui3-utils"),to=require("@mysten/bcs"),$s=require("@mysten/sui/transactions"),Qs=N(require("sort-keys-recursive")),Vs="msafe-plain-tx",Hs=ke.TransactionSubTypes.others.plain,yr=class o{constructor(t){this.data=t}application=Vs;txType=ke.TransactionType.Other;txSubType=Hs;serialize(){return JSON.stringify((0,Qs.default)(this.data))}async build(t){return $s.Transaction.from((0,to.fromHEX)(this.data.content))}static fromData(t){return new o(t)}},Zn=class{application;supportSDK="@mysten/sui";constructor(){this.application=Vs}async deserialize(t){let{transaction:e}=t,n=await e.build({client:t.suiClient});return{txType:ke.TransactionType.Other,txSubType:Hs,intentionData:{content:(0,to.toHEX)(n)}}}async build(t){let{account:e}=t,a=await yr.fromData(t.intentionData).build({suiClient:t.suiClient,network:t.network,account:t.account}),i=await t.suiClient.devInspectTransactionBlock({transactionBlock:a,sender:e.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return a}};var Sr=require("@mysten/sui/client"),Ks=require("@mysten/sui/transactions"),eo=require("@mysten/sui.js/client"),Gs=require("@mysten/sui.js/transactions"),no=class o{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new o;for(let n=0;n<t.length;n++){let a=t[n];switch(a.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(a);break;case"@mysten/sui":e.addHelper(a);break;default:throw new Error(`${a.application}: ${a.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new Tr(t))}addHelper(t){this.apps.set(t.application,new wr(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},wr=class{constructor(t){this.helper=t}async deserialize(t){let e=new Sr.SuiClient({url:t.clientUrl}),n=new eo.SuiClient({url:t.clientUrl}),a=await t.transactionBlock.build({client:n}),r=Ks.Transaction.from(a);return this.helper.deserialize({...t,suiClient:e,transaction:r})}async build(t){let e=new Sr.SuiClient({url:t.clientUrl}),n=await this.helper.build({...t,suiClient:e});n.setSender(t.account.address);let a=await n.build({client:e});return Gs.TransactionBlock.from(a)}},Tr=class{constructor(t){this.helper=t}async deserialize(t){let e=new eo.SuiClient({url:t.clientUrl});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new eo.SuiClient({url:t.clientUrl});return this.helper.build({...t,suiClient:e})}};var Ec=require("@msafe/sui3-utils");var A=require("@msafe/sui3-utils");var pt=class{constructor(t,e){this.txb=t;this.scallop=e}scallop;get coreId(){return{protocolPkg:this.scallop.address.get("core.packages.protocol.id"),market:this.scallop.address.get("core.market"),version:this.scallop.address.get("core.version"),coinDecimalsRegistry:this.scallop.address.get("core.coinDecimalsRegistry"),xOracle:this.scallop.address.get("core.oracles.xOracle"),spoolPkg:this.scallop.address.get("spool.id"),borrowIncentivePkg:this.scallop.address.get("borrowIncentive.id"),veScaPkgId:this.scallop.address.get("vesca.id"),scoin:this.scallop.address.get("scoin.id"),referral:this.scallop.address.get("referral.id")}}get transactions(){return this.txb.blockData.transactions}get inputTransaction(){return this.txb.blockData.inputs}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}};var zs="https://sui.apis.scallop.io";var Js="66f8e7ed9bb9e07fdfb86bbb",oo="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var mt="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",ft="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",Z=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],ao=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],bt=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],tt=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc"];var Xs=["sui"],gt=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc"];var Ys={weth:8,wbtc:8,wusdc:6,usdc:6,wusdt:6,sui:9,wapt:8,wsol:8,sca:9,cetus:9,afsui:9,hasui:9,vsui:9,sweth:8,swbtc:8,susdc:6,swusdt:6,swusdc:6,ssui:9,swapt:8,swsol:8,scetus:9,safsui:9,shasui:9,svsui:9,ssca:9};var ro={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},Zs={sui:["sui","sca"],wusdc:["sui","sca"],wusdt:["sui","sca"],afsui:["sui","sca"],hasui:["sui","sca"],vsui:["sui","sca"],sca:["sui","sca"],weth:["sui","sca"],wbtc:["sui","sca"],wsol:["sui","sca"],usdc:["sui","sca"]},tc={sui:"0x0000000000000000000000000000000000000000000000000000000000000002",weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",cetus:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",afsui:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",hasui:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",sca:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6",usdc:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7"},q={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Ir={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},ec={ssui:"0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI",scetus:"0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS",ssca:"0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA",swusdc:"0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC",swusdt:"0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT",sweth:"0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH",safsui:"0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI",shasui:"0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI",svsui:"0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI",swbtc:"0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC",swsol:"0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL",susdc:"0x854950aa624b1df59fe64e630b2ba7c550642e9342267a33061d59fb31582da5::scallop_usdc::SCALLOP_USDC"};var Cr=require("@mysten/sui.js/bcs"),ht=require("@mysten/sui.js/utils"),w=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,ht.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}getNestedInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="NestedResult")throw new Error("not input type");return this.txb.blockData.transactions[e.index]}isHaveNestedInput(t){return this.moveCall.arguments[t].kind==="NestedResult"}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Cr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,ht.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,ht.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,ht.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,ht.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Cr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,ht.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var nc=require("@mysten/sui.js/bcs");var _=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(w.getPureInputValue(t,"u64"))}).filter(t=>t!==void 0)}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return nc.bcs.de(e,new Uint8Array(n))}return t.value}};var io=class extends pt{decode(){if(this.isMoveAsset())return this.decodeMoveAsset();if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMoveAsset(){return!!this.getMoveCallTransaction("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage")}isMigrateScoinTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`),e=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);return!!t&&!!e}isUnstakeAndWithdrawTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`),e=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);return!!t&&!!e}isStakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`),e=!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return!!t&&!!e}isDepositCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isBorrowWithReferralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isUnstakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return!!t||!!e}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${ft}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);return!!t&&(!!e||!!n)}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperClaimBorrowV2Reward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new w(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new w(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new w(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new w(t,this.txb)}get helperBurnScoin(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new w(t,this.txb)}get helperSlippage(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage"));return new w(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new w(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new w(t,this.txb)}get helperDepositCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new w(t,this.txb)}get helperWithdrawCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new w(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new w(t,this.txb)}get helperBorrowWithReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new w(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new w(t,this.txb)}decodeMigrateScoin(){return{txType:A.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let e=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),a=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:A.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:a,veScaKey:t}}}decodeOpenObligation(){return{txType:A.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLendingScoin(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperBurnScoin.getNestedInputParam(1),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:a,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),a=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:a,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),a=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:a,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),a=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeBorrowWithReferral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),a=this.helperBorrowWithReferral.decodeSharedObjectId(1),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeRepay(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"Repay",intentionData:{amount:n,obligationId:a,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),a=new _(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:a,obligationId:r,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);e=new _(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let r=this.helperStake.getNestedInputParam(2);e=new _(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"StakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a;return this.isCreateStakeAccountTransaction()||(a=this.helperStake.decodeOwnedObjectId(1)),{txType:A.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:a}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(a=>{let r=a.decodeOwnedObjectId(1),i=a.decodeInputU64(2);t.push({id:r,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let a=this.helperBurnScoin.getNestedInputParam(1);n=new _(a,this.txb).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:A.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeMoveAsset(){let t=[];this.helperUnstakes.forEach(i=>{let s=i.decodeOwnedObjectId(1),c=i.decodeInputU64(2);t.push({id:s,coin:c})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);n=new _(i,this.txb).getAmountInput().reduce((s,c)=>s+c,0)}let a=this.helperSlippage.decodePureArg(1,"u64"),r=this.helperSlippage.decodePureArg(2,"string");return{txType:A.TransactionType.Other,type:"MigrateWusdcToUsdc",intentionData:{amount:n,coinName:e,slippage:a,validSwapAmount:r,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(a=>{let r=a.decodeOwnedObjectId(2),i=a.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(a=>{let r=a.decodeSharedObjectId(3),i=a.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(a=>{let r=a.decodeSharedObjectId(2),i=a.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:A.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};var so=require("@msafe/sui3-utils");var co=class extends pt{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(e=>new w(e,this.txb))}get helperBindReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new w(t,this.txb)}decodeCreateReferralLink(){return{txType:so.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:so.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:so.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};var Kt=require("@msafe/sui3-utils");var lo=class extends pt{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let t=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),e=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!t&&!!e}isRedeemSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new w(t,this.txb)}get helperStakeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new w(t,this.txb)}get helperExtendStakePeriod(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new w(t,this.txb)}get helperRedeemSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new w(t,this.txb)}get helperRenewExpired(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new w(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::unstake`));return new w(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new w(t,this.txb)}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:Kt.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new _(t,this.txb).getAmountInput().reduce((f,S)=>f+S,0),a=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,u,p,m=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let f=0;f<m.length;f++)m[f].condition.length>1&&([p,u]=m[f].condition,l=!0,d=m[f].isOld);return{txType:Kt.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:a,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],a=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:a,isOld:!1},{condition:r,isOld:!1}];for(let u=0;u<d.length;u++)d[u].condition.length>1&&([l,c]=d[u].condition,i=!0,s=d[u].isOld);return{txType:Kt.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:l,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new _(t,this.txb).getAmountInput().reduce((m,f)=>m+f,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:Kt.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:d,obligationKey:u,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):t=this.helperStakeMoreSca.getNestedInputParam(4);let n=new _(t,this.txb).getAmountInput().reduce((m,f)=>m+f,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:Kt.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:d,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}};var oc=N(require("sort-keys-recursive")),g=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,oc.default)(this.data))}};var uo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrow(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var po=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var mo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithReferral(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var fo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var bo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new o(e)}};var go=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAndClaim(this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName,this.data.veScaKey)}static fromData(e){return new o(e)}};var ho=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new o(e)}};var yo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateLendingWusdcToUsdcNative(this.data.coinName,Number(this.data.amount),this.data.slippage,this.data.validSwapAmount,this.data.stakeAccountId)}static fromData(e){return new o(e)}};var So=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new o(e)}};var wo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repay(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var To=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repayWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var Io=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var Co=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var ko=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var xo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new o(e)}};var vo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var Do=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var Ao=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.bindReferral(this.data.veScaKey)}static fromData(e){return new o(e)}};var Oo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claimRevenuReferral(this.data.veScaKey,this.data.coins)}static fromData(e){return new o(e)}};var Po=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new o(e)}};var _o=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendPeriodAndStakeMoreSca(this.data.amount,this.data.veScaKey,this.data.lockPeriodInDays,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Ro=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendStakeScaLockPeriod(this.data.lockPeriodInDays,this.data.veScaKey,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Bo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.redeemSca(this.data.veScaKey)}static fromData(e){return new o(e)}};var jo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.renewExpiredStakeSca(this.data.amount,this.data.lockPeriodInDays,this.data.vescaKey,this.data.isHaveRedeem,this.data.obligation,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Mo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stakeSca(this.data.amount,this.data.isObligationLocked,this.data.isOldBorrowIncentive,this.data.obligationId,this.data.obligationKey,this.data.lockPeriodInDays,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var No=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.supplyAndStake(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId,e.account.address)}static fromData(e){return new o(e)}};var Eo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new o(e)}};var Wo=class{id;addresses;constructor(t){let{id:e}=t;this.id=e}getId(){return this.id}getAddresses(){return this.addresses}get(t){if(!this.addresses)throw new Error(`Failed to fetch address ${this.id}`);return t.split(".").reduce((n,a)=>typeof n=="object"?n[a]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${zs}/addresses/${this.id}`,t);if(e.status===200){let n=await e.json();if("mainnet"in n){this.addresses=n.mainnet;return}throw new Error("Mainnet key is not in address!")}throw new Error(`Failed to fetch address with id ${this.id}`)}};var C=require("@mysten/sui.js/transactions"),jr=N(require("bignumber.js"));var ac=require("@mysten/sui.js/transactions"),Lo=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:a,utils:r}=e;this.address=n,this.query=a,this.utils=r,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new ac.TransactionBlock(t)}async selectCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,a),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[l,d]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:l,leftCoin:d,totalAmount:s}}async selectSCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[l,d]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:l,leftCoin:d,totalAmount:c}}};var rc=require("@mysten/sui.js/transactions"),xe=N(require("bignumber.js"));var Gt=async(o,t)=>{let e=t,n=o.address.get("core.object")||oo,a=[],r=!1,i=null;do{let d=await o.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});a.push(...d.data),d.hasNextPage&&d.nextCursor?(r=!0,i=d.nextCursor):r=!1}while(r);let s=a.map(d=>d?.data?.objectId).filter(d=>d!==void 0),c=await o.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),l=[];for(let d=0;d<c.length;d++){let u=c[d].data.objectId,{content:p}=c[d].data;if(p&&"fields"in p){let m=p.fields,f=String(m.ownership.fields.of),S=await xr(o,f);l.push({id:f,keyId:u,locked:S})}}return l},xr=async(o,t)=>{let e=await o.client.getObject({id:t,options:{showContent:!0}}),n=!1;return e.data&&e?.data?.content?.dataType==="moveObject"&&"lock_key"in e.data.content.fields&&(n=!!e.data.content.fields.lock_key),n},ic=async(o,t,e)=>{let n=e||[...Z],a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,xe.default)(c[m]??0).plus(p.balance).toNumber())}}),c},sc=async(o,t,e)=>{let n=e,a=o.utils.parseCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,xe.default)(c).plus(u.balance).toNumber()}}),c},cc=async(o,t,e)=>{let n=e||[...Z].map(d=>o.utils.parseMarketCoinName(d)),a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,xe.default)(c[m]??0).plus(p.balance).toNumber())}}),c},lc=async(o,t,e)=>{let n=e,a=o.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,xe.default)(c).plus(u.balance).toNumber()}}),c},dc=async(o,t)=>{let n=`${o.address.get("core.packages.query.id")}::obligation_query::obligation_data`,a=new rc.TransactionBlock;return a.moveCall({target:n,arguments:[a.object(t)]}),(await o.client.devInspectTransactionBlock({transactionBlock:a,sender:o.params.walletAddress})).events[0].parsedJson};var T=require("@mysten/sui.js/utils"),ve=async(o,t)=>{let e=t,n=o.address.get("spool.object"),a=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let p=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},options:{showContent:!0,showType:!0},cursor:s});r.push(...p.data),p.hasNextPage&&p.nextCursor?(i=!0,s=p.nextCursor):i=!1}while(i);let c={sweth:[],ssui:[],susdc:[],swusdc:[],swusdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},l=Object.keys(c).reduce((p,m)=>{let f=o.utils.parseCoinName(m),S=o.utils.parseMarketCoinType(f),I={...p},x=`${n}::spool_account::SpoolAccount<${S}>`;return I[m]=x,I},{}),d=r.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await o.client.multiGetObjects({ids:d,options:{showContent:!0,showType:!0}})).forEach(p=>{let m=p.data.objectId,f=p.data.type;if(p.data.content&&"fields"in p.data.content){let S=p.data.content.fields,I=String(S.spool_id),x=String(S.stake_type.fields.name),U=Number(S.stakes),R=Number(S.index),Q=Number(S.points),F=Number(S.total_points);(0,T.normalizeStructTag)(f)===l.sweth?c.sweth.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.ssui?c.ssui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.swusdc?c.swusdc.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.swusdt?c.swusdt.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.scetus?c.scetus.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.safsui?c.safsui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.shasui?c.shasui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.svsui?c.svsui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.susdc&&c.susdc.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(x),staked:U,index:R,points:Q,totalPoints:F})}}),c},vr=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.id`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=Number(c.max_distributed_point),d=Number(c.distributed_point),u=Number(c.distributed_point_per_period),p=Number(c.point_distribution_time),m=Number(c.max_stakes),f=String(c.stake_type.fields.name),S=Number(c.stakes),I=Number(c.index),x=Number(c.created_at),U=Number(c.last_update);n={id:i,type:(0,T.normalizeStructTag)(s),maxPoint:l,distributedPoint:d,pointPerPeriod:u,period:p,maxStake:m,stakeType:(0,T.normalizeStructTag)(f),totalStaked:S,index:I,createdAt:x,lastUpdate:U}}}return n},Dr=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.rewardPoolId`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=String(c.spool_id),d=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:(0,T.normalizeStructTag)(s),stakePoolId:l,ratioNumerator:d,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};var Sc=require("@mysten/sui.js/transactions"),qd=require("@mysten/sui.js/utils"),$d=N(require("bignumber.js"));var M=o=>{let{sender:t}=o.blockData;if(!t)throw new Error("Sender is required");return t},mc=(o,t,e,n)=>{let a=!n,r=!a&&n*1e3<=new Date().getTime();if(a||r)if(o!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof o=="number"&&o<1e10)throw new Error(`Minimum lock amount for ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if(zt(n),typeof o=="number"&&o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(e&&n&&e-n>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)}},fc=(o,t,e)=>{if(zt(e),o<=0)throw new Error("Lock period must be greater than 0");if(!!e&&e*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");if(e&&t-(e??0)>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},bc=(o,t)=>{if(zt(t),o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(!!t&&t*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead")},gc=(o,t,e)=>{if(zt(e),o<1e10)throw new Error("Minimum lock amount for renewing expired vesca 10 SCA");if(t*86400>=126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},zt=o=>{if(o===void 0)throw new Error("veSca not found")};var De=require("@mysten/sui.js/utils"),Ud=N(require("bignumber.js"));var Fd=o=>({pointType:(0,De.normalizeStructTag)(o.point_type.name),weightedAmount:Number(o.weighted_amount),points:Number(o.points),totalPoints:Number(o.total_points),index:Number(o.index)}),hc=o=>({poolType:(0,De.normalizeStructTag)(o.pool_type.name),debtAmount:Number(o.debt_amount),pointList:o.points_list.reduce((t,e)=>{let n=Fd(e),a=(0,De.parseStructTag)(n.pointType).name.toLowerCase();return t[a]=n,t},{})});var Fo=o=>{let t=o.slice(1).toLowerCase();return o.charAt(0).toLowerCase()==="s"&&[...new Set([...Z,...ao,...Xs])].includes(t)},Ar=o=>{switch(o){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return o.toUpperCase()}},yc=o=>{let t=new Date(o*1e3),e=new Date(o*1e3);e.setUTCHours(0,0,0,0),t.getUTCHours()>=0&&e.setUTCDate(e.getUTCDate()+1);let n=new Date().getTime();return e.getTime()-n>126144e3*1e3&&e.setUTCDate(e.getUTCDate()-1),Math.floor(e.getTime()/1e3)};var wc=async(o,t,e,n)=>{let a=n||[...gt],r=o.address.get("borrowIncentive.query"),i=o.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new Sc.TransactionBlock;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let d=(await o.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return d.pool_records.forEach(p=>{let m=hc(p),{poolType:f}=m,S=o.utils.parseCoinNameFromType(f);a.length>=1&&a.includes(S)&&(u[S]=m)},{}),u};var Tc=async({address:o,client:t},e)=>{let n=o.get("borrowIncentive.object"),a=o.get("borrowIncentive.incentiveAccounts"),r=o.get("core.object"),i=await t.getObject({id:a,options:{showContent:!0}});if(i?.data?.content?.dataType!=="moveObject")return null;let s=i.data.content.fields.accounts.fields.id.id,c=await t.getDynamicFieldObject({parentId:s,name:{type:`${n}::typed_id::TypedID<${r}::obligation::Obligation>`,value:e}});return c?.data?.content?.dataType!=="moveObject"?null:c.data.content.fields.value.fields.binded_ve_sca_key?.fields.id??null};var Ic=async(o,t)=>{let e=o.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await o.client.getObject({id:e,options:{showContent:!0}});if(n.data){let a=n.data;if(a.content&&"fields"in a.content){let r=a.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),l=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(l?-1:1)}}return 0};var qo=N(require("bignumber.js")),Cc=async(o,t)=>{let e=t,a=`${o.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let l=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);return r.map(l=>l.data).filter(l=>!!l)},kc=async(o,t)=>{let n=(await Cc(o,t)).map(r=>r.objectId),a=[];for(let r=0;r<n.length;r++){let i=await Or(o,n[r]);i&&a.push(i)}return a},Or=async(o,t,e)=>{let n=o.address.get("vesca.tableId"),a=t||(await Cc(o,e))[0].objectId,r,s=(await o.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:a}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:a,lockedScaAmount:(0,qo.default)(c.locked_sca_amount).toNumber(),lockedScaCoin:(0,qo.default)(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:(0,qo.default)(c.unlock_at).toNumber()}}return r};var $o=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:a}=e;this.address=n,this.utils=a}async getObligations(t=this.params.walletAddress){return Gt(this,t)}async getCoinAmounts(t,e){return ic(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return sc(this,t,e)}async getMarketCoinAmounts(t,e){return cc(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return lc(this,t,e)}async getPriceFromPyth(t){return Ic(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return ve(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let a=t[n],r=await vr(this,a);r&&(e[a]=r)}return e}async getStakePool(t){return vr(this,t)}async getStakeRewardPools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let a=await Dr(this,t[n]);a&&(e[t[n]]=a)}return e}async getStakeRewardPool(t){return Dr(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return wc(this,t,e,n)}async getObligationCoinNames(t){let e=await dc(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),a=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...a])].map(s=>this.utils.parseCoinNameFromType(s))}};var Jt=require("@mysten/sui.js/utils");var Qo=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Fo(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Ar(e)}return Ar(t)}parseCoinType(t){let e=Fo(t)?this.parseCoinName(t):t,n=tc[e];return[q.wusdc,q.wusdt,q.weth,q.wbtc,q.wsol,q.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Ir.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||oo,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=(0,Jt.normalizeStructTag)(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,a=t.match(n),r=t.includes("reserve::MarketCoin");e=a?.[1]||t;let i={[`${q.wusdc}::coin::COIN`]:"wusdc",[`${q.wusdt}::coin::COIN`]:"wusdt",[`${q.weth}::coin::COIN`]:"weth",[`${q.wbtc}::coin::COIN`]:"wbtc",[`${q.wsol}::coin::COIN`]:"wsol",[`${q.wapt}::coin::COIN`]:"wapt"},s={[`${Ir.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return r?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>ro[t];getBorrowIncentiveRewardCoinName=t=>Zs[t];getCoinDecimal(t){return Ys[t]}getCoinWrappedType(t){return t==="wusdc"||t==="wusdt"||t==="weth"||t==="wbtc"||t==="wapt"||t==="wsol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}parseSCoinType(t){return ec[t]}parseUnderlyingSCoinType(t){let e=this.parseCoinName(t);return this.parseCoinType(e)}getSCoinTreasury(t){return this._address.get(`scoin.coins.${t}.treasury`)}async selectCoins(t,e=Jt.SUI_TYPE_ARG,n){let a=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let l=await this.client.getCoins({owner:a,coinType:e,cursor:c});l.data.sort((d,u)=>parseInt(u.balance,10)-parseInt(d.balance,10));for(let d=0;d<l.data.length&&(r.push({objectId:l.data[d].coinObjectId,digest:l.data[d].digest,version:l.data[d].version,balance:l.data[d].balance}),i+=parseInt(l.data[d].balance,10),!(i>=t));d++);c=l.nextCursor,s=l.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r}async selectCoinsMarketCoin(t=Jt.SUI_TYPE_ARG,e){let n=e,a=[],r=!0,i=null;for(;r;){let s=await this.client.getCoins({owner:n,coinType:t,cursor:i});s.data.sort((c,l)=>parseInt(l.balance,10)-parseInt(c.balance,10));for(let c=0;c<s.data.length&&(a.push({objectId:s.data[c].coinObjectId,digest:s.data[c].digest,version:s.data[c].version,balance:s.data[c].balance}),!(a.length>50));c++);i=s.nextCursor,r=s.hasNextPage}return a}async selectCoinIds(t,e=Jt.SUI_TYPE_ARG,n){return(await this.selectCoins(t,e,n)).map(r=>r.objectId)}parseAprToApy(t,e=365){return(1+t/e)**e-1}parseApyToApr(t,e=365){return((1+t)**(1/e)-1)*e}takeAmountFromCoins(t,e,n){let a=e.map(s=>t.object(s)),r=a[0];a.length>1&&t.mergeCoins(r,a.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),a=e?Math.max(e-n,0):0,r=0;if(a===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+a:a,126144e3);r=n+i}return yc(r)}parseSCoinName(t){if(Fo(t)&&tt.includes(t))return t;let e=`s${t}`;if(tt.includes(e))return e}};var nt=require("@mysten/sui.js/utils");var Xt=async(...o)=>{let[t,e,n]=o;if(o.length===3&&n&&typeof n=="string"){let i=await Or(t.query,n);return i||void 0}let a=M(e),r=await kc(t.query,a);if(r.length!==0)return r[0]};var Pr=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&n&&a&&typeof n=="string"){let c=await xr(t.query,n);return{obligationId:n,obligationKey:a,obligationLocked:c}}let r=M(e),i=await Gt(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);let s=i.find(c=>c.id===n||c.keyId===a)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},Qd=async({builder:o,txBlock:t})=>{let e={borrowIncentivePkg:o.address.get("borrowIncentive.id"),query:o.address.get("borrowIncentive.query"),incentivePools:o.address.get("borrowIncentive.incentivePools"),incentiveAccounts:o.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:o.address.get("core.obligationAccessStore"),config:o.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},a={table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(a.config),t.object(a.treasury),t.object(a.table),t.object(s),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[nt.SUI_TYPE_ARG]})},claimBorrowIncentive:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.borrowIncentivePkg}::user::redeem_rewards`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},oldClaimBorrowIncentive(r,i,s){let c=o.utils.parseCoinType(s);return t.moveCall({target:`${n.id}::user::redeem_rewards`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})}}},E=async({builder:o,txBlock:t})=>{let e=await Qd({builder:o,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Pr(o,t,n,a),c=!!t.blockData.transactions.find(l=>l.kind==="MoveCall"&&(l.target===`${ft}::user::unstake`||l.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Pr(o,t,n,a);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,a,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await Pr(o,t,n,a),l=!!t.blockData.transactions.find(async d=>d.kind==="MoveCall"&&(d.target===`${ft}::user::unstake`||d.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));if(!c||l){let d=await Tc({address:o.address,client:o.client},i);if(r&&r!==d)throw new Error("Binded veScaKey is not equal to the provided veScaKey");d?e.stakeObligationWithVesca(i,s,d):e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,a,r)=>e.claimBorrowIncentive(a,r,n)}};var X=require("@mysten/sui.js/utils");var Oe=require("@mysten/sui.js/utils"),vc=N(require("axios"));var xc={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};var Vo=require("@mysten/sui.js/bcs"),Ae=require("@mysten/sui.js/utils"),_r=16*1024,Ho=class{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(t,e,n){this.provider=t,this.pythStateId=e,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!t.data||!t.data.content||t.data.content.dataType!=="moveObject")throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=t.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}}).then(n=>{if(n.data?.content?.dataType==="moveObject")return n.data.content.fields;throw new Error(`Cannot fetch package id for object ${t}`)});if("upgrade_cap"in e)return e.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(t,e){let n=await this.getWormholePackageId(),a=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(Vo.bcs.ser("vector<u8>",Array.from(r),{maxSize:_r}).toBytes()),e.object(Ae.SUI_CLOCK_OBJECT_ID)]});a.push(i)}),a}async updatePriceFeeds(t,e,n){let a=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${a}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Vo.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:_r}).toBytes()),s[0],t.object(Ae.SUI_CLOCK_OBJECT_ID)]});let c=[],l=await this.getBaseUpdateFee(),d=t.splitCoins(t.gas,n.map(()=>t.pure(l))),u=0;for(let p=0;p<n.length;p++){let m=await this.getPriceFeedObjectId(n[p]);if(!m)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(m),[r]=t.moveCall({target:`${a}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(m),d[u],t.object(Ae.SUI_CLOCK_OBJECT_ID)]}),u++}return t.moveCall({target:`${a}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${a}::price_info::PriceInfo`]}),c}async createPriceFeed(t,e){let n=await this.getPythPackageId();if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let a=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([a],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Vo.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:_r}).toBytes()),r[0],t.object(Ae.SUI_CLOCK_OBJECT_ID)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(t){let e=t.replace("0x","");if(!this.priceFeedObjectIdCache.has(e)){let{id:n,fieldType:a}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${a}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,a=t.readUint16BE(n),r=n+2;return t.subarray(r,r+a)}};var Vd=async(o,t)=>(await vc.default.get(`${o}/api/latest_vaas`,{params:{ids:t}})).data.map(a=>Buffer.from(a,"base64")),Pe=async(o,t,e)=>{let n=e??[...new Set([...Z,...ao])],a=o.isTestnet?["pyth"]:["pyth"];if(a.includes("pyth")){let i=new Ho(o.client,o.address.get("core.oracles.pyth.state"),o.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async l=>s.push(o.address.get(`core.coins.${l}.oracle.pyth.feed`))));let c=o.params.pythEndpoints??xc[o.isTestnet?"testnet":"mainnet"];try{let l=await Vd(c[0],s);await i.updatePriceFeeds(t,l,s)}catch(l){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${l}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await Hd(o,t,r[i],a)},Hd=async(o,t,e,n)=>{let a=o.utils.parseCoinType(e);Kd(t,n,o.address.get("core.packages.xOracle.id"),o.address.get("core.oracles.xOracle"),o.address.get("core.packages.pyth.id"),o.address.get("core.oracles.pyth.registry"),o.address.get("core.oracles.pyth.state"),o.address.get(`core.coins.${e}.oracle.pyth.feedObject`),o.address.get("core.packages.switchboard.id"),o.address.get("core.oracles.switchboard.registry"),o.address.get(`core.coins.${e}.oracle.switchboard`),o.address.get("core.packages.supra.id"),o.address.get("core.oracles.supra.registry"),o.address.get("core.oracles.supra.holder"),a)},Kd=(o,t,e,n,a,r,i,s,c,l,d,u,p,m,f)=>{let S=Gd(o,e,n,f);return t.includes("pyth")&&Yd(o,a,S,i,s,r,f),t.includes("switchboard")&&Xd(o,c,S,d,l,f),t.includes("supra")&&Jd(o,u,S,m,p,f),zd(o,e,n,S,f),o},Gd=(o,t,e,n)=>{let a=typeof e=="string"?o.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return o.moveCall({target:r,arguments:[a],typeArguments:i})},zd=(o,t,e,n,a)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[a],s=typeof e=="string"?o.object(e):e;return o.moveCall({target:r,arguments:[s,n,o.object(Oe.SUI_CLOCK_OBJECT_ID)],typeArguments:i}),o},Jd=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(Oe.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},Xd=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(Oe.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},Yd=(o,t,e,n,a,r,i)=>{let s=typeof e=="string"?o.object(e):e,c=typeof n=="string"?o.object(n):n,l=typeof a=="string"?o.object(a):a,d=typeof r=="string"?o.object(r):r;o.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,l,d,o.object(Oe.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})};var St=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("scoin.id")},n={};return await Promise.all(tt.map(async a=>{let r=o.utils.getSCoinTreasury(a);n[a]=r})),{mintSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]}),burnSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]})}};var _e=async(...o)=>{let[t,e,n,a]=o;if(o.length===3&&n)return{obligationId:n};if(o.length===4&&n&&a)return{obligationId:n,obligationKey:a};let r=M(t),i=await Gt(e.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},Zd=async({builder:o,txBlock:t})=>{let e={protocolPkg:o.address.get("core.packages.protocol.id"),market:o.address.get("core.market"),version:o.address.get("core.version"),coinDecimalsRegistry:o.address.get("core.coinDecimalsRegistry"),xOracle:o.address.get("core.oracles.xOracle")},a=`${o.address.get("referral.id")}::scallop_referral_program::REFERRAL_WITNESS`;return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.object(e.version)]}),returnObligation:(r,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(r),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},deposit:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},depositEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdraw:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdrawEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},borrow:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowEntry:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowWithReferral:(r,i,s,c,l)=>{let d=o.utils.parseCoinType(l);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,a]})},repay:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},borrowFlashLoan:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r)],typeArguments:[s]})},repayFlashLoan:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r),t.object(i)],typeArguments:[c]})}}},W=async({builder:o,txBlock:t})=>{let e=await Zd({builder:o,txBlock:t}),n=await St({builder:o,txBlock:t});return{normalMethod:e,addCollateralQuick:async(a,r,i)=>{let s=M(t),{obligationId:c}=await _e(t,o,i);if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);e.addCollateral(c,l,r)}else{let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);e.addCollateral(c,d,r),t.transferObjects([l],s)}},takeCollateralQuick:async(a,r,i,s)=>{let c=await _e(t,o,i,s),l=await o.query.getObligationCoinNames(c.obligationId);return await Pe(o,t,l),e.takeCollateral(c.obligationId,c.obligationKey,a,r)},depositQuick:async(a,r,i)=>{if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);return e.deposit(l,r)}let{leftCoin:s,takeCoin:c}=await o.selectCoin(t,r,a,i);return t.transferObjects([s],i),e.deposit(c,r)},withdrawQuick:async(a,r)=>{let i=M(t),s=o.utils.parseMarketCoinName(r);try{let c=o.utils.parseSCoinName(r);if(!c)throw new Error(`No sCoin for ${r}`);let{leftCoin:l,takeCoin:d,totalAmount:u}=await o.selectSCoin(t,c,a,i);t.transferObjects([l],i);let p=n.burnSCoin(c,d),m=e.withdraw(p,r),f=a-u;try{if(f>0){let{leftCoin:S,takeCoin:I}=await o.selectMarketCoin(t,s,f,i);t.transferObjects([S],i),t.mergeCoins(m,[e.withdraw(I,r)])}}catch{}return m}catch{let{leftCoin:l,takeCoin:d}=await o.selectMarketCoin(t,s,a,i);return t.transferObjects([l],i),e.withdraw(d,r)}},borrowQuick:async(a,r,i,s)=>{let c=await _e(t,o,i,s),d=[...await o.query.getObligationCoinNames(c.obligationId),r];return await Pe(o,t,d),e.borrow(c.obligationId,c.obligationKey,a,r)},borrowWithReferralQuick:async(a,r,i,s,c)=>{let l=await _e(t,o,s,c),u=[...await o.query.getObligationCoinNames(l.obligationId),r];return await Pe(o,t,u),e.borrowWithReferral(l.obligationId,l.obligationKey,i,a,r)},repayQuick:async(a,r,i,s)=>{let c=await _e(t,o,i);if(r==="sui"){let[u]=t.splitCoins(t.gas,[a]);return e.repay(c.obligationId,u,r)}let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);return t.transferObjects([l],s),e.repay(c.obligationId,d,r)},updateAssetPricesQuick:async a=>Pe(o,t,a)}};var Re=require("@mysten/sui.js/utils");var Ko=async({builder:o,txBlock:t})=>{let e={referralPgkId:o.address.get("referral.id"),referralBindings:o.address.get("referral.referralBindings"),referralRevenuePool:o.address.get("referral.referralRevenuePool"),authorizedWitnessList:o.address.get("referral.authorizedWitnessList"),referralTiers:o.address.get("referral.referralTiers"),version:o.address.get("referral.version")},n=o.address.get("vesca.table");return{bindToReferral:a=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(a),t.object(n),t.object(Re.SUI_CLOCK_OBJECT_ID)],typeArguments:[]}),claimReferralTicket:a=>{let r=o.utils.parseCoinType(a);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(n),t.object(e.referralBindings),t.object(e.authorizedWitnessList),t.object(e.referralTiers),t.object(Re.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},burnReferralTicket:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(a),t.object(e.referralRevenuePool),t.object(Re.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})},claimReferralRevenue:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,arguments:[t.object(e.version),t.object(e.referralRevenuePool),t.object(a),t.object(Re.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})}}},Dc=async({builder:o,txBlock:t})=>{let e=await Ko({builder:o,txBlock:t});return{claimReferralRevenueQuick:async(n,a,r=[...Z])=>{let i=[];for(let s=0;s<r.length;s++)if(r[s]==="sui"){let c=e.claimReferralRevenue(n,r[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,r[s]);try{let l=await o.utils.selectCoinIds(1/0,o.utils.parseCoinType(r[s]),a);t.mergeCoins(c,l.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(a))}}};var tu={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},Ac={check_slippage:(o,t,e,n,a)=>o.moveCall({target:`${tu.packageId}::slippage_check::check_slippage`,arguments:[t,o.pure(e),o.pure(n)],typeArguments:[a]})};var Be=require("@mysten/sui.js/utils");var Oc=async(o,t,e,n,a,r,i=!1)=>{let s=await St({builder:o,txBlock:t}),c=await _c({builder:o,txBlock:t});try{let{takeCoin:l,leftCoin:d,totalAmount:u}=i?await o.selectSCoin(t,n,a,r):await o.selectMarketCoin(t,n,a,r);if(i){let p=s.burnSCoin(n,l);c.stake(e,p,n)}else c.stake(e,l,n);return t.transferObjects([d],r),u}catch{return 0}},Pc=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&a)return[a];let r=M(e);return(await ve(t.query,r))[n].map(s=>s.id)},eu=async(...o)=>{let[t,e,n,a]=o,r=M(e),i=await ve(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return a?i[n].filter(c=>c.id===a):i[n]},_c=async({builder:o,txBlock:t})=>{let e={spoolPkg:o.address.get("spool.id")},n={},a={},r={};return bt.forEach(i=>{let s=o.address.get(`spool.pools.${i}.id`),c=o.address.get(`spool.pools.${i}.rewardPoolId`),l=o.utils.parseMarketCoinType(i);n[i]=s,a[i]=c,r[i]=l}),{createStakeAccount:i=>{let s=r[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(Be.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},stake:(i,s,c)=>{let l=r[c],d=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(d),t.object(i),typeof s=="string"?t.pure(s):s,t.object(Be.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},unstake:(i,s,c)=>{let l=r[c],d=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(d),t.object(i),t.pure(s),t.object(Be.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},claim:(i,s)=>{let c=n[s],l=a[s],d=r[s],u=ro[s],p=o.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(l),t.object(i),t.object(Be.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,p]})}}},ot=async({builder:o,txBlock:t})=>{let e=await _c({builder:o,txBlock:t}),n=await St({builder:o,txBlock:t});return{normalMethod:e,stakeQuick:async(a,r,i)=>{let s=M(t),c=await Pc(o,t,r,i),l=[];if(c.length===0){let d=e.createStakeAccount(r);l.push(d)}if(typeof a=="number"){let d=await Oc(o,t,c.length>0?c[0]:l[0],r,a,s);a-=d,d||await Oc(o,t,c.length>0?c[0]:l[0],r,a,s,!0)}else e.stake(c.length>0?c[0]:l[0],a,r);l.length>0&&t.transferObjects(l,s)},unstakeQuick:async(a,r,i,s)=>{let c=await eu(o,t,r,i),l=[],d=a;for(let u of c){if(u.staked===0)continue;let p=Math.min(d,u.staked),m=e.unstake(u.id,p,r);if(s){let f=n.mintSCoin(r,m);l.push(f)}else l.push(m);if(d-=p,a<=0)break}if(l.length>0){let u=l[0];return l.length>1&&t.mergeCoins(u,l.slice(1)),u}},claimQuick:async(a,r)=>{let i=await Pc(o,t,a,r),s=[];return i.forEach(c=>{let l=e.claim(c,a);s.push(l)}),s}}};var Yt=require("@mysten/sui.js/utils");var nu=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("vesca.id"),table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{lockSca:(n,a)=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_key`,arguments:[t.object(e.config),t.object(e.table),t.object(e.treasury),typeof n=="string"?t.pure(n):n,t.pure(a),t.object(Yt.SUI_CLOCK_OBJECT_ID)]}),extendLockPeriod:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::extend_lock_period`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.pure(a),t.object(Yt.SUI_CLOCK_OBJECT_ID)]})},extendLockAmount:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::lock_more_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.object(Yt.SUI_CLOCK_OBJECT_ID)]})},renewExpiredVeSca:(n,a,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.pure(r),t.object(Yt.SUI_CLOCK_OBJECT_ID)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(Yt.SUI_CLOCK_OBJECT_ID)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},wt=async({builder:o,txBlock:t})=>{let e=await nu({builder:o,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,a,r=!0)=>{let i=M(t),s=await Xt(o,t),c,l=[];if(n!==void 0&&typeof n=="number"){let m=await o.utils.selectCoinIds(n,mt,i),[f,S]=o.utils.takeAmountFromCoins(t,m,n);c=f,l.push(S)}else c=n;let d=o.utils.getUnlockAt(a,s?.unlockAt);r&&mc(n,a,d,s?.unlockAt),console.log(new Date(d*1e3).toLocaleString("en-CA",{hour12:!0}));let u=!s?.unlockAt,p=!u&&s.unlockAt*1e3<=new Date().getTime();if(u||p){if(c)if(u){let m=e.lockSca(c,d);l.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);l.push(m)}e.renewExpiredVeSca(s.keyId,c,d)}}else c&&a?(e.extendLockPeriod(s.keyId,d),e.extendLockAmount(s.keyId,c)):a?e.extendLockPeriod(s.keyId,d):c&&e.extendLockAmount(s.keyId,c);l.length>0&&t.transferObjects(l,i)},extendLockPeriodQuick:async(n,a,r=!0)=>{let i=await Xt(o,t,a),s=o.utils.getUnlockAt(n);r&&fc(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,a,r=!0)=>{let i=M(t),s=await Xt(o,t,a);if(r&&bc(n,s?.unlockAt),s){let c=await o.utils.selectCoinIds(n,mt,i),[l,d]=o.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,l),t.transferObjects([d],i)}},renewExpiredVeScaQuick:async(n,a,r,i=!0)=>{let s=M(t),c=await Xt(o,t,r),l=o.utils.getUnlockAt(a,c?.unlockAt);if(i&&gc(n,a,c?.unlockAt),c){let d=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);d.push(f)}let u=await o.utils.selectCoinIds(n,mt,s),[p,m]=o.utils.takeAmountFromCoins(t,u,n);d.push(m),e.renewExpiredVeSca(c.keyId,p,l),t.transferObjects(d,s)}},redeemScaQuick:async n=>{let a=M(t),r=await Xt(o,t,n);if(zt(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],a)}}}};var Nc=require("@mysten/sui.js/utils");var Mc=require("@mysten/sui.js/utils");var Zt={id:"0x000000000000000000000000000000000000000000000000000000000000dee9",pools:{sui2usdc:{object:{objectId:"0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33",initialSharedVersion:"32079148",mutable:!0},lotsize:1e8},usdt2usdc:{object:{objectId:"0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238",initialSharedVersion:"32079148",mutable:!0},lotsize:1e5},wusdc2usdc:{object:{objectId:"0x39f2f7c126189b9b5cda6b770ab34031dde22307d19842e95ab576873c77fa14",initialSharedVersion:"82838334",mutable:!0},lotsize:1e5}}},Rc={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},Rr={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},Bc={clob_v2:{swap_exact_quote_for_base:"clob_v2::swap_exact_quote_for_base",swap_exact_base_for_quote:"clob_v2::swap_exact_base_for_quote",create_account:"clob_v2::create_account"}};var jc={objectId:Mc.SUI_CLOCK_OBJECT_ID,initialSharedVersion:"1",mutable:!1},ou=(o,t)=>{if(o==="sui")switch(t){case"wusdc":return{pool:Zt.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdc")switch(t){case"sui":return{pool:Zt.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:Zt.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:Zt.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdt")switch(t){case"wusdc":return{pool:Zt.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else throw new Error(`Invalid coin pair: ${o} and ${t}`)},Br={createAccount:o=>o.moveCall({target:`${Rc.id}::${Bc.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(o,t,e,n,a,r,i)=>{let{pool:s,aToB:c}=ou(e,n),l=i.parseCoinType(e),d=i.parseCoinType(n),u=typeof r=="string"?o.object(r):"objectId"in r?o.objectRef(r):o.object(r);if(!s)throw new Error(`Deepbook: No pool found for ${e} to ${n}`);return c?o.moveCall({target:`${Rr.id}::deepbook::deepbook_base_for_quote`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.object(t),o.sharedObjectRef(jc),o.pure(s.lotsize)],typeArguments:[l,d]}):o.moveCall({target:`${Rr.id}::deepbook::deepbook_quote_for_base`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.sharedObjectRef(jc),o.object(t),o.pure(s.lotsize)],typeArguments:[d,l]})}};var Go=class{suiClient;scallopUtils;_clientOrderId=0;_accountCap;currentAddress;constructor({client:t,currentAddress:e,accountCap:n,scallopUtils:a}){this.currentAddress=e,this.suiClient=t,this._accountCap=n,this.scallopUtils=a}get clientOrderId(){let t=this._clientOrderId;return this._clientOrderId++,t}async accountCap(t){if(this._accountCap)return this._accountCap;try{let{data:e}=await this.suiClient.getOwnedObjects({owner:this.currentAddress,filter:{StructType:(0,Nc.normalizeStructTag)("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?Br.createAccount(t):{objectId:e[0].data.objectId,version:e[0].data.version,digest:e[0].data.digest}}catch{throw new Error("Failed to create account cap")}}async swapToken({tokenObjectIn:t,baseCoinName:e,quoteCoinName:n,tx:a}){let r=await this.accountCap(a);return{swapResult:Br.swap(a,t,e,n,this.clientOrderId,r,this.scallopUtils),accountCap:r}}};var zo=class{params;client;address;builder;query;utils;walletAddress;deepbookSwap;constructor(t,e){this.params=t,this.client=t.client,this.address=e,this.utils=new Qo(t,this.address),this.query=new $o(t,{address:this.address,utils:this.utils}),this.builder=new Lo(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new Go({client:this.client,currentAddress:this.params.walletAddress,scallopUtils:this.utils})}async getObligations(t){let e=t||this.params.walletAddress;return this.query.getObligations(e)}async getAllStakeAccounts(t){let e=t||this.params.walletAddress;return this.query.getAllStakeAccounts(e)}async getStakeAccounts(t,e){let n=e||this.params.walletAddress;return this.query.getStakeAccounts(t,n)}async getStakePool(t){return this.query.getStakePool(t)}async getStakeRewardPool(t){return this.query.getStakeRewardPool(t)}async openObligation(t){let e=new C.TransactionBlock,n=await W({builder:this.builder,txBlock:e}),a=await E({builder:this.builder,txBlock:e}),r=t||this.params.walletAddress;e.setSender(r);let[i,s,c]=n.normalMethod.openObligation();return a.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],r),e}async depositCollateral(t,e,n,a){let r=new C.TransactionBlock,i=a||this.params.walletAddress;r.setSender(i);let s=await W({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),l=n||c?.[0]?.id;if(l)await s.addCollateralQuick(e,t,l);else{let[d,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,d),s.normalMethod.returnObligation(d,p),r.transferObjects([u],i)}return r}async withdrawCollateral(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=r||this.params.walletAddress;i.setSender(c);let l=await s.takeCollateralQuick(e,t,n,a);return i.transferObjects([l],c),i}async deposit(t,e,n){let a=new C.TransactionBlock,r=await W({builder:this.builder,txBlock:a}),i=await St({builder:this.builder,txBlock:a}),s=n||this.params.walletAddress;a.setSender(s);let c=await r.depositQuick(e,t,n),l=this.utils.parseMarketCoinName(t);if(!tt.includes(l))a.transferObjects([c],s);else{let d=i.mintSCoin(l,c);a.transferObjects([d],s)}return a}async withdraw(t,e,n){let a=new C.TransactionBlock,r=n||this.params.walletAddress,i=await W({builder:this.builder,txBlock:a});a.setSender(r);let s=await i.withdrawQuick(e,t);return a.transferObjects([s],r),a}async borrow(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);d&&await c.unstakeObligationQuick(n,a);let u=await s.borrowQuick(e,t,n,a);return i.transferObjects([u],l),d&&await c.stakeObligationQuick(n,a),i}async borrowWithBoost(t,e,n,a,r,i){let s=new C.TransactionBlock,c=await W({builder:this.builder,txBlock:s}),l=await E({builder:this.builder,txBlock:s}),d=i||this.params.walletAddress;s.setSender(d);let u=gt.includes(t);u&&await l.unstakeObligationQuick(n,a);let p=await c.borrowQuick(e,t,n,a);return s.transferObjects([p],d),u&&await l.stakeObligationWithVeScaQuick(n,a,r),s}async borrowWithReferral(t,e,n,a,r,i){let s=new C.TransactionBlock,c=await W({builder:this.builder,txBlock:s}),l=await E({builder:this.builder,txBlock:s}),d=await Ko({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=gt.includes(t);p&&await l.unstakeObligationQuick(n,a);let m=d.claimReferralTicket(t),f=await c.borrowWithReferralQuick(e,t,m,n,a);return d.burnReferralTicket(m,t),s.transferObjects([f],u),p&&r?await l.stakeObligationWithVeScaQuick(n,a,r):await l.stakeObligationQuick(n,a),s}async repay(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);return d&&await c.unstakeObligationQuick(n,a),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationQuick(n,a),i}async repayWithBoost(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);return d&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationWithVeScaQuick(n,void 0,a),i}async createStakeAccount(t,e){let n=new C.TransactionBlock,a=await ot({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;n.setSender(r);let i=a.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,a){let r=new C.TransactionBlock,i=await W({builder:this.builder,txBlock:r}),s=await ot({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l=await i.depositQuick(e,t,a),d=this.utils.parseMarketCoinName(t);if(!bt.find(m=>m===d))return r;let u=await this.query.getStakeAccounts(d,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(l,d,p);else{let m=s.normalMethod.createStakeAccount(d);await s.stakeQuick(l,d,m),r.transferObjects([m],c)}return r}async unstakeAndWithdraw(t,e,n){let a=new C.TransactionBlock,r=await W({builder:this.builder,txBlock:a}),i=await ot({builder:this.builder,txBlock:a}),s=this.params.walletAddress,c=[];a.setSender(s);let l=this.utils.parseMarketCoinName(t);for(let d=0;d<n.length;d++){let u=n[d],[p]=await i.unstakeQuick(u.coin,l,u.id);if(p){let m=r.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let d=await r.withdrawQuick(e,t);c.push(d)}return c.length>1&&a.mergeCoins(c[0],c.slice(1)),a.transferObjects(c,s),a}async stake(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),l=n||(c.length>0?c[0].id:void 0);if(l)await i.stakeQuick(e,t,l);else{let d=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,d),r.transferObjects([d],s)}return r}async unstake(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=tt.includes(t),l=await i.unstakeQuick(e,t,n,c);return r.transferObjects([l],r.pure(s)),r}async claim(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=await E({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l={sui:[],sca:[]};for(let d=0;d<t.length;d++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[d],m=i.normalMethod.claim(p,u);l.sui.push(m)}for(let d=0;d<e.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[d],f=s.normalMethod.claimBorrowIncentive(u,p,m);l[m].push(f)}for(let d=0;d<n.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[d],f=s.normalMethod.oldClaimBorrowIncentive(u,p,m);l[m].push(f)}return l.sui.length>0&&(l.sui.length>1&&r.mergeCoins(l.sui[0],l.sui.slice(1)),r.transferObjects([l.sui[0]],r.pure(c))),l.sca.length>0&&(l.sca.length>1&&r.mergeCoins(l.sca[0],l.sca.slice(1)),r.transferObjects([l.sca[0]],r.pure(c))),r}async stakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await E({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.stakeObligationQuick(t,e),a}async unstakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await E({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.unstakeObligationQuick(t,e),a}async stakeSca(t,e=!1,n=!1,a,r,i,s,c){let l=new C.TransactionBlock,d=await wt({builder:this.builder,txBlock:l}),u=await E({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[f,S]=this.builder.utils.takeAmountFromCoins(l,m,t),I;return s?d.normalMethod.extendLockAmount(s,f):I=d.normalMethod.lockSca(f,i),a&&r&&(e&&(n?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,s||I)),s||l.transferObjects([I,S],p),l}async stakeMoreSca(t,e,n){let a=new C.TransactionBlock,r=n||this.params.walletAddress;return a.setSender(r),a}async extendStakeScaLockPeriod(t,e,n,a,r=!1,i=!1,s){let c=new C.TransactionBlock,l=await wt({builder:this.builder,txBlock:c}),d=await E({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),l.normalMethod.extendLockPeriod(e,t),n&&a&&(r&&(i?d.normalMethod.oldUnstakeObligation(n,a):d.normalMethod.unstakeObligation(n,a)),d.normalMethod.stakeObligationWithVesca(n,a,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,a,r,i=!1,s=!1,c){let l=new C.TransactionBlock,d=await wt({builder:this.builder,txBlock:l}),u=await E({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[f,S]=this.builder.utils.takeAmountFromCoins(l,m,t);return d.normalMethod.extendLockPeriod(e,n),d.normalMethod.extendLockAmount(e,f),l.transferObjects([S],p),!a||!r||(i&&(s?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,e)),l}async renewExpiredStakeSca(t,e,n,a=!1,r,i,s=!1,c=!1,l){let d=new C.TransactionBlock,u=await wt({builder:this.builder,txBlock:d}),p=await E({builder:this.builder,txBlock:d}),m=l||this.params.walletAddress;if(d.setSender(m),a){let x=u.normalMethod.redeemSca(n);d.transferObjects([x],m)}let f=await this.builder.utils.selectCoinIds(t,mt,m),[S,I]=this.builder.utils.takeAmountFromCoins(d,f,t);return d.transferObjects([I],m),u.normalMethod.renewExpiredVeSca(n,S,e),!r||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(r,i):p.normalMethod.unstakeObligation(r,i)),p.normalMethod.stakeObligationWithVesca(r,i,n)),d}async redeemSca(t){let e=new C.TransactionBlock,n=await wt({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,a){let r=new C.TransactionBlock,i=await E({builder:this.builder,txBlock:r}),s=this.params.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return r.transferObjects([c],s),await i.unstakeObligationQuick(e,t),a?await i.stakeObligationWithVeScaQuick(e,t,a):await i.stakeObligationQuick(e,t),r}async withdrawUnlockedSca(t,e){let n=new C.TransactionBlock,a=await wt({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;return n.setSender(r),await a.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new jr.default(t.weightedAmount),r=e.currentPointIndex?(0,jr.default)(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new C.TransactionBlock,e=await wt({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let a=e.normalMethod.mintEmptyVeSca();return t.transferObjects([a],n),t}async claimRevenuReferral(t,e){let n=new C.TransactionBlock,a=await Dc({builder:this.builder,txBlock:n}),r=this.params.walletAddress;n.setSender(r);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await a.claimReferralRevenueQuick(t,r,i),n}async bindReferral(t){let e=new C.TransactionBlock,n=await Ko({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new C.TransactionBlock,e=await St({builder:this.builder,txBlock:t}),n=await ot({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let a=[];return await Promise.all(tt.map(async r=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(r),this.params.walletAddress),l=c[0];c.length>1&&t.mergeCoins(l,c.slice(1)),s=l}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(r,s);try{let l=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(r),this.params.walletAddress);t.mergeCoins(c,l)}catch(l){console.log(l)}i.push(c)}if(bt.includes(r))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,r);c&&i.push(c)}catch(c){console.log(c)}if(i.length>0){let c=i[0];i.length>1&&t.mergeCoins(c,i.slice(1)),a.push(c)}})),a.length>0&&t.transferObjects(a,this.params.walletAddress),t}async migrateLendingWusdcToUsdcNative(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await ot({builder:this.builder,txBlock:i}),l=this.params.walletAddress,d=[],u=this.utils.parseMarketCoinName(t),p=this.utils.parseMarketCoinType(u),f=(await this.utils.selectCoinsMarketCoin(p,l)).map(R=>R.objectId);i.setSender(l);for(let R=0;R<r.length;R++){let Q=r[R],[F]=await c.unstakeQuick(Q.coin,u,Q.id);if(F){f.length>0&&i.mergeCoins(F,f);let $l=s.normalMethod.withdraw(F,t);d.push($l)}}if(e>0){let R=await s.withdrawQuick(e,t);d.push(R)}d.length>1&&i.mergeCoins(d[0],d.slice(1));let[S]=i.splitCoins(d[0],[i.pure(a)]);i.transferObjects([d[0]],l);let{swapResult:I,accountCap:x}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:S,tx:i});typeof x=="string"&&i.transferObjects([x],l),Ac.check_slippage(i,I,n,a,this.query.utils.parseCoinType("usdc"));let U=s.normalMethod.deposit(I,"usdc");return await c.stakeQuick(U,"susdc"),i}};var je=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Wo({id:Js})),await this.address.read(),this.client=new zo(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var Jo=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new je({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new io(e,this.scallop),a=new co(e,this.scallop),r=new lo(e,this.scallop),i=n.decode()||a.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:Ec.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:a,txSubType:r,intentionData:i}=t;this.scallop||(this.scallop=new je({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(r){case"SupplyLending":s=Co.fromData(i);break;case"WithdrawLending":s=Do.fromData(i);break;case"Borrow":s=uo.fromData(i);break;case"Repay":s=wo.fromData(i);break;case"DepositCollateral":s=bo.fromData(i);break;case"WithdrawCollateral":s=vo.fromData(i);break;case"OpenObligation":s=So.fromData(i);break;case"StakeSpool":s=Io.fromData(i);break;case"UnstakeSpool":s=ko.fromData(i);break;case"ClaimIncentiveReward":s=fo.fromData(i);break;case"BorrowWithBoost":s=po.fromData(i);break;case"StakeSca":s=Mo.fromData(i);break;case"ExtendStakePeriod":s=Ro.fromData(i);break;case"ExtendPeriodAndStakeMore":s=_o.fromData(i);break;case"RenewExpStakePeriod":s=jo.fromData(i);break;case"WithdrawStakedSca":s=Eo.fromData(i);break;case"SupplyAndStakeLending":s=No.fromData(i);break;case"WithdrawAndUnstakeLending":s=xo.fromData(i);break;case"RedeemSca":s=Bo.fromData(i);break;case"MigrateAndClaim":s=go.fromData(i);break;case"BorrowWithReferral":s=mo.fromData(i);break;case"CreateReferralLink":s=Po.fromData(i);break;case"ClaimRevenueReferral":s=Oo.fromData(i);break;case"BindReferral":s=Ao.fromData(i);break;case"MigrateScoin":s=ho.fromData(i);break;case"RepayWithBoost":s=To.fromData(i);break;case"MigrateWusdcToUsdc":s=yo.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:a,scallop:this.scallop})}};var nl=require("@msafe/sui3-utils"),ma=require("@suilend/frontend-sui"),ol=require("@suilend/springsui-sdk");var Xo=require("@msafe/sui3-utils");var Yo=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isMintTransaction())return this.decodeMint();if(this.isMintAndDepositTransaction())return this.decodeMintAndDeposit();if(this.isRedeemTransaction())return this.decodeRedeem();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintTransactionMoveCallCommands(){return!!this.getMoveCallCommand("mint")}isMintTransaction(){return this.hasMintTransactionMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isMintAndDepositTransaction(){return this.hasMintTransactionMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::MintEvent"))}.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeMint",e),{txType:Xo.TransactionType.Other,type:"mint",intentionData:{amount:e}}}decodeMintAndDeposit(){return{txType:Xo.TransactionType.Other,type:"mintAndDeposit",intentionData:this.decodeMint().intentionData}}decodeRedeem(){let e={RedeemEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::RedeemEvent"))}.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeRedeem",e),{txType:Xo.TransactionType.Other,type:"redeem",intentionData:{amount:e}}}};var Lc=require("@mysten/sui/transactions");var Wc=N(require("sort-keys-recursive")),Tt=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Wc.default)(this.data))}};var Zo=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintIntention.build",n,a,r,i,s,c);let l=new Lc.Transaction;return r.mintAndRebalanceAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("MintIntention.fromData",e),new o(e)}};var Uc=require("@mysten/sui/transactions");var ta=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintAndDepositIntention.build",n,a,r,i,s,c);let l=new Uc.Transaction;return i.depositCoin(a.address,r.mintAndRebalance(l,this.data.amount),r.liquidStakingObject.type,l,s?.id),l}static fromData(e){return console.log("MintAndDepositIntention.fromData",e),new o(e)}};var Fc=require("@mysten/sui/transactions");var ea=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("RedeemIntention.build",n,a,r,i,s,c);let l=new Fc.Transaction;return await r.redeemAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("RedeemIntention.fromData",e),new o(e)}};var Yc=require("@msafe/sui3-utils"),It=require("@suilend/sdk"),Zc=require("@suilend/sdk/_generated/_framework/reified"),tl=require("@suilend/sdk/_generated/suilend/lending-market/structs");var Rt=require("@msafe/sui3-utils"),ee=require("@mysten/bcs"),te=require("@mysten/sui/utils"),Bt=require("@suilend/sdk"),Mr=N(require("bignumber.js"));var na=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("XXX this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("XXX this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let t={MintEvent:this.simResult.events.find(a=>a.type.includes("lending_market::MintEvent"))},e=(0,te.normalizeStructTag)(t.MintEvent.parsedJson.coin_type.name),n=t.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",e,n),{txType:Rt.TransactionType.Other,type:"deposit",intentionData:{coinType:e,value:n}}}decodeWithdraw(){let t={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},e={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=(0,te.normalizeStructTag)(e.RedeemEvent.parsedJson.coin_type.name),a=e.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,a);let r=t.withdraw_ctokens.MoveCall.arguments[4].Input,i=new Mr.default((0,ee.toHEX)((0,ee.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Bt.maxU64.toString();return console.log("XXX decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Bt.maxU64.toString()),s&&(a=Bt.maxU64.toString()),{txType:Rt.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:a}}}decodeBorrow(){let t={borrow_request:this.getMoveCallCommand("borrow_request")},e={BorrowEvent:this.simResult.events.find(c=>c.type.includes("lending_market::BorrowEvent"))},n=(0,te.normalizeStructTag)(e.BorrowEvent.parsedJson.coin_type.name),a=`${+e.BorrowEvent.parsedJson.liquidity_amount-+e.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,a);let r=t.borrow_request.MoveCall.arguments[4].Input,i=new Mr.default((0,ee.toHEX)((0,ee.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Bt.maxU64.toString();return console.log("XXX decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Bt.maxU64.toString()),s&&(a=Bt.maxU64.toString()),{txType:Rt.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:a}}}decodeRepay(){let t={RepayEvent:this.simResult.events.find(a=>a.type.includes("lending_market::RepayEvent"))},e=(0,te.normalizeStructTag)(t.RepayEvent.parsedJson.coin_type.name),n=t.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",e,n),{txType:Rt.TransactionType.Other,type:"repay",intentionData:{coinType:e,value:n}}}decodeClaim(){let t={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},e={};for(let n=0;n<t.ClaimReward.length;n++){let a=t.ClaimReward[n],r=(0,te.normalizeStructTag)(a.parsedJson.coin_type.name),i=a.parsedJson.liquidity_amount;e[r]=`${+(e[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",e),{txType:Rt.TransactionType.Other,type:"claim",intentionData:{value:e}}}decodeClaimAndDeposit(){return{txType:Rt.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var $c=require("@mysten/sui/transactions");var qc=N(require("sort-keys-recursive")),L=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,qc.default)(this.data))}};var oa=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("BorrowIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new $c.Transaction;return await r.borrowAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("BorrowIntention.fromData",e),new o(e)}};var Kc=require("@mysten/sui/transactions");var Vc=require("@mysten/sui/utils"),ne=require("@suilend/sdk"),Hc=N(require("bignumber.js"));var Nr=require("@mysten/sui/utils"),iu="0x34fe4f3c9e450fed4d0a3c587ed842eec5313c30c3cc3c0841247c49425e246b::suilend_point::SUILEND_POINT",su=(0,Nr.normalizeStructTag)(iu),Qc=o=>(0,Nr.normalizeStructTag)(o)===su;var cu=(o,t)=>{let e={[ne.Side.DEPOSIT]:[],[ne.Side.BORROW]:[]};return o.lendingMarket.reserves.forEach(n=>{[ne.Side.DEPOSIT,ne.Side.BORROW].forEach(a=>{let r=a===ne.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,i=t.userRewardManagers.find(s=>s.poolRewardManagerId===r.id);i&&(e[a]=r.poolRewards.map((s,c)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(c),rewardCoinType:(0,Vc.normalizeStructTag)(s.coinType.name),side:a})).filter(s=>!Qc(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new Hc.default(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(e).flat()},aa=cu;var ra=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Kc.Transaction;return r.claimRewardsAndSendToUser(a.address,i.id,aa(r,s),c),c}static fromData(e){return console.log("ClaimIntention.fromData",e),new o(e)}};var Gc=require("@mysten/sui/transactions");var ia=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimAndDepositIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Gc.Transaction;return r.claimRewardsAndDeposit(a.address,i.id,aa(r,s),c),c}static fromData(e){return console.log("ClaimAndDepositIntention.fromData",e),new o(e)}};var zc=require("@mysten/sui/transactions");var sa=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;console.log("DepositIntention.build",n,a,r,i,s);let c=new zc.Transaction;return await r.depositIntoObligation(a.address,this.data.coinType,this.data.value,c,i?.id),c}static fromData(e){return console.log("DepositIntention.fromData",e),new o(e)}};var Jc=require("@mysten/sui/transactions");var ca=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("RepayIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Jc.Transaction;return await r.repayIntoObligation(a.address,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("RepayIntention.fromData",e),new o(e)}};var Xc=require("@mysten/sui/transactions");var la=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("WithdrawIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Xc.Transaction;return await r.withdrawAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("WithdrawIntention.fromData",e),new o(e)}};var da=async(o,t)=>{let e=await It.SuilendClient.initializeWithLendingMarket(await tl.LendingMarket.fetch(o,(0,Zc.phantom)(It.LENDING_MARKET_TYPE),It.LENDING_MARKET_ID),o),n=await It.SuilendClient.getObligationOwnerCaps(t.address,e.lendingMarket.$typeArgs,o),a=await Promise.all(n.map(r=>It.SuilendClient.getObligation(r.obligationId,e.lendingMarket.$typeArgs,o)));return{suilendClient:e,obligationOwnerCaps:n,obligations:a}},ua=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await da(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SuilendAppHelper.deserialize",r);let s=new na(e,r).decode();return{txType:Yc.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await da(r,i));let s;switch(n){case"deposit":s=sa.fromData(a);break;case"withdraw":s=la.fromData(a);break;case"borrow":s=oa.fromData(a);break;case"repay":s=ca.fromData(a);break;case"claim":s=ra.fromData(a);break;case"claimAndDeposit":s=ia.fromData(a);break;default:throw new Error("not implemented")}let c=window.localStorage.getItem("obligationId"),l=this.utils.obligations?.find(u=>u.id===c)??this.utils.obligations?.[0],d=this.utils.obligationOwnerCaps?.find(u=>u.obligationId===l?.id);return console.log("XXX obligationId:",c,"obligations:",this.utils.obligations,"obligationOwnerCaps:",this.utils.obligationOwnerCaps),s.build({network:e,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:d,obligation:l})}};var el=async(o,t)=>{let e=await ol.LstClient.initialize(o,ma.LIQUID_STAKING_INFO_MAP[ma.LstId.sSUI]),n=await da(o,t);return{lstClient:e,...n}},pa=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await el(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SpringSuiAppHelper.deserialize",r);let s=new Yo(e,r).decode();return{txType:nl.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await el(r,i));let s;switch(n){case"mint":s=Zo.fromData(a);break;case"mintAndDeposit":s=ta.fromData(a);break;case"redeem":s=ea.fromData(a);break;default:throw new Error("not implemented")}return s.build({network:e,suiClient:r,account:i,lstClient:this.utils.lstClient,suilendClient:this.utils.suilendClient,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};var xl=require("@msafe/sui3-utils"),vl=require("turbos-clmm-sdk");var $=require("@msafe/sui3-utils"),Er=require("@mysten/sui.js/bcs"),kt=require("@mysten/sui.js/utils"),al=require("turbos-clmm-sdk");var K={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},G={PackageId:"0xdee9"};var du=(o,t,e,n)=>{if(o===1)switch(n.findIndex(i=>i===t)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${t}`)}switch(e.findIndex(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},fa=class{constructor(t,e,n){this.txb=t;this.turbosSdk=e;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(t){if(this.isSwapTransaction())return await this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}getMoveCallsTransaction(t){return t.every(e=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===e))}getSwapMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&t.includes(e.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${K.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${K.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let t=this.transactions.find(m=>m.kind==="MoveCall"),e=0;this.swap2Layer.includes(t.target)&&(e=1);let n=du(e,t.target,this.swap1Layer,this.swap2Layer),a=n.map((m,f)=>{let S=this.helper.decodeSharedObjectId(f),I=this.helper.decodeInputU128(4+f+e),x=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new al.BN(I.toString()));return{pool:S,a2b:m,nextTickIndex:x}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),l=this.helper.decodeInputBool(5+2*e),d=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:a[0].pool,a2b:a[0].a2b,amountSpecified:d}],address:s,amountSpecifiedIsInput:l});return{txType:$.TransactionType.Other,type:"Swap",intentionData:{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:u,amountB:l?u:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:$.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:a,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),a=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:$.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:a,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:$.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:$.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:a,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),a=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:$.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:a,nft:e,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:$.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){console.log(this.helper,"decodeRemoveLiquidity this.helper");let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),a=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:$.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:$.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:$.TransactionType.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),a=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:$.TransactionType.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),a=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:$.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new Ct(t,this.txb)}get collectRewardHelper(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect_reward`).map(e=>new Ct(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new Ct(t,this.txb)}get decreaseLiquidityHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new Ct(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${G.PackageId}::clob_v2::swap_exact_base_for_quote`);return new Ct(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${G.PackageId}::clob_v2::swap_exact_quote_for_base`);return new Ct(t,this.txb)}},Ct=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU128(t){let e=this.decodePureArg(t,"u128");return Number(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU32(t){let e=this.decodePureArg(t,"u32");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,kt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Er.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,kt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,kt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,kt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,kt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Er.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,kt.normalizeStructTag)(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};var rl=require("turbos-clmm-sdk");var ba=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new rl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var il=require("turbos-clmm-sdk");var ga=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new il.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,nft:r,txb:i}=this.data;return n.nft.burn({pool:a,nft:r,txb:i})}static fromData(e){return new o(e)}};var sl=require("turbos-clmm-sdk");var ha=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new sl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:a,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(e){return new o(e)}};var cl=require("turbos-clmm-sdk");var ya=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new cl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:a,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(e){return new o(e)}};var ll=require("turbos-clmm-sdk");var Sa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new ll.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{fee:a,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,amountA:p,amountB:m,deadline:f,txb:S}=this.data;return n.pool.createPool({fee:a,amountA:p,amountB:m,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,deadline:f,txb:S})}static fromData(e){return new o(e)}};var dl=require("turbos-clmm-sdk");var wa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new dl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var ul=require("turbos-clmm-sdk");var Ta=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new ul.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:u}=this.data;return n.pool.increaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:u})}static fromData(e){return new o(e)}};var pl=require("@mysten/sui.js/transactions"),ml=require("@mysten/sui.js/utils");var Ia=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new pl.TransactionBlock;return n.moveCall({target:`${K.PackageId}::claim::claim`,typeArguments:[K.turbosCoinType],arguments:[n.object(K.Claim),n.object(ml.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(e){return new o(e)}};var fl=require("@mysten/sui.js/transactions");var Ca=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new fl.TransactionBlock;return n.moveCall({target:`${K.PackageId}::claim::join`,typeArguments:[K.turbosCoinType],arguments:[n.object(K.Claim)]}),n}static fromData(e){return new o(e)}};var bl=require("@mysten/sui.js/transactions"),gl=require("turbos-clmm-sdk");var ka=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new gl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),a=new bl.TransactionBlock;return a=await n.pool.collectFee({txb:a,...this.data}),a=await n.pool.collectReward({txb:a,...this.data}),a=await n.pool.decreaseLiquidity({txb:a,...this.data}),a=await n.nft.burn({txb:a,nft:this.data.nft,pool:this.data.pool}),a}static fromData(e){return new o(e)}};var hl=require("turbos-clmm-sdk");var xa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new hl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:u,slippage:d,deadline:p,txb:m})}static fromData(e){return new o(e)}};var Cl=require("turbos-clmm-sdk");var Wr=require("@mysten/sui.js/utils"),Lr=require("@mysten/sui.js/transactions");var yl=require("turbos-clmm-sdk");var Me=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let a=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),a.push(...r.data);while(r.hasNextPage);let i=[],s=0;return a.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let a=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(a,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(a,[n.pure(e)]);return[r,a]}isSuiCoinAddress(t){return t.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(t){let e=await this.turbosSdk.provider.getOwnedObjects({owner:t,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${G.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?(0,yl.unstable_getObjectId)(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${G.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var Sl=89,wl=1e6,Tl=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Lr.TransactionBlock,c=new Me(i),l=await c.getCoinsData(r,e,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),[f,S,I]=s.moveCall({typeArguments:[t,e],target:`${G.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(Sl),m,s.pure(a),s.object((0,Wr.normalizeSuiObjectId)("0x6")),d]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([f],s.pure(r)),s.transferObjects([S],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(wl),s},Il=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Lr.TransactionBlock,c=new Me(i),l=await c.getCoinsData(r,t,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),f=c.zero(e,s),[S,I,x]=s.moveCall({typeArguments:[t,e],target:`${G.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(Sl),m,s.pure(a),d,f,s.object((0,Wr.normalizeSuiObjectId)("0x6"))]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([S],s.pure(r)),s.transferObjects([I],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(wl),s};var va=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Cl.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await Il({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var kl=require("turbos-clmm-sdk");var Da=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new kl.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await Tl({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var Aa=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new vl.TurbosSdk(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:a,account:r}=t;console.log(t,"input");let s=await new fa(a,e,n).decode(r.address);return{txType:xl.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":r=Sa.fromData(t.intentionData);break;case"AddLiquidity":r=ba.fromData(t.intentionData);break;case"IncreaseLiquidity":r=Ta.fromData(t.intentionData);break;case"DecreaseLiquidity":r=wa.fromData(t.intentionData);break;case"RemoveLiquidity":r=ka.fromData(t.intentionData);break;case"CollectFee":r=ha.fromData(t.intentionData);break;case"CollectReward":r=ya.fromData(t.intentionData);break;case"Burn":r=ga.fromData(t.intentionData);break;case"Swap":r=xa.fromData(t.intentionData);break;case"PrixJoin":r=Ca.fromData(t.intentionData);break;case"PrixClaim":r=Ia.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=va.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=Da.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Pl=require("@msafe/sui3-utils");var Oa=require("@msafe/sui3-utils"),Ur=require("@mysten/sui.js/bcs"),xt=require("@mysten/sui.js/utils");var uu={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},O=uu;var Pa=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:Oa.TransactionType.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Oa.TransactionType.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:Oa.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(O.packageId));return new Fr(t,this.txb)}},Fr=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,xt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Ur.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,xt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,xt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,xt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,xt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ur.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,xt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Dl=require("@mysten/sui.js/transactions");var _a=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Dl.TransactionBlock,{ticketId:a}=this.data;return n.moveCall({target:`${O.packageId}::native_pool::burn_ticket`,arguments:[n.object(O.poolObjectId),n.object(O.systemStateObjectId),n.object(a)]}),n}static fromData(e){return new o(e)}};var Al=require("@mysten/sui.js/transactions");var Ra=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Al.TransactionBlock,{amount:a}=this.data,[r]=n.splitCoins(n.gas,[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::stake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),r]}),n}static fromData(e){return new o(e)}};var Ol=require("@mysten/sui.js/transactions");var Ba=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Ol.TransactionBlock,{amount:a}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===O.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::unstake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),l]}),n}static fromData(e){return new o(e)}};var ja=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,a=new Pa(e).decode();return{txType:Pl.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case"Stake":a=Ra.fromData(t.intentionData);break;case"UnStake":a=Ba.fromData(t.intentionData);break;case"ClaimTicket":a=_a.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var ql=require("@msafe/sui3-utils");var Ml=require("@msafe/sui3-utils");var Rl=require("@firefly-exchange/library-sui"),Bl=require("@firefly-exchange/library-sui/dist/src/spot"),_l={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x702301e7c6ca527a6f6a83f12c5edf2dcd6ec7a23fb5318ec86d88282eab7057"}},vt=(o,t)=>{if(o!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let e=new Rl.SuiClient({url:_l.rpc});return new Bl.OnChainCalls(e,_l.objects,{address:t.address,isUIWallet:!1})};var Ne=require("@firefly-exchange/library-sui"),jl=require("turbos-clmm-sdk"),B=class{static async openPositionAndAddLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.openPositionWithFixedAmount(r,t.lowerTick,t.upperTick,i,{returnTx:!0})}static async provideLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.provideLiquidityWithFixedAmount(r,t.position,i,{returnTx:!0})}static async removeLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.removeLiquidity(r,t.position,i,{returnTx:!0})}static async closePosition(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.closePosition(r,t.position,{returnTx:!0})}static async collectRewards(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectRewards(r,t.position,{rewardCoinsType:t.rewardCoinsType,returnTx:!0})}static async collectFee(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectFee(r,t.position,{returnTx:!0})}static async collectFeeAndRewards(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectFeeAndRewards(r,t.position,{returnTx:!0})}buildLiqInput(t,e){return Ne.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(e.lowerTick,e.upperTick,new Ne.BN(new jl.Decimal(e.tokenAmount).mul(10**(e.isCoinA?t.coin_a.decimals:t.coin_b.decimals)).toFixed(0)),e.isCoinA,!0,e.slippage,new Ne.BN(t.current_sqrt_price))}};var Ma=class o extends b{constructor(e){super(e);this.data=e}txType=Ml.TransactionType.Other;txSubType="ClosePosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.closePosition(r,n,a)}static fromData(e){return new o(e)}};var Nl=require("@msafe/sui3-utils");var Na=class o extends b{constructor(e){super(e);this.data=e}txType=Nl.TransactionType.Other;txSubType="CollectFee";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.collectFee(r,n,a)}static fromData(e){return new o(e)}};var El=require("@msafe/sui3-utils");var Ea=class o extends b{constructor(e){super(e);this.data=e}txType=El.TransactionType.Other;txSubType="CollectFeeAndRewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.collectFeeAndRewards(r,n,a)}static fromData(e){return new o(e)}};var Wl=require("@msafe/sui3-utils");var Wa=class o extends b{constructor(e){super(e);this.data=e}txType=Wl.TransactionType.Other;txSubType="CollectRewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.collectRewards(r,n,a)}static fromData(e){return new o(e)}};var Ll=require("@msafe/sui3-utils");var La=class o extends b{constructor(e){super(e);this.data=e}txType=Ll.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.openPositionAndAddLiquidity(r,n,a)}static fromData(e){return new o(e)}};var Ul=require("@msafe/sui3-utils");var Ua=class o extends b{constructor(e){super(e);this.data=e}txType=Ul.TransactionType.Other;txSubType="ProvideLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.provideLiquidity(r,n,a)}static fromData(e){return new o(e)}};var Fl=require("@msafe/sui3-utils");var Fa=class o extends b{constructor(e){super(e);this.data=e}txType=Fl.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await B.removeLiquidity(r,n,a)}static fromData(e){return new o(e)}};var qa=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(t){console.log("Bluefin helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:ql.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=La.fromData(t.intentionData);break;case"ProvideLiquidity":r=Ua.fromData(t.intentionData);break;case"RemoveLiquidity":r=Fa.fromData(t.intentionData);break;case"ClosePosition":r=Ma.fromData(t.intentionData);break;case"CollectFee":r=Na.fromData(t.intentionData);break;case"CollectRewards":r=Wa.fromData(t.intentionData);break;case"CollectFeeAndRewards":r=Ea.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var mu=no.fromHelpers([new Qn,new Yn,new Un,new Zn,new yn,new Aa,new Jo,new ja,new Ge,new ua,new pa,new $e,new qa]);
|
|
1
|
+
"use strict";var od=Object.create;var Ue=Object.defineProperty;var ad=Object.getOwnPropertyDescriptor;var rd=Object.getOwnPropertyNames;var id=Object.getPrototypeOf,sd=Object.prototype.hasOwnProperty;var za=(o,t)=>{for(var e in t)Ue(o,e,{get:t[e],enumerable:!0})},zr=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of rd(t))!sd.call(o,a)&&a!==e&&Ue(o,a,{get:()=>t[a],enumerable:!(n=ad(t,a))||n.enumerable});return o};var B=(o,t,e)=>(e=o!=null?od(id(o)):{},zr(t||!o||!o.__esModule?Ue(e,"default",{value:o,enumerable:!0}):e,o)),cd=o=>zr(Ue({},"__esModule",{value:!0}),o);var Du={};za(Du,{appHelpers:()=>vu});module.exports=cd(Du);var oi=require("@msafe/sui3-utils");var Jr=B(require("sort-keys-recursive")),b=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Jr.default)(this.data))}};var Xr=require("@alphafi/alphafi-sdk"),Fe=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r,isAmountA:i}=this.data;return await(0,Xr.depositDoubleAssetTxb)(a,n.address,r,i)}static fromData(e){return new o(e)}};var Yr=require("@alphafi/alphafi-sdk"),qe=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r}=this.data;return await(0,Yr.depositSingleAssetTxb)(a,n.address,r)}static fromData(e){return new o(e)}};var Zr=require("@alphafi/alphafi-sdk"),$e=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{withdrawFromLocked:a,xTokensAmount:r}=this.data;return await(0,Zr.withdrawAlphaTxb)(r,a,n.address)}static fromData(e){return new o(e)}};var ti=require("@alphafi/alphafi-sdk"),Ve=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,xTokensAmount:r}=this.data;return await(0,ti.withdrawTxb)(r,a,n.address)}static fromData(e){return new o(e)}};var ei=require("@alphafi/alphafi-sdk"),Qe=class o extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e;return await(0,ei.claimRewardTxb)(n.address)}static fromData(e){return new o(e)}};var Et=require("@msafe/sui3-utils");var ae=require("@alphafi/alphafi-sdk"),ni=B(require("bignumber.js")),Ke=require("@mysten/sui/utils"),He=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let t=this.getLiquidityChangeEvent();if(!t)throw new Error("No liquidity change event found. Unable to decode transaction.");let e=t.parsedJson,n=e.pool_id,a=ae.poolIdPoolNameMap[n];if(this.isWithdrawAlphaEvent(t))return this.decodeWithdrawAlpha(e);if(this.isWithdrawEvent(e))return this.decodeWithdraw(a);if(this.isDoubleAssetDepositEvent(e,a))return this.decodeDoubleAssetDeposit(a,e);if(this.isSingleAssetDepositEvent(e,a))return this.decodeSingleAssetDeposit(a,e);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getLiquidityChangeEvent(){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(t){return t.includes("LiquidityChangeEvent")||t.includes("LiquidityChangeNewNewEvent")||t.includes("WithdrawEventV2")}isWithdrawAlphaEvent(t){return t.type.includes("WithdrawEventV2")}isWithdrawEvent(t){return t.event_type===1}isDoubleAssetDepositEvent(t,e){return t.event_type===0&&ae.poolInfo[e].assetTypes.length===2}isSingleAssetDepositEvent(t,e){return t.event_type===0&&ae.poolInfo[e].assetTypes.length===1}extractXTokensAmount(){let t=this.inputs.find(n=>n.Pure!==void 0);if(!t||!t.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let e=t.Pure.bytes;return new ni.default((0,Ke.toHEX)((0,Ke.fromB64)(e)),16).toString()}decodeDoubleAssetDeposit(t,e){let{amount_a:n,amount_b:a}=e,r=Number(n)>0;return{txType:Et.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:t,amount:r?n:a,isAmountA:r}}}decodeSingleAssetDeposit(t,e){let{amount:n}=e;return{txType:Et.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:t,amount:n}}}decodeWithdraw(t){let e=this.extractXTokensAmount();return{txType:Et.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:t,xTokensAmount:e}}}decodeWithdrawAlpha(t){let e=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=t;return{txType:Et.TransactionType.Other,type:"depositDoubleAsset",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:e}}}decodeClaimReward(){return{txType:Et.TransactionType.Other,type:"claimReward",intentionData:{}}}};var Ge=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(t){let{transaction:e,suiClient:n,account:a}=t,r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e}),s=new He(e,r).decode();return{txType:oi.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{account:e}=t,n;switch(t.txSubType){case"depositSingleAsset":n=qe.fromData(t.intentionData);break;case"depositDoubleAsset":n=Fe.fromData(t.intentionData);break;case"withdraw":n=Ve.fromData(t.intentionData);break;case"withdrawAlpha":n=$e.fromData(t.intentionData);break;case"claimReward":n=Qe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({account:e})}};var di=require("@msafe/sui3-utils");var si=require("@msafe/sui3-utils");var ii=require("@mysten/sui/transactions");var ai=require("bucket-protocol-sdk"),ri=(o,t)=>{let e=o==="sui:mainnet"?"mainnet":"testnet";return new ai.BucketClient(e,t.address)};var ze=async(o,t,e,n)=>{let{coinType:a,amount:r}=o,i=new ii.Transaction;return await ri(e,t).getPsmTx(i,a,r,n,t.address),i};var Je=class o extends b{constructor(e){super(e);this.data=e}txType=si.TransactionType.Other;txSubType="psm-in";async build(e){let{account:n,network:a}=e;return await ze(this.data,n,a,!1)}static fromData(e){return new o(e)}};var ci=require("@msafe/sui3-utils");var Xe=class o extends b{constructor(e){super(e);this.data=e}txType=ci.TransactionType.Other;txSubType="psm-out";async build(e){let{account:n,network:a}=e;return await ze(this.data,n,a,!0)}static fromData(e){return new o(e)}};var Xa=require("@msafe/sui3-utils");var li=require("@mysten/sui/bcs"),Ye=class{constructor(t){this.transaction=t}decode(){if(this.isPsmInTransaction())return this.decodePsmIn();if(this.isPsmOutTransaction())return this.decodePsmOut();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(t=>t.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(t=>t.$kind==="TransferObjects")}isPsmInTransaction(){return!!this.getMoveCallCommand("charge_reservoir")}isPsmOutTransaction(){return!!this.getMoveCallCommand("discharge_reservoir")}decodePsmIn(){let t="0",e=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];e.$kind=="Input"&&(t=this.getPureInputU64(e.Input));let a=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments[0];return console.log("Decoder.decodePsmIn",a,t),{txType:Xa.TransactionType.Other,type:"psm-in",intentionData:{coinType:a,amount:t}}}decodePsmOut(){let t="0",e=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];e.$kind=="Input"&&(t=this.getPureInputU64(e.Input));let a=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments[0];return console.log("Decoder.decodePsmOut",a,t),{txType:Xa.TransactionType.Other,type:"psm-out",intentionData:{coinType:a,amount:t}}}getPureInputU64(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return li.bcs.U64.fromBase64(e.Pure.bytes)}};var Ze=class{application="bucket";supportSDK="@mysten/sui";async deserialize(t){console.log("Bucket helper deserialize input: ",t);let{transaction:e}=t,a=new Ye(e).decode();return{txType:di.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"psm-in":r=Je.fromData(t.intentionData);break;case"psm-out":r=Xe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var ms=require("@msafe/sui3-utils");var Ti=require("@msafe/sui3-utils");var re=require("@cetusprotocol/aggregator-sdk"),ui=require("@cetusprotocol/cetus-periphery-sdk"),pi=require("@cetusprotocol/cetus-sui-clmm-sdk"),mi=B(require("@cetusprotocol/vaults-sdk")),fi=require("@mysten/sui/client"),dd={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},ud={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Dt=(o,t)=>{let e=dd,n=new pi.CetusClmmSDK(e);return n.senderAddress=t.address,n},E=(o,t)=>{let e=Dt(o,t),n=ud;return new ui.CetusPeripherySDK(n,e)},pd="https://api-sui.cetus.zone/router_v2/find_routes",bi=(o,t)=>{let e=new fi.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new re.AggregatorClient(pd,t.address,e,re.Env.Mainnet)},md={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10"},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},aggregator:{endPoint:"https://api-sui.cetus.zone/router_v2/find_routes",fullNodeurl:"https://fullnode.mainnet.sui.io/",walletAddress:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb",env:re.Env.Mainnet,providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"]}},Ya=(o,t)=>{let e=new mi.default(md);return e.senderAddress=t.address,e};var gi=async(o,t,e)=>await Dt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),hi=async(o,t,e)=>await Dt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),yi=async(o,t,e)=>await Dt(e,t).Position.closePositionTransactionPayload(o),Si=async(o,t,e)=>await Dt(e,t).Position.removeLiquidityTransactionPayload(o),wi=async(o,t,e)=>await Dt(e,t).Rewarder.collectRewarderTransactionPayload(o);var tn=class o extends b{constructor(e){super(e);this.data=e}txType=Ti.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await gi(r,n,a)}static fromData(e){return new o(e)}};var Ii=require("@msafe/sui3-utils");var en=class o extends b{constructor(e){super(e);this.data=e}txType=Ii.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await wi(r,n,a)}static fromData(e){return new o(e)}};var Ci=require("@msafe/sui3-utils");var nn=class o extends b{constructor(e){super(e);this.data=e}txType=Ci.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Si(r,n,a)}static fromData(e){return new o(e)}};var Bi=require("@msafe/sui3-utils");var ki=async(o,t,e)=>await E(e,t).Farms.openPositionAddLiquidityStakePaylod(o),xi=async(o,t,e)=>await E(e,t).Farms.addLiquidityFixCoinPayload(o),vi=async(o,t,e)=>await E(e,t).Farms.removeLiquidityPayload(o),Di=async(o,t,e)=>await E(e,t).Farms.removeLiquidityPayload(o),Ai=async(o,t,e)=>await E(e,t).Farms.claimFeeAndClmmReward(o),Oi=async(o,t,e)=>await E(e,t).Farms.harvestPayload(o),Pi=async(o,t,e)=>{let n=E(e,t),a=Object.values(o);return await n.Farms.batchHarvestPayload(a)},Ri=async(o,t,e)=>await E(e,t).Farms.depositPayload(o),_i=async(o,t,e)=>await E(e,t).Farms.withdrawPayload(o);var on=class o extends b{constructor(e){super(e);this.data=e}txType=Bi.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ki(r,n,a)}static fromData(e){return new o(e)}};var ji=require("@msafe/sui3-utils");var an=class o extends b{constructor(e){super(e);this.data=e}txType=ji.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Pi(r,n,a)}static fromData(e){return new o(e)}};var Ei=require("@msafe/sui3-utils");var rn=class o extends b{constructor(e){super(e);this.data=e}txType=Ei.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ai(r,n,a)}static fromData(e){return new o(e)}};var Ni=require("@msafe/sui3-utils");var sn=class o extends b{constructor(e){super(e);this.data=e}txType=Ni.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await vi(r,n,a)}static fromData(e){return new o(e)}};var Mi=require("@msafe/sui3-utils");var cn=class o extends b{constructor(e){super(e);this.data=e}txType=Mi.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Oi(r,n,a)}static fromData(e){return new o(e)}};var Wi=require("@msafe/sui3-utils");var ln=class o extends b{constructor(e){super(e);this.data=e}txType=Wi.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await xi(r,n,a)}static fromData(e){return new o(e)}};var Li=require("@msafe/sui3-utils");var dn=class o extends b{constructor(e){super(e);this.data=e}txType=Li.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Di(r,n,a)}static fromData(e){return new o(e)}};var Ui=require("@msafe/sui3-utils");var un=class o extends b{constructor(e){super(e);this.data=e}txType=Ui.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ri(r,n,a)}static fromData(e){return new o(e)}};var Fi=require("@msafe/sui3-utils");var pn=class o extends b{constructor(e){super(e);this.data=e}txType=Fi.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await _i(r,n,a)}static fromData(e){return new o(e)}};var qi=require("@msafe/sui3-utils");var mn=class o extends b{constructor(e){super(e);this.data=e}txType=qi.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await hi(r,n,a)}static fromData(e){return new o(e)}};var $i=require("@msafe/sui3-utils");var fn=class o extends b{constructor(e){super(e);this.data=e}txType=$i.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await yi(r,n,a)}static fromData(e){return new o(e)}};var Ki=require("@msafe/sui3-utils");var Vi=require("@cetusprotocol/aggregator-sdk"),Qi=require("@mysten/sui/transactions");var Hi=async(o,t,e)=>{let n=bi(e,t),a=new Qi.Transaction;return await n.fastRouterSwap({...o,routers:(0,Vi.restituteMsafeFastRouterSwapParams)(o.routers),txb:a}),a};var bn=class o extends b{constructor(e){super(e);this.data=e}txType=Ki.TransactionType.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Hi(r,n,a)}static fromData(e){return new o(e)}};var Ji=require("@msafe/sui3-utils");var Gi=async(o,t,e)=>await Ya(e,t).Vaults.deposit(o),zi=async(o,t,e)=>await Ya(e,t).Vaults.withdraw(o);var gn=class o extends b{constructor(e){super(e);this.data=e}txType=Ji.TransactionType.Other;txSubType="AddVaultsPosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Gi(r,n,a)}static fromData(e){return new o(e)}};var Xi=require("@msafe/sui3-utils");var hn=class o extends b{constructor(e){super(e);this.data=e}txType=Xi.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await zi(r,n,a)}static fromData(e){return new o(e)}};var es=require("@msafe/sui3-utils");var Zi=require("@mysten/sui/transactions"),Yi={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},ts=async(o,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",o),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:a,periods:r,CLOCK_ADDRESS:i}=o,s=new Zi.Transaction;return r.forEach(c=>{s.moveCall({target:`${Yi.published_at}::router::redeem`,typeArguments:[Yi.cetus_coin_type],arguments:[s.object(n),s.object(a),s.pure(c),s.object(i)]})}),s};var yn=class o extends b{constructor(e){super(e);this.data=e}txType=es.TransactionType.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ts(r,n,a)}static fromData(e){return new o(e)}};var cs=require("@msafe/sui3-utils");var ns=require("@mysten/sui/transactions");var os=async(o,t,e)=>{let n=E(e,t),a=new ns.Transaction;return await n.XCetusModule.convertPayload(o,a)},as=async(o,t,e)=>await E(e,t).XCetusModule.redeemLockPayload(o),rs=async(o,t,e)=>await E(e,t).XCetusModule.redeemDividendV3Payload(o.phases,o.venft_id,o.bonus_types,o.bonus_types_v2,o.xTokenType),is=async(o,t,e)=>await E(e,t).XCetusModule.cancelRedeemPayload(o),ss=async(o,t,e)=>await E(e,t).XCetusModule.redeemPayload(o);var Sn=class o extends b{constructor(e){super(e);this.data=e}txType=cs.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await is(r,n,a)}static fromData(e){return new o(e)}};var ls=require("@msafe/sui3-utils");var wn=class o extends b{constructor(e){super(e);this.data=e}txType=ls.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await rs(r,n,a)}static fromData(e){return new o(e)}};var ds=require("@msafe/sui3-utils");var Tn=class o extends b{constructor(e){super(e);this.data=e}txType=ds.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await os(r,n,a)}static fromData(e){return new o(e)}};var us=require("@msafe/sui3-utils");var In=class o extends b{constructor(e){super(e);this.data=e}txType=us.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ss(r,n,a)}static fromData(e){return new o(e)}};var ps=require("@msafe/sui3-utils");var Cn=class o extends b{constructor(e){super(e);this.data=e}txType=ps.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await as(r,n,a)}static fromData(e){return new o(e)}};var kn=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:ms.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=tn.fromData(t.intentionData);break;case"IncreaseLiquidity":r=mn.fromData(t.intentionData);break;case"DecreaseLiquidity":r=nn.fromData(t.intentionData);break;case"RemoveLiquidity":r=fn.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=en.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=on.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=ln.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=sn.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=dn.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=rn.fromData(t.intentionData);break;case"FarmingHarvest":r=cn.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=an.fromData(t.intentionData);break;case"FarmingStake":r=un.fromData(t.intentionData);break;case"FarmingUnstake":r=pn.fromData(t.intentionData);break;case"xCETUSConvert":r=Tn.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Cn.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=wn.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=Sn.fromData(t.intentionData);break;case"xCETUSRedeem":r=In.fromData(t.intentionData);break;case"VestingRedeem":r=yn.fromData(t.intentionData);break;case"AggregatorSwap":r=bn.fromData(t.intentionData);break;case"AddVaultsPosition":r=gn.fromData(t.intentionData);break;case"RemoveVaultsPosition":r=hn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Ns=require("@msafe/sui3-utils");var fs=B(require("sort-keys-recursive")),y=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,fs.default)(this.data))}};var ie=require("@mysten/sui.js/client");var Za={};za(Za,{contractId:()=>gd,default:()=>Td,feeObjId:()=>Sd,roleObjId:()=>hd,status:()=>bd,transaction:()=>fd,upgradeCapObjId:()=>wd,vaultObjId:()=>yd});var fd="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",bd="success",gd="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",hd="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yd="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Sd="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",wd="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Td={transaction:fd,status:bd,contractId:gd,roleObjId:hd,vaultObjId:yd,feeObjId:Sd,upgradeCapObjId:wd};var tr={};za(tr,{contractId:()=>kd,default:()=>Od,feeObjId:()=>Dd,roleObjId:()=>xd,status:()=>Cd,transaction:()=>Id,upgradeCapObjId:()=>Ad,vaultObjId:()=>vd});var Id="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Cd="success",kd="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",xd="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",vd="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Dd="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ad="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Od={transaction:Id,status:Cd,contractId:kd,roleObjId:xd,vaultObjId:vd,feeObjId:Dd,upgradeCapObjId:Ad};var Pd=(0,ie.getFullnodeUrl)("testnet"),Rd=(0,ie.getFullnodeUrl)("testnet"),_d=(0,ie.getFullnodeUrl)("mainnet"),Bd=(0,ie.getFullnodeUrl)("mainnet"),jd="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Ed="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Nd="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Md="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",bs=Za,gs=tr,Wd=new Map([["dev",{env:"dev",rpc:{url:Pd},backend:{url:jd},contract:bs}],["stg",{env:"stg",rpc:{url:Rd},backend:{url:Ed},contract:bs}],["prev",{env:"prev",rpc:{url:_d},backend:{url:Nd},contract:gs}],["prod",{env:"prod",rpc:{url:Bd},backend:{url:Md},contract:gs}]]);function hs(o,t){let e=Wd.get(o);if(!e)throw new Error(`Env not supported: ${o}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}var ys=require("@mysten/sui.js/client");var k=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:a,context:r}=n;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var xn=class extends k{constructor(){super(11,"Backend is not specified")}};var vn=class extends k{constructor(){super(1,"Wallet not connected")}};var Y=B(require("axios"));var Nt=class extends k{constructor(t,e){super(10,t,{context:e})}};var Dn=class o{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Y.AxiosError)throw new Nt(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new Nt(t.data.code)}throw new Nt(t.status.toString())}async getIncomingStreams(t,e){let n=await Y.default.post(`${this.apiURL}/stream`,{recipient:t,...e});return o.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await Y.default.post(`${this.apiURL}/stream`,{sender:t,...e});return o.parseResponseData(n)}async getStreamHistory(t){let e=await Y.default.post(`${this.apiURL}/stream-events`,t),n=o.parseResponseData(e);return n.data.forEach(a=>{let r=a;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await Y.default.post(`${this.apiURL}/stream-info`,{address:t});return o.parseResponseData(e)}async getAllRecipients(t,e){let n=await Y.default.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return o.parseResponseData(n)}async getAllSenders(t,e){let n=await Y.default.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return o.parseResponseData(n)}};var Mt=class o{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new ys.SuiClient({url:t.rpc.url}),t.backend&&(this._backend=new Dn(t.backend.url))}static new(t,e){let n=hs(t,e);return new o(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new xn;return this._backend}set backend(t){this._backend=t}connectWallet(t){this.signer=t}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new vn;return this.signer}async walletAddress(){return this.wallet.address()}};var Ot=require("@mysten/sui.js/utils");var pe=require("@mysten/sui.js/transactions");var rr=require("@mysten/sui.js/transactions"),ue=require("@mysten/sui.js/utils");var er=50n,An=10000n,Ss=25n,nr=100000000n;var z=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},se=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},it=class o{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);let a=i=>new o(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return a(r)}})}moveArg(){return this.result}};var or=require("buffer"),ws=require("@mysten/sui.js/utils");var ce=class extends k{constructor(t,e){super(3,t,{context:e})}};var On=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="address")throw new ce("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return(0,ws.normalizeSuiAddress)(or.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="u64")throw new ce("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return or.Buffer.from(n).readBigInt64LE()}};var ar=require("@mysten/sui.js/bcs");var D=class extends k{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Is={groupId:"string",name:"string"},Ld=64;function Cs(o){return ks(o),ar.bcs.ser(Is,o).toString("base64")}function le(o){let t=ar.bcs.de(Is,o,"base64");return ks(t),t}function ks(o){if(!Ts(o.name))throw new D("Invalid metadata: Name contains unknown character");if(!Ts(o.groupId))throw new D("Invalid metadata: Group ID contains unknown character");if(o.name.length>Ld)throw new D("Invalid metadata: Name exceed max length 64")}function Ts(o){return/^[\x00-\x7F]+$/.test(o)}var de=require("@mysten/sui.js/utils");function Pn(o,t){return(0,de.normalizeStructTag)(o)===(0,de.normalizeStructTag)(t)}function st(o,t){return(0,de.normalizeStructTag)(o)===(0,de.normalizeStructTag)(t)}var Rn="txn.gas";var xs=require("nanoid");function vs(){return(0,xs.nanoid)()}var At=class o{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Cs({name:t.name,groupId:vs()}),coinType:(0,ue.normalizeStructTag)(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new rr.TransactionBlock,n=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,r[0]),s;a.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let l=t.recipients[c],d=this.amountForRecipient(l,t.numberEpoch),u=this.getStreamFeeLocal(d),[p]=e.splitCoins(i,[e.pure(d+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new it(p),flatFeeCoin:new it(m),metadata:t.metadata,recipient:l.address,timeStart:t.startTime,cliff:l.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=o.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:er,denominator:An},claimFeePercent:{numerator:Ss,denominator:An},flatFeePerStream:nr}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),n=t.object(e.primaryCoin)):e.primaryCoin===Rn?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return Pn(n,ue.SUI_TYPE_ARG)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:ue.SUI_TYPE_ARG,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:a.totalAmount+i,streamFeeAmount:a.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(t.recipients.length)*this.flatSuiFee,...e}}amountForRecipient(t,e){return BigInt(t.amountPerEpoch)*BigInt(e)+BigInt(t.cliffAmount)}get flatSuiFee(){return nr}getStreamFeeLocal(t){return t*er/An}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new rr.TransactionBlock,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new On(n).getU64()}get wallet(){return this.globals.wallet}};var ir=require("@mysten/sui.js/transactions");var Ds="0x0000000000000000000000000000000000000000000000000000000000000006";var Wt=class{constructor(t,e,n){this.moduleName=t;this.config=e;this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(ir.Transactions.MoveCall({target:n,arguments:e.arguments.map(a=>a instanceof se?a.moveArgs(t):a instanceof z?a.moveArg(t):a instanceof it?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],a=[]){t.add(ir.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof se?r.moveArgs(t):r instanceof z?r.moveArg(t):r instanceof it?r.moveArg():t.pure(r)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new z(t):t}vaultObject(){return new z(this.config.vaultObjId)}roleObject(){return new z(this.config.roleObjId)}feeObject(){return new z(this.config.feeObjId)}clockObject(){return new z(Ds)}};var Lt=class o extends Wt{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_fee,arguments:[a,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_flat_fee,arguments:[a,r,n],typeArgs:[]})}setClaimFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_claim_fee,arguments:[a,r,n],typeArgs:[]})}streamingFee(e,n){let a=this.feeObject();return this.addContractCall(e,{method:o.MethodName.streaming_fee,arguments:[a,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:o.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:o.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var J=class o extends Wt{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,n){let a=this.feeObject(),r=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:o.MethodName.create_stream,arguments:[a,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let a=this.makeObject(n.streamId);return this.addContractCall(e,{method:o.MethodName.set_auto_claim,arguments:[a,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.cancel_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let a=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream_by_proxy,arguments:[a,r,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream_by_proxy}`}};var Ut=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lt(e,t),this.streamContract=new J(e,t)}feeContract;streamContract;async createStreams(t){let e=At.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new At(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let a=new pe.TransactionBlock;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new pe.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new pe.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new pe.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var P=class extends k{constructor(t,e={}){super(0,t,e)}};async function cr(o){let t=[];for(;await o.hasNext();){let e=await o.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var sr=class{constructor(t){this.requester=t;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},Ft=class{constructor(t){this.requester=t;this.pager=new sr(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var _n=class extends k{constructor(e,n,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:a}});this.coinType=e;this.requestAmount=n;this.gotAmount=a}};var Ud=25;async function As(o,t,e,n="0x2::sui::SUI",a=Ud){let r=new lr(o,t,n,a),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new _n(n,e,i);return s}var lr=class extends Ft{constructor(e,n,a,r){super(new dr(e,n,a,r));this.suiClient=e;this.owner=n;this.coinType=a;this.reqPageSize=r}},dr=class{constructor(t,e,n,a){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=a;if(a<=0)throw new P("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var be=require("@mysten/sui.js/transactions"),ge=require("@mysten/sui.js/utils"),Ps=require("luxon");var Bn=class extends k{constructor(){super(7,"Connected wallet is not creator")}};var me=class extends k{constructor(){super(8,"Connected wallet is not recipient")}};var fe=class extends k{constructor(t,e){super(6,t,{context:e})}};var jn=class extends k{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};var Nn=require("luxon"),Os=(1n<<64n)-1n,En=1e3;function ur(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/En);return Nn.DateTime.fromMillis(e*En)}function pr(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/En);return Nn.Duration.fromMillis(e*En)}var ct=class o{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new J(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await o.fetchStreamData(t,e);return new o(t,e,n)}static fromObjectData(t,e,n){let a=o.parseRawStreamData(e,n);return new o(t,e,a)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await o.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new P("Object Id does not align");this.rawData=o.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new Bn;let t=new be.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new me;let t=new be.TransactionBlock;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new me;let e=new be.TransactionBlock;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new be.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,ge.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return pr(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return le(t).groupId}get name(){let{metadata:t}=this.rawData.config;return le(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ur(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return pr(e)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:ur((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let t=this.rawData.status.status;return t===16?"CANCELED":t===17?"SETTLED":t===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===Os?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Ps.DateTime.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let n=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let n=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return o.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new jn(t):new fe(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new fe("Unexpected object type",{gotType:n.dataType});let{typeParams:a}=(0,ge.parseStructTag)(n.type),r=(0,ge.normalizeStructTag)(a[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};var qt=require("@mysten/sui.js/utils"),mr=require("luxon");var Mn=class extends k{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Fd=1e3,Wn=class{constructor(t){this.globals=t;this.coinMetaHelper=new fr(t.suiClient),this.createStreamHelper=new Ut(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Mn(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-n)/t.steps,i={realTotalAmount:a*t.steps+n,cliffAmount:n,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new D("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(mr.Duration.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:n,interval:mr.Duration.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...n,coinType:(0,qt.normalizeStructTag)(n.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,r)=>({...a,coinType:(0,qt.normalizeStructTag)(a.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new D("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new D("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Fd)throw new D("Interval shall be at least 1 second","interval",t.interval)}},fr=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,qt.normalizeStructTag)(t||qt.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};var lt=require("@mysten/sui.js/utils"),hr=require("luxon");var $t=class extends k{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var qd=25;async function gr(o,t,e){let n=new he(t),a=new ye(o,n,e);return await cr(a)}var he=class{constructor(t){this.ids=t;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},ye=class extends Ft{constructor(e,n,a){super(new br(e,n,a));this.suiClient=e;this.idIter=n;this.options=a}},br=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||qd,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:a}=this;n=e.filter(r=>a?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Ln=class o{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new $t("stream size 0");let n=e.map(r=>r.groupId);if(new Set(n).size!==1)throw new D("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await gr(t.suiClient,e);return n.forEach(a=>{if(!a)throw new P("stream group object data undefined")}),o.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let a=await o.parseGroupStreams(t,e,n);return new o(t,a)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],a=!0;return e.forEach(r=>{$d(n,r)||(a=!1)}),a}async refresh(){let t=await gr(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,n)=>{e.refreshWithData(t[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(t=>t.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((t,e)=>t+e.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((t,e)=>t+e.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((t,e)=>e.nextReleaseAmount===null?t:t+e.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((t,e)=>t+e.totalAmount,0n),streamed:this.streams.reduce((t,e)=>t+e.streamedAmount,0n),claimed:this.streams.reduce((t,e)=>t+e.claimedAmount,0n),claimable:this.streams.reduce((t,e)=>t+e.claimable,0n),canceled:this.streams.reduce((t,e)=>t+e.canceledAmount,0n)}}async historyEvents(t){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:t})}static async parseGroupStreams(t,e,n){let a=n.map((r,i)=>ct.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(a.map(r=>r.groupId)).size!==1)throw new $t("Not same group ID");if(!this.checkStreamGroup(a))throw new $t("Not same stream settings");return a}};function $d(o,t){return o.name===t.name&&o.groupId===t.groupId&&o.creator===t.creator&&o.start.toMillis()===t.start.toMillis()&&o.interval.toMillis()===t.interval.toMillis()&&o.steps===t.steps&&o.cancelable===t.cancelable}var Se=class o{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await Un.newIncoming(t);return new o(e,t.pageSize)}static async newOutgoing(t){let e=await Un.newOutgoing(t);return new o(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},Un=class o{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Fn.newIncomingQuery(t);return new o(e)}static async newOutgoing(t){let e=await Fn.newOutgoingQuery(t);return new o(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new P("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new P("No more results");return t}},Fn=class o{constructor(t,e,n,a){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=a;this.current=0;let r=new he(n.flat().map(i=>i.streamId));this.objectIter=new ye(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=Gd(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>(0,lt.normalizeSuiAddress)(s.recipient)===(0,lt.normalizeSuiAddress)(n)),i=Rs(r);return new o(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=zd(t.query),n=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(n,e),r=Rs(a);return new o(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Hd(this.globals,t[0].streamId,this.objectIter);return this.current++,_s(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Kd(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,Qd(e,this.query)?e:this.doNextRequest()}throw new P("Stream group with no stream")}};function Rs(o){let t=new Map;return o.forEach(e=>{let n=t.get(e.groupId);n?(n.push(e),t.set(e.groupId,n)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,n)=>hr.DateTime.fromISO(n[0].createDate).toMillis()-hr.DateTime.fromISO(e[0].createDate).toMillis())}function _s(o,t){if(t===void 0)return!0;let e=Vd(o,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?o.progress.claimable!==0n:o.progress.claimable===0n;return e&&n}return e}function Vd(o,t){return t===void 0?!0:Array.isArray(t)?t.includes(o.progress.status):o.progress.status===t}function Qd(o,t){if(!t)return!0;let e=!1;return o.streams.forEach(n=>{_s(n,t)&&(e=!0)}),e}async function Hd(o,t,e){let n=await Bs(e,t);return ct.fromObjectData(o,t,n)}async function Kd(o,t,e){let n=[];for(;n.length<t.length;){let a=await Bs(e,t[n.length]);n.push(a)}return Ln.newFromObjectResponse(o,t,n)}async function Bs(o,t){if(!await o.hasNext())throw new P("object iterator has been consumed");let e=await o.next();if(!e||e.error||e.data===void 0||e.data===null)throw new P("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new P("stream id not aligned");return e}function Gd(o){return{status:yr(o?.status),coinType:js(o?.coinType),sender:Es(o?.sender)}}function zd(o){return{status:yr(o?.status),coinType:js(o?.coinType),recipient:Es(o?.recipient)}}function yr(o){return o===void 0||o.length===0?"all":Array.isArray(o)?o.reduce((t,e)=>{let n=yr(e);return!t||t===n?n:"all"},void 0):Jd(o)}function Jd(o){switch(o){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new D("Unknown stream filtered status")}}function js(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,lt.normalizeStructTag)(t)):void 0:(0,lt.normalizeStructTag)(o)}function Es(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,lt.normalizeSuiAddress)(t)):void 0:(0,lt.normalizeSuiAddress)(o)}var Sr=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},qn=class{constructor(t){this.account=t}async address(){return this.account.address}},wr=class{constructor(t,e){this.singleWallet=t;this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(Pn(t.coinType,Ot.SUI_TYPE_ARG))return{primaryCoin:Rn};if(t.amount<=0)throw new D("Invalid coin request","coinAmount",t.amount);let e=await As(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new P("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},$n=class{globals;helper;constructor(t,e){this.globals=Mt.new(t,e),this.helper=new Wn(this.globals)}connectSingleWallet(t){let e=new wr(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Sr(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ct.new(this.globals,t)}async getIncomingStreams(t,e=10){return Se.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Se.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(n=>(0,Ot.normalizeStructTag)(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>(0,Ot.normalizeSuiAddress)(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>(0,Ot.normalizeSuiAddress)(a))}get wallet(){return this.globals.wallet}builder(){return new Ut(this.globals)}};var H=class extends y{application="mpay";getClient(t,e){let n=new $n(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new qn(e)),n}};var we=class extends H{constructor(e){super(e);this.data=e}txType=Ns.TransactionType.Stream;txSubType="Cancel";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).cancel()}};var Ms=require("@msafe/sui3-utils");var Te=class extends H{constructor(e){super(e);this.data=e}txType=Ms.TransactionType.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claimByProxy()}};var Ws=require("@msafe/sui3-utils");var Ie=class extends H{constructor(e){super(e);this.data=e}txType=Ws.TransactionType.Stream;txSubType="Claim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claim()}};var Ls=require("@msafe/sui3-utils");var Ce=class extends H{constructor(e){super(e);this.data=e}txType=Ls.TransactionType.Stream;txSubType="CreateStream";async build(e){let{network:n,account:a}=e;return this.getClient(n,a).createStream(this.data)}};var Tr=require("@mysten/sui.js/bcs"),dt=require("@mysten/sui.js/utils"),Vt=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,dt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Tr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,dt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,dt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,dt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,dt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Tr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,dt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Vn=class{constructor(t,e){this.globals=t;this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let e=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&st(e.target,this.contract.createStreamTarget));if(t.length===0)throw new P("No create stream transactions");return t.map(e=>new Vt(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:a}=le(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:a,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(a=>JSON.stringify({name:a.name,groupId:a.groupId,timeStart:String(a.timeStart),epochInterval:String(a.epochInterval),totalEpoch:String(a.totalEpoch),cancelable:a.cancelable,coinType:a.coinType}))).size!==1)throw new D("Stream group not have common info");let n=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:n,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new J(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new At(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}};var Qn=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new J(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(e=>e.kind==="MoveCall"&&st(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&st(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Vn(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:t}}decodeClaimByProxyTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:t}}decodeCancelStreamTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:t}}get helper(){let t=this.transactions[0];return new Vt(t,this.txb)}};var Us=require("@msafe/sui3-utils");var ke=class extends H{constructor(e){super(e);this.data=e}txType=Us.TransactionType.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Hn=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,a=Mt.new(e==="sui:mainnet"?"prod":"dev"),i=new Qn(a,n).decode(),s;switch(i.type){case"CreateStream":s=new Ce(i.info);break;case"SetAutoClaim":s=new ke({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Ie({streamId:i.streamId});break;case"ClaimByProxy":s=new Te({streamId:i.streamId});break;case"Cancel":s=new we({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:s.txType,txSubType:s.txSubType,intentionData:s.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new Ce(e);break;case"Claim":n=new Ie(e);break;case"ClaimByProxy":n=new Te(e);break;case"SetAutoClaim":n=new ke(e);break;case"Cancel":n=new we(e);break;default:throw new Error("not implemented")}return n.build({...t})}};var Qt=require("@msafe/sui3-utils");var Fs=require("@msafe/sui3-utils");var Kn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,Fs.buildCoinTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var qs=require("@msafe/sui3-utils");var Gn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,qs.buildObjectTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var $s=require("@msafe/sui3-utils"),Vs=require("@mysten/sui.js/transactions");var zn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,a=Vs.TransactionBlock.from(this.data.content);if(!(0,$s.isSameAddress)(a.blockData.sender,n.address))throw new Error("Invalid sender address");return a}static fromData(e){return new o(e)}};var Jn=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Qt.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case Qt.TransactionSubTypes.assets.coin.send:a=Kn.fromData(t.intentionData);break;case Qt.TransactionSubTypes.assets.object.send:a=Gn.fromData(t.intentionData);break;case Qt.TransactionSubTypes.others.plain:a=zn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var ec=require("@msafe/sui3-utils");var Qs=!1,xe={ProtocolPackage:"0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Ir(){if(!Qs)try{let o=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n,pool:a}=o;t&&(xe.ProtocolPackage=t),e&&(xe.borrowFee=e),n&&(xe.borrowFeeAddress=n),a&&(xe.pool=a),Qs=!0}catch(o){console.error(o.message)}}var h=xe;var Rt=require("@msafe/sui3-utils"),Cr=require("@mysten/sui.js/bcs"),ut=require("@mysten/sui.js/utils");var Xn=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::borrow`)}isEntryMultiDepositTransaction(){let t=`${h.ProtocolPackage}::incentive_v2::entry_deposit`,e=this.transactions.filter(a=>a.kind==="MoveCall"&&a.target===t);return this.transactions.find(a=>a.kind==="MoveCall"&&a.target===`${h.ProtocolPackage}::incentive_v2::claim_reward_non_entry`)?!1:e.length>1}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(h.pool).find(n=>n.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${h.ProtocolPackage}::incentive_v2::claim_reward`){let n=new ve(e,this.txb),a=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(a),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:a,poolId:i})}}),console.log("decode claims",t),{txType:Rt.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Rt.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryMultiDeposit(){let t=[],e=`${h.ProtocolPackage}::incentive_v2::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===e){let a=new ve(n,this.txb),r=a.decodeInputU8(3),i=a.decodeInputU64(5),s=this.findPoolByAssetId(r);t.push({coinType:s.coinType,amount:i})}}),{txType:Rt.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:t}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Rt.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:Rt.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Rt.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(h.ProtocolPackage));return new ve(t,this.txb)}},ve=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,ut.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Cr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,ut.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,ut.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,ut.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,ut.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Cr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,ut.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var zs=require("@mysten/sui.js/transactions");function Ht(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[o.object("0x06"),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Hs(o,t,e){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Ks(o,t,e,n){let a=o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.IncentiveV2)],typeArguments:[t.type]}),[r]=o.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[a]});if(h.borrowFee>0){let[i]=o.splitCoins(r,[o.pure(Math.floor(e*h.borrowFee))]);o.transferObjects([r],o.pure(n)),o.transferObjects([i],o.pure(h.borrowFeeAddress))}else o.transferObjects([r],o.pure(n));return o}function kr(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Gs(o,t,e,n,a){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[o.object("0x06"),o.object(h.IncentiveV2),o.object(e),o.object(h.StorageId),o.pure(t),o.pure(n)],typeArguments:a}),o}var Yn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new zs.TransactionBlock;return e.forEach(a=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=a;Gs(n,r,i,s,c)}),n}static fromData(e){return new o(e)}};var Js=require("@mysten/sui.js/transactions");var Zn=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:a}=this.data,r=new Js.TransactionBlock;console.log("build",this.data);let i=h.pool[n];if(!i)throw new Error(`${n} not support, please use ${Object.keys(h.pool).join(", ")}.`);return Ks(r,i,a,e.account.address)}static fromData(e){return new o(e)}};var Xs=require("@mysten/sui.js/transactions");async function Kt(o,t,e){let n=await o.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var to=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new Xs.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Ht(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await Kt(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return Ht(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var Ys=require("@mysten/sui.js/transactions");var eo=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new Ys.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return kr(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await Kt(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return kr(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var Zs=require("@mysten/sui.js/transactions");var no=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,a=new Zs.TransactionBlock;console.log("build",this.data);let r=h.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return Hs(a,r,n)}static fromData(e){return new o(e)}};var tc=require("@mysten/sui.js/transactions");var oo=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{list:r}=this.data,i=new tc.TransactionBlock;console.log("build",this.data);for(let s=0;s<r.length;s++){let{coinType:c,amount:l}=r[s];if(c==="sui"){let[m]=i.splitCoins(i.gas,[l]);Ht(i,h.pool.sui,m,l);continue}let d=h.pool[c];if(!d)throw new Error(`${c} not support, please use ${Object.keys(h.pool).join(", ")}.`);let u=await Kt(n,a.address,d.type);if(!u.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let p=u.data[0].coinObjectId;if(u.data.length>=2){let m=1;for(;m<u.data.length;)i.mergeCoins(p,[u.data[s].coinObjectId]),m++}Ht(i,d,i.object(p),l)}return i}static fromData(e){return new o(e)}};var ao=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await Ir();let{transactionBlock:e}=t,a=new Xn(e).decode();return{txType:ec.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(await Ir(),t.txSubType){case"EntryDeposit":a=to.fromData(t.intentionData);break;case"EntryBorrow":a=Zn.fromData(t.intentionData);break;case"EntryRepay":a=eo.fromData(t.intentionData);break;case"EntryWithdraw":a=no.fromData(t.intentionData);break;case"EntryMultiDeposit":a=oo.fromData(t.intentionData);break;case"ClaimReward":a=Yn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var De=require("@msafe/sui3-utils"),io=require("@mysten/bcs"),nc=require("@mysten/sui/transactions"),oc=B(require("sort-keys-recursive")),ac="msafe-plain-tx",rc=De.TransactionSubTypes.others.plain,xr=class o{constructor(t){this.data=t}application=ac;txType=De.TransactionType.Other;txSubType=rc;serialize(){return JSON.stringify((0,oc.default)(this.data))}async build(t){return nc.Transaction.from((0,io.fromHEX)(this.data.content))}static fromData(t){return new o(t)}},ro=class{application;supportSDK="@mysten/sui";constructor(){this.application=ac}async deserialize(t){let{transaction:e}=t,n=await e.build({client:t.suiClient});return{txType:De.TransactionType.Other,txSubType:rc,intentionData:{content:(0,io.toHEX)(n)}}}async build(t){let{account:e}=t,a=await xr.fromData(t.intentionData).build({suiClient:t.suiClient,network:t.network,account:t.account}),i=await t.suiClient.devInspectTransactionBlock({transactionBlock:a,sender:e.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return a}};var vr=require("@mysten/sui/client"),ic=require("@mysten/sui/transactions"),so=require("@mysten/sui.js/client"),sc=require("@mysten/sui.js/transactions"),co=class o{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new o;for(let n=0;n<t.length;n++){let a=t[n];switch(a.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(a);break;case"@mysten/sui":e.addHelper(a);break;default:throw new Error(`${a.application}: ${a.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new Ar(t))}addHelper(t){this.apps.set(t.application,new Dr(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},Dr=class{constructor(t){this.helper=t}async deserialize(t){let e=new vr.SuiClient({url:t.clientUrl}),n=new so.SuiClient({url:t.clientUrl}),a=await t.transactionBlock.build({client:n}),r=ic.Transaction.from(a);return this.helper.deserialize({...t,suiClient:e,transaction:r})}async build(t){let e=new vr.SuiClient({url:t.clientUrl}),n=await this.helper.build({...t,suiClient:e});n.setSender(t.account.address);let a=await n.build({client:e});return sc.TransactionBlock.from(a)}},Ar=class{constructor(t){this.helper=t}async deserialize(t){let e=new so.SuiClient({url:t.clientUrl});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new so.SuiClient({url:t.clientUrl});return this.helper.build({...t,suiClient:e})}};var Jc=require("@msafe/sui3-utils");var A=require("@msafe/sui3-utils");var pt=class{constructor(t,e){this.txb=t;this.scallop=e}scallop;get coreId(){return{protocolPkg:this.scallop.address.get("core.packages.protocol.id"),market:this.scallop.address.get("core.market"),version:this.scallop.address.get("core.version"),coinDecimalsRegistry:this.scallop.address.get("core.coinDecimalsRegistry"),xOracle:this.scallop.address.get("core.oracles.xOracle"),spoolPkg:this.scallop.address.get("spool.id"),borrowIncentivePkg:this.scallop.address.get("borrowIncentive.id"),veScaPkgId:this.scallop.address.get("vesca.id"),scoin:this.scallop.address.get("scoin.id"),referral:this.scallop.address.get("referral.id")}}get transactions(){return this.txb.blockData.transactions}get inputTransaction(){return this.txb.blockData.inputs}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}};var cc="https://sui.apis.scallop.io";var lc="66f8e7ed9bb9e07fdfb86bbb",lo="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var mt="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",ft="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",Z=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],uo=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],bt=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],tt=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc"];var dc=["sui"],gt=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc"];var uc={weth:8,wbtc:8,wusdc:6,usdc:6,wusdt:6,sui:9,wapt:8,wsol:8,sca:9,cetus:9,afsui:9,hasui:9,vsui:9,sweth:8,swbtc:8,susdc:6,swusdt:6,swusdc:6,ssui:9,swapt:8,swsol:8,scetus:9,safsui:9,shasui:9,svsui:9,ssca:9};var po={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},pc={sui:["sui","sca"],wusdc:["sui","sca"],wusdt:["sui","sca"],afsui:["sui","sca"],hasui:["sui","sca"],vsui:["sui","sca"],sca:["sui","sca"],weth:["sui","sca"],wbtc:["sui","sca"],wsol:["sui","sca"],usdc:["sui","sca"]},mc={sui:"0x0000000000000000000000000000000000000000000000000000000000000002",weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",cetus:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",afsui:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",hasui:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",sca:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6",usdc:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7"},q={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Or={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},fc={ssui:"0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI",scetus:"0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS",ssca:"0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA",swusdc:"0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC",swusdt:"0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT",sweth:"0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH",safsui:"0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI",shasui:"0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI",svsui:"0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI",swbtc:"0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC",swsol:"0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL",susdc:"0x854950aa624b1df59fe64e630b2ba7c550642e9342267a33061d59fb31582da5::scallop_usdc::SCALLOP_USDC"};var Pr=require("@mysten/sui.js/bcs"),ht=require("@mysten/sui.js/utils"),w=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,ht.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}getNestedInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="NestedResult")throw new Error("not input type");return this.txb.blockData.transactions[e.index]}isHaveNestedInput(t){return this.moveCall.arguments[t].kind==="NestedResult"}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Pr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,ht.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,ht.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,ht.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,ht.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Pr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,ht.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var bc=require("@mysten/sui.js/bcs");var R=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(w.getPureInputValue(t,"u64"))}).filter(t=>t!==void 0)}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return bc.bcs.de(e,new Uint8Array(n))}return t.value}};var mo=class extends pt{decode(){if(this.isMoveAsset())return this.decodeMoveAsset();if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMoveAsset(){return!!this.getMoveCallTransaction("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage")}isMigrateScoinTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`),e=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);return!!t&&!!e}isUnstakeAndWithdrawTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`),e=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);return!!t&&!!e}isStakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`),e=!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return!!t&&!!e}isDepositCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isBorrowWithReferralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isUnstakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return!!t||!!e}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${ft}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);return!!t&&(!!e||!!n)}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperClaimBorrowV2Reward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new w(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new w(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new w(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new w(t,this.txb)}get helperBurnScoin(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new w(t,this.txb)}get helperSlippage(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage"));return new w(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new w(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new w(t,this.txb)}get helperDepositCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new w(t,this.txb)}get helperWithdrawCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new w(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new w(t,this.txb)}get helperBorrowWithReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new w(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new w(t,this.txb)}decodeMigrateScoin(){return{txType:A.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let e=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),a=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:A.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:a,veScaKey:t}}}decodeOpenObligation(){return{txType:A.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLendingScoin(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperBurnScoin.getNestedInputParam(1),n=new R(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:a,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),a=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:a,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),a=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:a,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),a=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeBorrowWithReferral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),a=this.helperBorrowWithReferral.decodeSharedObjectId(1),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeRepay(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"Repay",intentionData:{amount:n,obligationId:a,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),a=new R(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:a,obligationId:r,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);e=new R(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let r=this.helperStake.getNestedInputParam(2);e=new R(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"StakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a;return this.isCreateStakeAccountTransaction()||(a=this.helperStake.decodeOwnedObjectId(1)),{txType:A.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:a}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(a=>{let r=a.decodeOwnedObjectId(1),i=a.decodeInputU64(2);t.push({id:r,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let a=this.helperBurnScoin.getNestedInputParam(1);n=new R(a,this.txb).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:A.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeMoveAsset(){let t=[];this.helperUnstakes.forEach(i=>{let s=i.decodeOwnedObjectId(1),c=i.decodeInputU64(2);t.push({id:s,coin:c})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);n=new R(i,this.txb).getAmountInput().reduce((s,c)=>s+c,0)}let a=this.helperSlippage.decodePureArg(1,"u64"),r=this.helperSlippage.decodePureArg(2,"string");return{txType:A.TransactionType.Other,type:"MigrateWusdcToUsdc",intentionData:{amount:n,coinName:e,slippage:a,validSwapAmount:r,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(a=>{let r=a.decodeOwnedObjectId(2),i=a.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(a=>{let r=a.decodeSharedObjectId(3),i=a.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(a=>{let r=a.decodeSharedObjectId(2),i=a.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:A.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};var fo=require("@msafe/sui3-utils");var bo=class extends pt{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(e=>new w(e,this.txb))}get helperBindReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new w(t,this.txb)}decodeCreateReferralLink(){return{txType:fo.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:fo.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:fo.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};var Gt=require("@msafe/sui3-utils");var go=class extends pt{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let t=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),e=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!t&&!!e}isRedeemSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new w(t,this.txb)}get helperStakeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new w(t,this.txb)}get helperExtendStakePeriod(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new w(t,this.txb)}get helperRedeemSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new w(t,this.txb)}get helperRenewExpired(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new w(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::unstake`));return new w(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new w(t,this.txb)}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:Gt.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new R(t,this.txb).getAmountInput().reduce((f,S)=>f+S,0),a=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,u,p,m=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let f=0;f<m.length;f++)m[f].condition.length>1&&([p,u]=m[f].condition,l=!0,d=m[f].isOld);return{txType:Gt.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:a,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],a=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:a,isOld:!1},{condition:r,isOld:!1}];for(let u=0;u<d.length;u++)d[u].condition.length>1&&([l,c]=d[u].condition,i=!0,s=d[u].isOld);return{txType:Gt.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:l,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new R(t,this.txb).getAmountInput().reduce((m,f)=>m+f,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:Gt.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:d,obligationKey:u,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):t=this.helperStakeMoreSca.getNestedInputParam(4);let n=new R(t,this.txb).getAmountInput().reduce((m,f)=>m+f,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:Gt.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:d,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}};var gc=B(require("sort-keys-recursive")),g=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,gc.default)(this.data))}};var ho=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrow(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var yo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var So=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithReferral(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var wo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var To=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new o(e)}};var Io=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAndClaim(this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName,this.data.veScaKey)}static fromData(e){return new o(e)}};var Co=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new o(e)}};var ko=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateLendingWusdcToUsdcNative(this.data.coinName,Number(this.data.amount),this.data.slippage,this.data.validSwapAmount,this.data.stakeAccountId)}static fromData(e){return new o(e)}};var xo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new o(e)}};var vo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repay(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var Do=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repayWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var Ao=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var Oo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var Po=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var Ro=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new o(e)}};var _o=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var Bo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var jo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.bindReferral(this.data.veScaKey)}static fromData(e){return new o(e)}};var Eo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claimRevenuReferral(this.data.veScaKey,this.data.coins)}static fromData(e){return new o(e)}};var No=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new o(e)}};var Mo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendPeriodAndStakeMoreSca(this.data.amount,this.data.veScaKey,this.data.lockPeriodInDays,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Wo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendStakeScaLockPeriod(this.data.lockPeriodInDays,this.data.veScaKey,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Lo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.redeemSca(this.data.veScaKey)}static fromData(e){return new o(e)}};var Uo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.renewExpiredStakeSca(this.data.amount,this.data.lockPeriodInDays,this.data.vescaKey,this.data.isHaveRedeem,this.data.obligation,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var Fo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stakeSca(this.data.amount,this.data.isObligationLocked,this.data.isOldBorrowIncentive,this.data.obligationId,this.data.obligationKey,this.data.lockPeriodInDays,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var qo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.supplyAndStake(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId,e.account.address)}static fromData(e){return new o(e)}};var $o=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new o(e)}};var Vo=class{id;addresses;constructor(t){let{id:e}=t;this.id=e}getId(){return this.id}getAddresses(){return this.addresses}get(t){if(!this.addresses)throw new Error(`Failed to fetch address ${this.id}`);return t.split(".").reduce((n,a)=>typeof n=="object"?n[a]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${cc}/addresses/${this.id}`,t);if(e.status===200){let n=await e.json();if("mainnet"in n){this.addresses=n.mainnet;return}throw new Error("Mainnet key is not in address!")}throw new Error(`Failed to fetch address with id ${this.id}`)}};var C=require("@mysten/sui.js/transactions"),Fr=B(require("bignumber.js"));var hc=require("@mysten/sui.js/transactions"),Qo=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:a,utils:r}=e;this.address=n,this.query=a,this.utils=r,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new hc.TransactionBlock(t)}async selectCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,a),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[l,d]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:l,leftCoin:d,totalAmount:s}}async selectSCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[l,d]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:l,leftCoin:d,totalAmount:c}}};var yc=require("@mysten/sui.js/transactions"),Ae=B(require("bignumber.js"));var zt=async(o,t)=>{let e=t,n=o.address.get("core.object")||lo,a=[],r=!1,i=null;do{let d=await o.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});a.push(...d.data),d.hasNextPage&&d.nextCursor?(r=!0,i=d.nextCursor):r=!1}while(r);let s=a.map(d=>d?.data?.objectId).filter(d=>d!==void 0),c=await o.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),l=[];for(let d=0;d<c.length;d++){let u=c[d].data.objectId,{content:p}=c[d].data;if(p&&"fields"in p){let m=p.fields,f=String(m.ownership.fields.of),S=await _r(o,f);l.push({id:f,keyId:u,locked:S})}}return l},_r=async(o,t)=>{let e=await o.client.getObject({id:t,options:{showContent:!0}}),n=!1;return e.data&&e?.data?.content?.dataType==="moveObject"&&"lock_key"in e.data.content.fields&&(n=!!e.data.content.fields.lock_key),n},Sc=async(o,t,e)=>{let n=e||[...Z],a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,Ae.default)(c[m]??0).plus(p.balance).toNumber())}}),c},wc=async(o,t,e)=>{let n=e,a=o.utils.parseCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,Ae.default)(c).plus(u.balance).toNumber()}}),c},Tc=async(o,t,e)=>{let n=e||[...Z].map(d=>o.utils.parseMarketCoinName(d)),a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,Ae.default)(c[m]??0).plus(p.balance).toNumber())}}),c},Ic=async(o,t,e)=>{let n=e,a=o.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,Ae.default)(c).plus(u.balance).toNumber()}}),c},Cc=async(o,t)=>{let n=`${o.address.get("core.packages.query.id")}::obligation_query::obligation_data`,a=new yc.TransactionBlock;return a.moveCall({target:n,arguments:[a.object(t)]}),(await o.client.devInspectTransactionBlock({transactionBlock:a,sender:o.params.walletAddress})).events[0].parsedJson};var T=require("@mysten/sui.js/utils"),Oe=async(o,t)=>{let e=t,n=o.address.get("spool.object"),a=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let p=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},options:{showContent:!0,showType:!0},cursor:s});r.push(...p.data),p.hasNextPage&&p.nextCursor?(i=!0,s=p.nextCursor):i=!1}while(i);let c={sweth:[],ssui:[],susdc:[],swusdc:[],swusdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},l=Object.keys(c).reduce((p,m)=>{let f=o.utils.parseCoinName(m),S=o.utils.parseMarketCoinType(f),I={...p},v=`${n}::spool_account::SpoolAccount<${S}>`;return I[m]=v,I},{}),d=r.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await o.client.multiGetObjects({ids:d,options:{showContent:!0,showType:!0}})).forEach(p=>{let m=p.data.objectId,f=p.data.type;if(p.data.content&&"fields"in p.data.content){let S=p.data.content.fields,I=String(S.spool_id),v=String(S.stake_type.fields.name),U=Number(S.stakes),_=Number(S.index),V=Number(S.points),F=Number(S.total_points);(0,T.normalizeStructTag)(f)===l.sweth?c.sweth.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.ssui?c.ssui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.swusdc?c.swusdc.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.swusdt?c.swusdt.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.scetus?c.scetus.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.safsui?c.safsui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.shasui?c.shasui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.svsui?c.svsui.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F}):(0,T.normalizeStructTag)(f)===l.susdc&&c.susdc.push({id:m,type:(0,T.normalizeStructTag)(f),stakePoolId:I,stakeType:(0,T.normalizeStructTag)(v),staked:U,index:_,points:V,totalPoints:F})}}),c},Br=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.id`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=Number(c.max_distributed_point),d=Number(c.distributed_point),u=Number(c.distributed_point_per_period),p=Number(c.point_distribution_time),m=Number(c.max_stakes),f=String(c.stake_type.fields.name),S=Number(c.stakes),I=Number(c.index),v=Number(c.created_at),U=Number(c.last_update);n={id:i,type:(0,T.normalizeStructTag)(s),maxPoint:l,distributedPoint:d,pointPerPeriod:u,period:p,maxStake:m,stakeType:(0,T.normalizeStructTag)(f),totalStaked:S,index:I,createdAt:v,lastUpdate:U}}}return n},jr=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.rewardPoolId`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=String(c.spool_id),d=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:(0,T.normalizeStructTag)(s),stakePoolId:l,ratioNumerator:d,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};var _c=require("@mysten/sui.js/transactions"),eu=require("@mysten/sui.js/utils"),nu=B(require("bignumber.js"));var N=o=>{let{sender:t}=o.blockData;if(!t)throw new Error("Sender is required");return t},vc=(o,t,e,n)=>{let a=!n,r=!a&&n*1e3<=new Date().getTime();if(a||r)if(o!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof o=="number"&&o<1e10)throw new Error(`Minimum lock amount for ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if(Jt(n),typeof o=="number"&&o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(e&&n&&e-n>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)}},Dc=(o,t,e)=>{if(Jt(e),o<=0)throw new Error("Lock period must be greater than 0");if(!!e&&e*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");if(e&&t-(e??0)>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},Ac=(o,t)=>{if(Jt(t),o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(!!t&&t*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead")},Oc=(o,t,e)=>{if(Jt(e),o<1e10)throw new Error("Minimum lock amount for renewing expired vesca 10 SCA");if(t*86400>=126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},Jt=o=>{if(o===void 0)throw new Error("veSca not found")};var Pe=require("@mysten/sui.js/utils"),Zd=B(require("bignumber.js"));var tu=o=>({pointType:(0,Pe.normalizeStructTag)(o.point_type.name),weightedAmount:Number(o.weighted_amount),points:Number(o.points),totalPoints:Number(o.total_points),index:Number(o.index)}),Pc=o=>({poolType:(0,Pe.normalizeStructTag)(o.pool_type.name),debtAmount:Number(o.debt_amount),pointList:o.points_list.reduce((t,e)=>{let n=tu(e),a=(0,Pe.parseStructTag)(n.pointType).name.toLowerCase();return t[a]=n,t},{})});var Ko=o=>{let t=o.slice(1).toLowerCase();return o.charAt(0).toLowerCase()==="s"&&[...new Set([...Z,...uo,...dc])].includes(t)},Er=o=>{switch(o){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return o.toUpperCase()}},Rc=o=>{let t=new Date(o*1e3),e=new Date(o*1e3);e.setUTCHours(0,0,0,0),t.getUTCHours()>=0&&e.setUTCDate(e.getUTCDate()+1);let n=new Date().getTime();return e.getTime()-n>126144e3*1e3&&e.setUTCDate(e.getUTCDate()-1),Math.floor(e.getTime()/1e3)};var Bc=async(o,t,e,n)=>{let a=n||[...gt],r=o.address.get("borrowIncentive.query"),i=o.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new _c.TransactionBlock;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let d=(await o.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return d.pool_records.forEach(p=>{let m=Pc(p),{poolType:f}=m,S=o.utils.parseCoinNameFromType(f);a.length>=1&&a.includes(S)&&(u[S]=m)},{}),u};var jc=async({address:o,client:t},e)=>{let n=o.get("borrowIncentive.object"),a=o.get("borrowIncentive.incentiveAccounts"),r=o.get("core.object"),i=await t.getObject({id:a,options:{showContent:!0}});if(i?.data?.content?.dataType!=="moveObject")return null;let s=i.data.content.fields.accounts.fields.id.id,c=await t.getDynamicFieldObject({parentId:s,name:{type:`${n}::typed_id::TypedID<${r}::obligation::Obligation>`,value:e}});return c?.data?.content?.dataType!=="moveObject"?null:c.data.content.fields.value.fields.binded_ve_sca_key?.fields.id??null};var Ec=async(o,t)=>{let e=o.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await o.client.getObject({id:e,options:{showContent:!0}});if(n.data){let a=n.data;if(a.content&&"fields"in a.content){let r=a.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),l=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(l?-1:1)}}return 0};var Go=B(require("bignumber.js")),Nc=async(o,t)=>{let e=t,a=`${o.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let l=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);return r.map(l=>l.data).filter(l=>!!l)},Mc=async(o,t)=>{let n=(await Nc(o,t)).map(r=>r.objectId),a=[];for(let r=0;r<n.length;r++){let i=await Nr(o,n[r]);i&&a.push(i)}return a},Nr=async(o,t,e)=>{let n=o.address.get("vesca.tableId"),a=t||(await Nc(o,e))[0].objectId,r,s=(await o.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:a}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:a,lockedScaAmount:(0,Go.default)(c.locked_sca_amount).toNumber(),lockedScaCoin:(0,Go.default)(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:(0,Go.default)(c.unlock_at).toNumber()}}return r};var zo=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:a}=e;this.address=n,this.utils=a}async getObligations(t=this.params.walletAddress){return zt(this,t)}async getCoinAmounts(t,e){return Sc(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return wc(this,t,e)}async getMarketCoinAmounts(t,e){return Tc(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return Ic(this,t,e)}async getPriceFromPyth(t){return Ec(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return Oe(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let a=t[n],r=await Br(this,a);r&&(e[a]=r)}return e}async getStakePool(t){return Br(this,t)}async getStakeRewardPools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let a=await jr(this,t[n]);a&&(e[t[n]]=a)}return e}async getStakeRewardPool(t){return jr(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return Bc(this,t,e,n)}async getObligationCoinNames(t){let e=await Cc(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),a=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...a])].map(s=>this.utils.parseCoinNameFromType(s))}};var Xt=require("@mysten/sui.js/utils");var Jo=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Ko(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Er(e)}return Er(t)}parseCoinType(t){let e=Ko(t)?this.parseCoinName(t):t,n=mc[e];return[q.wusdc,q.wusdt,q.weth,q.wbtc,q.wsol,q.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Or.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||lo,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=(0,Xt.normalizeStructTag)(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,a=t.match(n),r=t.includes("reserve::MarketCoin");e=a?.[1]||t;let i={[`${q.wusdc}::coin::COIN`]:"wusdc",[`${q.wusdt}::coin::COIN`]:"wusdt",[`${q.weth}::coin::COIN`]:"weth",[`${q.wbtc}::coin::COIN`]:"wbtc",[`${q.wsol}::coin::COIN`]:"wsol",[`${q.wapt}::coin::COIN`]:"wapt"},s={[`${Or.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return r?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>po[t];getBorrowIncentiveRewardCoinName=t=>pc[t];getCoinDecimal(t){return uc[t]}getCoinWrappedType(t){return t==="wusdc"||t==="wusdt"||t==="weth"||t==="wbtc"||t==="wapt"||t==="wsol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}parseSCoinType(t){return fc[t]}parseUnderlyingSCoinType(t){let e=this.parseCoinName(t);return this.parseCoinType(e)}getSCoinTreasury(t){return this._address.get(`scoin.coins.${t}.treasury`)}async selectCoins(t,e=Xt.SUI_TYPE_ARG,n){let a=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let l=await this.client.getCoins({owner:a,coinType:e,cursor:c});l.data.sort((d,u)=>parseInt(u.balance,10)-parseInt(d.balance,10));for(let d=0;d<l.data.length&&(r.push({objectId:l.data[d].coinObjectId,digest:l.data[d].digest,version:l.data[d].version,balance:l.data[d].balance}),i+=parseInt(l.data[d].balance,10),!(i>=t));d++);c=l.nextCursor,s=l.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r}async selectCoinsMarketCoin(t=Xt.SUI_TYPE_ARG,e){let n=e,a=[],r=!0,i=null;for(;r;){let s=await this.client.getCoins({owner:n,coinType:t,cursor:i});s.data.sort((c,l)=>parseInt(l.balance,10)-parseInt(c.balance,10));for(let c=0;c<s.data.length&&(a.push({objectId:s.data[c].coinObjectId,digest:s.data[c].digest,version:s.data[c].version,balance:s.data[c].balance}),!(a.length>50));c++);i=s.nextCursor,r=s.hasNextPage}return a}async selectCoinIds(t,e=Xt.SUI_TYPE_ARG,n){return(await this.selectCoins(t,e,n)).map(r=>r.objectId)}parseAprToApy(t,e=365){return(1+t/e)**e-1}parseApyToApr(t,e=365){return((1+t)**(1/e)-1)*e}takeAmountFromCoins(t,e,n){let a=e.map(s=>t.object(s)),r=a[0];a.length>1&&t.mergeCoins(r,a.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),a=e?Math.max(e-n,0):0,r=0;if(a===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+a:a,126144e3);r=n+i}return Rc(r)}parseSCoinName(t){if(Ko(t)&&tt.includes(t))return t;let e=`s${t}`;if(tt.includes(e))return e}};var nt=require("@mysten/sui.js/utils");var Yt=async(...o)=>{let[t,e,n]=o;if(o.length===3&&n&&typeof n=="string"){let i=await Nr(t.query,n);return i||void 0}let a=N(e),r=await Mc(t.query,a);if(r.length!==0)return r[0]};var Mr=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&n&&a&&typeof n=="string"){let c=await _r(t.query,n);return{obligationId:n,obligationKey:a,obligationLocked:c}}let r=N(e),i=await zt(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);let s=i.find(c=>c.id===n||c.keyId===a)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},ou=async({builder:o,txBlock:t})=>{let e={borrowIncentivePkg:o.address.get("borrowIncentive.id"),query:o.address.get("borrowIncentive.query"),incentivePools:o.address.get("borrowIncentive.incentivePools"),incentiveAccounts:o.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:o.address.get("core.obligationAccessStore"),config:o.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},a={table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(a.config),t.object(a.treasury),t.object(a.table),t.object(s),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[nt.SUI_TYPE_ARG]})},claimBorrowIncentive:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.borrowIncentivePkg}::user::redeem_rewards`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},oldClaimBorrowIncentive(r,i,s){let c=o.utils.parseCoinType(s);return t.moveCall({target:`${n.id}::user::redeem_rewards`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(nt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})}}},M=async({builder:o,txBlock:t})=>{let e=await ou({builder:o,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Mr(o,t,n,a),c=!!t.blockData.transactions.find(l=>l.kind==="MoveCall"&&(l.target===`${ft}::user::unstake`||l.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Mr(o,t,n,a);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,a,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await Mr(o,t,n,a),l=!!t.blockData.transactions.find(async d=>d.kind==="MoveCall"&&(d.target===`${ft}::user::unstake`||d.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));if(!c||l){let d=await jc({address:o.address,client:o.client},i);if(r&&r!==d)throw new Error("Binded veScaKey is not equal to the provided veScaKey");d?e.stakeObligationWithVesca(i,s,d):e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,a,r)=>e.claimBorrowIncentive(a,r,n)}};var X=require("@mysten/sui.js/utils");var _e=require("@mysten/sui.js/utils"),Lc=B(require("axios"));var Wc={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};var Xo=require("@mysten/sui.js/bcs"),Re=require("@mysten/sui.js/utils"),Wr=16*1024,Yo=class{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(t,e,n){this.provider=t,this.pythStateId=e,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!t.data||!t.data.content||t.data.content.dataType!=="moveObject")throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=t.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}}).then(n=>{if(n.data?.content?.dataType==="moveObject")return n.data.content.fields;throw new Error(`Cannot fetch package id for object ${t}`)});if("upgrade_cap"in e)return e.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(t,e){let n=await this.getWormholePackageId(),a=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(Xo.bcs.ser("vector<u8>",Array.from(r),{maxSize:Wr}).toBytes()),e.object(Re.SUI_CLOCK_OBJECT_ID)]});a.push(i)}),a}async updatePriceFeeds(t,e,n){let a=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${a}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Xo.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:Wr}).toBytes()),s[0],t.object(Re.SUI_CLOCK_OBJECT_ID)]});let c=[],l=await this.getBaseUpdateFee(),d=t.splitCoins(t.gas,n.map(()=>t.pure(l))),u=0;for(let p=0;p<n.length;p++){let m=await this.getPriceFeedObjectId(n[p]);if(!m)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(m),[r]=t.moveCall({target:`${a}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(m),d[u],t.object(Re.SUI_CLOCK_OBJECT_ID)]}),u++}return t.moveCall({target:`${a}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${a}::price_info::PriceInfo`]}),c}async createPriceFeed(t,e){let n=await this.getPythPackageId();if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let a=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([a],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Xo.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:Wr}).toBytes()),r[0],t.object(Re.SUI_CLOCK_OBJECT_ID)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(t){let e=t.replace("0x","");if(!this.priceFeedObjectIdCache.has(e)){let{id:n,fieldType:a}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${a}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,a=t.readUint16BE(n),r=n+2;return t.subarray(r,r+a)}};var au=async(o,t)=>(await Lc.default.get(`${o}/api/latest_vaas`,{params:{ids:t}})).data.map(a=>Buffer.from(a,"base64")),Be=async(o,t,e)=>{let n=e??[...new Set([...Z,...uo])],a=o.isTestnet?["pyth"]:["pyth"];if(a.includes("pyth")){let i=new Yo(o.client,o.address.get("core.oracles.pyth.state"),o.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async l=>s.push(o.address.get(`core.coins.${l}.oracle.pyth.feed`))));let c=o.params.pythEndpoints??Wc[o.isTestnet?"testnet":"mainnet"];try{let l=await au(c[0],s);await i.updatePriceFeeds(t,l,s)}catch(l){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${l}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await ru(o,t,r[i],a)},ru=async(o,t,e,n)=>{let a=o.utils.parseCoinType(e);iu(t,n,o.address.get("core.packages.xOracle.id"),o.address.get("core.oracles.xOracle"),o.address.get("core.packages.pyth.id"),o.address.get("core.oracles.pyth.registry"),o.address.get("core.oracles.pyth.state"),o.address.get(`core.coins.${e}.oracle.pyth.feedObject`),o.address.get("core.packages.switchboard.id"),o.address.get("core.oracles.switchboard.registry"),o.address.get(`core.coins.${e}.oracle.switchboard`),o.address.get("core.packages.supra.id"),o.address.get("core.oracles.supra.registry"),o.address.get("core.oracles.supra.holder"),a)},iu=(o,t,e,n,a,r,i,s,c,l,d,u,p,m,f)=>{let S=su(o,e,n,f);return t.includes("pyth")&&uu(o,a,S,i,s,r,f),t.includes("switchboard")&&du(o,c,S,d,l,f),t.includes("supra")&&lu(o,u,S,m,p,f),cu(o,e,n,S,f),o},su=(o,t,e,n)=>{let a=typeof e=="string"?o.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return o.moveCall({target:r,arguments:[a],typeArguments:i})},cu=(o,t,e,n,a)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[a],s=typeof e=="string"?o.object(e):e;return o.moveCall({target:r,arguments:[s,n,o.object(_e.SUI_CLOCK_OBJECT_ID)],typeArguments:i}),o},lu=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(_e.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},du=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(_e.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},uu=(o,t,e,n,a,r,i)=>{let s=typeof e=="string"?o.object(e):e,c=typeof n=="string"?o.object(n):n,l=typeof a=="string"?o.object(a):a,d=typeof r=="string"?o.object(r):r;o.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,l,d,o.object(_e.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})};var St=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("scoin.id")},n={};return await Promise.all(tt.map(async a=>{let r=o.utils.getSCoinTreasury(a);n[a]=r})),{mintSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]}),burnSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]})}};var je=async(...o)=>{let[t,e,n,a]=o;if(o.length===3&&n)return{obligationId:n};if(o.length===4&&n&&a)return{obligationId:n,obligationKey:a};let r=N(t),i=await zt(e.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},pu=async({builder:o,txBlock:t})=>{let e={protocolPkg:o.address.get("core.packages.protocol.id"),market:o.address.get("core.market"),version:o.address.get("core.version"),coinDecimalsRegistry:o.address.get("core.coinDecimalsRegistry"),xOracle:o.address.get("core.oracles.xOracle")},a=`${o.address.get("referral.id")}::scallop_referral_program::REFERRAL_WITNESS`;return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.object(e.version)]}),returnObligation:(r,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(r),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},deposit:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},depositEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdraw:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdrawEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},borrow:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowEntry:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowWithReferral:(r,i,s,c,l)=>{let d=o.utils.parseCoinType(l);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,a]})},repay:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(X.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},borrowFlashLoan:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r)],typeArguments:[s]})},repayFlashLoan:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r),t.object(i)],typeArguments:[c]})}}},W=async({builder:o,txBlock:t})=>{let e=await pu({builder:o,txBlock:t}),n=await St({builder:o,txBlock:t});return{normalMethod:e,addCollateralQuick:async(a,r,i)=>{let s=N(t),{obligationId:c}=await je(t,o,i);if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);e.addCollateral(c,l,r)}else{let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);e.addCollateral(c,d,r),t.transferObjects([l],s)}},takeCollateralQuick:async(a,r,i,s)=>{let c=await je(t,o,i,s),l=await o.query.getObligationCoinNames(c.obligationId);return await Be(o,t,l),e.takeCollateral(c.obligationId,c.obligationKey,a,r)},depositQuick:async(a,r,i)=>{if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);return e.deposit(l,r)}let{leftCoin:s,takeCoin:c}=await o.selectCoin(t,r,a,i);return t.transferObjects([s],i),e.deposit(c,r)},withdrawQuick:async(a,r)=>{let i=N(t),s=o.utils.parseMarketCoinName(r);try{let c=o.utils.parseSCoinName(r);if(!c)throw new Error(`No sCoin for ${r}`);let{leftCoin:l,takeCoin:d,totalAmount:u}=await o.selectSCoin(t,c,a,i);t.transferObjects([l],i);let p=n.burnSCoin(c,d),m=e.withdraw(p,r),f=a-u;try{if(f>0){let{leftCoin:S,takeCoin:I}=await o.selectMarketCoin(t,s,f,i);t.transferObjects([S],i),t.mergeCoins(m,[e.withdraw(I,r)])}}catch{}return m}catch{let{leftCoin:l,takeCoin:d}=await o.selectMarketCoin(t,s,a,i);return t.transferObjects([l],i),e.withdraw(d,r)}},borrowQuick:async(a,r,i,s)=>{let c=await je(t,o,i,s),d=[...await o.query.getObligationCoinNames(c.obligationId),r];return await Be(o,t,d),e.borrow(c.obligationId,c.obligationKey,a,r)},borrowWithReferralQuick:async(a,r,i,s,c)=>{let l=await je(t,o,s,c),u=[...await o.query.getObligationCoinNames(l.obligationId),r];return await Be(o,t,u),e.borrowWithReferral(l.obligationId,l.obligationKey,i,a,r)},repayQuick:async(a,r,i,s)=>{let c=await je(t,o,i);if(r==="sui"){let[u]=t.splitCoins(t.gas,[a]);return e.repay(c.obligationId,u,r)}let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);return t.transferObjects([l],s),e.repay(c.obligationId,d,r)},updateAssetPricesQuick:async a=>Be(o,t,a)}};var Ee=require("@mysten/sui.js/utils");var Zo=async({builder:o,txBlock:t})=>{let e={referralPgkId:o.address.get("referral.id"),referralBindings:o.address.get("referral.referralBindings"),referralRevenuePool:o.address.get("referral.referralRevenuePool"),authorizedWitnessList:o.address.get("referral.authorizedWitnessList"),referralTiers:o.address.get("referral.referralTiers"),version:o.address.get("referral.version")},n=o.address.get("vesca.table");return{bindToReferral:a=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(a),t.object(n),t.object(Ee.SUI_CLOCK_OBJECT_ID)],typeArguments:[]}),claimReferralTicket:a=>{let r=o.utils.parseCoinType(a);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(n),t.object(e.referralBindings),t.object(e.authorizedWitnessList),t.object(e.referralTiers),t.object(Ee.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},burnReferralTicket:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(a),t.object(e.referralRevenuePool),t.object(Ee.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})},claimReferralRevenue:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,arguments:[t.object(e.version),t.object(e.referralRevenuePool),t.object(a),t.object(Ee.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})}}},Uc=async({builder:o,txBlock:t})=>{let e=await Zo({builder:o,txBlock:t});return{claimReferralRevenueQuick:async(n,a,r=[...Z])=>{let i=[];for(let s=0;s<r.length;s++)if(r[s]==="sui"){let c=e.claimReferralRevenue(n,r[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,r[s]);try{let l=await o.utils.selectCoinIds(1/0,o.utils.parseCoinType(r[s]),a);t.mergeCoins(c,l.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(a))}}};var mu={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},Fc={check_slippage:(o,t,e,n,a)=>o.moveCall({target:`${mu.packageId}::slippage_check::check_slippage`,arguments:[t,o.pure(e),o.pure(n)],typeArguments:[a]})};var Ne=require("@mysten/sui.js/utils");var qc=async(o,t,e,n,a,r,i=!1)=>{let s=await St({builder:o,txBlock:t}),c=await Vc({builder:o,txBlock:t});try{let{takeCoin:l,leftCoin:d,totalAmount:u}=i?await o.selectSCoin(t,n,a,r):await o.selectMarketCoin(t,n,a,r);if(i){let p=s.burnSCoin(n,l);c.stake(e,p,n)}else c.stake(e,l,n);return t.transferObjects([d],r),u}catch{return 0}},$c=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&a)return[a];let r=N(e);return(await Oe(t.query,r))[n].map(s=>s.id)},fu=async(...o)=>{let[t,e,n,a]=o,r=N(e),i=await Oe(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return a?i[n].filter(c=>c.id===a):i[n]},Vc=async({builder:o,txBlock:t})=>{let e={spoolPkg:o.address.get("spool.id")},n={},a={},r={};return bt.forEach(i=>{let s=o.address.get(`spool.pools.${i}.id`),c=o.address.get(`spool.pools.${i}.rewardPoolId`),l=o.utils.parseMarketCoinType(i);n[i]=s,a[i]=c,r[i]=l}),{createStakeAccount:i=>{let s=r[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(Ne.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},stake:(i,s,c)=>{let l=r[c],d=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(d),t.object(i),typeof s=="string"?t.pure(s):s,t.object(Ne.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},unstake:(i,s,c)=>{let l=r[c],d=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(d),t.object(i),t.pure(s),t.object(Ne.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},claim:(i,s)=>{let c=n[s],l=a[s],d=r[s],u=po[s],p=o.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(l),t.object(i),t.object(Ne.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,p]})}}},ot=async({builder:o,txBlock:t})=>{let e=await Vc({builder:o,txBlock:t}),n=await St({builder:o,txBlock:t});return{normalMethod:e,stakeQuick:async(a,r,i)=>{let s=N(t),c=await $c(o,t,r,i),l=[];if(c.length===0){let d=e.createStakeAccount(r);l.push(d)}if(typeof a=="number"){let d=await qc(o,t,c.length>0?c[0]:l[0],r,a,s);a-=d,d||await qc(o,t,c.length>0?c[0]:l[0],r,a,s,!0)}else e.stake(c.length>0?c[0]:l[0],a,r);l.length>0&&t.transferObjects(l,s)},unstakeQuick:async(a,r,i,s)=>{let c=await fu(o,t,r,i),l=[],d=a;for(let u of c){if(u.staked===0)continue;let p=Math.min(d,u.staked),m=e.unstake(u.id,p,r);if(s){let f=n.mintSCoin(r,m);l.push(f)}else l.push(m);if(d-=p,a<=0)break}if(l.length>0){let u=l[0];return l.length>1&&t.mergeCoins(u,l.slice(1)),u}},claimQuick:async(a,r)=>{let i=await $c(o,t,a,r),s=[];return i.forEach(c=>{let l=e.claim(c,a);s.push(l)}),s}}};var Zt=require("@mysten/sui.js/utils");var bu=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("vesca.id"),table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{lockSca:(n,a)=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_key`,arguments:[t.object(e.config),t.object(e.table),t.object(e.treasury),typeof n=="string"?t.pure(n):n,t.pure(a),t.object(Zt.SUI_CLOCK_OBJECT_ID)]}),extendLockPeriod:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::extend_lock_period`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.pure(a),t.object(Zt.SUI_CLOCK_OBJECT_ID)]})},extendLockAmount:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::lock_more_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.object(Zt.SUI_CLOCK_OBJECT_ID)]})},renewExpiredVeSca:(n,a,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.pure(r),t.object(Zt.SUI_CLOCK_OBJECT_ID)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(Zt.SUI_CLOCK_OBJECT_ID)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},wt=async({builder:o,txBlock:t})=>{let e=await bu({builder:o,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,a,r=!0)=>{let i=N(t),s=await Yt(o,t),c,l=[];if(n!==void 0&&typeof n=="number"){let m=await o.utils.selectCoinIds(n,mt,i),[f,S]=o.utils.takeAmountFromCoins(t,m,n);c=f,l.push(S)}else c=n;let d=o.utils.getUnlockAt(a,s?.unlockAt);r&&vc(n,a,d,s?.unlockAt),console.log(new Date(d*1e3).toLocaleString("en-CA",{hour12:!0}));let u=!s?.unlockAt,p=!u&&s.unlockAt*1e3<=new Date().getTime();if(u||p){if(c)if(u){let m=e.lockSca(c,d);l.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);l.push(m)}e.renewExpiredVeSca(s.keyId,c,d)}}else c&&a?(e.extendLockPeriod(s.keyId,d),e.extendLockAmount(s.keyId,c)):a?e.extendLockPeriod(s.keyId,d):c&&e.extendLockAmount(s.keyId,c);l.length>0&&t.transferObjects(l,i)},extendLockPeriodQuick:async(n,a,r=!0)=>{let i=await Yt(o,t,a),s=o.utils.getUnlockAt(n);r&&Dc(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,a,r=!0)=>{let i=N(t),s=await Yt(o,t,a);if(r&&Ac(n,s?.unlockAt),s){let c=await o.utils.selectCoinIds(n,mt,i),[l,d]=o.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,l),t.transferObjects([d],i)}},renewExpiredVeScaQuick:async(n,a,r,i=!0)=>{let s=N(t),c=await Yt(o,t,r),l=o.utils.getUnlockAt(a,c?.unlockAt);if(i&&Oc(n,a,c?.unlockAt),c){let d=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);d.push(f)}let u=await o.utils.selectCoinIds(n,mt,s),[p,m]=o.utils.takeAmountFromCoins(t,u,n);d.push(m),e.renewExpiredVeSca(c.keyId,p,l),t.transferObjects(d,s)}},redeemScaQuick:async n=>{let a=N(t),r=await Yt(o,t,n);if(Jt(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],a)}}}};var zc=require("@mysten/sui.js/utils");var Gc=require("@mysten/sui.js/utils");var te={id:"0x000000000000000000000000000000000000000000000000000000000000dee9",pools:{sui2usdc:{object:{objectId:"0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33",initialSharedVersion:"32079148",mutable:!0},lotsize:1e8},usdt2usdc:{object:{objectId:"0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238",initialSharedVersion:"32079148",mutable:!0},lotsize:1e5},wusdc2usdc:{object:{objectId:"0x39f2f7c126189b9b5cda6b770ab34031dde22307d19842e95ab576873c77fa14",initialSharedVersion:"82838334",mutable:!0},lotsize:1e5}}},Qc={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},Lr={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},Hc={clob_v2:{swap_exact_quote_for_base:"clob_v2::swap_exact_quote_for_base",swap_exact_base_for_quote:"clob_v2::swap_exact_base_for_quote",create_account:"clob_v2::create_account"}};var Kc={objectId:Gc.SUI_CLOCK_OBJECT_ID,initialSharedVersion:"1",mutable:!1},gu=(o,t)=>{if(o==="sui")switch(t){case"wusdc":return{pool:te.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdc")switch(t){case"sui":return{pool:te.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:te.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:te.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdt")switch(t){case"wusdc":return{pool:te.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else throw new Error(`Invalid coin pair: ${o} and ${t}`)},Ur={createAccount:o=>o.moveCall({target:`${Qc.id}::${Hc.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(o,t,e,n,a,r,i)=>{let{pool:s,aToB:c}=gu(e,n),l=i.parseCoinType(e),d=i.parseCoinType(n),u=typeof r=="string"?o.object(r):"objectId"in r?o.objectRef(r):o.object(r);if(!s)throw new Error(`Deepbook: No pool found for ${e} to ${n}`);return c?o.moveCall({target:`${Lr.id}::deepbook::deepbook_base_for_quote`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.object(t),o.sharedObjectRef(Kc),o.pure(s.lotsize)],typeArguments:[l,d]}):o.moveCall({target:`${Lr.id}::deepbook::deepbook_quote_for_base`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.sharedObjectRef(Kc),o.object(t),o.pure(s.lotsize)],typeArguments:[d,l]})}};var ta=class{suiClient;scallopUtils;_clientOrderId=0;_accountCap;currentAddress;constructor({client:t,currentAddress:e,accountCap:n,scallopUtils:a}){this.currentAddress=e,this.suiClient=t,this._accountCap=n,this.scallopUtils=a}get clientOrderId(){let t=this._clientOrderId;return this._clientOrderId++,t}async accountCap(t){if(this._accountCap)return this._accountCap;try{let{data:e}=await this.suiClient.getOwnedObjects({owner:this.currentAddress,filter:{StructType:(0,zc.normalizeStructTag)("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?Ur.createAccount(t):{objectId:e[0].data.objectId,version:e[0].data.version,digest:e[0].data.digest}}catch{throw new Error("Failed to create account cap")}}async swapToken({tokenObjectIn:t,baseCoinName:e,quoteCoinName:n,tx:a}){let r=await this.accountCap(a);return{swapResult:Ur.swap(a,t,e,n,this.clientOrderId,r,this.scallopUtils),accountCap:r}}};var ea=class{params;client;address;builder;query;utils;walletAddress;deepbookSwap;constructor(t,e){this.params=t,this.client=t.client,this.address=e,this.utils=new Jo(t,this.address),this.query=new zo(t,{address:this.address,utils:this.utils}),this.builder=new Qo(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new ta({client:this.client,currentAddress:this.params.walletAddress,scallopUtils:this.utils})}async getObligations(t){let e=t||this.params.walletAddress;return this.query.getObligations(e)}async getAllStakeAccounts(t){let e=t||this.params.walletAddress;return this.query.getAllStakeAccounts(e)}async getStakeAccounts(t,e){let n=e||this.params.walletAddress;return this.query.getStakeAccounts(t,n)}async getStakePool(t){return this.query.getStakePool(t)}async getStakeRewardPool(t){return this.query.getStakeRewardPool(t)}async openObligation(t){let e=new C.TransactionBlock,n=await W({builder:this.builder,txBlock:e}),a=await M({builder:this.builder,txBlock:e}),r=t||this.params.walletAddress;e.setSender(r);let[i,s,c]=n.normalMethod.openObligation();return a.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],r),e}async depositCollateral(t,e,n,a){let r=new C.TransactionBlock,i=a||this.params.walletAddress;r.setSender(i);let s=await W({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),l=n||c?.[0]?.id;if(l)await s.addCollateralQuick(e,t,l);else{let[d,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,d),s.normalMethod.returnObligation(d,p),r.transferObjects([u],i)}return r}async withdrawCollateral(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=r||this.params.walletAddress;i.setSender(c);let l=await s.takeCollateralQuick(e,t,n,a);return i.transferObjects([l],c),i}async deposit(t,e,n){let a=new C.TransactionBlock,r=await W({builder:this.builder,txBlock:a}),i=await St({builder:this.builder,txBlock:a}),s=n||this.params.walletAddress;a.setSender(s);let c=await r.depositQuick(e,t,n),l=this.utils.parseMarketCoinName(t);if(!tt.includes(l))a.transferObjects([c],s);else{let d=i.mintSCoin(l,c);a.transferObjects([d],s)}return a}async withdraw(t,e,n){let a=new C.TransactionBlock,r=n||this.params.walletAddress,i=await W({builder:this.builder,txBlock:a});a.setSender(r);let s=await i.withdrawQuick(e,t);return a.transferObjects([s],r),a}async borrow(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await M({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);d&&await c.unstakeObligationQuick(n,a);let u=await s.borrowQuick(e,t,n,a);return i.transferObjects([u],l),d&&await c.stakeObligationQuick(n,a),i}async borrowWithBoost(t,e,n,a,r,i){let s=new C.TransactionBlock,c=await W({builder:this.builder,txBlock:s}),l=await M({builder:this.builder,txBlock:s}),d=i||this.params.walletAddress;s.setSender(d);let u=gt.includes(t);u&&await l.unstakeObligationQuick(n,a);let p=await c.borrowQuick(e,t,n,a);return s.transferObjects([p],d),u&&await l.stakeObligationWithVeScaQuick(n,a,r),s}async borrowWithReferral(t,e,n,a,r,i){let s=new C.TransactionBlock,c=await W({builder:this.builder,txBlock:s}),l=await M({builder:this.builder,txBlock:s}),d=await Zo({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=gt.includes(t);p&&await l.unstakeObligationQuick(n,a);let m=d.claimReferralTicket(t),f=await c.borrowWithReferralQuick(e,t,m,n,a);return d.burnReferralTicket(m,t),s.transferObjects([f],u),p&&r?await l.stakeObligationWithVeScaQuick(n,a,r):await l.stakeObligationQuick(n,a),s}async repay(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await M({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);return d&&await c.unstakeObligationQuick(n,a),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationQuick(n,a),i}async repayWithBoost(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await M({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=gt.includes(t);return d&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationWithVeScaQuick(n,void 0,a),i}async createStakeAccount(t,e){let n=new C.TransactionBlock,a=await ot({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;n.setSender(r);let i=a.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,a){let r=new C.TransactionBlock,i=await W({builder:this.builder,txBlock:r}),s=await ot({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l=await i.depositQuick(e,t,a),d=this.utils.parseMarketCoinName(t);if(!bt.find(m=>m===d))return r;let u=await this.query.getStakeAccounts(d,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(l,d,p);else{let m=s.normalMethod.createStakeAccount(d);await s.stakeQuick(l,d,m),r.transferObjects([m],c)}return r}async unstakeAndWithdraw(t,e,n){let a=new C.TransactionBlock,r=await W({builder:this.builder,txBlock:a}),i=await ot({builder:this.builder,txBlock:a}),s=this.params.walletAddress,c=[];a.setSender(s);let l=this.utils.parseMarketCoinName(t);for(let d=0;d<n.length;d++){let u=n[d],[p]=await i.unstakeQuick(u.coin,l,u.id);if(p){let m=r.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let d=await r.withdrawQuick(e,t);c.push(d)}return c.length>1&&a.mergeCoins(c[0],c.slice(1)),a.transferObjects(c,s),a}async stake(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),l=n||(c.length>0?c[0].id:void 0);if(l)await i.stakeQuick(e,t,l);else{let d=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,d),r.transferObjects([d],s)}return r}async unstake(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=tt.includes(t),l=await i.unstakeQuick(e,t,n,c);return r.transferObjects([l],r.pure(s)),r}async claim(t,e,n,a){let r=new C.TransactionBlock,i=await ot({builder:this.builder,txBlock:r}),s=await M({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l={sui:[],sca:[]};for(let d=0;d<t.length;d++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[d],m=i.normalMethod.claim(p,u);l.sui.push(m)}for(let d=0;d<e.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[d],f=s.normalMethod.claimBorrowIncentive(u,p,m);l[m].push(f)}for(let d=0;d<n.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[d],f=s.normalMethod.oldClaimBorrowIncentive(u,p,m);l[m].push(f)}return l.sui.length>0&&(l.sui.length>1&&r.mergeCoins(l.sui[0],l.sui.slice(1)),r.transferObjects([l.sui[0]],r.pure(c))),l.sca.length>0&&(l.sca.length>1&&r.mergeCoins(l.sca[0],l.sca.slice(1)),r.transferObjects([l.sca[0]],r.pure(c))),r}async stakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await M({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.stakeObligationQuick(t,e),a}async unstakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await M({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.unstakeObligationQuick(t,e),a}async stakeSca(t,e=!1,n=!1,a,r,i,s,c){let l=new C.TransactionBlock,d=await wt({builder:this.builder,txBlock:l}),u=await M({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[f,S]=this.builder.utils.takeAmountFromCoins(l,m,t),I;return s?d.normalMethod.extendLockAmount(s,f):I=d.normalMethod.lockSca(f,i),a&&r&&(e&&(n?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,s||I)),s||l.transferObjects([I,S],p),l}async stakeMoreSca(t,e,n){let a=new C.TransactionBlock,r=n||this.params.walletAddress;return a.setSender(r),a}async extendStakeScaLockPeriod(t,e,n,a,r=!1,i=!1,s){let c=new C.TransactionBlock,l=await wt({builder:this.builder,txBlock:c}),d=await M({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),l.normalMethod.extendLockPeriod(e,t),n&&a&&(r&&(i?d.normalMethod.oldUnstakeObligation(n,a):d.normalMethod.unstakeObligation(n,a)),d.normalMethod.stakeObligationWithVesca(n,a,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,a,r,i=!1,s=!1,c){let l=new C.TransactionBlock,d=await wt({builder:this.builder,txBlock:l}),u=await M({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[f,S]=this.builder.utils.takeAmountFromCoins(l,m,t);return d.normalMethod.extendLockPeriod(e,n),d.normalMethod.extendLockAmount(e,f),l.transferObjects([S],p),!a||!r||(i&&(s?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,e)),l}async renewExpiredStakeSca(t,e,n,a=!1,r,i,s=!1,c=!1,l){let d=new C.TransactionBlock,u=await wt({builder:this.builder,txBlock:d}),p=await M({builder:this.builder,txBlock:d}),m=l||this.params.walletAddress;if(d.setSender(m),a){let v=u.normalMethod.redeemSca(n);d.transferObjects([v],m)}let f=await this.builder.utils.selectCoinIds(t,mt,m),[S,I]=this.builder.utils.takeAmountFromCoins(d,f,t);return d.transferObjects([I],m),u.normalMethod.renewExpiredVeSca(n,S,e),!r||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(r,i):p.normalMethod.unstakeObligation(r,i)),p.normalMethod.stakeObligationWithVesca(r,i,n)),d}async redeemSca(t){let e=new C.TransactionBlock,n=await wt({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,a){let r=new C.TransactionBlock,i=await M({builder:this.builder,txBlock:r}),s=this.params.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return r.transferObjects([c],s),await i.unstakeObligationQuick(e,t),a?await i.stakeObligationWithVeScaQuick(e,t,a):await i.stakeObligationQuick(e,t),r}async withdrawUnlockedSca(t,e){let n=new C.TransactionBlock,a=await wt({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;return n.setSender(r),await a.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new Fr.default(t.weightedAmount),r=e.currentPointIndex?(0,Fr.default)(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new C.TransactionBlock,e=await wt({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let a=e.normalMethod.mintEmptyVeSca();return t.transferObjects([a],n),t}async claimRevenuReferral(t,e){let n=new C.TransactionBlock,a=await Uc({builder:this.builder,txBlock:n}),r=this.params.walletAddress;n.setSender(r);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await a.claimReferralRevenueQuick(t,r,i),n}async bindReferral(t){let e=new C.TransactionBlock,n=await Zo({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new C.TransactionBlock,e=await St({builder:this.builder,txBlock:t}),n=await ot({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let a=[];return await Promise.all(tt.map(async r=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(r),this.params.walletAddress),l=c[0];c.length>1&&t.mergeCoins(l,c.slice(1)),s=l}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(r,s);try{let l=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(r),this.params.walletAddress);t.mergeCoins(c,l)}catch(l){console.log(l)}i.push(c)}if(bt.includes(r))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,r);c&&i.push(c)}catch(c){console.log(c)}if(i.length>0){let c=i[0];i.length>1&&t.mergeCoins(c,i.slice(1)),a.push(c)}})),a.length>0&&t.transferObjects(a,this.params.walletAddress),t}async migrateLendingWusdcToUsdcNative(t,e,n,a,r){let i=new C.TransactionBlock,s=await W({builder:this.builder,txBlock:i}),c=await ot({builder:this.builder,txBlock:i}),l=this.params.walletAddress,d=[],u=this.utils.parseMarketCoinName(t),p=this.utils.parseMarketCoinType(u),f=(await this.utils.selectCoinsMarketCoin(p,l)).map(_=>_.objectId);i.setSender(l);for(let _=0;_<r.length;_++){let V=r[_],[F]=await c.unstakeQuick(V.coin,u,V.id);if(F){f.length>0&&i.mergeCoins(F,f);let nd=s.normalMethod.withdraw(F,t);d.push(nd)}}if(e>0){let _=await s.withdrawQuick(e,t);d.push(_)}d.length>1&&i.mergeCoins(d[0],d.slice(1));let[S]=i.splitCoins(d[0],[i.pure(a)]);i.transferObjects([d[0]],l);let{swapResult:I,accountCap:v}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:S,tx:i});typeof v=="string"&&i.transferObjects([v],l),Fc.check_slippage(i,I,n,a,this.query.utils.parseCoinType("usdc"));let U=s.normalMethod.deposit(I,"usdc");return await c.stakeQuick(U,"susdc"),i}};var Me=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Vo({id:lc})),await this.address.read(),this.client=new ea(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var na=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new Me({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new mo(e,this.scallop),a=new bo(e,this.scallop),r=new go(e,this.scallop),i=n.decode()||a.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:Jc.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:a,txSubType:r,intentionData:i}=t;this.scallop||(this.scallop=new Me({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(r){case"SupplyLending":s=Oo.fromData(i);break;case"WithdrawLending":s=Bo.fromData(i);break;case"Borrow":s=ho.fromData(i);break;case"Repay":s=vo.fromData(i);break;case"DepositCollateral":s=To.fromData(i);break;case"WithdrawCollateral":s=_o.fromData(i);break;case"OpenObligation":s=xo.fromData(i);break;case"StakeSpool":s=Ao.fromData(i);break;case"UnstakeSpool":s=Po.fromData(i);break;case"ClaimIncentiveReward":s=wo.fromData(i);break;case"BorrowWithBoost":s=yo.fromData(i);break;case"StakeSca":s=Fo.fromData(i);break;case"ExtendStakePeriod":s=Wo.fromData(i);break;case"ExtendPeriodAndStakeMore":s=Mo.fromData(i);break;case"RenewExpStakePeriod":s=Uo.fromData(i);break;case"WithdrawStakedSca":s=$o.fromData(i);break;case"SupplyAndStakeLending":s=qo.fromData(i);break;case"WithdrawAndUnstakeLending":s=Ro.fromData(i);break;case"RedeemSca":s=Lo.fromData(i);break;case"MigrateAndClaim":s=Io.fromData(i);break;case"BorrowWithReferral":s=So.fromData(i);break;case"CreateReferralLink":s=No.fromData(i);break;case"ClaimRevenueReferral":s=Eo.fromData(i);break;case"BindReferral":s=jo.fromData(i);break;case"MigrateScoin":s=Co.fromData(i);break;case"RepayWithBoost":s=Do.fromData(i);break;case"MigrateWusdcToUsdc":s=ko.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:a,scallop:this.scallop})}};var bl=require("@msafe/sui3-utils"),Sa=require("@suilend/frontend-sui"),gl=require("@suilend/springsui-sdk");var oa=require("@msafe/sui3-utils");var aa=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isMintTransaction())return this.decodeMint();if(this.isMintAndDepositTransaction())return this.decodeMintAndDeposit();if(this.isRedeemTransaction())return this.decodeRedeem();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintTransactionMoveCallCommands(){return!!this.getMoveCallCommand("mint")}isMintTransaction(){return this.hasMintTransactionMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isMintAndDepositTransaction(){return this.hasMintTransactionMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::MintEvent"))}.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeMint",e),{txType:oa.TransactionType.Other,type:"mint",intentionData:{amount:e}}}decodeMintAndDeposit(){return{txType:oa.TransactionType.Other,type:"mintAndDeposit",intentionData:this.decodeMint().intentionData}}decodeRedeem(){let e={RedeemEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::RedeemEvent"))}.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeRedeem",e),{txType:oa.TransactionType.Other,type:"redeem",intentionData:{amount:e}}}};var Yc=require("@mysten/sui/transactions");var Xc=B(require("sort-keys-recursive")),Tt=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Xc.default)(this.data))}};var ra=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintIntention.build",n,a,r,i,s,c);let l=new Yc.Transaction;return r.mintAndRebalanceAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("MintIntention.fromData",e),new o(e)}};var Zc=require("@mysten/sui/transactions");var ia=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintAndDepositIntention.build",n,a,r,i,s,c);let l=new Zc.Transaction;return i.depositCoin(a.address,r.mintAndRebalance(l,this.data.amount),r.liquidStakingObject.type,l,s?.id),l}static fromData(e){return console.log("MintAndDepositIntention.fromData",e),new o(e)}};var tl=require("@mysten/sui/transactions");var sa=class o extends Tt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("RedeemIntention.build",n,a,r,i,s,c);let l=new tl.Transaction;return await r.redeemAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("RedeemIntention.fromData",e),new o(e)}};var ul=require("@msafe/sui3-utils"),It=require("@suilend/sdk"),pl=require("@suilend/sdk/_generated/_framework/reified"),ml=require("@suilend/sdk/_generated/suilend/lending-market/structs");var _t=require("@msafe/sui3-utils"),ne=require("@mysten/bcs"),ee=require("@mysten/sui/utils"),Bt=require("@suilend/sdk"),qr=B(require("bignumber.js"));var ca=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("XXX this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("XXX this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let t={MintEvent:this.simResult.events.find(a=>a.type.includes("lending_market::MintEvent"))},e=(0,ee.normalizeStructTag)(t.MintEvent.parsedJson.coin_type.name),n=t.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",e,n),{txType:_t.TransactionType.Other,type:"deposit",intentionData:{coinType:e,value:n}}}decodeWithdraw(){let t={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},e={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=(0,ee.normalizeStructTag)(e.RedeemEvent.parsedJson.coin_type.name),a=e.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,a);let r=t.withdraw_ctokens.MoveCall.arguments[4].Input,i=new qr.default((0,ne.toHEX)((0,ne.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Bt.maxU64.toString();return console.log("XXX decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Bt.maxU64.toString()),s&&(a=Bt.maxU64.toString()),{txType:_t.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:a}}}decodeBorrow(){let t={borrow_request:this.getMoveCallCommand("borrow_request")},e={BorrowEvent:this.simResult.events.find(c=>c.type.includes("lending_market::BorrowEvent"))},n=(0,ee.normalizeStructTag)(e.BorrowEvent.parsedJson.coin_type.name),a=`${+e.BorrowEvent.parsedJson.liquidity_amount-+e.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,a);let r=t.borrow_request.MoveCall.arguments[4].Input,i=new qr.default((0,ne.toHEX)((0,ne.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Bt.maxU64.toString();return console.log("XXX decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Bt.maxU64.toString()),s&&(a=Bt.maxU64.toString()),{txType:_t.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:a}}}decodeRepay(){let t={RepayEvent:this.simResult.events.find(a=>a.type.includes("lending_market::RepayEvent"))},e=(0,ee.normalizeStructTag)(t.RepayEvent.parsedJson.coin_type.name),n=t.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",e,n),{txType:_t.TransactionType.Other,type:"repay",intentionData:{coinType:e,value:n}}}decodeClaim(){let t={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},e={};for(let n=0;n<t.ClaimReward.length;n++){let a=t.ClaimReward[n],r=(0,ee.normalizeStructTag)(a.parsedJson.coin_type.name),i=a.parsedJson.liquidity_amount;e[r]=`${+(e[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",e),{txType:_t.TransactionType.Other,type:"claim",intentionData:{value:e}}}decodeClaimAndDeposit(){return{txType:_t.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var nl=require("@mysten/sui/transactions");var el=B(require("sort-keys-recursive")),L=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,el.default)(this.data))}};var la=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("BorrowIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new nl.Transaction;return await r.borrowAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("BorrowIntention.fromData",e),new o(e)}};var il=require("@mysten/sui/transactions");var al=require("@mysten/sui/utils"),oe=require("@suilend/sdk"),rl=B(require("bignumber.js"));var $r=require("@mysten/sui/utils"),Su="0x34fe4f3c9e450fed4d0a3c587ed842eec5313c30c3cc3c0841247c49425e246b::suilend_point::SUILEND_POINT",wu=(0,$r.normalizeStructTag)(Su),ol=o=>(0,$r.normalizeStructTag)(o)===wu;var Tu=(o,t)=>{let e={[oe.Side.DEPOSIT]:[],[oe.Side.BORROW]:[]};return o.lendingMarket.reserves.forEach(n=>{[oe.Side.DEPOSIT,oe.Side.BORROW].forEach(a=>{let r=a===oe.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,i=t.userRewardManagers.find(s=>s.poolRewardManagerId===r.id);i&&(e[a]=r.poolRewards.map((s,c)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(c),rewardCoinType:(0,al.normalizeStructTag)(s.coinType.name),side:a})).filter(s=>!ol(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new rl.default(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(e).flat()},da=Tu;var ua=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new il.Transaction;return r.claimRewardsAndSendToUser(a.address,i.id,da(r,s),c),c}static fromData(e){return console.log("ClaimIntention.fromData",e),new o(e)}};var sl=require("@mysten/sui/transactions");var pa=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimAndDepositIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new sl.Transaction;return r.claimRewardsAndDeposit(a.address,i.id,da(r,s),c),c}static fromData(e){return console.log("ClaimAndDepositIntention.fromData",e),new o(e)}};var cl=require("@mysten/sui/transactions");var ma=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;console.log("DepositIntention.build",n,a,r,i,s);let c=new cl.Transaction;return await r.depositIntoObligation(a.address,this.data.coinType,this.data.value,c,i?.id),c}static fromData(e){return console.log("DepositIntention.fromData",e),new o(e)}};var ll=require("@mysten/sui/transactions");var fa=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("RepayIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new ll.Transaction;return await r.repayIntoObligation(a.address,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("RepayIntention.fromData",e),new o(e)}};var dl=require("@mysten/sui/transactions");var ba=class o extends L{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("WithdrawIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new dl.Transaction;return await r.withdrawAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("WithdrawIntention.fromData",e),new o(e)}};var ga=async(o,t)=>{let e=await It.SuilendClient.initializeWithLendingMarket(await ml.LendingMarket.fetch(o,(0,pl.phantom)(It.LENDING_MARKET_TYPE),It.LENDING_MARKET_ID),o),n=await It.SuilendClient.getObligationOwnerCaps(t.address,e.lendingMarket.$typeArgs,o),a=await Promise.all(n.map(r=>It.SuilendClient.getObligation(r.obligationId,e.lendingMarket.$typeArgs,o)));return{suilendClient:e,obligationOwnerCaps:n,obligations:a}},ha=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await ga(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SuilendAppHelper.deserialize",r);let s=new ca(e,r).decode();return{txType:ul.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await ga(r,i));let s;switch(n){case"deposit":s=ma.fromData(a);break;case"withdraw":s=ba.fromData(a);break;case"borrow":s=la.fromData(a);break;case"repay":s=fa.fromData(a);break;case"claim":s=ua.fromData(a);break;case"claimAndDeposit":s=pa.fromData(a);break;default:throw new Error("not implemented")}let c=window.localStorage.getItem("obligationId"),l=this.utils.obligations?.find(u=>u.id===c)??this.utils.obligations?.[0],d=this.utils.obligationOwnerCaps?.find(u=>u.obligationId===l?.id);return console.log("XXX obligationId:",c,"obligations:",this.utils.obligations,"obligationOwnerCaps:",this.utils.obligationOwnerCaps),s.build({network:e,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:d,obligation:l})}};var fl=async(o,t)=>{let e=await gl.LstClient.initialize(o,Sa.LIQUID_STAKING_INFO_MAP[Sa.LstId.sSUI]),n=await ga(o,t);return{lstClient:e,...n}},ya=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await fl(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SpringSuiAppHelper.deserialize",r);let s=new aa(e,r).decode();return{txType:bl.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await fl(r,i));let s;switch(n){case"mint":s=ra.fromData(a);break;case"mintAndDeposit":s=ia.fromData(a);break;case"redeem":s=sa.fromData(a);break;default:throw new Error("not implemented")}return s.build({network:e,suiClient:r,account:i,lstClient:this.utils.lstClient,suilendClient:this.utils.suilendClient,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};var Wl=require("@msafe/sui3-utils"),Ll=require("turbos-clmm-sdk");var $=require("@msafe/sui3-utils"),Vr=require("@mysten/sui.js/bcs"),kt=require("@mysten/sui.js/utils"),hl=require("turbos-clmm-sdk");var K={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},G={PackageId:"0xdee9"};var Cu=(o,t,e,n)=>{if(o===1)switch(n.findIndex(i=>i===t)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${t}`)}switch(e.findIndex(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},wa=class{constructor(t,e,n){this.txb=t;this.turbosSdk=e;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(t){if(this.isSwapTransaction())return await this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}getMoveCallsTransaction(t){return t.every(e=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===e))}getSwapMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&t.includes(e.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${K.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${K.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let t=this.transactions.find(m=>m.kind==="MoveCall"),e=0;this.swap2Layer.includes(t.target)&&(e=1);let n=Cu(e,t.target,this.swap1Layer,this.swap2Layer),a=n.map((m,f)=>{let S=this.helper.decodeSharedObjectId(f),I=this.helper.decodeInputU128(4+f+e),v=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new hl.BN(I.toString()));return{pool:S,a2b:m,nextTickIndex:v}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),l=this.helper.decodeInputBool(5+2*e),d=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:a[0].pool,a2b:a[0].a2b,amountSpecified:d}],address:s,amountSpecifiedIsInput:l});return{txType:$.TransactionType.Other,type:"Swap",intentionData:{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:u,amountB:l?u:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:$.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:a,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),a=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:$.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:a,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:$.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:$.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:a,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),a=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:$.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:a,nft:e,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:$.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){console.log(this.helper,"decodeRemoveLiquidity this.helper");let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),a=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:$.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:$.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:$.TransactionType.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),a=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:$.TransactionType.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),a=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:$.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new Ct(t,this.txb)}get collectRewardHelper(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect_reward`).map(e=>new Ct(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new Ct(t,this.txb)}get decreaseLiquidityHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new Ct(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${G.PackageId}::clob_v2::swap_exact_base_for_quote`);return new Ct(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${G.PackageId}::clob_v2::swap_exact_quote_for_base`);return new Ct(t,this.txb)}},Ct=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU128(t){let e=this.decodePureArg(t,"u128");return Number(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU32(t){let e=this.decodePureArg(t,"u32");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,kt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Vr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,kt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,kt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,kt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,kt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Vr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,kt.normalizeStructTag)(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};var yl=require("turbos-clmm-sdk");var Ta=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new yl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var Sl=require("turbos-clmm-sdk");var Ia=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Sl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,nft:r,txb:i}=this.data;return n.nft.burn({pool:a,nft:r,txb:i})}static fromData(e){return new o(e)}};var wl=require("turbos-clmm-sdk");var Ca=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new wl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:a,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(e){return new o(e)}};var Tl=require("turbos-clmm-sdk");var ka=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Tl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:a,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(e){return new o(e)}};var Il=require("turbos-clmm-sdk");var xa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Il.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{fee:a,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,amountA:p,amountB:m,deadline:f,txb:S}=this.data;return n.pool.createPool({fee:a,amountA:p,amountB:m,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,deadline:f,txb:S})}static fromData(e){return new o(e)}};var Cl=require("turbos-clmm-sdk");var va=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Cl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var kl=require("turbos-clmm-sdk");var Da=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new kl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:u}=this.data;return n.pool.increaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:u})}static fromData(e){return new o(e)}};var xl=require("@mysten/sui.js/transactions"),vl=require("@mysten/sui.js/utils");var Aa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new xl.TransactionBlock;return n.moveCall({target:`${K.PackageId}::claim::claim`,typeArguments:[K.turbosCoinType],arguments:[n.object(K.Claim),n.object(vl.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(e){return new o(e)}};var Dl=require("@mysten/sui.js/transactions");var Oa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Dl.TransactionBlock;return n.moveCall({target:`${K.PackageId}::claim::join`,typeArguments:[K.turbosCoinType],arguments:[n.object(K.Claim)]}),n}static fromData(e){return new o(e)}};var Al=require("@mysten/sui.js/transactions"),Ol=require("turbos-clmm-sdk");var Pa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ol.TurbosSdk(e.network.replace("sui:",""),e.suiClient),a=new Al.TransactionBlock;return a=await n.pool.collectFee({txb:a,...this.data}),a=await n.pool.collectReward({txb:a,...this.data}),a=await n.pool.decreaseLiquidity({txb:a,...this.data}),a=await n.nft.burn({txb:a,nft:this.data.nft,pool:this.data.pool}),a}static fromData(e){return new o(e)}};var Pl=require("turbos-clmm-sdk");var Ra=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new Pl.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:u,slippage:d,deadline:p,txb:m})}static fromData(e){return new o(e)}};var Nl=require("turbos-clmm-sdk");var Qr=require("@mysten/sui.js/utils"),Hr=require("@mysten/sui.js/transactions");var Rl=require("turbos-clmm-sdk");var We=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let a=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),a.push(...r.data);while(r.hasNextPage);let i=[],s=0;return a.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let a=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(a,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(a,[n.pure(e)]);return[r,a]}isSuiCoinAddress(t){return t.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(t){let e=await this.turbosSdk.provider.getOwnedObjects({owner:t,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${G.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?(0,Rl.unstable_getObjectId)(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${G.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var _l=89,Bl=1e6,jl=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Hr.TransactionBlock,c=new We(i),l=await c.getCoinsData(r,e,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),[f,S,I]=s.moveCall({typeArguments:[t,e],target:`${G.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(_l),m,s.pure(a),s.object((0,Qr.normalizeSuiObjectId)("0x6")),d]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([f],s.pure(r)),s.transferObjects([S],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(Bl),s},El=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Hr.TransactionBlock,c=new We(i),l=await c.getCoinsData(r,t,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),f=c.zero(e,s),[S,I,v]=s.moveCall({typeArguments:[t,e],target:`${G.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(_l),m,s.pure(a),d,f,s.object((0,Qr.normalizeSuiObjectId)("0x6"))]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([S],s.pure(r)),s.transferObjects([I],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(Bl),s};var _a=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Nl.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await El({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var Ml=require("turbos-clmm-sdk");var Ba=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ml.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await jl({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var ja=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new Ll.TurbosSdk(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:a,account:r}=t;console.log(t,"input");let s=await new wa(a,e,n).decode(r.address);return{txType:Wl.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":r=xa.fromData(t.intentionData);break;case"AddLiquidity":r=Ta.fromData(t.intentionData);break;case"IncreaseLiquidity":r=Da.fromData(t.intentionData);break;case"DecreaseLiquidity":r=va.fromData(t.intentionData);break;case"RemoveLiquidity":r=Pa.fromData(t.intentionData);break;case"CollectFee":r=Ca.fromData(t.intentionData);break;case"CollectReward":r=ka.fromData(t.intentionData);break;case"Burn":r=Ia.fromData(t.intentionData);break;case"Swap":r=Ra.fromData(t.intentionData);break;case"PrixJoin":r=Oa.fromData(t.intentionData);break;case"PrixClaim":r=Aa.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=_a.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=Ba.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var $l=require("@msafe/sui3-utils");var Ea=require("@msafe/sui3-utils"),Kr=require("@mysten/sui.js/bcs"),xt=require("@mysten/sui.js/utils");var ku={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},O=ku;var Na=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:Ea.TransactionType.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Ea.TransactionType.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:Ea.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(O.packageId));return new Gr(t,this.txb)}},Gr=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,xt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Kr.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,xt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,xt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,xt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,xt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Kr.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,xt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Ul=require("@mysten/sui.js/transactions");var Ma=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Ul.TransactionBlock,{ticketId:a}=this.data;return n.moveCall({target:`${O.packageId}::native_pool::burn_ticket`,arguments:[n.object(O.poolObjectId),n.object(O.systemStateObjectId),n.object(a)]}),n}static fromData(e){return new o(e)}};var Fl=require("@mysten/sui.js/transactions");var Wa=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Fl.TransactionBlock,{amount:a}=this.data,[r]=n.splitCoins(n.gas,[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::stake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),r]}),n}static fromData(e){return new o(e)}};var ql=require("@mysten/sui.js/transactions");var La=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new ql.TransactionBlock,{amount:a}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===O.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::unstake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),l]}),n}static fromData(e){return new o(e)}};var Ua=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,a=new Na(e).decode();return{txType:$l.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case"Stake":a=Wa.fromData(t.intentionData);break;case"UnStake":a=La.fromData(t.intentionData);break;case"ClaimTicket":a=Ma.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var ed=require("@msafe/sui3-utils");var Gl=require("@msafe/sui3-utils");var Ql=require("@firefly-exchange/library-sui"),Hl=require("@firefly-exchange/library-sui/dist/src/spot"),Vl={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x702301e7c6ca527a6f6a83f12c5edf2dcd6ec7a23fb5318ec86d88282eab7057"}},vt=(o,t)=>{if(o!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let e=new Ql.SuiClient({url:Vl.rpc});return new Hl.OnChainCalls(e,Vl.objects,{address:t.address,isUIWallet:!1})};var Le=require("@firefly-exchange/library-sui"),Kl=require("turbos-clmm-sdk"),j=class{static async openPositionAndAddLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.openPositionWithFixedAmount(r,t.lowerTick,t.upperTick,i,{returnTx:!0})}static async provideLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.provideLiquidityWithFixedAmount(r,t.position,i,{returnTx:!0})}static async removeLiquidity(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.removeLiquidity(r,t.position,i,{returnTx:!0})}static async closePosition(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.closePosition(r,t.position,{returnTx:!0})}static async collectRewards(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectRewards(r,t.position,{rewardCoinsType:t.rewardCoinsType,returnTx:!0})}static async collectFee(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectFee(r,t.position,{returnTx:!0})}static async collectFeeAndRewards(t,e,n){let a=vt(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectFeeAndRewards(r,t.position,{returnTx:!0})}buildLiqInput(t,e){return Le.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(e.lowerTick,e.upperTick,new Le.BN(new Kl.Decimal(e.tokenAmount).mul(10**(e.isCoinA?t.coin_a.decimals:t.coin_b.decimals)).toFixed(0)),e.isCoinA,!0,e.slippage,new Le.BN(t.current_sqrt_price))}};var Fa=class o extends b{constructor(e){super(e);this.data=e}txType=Gl.TransactionType.Other;txSubType="ClosePosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.closePosition(r,n,a)}static fromData(e){return new o(e)}};var zl=require("@msafe/sui3-utils");var qa=class o extends b{constructor(e){super(e);this.data=e}txType=zl.TransactionType.Other;txSubType="CollectFee";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.collectFee(r,n,a)}static fromData(e){return new o(e)}};var Jl=require("@msafe/sui3-utils");var $a=class o extends b{constructor(e){super(e);this.data=e}txType=Jl.TransactionType.Other;txSubType="CollectFeeAndRewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.collectFeeAndRewards(r,n,a)}static fromData(e){return new o(e)}};var Xl=require("@msafe/sui3-utils");var Va=class o extends b{constructor(e){super(e);this.data=e}txType=Xl.TransactionType.Other;txSubType="CollectRewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.collectRewards(r,n,a)}static fromData(e){return new o(e)}};var Yl=require("@msafe/sui3-utils");var Qa=class o extends b{constructor(e){super(e);this.data=e}txType=Yl.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.openPositionAndAddLiquidity(r,n,a)}static fromData(e){return new o(e)}};var Zl=require("@msafe/sui3-utils");var Ha=class o extends b{constructor(e){super(e);this.data=e}txType=Zl.TransactionType.Other;txSubType="ProvideLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.provideLiquidity(r,n,a)}static fromData(e){return new o(e)}};var td=require("@msafe/sui3-utils");var Ka=class o extends b{constructor(e){super(e);this.data=e}txType=td.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await j.removeLiquidity(r,n,a)}static fromData(e){return new o(e)}};var Ga=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(t){console.log("Bluefin helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:ed.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=Qa.fromData(t.intentionData);break;case"ProvideLiquidity":r=Ha.fromData(t.intentionData);break;case"RemoveLiquidity":r=Ka.fromData(t.intentionData);break;case"ClosePosition":r=Fa.fromData(t.intentionData);break;case"CollectFee":r=qa.fromData(t.intentionData);break;case"CollectRewards":r=Va.fromData(t.intentionData);break;case"CollectFeeAndRewards":r=$a.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var vu=co.fromHelpers([new Jn,new ao,new Hn,new ro,new kn,new ja,new na,new Ua,new Ze,new ha,new ya,new Ge,new Ga]);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|