@msafe/sui-app-store 0.0.142 → 0.0.144

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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var oi=Object.defineProperty;var dr=(a,t)=>{for(var e in t)oi(a,e,{get:t[e],enumerable:!0})};import{TransactionType as $i}from"@msafe/sui3-utils";import{TransactionType as hi}from"@msafe/sui3-utils";import ii from"sort-keys-recursive";var S=class{constructor(t){this.data=t}serialize(){return JSON.stringify(ii(this.data))}};import{AggregatorClient as si,Env as ci}from"@cetusprotocol/aggregator-sdk";import{CetusPeripherySDK as li}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as di}from"@cetusprotocol/cetus-sui-clmm-sdk";import{SuiClient as ui}from"@mysten/sui/client";var pi={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:"0x6f5e582ede61fe5395b50c4a449ec11479a54d7ff8e0158247adfda60d98970b",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"},mi={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:"0x016b8ce6560f55bfe02abb2cc0681bb91f767107cfb1c9b6e73a6bcf74492a02",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:""}}},fi={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"},bi={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:""}}},mt=(a,t)=>{let e=a==="sui:mainnet"?pi:fi,n=new di(e);return n.senderAddress=t.address,n},_=(a,t)=>{let e=mt(a,t),n=a==="sui:mainnet"?mi:bi;return new li(n,e)},gi="https://api-sui.cetus.zone/router_v2/find_routes",ur=(a,t)=>{let e=new ui({url:"https://fullnode.mainnet.sui.io/"});return new si(gi,t.address,e,ci.Mainnet)};var pr=async(a,t,e)=>await mt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),mr=async(a,t,e)=>await mt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),fr=async(a,t,e)=>await mt(e,t).Position.closePositionTransactionPayload(a),br=async(a,t,e)=>await mt(e,t).Position.removeLiquidityTransactionPayload(a),gr=async(a,t,e)=>await mt(e,t).Rewarder.collectRewarderTransactionPayload(a);var ee=class a extends S{constructor(e){super(e);this.data=e}txType=hi.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await pr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Si}from"@msafe/sui3-utils";var ne=class a extends S{constructor(e){super(e);this.data=e}txType=Si.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await gr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as yi}from"@msafe/sui3-utils";var ae=class a extends S{constructor(e){super(e);this.data=e}txType=yi.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await br(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as wi}from"@msafe/sui3-utils";var hr=async(a,t,e)=>await _(e,t).Farms.openPositionAddLiquidityStakePaylod(a),Sr=async(a,t,e)=>await _(e,t).Farms.addLiquidityFixCoinPayload(a),yr=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),wr=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),Cr=async(a,t,e)=>await _(e,t).Farms.claimFeeAndClmmReward(a),Ir=async(a,t,e)=>await _(e,t).Farms.harvestPayload(a),Tr=async(a,t,e)=>{let n=_(e,t),r=Object.values(a);return await n.Farms.batchHarvestPayload(r)},kr=async(a,t,e)=>await _(e,t).Farms.depositPayload(a),xr=async(a,t,e)=>await _(e,t).Farms.withdrawPayload(a);var re=class a extends S{constructor(e){super(e);this.data=e}txType=wi.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await hr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ci}from"@msafe/sui3-utils";var oe=class a extends S{constructor(e){super(e);this.data=e}txType=Ci.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Tr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ii}from"@msafe/sui3-utils";var ie=class a extends S{constructor(e){super(e);this.data=e}txType=Ii.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Cr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ti}from"@msafe/sui3-utils";var se=class a extends S{constructor(e){super(e);this.data=e}txType=Ti.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await yr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as ki}from"@msafe/sui3-utils";var ce=class a extends S{constructor(e){super(e);this.data=e}txType=ki.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Ir(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as xi}from"@msafe/sui3-utils";var le=class a extends S{constructor(e){super(e);this.data=e}txType=xi.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Sr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as vi}from"@msafe/sui3-utils";var de=class a extends S{constructor(e){super(e);this.data=e}txType=vi.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await wr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ai}from"@msafe/sui3-utils";var ue=class a extends S{constructor(e){super(e);this.data=e}txType=Ai.Other;txSubType="FarmingStake";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await kr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Oi}from"@msafe/sui3-utils";var pe=class a extends S{constructor(e){super(e);this.data=e}txType=Oi.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await xr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Pi}from"@msafe/sui3-utils";var me=class a extends S{constructor(e){super(e);this.data=e}txType=Pi.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await mr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Di}from"@msafe/sui3-utils";var fe=class a extends S{constructor(e){super(e);this.data=e}txType=Di.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await fr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as ji}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as _i}from"@cetusprotocol/aggregator-sdk";import{Transaction as Ri}from"@mysten/sui/transactions";var vr=async(a,t,e)=>{let n=ur(e,t),r=new Ri;return await n.fastRouterSwap({...a,routers:_i(a.routers),txb:r}),r};var be=class a extends S{constructor(e){super(e);this.data=e}txType=ji.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await vr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Bi}from"@msafe/sui3-utils";import{Transaction as Ni}from"@mysten/sui/transactions";var Ar={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Or=async(a,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:r,periods:o,CLOCK_ADDRESS:i}=a,s=new Ni;return o.forEach(c=>{s.moveCall({target:`${Ar.published_at}::router::redeem`,typeArguments:[Ar.cetus_coin_type],arguments:[s.object(n),s.object(r),s.pure(c),s.object(i)]})}),s};var ge=class a extends S{constructor(e){super(e);this.data=e}txType=Bi.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Or(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Mi}from"@msafe/sui3-utils";import{Transaction as Ei}from"@mysten/sui/transactions";var Pr=async(a,t,e)=>{let n=_(e,t),r=new Ei;return await n.XCetusModule.convertPayload(a,r)},Dr=async(a,t,e)=>await _(e,t).XCetusModule.redeemLockPayload(a),_r=async(a,t,e)=>await _(e,t).XCetusModule.redeemDividendV3Payload(a.phases,a.venft_id,a.bonus_types,a.bonus_types_v2,a.xTokenType),Rr=async(a,t,e)=>await _(e,t).XCetusModule.cancelRedeemPayload(a),jr=async(a,t,e)=>await _(e,t).XCetusModule.redeemPayload(a);var he=class a extends S{constructor(e){super(e);this.data=e}txType=Mi.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Rr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Li}from"@msafe/sui3-utils";var Se=class a extends S{constructor(e){super(e);this.data=e}txType=Li.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await _r(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Wi}from"@msafe/sui3-utils";var ye=class a extends S{constructor(e){super(e);this.data=e}txType=Wi.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Pr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Fi}from"@msafe/sui3-utils";var we=class a extends S{constructor(e){super(e);this.data=e}txType=Fi.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await jr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ui}from"@msafe/sui3-utils";var Ce=class a extends S{constructor(e){super(e);this.data=e}txType=Ui.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Dr(o,n,r)}static fromData(e){return new a(e)}};var Ie=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:$i.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:r}=t,o;switch(t.txSubType){case"OpenAndAddLiquidity":o=ee.fromData(t.intentionData);break;case"IncreaseLiquidity":o=me.fromData(t.intentionData);break;case"DecreaseLiquidity":o=ae.fromData(t.intentionData);break;case"RemoveLiquidity":o=fe.fromData(t.intentionData);break;case"ClaimFeeAndMining":o=ne.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":o=re.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":o=le.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":o=se.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":o=de.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":o=ie.fromData(t.intentionData);break;case"FarmingHarvest":o=ce.fromData(t.intentionData);break;case"FarmingBatchHarvest":o=oe.fromData(t.intentionData);break;case"FarmingStake":o=ue.fromData(t.intentionData);break;case"FarmingUnstake":o=pe.fromData(t.intentionData);break;case"xCETUSConvert":o=ye.fromData(t.intentionData);break;case"xCETUSRedeemLock":o=Ce.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":o=Se.fromData(t.intentionData);break;case"xCETUSCancelRedeem":o=he.fromData(t.intentionData);break;case"xCETUSRedeem":o=we.fromData(t.intentionData);break;case"VestingRedeem":o=ge.fromData(t.intentionData);break;case"AggregatorSwap":o=be.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n,network:r})}};import{TransactionType as Fs}from"@msafe/sui3-utils";import qi from"sort-keys-recursive";var g=class{constructor(t){this.data=t}serialize(){return JSON.stringify(qi(this.data))}};import{getFullnodeUrl as Te}from"@mysten/sui.js/client";var xa={};dr(xa,{contractId:()=>Hi,default:()=>Xi,feeObjId:()=>zi,roleObjId:()=>Ki,status:()=>Vi,transaction:()=>Qi,upgradeCapObjId:()=>Ji,vaultObjId:()=>Gi});var Qi="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Vi="success",Hi="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Ki="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Gi="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",zi="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Ji="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Xi={transaction:Qi,status:Vi,contractId:Hi,roleObjId:Ki,vaultObjId:Gi,feeObjId:zi,upgradeCapObjId:Ji};var va={};dr(va,{contractId:()=>ts,default:()=>os,feeObjId:()=>as,roleObjId:()=>es,status:()=>Zi,transaction:()=>Yi,upgradeCapObjId:()=>rs,vaultObjId:()=>ns});var Yi="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Zi="success",ts="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",es="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",ns="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",as="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",rs="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",os={transaction:Yi,status:Zi,contractId:ts,roleObjId:es,vaultObjId:ns,feeObjId:as,upgradeCapObjId:rs};var is=Te("testnet"),ss=Te("testnet"),cs=Te("mainnet"),ls=Te("mainnet"),ds="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",us="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",ps="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",ms="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Nr=xa,Br=va,fs=new Map([["dev",{env:"dev",rpc:{url:is},backend:{url:ds},contract:Nr}],["stg",{env:"stg",rpc:{url:ss},backend:{url:us},contract:Nr}],["prev",{env:"prev",rpc:{url:cs},backend:{url:ps},contract:Br}],["prod",{env:"prod",rpc:{url:ls},backend:{url:ms},contract:Br}]]);function Er(a,t){let e=fs.get(a);if(!e)throw new Error(`Env not supported: ${a}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as gs}from"@mysten/sui.js/client";var C=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:r,context:o}=n;r?super(`[MPay] ${e}: ${r}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var ke=class extends C{constructor(){super(11,"Backend is not specified")}};var xe=class extends C{constructor(){super(1,"Wallet not connected")}};import St,{AxiosError as bs}from"axios";var ht=class extends C{constructor(t,e){super(10,t,{context:e})}};var ve=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof bs)throw new ht(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new ht(t.data.code)}throw new ht(t.status.toString())}async getIncomingStreams(t,e){let n=await St.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await St.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await St.post(`${this.apiURL}/stream-events`,t),n=a.parseResponseData(e);return n.data.forEach(r=>{let o=r;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),n}async getAllCoinTypes(t){let e=await St.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await St.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await St.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(n)}};var yt=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new gs({url:t.rpc.url}),t.backend&&(this._backend=new ve(t.backend.url))}static new(t,e){let n=Er(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new ke;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 xe;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Ms,normalizeStructTag as Ls,normalizeSuiAddress as io}from"@mysten/sui.js/utils";import{TransactionBlock as Re}from"@mysten/sui.js/transactions";import{TransactionBlock as Vr}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Hr,normalizeStructTag as ws}from"@mysten/sui.js/utils";var Aa=50n,Ae=10000n,Mr=25n,Oa=100000000n;var q=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Pt=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},tt=class a{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 r=i=>new a(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield r(i),i++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}};import{Buffer as Lr}from"buffer";import{normalizeSuiAddress as hs}from"@mysten/sui.js/utils";var Dt=class extends C{constructor(t,e){super(3,t,{context:e})}};var Oe=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,r]=this.getValue(t,e);if(r!=="address")throw new Dt("Invalid contract return type.",{ctx:{expectType:"address",gotType:r}});return hs(Lr.from(n).toString("hex"))}getU64(t=0,e=0){let[n,r]=this.getValue(t,e);if(r!=="u64")throw new Dt("Invalid contract return type.",{ctx:{expectType:"u64",gotType:r}});return Lr.from(n).readBigInt64LE()}};import{bcs as Fr}from"@mysten/sui.js/bcs";var v=class extends C{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Ur={groupId:"string",name:"string"},Ss=64;function $r(a){return qr(a),Fr.ser(Ur,a).toString("base64")}function _t(a){let t=Fr.de(Ur,a,"base64");return qr(t),t}function qr(a){if(!Wr(a.name))throw new v("Invalid metadata: Name contains unknown character");if(!Wr(a.groupId))throw new v("Invalid metadata: Group ID contains unknown character");if(a.name.length>Ss)throw new v("Invalid metadata: Name exceed max length 64")}function Wr(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as Pe}from"@mysten/sui.js/utils";function De(a,t){return Pe(a)===Pe(t)}function et(a,t){return Pe(a)===Pe(t)}var _e="txn.gas";import{nanoid as ys}from"nanoid";function Qr(){return ys()}var ft=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:$r({name:t.name,groupId:Qr()}),coinType:ws(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 Vr,n=this.calculateFeesInternal(t),r=this.getCreateStreamCoinRequests(t,n),o=await this.wallet.requestCoins(r),i=await this.addMergeCoins(e,o[0]),s;r.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let c=0;c<t.recipients.length;c++){let d=t.recipients[c],l=this.amountForRecipient(d,t.numberEpoch),u=this.getStreamFeeLocal(l),[p]=e.splitCoins(i,[e.pure(l+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new tt(p),flatFeeCoin:new tt(m),metadata:t.metadata,recipient:d.address,timeStart:t.startTime,cliff:d.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:Aa,denominator:Ae},claimFeePercent:{numerator:Mr,denominator:Ae},flatFeePerStream:Oa}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(r=>t.object(r))),n=t.object(e.primaryCoin)):e.primaryCoin===_e?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return De(n,Hr)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:Hr,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((r,o)=>{let i=this.amountForRecipient(o,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:r.totalAmount+i,streamFeeAmount:r.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 Oa}getStreamFeeLocal(t){return t*Aa/Ae}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Vr,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Oe(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as Gr}from"@mysten/sui.js/transactions";var Kr="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(Gr.MoveCall({target:n,arguments:e.arguments.map(r=>r instanceof Pt?r.moveArgs(t):r instanceof q?r.moveArg(t):r instanceof tt?r.moveArg():t.pure(r)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],r=[]){t.add(Gr.MoveCall({target:e,arguments:n.map(o=>o instanceof Pt?o.moveArgs(t):o instanceof q?o.moveArg(t):o instanceof tt?o.moveArg():t.pure(o)),typeArguments:r}))}makeObject(t){return typeof t=="string"?new q(t):t}vaultObject(){return new q(this.config.vaultObjId)}roleObject(){return new q(this.config.roleObjId)}feeObject(){return new q(this.config.feeObjId)}clockObject(){return new q(Kr)}};var Ct=class a extends wt{constructor(e,n){super(a.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 r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[r,o,n],typeArgs:[]})}setStreamingFlatFee(e,n){let r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[r,o,n],typeArgs:[]})}setClaimFee(e,n){let r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[r,o,n],typeArgs:[]})}streamingFee(e,n){let r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[r,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Q=class a extends wt{constructor(e,n){super(a.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 r=this.feeObject(),o=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:a.MethodName.create_stream,arguments:[r,o,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 r=this.makeObject(n.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[r,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let r=this.makeObject(n.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[r,o],typeArgs:[n.coinType]})}claimStream(e,n){let r=this.makeObject(n.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[r,o],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let r=this.makeObject(n.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[r,o,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var It=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Ct(e,t),this.streamContract=new Q(e,t)}feeContract;streamContract;async createStreams(t){let e=ft.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new ft(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let r=new Re;return this.streamContract.setAutoClaim(r,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Re;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Re;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Re;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var O=class extends C{constructor(t,e={}){super(0,t,e)}};async function Da(a){let t=[];for(;await a.hasNext();){let e=await a.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Pa=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)}},Tt=class{constructor(t){this.requester=t;this.pager=new Pa(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 je=class extends C{constructor(e,n,r){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:r}});this.coinType=e;this.requestAmount=n;this.gotAmount=r}};var Cs=25;async function zr(a,t,e,n="0x2::sui::SUI",r=Cs){let o=new _a(a,t,n,r),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let c=await o.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new je(n,e,i);return s}var _a=class extends Tt{constructor(e,n,r,o){super(new Ra(e,n,r,o));this.suiClient=e;this.owner=n;this.coinType=r;this.reqPageSize=o}},Ra=class{constructor(t,e,n,r){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=r;if(r<=0)throw new O("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}}};import{TransactionBlock as Me}from"@mysten/sui.js/transactions";import{normalizeStructTag as Xr,parseStructTag as ks}from"@mysten/sui.js/utils";import{DateTime as xs}from"luxon";var Ne=class extends C{constructor(){super(7,"Connected wallet is not creator")}};var Rt=class extends C{constructor(){super(8,"Connected wallet is not recipient")}};var jt=class extends C{constructor(t,e){super(6,t,{context:e})}};var Be=class extends C{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Is,Duration as Ts}from"luxon";var Jr=(1n<<64n)-1n,Ee=1e3;function ja(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ee);return Is.fromMillis(e*Ee)}function Na(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ee);return Ts.fromMillis(e*Ee)}var nt=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new Q(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await a.fetchStreamData(t,e);return new a(t,e,n)}static fromObjectData(t,e,n){let r=a.parseRawStreamData(e,n);return new a(t,e,r)}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 a.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new O("Object Id does not align");this.rawData=a.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 Ne;let t=new Me;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Rt;let t=new Me;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Rt;let e=new Me;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Me;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 Xr(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 Na(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return _t(t).groupId}get name(){let{metadata:t}=this.rawData.config;return _t(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ja(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Na(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:ja((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===Jr?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=xs.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 a.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new Be(t):new jt(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new jt("Unexpected object type",{gotType:n.dataType});let{typeParams:r}=ks(n.type),o=Xr(r[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:o,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)}}}};import{normalizeStructTag as Ba,SUI_TYPE_ARG as vs}from"@mysten/sui.js/utils";import{Duration as Yr}from"luxon";var Le=class extends C{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var As=1e3,We=class{constructor(t){this.globals=t;this.coinMetaHelper=new Ea(t.suiClient),this.createStreamHelper=new It(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Le(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 v("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,r=(t.totalAmount-n)/t.steps,i={realTotalAmount:r*t.steps+n,cliffAmount:n,amountPerStep:r};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new v("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 v("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(Yr.fromMillis(Number(e*t.steps))),r={timeStart:t.timeStart,timeEnd:n,interval:Yr.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(r),r}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),r=await this.getCoinMeta(e);return{...n,coinType:Ba(n.coinType),coinMeta:r}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(r=>this.getCoinMeta(r.coinType)));return e.map((r,o)=>({...r,coinType:Ba(r.coinType),coinMeta:n[o]}))}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 v("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new v("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<As)throw new v("Interval shall be at least 1 second","interval",t.interval)}},Ea=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Ba(t||vs);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}};import{normalizeStructTag as Zr,normalizeSuiAddress as Ue}from"@mysten/sui.js/utils";import{DateTime as to}from"luxon";var kt=class extends C{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var Os=25;async function La(a,t,e){let n=new Nt(t),r=new Bt(a,n,e);return await Da(r)}var Nt=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]}},Bt=class extends Tt{constructor(e,n,r){super(new Ma(e,n,r));this.suiClient=e;this.idIter=n;this.options=r}},Ma=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||Os,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 o=await this.stringIter.next();o&&t.push(o)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:r}=this;n=e.filter(o=>r?.(o))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Fe=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new kt("stream size 0");let n=e.map(o=>o.groupId);if(new Set(n).size!==1)throw new v("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await La(t.suiClient,e);return n.forEach(r=>{if(!r)throw new O("stream group object data undefined")}),a.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let r=await a.parseGroupStreams(t,e,n);return new a(t,r)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),n=e[0],r=!0;return e.forEach(o=>{Ps(n,o)||(r=!1)}),r}async refresh(){let t=await La(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 r=n.map((o,i)=>nt.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new kt("Not same group ID");if(!this.checkStreamGroup(r))throw new kt("Not same stream settings");return r}};function Ps(a,t){return a.name===t.name&&a.groupId===t.groupId&&a.creator===t.creator&&a.start.toMillis()===t.start.toMillis()&&a.interval.toMillis()===t.interval.toMillis()&&a.steps===t.steps&&a.cancelable===t.cancelable}var Et=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await $e.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await $e.newOutgoing(t);return new a(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}},$e=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await qe.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await qe.newOutgoingQuery(t);return new a(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 O("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new O("No more results");return t}},qe=class a{constructor(t,e,n,r){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=r;this.current=0;let o=new Nt(n.flat().map(i=>i.streamId));this.objectIter=new Bt(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Ns(t.query),n=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>Ue(s.recipient)===Ue(n)),i=eo(o);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=Bs(t.query),n=await t.globals.walletAddress(),r=await t.globals.backend.getOutgoingStreams(n,e),o=eo(r);return new a(t.globals,n,o,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 Rs(this.globals,t[0].streamId,this.objectIter);return this.current++,no(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await js(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,_s(e,this.query)?e:this.doNextRequest()}throw new O("Stream group with no stream")}};function eo(a){let t=new Map;return a.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)=>to.fromISO(n[0].createDate).toMillis()-to.fromISO(e[0].createDate).toMillis())}function no(a,t){if(t===void 0)return!0;let e=Ds(a,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return e&&n}return e}function Ds(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function _s(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{no(n,t)&&(e=!0)}),e}async function Rs(a,t,e){let n=await ao(e,t);return nt.fromObjectData(a,t,n)}async function js(a,t,e){let n=[];for(;n.length<t.length;){let r=await ao(e,t[n.length]);n.push(r)}return Fe.newFromObjectResponse(a,t,n)}async function ao(a,t){if(!await a.hasNext())throw new O("object iterator has been consumed");let e=await a.next();if(!e||e.error||e.data===void 0||e.data===null)throw new O("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new O("stream id not aligned");return e}function Ns(a){return{status:Wa(a?.status),coinType:ro(a?.coinType),sender:oo(a?.sender)}}function Bs(a){return{status:Wa(a?.status),coinType:ro(a?.coinType),recipient:oo(a?.recipient)}}function Wa(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=Wa(e);return!t||t===n?n:"all"},void 0):Es(a)}function Es(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new v("Unknown stream filtered status")}}function ro(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>Zr(t)):void 0:Zr(a)}function oo(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>Ue(t)):void 0:Ue(a)}var Fa=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Qe=class{constructor(t){this.account=t}async address(){return this.account.address}},Ua=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(De(t.coinType,Ms))return{primaryCoin:_e};if(t.amount<=0)throw new v("Invalid coin request","coinAmount",t.amount);let e=await zr(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new O("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},Ve=class{globals;helper;constructor(t,e){this.globals=yt.new(t,e),this.helper=new We(this.globals)}connectSingleWallet(t){let e=new Ua(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Fa(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return nt.new(this.globals,t)}async getIncomingStreams(t,e=10){return Et.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Et.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=>Ls(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>io(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>io(r))}get wallet(){return this.globals.wallet}builder(){return new It(this.globals)}};var L=class extends g{application="mpay";getClient(t,e){let n=new Ve(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Qe(e)),n}};var Mt=class extends L{constructor(e){super(e);this.data=e}txType=Fs.Stream;txSubType="Cancel";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).cancel()}};import{TransactionType as Us}from"@msafe/sui3-utils";var Lt=class extends L{constructor(e){super(e);this.data=e}txType=Us.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as $s}from"@msafe/sui3-utils";var Wt=class extends L{constructor(e){super(e);this.data=e}txType=$s.Stream;txSubType="Claim";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).claim()}};import{TransactionType as qs}from"@msafe/sui3-utils";var Ft=class extends L{constructor(e){super(e);this.data=e}txType=qs.Stream;txSubType="CreateStream";async build(e){let{network:n,account:r}=e;return this.getClient(n,r).createStream(this.data)}};import{bcs as so}from"@mysten/sui.js/bcs";import{normalizeStructTag as Qs,normalizeSuiAddress as Ut}from"@mysten/sui.js/utils";var xt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return Ut(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 so.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 Ut(t.value.Object.ImmOrOwned.objectId)}return Ut(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Ut(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Ut(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 so.de(e,new Uint8Array(n))}typeArg(t){return Qs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var He=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"&&et(e.target,this.contract.createStreamTarget));if(t.length===0)throw new O("No create stream transactions");return t.map(e=>new xt(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:r}=_t(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),d=t.decodeInputU64(9),l=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:r,recipient:o,timeStart:i,cliff:s,epochInterval:c,totalEpoch:d,amountPerEpoch:l,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new v("Stream group not have common info");let n=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.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 Q(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ct(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ft(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 Ke=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new Q(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"&&et(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&et(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&et(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&et(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&et(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new He(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 xt(t,this.txb)}};import{TransactionType as Vs}from"@msafe/sui3-utils";var $t=class extends L{constructor(e){super(e);this.data=e}txType=Vs.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Ge=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,r=yt.new(e==="sui:mainnet"?"prod":"dev"),i=new Ke(r,n).decode(),s;switch(i.type){case"CreateStream":s=new Ft(i.info);break;case"SetAutoClaim":s=new $t({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Wt({streamId:i.streamId});break;case"ClaimByProxy":s=new Lt({streamId:i.streamId});break;case"Cancel":s=new Mt({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 Ft(e);break;case"Claim":n=new Wt(e);break;case"ClaimByProxy":n=new Lt(e);break;case"SetAutoClaim":n=new $t(e);break;case"Cancel":n=new Mt(e);break;default:throw new Error("not implemented")}return n.build({...t})}};import{TransactionDefaultApplication as Js,TransactionSubTypes as $a}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Hs}from"@msafe/sui3-utils";var ze=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e;return Hs(n,this.data,r.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as Ks}from"@msafe/sui3-utils";var Je=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e;return Ks(n,this.data,r.address)}static fromData(e){return new a(e)}};import{isSameAddress as Gs}from"@msafe/sui3-utils";import{TransactionBlock as zs}from"@mysten/sui.js/transactions";var Xe=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,r=zs.from(this.data.content);if(!Gs(r.blockData.sender,n.address))throw new Error("Invalid sender address");return r}static fromData(e){return new a(e)}};var Ye=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Js}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,r;switch(t.txSubType){case $a.assets.coin.send:r=ze.fromData(t.intentionData);break;case $a.assets.object.send:r=Je.fromData(t.intentionData);break;case $a.others.plain:r=Xe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};import{TransactionType as rc}from"@msafe/sui3-utils";var co=!1,Ze={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"},usdc:{name:"USDC",assetId:1,coinType:"usdc",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"}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function qa(){if(!co)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n}=a;t&&(Ze.ProtocolPackage=t),e&&(Ze.borrowFee=e),n&&(Ze.borrowFeeAddress=n),co=!0}catch(a){console.error(a.message)}}var h=Ze;import{TransactionType as qt}from"@msafe/sui3-utils";import{bcs as lo}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ys,normalizeSuiAddress as Qt}from"@mysten/sui.js/utils";var tn=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.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`)}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 en(e,this.txb),r=n.decodeInputU8(4),o=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(r),c=[...e.typeArguments];t.push({coinType:s.coinType,option:o,typeArguments:c,assetId:r,poolId:i})}}),console.log("decode claims",t),{txType:qt.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:qt.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:qt.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:qt.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:qt.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 en(t,this.txb)}},en=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Qt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 lo.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 Qt(t.value.Object.ImmOrOwned.objectId)}return Qt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Qt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Qt(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 lo.de(e,new Uint8Array(n))}typeArg(t){return Ys(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Zs}from"@mysten/sui.js/transactions";function Qa(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function uo(a,t,e){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function po(a,t,e,n){let r=a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.IncentiveV2)],typeArguments:[t.type]}),[o]=a.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[r]});if(h.borrowFee>0){let[i]=a.splitCoins(o,[a.pure(Math.floor(e*h.borrowFee))]);a.transferObjects([o],a.pure(n)),a.transferObjects([i],a.pure(h.borrowFeeAddress))}else a.transferObjects([o],a.pure(n));return a}function Va(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function mo(a,t,e,n,r){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(h.IncentiveV2),a.object(e),a.object(h.StorageId),a.pure(t),a.pure(n)],typeArguments:r}),a}var nn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Zs;return e.forEach(r=>{let{assetId:o,poolId:i,option:s,typeArguments:c}=r;mo(n,o,i,s,c)}),n}static fromData(e){return new a(e)}};import{TransactionBlock as tc}from"@mysten/sui.js/transactions";var an=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:r}=this.data,o=new tc;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 po(o,i,r,e.account.address)}static fromData(e){return new a(e)}};import{TransactionBlock as ec}from"@mysten/sui.js/transactions";async function rn(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var on=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e,{coinType:o,amount:i}=this.data,s=new ec;if(console.log("build",this.data),o==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Qa(s,h.pool.sui,u,i)}let c=h.pool[o];if(!c)throw new Error(`${o} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await rn(n,r.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let u=1;for(;u<d.data.length;)s.mergeCoins(l,[d.data[u].coinObjectId]),u++}return Qa(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as nc}from"@mysten/sui.js/transactions";var sn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e,{coinType:o,amount:i}=this.data,s=new nc;if(console.log("build",this.data),o==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Va(s,h.pool.sui,u,i)}let c=h.pool[o];if(!c)throw new Error(`${o} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await rn(n,r.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let u=1;for(;u<d.data.length;)s.mergeCoins(l,[d.data[u].coinObjectId]),u++}return Va(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as ac}from"@mysten/sui.js/transactions";var cn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,r=new ac;console.log("build",this.data);let o=h.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return uo(r,o,n)}static fromData(e){return new a(e)}};var ln=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await qa();let{transactionBlock:e}=t,r=new tn(e).decode();return{txType:rc.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n}=t,r;switch(await qa(),t.txSubType){case"EntryDeposit":r=on.fromData(t.intentionData);break;case"EntryBorrow":r=an.fromData(t.intentionData);break;case"EntryRepay":r=sn.fromData(t.intentionData);break;case"EntryWithdraw":r=cn.fromData(t.intentionData);break;case"ClaimReward":r=nn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};import{TransactionSubTypes as oc,TransactionType as fo}from"@msafe/sui3-utils";import{fromHEX as ic,toHEX as sc}from"@mysten/bcs";import{Transaction as cc}from"@mysten/sui/transactions";import lc from"sort-keys-recursive";var bo="msafe-plain-tx",go=oc.others.plain,Ha=class a{constructor(t){this.data=t}application=bo;txType=fo.Other;txSubType=go;serialize(){return JSON.stringify(lc(this.data))}async build(t){return cc.from(ic(this.data.content))}static fromData(t){return new a(t)}},dn=class{application;supportSDK="@mysten/sui";constructor(){this.application=bo}async deserialize(t){let{transaction:e}=t,n=await e.build({client:t.suiClient});return{txType:fo.Other,txSubType:go,intentionData:{content:sc(n)}}}async build(t){let{account:e}=t,r=await Ha.fromData(t.intentionData).build({suiClient:t.suiClient,network:t.network,account:t.account}),i=await t.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:e.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return r}};import{SuiClient as ho}from"@mysten/sui/client";import{Transaction as dc}from"@mysten/sui/transactions";import{SuiClient as Ka}from"@mysten/sui.js/client";import{TransactionBlock as uc}from"@mysten/sui.js/transactions";var un=class a{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new a;for(let n=0;n<t.length;n++){let r=t[n];switch(r.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(r);break;case"@mysten/sui":e.addHelper(r);break;default:throw new Error(`${r.application}: ${r.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new za(t))}addHelper(t){this.apps.set(t.application,new Ga(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},Ga=class{constructor(t){this.helper=t}async deserialize(t){let e=new ho({url:t.clientUrl}),n=new Ka({url:t.clientUrl}),r=await t.transactionBlock.build({client:n}),o=dc.from(r);return this.helper.deserialize({...t,suiClient:e,transaction:o})}async build(t){let e=new ho({url:t.clientUrl}),n=await this.helper.build({...t,suiClient:e});n.setSender(t.account.address);let r=await n.build({client:e});return uc.from(r)}},za=class{constructor(t){this.helper=t}async deserialize(t){let e=new Ka({url:t.clientUrl});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new Ka({url:t.clientUrl});return this.helper.build({...t,suiClient:e})}};import{TransactionType as Ec}from"@msafe/sui3-utils";import{TransactionType as P}from"@msafe/sui3-utils";var at=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 So="https://sui.apis.scallop.io";var yo="664dfe22898c36c159e28bc8",pn="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var rt="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",ot="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",V=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],mn=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],it=["seth","ssui","susdc","susdt","scetus","safsui","shasui","svsui"],H=["ssui","susdc","susdt","safsui","shasui","svsui","seth","ssca","scetus","sbtc","ssol"];var wo=["sui"],st=["sui","usdc","usdt","afsui","hasui","vsui","eth","sca","btc","sol"];var Co={eth:8,btc:8,usdc:6,usdt:6,sui:9,apt:8,sol:8,sca:9,cetus:9,afsui:9,hasui:9,vsui:9,seth:8,sbtc:8,susdc:6,susdt:6,ssui:9,sapt:8,ssol:8,scetus:9,safsui:9,shasui:9,svsui:9,ssca:9};var fn={seth:"sui",ssui:"sui",susdc:"sui",susdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui"},Io={sui:["sui","sca"],usdc:["sui","sca"],usdt:["sui","sca"],afsui:["sui","sca"],hasui:["sui","sca"],vsui:["sui","sca"],sca:["sui","sca"],eth:["sui","sca"],btc:["sui","sca"],sol:["sui","sca"]},To={sui:"0x0000000000000000000000000000000000000000000000000000000000000002",eth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",btc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",usdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",usdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",apt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",sol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",cetus:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",afsui:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",hasui:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",sca:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6"},B={eth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",btc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",usdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",usdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",apt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",sol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Ja={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},ko={ssui:"0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI",scetus:"0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS",ssca:"0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA",susdc:"0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC",susdt:"0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT",seth:"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",sbtc:"0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC",ssol:"0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL"};import{bcs as xo}from"@mysten/sui.js/bcs";import{normalizeStructTag as pc,normalizeSuiAddress as Vt}from"@mysten/sui.js/utils";var w=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Vt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 xo.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 Vt(t.value.Object.ImmOrOwned.objectId)}return Vt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Vt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Vt(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 xo.de(e,new Uint8Array(n))}typeArg(t){return pc(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{bcs as mc}from"@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 mc.de(e,new Uint8Array(n))}return t.value}};var bn=class extends at{decode(){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()}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(`${ot}::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(`${ot}::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 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:P.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),r=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:P.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:r,veScaKey:t}}}decodeOpenObligation(){return{txType:P.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((r,o)=>r+o,0);return{txType:P.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((r,o)=>r+o,0);return{txType:P.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((r,o)=>r+o,0);return{txType:P.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((o,i)=>o+i,0),r=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:P.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:r,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),r=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:P.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:r,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:P.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:r,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),r=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:P.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:o,obligationId:r,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),r=this.helperBorrowWithReferral.decodeSharedObjectId(1),o=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:P.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:o,obligationId:r,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((o,i)=>o+i,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:P.Other,type:"Repay",intentionData:{amount:n,obligationId:r,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),r=new R(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:P.Other,type:"RepayWithBoost",intentionData:{amount:r,obligationId:o,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=this.helperBurnScoin.getNestedInputParam(1),n=new R(e,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperStake.typeArg(0),o=this.scallop.utils.parseCoinNameFromType(r);return{txType:P.Other,type:"StakeSpool",intentionData:{amount:n,marketCoinName:o,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),r=this.scallop.utils.parseCoinNameFromType(n);return{txType:P.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:r,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((o,i)=>o+i,0),r;return this.isCreateStakeAccountTransaction()||(r=this.helperStake.decodeOwnedObjectId(1)),{txType:P.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:r}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(r=>{let o=r.decodeOwnedObjectId(1),i=r.decodeInputU64(2);t.push({id:o,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);n=new R(r,this.txb).getAmountInput().reduce((o,i)=>o+i,0)}return{txType:P.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(r=>{let o=r.decodeOwnedObjectId(2),i=r.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:o})}),this.helperClaimBorrowV2Reward.forEach(r=>{let o=r.decodeSharedObjectId(3),i=r.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(r.typeArg(0));e.push({obligationId:i,obligationKey:o,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(r=>{let o=r.decodeSharedObjectId(2),i=r.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(r.typeArg(0));n.push({obligationId:i,obligationKey:o,rewardCoinName:s})}),{txType:P.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};import{TransactionType as Ya}from"@msafe/sui3-utils";var gn=class extends at{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:Ya.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Ya.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:Ya.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};import{TransactionType as Ht}from"@msafe/sui3-utils";var hn=class extends at{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(`${ot}::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:Ht.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,y)=>f+y,0),r=this.helperRenewExpired.decodeOwnedObjectId(1),o=!!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 d=!1,l=!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,d=!0,l=m[f].isOld);return{txType:Ht.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:r,isHaveRedeem:o,isObligationLocked:d,isOldBorrowIncentive:l}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],r=[],o=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(o=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,d,l=[{condition:n,isOld:!0},{condition:r,isOld:!1},{condition:o,isOld:!1}];for(let u=0;u<l.length;u++)l[u].condition.length>1&&([d,c]=l[u].condition,i=!0,s=l[u].isOld);return{txType:Ht.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:d,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),r=[],o=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(r=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[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,d=!1,l,u,p=[{condition:r,isOld:!0},{condition:o,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:Ht.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:l,obligationKey:u,isOldBorrowIncentive:d,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),r=[],o=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(r=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[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,d=!1,l,u,p=[{condition:r,isOld:!0},{condition:o,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:Ht.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:l,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:d}}}};import fc from"sort-keys-recursive";var b=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(fc(this.data))}};var Sn=class a extends b{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 a(e)}};var yn=class a extends b{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 a(e)}};var wn=class a extends b{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 a(e)}};var Cn=class a extends b{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 a(e)}};var In=class a extends b{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 a(e)}};var Tn=class a extends b{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 a(e)}};var kn=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new a(e)}};var xn=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new a(e)}};var vn=class a extends b{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 a(e)}};var An=class a extends b{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 a(e)}};var On=class a extends b{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 a(e)}};var Pn=class a extends b{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 a(e)}};var Dn=class a extends b{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 a(e)}};var _n=class a extends b{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 a(e)}};var Rn=class a extends b{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 a(e)}};var jn=class a extends b{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 a(e)}};var Nn=class a extends b{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 a(e)}};var Bn=class a extends b{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 a(e)}};var En=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new a(e)}};var Mn=class a extends b{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 a(e)}};var Ln=class a extends b{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 a(e)}};var Wn=class a extends b{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 a(e)}};var Fn=class a extends b{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 a(e)}};var Un=class a extends b{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 a(e)}};var $n=class a extends b{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 a(e)}};var qn=class a extends b{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 a(e)}};var Qn=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,r)=>typeof n=="object"?n[r]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${So}/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}`)}};import{TransactionBlock as I}from"@mysten/sui.js/transactions";import Jo from"bignumber.js";import{TransactionBlock as bc}from"@mysten/sui.js/transactions";var Vn=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:r,utils:o}=e;this.address=n,this.query=r,this.utils=o,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new bc(t)}async selectCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,o,r),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,o,r),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[d,l]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:d,leftCoin:l,totalAmount:s}}async selectSCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,o,r),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[d,l]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:d,leftCoin:l,totalAmount:c}}};import{TransactionBlock as gc}from"@mysten/sui.js/transactions";import Hn from"bignumber.js";var vt=async(a,t)=>{let e=t,n=a.address.get("core.object")||pn,r=[],o=!1,i=null;do{let l=await a.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});r.push(...l.data),l.hasNextPage&&l.nextCursor?(o=!0,i=l.nextCursor):o=!1}while(o);let s=r.map(l=>l?.data?.objectId).filter(l=>l!==void 0),c=await a.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),d=[];for(let l=0;l<c.length;l++){let u=c[l].data.objectId,{content:p}=c[l].data;if(p&&"fields"in p){let m=p.fields,f=String(m.ownership.fields.of),y=await Za(a,f);d.push({id:f,keyId:u,locked:y})}}return d},Za=async(a,t)=>{let e=await a.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},vo=async(a,t,e)=>{let n=e||[...V],r=t,o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:r,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Hn(c[m]??0).plus(p.balance).toNumber())}}),c},Ao=async(a,t,e)=>{let n=e,r=a.utils.parseCoinType(t),o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${r}>`},options:{showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Hn(c).plus(u.balance).toNumber()}}),c},Oo=async(a,t,e)=>{let n=e||[...V].map(l=>a.utils.parseMarketCoinName(l)),r=t,o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:r,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Hn(c[m]??0).plus(p.balance).toNumber())}}),c},Po=async(a,t,e)=>{let n=e,r=a.utils.parseMarketCoinType(t);console.log(r);let o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${r}>`},options:{showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Hn(c).plus(u.balance).toNumber()}}),c},Do=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,r=new gc;return r.moveCall({target:n,arguments:[r.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:r,sender:a.params.walletAddress})).events[0].parsedJson};import{normalizeStructTag as T}from"@mysten/sui.js/utils";var Kt=async(a,t)=>{let e=t,n=a.address.get("spool.object"),r=`${n}::spool_account::SpoolAccount`,o=[],i=!1,s=null;do{let p=await a.client.getOwnedObjects({owner:e,filter:{StructType:r},options:{showContent:!0,showType:!0},cursor:s});o.push(...p.data),p.hasNextPage&&p.nextCursor?(i=!0,s=p.nextCursor):i=!1}while(i);let c={seth:[],ssui:[],susdc:[],susdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},d=Object.keys(c).reduce((p,m)=>{let f=a.utils.parseCoinName(m),y=a.utils.parseMarketCoinType(f),k={...p},D=`${n}::spool_account::SpoolAccount<${y}>`;return k[m]=D,k},{}),l=o.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await a.client.multiGetObjects({ids:l,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 y=p.data.content.fields,k=String(y.spool_id),D=String(y.stake_type.fields.name),$=Number(y.stakes),z=Number(y.index),J=Number(y.points),X=Number(y.total_points);T(f)===d.seth?c.seth.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.ssui?c.ssui.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.susdc?c.susdc.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.susdt?c.susdt.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.scetus?c.scetus.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.safsui?c.safsui.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.shasui?c.shasui.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X}):T(f)===d.svsui&&c.svsui.push({id:m,type:T(f),stakePoolId:k,stakeType:T(D),staked:$,index:z,points:J,totalPoints:X})}}),c},tr=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.id`),n,r=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(r.data){let o=r.data,i=o.objectId,s=o.type;if(o.content&&"fields"in o.content){let c=o.content.fields,d=Number(c.max_distributed_point),l=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),y=Number(c.stakes),k=Number(c.index),D=Number(c.created_at),$=Number(c.last_update);n={id:i,type:T(s),maxPoint:d,distributedPoint:l,pointPerPeriod:u,period:p,maxStake:m,stakeType:T(f),totalStaked:y,index:k,createdAt:D,lastUpdate:$}}}return n},er=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.rewardPoolId`),n,r=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(r.data){let o=r.data,i=o.objectId,s=o.type;if(o.content&&"fields"in o.content){let c=o.content.fields,d=String(c.spool_id),l=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:T(s),stakePoolId:d,ratioNumerator:l,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};import{TransactionBlock as yc}from"@mysten/sui.js/transactions";import{normalizeStructTag as jw}from"@mysten/sui.js/utils";import Bw from"bignumber.js";var j=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},jo=(a,t,e,n)=>{let r=!n,o=!r&&n*1e3<=new Date().getTime();if(r||o)if(a!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof a=="number"&&a<1e10)throw new Error(`Minimum lock amount for ${o?"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 ${o?"renewing expired veSca":"initial lock"}`);else{if(At(n),typeof a=="number"&&a<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)`)}},No=(a,t,e)=>{if(At(e),a<=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)`)},Bo=(a,t)=>{if(At(t),a<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")},Eo=(a,t,e)=>{if(At(e),a<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)`)},At=a=>{if(a===void 0)throw new Error("veSca not found")};import{normalizeStructTag as Mo,parseStructTag as hc}from"@mysten/sui.js/utils";import Iw from"bignumber.js";var Sc=a=>({pointType:Mo(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),Lo=a=>({poolType:Mo(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=Sc(e),r=hc(n.pointType).name.toLowerCase();return t[r]=n,t},{})});var Gn=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...V,...mn,...wo])].includes(t)},nr=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}},Wo=a=>{let t=new Date(a*1e3),e=new Date(a*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 Fo=async(a,t,e,n)=>{let r=n||[...st],o=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${o}::incentive_account_query::incentive_account_data`,c=new yc;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let l=(await a.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return l.pool_records.forEach(p=>{let m=Lo(p),{poolType:f}=m,y=a.utils.parseCoinNameFromType(f);r.length>=1&&r.includes(y)&&(u[y]=m)},{}),u};var Uo=async(a,t)=>{let e=a.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await a.client.getObject({id:e,options:{showContent:!0}});if(n.data){let r=n.data;if(r.content&&"fields"in r.content){let o=r.content.fields,i=Number(o.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(o.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(o.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),d=Number(o.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(d?-1:1)}}return 0};import ar from"bignumber.js";var $o=async(a,t)=>{let e=t,r=`${a.address.get("vesca.id")}::ve_sca::VeScaKey`,o=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:e,filter:{StructType:r},cursor:s});o.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);return o.map(d=>d.data).filter(d=>!!d)},qo=async(a,t)=>{let n=(await $o(a,t)).map(o=>o.objectId),r=[];for(let o=0;o<n.length;o++){let i=await rr(a,n[o]);i&&r.push(i)}return r},rr=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),r=t||(await $o(a,e))[0].objectId,o,s=(await a.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:r}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;o={id:s.objectId,keyId:r,lockedScaAmount:ar(c.locked_sca_amount).toNumber(),lockedScaCoin:ar(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:ar(c.unlock_at).toNumber()}}return o};var zn=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:r}=e;this.address=n,this.utils=r}async getObligations(t=this.params.walletAddress){return vt(this,t)}async getCoinAmounts(t,e){return vo(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return Ao(this,t,e)}async getMarketCoinAmounts(t,e){return Oo(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return Po(this,t,e)}async getPriceFromPyth(t){return Uo(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return Kt(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...it]){let e={};for(let n=0;n<t.length;n++){let r=t[n],o=await tr(this,r);o&&(e[r]=o)}return e}async getStakePool(t){return tr(this,t)}async getStakeRewardPools(t=[...it]){let e={};for(let n=0;n<t.length;n++){let r=await er(this,t[n]);r&&(e[t[n]]=r)}return e}async getStakeRewardPool(t){return er(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return Fo(this,t,e,n)}async getObligationCoinNames(t){let e=await Do(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),r=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...r])].map(s=>this.utils.parseCoinNameFromType(s))}};import{SUI_TYPE_ARG as Qo,normalizeStructTag as wc}from"@mysten/sui.js/utils";var Jn=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Gn(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+nr(e)}return nr(t)}parseCoinType(t){let e=Gn(t)?this.parseCoinName(t):t,n=To[e];return[B.usdc,B.usdt,B.eth,B.btc,B.sol,B.apt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Ja.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||pn,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=wc(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,r=t.match(n),o=t.includes("reserve::MarketCoin");e=r?.[1]||t;let i={[`${B.usdc}::coin::COIN`]:"usdc",[`${B.usdt}::coin::COIN`]:"usdt",[`${B.eth}::coin::COIN`]:"eth",[`${B.btc}::coin::COIN`]:"btc",[`${B.sol}::coin::COIN`]:"sol",[`${B.apt}::coin::COIN`]:"apt"},s={[`${Ja.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return o?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>fn[t];getBorrowIncentiveRewardCoinName=t=>Io[t];getCoinDecimal(t){return Co[t]}getCoinWrappedType(t){return t==="usdc"||t==="usdt"||t==="eth"||t==="btc"||t==="apt"||t==="sol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}parseSCoinType(t){return ko[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=Qo,n){let r=n,o=[],i=0,s=!0,c=null;for(;s&&i<t;){let d=await this.client.getCoins({owner:r,coinType:e,cursor:c});d.data.sort((l,u)=>parseInt(u.balance,10)-parseInt(l.balance,10));for(let l=0;l<d.data.length&&(o.push({objectId:d.data[l].coinObjectId,digest:d.data[l].digest,version:d.data[l].version,balance:d.data[l].balance}),i+=parseInt(d.data[l].balance,10),!(i>=t));l++);c=d.nextCursor,s=d.hasNextPage}if(!o.length)throw new Error("No valid coins found for the transaction.");return o}async selectCoinIds(t,e=Qo,n){return(await this.selectCoins(t,e,n)).map(o=>o.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 r=e.map(s=>t.object(s)),o=r[0];r.length>1&&t.mergeCoins(o,r.slice(1));let[i]=t.splitCoins(o,[t.pure(n)]);return[i,o]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),r=e?Math.max(e-n,0):0,o=0;if(r===0){let i=(t??1)*86400;o=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+r:r,126144e3);o=n+i}return Wo(o)}parseSCoinName(t){if(Gn(t)&&H.includes(t))return t;let e=`s${t}`;if(H.includes(e))return e}};import{SUI_CLOCK_OBJECT_ID as Ot,SUI_TYPE_ARG as Cc}from"@mysten/sui.js/utils";var gt=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await rr(t.query,n);return i||void 0}let r=j(e),o=await qo(t.query,r);if(o.length!==0)return o[0]},Ic=async(a,t)=>{let e=a.address.get("borrowIncentive.object"),n=a.address.get("borrowIncentive.incentivePools"),r=a.address.get("vesca.id"),{client:o}=a,i=await o.getObject({id:n,options:{showContent:!0}});if(i.data?.content?.dataType!=="moveObject")return!1;let c=i.data.content.fields.ve_sca_bind.fields.id.id,d=`${e}::typed_id::TypedID<${r}::ve_sca::VeScaKey>`,l=await o.getDynamicFieldObject({parentId:c,name:{type:d,value:t}});return l.data?.content?.dataType!=="moveObject"?!1:l.data.content.fields.value.fields.id},or=async(...a)=>{let[t,e,n,r]=a;if(a.length===4&&n&&r&&typeof n=="string"){let c=await Za(t.query,n);return{obligationId:n,obligationKey:r,obligationLocked:c}}let o=j(e),i=await vt(t.query,o);if(i.length===0)throw new Error(`No obligation found for sender ${o}`);let s=i.find(c=>c.id===n||c.keyId===r)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},Tc=async({builder:a,txBlock:t})=>{let e={borrowIncentivePkg:a.address.get("borrowIncentive.id"),query:a.address.get("borrowIncentive.query"),incentivePools:a.address.get("borrowIncentive.incentivePools"),incentiveAccounts:a.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:a.address.get("core.obligationAccessStore"),config:a.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},r={table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{stakeObligation:(o,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(o),t.object(e.obligationAccessStore),t.object(Ot)]})},stakeObligationWithVesca:(o,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(o),t.object(e.obligationAccessStore),t.object(r.config),t.object(r.treasury),t.object(r.table),t.object(s),t.object(Ot)]})},unstakeObligation:(o,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(o),t.object(Ot)]})},oldUnstakeObligation:(o,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(o),t.object(Ot)],typeArguments:[Cc]})},claimBorrowIncentive:(o,i,s)=>{let c=a.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(o),t.object(Ot)],typeArguments:[c]})},oldClaimBorrowIncentive(o,i,s){let c=a.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(o),t.object(Ot)],typeArguments:[c]})}}},N=async({builder:a,txBlock:t})=>{let e=await Tc({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,r)=>{let{obligationId:o,obligationKey:i,obligationLocked:s}=await or(a,t,n,r),c=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${ot}::user::unstake`||d.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(o,i)},unstakeObligationQuick:async(n,r)=>{let{obligationId:o,obligationKey:i,obligationLocked:s}=await or(a,t,n,r);s&&e.unstakeObligation(o,i)},stakeObligationWithVeScaQuick:async(n,r,o)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await or(a,t,n,r),d=!!t.blockData.transactions.find(async l=>l.kind==="MoveCall"&&(l.target===`${ot}::user::unstake`||l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||d){let l=await gt(a,t,o);if(l){let u=await Ic(a,l.keyId);!u||u===i?e.stakeObligationWithVesca(i,s,l.keyId):e.stakeObligation(i,s)}else e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,r,o)=>e.claimBorrowIncentive(r,o,n)}};import{SUI_CLOCK_OBJECT_ID as G}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as Zn}from"@mysten/sui.js/utils";import kc from"axios";var Vo={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};import{bcs as ir}from"@mysten/sui.js/bcs";import{SUI_CLOCK_OBJECT_ID as Xn}from"@mysten/sui.js/utils";var sr=16*1024,Yn=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 console.log(n.data?.content),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(),r=[];return t.forEach(o=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(ir.ser("vector<u8>",Array.from(o),{maxSize:sr}).toBytes()),e.object(Xn)]});r.push(i)}),r}async updatePriceFeeds(t,e,n){let r=await this.getPythPackageId(),o;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);[o]=t.moveCall({target:`${r}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(ir.ser("vector<u8>",Array.from(e[0]),{maxSize:sr}).toBytes()),s[0],t.object(Xn)]});let c=[],d=await this.getBaseUpdateFee(),l=t.splitCoins(t.gas,n.map(()=>t.pure(d))),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),[o]=t.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),o,t.object(m),l[u],t.object(Xn)]}),u++}return t.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[o],typeArguments:[`${r}::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 r=this.extractVaaBytesFromAccumulatorMessage(e[0]),o=await this.verifyVaas([r],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(ir.ser("vector<u8>",Array.from(e[0]),{maxSize:sr}).toBytes()),o[0],t.object(Xn)]})}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:r}=await this.getPriceTableInfo(),o=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${r}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!o.data||!o.data.content)return;if(o.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,o.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,r=t.readUint16BE(n),o=n+2;return t.subarray(o,o+r)}};var xc=async(a,t)=>(await kc.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(r=>Buffer.from(r,"base64")),Gt=async(a,t,e)=>{let n=e??[...new Set([...V,...mn])],r=a.isTestnet?["pyth"]:["pyth"];if(r.includes("pyth")){let i=new Yn(a.client,a.address.get("core.oracles.pyth.state"),a.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async d=>s.push(a.address.get(`core.coins.${d}.oracle.pyth.feed`))));let c=a.params.pythEndpoints??Vo[a.isTestnet?"testnet":"mainnet"];try{let d=await xc(c[0],s);await i.updatePriceFeeds(t,d,s)}catch(d){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${d}`)}}let o=[...new Set(n)];for(let i=0;i<o.length;i++)await vc(a,t,o[i],r)},vc=async(a,t,e,n)=>{let r=a.utils.parseCoinType(e);Ac(t,n,a.address.get("core.packages.xOracle.id"),a.address.get("core.oracles.xOracle"),a.address.get("core.packages.pyth.id"),a.address.get("core.oracles.pyth.registry"),a.address.get("core.oracles.pyth.state"),a.address.get(`core.coins.${e}.oracle.pyth.feedObject`),a.address.get("core.packages.switchboard.id"),a.address.get("core.oracles.switchboard.registry"),a.address.get(`core.coins.${e}.oracle.switchboard`),a.address.get("core.packages.supra.id"),a.address.get("core.oracles.supra.registry"),a.address.get("core.oracles.supra.holder"),r)},Ac=(a,t,e,n,r,o,i,s,c,d,l,u,p,m,f)=>{let y=Oc(a,e,n,f);return t.includes("pyth")&&Rc(a,r,y,i,s,o,f),t.includes("switchboard")&&_c(a,c,y,l,d,f),t.includes("supra")&&Dc(a,u,y,m,p,f),Pc(a,e,n,y,f),a},Oc=(a,t,e,n)=>{let r=typeof e=="string"?a.object(e):e,o=`${t}::x_oracle::price_update_request`,i=[n];return a.moveCall({target:o,arguments:[r],typeArguments:i})},Pc=(a,t,e,n,r)=>{let o=`${t}::x_oracle::confirm_price_update_request`,i=[r],s=typeof e=="string"?a.object(e):e;return a.moveCall({target:o,arguments:[s,n,a.object(Zn)],typeArguments:i}),a},Dc=(a,t,e,n,r,o)=>{let i=typeof n=="string"?a.object(n):n,s=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(Zn)],typeArguments:[o]})},_c=(a,t,e,n,r,o)=>{let i=typeof n=="string"?a.object(n):n,s=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(Zn)],typeArguments:[o]})},Rc=(a,t,e,n,r,o,i)=>{let s=typeof e=="string"?a.object(e):e,c=typeof n=="string"?a.object(n):n,d=typeof r=="string"?a.object(r):r,l=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,d,l,a.object(Zn)],typeArguments:[i]})};var lt=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("scoin.id")},n={};return await Promise.all(H.map(async r=>{let o=a.utils.getSCoinTreasury(r);n[r]=o})),{mintSCoin:(r,o)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[r]),typeof o!="string"?o:t.pure(o)],typeArguments:[a.utils.parseSCoinType(r),a.utils.parseUnderlyingSCoinType(r)]}),burnSCoin:(r,o)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[r]),typeof o!="string"?o:t.pure(o)],typeArguments:[a.utils.parseSCoinType(r),a.utils.parseUnderlyingSCoinType(r)]})}};var zt=async(...a)=>{let[t,e,n,r]=a;if(a.length===3&&n)return{obligationId:n};if(a.length===4&&n&&r)return{obligationId:n,obligationKey:r};let o=j(t),i=await vt(e.query,o);if(i.length===0)throw new Error(`No obligation found for sender ${o}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},jc=async({builder:a,txBlock:t})=>{let e={protocolPkg:a.address.get("core.packages.protocol.id"),market:a.address.get("core.market"),version:a.address.get("core.version"),coinDecimalsRegistry:a.address.get("core.coinDecimalsRegistry"),xOracle:a.address.get("core.oracles.xOracle")},r=`${a.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:(o,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(o),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(o,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(o),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(G)],typeArguments:[d]})},deposit:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(G)],typeArguments:[s]})},depositEntry:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(G)],typeArguments:[s]})},withdraw:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(G)],typeArguments:[s]})},withdrawEntry:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(G)],typeArguments:[s]})},borrow:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(G)],typeArguments:[d]})},borrowEntry:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(G)],typeArguments:[d]})},borrowWithReferral:(o,i,s,c,d)=>{let l=a.utils.parseCoinType(d);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(G)],typeArguments:[l,r]})},repay:(o,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(o),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(G)],typeArguments:[c]})},borrowFlashLoan:(o,i)=>{let s=a.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(o)],typeArguments:[s]})},repayFlashLoan:(o,i,s)=>{let c=a.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(o),t.object(i)],typeArguments:[c]})}}},E=async({builder:a,txBlock:t})=>{let e=await jc({builder:a,txBlock:t}),n=await lt({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(r,o,i)=>{let s=j(t),{obligationId:c}=await zt(t,a,i);if(o==="sui"){let[d]=t.splitCoins(t.gas,[r]);e.addCollateral(c,d,o)}else{let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,o,r,s);e.addCollateral(c,l,o),t.transferObjects([d],s)}},takeCollateralQuick:async(r,o,i,s)=>{let c=await zt(t,a,i,s),d=await a.query.getObligationCoinNames(c.obligationId);return await Gt(a,t,d),e.takeCollateral(c.obligationId,c.obligationKey,r,o)},depositQuick:async(r,o,i)=>{if(o==="sui"){let[d]=t.splitCoins(t.gas,[r]);return e.deposit(d,o)}let{leftCoin:s,takeCoin:c}=await a.selectCoin(t,o,r,i);return t.transferObjects([s],i),e.deposit(c,o)},withdrawQuick:async(r,o)=>{let i=j(t),s=a.utils.parseMarketCoinName(o);try{let c=a.utils.parseSCoinName(o);if(!c)throw new Error(`No sCoin for ${o}`);let{leftCoin:d,takeCoin:l,totalAmount:u}=await a.selectSCoin(t,c,r,i);t.transferObjects([d],i);let p=n.burnSCoin(c,l),m=e.withdraw(p,o),f=r-u;try{if(f>0){let{leftCoin:y,takeCoin:k}=await a.selectMarketCoin(t,s,f,i);t.transferObjects([y],i),t.mergeCoins(m,[e.withdraw(k,o)])}}catch{}return m}catch{let{leftCoin:d,takeCoin:l}=await a.selectMarketCoin(t,s,r,i);return t.transferObjects([d],i),e.withdraw(l,o)}},borrowQuick:async(r,o,i,s)=>{let c=await zt(t,a,i,s),l=[...await a.query.getObligationCoinNames(c.obligationId),o];return await Gt(a,t,l),e.borrow(c.obligationId,c.obligationKey,r,o)},borrowWithReferralQuick:async(r,o,i,s,c)=>{let d=await zt(t,a,s,c),u=[...await a.query.getObligationCoinNames(d.obligationId),o];return await Gt(a,t,u),e.borrowWithReferral(d.obligationId,d.obligationKey,i,r,o)},repayQuick:async(r,o,i,s)=>{let c=await zt(t,a,i);if(o==="sui"){let[u]=t.splitCoins(t.gas,[r]);return e.repay(c.obligationId,u,o)}let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,o,r,s);return t.transferObjects([d],s),e.repay(c.obligationId,l,o)},updateAssetPricesQuick:async r=>Gt(a,t,r)}};import{SUI_CLOCK_OBJECT_ID as ta}from"@mysten/sui.js/utils";var ea=async({builder:a,txBlock:t})=>{let e={referralPgkId:a.address.get("referral.id"),referralBindings:a.address.get("referral.referralBindings"),referralRevenuePool:a.address.get("referral.referralRevenuePool"),authorizedWitnessList:a.address.get("referral.authorizedWitnessList"),referralTiers:a.address.get("referral.referralTiers"),version:a.address.get("referral.version")},n=a.address.get("vesca.table");return{bindToReferral:r=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(r),t.object(n),t.object(ta)],typeArguments:[]}),claimReferralTicket:r=>{let o=a.utils.parseCoinType(r);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(ta)],typeArguments:[o]})},burnReferralTicket:(r,o)=>{let i=a.utils.parseCoinType(o);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(r),t.object(e.referralRevenuePool),t.object(ta)],typeArguments:[i]})},claimReferralRevenue:(r,o)=>{let i=a.utils.parseCoinType(o);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(r),t.object(ta)],typeArguments:[i]})}}},Ho=async({builder:a,txBlock:t})=>{let e=await ea({builder:a,txBlock:t});return{claimReferralRevenueQuick:async(n,r,o=[...V])=>{let i=[];for(let s=0;s<o.length;s++)if(o[s]==="sui"){let c=e.claimReferralRevenue(n,o[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,o[s]);try{let d=await a.utils.selectCoinIds(1/0,a.utils.parseCoinType(o[s]),r);t.mergeCoins(c,d.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(r))}}};import{SUI_CLOCK_OBJECT_ID as na}from"@mysten/sui.js/utils";var Ko=async(a,t,e,n,r,o,i=!1)=>{let s=await lt({builder:a,txBlock:t}),c=await zo({builder:a,txBlock:t});try{let{takeCoin:d,leftCoin:l,totalAmount:u}=i?await a.selectSCoin(t,n,r,o):await a.selectMarketCoin(t,n,r,o);if(i){let p=s.burnSCoin(n,d);c.stake(e,p,n)}else c.stake(e,d,n);return t.transferObjects([l],o),u}catch{return 0}},Go=async(...a)=>{let[t,e,n,r]=a;if(a.length===4&&r)return[r];let o=j(e),i=await Kt(t.query,o);if(i[n].length===0)throw new Error(`No stake account id found for sender ${o}`);return i[n].map(s=>s.id)},Nc=async(...a)=>{let[t,e,n,r]=a,o=j(e),i=await Kt(t.query,o);if(i[n].length===0)throw new Error(`No stake account found for sender ${o}`);return r?i[n].filter(c=>c.id===r):i[n]},zo=async({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")},n={},r={},o={};return it.forEach(i=>{let s=a.address.get(`spool.pools.${i}.id`),c=a.address.get(`spool.pools.${i}.rewardPoolId`),d=a.utils.parseMarketCoinType(i);n[i]=s,r[i]=c,o[i]=d}),{createStakeAccount:i=>{let s=o[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(na)],typeArguments:[s]})},stake:(i,s,c)=>{let d=o[c],l=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(l),t.object(i),typeof s=="string"?t.pure(s):s,t.object(na)],typeArguments:[d]})},unstake:(i,s,c)=>{let d=o[c],l=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(l),t.object(i),t.pure(s),t.object(na)],typeArguments:[d]})},claim:(i,s)=>{let c=n[s],d=r[s],l=o[s],u=fn[s],p=a.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(d),t.object(i),t.object(na)],typeArguments:[l,p]})}}},dt=async({builder:a,txBlock:t})=>{let e=await zo({builder:a,txBlock:t}),n=await lt({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(r,o,i)=>{let s=j(t),c=await Go(a,t,o,i);if(typeof r=="number"){let d=await Ko(a,t,c[0],o,r,s);r-=d,d||await Ko(a,t,c[0],o,r,s,!0)}else e.stake(c[0],r,o)},unstakeQuick:async(r,o,i,s)=>{let c=await Nc(a,t,o,i),d=[],l=r;for(let u of c){if(u.staked===0)continue;let p=Math.min(l,u.staked),m=e.unstake(u.id,p,o);if(s){let f=n.mintSCoin(o,m);d.push(f)}else d.push(m);if(l-=p,r<=0)break}if(d.length>0){let u=d[0];return d.length>1&&t.mergeCoins(u,d.slice(1)),u}},claimQuick:async(r,o)=>{let i=await Go(a,t,r,o),s=[];return i.forEach(c=>{let d=e.claim(c,r);s.push(d)}),s}}};import{SUI_CLOCK_OBJECT_ID as Jt}from"@mysten/sui.js/utils";var Bc=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("vesca.id"),table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{lockSca:(n,r)=>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(r),t.object(Jt)]}),extendLockPeriod:(n,r)=>{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(r),t.object(Jt)]})},extendLockAmount:(n,r)=>{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 r=="string"?t.pure(r):r,t.object(Jt)]})},renewExpiredVeSca:(n,r,o)=>{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 r=="string"?t.pure(r):r,t.pure(o),t.object(Jt)]})},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(Jt)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},ut=async({builder:a,txBlock:t})=>{let e=await Bc({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,r,o=!0)=>{let i=j(t),s=await gt(a,t),c,d=[];if(n!==void 0&&typeof n=="number"){let m=await a.utils.selectCoinIds(n,rt,i),[f,y]=a.utils.takeAmountFromCoins(t,m,n);c=f,d.push(y)}else c=n;let l=a.utils.getUnlockAt(r,s?.unlockAt);o&&jo(n,r,l,s?.unlockAt),console.log(new Date(l*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,l);d.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);d.push(m)}e.renewExpiredVeSca(s.keyId,c,l)}}else c&&r?(e.extendLockPeriod(s.keyId,l),e.extendLockAmount(s.keyId,c)):r?e.extendLockPeriod(s.keyId,l):c&&e.extendLockAmount(s.keyId,c);d.length>0&&t.transferObjects(d,i)},extendLockPeriodQuick:async(n,r,o=!0)=>{let i=await gt(a,t,r),s=a.utils.getUnlockAt(n);o&&No(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,r,o=!0)=>{let i=j(t),s=await gt(a,t,r);if(o&&Bo(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,rt,i),[d,l]=a.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,d),t.transferObjects([l],i)}},renewExpiredVeScaQuick:async(n,r,o,i=!0)=>{let s=j(t),c=await gt(a,t,o),d=a.utils.getUnlockAt(r,c?.unlockAt);if(i&&Eo(n,r,c?.unlockAt),c){let l=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);l.push(f)}let u=await a.utils.selectCoinIds(n,rt,s),[p,m]=a.utils.takeAmountFromCoins(t,u,n);l.push(m),e.renewExpiredVeSca(c.keyId,p,d),t.transferObjects(l,s)}},redeemScaQuick:async n=>{let r=j(t),o=await gt(a,t,n);if(At(o?.unlockAt),o){let i=e.redeemSca(o.keyId);t.transferObjects([i],r)}}}};var aa=class{params;client;address;builder;query;utils;walletAddress;constructor(t,e){this.params=t,this.client=t.client,this.address=e,this.utils=new Jn(t,this.address),this.query=new zn(t,{address:this.address,utils:this.utils}),this.builder=new Vn(t,{address:this.address,query:this.query,utils: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 I,n=await E({builder:this.builder,txBlock:e}),r=await N({builder:this.builder,txBlock:e}),o=t||this.params.walletAddress;e.setSender(o);let[i,s,c]=n.normalMethod.openObligation();return r.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],o),e}async depositCollateral(t,e,n,r){let o=new I,i=r||this.params.walletAddress;o.setSender(i);let s=await E({builder:this.builder,txBlock:o}),c=await this.query.getObligations(i),d=n||c?.[0]?.id;if(d)await s.addCollateralQuick(e,t,d);else{let[l,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,l),s.normalMethod.returnObligation(l,p),o.transferObjects([u],i)}return o}async withdrawCollateral(t,e,n,r,o){let i=new I,s=await E({builder:this.builder,txBlock:i}),c=o||this.params.walletAddress;i.setSender(c);let d=await s.takeCollateralQuick(e,t,n,r);return i.transferObjects([d],c),i}async deposit(t,e,n){let r=new I,o=await E({builder:this.builder,txBlock:r}),i=await lt({builder:this.builder,txBlock:r}),s=n||this.params.walletAddress;r.setSender(s);let c=await o.depositQuick(e,t,n),d=this.utils.parseMarketCoinName(t);if(!H.includes(d))r.transferObjects([c],s);else{let l=i.mintSCoin(d,c);r.transferObjects([l],s)}return r}async withdraw(t,e,n){let r=new I,o=n||this.params.walletAddress,i=await E({builder:this.builder,txBlock:r});r.setSender(o);let s=await i.withdrawQuick(e,t);return r.transferObjects([s],o),r}async borrow(t,e,n,r,o){let i=new I,s=await E({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=st.includes(t);l&&await c.unstakeObligationQuick(n,r);let u=await s.borrowQuick(e,t,n,r);return i.transferObjects([u],d),l&&await c.stakeObligationQuick(n,r),i}async borrowWithBoost(t,e,n,r,o,i){let s=new I,c=await E({builder:this.builder,txBlock:s}),d=await N({builder:this.builder,txBlock:s}),l=i||this.params.walletAddress;s.setSender(l);let u=st.includes(t);u&&await d.unstakeObligationQuick(n,r);let p=await c.borrowQuick(e,t,n,r);return s.transferObjects([p],l),u&&await d.stakeObligationWithVeScaQuick(n,r,o),s}async borrowWithReferral(t,e,n,r,o,i){let s=new I,c=await E({builder:this.builder,txBlock:s}),d=await N({builder:this.builder,txBlock:s}),l=await ea({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=st.includes(t);p&&await d.unstakeObligationQuick(n,r);let m=l.claimReferralTicket(t),f=await c.borrowWithReferralQuick(e,t,m,n,r);return l.burnReferralTicket(m,t),s.transferObjects([f],u),p&&o?await d.stakeObligationWithVeScaQuick(n,r,o):await d.stakeObligationQuick(n,r),s}async repay(t,e,n,r,o){let i=new I,s=await E({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=st.includes(t);return l&&await c.unstakeObligationQuick(n,r),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationQuick(n,r),i}async repayWithBoost(t,e,n,r,o){let i=new I,s=await E({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=st.includes(t);return l&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationWithVeScaQuick(n,void 0,r),i}async createStakeAccount(t,e){let n=new I,r=await dt({builder:this.builder,txBlock:n}),o=e||this.params.walletAddress;n.setSender(o);let i=r.normalMethod.createStakeAccount(t);return n.transferObjects([i],o),n}async supplyAndStake(t,e,n,r){let o=new I,i=await E({builder:this.builder,txBlock:o}),s=await dt({builder:this.builder,txBlock:o}),c=r||this.params.walletAddress;o.setSender(c);let d=await i.depositQuick(e,t,r),l=this.utils.parseMarketCoinName(t);if(!it.find(m=>m===l))return o;let u=await this.query.getStakeAccounts(l,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(d,l,p);else{let m=s.normalMethod.createStakeAccount(l);await s.stakeQuick(d,l,m),o.transferObjects([m],c)}return o}async unstakeAndWithdraw(t,e,n){let r=new I,o=await E({builder:this.builder,txBlock:r}),i=await dt({builder:this.builder,txBlock:r}),s=this.params.walletAddress,c=[];r.setSender(s);let d=this.utils.parseMarketCoinName(t);for(let l=0;l<n.length;l++){let u=n[l],[p]=await i.unstakeQuick(u.coin,d,u.id);if(p){let m=o.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let l=await o.withdrawQuick(e,t);c.push(l)}return r.transferObjects(c,s),r}async stake(t,e,n,r){let o=new I,i=await dt({builder:this.builder,txBlock:o}),s=r||this.params.walletAddress;o.setSender(s);let c=await this.query.getStakeAccounts(t,s),d=n||(c.length>0?c[0].id:void 0);if(d)await i.stakeQuick(e,t,d);else{let l=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,l),o.transferObjects([l],s)}return o}async unstake(t,e,n,r){let o=new I,i=await dt({builder:this.builder,txBlock:o}),s=r||this.params.walletAddress;o.setSender(s);let c=H.includes(t),d=await i.unstakeQuick(e,t,n,c);return o.transferObjects([d],o.pure(s)),o}async claim(t,e,n,r){let o=new I,i=await dt({builder:this.builder,txBlock:o}),s=await N({builder:this.builder,txBlock:o}),c=r||this.params.walletAddress;o.setSender(c);let d={sui:[],sca:[]};for(let l=0;l<t.length;l++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[l],m=i.normalMethod.claim(p,u);d.sui.push(m)}for(let l=0;l<e.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[l],f=s.normalMethod.claimBorrowIncentive(u,p,m);d[m].push(f)}for(let l=0;l<n.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[l],f=s.normalMethod.oldClaimBorrowIncentive(u,p,m);d[m].push(f)}return d.sui.length>0&&(d.sui.length>1&&o.mergeCoins(d.sui[0],d.sui.slice(1)),o.transferObjects([d.sui[0]],o.pure(c))),d.sca.length>0&&(d.sca.length>1&&o.mergeCoins(d.sca[0],d.sca.slice(1)),o.transferObjects([d.sca[0]],o.pure(c))),o}async stakeObligation(t,e,n){let r=this.builder.createTxBlock(),o=await N({builder:this.builder,txBlock:r}),i=n||this.params.walletAddress;return r.setSender(i),await o.stakeObligationQuick(t,e),r}async unstakeObligation(t,e,n){let r=this.builder.createTxBlock(),o=await N({builder:this.builder,txBlock:r}),i=n||this.params.walletAddress;return r.setSender(i),await o.unstakeObligationQuick(t,e),r}async stakeSca(t,e=!1,n=!1,r,o,i,s,c){let d=new I,l=await ut({builder:this.builder,txBlock:d}),u=await N({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,rt,p),[f,y]=this.builder.utils.takeAmountFromCoins(d,m,t),k;return s?l.normalMethod.extendLockAmount(s,f):k=l.normalMethod.lockSca(f,i),r&&o&&(e&&(n?u.normalMethod.oldUnstakeObligation(r,o):u.normalMethod.unstakeObligation(r,o)),u.normalMethod.stakeObligationWithVesca(r,o,s||k)),s||d.transferObjects([k,y],p),d}async stakeMoreSca(t,e,n){let r=new I,o=n||this.params.walletAddress;return r.setSender(o),r}async extendStakeScaLockPeriod(t,e,n,r,o=!1,i=!1,s){let c=new I,d=await ut({builder:this.builder,txBlock:c}),l=await N({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),d.normalMethod.extendLockPeriod(e,t),n&&r&&(o&&(i?l.normalMethod.oldUnstakeObligation(n,r):l.normalMethod.unstakeObligation(n,r)),l.normalMethod.stakeObligationWithVesca(n,r,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,r,o,i=!1,s=!1,c){let d=new I,l=await ut({builder:this.builder,txBlock:d}),u=await N({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,rt,p),[f,y]=this.builder.utils.takeAmountFromCoins(d,m,t);return l.normalMethod.extendLockPeriod(e,n),l.normalMethod.extendLockAmount(e,f),d.transferObjects([y],p),!r||!o||(i&&(s?u.normalMethod.oldUnstakeObligation(r,o):u.normalMethod.unstakeObligation(r,o)),u.normalMethod.stakeObligationWithVesca(r,o,e)),d}async renewExpiredStakeSca(t,e,n,r=!1,o,i,s=!1,c=!1,d){let l=new I,u=await ut({builder:this.builder,txBlock:l}),p=await N({builder:this.builder,txBlock:l}),m=d||this.params.walletAddress;if(l.setSender(m),r){let D=u.normalMethod.redeemSca(n);l.transferObjects([D],m)}let f=await this.builder.utils.selectCoinIds(t,rt,m),[y,k]=this.builder.utils.takeAmountFromCoins(l,f,t);return l.transferObjects([k],m),u.normalMethod.renewExpiredVeSca(n,y,e),!o||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(o,i):p.normalMethod.unstakeObligation(o,i)),p.normalMethod.stakeObligationWithVesca(o,i,n)),l}async redeemSca(t){let e=new I,n=await ut({builder:this.builder,txBlock:e}),r=this.params.walletAddress;return e.setSender(r),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,r){let o=new I,i=await N({builder:this.builder,txBlock:o}),s=this.params.walletAddress;o.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return o.transferObjects([c],s),await i.unstakeObligationQuick(e,t),r?await i.stakeObligationWithVeScaQuick(e,t,r):await i.stakeObligationQuick(e,t),o}async withdrawUnlockedSca(t,e){let n=new I,r=await ut({builder:this.builder,txBlock:n}),o=e||this.params.walletAddress;return n.setSender(o),await r.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new Jo(t.weightedAmount),o=e.currentPointIndex?Jo(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(o).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new I,e=await ut({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let r=e.normalMethod.mintEmptyVeSca();return t.transferObjects([r],n),t}async claimRevenuReferral(t,e){let n=new I,r=await Ho({builder:this.builder,txBlock:n}),o=this.params.walletAddress;n.setSender(o);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await r.claimReferralRevenueQuick(t,o,i),n}async bindReferral(t){let e=new I,n=await ea({builder:this.builder,txBlock:e}),r=this.params.walletAddress;return e.setSender(r),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new I,e=await lt({builder:this.builder,txBlock:t}),n=await dt({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let r=[];return await Promise.all(H.map(async o=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(o),this.params.walletAddress),d=c[0];c.length>1&&t.mergeCoins(d,c.slice(1)),s=d}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(o,s);try{let d=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(o),this.params.walletAddress);t.mergeCoins(c,d)}catch(d){console.log(d)}i.push(c)}if(it.includes(o))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,o);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)),r.push(c)}})),r.length>0&&t.transferObjects(r,this.params.walletAddress),t}};var Xt=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Qn({id:yo})),await this.address.read(),this.client=new aa(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var ra=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new Xt({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new bn(e,this.scallop),r=new gn(e,this.scallop),o=new hn(e,this.scallop),i=n.decode()||r.decode()||o.decode();if(!i)throw new Error("Unknown transaction type");return{txType:Ec.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:r,txSubType:o,intentionData:i}=t;this.scallop||(this.scallop=new Xt({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(o){case"SupplyLending":s=Pn.fromData(i);break;case"WithdrawLending":s=jn.fromData(i);break;case"Borrow":s=Sn.fromData(i);break;case"Repay":s=vn.fromData(i);break;case"DepositCollateral":s=In.fromData(i);break;case"WithdrawCollateral":s=Rn.fromData(i);break;case"OpenObligation":s=xn.fromData(i);break;case"StakeSpool":s=On.fromData(i);break;case"UnstakeSpool":s=Dn.fromData(i);break;case"ClaimIncentiveReward":s=Cn.fromData(i);break;case"BorrowWithBoost":s=yn.fromData(i);break;case"StakeSca":s=Un.fromData(i);break;case"ExtendStakePeriod":s=Ln.fromData(i);break;case"ExtendPeriodAndStakeMore":s=Mn.fromData(i);break;case"RenewExpStakePeriod":s=Fn.fromData(i);break;case"WithdrawStakedSca":s=qn.fromData(i);break;case"SupplyAndStakeLending":s=$n.fromData(i);break;case"WithdrawAndUnstakeLending":s=_n.fromData(i);break;case"RedeemSca":s=Wn.fromData(i);break;case"MigrateAndClaim":s=Tn.fromData(i);break;case"BorrowWithReferral":s=wn.fromData(i);break;case"CreateReferralLink":s=En.fromData(i);break;case"ClaimRevenueReferral":s=Bn.fromData(i);break;case"BindReferral":s=Nn.fromData(i);break;case"MigrateScoin":s=kn.fromData(i);break;case"RepayWithBoost":s=An.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:r,scallop:this.scallop})}};import{TransactionType as al}from"@msafe/sui3-utils";import{TurbosSdk as rl}from"turbos-clmm-sdk";import{TransactionType as W}from"@msafe/sui3-utils";import{bcs as Xo}from"@mysten/sui.js/bcs";import{normalizeStructTag as Lc,normalizeSuiAddress as Yt}from"@mysten/sui.js/utils";import{BN as Wc}from"turbos-clmm-sdk";var F={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},U={PackageId:"0xdee9"};var Fc=(a,t,e,n)=>{if(a===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(o=>o===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},oa=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(`${F.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${F.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${U.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${U.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=Fc(e,t.target,this.swap1Layer,this.swap2Layer),r=n.map((m,f)=>{let y=this.helper.decodeSharedObjectId(f),k=this.helper.decodeInputU128(4+f+e),D=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Wc(k.toString()));return{pool:y,a2b:m,nextTickIndex:D}}),o=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),d=this.helper.decodeInputBool(5+2*e),l=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:r[0].pool,a2b:r[0].a2b,amountSpecified:l}],address:s,amountSpecifiedIsInput:d});return{txType:W.Other,type:"Swap",intentionData:{routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:d?l:u,amountB:d?u:l,amountSpecifiedIsInput:d,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),r=this.helper.decodeInputU64(9),o=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),d=this.helper.decodeInputU64(13);return{txType:W.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:r,tickLower:i?-o:o,tickUpper:c?-s:s,deadline:d}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),r=this.helper.decodeInputU64(5),o=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:W.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:r,amountB:o,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),r=this.helper.decodeInputU64(3),o=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:W.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:r,nft:n,amountA:o,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),r=this.helper.decodeInputU64(3),o=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:W.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:r,collectAmountB:o,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),r=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),o=this.helper.decodeInputU64(7);return{txType:W.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:r,nft:e,deadline:o}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:W.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),r=this.decreaseLiquidityHelper.decodeInputU64(3),o=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),d=this.collectFeeHelper.decodeInputU64(3)||0,l=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:W.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:r,nft:n,amountA:o,amountB:i,slippage:10,address:t,collectAmountA:d,collectAmountB:l,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:W.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:W.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),r=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:W.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:r}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),r=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:W.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:r}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new pt(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 pt(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new pt(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 pt(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${U.PackageId}::clob_v2::swap_exact_base_for_quote`);return new pt(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${U.PackageId}::clob_v2::swap_exact_quote_for_base`);return new pt(t,this.txb)}},pt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Yt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 Xo.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 Yt(t.value.Object.ImmOrOwned.objectId)}return Yt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Yt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Yt(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 Xo.de(e,new Uint8Array(n))}typeArg(t){return Lc(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as Uc}from"turbos-clmm-sdk";var ia=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Uc(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,tickLower:d,tickUpper:l,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,tickLower:d,tickUpper:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as $c}from"turbos-clmm-sdk";var sa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new $c(e.network.replace("sui:",""),e.suiClient),{pool:r,nft:o,txb:i}=this.data;return n.nft.burn({pool:r,nft:o,txb:i})}static fromData(e){return new a(e)}};import{TurbosSdk as qc}from"turbos-clmm-sdk";var ca=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new qc(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,nft:i,collectAmountA:s,collectAmountB:c,deadline:d,txb:l}=this.data;return n.pool.collectFee({pool:r,address:o,collectAmountA:s,collectAmountB:c,nft:i,deadline:d,txb:l})}static fromData(e){return new a(e)}};import{TurbosSdk as Qc}from"turbos-clmm-sdk";var la=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Qc(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,nft:i,rewardAmounts:s,deadline:c,txb:d}=this.data;return n.pool.collectReward({pool:r,address:o,rewardAmounts:s,nft:i,deadline:c,txb:d})}static fromData(e){return new a(e)}};import{TurbosSdk as Vc}from"turbos-clmm-sdk";var da=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Vc(e.network.replace("sui:",""),e.suiClient),{fee:r,address:o,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,amountA:p,amountB:m,deadline:f,txb:y}=this.data;return n.pool.createPool({fee:r,amountA:p,amountB:m,address:o,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,deadline:f,txb:y})}static fromData(e){return new a(e)}};import{TurbosSdk as Hc}from"turbos-clmm-sdk";var ua=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Hc(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,nft:d,decreaseLiquidity:l,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,nft:d,decreaseLiquidity:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as Kc}from"turbos-clmm-sdk";var pa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Kc(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,nft:d,deadline:l,txb:u}=this.data;return n.pool.increaseLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,nft:d,deadline:l,txb:u})}static fromData(e){return new a(e)}};import{TransactionBlock as Gc}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as zc}from"@mysten/sui.js/utils";var ma=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Gc;return n.moveCall({target:`${F.PackageId}::claim::claim`,typeArguments:[F.turbosCoinType],arguments:[n.object(F.Claim),n.object(zc)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Jc}from"@mysten/sui.js/transactions";var fa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Jc;return n.moveCall({target:`${F.PackageId}::claim::join`,typeArguments:[F.turbosCoinType],arguments:[n.object(F.Claim)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Xc}from"@mysten/sui.js/transactions";import{TurbosSdk as Yc}from"turbos-clmm-sdk";var ba=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Yc(e.network.replace("sui:",""),e.suiClient),r=new Xc;return r=await n.pool.collectFee({txb:r,...this.data}),r=await n.pool.collectReward({txb:r,...this.data}),r=await n.pool.decreaseLiquidity({txb:r,...this.data}),r=await n.nft.burn({txb:r,nft:this.data.nft,pool:this.data.pool}),r}static fromData(e){return new a(e)}};import{TurbosSdk as Zc}from"turbos-clmm-sdk";var ga=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new Zc(e.network.replace("sui:",""),e.suiClient),{routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:c,amountB:d,slippage:l,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:c,amountB:d,amountSpecifiedIsInput:u,slippage:l,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as el}from"turbos-clmm-sdk";import{normalizeSuiObjectId as Yo}from"@mysten/sui.js/utils";import{TransactionBlock as Zo}from"@mysten/sui.js/transactions";import{unstable_getObjectId as tl}from"turbos-clmm-sdk";var Zt=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let r=[],o;do o=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:o?.nextCursor}),r.push(...o.data);while(o.hasNextPage);let i=[],s=0;return r.sort((c,d)=>Number(d.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 r=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(r,t.slice(1).map(i=>n.object(i.coinObjectId)));let[o]=n.splitCoins(r,[n.pure(e)]);return[o,r]}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:`${U.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?tl(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${U.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var ti=89,ei=1e6,ni=async a=>{let{token1:t,token2:e,poolId:n,amountIn:r,currentAddress:o,turbosSdk:i}=a,s=new Zo,c=new Zt(i),d=await c.getCoinsData(o,e,r),[l,u]=c.splitAndMergeCoin(d,r,s);if(!l)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(o),m=p?s.object(p):c.createAccount(s),[f,y,k]=s.moveCall({typeArguments:[t,e],target:`${U.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(ti),m,s.pure(r),s.object(Yo("0x6")),l]});return u&&s.transferObjects([u],s.pure(o)),s.transferObjects([f],s.pure(o)),s.transferObjects([y],s.pure(o)),p||s.transferObjects([m],s.pure(o)),s.setSenderIfNotSet(o),s.setGasBudget(ei),s},ai=async a=>{let{token1:t,token2:e,poolId:n,amountIn:r,currentAddress:o,turbosSdk:i}=a,s=new Zo,c=new Zt(i),d=await c.getCoinsData(o,t,r),[l,u]=c.splitAndMergeCoin(d,r,s);if(!l)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(o),m=p?s.object(p):c.createAccount(s),f=c.zero(e,s),[y,k,D]=s.moveCall({typeArguments:[t,e],target:`${U.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(ti),m,s.pure(r),l,f,s.object(Yo("0x6"))]});return u&&s.transferObjects([u],s.pure(o)),s.transferObjects([y],s.pure(o)),s.transferObjects([k],s.pure(o)),p||s.transferObjects([m],s.pure(o)),s.setSenderIfNotSet(o),s.setGasBudget(ei),s};var ha=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new el(e.network.replace("sui:",""),e.suiClient);return await ai({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};import{TurbosSdk as nl}from"turbos-clmm-sdk";var Sa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new nl(e.network.replace("sui:",""),e.suiClient);return await ni({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var ya=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new rl(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:r,account:o}=t;console.log(t,"input");let s=await new oa(r,e,n).decode(o.address);return{txType:al.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:r}=t,o;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":o=da.fromData(t.intentionData);break;case"AddLiquidity":o=ia.fromData(t.intentionData);break;case"IncreaseLiquidity":o=pa.fromData(t.intentionData);break;case"DecreaseLiquidity":o=ua.fromData(t.intentionData);break;case"RemoveLiquidity":o=ba.fromData(t.intentionData);break;case"CollectFee":o=ca.fromData(t.intentionData);break;case"CollectReward":o=la.fromData(t.intentionData);break;case"Burn":o=sa.fromData(t.intentionData);break;case"Swap":o=ga.fromData(t.intentionData);break;case"PrixJoin":o=fa.fromData(t.intentionData);break;case"PrixClaim":o=ma.fromData(t.intentionData);break;case"SwapExactBaseForQuote":o=ha.fromData(t.intentionData);break;case"SwapExactQuoteForBase":o=Sa.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n,network:r})}};import{TransactionType as ul}from"@msafe/sui3-utils";import{TransactionType as cr}from"@msafe/sui3-utils";import{bcs as ri}from"@mysten/sui.js/bcs";import{normalizeStructTag as sl,normalizeSuiAddress as te}from"@mysten/sui.js/utils";var ol={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},A=ol;var wa=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(`${A.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${A.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${A.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:cr.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:cr.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:cr.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(A.packageId));return new lr(t,this.txb)}},lr=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 te(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 ri.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 te(t.value.Object.ImmOrOwned.objectId)}return te(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return te(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return te(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 ri.de(e,new Uint8Array(n))}typeArg(t){return sl(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as cl}from"@mysten/sui.js/transactions";var Ca=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new cl,{ticketId:r}=this.data;return n.moveCall({target:`${A.packageId}::native_pool::burn_ticket`,arguments:[n.object(A.poolObjectId),n.object(A.systemStateObjectId),n.object(r)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as ll}from"@mysten/sui.js/transactions";var Ia=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new ll,{amount:r}=this.data,[o]=n.splitCoins(n.gas,[n.pure(r)]);return n.moveCall({target:`${A.packageId}::native_pool::stake`,arguments:[n.object(A.poolObjectId),n.object(A.metadataObjectId),n.object(A.systemStateObjectId),o]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as dl}from"@mysten/sui.js/transactions";var Ta=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new dl,{amount:r}=this.data,o=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=o.filter(l=>l.coinType.split("::")[0]===A.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(l=>n.object(l.coinObjectId)));let d=n.splitCoins(n.object(i.coinObjectId),[n.pure(r)]);return n.moveCall({target:`${A.packageId}::native_pool::unstake`,arguments:[n.object(A.poolObjectId),n.object(A.metadataObjectId),n.object(A.systemStateObjectId),d]}),n}static fromData(e){return new a(e)}};var ka=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,r=new wa(e).decode();return{txType:ul.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n}=t,r;switch(t.txSubType){case"Stake":r=Ia.fromData(t.intentionData);break;case"UnStake":r=Ta.fromData(t.intentionData);break;case"ClaimTicket":r=Ca.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};var ox=un.fromHelpers([new Ye,new ln,new Ge,new dn,new Ie,new ya,new ra,new ka]);export{ox as appHelpers};
1
+ var gi=Object.defineProperty;var gr=(a,t)=>{for(var e in t)gi(a,e,{get:t[e],enumerable:!0})};import{TransactionType as Zi}from"@msafe/sui3-utils";import{TransactionType as Oi}from"@msafe/sui3-utils";import hi from"sort-keys-recursive";var S=class{constructor(t){this.data=t}serialize(){return JSON.stringify(hi(this.data))}};import{AggregatorClient as Si,Env as yi}from"@cetusprotocol/aggregator-sdk";import{CetusPeripherySDK as wi}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as Ci}from"@cetusprotocol/cetus-sui-clmm-sdk";import{SuiClient as Ii}from"@mysten/sui/client";var Ti={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:"0x6f5e582ede61fe5395b50c4a449ec11479a54d7ff8e0158247adfda60d98970b",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"},ki={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:"0x016b8ce6560f55bfe02abb2cc0681bb91f767107cfb1c9b6e73a6bcf74492a02",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:""}}},vi={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"},xi={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:""}}},mt=(a,t)=>{let e=a==="sui:mainnet"?Ti:vi,n=new Ci(e);return n.senderAddress=t.address,n},j=(a,t)=>{let e=mt(a,t),n=a==="sui:mainnet"?ki:xi;return new wi(n,e)},Ai="https://api-sui.cetus.zone/router_v2/find_routes",hr=(a,t)=>{let e=new Ii({url:"https://fullnode.mainnet.sui.io/"});return new Si(Ai,t.address,e,yi.Mainnet)};var Sr=async(a,t,e)=>await mt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),yr=async(a,t,e)=>await mt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),wr=async(a,t,e)=>await mt(e,t).Position.closePositionTransactionPayload(a),Cr=async(a,t,e)=>await mt(e,t).Position.removeLiquidityTransactionPayload(a),Ir=async(a,t,e)=>await mt(e,t).Rewarder.collectRewarderTransactionPayload(a);var ne=class a extends S{constructor(e){super(e);this.data=e}txType=Oi.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Sr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Pi}from"@msafe/sui3-utils";var ae=class a extends S{constructor(e){super(e);this.data=e}txType=Pi.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Ir(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Di}from"@msafe/sui3-utils";var re=class a extends S{constructor(e){super(e);this.data=e}txType=Di.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Cr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as _i}from"@msafe/sui3-utils";var Tr=async(a,t,e)=>await j(e,t).Farms.openPositionAddLiquidityStakePaylod(a),kr=async(a,t,e)=>await j(e,t).Farms.addLiquidityFixCoinPayload(a),vr=async(a,t,e)=>await j(e,t).Farms.removeLiquidityPayload(a),xr=async(a,t,e)=>await j(e,t).Farms.removeLiquidityPayload(a),Ar=async(a,t,e)=>await j(e,t).Farms.claimFeeAndClmmReward(a),Or=async(a,t,e)=>await j(e,t).Farms.harvestPayload(a),Pr=async(a,t,e)=>{let n=j(e,t),r=Object.values(a);return await n.Farms.batchHarvestPayload(r)},Dr=async(a,t,e)=>await j(e,t).Farms.depositPayload(a),_r=async(a,t,e)=>await j(e,t).Farms.withdrawPayload(a);var oe=class a extends S{constructor(e){super(e);this.data=e}txType=_i.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Tr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ri}from"@msafe/sui3-utils";var ie=class a extends S{constructor(e){super(e);this.data=e}txType=Ri.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Pr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as ji}from"@msafe/sui3-utils";var se=class a extends S{constructor(e){super(e);this.data=e}txType=ji.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Ar(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Bi}from"@msafe/sui3-utils";var ce=class a extends S{constructor(e){super(e);this.data=e}txType=Bi.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await vr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ni}from"@msafe/sui3-utils";var le=class a extends S{constructor(e){super(e);this.data=e}txType=Ni.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Or(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Mi}from"@msafe/sui3-utils";var de=class a extends S{constructor(e){super(e);this.data=e}txType=Mi.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await kr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ei}from"@msafe/sui3-utils";var ue=class a extends S{constructor(e){super(e);this.data=e}txType=Ei.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await xr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Li}from"@msafe/sui3-utils";var pe=class a extends S{constructor(e){super(e);this.data=e}txType=Li.Other;txSubType="FarmingStake";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Dr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Wi}from"@msafe/sui3-utils";var me=class a extends S{constructor(e){super(e);this.data=e}txType=Wi.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await _r(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ui}from"@msafe/sui3-utils";var fe=class a extends S{constructor(e){super(e);this.data=e}txType=Ui.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await yr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Fi}from"@msafe/sui3-utils";var be=class a extends S{constructor(e){super(e);this.data=e}txType=Fi.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await wr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Qi}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as $i}from"@cetusprotocol/aggregator-sdk";import{Transaction as qi}from"@mysten/sui/transactions";var Rr=async(a,t,e)=>{let n=hr(e,t),r=new qi;return await n.fastRouterSwap({...a,routers:$i(a.routers),txb:r}),r};var ge=class a extends S{constructor(e){super(e);this.data=e}txType=Qi.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Rr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ki}from"@msafe/sui3-utils";import{Transaction as Vi}from"@mysten/sui/transactions";var jr={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Br=async(a,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:r,periods:o,CLOCK_ADDRESS:i}=a,s=new Vi;return o.forEach(c=>{s.moveCall({target:`${jr.published_at}::router::redeem`,typeArguments:[jr.cetus_coin_type],arguments:[s.object(n),s.object(r),s.pure(c),s.object(i)]})}),s};var he=class a extends S{constructor(e){super(e);this.data=e}txType=Ki.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Br(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Gi}from"@msafe/sui3-utils";import{Transaction as Hi}from"@mysten/sui/transactions";var Nr=async(a,t,e)=>{let n=j(e,t),r=new Hi;return await n.XCetusModule.convertPayload(a,r)},Mr=async(a,t,e)=>await j(e,t).XCetusModule.redeemLockPayload(a),Er=async(a,t,e)=>await j(e,t).XCetusModule.redeemDividendV3Payload(a.phases,a.venft_id,a.bonus_types,a.bonus_types_v2,a.xTokenType),Lr=async(a,t,e)=>await j(e,t).XCetusModule.cancelRedeemPayload(a),Wr=async(a,t,e)=>await j(e,t).XCetusModule.redeemPayload(a);var Se=class a extends S{constructor(e){super(e);this.data=e}txType=Gi.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Lr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as zi}from"@msafe/sui3-utils";var ye=class a extends S{constructor(e){super(e);this.data=e}txType=zi.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Er(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Ji}from"@msafe/sui3-utils";var we=class a extends S{constructor(e){super(e);this.data=e}txType=Ji.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Nr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Xi}from"@msafe/sui3-utils";var Ce=class a extends S{constructor(e){super(e);this.data=e}txType=Xi.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Wr(o,n,r)}static fromData(e){return new a(e)}};import{TransactionType as Yi}from"@msafe/sui3-utils";var Ie=class a extends S{constructor(e){super(e);this.data=e}txType=Yi.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:r}=e,{txbParams:o}=this.data;return await Mr(o,n,r)}static fromData(e){return new a(e)}};var Te=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:Zi.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:r}=t,o;switch(t.txSubType){case"OpenAndAddLiquidity":o=ne.fromData(t.intentionData);break;case"IncreaseLiquidity":o=fe.fromData(t.intentionData);break;case"DecreaseLiquidity":o=re.fromData(t.intentionData);break;case"RemoveLiquidity":o=be.fromData(t.intentionData);break;case"ClaimFeeAndMining":o=ae.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":o=oe.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":o=de.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":o=ce.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":o=ue.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":o=se.fromData(t.intentionData);break;case"FarmingHarvest":o=le.fromData(t.intentionData);break;case"FarmingBatchHarvest":o=ie.fromData(t.intentionData);break;case"FarmingStake":o=pe.fromData(t.intentionData);break;case"FarmingUnstake":o=me.fromData(t.intentionData);break;case"xCETUSConvert":o=we.fromData(t.intentionData);break;case"xCETUSRedeemLock":o=Ie.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":o=ye.fromData(t.intentionData);break;case"xCETUSCancelRedeem":o=Se.fromData(t.intentionData);break;case"xCETUSRedeem":o=Ce.fromData(t.intentionData);break;case"VestingRedeem":o=he.fromData(t.intentionData);break;case"AggregatorSwap":o=ge.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n,network:r})}};import{TransactionType as Xs}from"@msafe/sui3-utils";import ts from"sort-keys-recursive";var g=class{constructor(t){this.data=t}serialize(){return JSON.stringify(ts(this.data))}};import{getFullnodeUrl as ke}from"@mysten/sui.js/client";var Oa={};gr(Oa,{contractId:()=>as,default:()=>cs,feeObjId:()=>is,roleObjId:()=>rs,status:()=>ns,transaction:()=>es,upgradeCapObjId:()=>ss,vaultObjId:()=>os});var es="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",ns="success",as="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",rs="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",os="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",is="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",ss="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",cs={transaction:es,status:ns,contractId:as,roleObjId:rs,vaultObjId:os,feeObjId:is,upgradeCapObjId:ss};var Pa={};gr(Pa,{contractId:()=>us,default:()=>gs,feeObjId:()=>fs,roleObjId:()=>ps,status:()=>ds,transaction:()=>ls,upgradeCapObjId:()=>bs,vaultObjId:()=>ms});var ls="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ds="success",us="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",ps="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",ms="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",fs="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",bs="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",gs={transaction:ls,status:ds,contractId:us,roleObjId:ps,vaultObjId:ms,feeObjId:fs,upgradeCapObjId:bs};var hs=ke("testnet"),Ss=ke("testnet"),ys=ke("mainnet"),ws=ke("mainnet"),Cs="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Is="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Ts="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",ks="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Ur=Oa,Fr=Pa,vs=new Map([["dev",{env:"dev",rpc:{url:hs},backend:{url:Cs},contract:Ur}],["stg",{env:"stg",rpc:{url:Ss},backend:{url:Is},contract:Ur}],["prev",{env:"prev",rpc:{url:ys},backend:{url:Ts},contract:Fr}],["prod",{env:"prod",rpc:{url:ws},backend:{url:ks},contract:Fr}]]);function $r(a,t){let e=vs.get(a);if(!e)throw new Error(`Env not supported: ${a}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as As}from"@mysten/sui.js/client";var k=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:r,context:o}=n;r?super(`[MPay] ${e}: ${r}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var ve=class extends k{constructor(){super(11,"Backend is not specified")}};var xe=class extends k{constructor(){super(1,"Wallet not connected")}};import ht,{AxiosError as xs}from"axios";var gt=class extends k{constructor(t,e){super(10,t,{context:e})}};var Ae=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof xs)throw new gt(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new gt(t.data.code)}throw new gt(t.status.toString())}async getIncomingStreams(t,e){let n=await ht.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await ht.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await ht.post(`${this.apiURL}/stream-events`,t),n=a.parseResponseData(e);return n.data.forEach(r=>{let o=r;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),n}async getAllCoinTypes(t){let e=await ht.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await ht.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await ht.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(n)}};var St=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new As({url:t.rpc.url}),t.backend&&(this._backend=new Ae(t.backend.url))}static new(t,e){let n=$r(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new ve;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 xe;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Gs,normalizeStructTag as zs,normalizeSuiAddress as mo}from"@mysten/sui.js/utils";import{TransactionBlock as je}from"@mysten/sui.js/transactions";import{TransactionBlock as Xr}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Yr,normalizeStructTag as _s}from"@mysten/sui.js/utils";var Da=50n,Oe=10000n,qr=25n,_a=100000000n;var K=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Dt=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},et=class a{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 r=i=>new a(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield r(i),i++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}};import{Buffer as Qr}from"buffer";import{normalizeSuiAddress as Os}from"@mysten/sui.js/utils";var _t=class extends k{constructor(t,e){super(3,t,{context:e})}};var Pe=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,r]=this.getValue(t,e);if(r!=="address")throw new _t("Invalid contract return type.",{ctx:{expectType:"address",gotType:r}});return Os(Qr.from(n).toString("hex"))}getU64(t=0,e=0){let[n,r]=this.getValue(t,e);if(r!=="u64")throw new _t("Invalid contract return type.",{ctx:{expectType:"u64",gotType:r}});return Qr.from(n).readBigInt64LE()}};import{bcs as Kr}from"@mysten/sui.js/bcs";var A=class extends k{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Hr={groupId:"string",name:"string"},Ps=64;function Gr(a){return zr(a),Kr.ser(Hr,a).toString("base64")}function Rt(a){let t=Kr.de(Hr,a,"base64");return zr(t),t}function zr(a){if(!Vr(a.name))throw new A("Invalid metadata: Name contains unknown character");if(!Vr(a.groupId))throw new A("Invalid metadata: Group ID contains unknown character");if(a.name.length>Ps)throw new A("Invalid metadata: Name exceed max length 64")}function Vr(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as De}from"@mysten/sui.js/utils";function _e(a,t){return De(a)===De(t)}function nt(a,t){return De(a)===De(t)}var Re="txn.gas";import{nanoid as Ds}from"nanoid";function Jr(){return Ds()}var ft=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Gr({name:t.name,groupId:Jr()}),coinType:_s(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 Xr,n=this.calculateFeesInternal(t),r=this.getCreateStreamCoinRequests(t,n),o=await this.wallet.requestCoins(r),i=await this.addMergeCoins(e,o[0]),s;r.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let c=0;c<t.recipients.length;c++){let d=t.recipients[c],l=this.amountForRecipient(d,t.numberEpoch),u=this.getStreamFeeLocal(l),[p]=e.splitCoins(i,[e.pure(l+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new et(p),flatFeeCoin:new et(m),metadata:t.metadata,recipient:d.address,timeStart:t.startTime,cliff:d.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:Da,denominator:Oe},claimFeePercent:{numerator:qr,denominator:Oe},flatFeePerStream:_a}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(r=>t.object(r))),n=t.object(e.primaryCoin)):e.primaryCoin===Re?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return _e(n,Yr)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:Yr,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((r,o)=>{let i=this.amountForRecipient(o,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:r.totalAmount+i,streamFeeAmount:r.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 _a}getStreamFeeLocal(t){return t*Da/Oe}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Xr,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Pe(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as to}from"@mysten/sui.js/transactions";var Zr="0x0000000000000000000000000000000000000000000000000000000000000006";var yt=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(to.MoveCall({target:n,arguments:e.arguments.map(r=>r instanceof Dt?r.moveArgs(t):r instanceof K?r.moveArg(t):r instanceof et?r.moveArg():t.pure(r)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],r=[]){t.add(to.MoveCall({target:e,arguments:n.map(o=>o instanceof Dt?o.moveArgs(t):o instanceof K?o.moveArg(t):o instanceof et?o.moveArg():t.pure(o)),typeArguments:r}))}makeObject(t){return typeof t=="string"?new K(t):t}vaultObject(){return new K(this.config.vaultObjId)}roleObject(){return new K(this.config.roleObjId)}feeObject(){return new K(this.config.feeObjId)}clockObject(){return new K(Zr)}};var wt=class a extends yt{constructor(e,n){super(a.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 r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[r,o,n],typeArgs:[]})}setStreamingFlatFee(e,n){let r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[r,o,n],typeArgs:[]})}setClaimFee(e,n){let r=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[r,o,n],typeArgs:[]})}streamingFee(e,n){let r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[r,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var H=class a extends yt{constructor(e,n){super(a.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 r=this.feeObject(),o=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:a.MethodName.create_stream,arguments:[r,o,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 r=this.makeObject(n.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[r,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let r=this.makeObject(n.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[r,o],typeArgs:[n.coinType]})}claimStream(e,n){let r=this.makeObject(n.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[r,o],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let r=this.makeObject(n.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[r,o,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var Ct=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new wt(e,t),this.streamContract=new H(e,t)}feeContract;streamContract;async createStreams(t){let e=ft.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new ft(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let r=new je;return this.streamContract.setAutoClaim(r,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new je;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new je;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new je;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var P=class extends k{constructor(t,e={}){super(0,t,e)}};async function ja(a){let t=[];for(;await a.hasNext();){let e=await a.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Ra=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)}},It=class{constructor(t){this.requester=t;this.pager=new Ra(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 Be=class extends k{constructor(e,n,r){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:r}});this.coinType=e;this.requestAmount=n;this.gotAmount=r}};var Rs=25;async function eo(a,t,e,n="0x2::sui::SUI",r=Rs){let o=new Ba(a,t,n,r),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let c=await o.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new Be(n,e,i);return s}var Ba=class extends It{constructor(e,n,r,o){super(new Na(e,n,r,o));this.suiClient=e;this.owner=n;this.coinType=r;this.reqPageSize=o}},Na=class{constructor(t,e,n,r){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=r;if(r<=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}}};import{TransactionBlock as Le}from"@mysten/sui.js/transactions";import{normalizeStructTag as ao,parseStructTag as Ns}from"@mysten/sui.js/utils";import{DateTime as Ms}from"luxon";var Ne=class extends k{constructor(){super(7,"Connected wallet is not creator")}};var jt=class extends k{constructor(){super(8,"Connected wallet is not recipient")}};var Bt=class extends k{constructor(t,e){super(6,t,{context:e})}};var Me=class extends k{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as js,Duration as Bs}from"luxon";var no=(1n<<64n)-1n,Ee=1e3;function Ma(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ee);return js.fromMillis(e*Ee)}function Ea(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ee);return Bs.fromMillis(e*Ee)}var at=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new H(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await a.fetchStreamData(t,e);return new a(t,e,n)}static fromObjectData(t,e,n){let r=a.parseRawStreamData(e,n);return new a(t,e,r)}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 a.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new P("Object Id does not align");this.rawData=a.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 Ne;let t=new Le;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new jt;let t=new Le;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new jt;let e=new Le;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Le;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 ao(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 Ea(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return Rt(t).groupId}get name(){let{metadata:t}=this.rawData.config;return Rt(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Ma(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Ea(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:Ma((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===no?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Ms.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 a.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new Me(t):new Bt(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new Bt("Unexpected object type",{gotType:n.dataType});let{typeParams:r}=Ns(n.type),o=ao(r[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:o,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)}}}};import{normalizeStructTag as La,SUI_TYPE_ARG as Es}from"@mysten/sui.js/utils";import{Duration as ro}from"luxon";var We=class extends k{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Ls=1e3,Ue=class{constructor(t){this.globals=t;this.coinMetaHelper=new Wa(t.suiClient),this.createStreamHelper=new Ct(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new We(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 A("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,r=(t.totalAmount-n)/t.steps,i={realTotalAmount:r*t.steps+n,cliffAmount:n,amountPerStep:r};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new A("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 A("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(ro.fromMillis(Number(e*t.steps))),r={timeStart:t.timeStart,timeEnd:n,interval:ro.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(r),r}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),r=await this.getCoinMeta(e);return{...n,coinType:La(n.coinType),coinMeta:r}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(r=>this.getCoinMeta(r.coinType)));return e.map((r,o)=>({...r,coinType:La(r.coinType),coinMeta:n[o]}))}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 A("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new A("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Ls)throw new A("Interval shall be at least 1 second","interval",t.interval)}},Wa=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=La(t||Es);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}};import{normalizeStructTag as oo,normalizeSuiAddress as $e}from"@mysten/sui.js/utils";import{DateTime as io}from"luxon";var Tt=class extends k{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var Ws=25;async function Fa(a,t,e){let n=new Nt(t),r=new Mt(a,n,e);return await ja(r)}var Nt=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]}},Mt=class extends It{constructor(e,n,r){super(new Ua(e,n,r));this.suiClient=e;this.idIter=n;this.options=r}},Ua=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||Ws,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 o=await this.stringIter.next();o&&t.push(o)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:r}=this;n=e.filter(o=>r?.(o))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Fe=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new Tt("stream size 0");let n=e.map(o=>o.groupId);if(new Set(n).size!==1)throw new A("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await Fa(t.suiClient,e);return n.forEach(r=>{if(!r)throw new P("stream group object data undefined")}),a.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let r=await a.parseGroupStreams(t,e,n);return new a(t,r)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),n=e[0],r=!0;return e.forEach(o=>{Us(n,o)||(r=!1)}),r}async refresh(){let t=await Fa(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 r=n.map((o,i)=>at.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new Tt("Not same group ID");if(!this.checkStreamGroup(r))throw new Tt("Not same stream settings");return r}};function Us(a,t){return a.name===t.name&&a.groupId===t.groupId&&a.creator===t.creator&&a.start.toMillis()===t.start.toMillis()&&a.interval.toMillis()===t.interval.toMillis()&&a.steps===t.steps&&a.cancelable===t.cancelable}var Et=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await qe.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await qe.newOutgoing(t);return new a(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}},qe=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Qe.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await Qe.newOutgoingQuery(t);return new a(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}},Qe=class a{constructor(t,e,n,r){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=r;this.current=0;let o=new Nt(n.flat().map(i=>i.streamId));this.objectIter=new Mt(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Vs(t.query),n=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>$e(s.recipient)===$e(n)),i=so(o);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=Ks(t.query),n=await t.globals.walletAddress(),r=await t.globals.backend.getOutgoingStreams(n,e),o=so(r);return new a(t.globals,n,o,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 qs(this.globals,t[0].streamId,this.objectIter);return this.current++,co(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Qs(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,$s(e,this.query)?e:this.doNextRequest()}throw new P("Stream group with no stream")}};function so(a){let t=new Map;return a.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)=>io.fromISO(n[0].createDate).toMillis()-io.fromISO(e[0].createDate).toMillis())}function co(a,t){if(t===void 0)return!0;let e=Fs(a,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return e&&n}return e}function Fs(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function $s(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{co(n,t)&&(e=!0)}),e}async function qs(a,t,e){let n=await lo(e,t);return at.fromObjectData(a,t,n)}async function Qs(a,t,e){let n=[];for(;n.length<t.length;){let r=await lo(e,t[n.length]);n.push(r)}return Fe.newFromObjectResponse(a,t,n)}async function lo(a,t){if(!await a.hasNext())throw new P("object iterator has been consumed");let e=await a.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 Vs(a){return{status:$a(a?.status),coinType:uo(a?.coinType),sender:po(a?.sender)}}function Ks(a){return{status:$a(a?.status),coinType:uo(a?.coinType),recipient:po(a?.recipient)}}function $a(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=$a(e);return!t||t===n?n:"all"},void 0):Hs(a)}function Hs(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new A("Unknown stream filtered status")}}function uo(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>oo(t)):void 0:oo(a)}function po(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>$e(t)):void 0:$e(a)}var qa=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ve=class{constructor(t){this.account=t}async address(){return this.account.address}},Qa=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(_e(t.coinType,Gs))return{primaryCoin:Re};if(t.amount<=0)throw new A("Invalid coin request","coinAmount",t.amount);let e=await eo(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)}}},Ke=class{globals;helper;constructor(t,e){this.globals=St.new(t,e),this.helper=new Ue(this.globals)}connectSingleWallet(t){let e=new Qa(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new qa(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return at.new(this.globals,t)}async getIncomingStreams(t,e=10){return Et.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Et.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=>zs(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>mo(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>mo(r))}get wallet(){return this.globals.wallet}builder(){return new Ct(this.globals)}};var $=class extends g{application="mpay";getClient(t,e){let n=new Ke(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Ve(e)),n}};var Lt=class extends ${constructor(e){super(e);this.data=e}txType=Xs.Stream;txSubType="Cancel";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).cancel()}};import{TransactionType as Ys}from"@msafe/sui3-utils";var Wt=class extends ${constructor(e){super(e);this.data=e}txType=Ys.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Zs}from"@msafe/sui3-utils";var Ut=class extends ${constructor(e){super(e);this.data=e}txType=Zs.Stream;txSubType="Claim";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).claim()}};import{TransactionType as tc}from"@msafe/sui3-utils";var Ft=class extends ${constructor(e){super(e);this.data=e}txType=tc.Stream;txSubType="CreateStream";async build(e){let{network:n,account:r}=e;return this.getClient(n,r).createStream(this.data)}};import{bcs as fo}from"@mysten/sui.js/bcs";import{normalizeStructTag as ec,normalizeSuiAddress as $t}from"@mysten/sui.js/utils";var kt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return $t(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 fo.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 $t(t.value.Object.ImmOrOwned.objectId)}return $t(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return $t(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return $t(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 fo.de(e,new Uint8Array(n))}typeArg(t){return ec(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var He=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"&&nt(e.target,this.contract.createStreamTarget));if(t.length===0)throw new P("No create stream transactions");return t.map(e=>new kt(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:r}=Rt(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),d=t.decodeInputU64(9),l=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:r,recipient:o,timeStart:i,cliff:s,epochInterval:c,totalEpoch:d,amountPerEpoch:l,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new A("Stream group not have common info");let n=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.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 H(this.globals.envConfig.contract,this.globals)}get feeContract(){return new wt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ft(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 Ge=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new H(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"&&nt(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&nt(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&nt(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&nt(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&nt(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new He(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 kt(t,this.txb)}};import{TransactionType as nc}from"@msafe/sui3-utils";var qt=class extends ${constructor(e){super(e);this.data=e}txType=nc.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:r}=e;return(await this.getClient(n,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var ze=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,r=St.new(e==="sui:mainnet"?"prod":"dev"),i=new Ge(r,n).decode(),s;switch(i.type){case"CreateStream":s=new Ft(i.info);break;case"SetAutoClaim":s=new qt({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Ut({streamId:i.streamId});break;case"ClaimByProxy":s=new Wt({streamId:i.streamId});break;case"Cancel":s=new Lt({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 Ft(e);break;case"Claim":n=new Ut(e);break;case"ClaimByProxy":n=new Wt(e);break;case"SetAutoClaim":n=new qt(e);break;case"Cancel":n=new Lt(e);break;default:throw new Error("not implemented")}return n.build({...t})}};import{TransactionDefaultApplication as sc,TransactionSubTypes as Va}from"@msafe/sui3-utils";import{buildCoinTransferTxb as ac}from"@msafe/sui3-utils";var Je=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e;return ac(n,this.data,r.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as rc}from"@msafe/sui3-utils";var Xe=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e;return rc(n,this.data,r.address)}static fromData(e){return new a(e)}};import{isSameAddress as oc}from"@msafe/sui3-utils";import{TransactionBlock as ic}from"@mysten/sui.js/transactions";var Ye=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,r=ic.from(this.data.content);if(!oc(r.blockData.sender,n.address))throw new Error("Invalid sender address");return r}static fromData(e){return new a(e)}};var Ze=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=sc}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,r;switch(t.txSubType){case Va.assets.coin.send:r=Je.fromData(t.intentionData);break;case Va.assets.object.send:r=Xe.fromData(t.intentionData);break;case Va.others.plain:r=Ye.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};import{TransactionType as bc}from"@msafe/sui3-utils";var bo=!1,tn={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"},usdc:{name:"USDC",assetId:1,coinType:"usdc",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"}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Ka(){if(!bo)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n}=a;t&&(tn.ProtocolPackage=t),e&&(tn.borrowFee=e),n&&(tn.borrowFeeAddress=n),bo=!0}catch(a){console.error(a.message)}}var h=tn;import{TransactionType as Qt}from"@msafe/sui3-utils";import{bcs as go}from"@mysten/sui.js/bcs";import{normalizeStructTag as lc,normalizeSuiAddress as Vt}from"@mysten/sui.js/utils";var en=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.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`)}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 nn(e,this.txb),r=n.decodeInputU8(4),o=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(r),c=[...e.typeArguments];t.push({coinType:s.coinType,option:o,typeArguments:c,assetId:r,poolId:i})}}),console.log("decode claims",t),{txType:Qt.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Qt.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Qt.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:Qt.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:Qt.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 nn(t,this.txb)}},nn=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Vt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 go.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 Vt(t.value.Object.ImmOrOwned.objectId)}return Vt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Vt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Vt(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 go.de(e,new Uint8Array(n))}typeArg(t){return lc(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as dc}from"@mysten/sui.js/transactions";function Ha(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function ho(a,t,e){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function So(a,t,e,n){let r=a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.IncentiveV2)],typeArguments:[t.type]}),[o]=a.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[r]});if(h.borrowFee>0){let[i]=a.splitCoins(o,[a.pure(Math.floor(e*h.borrowFee))]);a.transferObjects([o],a.pure(n)),a.transferObjects([i],a.pure(h.borrowFeeAddress))}else a.transferObjects([o],a.pure(n));return a}function Ga(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function yo(a,t,e,n,r){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(h.IncentiveV2),a.object(e),a.object(h.StorageId),a.pure(t),a.pure(n)],typeArguments:r}),a}var an=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new dc;return e.forEach(r=>{let{assetId:o,poolId:i,option:s,typeArguments:c}=r;yo(n,o,i,s,c)}),n}static fromData(e){return new a(e)}};import{TransactionBlock as uc}from"@mysten/sui.js/transactions";var rn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:r}=this.data,o=new uc;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 So(o,i,r,e.account.address)}static fromData(e){return new a(e)}};import{TransactionBlock as pc}from"@mysten/sui.js/transactions";async function on(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var sn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e,{coinType:o,amount:i}=this.data,s=new pc;if(console.log("build",this.data),o==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Ha(s,h.pool.sui,u,i)}let c=h.pool[o];if(!c)throw new Error(`${o} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await on(n,r.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let u=1;for(;u<d.data.length;)s.mergeCoins(l,[d.data[u].coinObjectId]),u++}return Ha(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as mc}from"@mysten/sui.js/transactions";var cn=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:r}=e,{coinType:o,amount:i}=this.data,s=new mc;if(console.log("build",this.data),o==="sui"){let[u]=s.splitCoins(s.gas,[i]);return Ga(s,h.pool.sui,u,i)}let c=h.pool[o];if(!c)throw new Error(`${o} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await on(n,r.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let u=1;for(;u<d.data.length;)s.mergeCoins(l,[d.data[u].coinObjectId]),u++}return Ga(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as fc}from"@mysten/sui.js/transactions";var ln=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,r=new fc;console.log("build",this.data);let o=h.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return ho(r,o,n)}static fromData(e){return new a(e)}};var dn=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await Ka();let{transactionBlock:e}=t,r=new en(e).decode();return{txType:bc.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n}=t,r;switch(await Ka(),t.txSubType){case"EntryDeposit":r=sn.fromData(t.intentionData);break;case"EntryBorrow":r=rn.fromData(t.intentionData);break;case"EntryRepay":r=cn.fromData(t.intentionData);break;case"EntryWithdraw":r=ln.fromData(t.intentionData);break;case"ClaimReward":r=an.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};import{TransactionSubTypes as gc,TransactionType as wo}from"@msafe/sui3-utils";import{fromHEX as hc,toHEX as Sc}from"@mysten/bcs";import{Transaction as yc}from"@mysten/sui/transactions";import wc from"sort-keys-recursive";var Co="msafe-plain-tx",Io=gc.others.plain,za=class a{constructor(t){this.data=t}application=Co;txType=wo.Other;txSubType=Io;serialize(){return JSON.stringify(wc(this.data))}async build(t){return yc.from(hc(this.data.content))}static fromData(t){return new a(t)}},un=class{application;supportSDK="@mysten/sui";constructor(){this.application=Co}async deserialize(t){let{transaction:e}=t,n=await e.build({client:t.suiClient});return{txType:wo.Other,txSubType:Io,intentionData:{content:Sc(n)}}}async build(t){let{account:e}=t,r=await za.fromData(t.intentionData).build({suiClient:t.suiClient,network:t.network,account:t.account}),i=await t.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:e.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return r}};import{SuiClient as To}from"@mysten/sui/client";import{Transaction as Cc}from"@mysten/sui/transactions";import{SuiClient as Ja}from"@mysten/sui.js/client";import{TransactionBlock as Ic}from"@mysten/sui.js/transactions";var pn=class a{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new a;for(let n=0;n<t.length;n++){let r=t[n];switch(r.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(r);break;case"@mysten/sui":e.addHelper(r);break;default:throw new Error(`${r.application}: ${r.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new Ya(t))}addHelper(t){this.apps.set(t.application,new Xa(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},Xa=class{constructor(t){this.helper=t}async deserialize(t){let e=new To({url:t.clientUrl}),n=new Ja({url:t.clientUrl}),r=await t.transactionBlock.build({client:n}),o=Cc.from(r);return this.helper.deserialize({...t,suiClient:e,transaction:o})}async build(t){let e=new To({url:t.clientUrl}),n=await this.helper.build({...t,suiClient:e});n.setSender(t.account.address);let r=await n.build({client:e});return Ic.from(r)}},Ya=class{constructor(t){this.helper=t}async deserialize(t){let e=new Ja({url:t.clientUrl});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new Ja({url:t.clientUrl});return this.helper.build({...t,suiClient:e})}};import{TransactionType as Jc}from"@msafe/sui3-utils";import{TransactionType as D}from"@msafe/sui3-utils";var rt=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 ko="https://sui.apis.scallop.io";var vo="66f8e7ed9bb9e07fdfb86bbb",mn="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var ot="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",it="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",G=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],fn=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc"],st=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],z=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc"];var xo=["sui"],ct=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc"];var Ao={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 bn={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},Oo={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"]},Po={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"},W={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Za={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},Do={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"};import{bcs as _o}from"@mysten/sui.js/bcs";import{normalizeStructTag as Tc,normalizeSuiAddress as Kt}from"@mysten/sui.js/utils";var w=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Kt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 _o.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 Kt(t.value.Object.ImmOrOwned.objectId)}return Kt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Kt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Kt(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 _o.de(e,new Uint8Array(n))}typeArg(t){return Tc(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{bcs as kc}from"@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 kc.de(e,new Uint8Array(n))}return t.value}};var gn=class extends rt{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(`${it}::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(`${it}::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:D.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),r=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:D.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:r,veScaKey:t}}}decodeOpenObligation(){return{txType:D.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((r,o)=>r+o,0);return{txType:D.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((r,o)=>r+o,0);return{txType:D.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((r,o)=>r+o,0);return{txType:D.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((o,i)=>o+i,0),r=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:D.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:r,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),r=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:D.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:r,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:r,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),r=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:o,obligationId:r,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),r=this.helperBorrowWithReferral.decodeSharedObjectId(1),o=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:o,obligationId:r,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((o,i)=>o+i,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"Repay",intentionData:{amount:n,obligationId:r,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),r=new _(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"RepayWithBoost",intentionData:{amount:r,obligationId:o,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);e=new _(o,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let o=this.helperStake.getNestedInputParam(2);e=new _(o,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),r=this.scallop.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"StakeSpool",intentionData:{amount:e,marketCoinName:r,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),r=this.scallop.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:r,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((o,i)=>o+i,0),r;return this.isCreateStakeAccountTransaction()||(r=this.helperStake.decodeOwnedObjectId(1)),{txType:D.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:r}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(r=>{let o=r.decodeOwnedObjectId(1),i=r.decodeInputU64(2);t.push({id:o,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);n=new _(r,this.txb).getAmountInput().reduce((o,i)=>o+i,0)}return{txType:D.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 r=this.helperSlippage.decodePureArg(1,"u64"),o=this.helperSlippage.decodePureArg(2,"string");return{txType:D.Other,type:"MigrateWusdcToUsdc",intentionData:{amount:n,coinName:e,slippage:r,validSwapAmount:o,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(r=>{let o=r.decodeOwnedObjectId(2),i=r.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:o})}),this.helperClaimBorrowV2Reward.forEach(r=>{let o=r.decodeSharedObjectId(3),i=r.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(r.typeArg(0));e.push({obligationId:i,obligationKey:o,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(r=>{let o=r.decodeSharedObjectId(2),i=r.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(r.typeArg(0));n.push({obligationId:i,obligationKey:o,rewardCoinName:s})}),{txType:D.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};import{TransactionType as er}from"@msafe/sui3-utils";var hn=class extends rt{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:er.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:er.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:er.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};import{TransactionType as Ht}from"@msafe/sui3-utils";var Sn=class extends rt{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(`${it}::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:Ht.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,y)=>f+y,0),r=this.helperRenewExpired.decodeOwnedObjectId(1),o=!!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 d=!1,l=!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,d=!0,l=m[f].isOld);return{txType:Ht.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:r,isHaveRedeem:o,isObligationLocked:d,isOldBorrowIncentive:l}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],r=[],o=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(o=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,d,l=[{condition:n,isOld:!0},{condition:r,isOld:!1},{condition:o,isOld:!1}];for(let u=0;u<l.length;u++)l[u].condition.length>1&&([d,c]=l[u].condition,i=!0,s=l[u].isOld);return{txType:Ht.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:d,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),r=[],o=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(r=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[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,d=!1,l,u,p=[{condition:r,isOld:!0},{condition:o,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:Ht.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:l,obligationKey:u,isOldBorrowIncentive:d,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),r=[],o=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(r=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[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,d=!1,l,u,p=[{condition:r,isOld:!0},{condition:o,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:Ht.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:l,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:d}}}};import vc from"sort-keys-recursive";var b=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(vc(this.data))}};var yn=class a extends b{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 a(e)}};var wn=class a extends b{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 a(e)}};var Cn=class a extends b{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 a(e)}};var In=class a extends b{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 a(e)}};var Tn=class a extends b{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 a(e)}};var kn=class a extends b{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 a(e)}};var vn=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new a(e)}};var xn=class a extends b{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 a(e)}};var An=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new a(e)}};var On=class a extends b{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 a(e)}};var Pn=class a extends b{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 a(e)}};var Dn=class a extends b{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 a(e)}};var _n=class a extends b{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 a(e)}};var Rn=class a extends b{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 a(e)}};var jn=class a extends b{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 a(e)}};var Bn=class a extends b{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 a(e)}};var Nn=class a extends b{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 a(e)}};var Mn=class a extends b{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 a(e)}};var En=class a extends b{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 a(e)}};var Ln=class a extends b{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new a(e)}};var Wn=class a extends b{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 a(e)}};var Un=class a extends b{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 a(e)}};var Fn=class a extends b{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 a(e)}};var $n=class a extends b{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 a(e)}};var qn=class a extends b{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 a(e)}};var Qn=class a extends b{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 a(e)}};var Vn=class a extends b{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 a(e)}};var Kn=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,r)=>typeof n=="object"?n[r]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${ko}/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}`)}};import{TransactionBlock as T}from"@mysten/sui.js/transactions";import ii from"bignumber.js";import{TransactionBlock as xc}from"@mysten/sui.js/transactions";var Hn=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:r,utils:o}=e;this.address=n,this.query=r,this.utils=o,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new xc(t)}async selectCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,o,r),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,o,r),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[d,l]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:d,leftCoin:l,totalAmount:s}}async selectSCoin(t,e,n,r=this.params.walletAddress){let o=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,o,r),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[d,l]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:d,leftCoin:l,totalAmount:c}}};import{TransactionBlock as Ac}from"@mysten/sui.js/transactions";import Gn from"bignumber.js";var vt=async(a,t)=>{let e=t,n=a.address.get("core.object")||mn,r=[],o=!1,i=null;do{let l=await a.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});r.push(...l.data),l.hasNextPage&&l.nextCursor?(o=!0,i=l.nextCursor):o=!1}while(o);let s=r.map(l=>l?.data?.objectId).filter(l=>l!==void 0),c=await a.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),d=[];for(let l=0;l<c.length;l++){let u=c[l].data.objectId,{content:p}=c[l].data;if(p&&"fields"in p){let m=p.fields,f=String(m.ownership.fields.of),y=await nr(a,f);d.push({id:f,keyId:u,locked:y})}}return d},nr=async(a,t)=>{let e=await a.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},Ro=async(a,t,e)=>{let n=e||[...G],r=t,o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:r,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Gn(c[m]??0).plus(p.balance).toNumber())}}),c},jo=async(a,t,e)=>{let n=e,r=a.utils.parseCoinType(t),o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${r}>`},options:{showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Gn(c).plus(u.balance).toNumber()}}),c},Bo=async(a,t,e)=>{let n=e||[...G].map(l=>a.utils.parseMarketCoinName(l)),r=t,o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:r,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Gn(c[m]??0).plus(p.balance).toNumber())}}),c},No=async(a,t,e)=>{let n=e,r=a.utils.parseMarketCoinType(t),o=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${r}>`},options:{showContent:!0},cursor:s});o.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return o.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Gn(c).plus(u.balance).toNumber()}}),c},Mo=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,r=new Ac;return r.moveCall({target:n,arguments:[r.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:r,sender:a.params.walletAddress})).events[0].parsedJson};import{normalizeStructTag as I}from"@mysten/sui.js/utils";var Gt=async(a,t)=>{let e=t,n=a.address.get("spool.object"),r=`${n}::spool_account::SpoolAccount`,o=[],i=!1,s=null;do{let p=await a.client.getOwnedObjects({owner:e,filter:{StructType:r},options:{showContent:!0,showType:!0},cursor:s});o.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:[]},d=Object.keys(c).reduce((p,m)=>{let f=a.utils.parseCoinName(m),y=a.utils.parseMarketCoinType(f),C={...p},v=`${n}::spool_account::SpoolAccount<${y}>`;return C[m]=v,C},{}),l=o.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await a.client.multiGetObjects({ids:l,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 y=p.data.content.fields,C=String(y.spool_id),v=String(y.stake_type.fields.name),E=Number(y.stakes),R=Number(y.index),U=Number(y.points),L=Number(y.total_points);I(f)===d.sweth?c.sweth.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.ssui?c.ssui.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.swusdc?c.swusdc.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.swusdt?c.swusdt.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.scetus?c.scetus.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.safsui?c.safsui.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.shasui?c.shasui.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.svsui?c.svsui.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L}):I(f)===d.susdc&&c.susdc.push({id:m,type:I(f),stakePoolId:C,stakeType:I(v),staked:E,index:R,points:U,totalPoints:L})}}),c},ar=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.id`),n,r=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(r.data){let o=r.data,i=o.objectId,s=o.type;if(o.content&&"fields"in o.content){let c=o.content.fields,d=Number(c.max_distributed_point),l=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),y=Number(c.stakes),C=Number(c.index),v=Number(c.created_at),E=Number(c.last_update);n={id:i,type:I(s),maxPoint:d,distributedPoint:l,pointPerPeriod:u,period:p,maxStake:m,stakeType:I(f),totalStaked:y,index:C,createdAt:v,lastUpdate:E}}}return n},rr=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.rewardPoolId`),n,r=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(r.data){let o=r.data,i=o.objectId,s=o.type;if(o.content&&"fields"in o.content){let c=o.content.fields,d=String(c.spool_id),l=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:I(s),stakePoolId:d,ratioNumerator:l,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};import{TransactionBlock as Dc}from"@mysten/sui.js/transactions";import{normalizeStructTag as zw}from"@mysten/sui.js/utils";import Xw from"bignumber.js";var B=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},Wo=(a,t,e,n)=>{let r=!n,o=!r&&n*1e3<=new Date().getTime();if(r||o)if(a!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof a=="number"&&a<1e10)throw new Error(`Minimum lock amount for ${o?"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 ${o?"renewing expired veSca":"initial lock"}`);else{if(xt(n),typeof a=="number"&&a<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)`)}},Uo=(a,t,e)=>{if(xt(e),a<=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)`)},Fo=(a,t)=>{if(xt(t),a<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")},$o=(a,t,e)=>{if(xt(e),a<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)`)},xt=a=>{if(a===void 0)throw new Error("veSca not found")};import{normalizeStructTag as qo,parseStructTag as Oc}from"@mysten/sui.js/utils";import Lw from"bignumber.js";var Pc=a=>({pointType:qo(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),Qo=a=>({poolType:qo(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=Pc(e),r=Oc(n.pointType).name.toLowerCase();return t[r]=n,t},{})});var Jn=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...G,...fn,...xo])].includes(t)},or=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}},Vo=a=>{let t=new Date(a*1e3),e=new Date(a*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 Ko=async(a,t,e,n)=>{let r=n||[...ct],o=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${o}::incentive_account_query::incentive_account_data`,c=new Dc;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let l=(await a.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return l.pool_records.forEach(p=>{let m=Qo(p),{poolType:f}=m,y=a.utils.parseCoinNameFromType(f);r.length>=1&&r.includes(y)&&(u[y]=m)},{}),u};var Ho=async({address:a,client:t},e)=>{let n=a.get("borrowIncentive.object"),r=a.get("borrowIncentive.incentiveAccounts"),o=a.get("core.object"),i=await t.getObject({id:r,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<${o}::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 Go=async(a,t)=>{let e=a.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await a.client.getObject({id:e,options:{showContent:!0}});if(n.data){let r=n.data;if(r.content&&"fields"in r.content){let o=r.content.fields,i=Number(o.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(o.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(o.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),d=Number(o.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(d?-1:1)}}return 0};import ir from"bignumber.js";var zo=async(a,t)=>{let e=t,r=`${a.address.get("vesca.id")}::ve_sca::VeScaKey`,o=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:e,filter:{StructType:r},cursor:s});o.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);return o.map(d=>d.data).filter(d=>!!d)},Jo=async(a,t)=>{let n=(await zo(a,t)).map(o=>o.objectId),r=[];for(let o=0;o<n.length;o++){let i=await sr(a,n[o]);i&&r.push(i)}return r},sr=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),r=t||(await zo(a,e))[0].objectId,o,s=(await a.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:r}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;o={id:s.objectId,keyId:r,lockedScaAmount:ir(c.locked_sca_amount).toNumber(),lockedScaCoin:ir(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:ir(c.unlock_at).toNumber()}}return o};var Xn=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:r}=e;this.address=n,this.utils=r}async getObligations(t=this.params.walletAddress){return vt(this,t)}async getCoinAmounts(t,e){return Ro(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return jo(this,t,e)}async getMarketCoinAmounts(t,e){return Bo(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return No(this,t,e)}async getPriceFromPyth(t){return Go(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return Gt(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...st]){let e={};for(let n=0;n<t.length;n++){let r=t[n],o=await ar(this,r);o&&(e[r]=o)}return e}async getStakePool(t){return ar(this,t)}async getStakeRewardPools(t=[...st]){let e={};for(let n=0;n<t.length;n++){let r=await rr(this,t[n]);r&&(e[t[n]]=r)}return e}async getStakeRewardPool(t){return rr(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return Ko(this,t,e,n)}async getObligationCoinNames(t){let e=await Mo(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),r=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...r])].map(s=>this.utils.parseCoinNameFromType(s))}};import{SUI_TYPE_ARG as cr,normalizeStructTag as _c}from"@mysten/sui.js/utils";var Yn=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Jn(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+or(e)}return or(t)}parseCoinType(t){let e=Jn(t)?this.parseCoinName(t):t,n=Po[e];return[W.wusdc,W.wusdt,W.weth,W.wbtc,W.wsol,W.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Za.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||mn,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=_c(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,r=t.match(n),o=t.includes("reserve::MarketCoin");e=r?.[1]||t;let i={[`${W.wusdc}::coin::COIN`]:"wusdc",[`${W.wusdt}::coin::COIN`]:"wusdt",[`${W.weth}::coin::COIN`]:"weth",[`${W.wbtc}::coin::COIN`]:"wbtc",[`${W.wsol}::coin::COIN`]:"wsol",[`${W.wapt}::coin::COIN`]:"wapt"},s={[`${Za.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return o?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>bn[t];getBorrowIncentiveRewardCoinName=t=>Oo[t];getCoinDecimal(t){return Ao[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 Do[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=cr,n){let r=n,o=[],i=0,s=!0,c=null;for(;s&&i<t;){let d=await this.client.getCoins({owner:r,coinType:e,cursor:c});d.data.sort((l,u)=>parseInt(u.balance,10)-parseInt(l.balance,10));for(let l=0;l<d.data.length&&(o.push({objectId:d.data[l].coinObjectId,digest:d.data[l].digest,version:d.data[l].version,balance:d.data[l].balance}),i+=parseInt(d.data[l].balance,10),!(i>=t));l++);c=d.nextCursor,s=d.hasNextPage}if(!o.length)throw new Error("No valid coins found for the transaction.");return o}async selectCoinsMarketCoin(t=cr,e){let n=e,r=[],o=!0,i=null;for(;o;){let s=await this.client.getCoins({owner:n,coinType:t,cursor:i});s.data.sort((c,d)=>parseInt(d.balance,10)-parseInt(c.balance,10));for(let c=0;c<s.data.length&&(r.push({objectId:s.data[c].coinObjectId,digest:s.data[c].digest,version:s.data[c].version,balance:s.data[c].balance}),!(r.length>50));c++);i=s.nextCursor,o=s.hasNextPage}return r}async selectCoinIds(t,e=cr,n){return(await this.selectCoins(t,e,n)).map(o=>o.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 r=e.map(s=>t.object(s)),o=r[0];r.length>1&&t.mergeCoins(o,r.slice(1));let[i]=t.splitCoins(o,[t.pure(n)]);return[i,o]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),r=e?Math.max(e-n,0):0,o=0;if(r===0){let i=(t??1)*86400;o=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+r:r,126144e3);o=n+i}return Vo(o)}parseSCoinName(t){if(Jn(t)&&z.includes(t))return t;let e=`s${t}`;if(z.includes(e))return e}};import{SUI_CLOCK_OBJECT_ID as At,SUI_TYPE_ARG as Rc}from"@mysten/sui.js/utils";var Ot=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await sr(t.query,n);return i||void 0}let r=B(e),o=await Jo(t.query,r);if(o.length!==0)return o[0]};var lr=async(...a)=>{let[t,e,n,r]=a;if(a.length===4&&n&&r&&typeof n=="string"){let c=await nr(t.query,n);return{obligationId:n,obligationKey:r,obligationLocked:c}}let o=B(e),i=await vt(t.query,o);if(i.length===0)throw new Error(`No obligation found for sender ${o}`);let s=i.find(c=>c.id===n||c.keyId===r)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},jc=async({builder:a,txBlock:t})=>{let e={borrowIncentivePkg:a.address.get("borrowIncentive.id"),query:a.address.get("borrowIncentive.query"),incentivePools:a.address.get("borrowIncentive.incentivePools"),incentiveAccounts:a.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:a.address.get("core.obligationAccessStore"),config:a.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},r={table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{stakeObligation:(o,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(o),t.object(e.obligationAccessStore),t.object(At)]})},stakeObligationWithVesca:(o,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(o),t.object(e.obligationAccessStore),t.object(r.config),t.object(r.treasury),t.object(r.table),t.object(s),t.object(At)]})},unstakeObligation:(o,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(o),t.object(At)]})},oldUnstakeObligation:(o,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(o),t.object(At)],typeArguments:[Rc]})},claimBorrowIncentive:(o,i,s)=>{let c=a.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(o),t.object(At)],typeArguments:[c]})},oldClaimBorrowIncentive(o,i,s){let c=a.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(o),t.object(At)],typeArguments:[c]})}}},N=async({builder:a,txBlock:t})=>{let e=await jc({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,r)=>{let{obligationId:o,obligationKey:i,obligationLocked:s}=await lr(a,t,n,r),c=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${it}::user::unstake`||d.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(o,i)},unstakeObligationQuick:async(n,r)=>{let{obligationId:o,obligationKey:i,obligationLocked:s}=await lr(a,t,n,r);s&&e.unstakeObligation(o,i)},stakeObligationWithVeScaQuick:async(n,r,o)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await lr(a,t,n,r),d=!!t.blockData.transactions.find(async l=>l.kind==="MoveCall"&&(l.target===`${it}::user::unstake`||l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||d){let l=await Ho({address:a.address,client:a.client},i);if(o&&o!==l)throw new Error("Binded veScaKey is not equal to the provided veScaKey");l?e.stakeObligationWithVesca(i,s,l):e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,r,o)=>e.claimBorrowIncentive(r,o,n)}};import{SUI_CLOCK_OBJECT_ID as X}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as ea}from"@mysten/sui.js/utils";import Bc from"axios";var Xo={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};import{bcs as dr}from"@mysten/sui.js/bcs";import{SUI_CLOCK_OBJECT_ID as Zn}from"@mysten/sui.js/utils";var ur=16*1024,ta=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(),r=[];return t.forEach(o=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(dr.ser("vector<u8>",Array.from(o),{maxSize:ur}).toBytes()),e.object(Zn)]});r.push(i)}),r}async updatePriceFeeds(t,e,n){let r=await this.getPythPackageId(),o;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);[o]=t.moveCall({target:`${r}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(dr.ser("vector<u8>",Array.from(e[0]),{maxSize:ur}).toBytes()),s[0],t.object(Zn)]});let c=[],d=await this.getBaseUpdateFee(),l=t.splitCoins(t.gas,n.map(()=>t.pure(d))),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),[o]=t.moveCall({target:`${r}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),o,t.object(m),l[u],t.object(Zn)]}),u++}return t.moveCall({target:`${r}::hot_potato_vector::destroy`,arguments:[o],typeArguments:[`${r}::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 r=this.extractVaaBytesFromAccumulatorMessage(e[0]),o=await this.verifyVaas([r],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(dr.ser("vector<u8>",Array.from(e[0]),{maxSize:ur}).toBytes()),o[0],t.object(Zn)]})}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:r}=await this.getPriceTableInfo(),o=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${r}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!o.data||!o.data.content)return;if(o.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,o.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,r=t.readUint16BE(n),o=n+2;return t.subarray(o,o+r)}};var Nc=async(a,t)=>(await Bc.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(r=>Buffer.from(r,"base64")),zt=async(a,t,e)=>{let n=e??[...new Set([...G,...fn])],r=a.isTestnet?["pyth"]:["pyth"];if(r.includes("pyth")){let i=new ta(a.client,a.address.get("core.oracles.pyth.state"),a.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async d=>s.push(a.address.get(`core.coins.${d}.oracle.pyth.feed`))));let c=a.params.pythEndpoints??Xo[a.isTestnet?"testnet":"mainnet"];try{let d=await Nc(c[0],s);await i.updatePriceFeeds(t,d,s)}catch(d){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${d}`)}}let o=[...new Set(n)];for(let i=0;i<o.length;i++)await Mc(a,t,o[i],r)},Mc=async(a,t,e,n)=>{let r=a.utils.parseCoinType(e);Ec(t,n,a.address.get("core.packages.xOracle.id"),a.address.get("core.oracles.xOracle"),a.address.get("core.packages.pyth.id"),a.address.get("core.oracles.pyth.registry"),a.address.get("core.oracles.pyth.state"),a.address.get(`core.coins.${e}.oracle.pyth.feedObject`),a.address.get("core.packages.switchboard.id"),a.address.get("core.oracles.switchboard.registry"),a.address.get(`core.coins.${e}.oracle.switchboard`),a.address.get("core.packages.supra.id"),a.address.get("core.oracles.supra.registry"),a.address.get("core.oracles.supra.holder"),r)},Ec=(a,t,e,n,r,o,i,s,c,d,l,u,p,m,f)=>{let y=Lc(a,e,n,f);return t.includes("pyth")&&$c(a,r,y,i,s,o,f),t.includes("switchboard")&&Fc(a,c,y,l,d,f),t.includes("supra")&&Uc(a,u,y,m,p,f),Wc(a,e,n,y,f),a},Lc=(a,t,e,n)=>{let r=typeof e=="string"?a.object(e):e,o=`${t}::x_oracle::price_update_request`,i=[n];return a.moveCall({target:o,arguments:[r],typeArguments:i})},Wc=(a,t,e,n,r)=>{let o=`${t}::x_oracle::confirm_price_update_request`,i=[r],s=typeof e=="string"?a.object(e):e;return a.moveCall({target:o,arguments:[s,n,a.object(ea)],typeArguments:i}),a},Uc=(a,t,e,n,r,o)=>{let i=typeof n=="string"?a.object(n):n,s=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(ea)],typeArguments:[o]})},Fc=(a,t,e,n,r,o)=>{let i=typeof n=="string"?a.object(n):n,s=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(ea)],typeArguments:[o]})},$c=(a,t,e,n,r,o,i)=>{let s=typeof e=="string"?a.object(e):e,c=typeof n=="string"?a.object(n):n,d=typeof r=="string"?a.object(r):r,l=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,d,l,a.object(ea)],typeArguments:[i]})};var dt=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("scoin.id")},n={};return await Promise.all(z.map(async r=>{let o=a.utils.getSCoinTreasury(r);n[r]=o})),{mintSCoin:(r,o)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[r]),typeof o!="string"?o:t.pure(o)],typeArguments:[a.utils.parseSCoinType(r),a.utils.parseUnderlyingSCoinType(r)]}),burnSCoin:(r,o)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[r]),typeof o!="string"?o:t.pure(o)],typeArguments:[a.utils.parseSCoinType(r),a.utils.parseUnderlyingSCoinType(r)]})}};var Jt=async(...a)=>{let[t,e,n,r]=a;if(a.length===3&&n)return{obligationId:n};if(a.length===4&&n&&r)return{obligationId:n,obligationKey:r};let o=B(t),i=await vt(e.query,o);if(i.length===0)throw new Error(`No obligation found for sender ${o}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},qc=async({builder:a,txBlock:t})=>{let e={protocolPkg:a.address.get("core.packages.protocol.id"),market:a.address.get("core.market"),version:a.address.get("core.version"),coinDecimalsRegistry:a.address.get("core.coinDecimalsRegistry"),xOracle:a.address.get("core.oracles.xOracle")},r=`${a.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:(o,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(o),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(o,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(o),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X)],typeArguments:[d]})},deposit:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(X)],typeArguments:[s]})},depositEntry:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(X)],typeArguments:[s]})},withdraw:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(X)],typeArguments:[s]})},withdrawEntry:(o,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(X)],typeArguments:[s]})},borrow:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X)],typeArguments:[d]})},borrowEntry:(o,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(X)],typeArguments:[d]})},borrowWithReferral:(o,i,s,c,d)=>{let l=a.utils.parseCoinType(d);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(o),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(X)],typeArguments:[l,r]})},repay:(o,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(o),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(X)],typeArguments:[c]})},borrowFlashLoan:(o,i)=>{let s=a.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(o)],typeArguments:[s]})},repayFlashLoan:(o,i,s)=>{let c=a.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(o),t.object(i)],typeArguments:[c]})}}},M=async({builder:a,txBlock:t})=>{let e=await qc({builder:a,txBlock:t}),n=await dt({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(r,o,i)=>{let s=B(t),{obligationId:c}=await Jt(t,a,i);if(o==="sui"){let[d]=t.splitCoins(t.gas,[r]);e.addCollateral(c,d,o)}else{let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,o,r,s);e.addCollateral(c,l,o),t.transferObjects([d],s)}},takeCollateralQuick:async(r,o,i,s)=>{let c=await Jt(t,a,i,s),d=await a.query.getObligationCoinNames(c.obligationId);return await zt(a,t,d),e.takeCollateral(c.obligationId,c.obligationKey,r,o)},depositQuick:async(r,o,i)=>{if(o==="sui"){let[d]=t.splitCoins(t.gas,[r]);return e.deposit(d,o)}let{leftCoin:s,takeCoin:c}=await a.selectCoin(t,o,r,i);return t.transferObjects([s],i),e.deposit(c,o)},withdrawQuick:async(r,o)=>{let i=B(t),s=a.utils.parseMarketCoinName(o);try{let c=a.utils.parseSCoinName(o);if(!c)throw new Error(`No sCoin for ${o}`);let{leftCoin:d,takeCoin:l,totalAmount:u}=await a.selectSCoin(t,c,r,i);t.transferObjects([d],i);let p=n.burnSCoin(c,l),m=e.withdraw(p,o),f=r-u;try{if(f>0){let{leftCoin:y,takeCoin:C}=await a.selectMarketCoin(t,s,f,i);t.transferObjects([y],i),t.mergeCoins(m,[e.withdraw(C,o)])}}catch{}return m}catch{let{leftCoin:d,takeCoin:l}=await a.selectMarketCoin(t,s,r,i);return t.transferObjects([d],i),e.withdraw(l,o)}},borrowQuick:async(r,o,i,s)=>{let c=await Jt(t,a,i,s),l=[...await a.query.getObligationCoinNames(c.obligationId),o];return await zt(a,t,l),e.borrow(c.obligationId,c.obligationKey,r,o)},borrowWithReferralQuick:async(r,o,i,s,c)=>{let d=await Jt(t,a,s,c),u=[...await a.query.getObligationCoinNames(d.obligationId),o];return await zt(a,t,u),e.borrowWithReferral(d.obligationId,d.obligationKey,i,r,o)},repayQuick:async(r,o,i,s)=>{let c=await Jt(t,a,i);if(o==="sui"){let[u]=t.splitCoins(t.gas,[r]);return e.repay(c.obligationId,u,o)}let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,o,r,s);return t.transferObjects([d],s),e.repay(c.obligationId,l,o)},updateAssetPricesQuick:async r=>zt(a,t,r)}};import{SUI_CLOCK_OBJECT_ID as na}from"@mysten/sui.js/utils";var aa=async({builder:a,txBlock:t})=>{let e={referralPgkId:a.address.get("referral.id"),referralBindings:a.address.get("referral.referralBindings"),referralRevenuePool:a.address.get("referral.referralRevenuePool"),authorizedWitnessList:a.address.get("referral.authorizedWitnessList"),referralTiers:a.address.get("referral.referralTiers"),version:a.address.get("referral.version")},n=a.address.get("vesca.table");return{bindToReferral:r=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(r),t.object(n),t.object(na)],typeArguments:[]}),claimReferralTicket:r=>{let o=a.utils.parseCoinType(r);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(na)],typeArguments:[o]})},burnReferralTicket:(r,o)=>{let i=a.utils.parseCoinType(o);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(r),t.object(e.referralRevenuePool),t.object(na)],typeArguments:[i]})},claimReferralRevenue:(r,o)=>{let i=a.utils.parseCoinType(o);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(r),t.object(na)],typeArguments:[i]})}}},Yo=async({builder:a,txBlock:t})=>{let e=await aa({builder:a,txBlock:t});return{claimReferralRevenueQuick:async(n,r,o=[...G])=>{let i=[];for(let s=0;s<o.length;s++)if(o[s]==="sui"){let c=e.claimReferralRevenue(n,o[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,o[s]);try{let d=await a.utils.selectCoinIds(1/0,a.utils.parseCoinType(o[s]),r);t.mergeCoins(c,d.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(r))}}};var Qc={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},Zo={check_slippage:(a,t,e,n,r)=>a.moveCall({target:`${Qc.packageId}::slippage_check::check_slippage`,arguments:[t,a.pure(e),a.pure(n)],typeArguments:[r]})};import{SUI_CLOCK_OBJECT_ID as ra}from"@mysten/sui.js/utils";var ti=async(a,t,e,n,r,o,i=!1)=>{let s=await dt({builder:a,txBlock:t}),c=await ni({builder:a,txBlock:t});try{let{takeCoin:d,leftCoin:l,totalAmount:u}=i?await a.selectSCoin(t,n,r,o):await a.selectMarketCoin(t,n,r,o);if(i){let p=s.burnSCoin(n,d);c.stake(e,p,n)}else c.stake(e,d,n);return t.transferObjects([l],o),u}catch{return 0}},ei=async(...a)=>{let[t,e,n,r]=a;if(a.length===4&&r)return[r];let o=B(e);return(await Gt(t.query,o))[n].map(s=>s.id)},Vc=async(...a)=>{let[t,e,n,r]=a,o=B(e),i=await Gt(t.query,o);if(i[n].length===0)throw new Error(`No stake account found for sender ${o}`);return r?i[n].filter(c=>c.id===r):i[n]},ni=async({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")},n={},r={},o={};return st.forEach(i=>{let s=a.address.get(`spool.pools.${i}.id`),c=a.address.get(`spool.pools.${i}.rewardPoolId`),d=a.utils.parseMarketCoinType(i);n[i]=s,r[i]=c,o[i]=d}),{createStakeAccount:i=>{let s=o[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(ra)],typeArguments:[s]})},stake:(i,s,c)=>{let d=o[c],l=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(l),t.object(i),typeof s=="string"?t.pure(s):s,t.object(ra)],typeArguments:[d]})},unstake:(i,s,c)=>{let d=o[c],l=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(l),t.object(i),t.pure(s),t.object(ra)],typeArguments:[d]})},claim:(i,s)=>{let c=n[s],d=r[s],l=o[s],u=bn[s],p=a.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(d),t.object(i),t.object(ra)],typeArguments:[l,p]})}}},Y=async({builder:a,txBlock:t})=>{let e=await ni({builder:a,txBlock:t}),n=await dt({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(r,o,i)=>{let s=B(t),c=await ei(a,t,o,i),d=[];if(c.length===0){let l=e.createStakeAccount(o);d.push(l)}if(typeof r=="number"){let l=await ti(a,t,c.length>0?c[0]:d[0],o,r,s);r-=l,l||await ti(a,t,c.length>0?c[0]:d[0],o,r,s,!0)}else e.stake(c.length>0?c[0]:d[0],r,o);d.length>0&&t.transferObjects(d,s)},unstakeQuick:async(r,o,i,s)=>{let c=await Vc(a,t,o,i),d=[],l=r;for(let u of c){if(u.staked===0)continue;let p=Math.min(l,u.staked),m=e.unstake(u.id,p,o);if(s){let f=n.mintSCoin(o,m);d.push(f)}else d.push(m);if(l-=p,r<=0)break}if(d.length>0){let u=d[0];return d.length>1&&t.mergeCoins(u,d.slice(1)),u}},claimQuick:async(r,o)=>{let i=await ei(a,t,r,o),s=[];return i.forEach(c=>{let d=e.claim(c,r);s.push(d)}),s}}};import{SUI_CLOCK_OBJECT_ID as Xt}from"@mysten/sui.js/utils";var Kc=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("vesca.id"),table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{lockSca:(n,r)=>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(r),t.object(Xt)]}),extendLockPeriod:(n,r)=>{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(r),t.object(Xt)]})},extendLockAmount:(n,r)=>{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 r=="string"?t.pure(r):r,t.object(Xt)]})},renewExpiredVeSca:(n,r,o)=>{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 r=="string"?t.pure(r):r,t.pure(o),t.object(Xt)]})},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(Xt)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},ut=async({builder:a,txBlock:t})=>{let e=await Kc({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,r,o=!0)=>{let i=B(t),s=await Ot(a,t),c,d=[];if(n!==void 0&&typeof n=="number"){let m=await a.utils.selectCoinIds(n,ot,i),[f,y]=a.utils.takeAmountFromCoins(t,m,n);c=f,d.push(y)}else c=n;let l=a.utils.getUnlockAt(r,s?.unlockAt);o&&Wo(n,r,l,s?.unlockAt),console.log(new Date(l*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,l);d.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);d.push(m)}e.renewExpiredVeSca(s.keyId,c,l)}}else c&&r?(e.extendLockPeriod(s.keyId,l),e.extendLockAmount(s.keyId,c)):r?e.extendLockPeriod(s.keyId,l):c&&e.extendLockAmount(s.keyId,c);d.length>0&&t.transferObjects(d,i)},extendLockPeriodQuick:async(n,r,o=!0)=>{let i=await Ot(a,t,r),s=a.utils.getUnlockAt(n);o&&Uo(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,r,o=!0)=>{let i=B(t),s=await Ot(a,t,r);if(o&&Fo(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,ot,i),[d,l]=a.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,d),t.transferObjects([l],i)}},renewExpiredVeScaQuick:async(n,r,o,i=!0)=>{let s=B(t),c=await Ot(a,t,o),d=a.utils.getUnlockAt(r,c?.unlockAt);if(i&&$o(n,r,c?.unlockAt),c){let l=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);l.push(f)}let u=await a.utils.selectCoinIds(n,ot,s),[p,m]=a.utils.takeAmountFromCoins(t,u,n);l.push(m),e.renewExpiredVeSca(c.keyId,p,d),t.transferObjects(l,s)}},redeemScaQuick:async n=>{let r=B(t),o=await Ot(a,t,n);if(xt(o?.unlockAt),o){let i=e.redeemSca(o.keyId);t.transferObjects([i],r)}}}};import{normalizeStructTag as zc}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as Hc}from"@mysten/sui.js/utils";var Pt={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}}},ai={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},pr={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},ri={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 oi={objectId:Hc,initialSharedVersion:"1",mutable:!1},Gc=(a,t)=>{if(a==="sui")switch(t){case"wusdc":return{pool:Pt.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdc")switch(t){case"sui":return{pool:Pt.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:Pt.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:Pt.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdt")switch(t){case"wusdc":return{pool:Pt.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else throw new Error(`Invalid coin pair: ${a} and ${t}`)},mr={createAccount:a=>a.moveCall({target:`${ai.id}::${ri.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(a,t,e,n,r,o,i)=>{let{pool:s,aToB:c}=Gc(e,n),d=i.parseCoinType(e),l=i.parseCoinType(n),u=typeof o=="string"?a.object(o):"objectId"in o?a.objectRef(o):a.object(o);if(!s)throw new Error(`Deepbook: No pool found for ${e} to ${n}`);return c?a.moveCall({target:`${pr.id}::deepbook::deepbook_base_for_quote`,arguments:[a.sharedObjectRef(s.object),a.pure(r),u,a.object(t),a.sharedObjectRef(oi),a.pure(s.lotsize)],typeArguments:[d,l]}):a.moveCall({target:`${pr.id}::deepbook::deepbook_quote_for_base`,arguments:[a.sharedObjectRef(s.object),a.pure(r),u,a.sharedObjectRef(oi),a.object(t),a.pure(s.lotsize)],typeArguments:[l,d]})}};var oa=class{suiClient;scallopUtils;_clientOrderId=0;_accountCap;currentAddress;constructor({client:t,currentAddress:e,accountCap:n,scallopUtils:r}){this.currentAddress=e,this.suiClient=t,this._accountCap=n,this.scallopUtils=r}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:zc("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?mr.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:r}){let o=await this.accountCap(r);return{swapResult:mr.swap(r,t,e,n,this.clientOrderId,o,this.scallopUtils),accountCap:o}}};var ia=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 Yn(t,this.address),this.query=new Xn(t,{address:this.address,utils:this.utils}),this.builder=new Hn(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new oa({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 T,n=await M({builder:this.builder,txBlock:e}),r=await N({builder:this.builder,txBlock:e}),o=t||this.params.walletAddress;e.setSender(o);let[i,s,c]=n.normalMethod.openObligation();return r.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],o),e}async depositCollateral(t,e,n,r){let o=new T,i=r||this.params.walletAddress;o.setSender(i);let s=await M({builder:this.builder,txBlock:o}),c=await this.query.getObligations(i),d=n||c?.[0]?.id;if(d)await s.addCollateralQuick(e,t,d);else{let[l,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,l),s.normalMethod.returnObligation(l,p),o.transferObjects([u],i)}return o}async withdrawCollateral(t,e,n,r,o){let i=new T,s=await M({builder:this.builder,txBlock:i}),c=o||this.params.walletAddress;i.setSender(c);let d=await s.takeCollateralQuick(e,t,n,r);return i.transferObjects([d],c),i}async deposit(t,e,n){let r=new T,o=await M({builder:this.builder,txBlock:r}),i=await dt({builder:this.builder,txBlock:r}),s=n||this.params.walletAddress;r.setSender(s);let c=await o.depositQuick(e,t,n),d=this.utils.parseMarketCoinName(t);if(!z.includes(d))r.transferObjects([c],s);else{let l=i.mintSCoin(d,c);r.transferObjects([l],s)}return r}async withdraw(t,e,n){let r=new T,o=n||this.params.walletAddress,i=await M({builder:this.builder,txBlock:r});r.setSender(o);let s=await i.withdrawQuick(e,t);return r.transferObjects([s],o),r}async borrow(t,e,n,r,o){let i=new T,s=await M({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=ct.includes(t);l&&await c.unstakeObligationQuick(n,r);let u=await s.borrowQuick(e,t,n,r);return i.transferObjects([u],d),l&&await c.stakeObligationQuick(n,r),i}async borrowWithBoost(t,e,n,r,o,i){let s=new T,c=await M({builder:this.builder,txBlock:s}),d=await N({builder:this.builder,txBlock:s}),l=i||this.params.walletAddress;s.setSender(l);let u=ct.includes(t);u&&await d.unstakeObligationQuick(n,r);let p=await c.borrowQuick(e,t,n,r);return s.transferObjects([p],l),u&&await d.stakeObligationWithVeScaQuick(n,r,o),s}async borrowWithReferral(t,e,n,r,o,i){let s=new T,c=await M({builder:this.builder,txBlock:s}),d=await N({builder:this.builder,txBlock:s}),l=await aa({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=ct.includes(t);p&&await d.unstakeObligationQuick(n,r);let m=l.claimReferralTicket(t),f=await c.borrowWithReferralQuick(e,t,m,n,r);return l.burnReferralTicket(m,t),s.transferObjects([f],u),p&&o?await d.stakeObligationWithVeScaQuick(n,r,o):await d.stakeObligationQuick(n,r),s}async repay(t,e,n,r,o){let i=new T,s=await M({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=ct.includes(t);return l&&await c.unstakeObligationQuick(n,r),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationQuick(n,r),i}async repayWithBoost(t,e,n,r,o){let i=new T,s=await M({builder:this.builder,txBlock:i}),c=await N({builder:this.builder,txBlock:i}),d=o||this.params.walletAddress;i.setSender(d);let l=ct.includes(t);return l&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationWithVeScaQuick(n,void 0,r),i}async createStakeAccount(t,e){let n=new T,r=await Y({builder:this.builder,txBlock:n}),o=e||this.params.walletAddress;n.setSender(o);let i=r.normalMethod.createStakeAccount(t);return n.transferObjects([i],o),n}async supplyAndStake(t,e,n,r){let o=new T,i=await M({builder:this.builder,txBlock:o}),s=await Y({builder:this.builder,txBlock:o}),c=r||this.params.walletAddress;o.setSender(c);let d=await i.depositQuick(e,t,r),l=this.utils.parseMarketCoinName(t);if(!st.find(m=>m===l))return o;let u=await this.query.getStakeAccounts(l,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(d,l,p);else{let m=s.normalMethod.createStakeAccount(l);await s.stakeQuick(d,l,m),o.transferObjects([m],c)}return o}async unstakeAndWithdraw(t,e,n){let r=new T,o=await M({builder:this.builder,txBlock:r}),i=await Y({builder:this.builder,txBlock:r}),s=this.params.walletAddress,c=[];r.setSender(s);let d=this.utils.parseMarketCoinName(t);for(let l=0;l<n.length;l++){let u=n[l],[p]=await i.unstakeQuick(u.coin,d,u.id);if(p){let m=o.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let l=await o.withdrawQuick(e,t);c.push(l)}return c.length>1&&r.mergeCoins(c[0],c.slice(1)),r.transferObjects(c,s),r}async stake(t,e,n,r){let o=new T,i=await Y({builder:this.builder,txBlock:o}),s=r||this.params.walletAddress;o.setSender(s);let c=await this.query.getStakeAccounts(t,s),d=n||(c.length>0?c[0].id:void 0);if(d)await i.stakeQuick(e,t,d);else{let l=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,l),o.transferObjects([l],s)}return o}async unstake(t,e,n,r){let o=new T,i=await Y({builder:this.builder,txBlock:o}),s=r||this.params.walletAddress;o.setSender(s);let c=z.includes(t),d=await i.unstakeQuick(e,t,n,c);return o.transferObjects([d],o.pure(s)),o}async claim(t,e,n,r){let o=new T,i=await Y({builder:this.builder,txBlock:o}),s=await N({builder:this.builder,txBlock:o}),c=r||this.params.walletAddress;o.setSender(c);let d={sui:[],sca:[]};for(let l=0;l<t.length;l++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[l],m=i.normalMethod.claim(p,u);d.sui.push(m)}for(let l=0;l<e.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[l],f=s.normalMethod.claimBorrowIncentive(u,p,m);d[m].push(f)}for(let l=0;l<n.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[l],f=s.normalMethod.oldClaimBorrowIncentive(u,p,m);d[m].push(f)}return d.sui.length>0&&(d.sui.length>1&&o.mergeCoins(d.sui[0],d.sui.slice(1)),o.transferObjects([d.sui[0]],o.pure(c))),d.sca.length>0&&(d.sca.length>1&&o.mergeCoins(d.sca[0],d.sca.slice(1)),o.transferObjects([d.sca[0]],o.pure(c))),o}async stakeObligation(t,e,n){let r=this.builder.createTxBlock(),o=await N({builder:this.builder,txBlock:r}),i=n||this.params.walletAddress;return r.setSender(i),await o.stakeObligationQuick(t,e),r}async unstakeObligation(t,e,n){let r=this.builder.createTxBlock(),o=await N({builder:this.builder,txBlock:r}),i=n||this.params.walletAddress;return r.setSender(i),await o.unstakeObligationQuick(t,e),r}async stakeSca(t,e=!1,n=!1,r,o,i,s,c){let d=new T,l=await ut({builder:this.builder,txBlock:d}),u=await N({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,ot,p),[f,y]=this.builder.utils.takeAmountFromCoins(d,m,t),C;return s?l.normalMethod.extendLockAmount(s,f):C=l.normalMethod.lockSca(f,i),r&&o&&(e&&(n?u.normalMethod.oldUnstakeObligation(r,o):u.normalMethod.unstakeObligation(r,o)),u.normalMethod.stakeObligationWithVesca(r,o,s||C)),s||d.transferObjects([C,y],p),d}async stakeMoreSca(t,e,n){let r=new T,o=n||this.params.walletAddress;return r.setSender(o),r}async extendStakeScaLockPeriod(t,e,n,r,o=!1,i=!1,s){let c=new T,d=await ut({builder:this.builder,txBlock:c}),l=await N({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),d.normalMethod.extendLockPeriod(e,t),n&&r&&(o&&(i?l.normalMethod.oldUnstakeObligation(n,r):l.normalMethod.unstakeObligation(n,r)),l.normalMethod.stakeObligationWithVesca(n,r,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,r,o,i=!1,s=!1,c){let d=new T,l=await ut({builder:this.builder,txBlock:d}),u=await N({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,ot,p),[f,y]=this.builder.utils.takeAmountFromCoins(d,m,t);return l.normalMethod.extendLockPeriod(e,n),l.normalMethod.extendLockAmount(e,f),d.transferObjects([y],p),!r||!o||(i&&(s?u.normalMethod.oldUnstakeObligation(r,o):u.normalMethod.unstakeObligation(r,o)),u.normalMethod.stakeObligationWithVesca(r,o,e)),d}async renewExpiredStakeSca(t,e,n,r=!1,o,i,s=!1,c=!1,d){let l=new T,u=await ut({builder:this.builder,txBlock:l}),p=await N({builder:this.builder,txBlock:l}),m=d||this.params.walletAddress;if(l.setSender(m),r){let v=u.normalMethod.redeemSca(n);l.transferObjects([v],m)}let f=await this.builder.utils.selectCoinIds(t,ot,m),[y,C]=this.builder.utils.takeAmountFromCoins(l,f,t);return l.transferObjects([C],m),u.normalMethod.renewExpiredVeSca(n,y,e),!o||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(o,i):p.normalMethod.unstakeObligation(o,i)),p.normalMethod.stakeObligationWithVesca(o,i,n)),l}async redeemSca(t){let e=new T,n=await ut({builder:this.builder,txBlock:e}),r=this.params.walletAddress;return e.setSender(r),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,r){let o=new T,i=await N({builder:this.builder,txBlock:o}),s=this.params.walletAddress;o.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return o.transferObjects([c],s),await i.unstakeObligationQuick(e,t),r?await i.stakeObligationWithVeScaQuick(e,t,r):await i.stakeObligationQuick(e,t),o}async withdrawUnlockedSca(t,e){let n=new T,r=await ut({builder:this.builder,txBlock:n}),o=e||this.params.walletAddress;return n.setSender(o),await r.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new ii(t.weightedAmount),o=e.currentPointIndex?ii(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(o).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new T,e=await ut({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let r=e.normalMethod.mintEmptyVeSca();return t.transferObjects([r],n),t}async claimRevenuReferral(t,e){let n=new T,r=await Yo({builder:this.builder,txBlock:n}),o=this.params.walletAddress;n.setSender(o);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await r.claimReferralRevenueQuick(t,o,i),n}async bindReferral(t){let e=new T,n=await aa({builder:this.builder,txBlock:e}),r=this.params.walletAddress;return e.setSender(r),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new T,e=await dt({builder:this.builder,txBlock:t}),n=await Y({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let r=[];return await Promise.all(z.map(async o=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(o),this.params.walletAddress),d=c[0];c.length>1&&t.mergeCoins(d,c.slice(1)),s=d}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(o,s);try{let d=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(o),this.params.walletAddress);t.mergeCoins(c,d)}catch(d){console.log(d)}i.push(c)}if(st.includes(o))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,o);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)),r.push(c)}})),r.length>0&&t.transferObjects(r,this.params.walletAddress),t}async migrateLendingWusdcToUsdcNative(t,e,n,r,o){let i=new T,s=await M({builder:this.builder,txBlock:i}),c=await Y({builder:this.builder,txBlock:i}),d=this.params.walletAddress,l=[],u=this.utils.parseMarketCoinName(t),p=this.utils.parseMarketCoinType(u),f=(await this.utils.selectCoinsMarketCoin(p,d)).map(R=>R.objectId);i.setSender(d);for(let R=0;R<o.length;R++){let U=o[R],[L]=await c.unstakeQuick(U.coin,u,U.id);if(L){f.length>0&&i.mergeCoins(L,f);let bi=s.normalMethod.withdraw(L,t);l.push(bi)}}if(e>0){let R=await s.withdrawQuick(e,t);l.push(R)}l.length>1&&i.mergeCoins(l[0],l.slice(1));let[y]=i.splitCoins(l[0],[i.pure(r)]);i.transferObjects([l[0]],d);let{swapResult:C,accountCap:v}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:y,tx:i});typeof v=="string"&&i.transferObjects([v],d),Zo.check_slippage(i,C,n,r,this.query.utils.parseCoinType("usdc"));let E=s.normalMethod.deposit(C,"usdc");return await c.stakeQuick(E,"susdc"),i}};var Yt=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Kn({id:vo})),await this.address.read(),this.client=new ia(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var sa=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new Yt({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new gn(e,this.scallop),r=new hn(e,this.scallop),o=new Sn(e,this.scallop),i=n.decode()||r.decode()||o.decode();if(!i)throw new Error("Unknown transaction type");return{txType:Jc.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:r,txSubType:o,intentionData:i}=t;this.scallop||(this.scallop=new Yt({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(o){case"SupplyLending":s=_n.fromData(i);break;case"WithdrawLending":s=Nn.fromData(i);break;case"Borrow":s=yn.fromData(i);break;case"Repay":s=On.fromData(i);break;case"DepositCollateral":s=Tn.fromData(i);break;case"WithdrawCollateral":s=Bn.fromData(i);break;case"OpenObligation":s=An.fromData(i);break;case"StakeSpool":s=Dn.fromData(i);break;case"UnstakeSpool":s=Rn.fromData(i);break;case"ClaimIncentiveReward":s=In.fromData(i);break;case"BorrowWithBoost":s=wn.fromData(i);break;case"StakeSca":s=qn.fromData(i);break;case"ExtendStakePeriod":s=Un.fromData(i);break;case"ExtendPeriodAndStakeMore":s=Wn.fromData(i);break;case"RenewExpStakePeriod":s=$n.fromData(i);break;case"WithdrawStakedSca":s=Vn.fromData(i);break;case"SupplyAndStakeLending":s=Qn.fromData(i);break;case"WithdrawAndUnstakeLending":s=jn.fromData(i);break;case"RedeemSca":s=Fn.fromData(i);break;case"MigrateAndClaim":s=kn.fromData(i);break;case"BorrowWithReferral":s=Cn.fromData(i);break;case"CreateReferralLink":s=Ln.fromData(i);break;case"ClaimRevenueReferral":s=En.fromData(i);break;case"BindReferral":s=Mn.fromData(i);break;case"MigrateScoin":s=vn.fromData(i);break;case"RepayWithBoost":s=Pn.fromData(i);break;case"MigrateWusdcToUsdc":s=xn.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:r,scallop:this.scallop})}};import{TransactionType as hl}from"@msafe/sui3-utils";import{TurbosSdk as Sl}from"turbos-clmm-sdk";import{TransactionType as q}from"@msafe/sui3-utils";import{bcs as si}from"@mysten/sui.js/bcs";import{normalizeStructTag as Yc,normalizeSuiAddress as Zt}from"@mysten/sui.js/utils";import{BN as Zc}from"turbos-clmm-sdk";var Q={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},V={PackageId:"0xdee9"};var tl=(a,t,e,n)=>{if(a===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(o=>o===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},ca=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(`${Q.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Q.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${V.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${V.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=tl(e,t.target,this.swap1Layer,this.swap2Layer),r=n.map((m,f)=>{let y=this.helper.decodeSharedObjectId(f),C=this.helper.decodeInputU128(4+f+e),v=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Zc(C.toString()));return{pool:y,a2b:m,nextTickIndex:v}}),o=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),d=this.helper.decodeInputBool(5+2*e),l=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:r[0].pool,a2b:r[0].a2b,amountSpecified:l}],address:s,amountSpecifiedIsInput:d});return{txType:q.Other,type:"Swap",intentionData:{routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:d?l:u,amountB:d?u:l,amountSpecifiedIsInput:d,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),r=this.helper.decodeInputU64(9),o=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),d=this.helper.decodeInputU64(13);return{txType:q.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:r,tickLower:i?-o:o,tickUpper:c?-s:s,deadline:d}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),r=this.helper.decodeInputU64(5),o=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:q.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:r,amountB:o,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),r=this.helper.decodeInputU64(3),o=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:q.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:r,nft:n,amountA:o,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),r=this.helper.decodeInputU64(3),o=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:q.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:r,collectAmountB:o,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),r=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),o=this.helper.decodeInputU64(7);return{txType:q.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:r,nft:e,deadline:o}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:q.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),r=this.decreaseLiquidityHelper.decodeInputU64(3),o=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),d=this.collectFeeHelper.decodeInputU64(3)||0,l=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:q.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:r,nft:n,amountA:o,amountB:i,slippage:10,address:t,collectAmountA:d,collectAmountB:l,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:q.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:q.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),r=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:q.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:r}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),r=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:q.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:r}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new pt(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 pt(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new pt(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 pt(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${V.PackageId}::clob_v2::swap_exact_base_for_quote`);return new pt(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${V.PackageId}::clob_v2::swap_exact_quote_for_base`);return new pt(t,this.txb)}},pt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 Zt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 si.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 Zt(t.value.Object.ImmOrOwned.objectId)}return Zt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Zt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Zt(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 si.de(e,new Uint8Array(n))}typeArg(t){return Yc(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as el}from"turbos-clmm-sdk";var la=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new el(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,tickLower:d,tickUpper:l,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,tickLower:d,tickUpper:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as nl}from"turbos-clmm-sdk";var da=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new nl(e.network.replace("sui:",""),e.suiClient),{pool:r,nft:o,txb:i}=this.data;return n.nft.burn({pool:r,nft:o,txb:i})}static fromData(e){return new a(e)}};import{TurbosSdk as al}from"turbos-clmm-sdk";var ua=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new al(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,nft:i,collectAmountA:s,collectAmountB:c,deadline:d,txb:l}=this.data;return n.pool.collectFee({pool:r,address:o,collectAmountA:s,collectAmountB:c,nft:i,deadline:d,txb:l})}static fromData(e){return new a(e)}};import{TurbosSdk as rl}from"turbos-clmm-sdk";var pa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new rl(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,nft:i,rewardAmounts:s,deadline:c,txb:d}=this.data;return n.pool.collectReward({pool:r,address:o,rewardAmounts:s,nft:i,deadline:c,txb:d})}static fromData(e){return new a(e)}};import{TurbosSdk as ol}from"turbos-clmm-sdk";var ma=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new ol(e.network.replace("sui:",""),e.suiClient),{fee:r,address:o,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,amountA:p,amountB:m,deadline:f,txb:y}=this.data;return n.pool.createPool({fee:r,amountA:p,amountB:m,address:o,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,deadline:f,txb:y})}static fromData(e){return new a(e)}};import{TurbosSdk as il}from"turbos-clmm-sdk";var fa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new il(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,nft:d,decreaseLiquidity:l,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,nft:d,decreaseLiquidity:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as sl}from"turbos-clmm-sdk";var ba=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new sl(e.network.replace("sui:",""),e.suiClient),{pool:r,address:o,amountA:i,amountB:s,slippage:c,nft:d,deadline:l,txb:u}=this.data;return n.pool.increaseLiquidity({pool:r,slippage:c,address:o,amountA:i,amountB:s,nft:d,deadline:l,txb:u})}static fromData(e){return new a(e)}};import{TransactionBlock as cl}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as ll}from"@mysten/sui.js/utils";var ga=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new cl;return n.moveCall({target:`${Q.PackageId}::claim::claim`,typeArguments:[Q.turbosCoinType],arguments:[n.object(Q.Claim),n.object(ll)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as dl}from"@mysten/sui.js/transactions";var ha=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new dl;return n.moveCall({target:`${Q.PackageId}::claim::join`,typeArguments:[Q.turbosCoinType],arguments:[n.object(Q.Claim)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as ul}from"@mysten/sui.js/transactions";import{TurbosSdk as pl}from"turbos-clmm-sdk";var Sa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new pl(e.network.replace("sui:",""),e.suiClient),r=new ul;return r=await n.pool.collectFee({txb:r,...this.data}),r=await n.pool.collectReward({txb:r,...this.data}),r=await n.pool.decreaseLiquidity({txb:r,...this.data}),r=await n.nft.burn({txb:r,nft:this.data.nft,pool:this.data.pool}),r}static fromData(e){return new a(e)}};import{TurbosSdk as ml}from"turbos-clmm-sdk";var ya=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new ml(e.network.replace("sui:",""),e.suiClient),{routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:c,amountB:d,slippage:l,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:r,coinTypeA:o,coinTypeB:i,address:s,amountA:c,amountB:d,amountSpecifiedIsInput:u,slippage:l,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as bl}from"turbos-clmm-sdk";import{normalizeSuiObjectId as ci}from"@mysten/sui.js/utils";import{TransactionBlock as li}from"@mysten/sui.js/transactions";import{unstable_getObjectId as fl}from"turbos-clmm-sdk";var te=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let r=[],o;do o=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:o?.nextCursor}),r.push(...o.data);while(o.hasNextPage);let i=[],s=0;return r.sort((c,d)=>Number(d.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 r=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(r,t.slice(1).map(i=>n.object(i.coinObjectId)));let[o]=n.splitCoins(r,[n.pure(e)]);return[o,r]}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:`${V.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?fl(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${V.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var di=89,ui=1e6,pi=async a=>{let{token1:t,token2:e,poolId:n,amountIn:r,currentAddress:o,turbosSdk:i}=a,s=new li,c=new te(i),d=await c.getCoinsData(o,e,r),[l,u]=c.splitAndMergeCoin(d,r,s);if(!l)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(o),m=p?s.object(p):c.createAccount(s),[f,y,C]=s.moveCall({typeArguments:[t,e],target:`${V.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(di),m,s.pure(r),s.object(ci("0x6")),l]});return u&&s.transferObjects([u],s.pure(o)),s.transferObjects([f],s.pure(o)),s.transferObjects([y],s.pure(o)),p||s.transferObjects([m],s.pure(o)),s.setSenderIfNotSet(o),s.setGasBudget(ui),s},mi=async a=>{let{token1:t,token2:e,poolId:n,amountIn:r,currentAddress:o,turbosSdk:i}=a,s=new li,c=new te(i),d=await c.getCoinsData(o,t,r),[l,u]=c.splitAndMergeCoin(d,r,s);if(!l)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(o),m=p?s.object(p):c.createAccount(s),f=c.zero(e,s),[y,C,v]=s.moveCall({typeArguments:[t,e],target:`${V.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(di),m,s.pure(r),l,f,s.object(ci("0x6"))]});return u&&s.transferObjects([u],s.pure(o)),s.transferObjects([y],s.pure(o)),s.transferObjects([C],s.pure(o)),p||s.transferObjects([m],s.pure(o)),s.setSenderIfNotSet(o),s.setGasBudget(ui),s};var wa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new bl(e.network.replace("sui:",""),e.suiClient);return await mi({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};import{TurbosSdk as gl}from"turbos-clmm-sdk";var Ca=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new gl(e.network.replace("sui:",""),e.suiClient);return await pi({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var Ia=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new Sl(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:r,account:o}=t;console.log(t,"input");let s=await new ca(r,e,n).decode(o.address);return{txType:hl.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:r}=t,o;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":o=ma.fromData(t.intentionData);break;case"AddLiquidity":o=la.fromData(t.intentionData);break;case"IncreaseLiquidity":o=ba.fromData(t.intentionData);break;case"DecreaseLiquidity":o=fa.fromData(t.intentionData);break;case"RemoveLiquidity":o=Sa.fromData(t.intentionData);break;case"CollectFee":o=ua.fromData(t.intentionData);break;case"CollectReward":o=pa.fromData(t.intentionData);break;case"Burn":o=da.fromData(t.intentionData);break;case"Swap":o=ya.fromData(t.intentionData);break;case"PrixJoin":o=ha.fromData(t.intentionData);break;case"PrixClaim":o=ga.fromData(t.intentionData);break;case"SwapExactBaseForQuote":o=wa.fromData(t.intentionData);break;case"SwapExactQuoteForBase":o=Ca.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n,network:r})}};import{TransactionType as vl}from"@msafe/sui3-utils";import{TransactionType as fr}from"@msafe/sui3-utils";import{bcs as fi}from"@mysten/sui.js/bcs";import{normalizeStructTag as Cl,normalizeSuiAddress as ee}from"@mysten/sui.js/utils";var yl={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},O=yl;var Ta=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:fr.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:fr.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:fr.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(O.packageId));return new br(t,this.txb)}},br=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.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 ee(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.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 fi.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 ee(t.value.Object.ImmOrOwned.objectId)}return ee(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ee(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ee(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 fi.de(e,new Uint8Array(n))}typeArg(t){return Cl(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Il}from"@mysten/sui.js/transactions";var ka=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Il,{ticketId:r}=this.data;return n.moveCall({target:`${O.packageId}::native_pool::burn_ticket`,arguments:[n.object(O.poolObjectId),n.object(O.systemStateObjectId),n.object(r)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Tl}from"@mysten/sui.js/transactions";var va=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Tl,{amount:r}=this.data,[o]=n.splitCoins(n.gas,[n.pure(r)]);return n.moveCall({target:`${O.packageId}::native_pool::stake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),o]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as kl}from"@mysten/sui.js/transactions";var xa=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new kl,{amount:r}=this.data,o=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=o.filter(l=>l.coinType.split("::")[0]===O.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(l=>n.object(l.coinObjectId)));let d=n.splitCoins(n.object(i.coinObjectId),[n.pure(r)]);return n.moveCall({target:`${O.packageId}::native_pool::unstake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),d]}),n}static fromData(e){return new a(e)}};var Aa=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,r=new Ta(e).decode();return{txType:vl.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n}=t,r;switch(t.txSubType){case"Stake":r=va.fromData(t.intentionData);break;case"UnStake":r=xa.fromData(t.intentionData);break;case"ClaimTicket":r=ka.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n})}};var jv=pn.fromHelpers([new Ze,new dn,new ze,new un,new Te,new Ia,new sa,new Aa]);export{jv as appHelpers};
2
2
  //# sourceMappingURL=index.mjs.map