@msafe/sui-app-store 0.0.112 → 0.0.113

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 Er=Object.defineProperty;var Za=(a,t)=>{for(var e in t)Er(a,e,{get:t[e],enumerable:!0})};import{TransactionType as di}from"@msafe/sui3-utils";import{TransactionType as Qr}from"@msafe/sui3-utils";import Mr from"sort-keys-recursive";var u=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(Mr(this.data))}};import{CetusPeripherySDK as Lr}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as Wr}from"@cetusprotocol/cetus-sui-clmm-sdk";var Fr={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:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",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"},qr={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:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},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:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},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:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Ur={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"},$r={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"}},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"}},haedal:{package_id:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472",published_at:"0x9dac9c5770e5f930d2223ff68782958701acfaee9337e8d8363978ce7670dffb",config:{support_stakings:[{staking_id:"0x6e384d2da5b040b27f973155e25bbe4beb0ad5ca8ee0a36e20dff356094c9fc0",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472::hasui::HASUI"}]}}},dt=(a,t)=>{let e=a==="sui:mainnet"?Fr:Ur,n=new Wr(e);return n.senderAddress=t.address,n},_=(a,t)=>{let e=dt(a,t),n=a==="sui:mainnet"?qr:$r;return new Lr(n,e)};var to=async(a,t,e)=>await dt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),eo=async(a,t,e)=>await dt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),no=async(a,t,e)=>await dt(e,t).Position.closePositionTransactionPayload(a),ao=async(a,t,e)=>await dt(e,t).Position.removeLiquidityTransactionPayload(a),oo=async(a,t,e)=>await dt(e,t).Rewarder.collectRewarderTransactionPayload(a);var ae=class a extends u{constructor(e){super(e);this.data=e}txType=Qr.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await to(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Vr}from"@msafe/sui3-utils";var oe=class a extends u{constructor(e){super(e);this.data=e}txType=Vr.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await oo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Gr}from"@msafe/sui3-utils";var re=class a extends u{constructor(e){super(e);this.data=e}txType=Gr.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ao(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Kr}from"@msafe/sui3-utils";var ro=async(a,t,e)=>await _(e,t).Farms.openPositionAddLiquidityStakePaylod(a),io=async(a,t,e)=>await _(e,t).Farms.addLiquidityFixCoinPayload(a),so=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),co=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),lo=async(a,t,e)=>await _(e,t).Farms.claimFeeAndClmmReward(a),uo=async(a,t,e)=>{let n=_(e,t);return console.log("getFarmingHarvest txbParams: ",a),await n.Farms.harvestPayload(a)},po=async(a,t,e)=>{let n=_(e,t),o=Object.values(a);return console.log("getFarmingBatchHarvest params: ",o),await n.Farms.batchHarvestPayload(o)},mo=async(a,t,e)=>await _(e,t).Farms.depositPayload(a),bo=async(a,t,e)=>await _(e,t).Farms.withdrawPayload(a);var ie=class a extends u{constructor(e){super(e);this.data=e}txType=Kr.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ro(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Hr}from"@msafe/sui3-utils";var se=class a extends u{constructor(e){super(e);this.data=e}txType=Hr.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await po(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as zr}from"@msafe/sui3-utils";var ce=class a extends u{constructor(e){super(e);this.data=e}txType=zr.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await lo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Xr}from"@msafe/sui3-utils";var de=class a extends u{constructor(e){super(e);this.data=e}txType=Xr.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await so(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Jr}from"@msafe/sui3-utils";var le=class a extends u{constructor(e){super(e);this.data=e}txType=Jr.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await uo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Yr}from"@msafe/sui3-utils";var ue=class a extends u{constructor(e){super(e);this.data=e}txType=Yr.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await io(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Zr}from"@msafe/sui3-utils";var pe=class a extends u{constructor(e){super(e);this.data=e}txType=Zr.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await co(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ti}from"@msafe/sui3-utils";var me=class a extends u{constructor(e){super(e);this.data=e}txType=ti.Other;txSubType="FarmingStake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await mo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ei}from"@msafe/sui3-utils";var be=class a extends u{constructor(e){super(e);this.data=e}txType=ei.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await bo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ni}from"@msafe/sui3-utils";var fe=class a extends u{constructor(e){super(e);this.data=e}txType=ni.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await eo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ai}from"@msafe/sui3-utils";var ge=class a extends u{constructor(e){super(e);this.data=e}txType=ai.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await no(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as oi}from"@msafe/sui3-utils";var fo=async(a,t,e)=>await _(e,t).XCetusModule.convertPayload(a),go=async(a,t,e)=>await _(e,t).XCetusModule.redeemLockPayload(a),ho=async(a,t,e)=>await _(e,t).XCetusModule.redeemDividendV2Payload(a.venft_id,a.bonus_types,a.xTokenType),yo=async(a,t,e)=>await _(e,t).XCetusModule.cancelRedeemPayload(a),So=async(a,t,e)=>await _(e,t).XCetusModule.redeemPayload(a);var he=class a extends u{constructor(e){super(e);this.data=e}txType=oi.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await yo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ri}from"@msafe/sui3-utils";var ye=class a extends u{constructor(e){super(e);this.data=e}txType=ri.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ho(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ii}from"@msafe/sui3-utils";var Se=class a extends u{constructor(e){super(e);this.data=e}txType=ii.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await fo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as si}from"@msafe/sui3-utils";var we=class a extends u{constructor(e){super(e);this.data=e}txType=si.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await So(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ci}from"@msafe/sui3-utils";var Ce=class a extends u{constructor(e){super(e);this.data=e}txType=ci.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await go(r,n,o)}static fromData(e){return new a(e)}};var Te=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:di.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:o}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let r;switch(t.txSubType){case"OpenAndAddLiquidity":r=ae.fromData(t.intentionData);break;case"IncreaseLiquidity":r=fe.fromData(t.intentionData);break;case"DecreaseLiquidity":r=re.fromData(t.intentionData);break;case"RemoveLiquidity":r=ge.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=oe.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=ie.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=ue.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=de.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=pe.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=ce.fromData(t.intentionData);break;case"FarmingHarvest":r=le.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=se.fromData(t.intentionData);break;case"FarmingStake":r=me.fromData(t.intentionData);break;case"FarmingUnstake":r=be.fromData(t.intentionData);break;case"xCETUSConvert":r=Se.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Ce.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=ye.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=he.fromData(t.intentionData);break;case"xCETUSRedeem":r=we.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",r),console.log("helper build account: ",n),console.log("helper build network: ",o),r.build({suiClient:e,account:n,network:o})}};import{TransactionType as Ii}from"@msafe/sui3-utils";import{TransactionType as gt}from"@msafe/sui3-utils";import{bcs as wo}from"@mysten/sui.js/bcs";import{normalizeStructTag as ui,normalizeSuiAddress as Bt}from"@mysten/sui.js/utils";var I={packageId:"0xa0eba10b173538c8fecca1dff298e488402cc9ff374f8a12ca7758eebe830b66",farmPackageId:"0x88701243d0445aa38c0a13f02a9af49a58092dfadb93af9754edb41c52f40085",functions:{swapX:"swap_token_x",swapY:"swap_token_y"}};var N="https://fullnode.mainnet.sui.io/";var ke=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isAddLiquiditySingleSidedTransaction())return this.decodeAddLiquiditySingleSided();if(this.isClaimRewardsTransaction())return this.decodeClaimRewards();if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity();if(this.isStakeLiquidityTransaction())return this.decodeStakeLiquidity();if(this.isUnstakeLiquidityTransaction())return this.decodeUnstakeLiquidity();throw new Error("Unknown transaction type")}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::add_liquidity`)}isAddLiquiditySingleSidedTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::add_liquidity`)&&(!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::${I.functions.swapX}`)||!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::${I.functions.swapY}`))}isClaimRewardsTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::remove_liquidity`)}isStakeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::stake`)}isUnstakeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::unstake`)}decodeAddLiquidity(){let t=this.helperLiquidityDex.getInputParam(0).value,e=this.helperLiquidityDex.typeArg(0),n=this.helperLiquidityDex.typeArg(1),o=this.helperLiquidityDex.decodeInputU64String(4),r=this.helperLiquidityDex.decodeInputU64String(3),i=this.helperLiquidityDex.decodeInputU64String(6),s=this.helperLiquidityDex.decodeInputU64String(5),c=this.helperLiquidityDex.getInputParam(2).value,l=this.helperLiquidityDex.getInputParam(1).value;return{txType:gt.Other,type:"AddLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,amountX:o,amountY:r,minAddAmountX:i,minAddAmountY:s,coinX:c,coinY:l}}}decodeAddLiquiditySingleSided(){let t=this.helperLiquidityDex.getInputParam(0).value,e=this.helperLiquidityDex.typeArg(0),n=this.helperLiquidityDex.typeArg(1),o=this.helperSwapDex.moveCall.target===`${I.packageId}::spot_dex::${I.functions.swapX}`?e:n,r=this.helperSwapDex.decodeInputU64String(2),i=this.helperSwapDex.getInputParam(1).value;return{txType:gt.Other,type:"AddLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,inputCoinType:o,inputCoinAmount:r,inputCoin:i}}}decodeRemoveLiquidity(){let t=this.helperRemoveLiqDex.getInputParam(0).value,e=this.helperRemoveLiqDex.typeArg(0),n=this.helperRemoveLiqDex.typeArg(1),o=this.helperRemoveLiqDex.decodeInputU64String(2),r=this.helperRemoveLiqDex.getInputParam(1).value;return{txType:gt.Other,type:"RemoveLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,amount:o,kriyaLpToken:r}}}decodeClaimRewards(){let t=this.helperFarmClaim.getInputParam(1).value,e=this.helperFarmClaim.getInputParam(2).value,n=this.helperFarmClaim.typeArg(0),o=this.helperFarmClaim.typeArg(1);return{txType:gt.Other,type:"ClaimRewards",intentionData:{objectId:t,tokenXType:n,tokenYType:o,positionObjectId:e}}}decodeStakeLiquidity(){let t=this.helperFarmStake.getInputParam(1).value,e=this.helperFarmStake.typeArg(0),n=this.helperFarmStake.typeArg(1),o=this.helperFarmStake.getInputParam(2).value,r=this.helperFarmStake.decodeInputU64String(3);return{txType:gt.Other,type:"StakeLiquidity",intentionData:{lpObject:o,lockTime:r,objectId:t,tokenXType:e,tokenYType:n}}}decodeUnstakeLiquidity(){let t=this.helperFarmUnstake.getInputParam(1).value,e=this.helperFarmUnstake.getInputParam(2).value,n=this.helperFarmUnstake.typeArg(0),o=this.helperFarmUnstake.typeArg(1);return{txType:gt.Other,type:"UnstakeLiquidity",intentionData:{objectId:t,tokenXType:n,tokenYType:o,positionObjectId:e}}}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}get helperRemoveLiqDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.packageId}::spot_dex::remove_liquidity`);return new J(t,this.txb)}get helperLiquidityDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.packageId}::spot_dex::add_liquidity`);return new J(t,this.txb)}get helperSwapDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&(e.target===`${I.packageId}::spot_dex::${I.functions.swapX}`||e.target===`${I.packageId}::spot_dex::${I.functions.swapY}`));return new J(t,this.txb)}get helperFarmClaim(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::claim`);return new J(t,this.txb)}get helperFarmStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::stake`);return new J(t,this.txb)}get helperFarmUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::unstake`);return new J(t,this.txb)}},J=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)}decodeInputU64String(t){return this.decodePureArg(t,"u64")}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return Bt(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 wo.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 Bt(t.value.Object.ImmOrOwned.objectId)}return Bt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Bt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Bt(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 wo.de(e,new Uint8Array(n))}typeArg(t){return ui(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as pi}from"@mysten/sui.js/transactions";import{KriyaSDK as mi}from"kriya-dex-sdk";var Ie=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new mi.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,amountX:d,amountY:p,minAddAmountX:m,minAddAmountY:b,coinX:f,coinY:h}=this.data,w=new pi,R=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable;return i.addLiquidity({objectId:s,tokenXType:c,tokenYType:l,isStable:R},BigInt(d),BigInt(p),BigInt(m),BigInt(b),f,h,w,r),w}static fromData(e){return new a(e)}};import{TransactionBlock as bi}from"@mysten/sui.js/transactions";import{KriyaSDK as fi}from"kriya-dex-sdk";var xe=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new fi.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,inputCoinType:d,inputCoinAmount:p,inputCoin:m}=this.data,b=new bi,h=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable;return i.addLiquiditySingleSided({objectId:s,tokenXType:c,tokenYType:l,isStable:h},d,BigInt(p),m,1,b,r),b}static fromData(e){return new a(e)}};import{TransactionBlock as gi}from"@mysten/sui.js/transactions";import{KriyaSDK as hi}from"kriya-dex-sdk";var ve=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new hi.StakingFarm(N,i),{objectId:c,tokenXType:l,tokenYType:d,positionObjectId:p}=this.data,m={objectId:c,tokenXType:l,tokenYType:d},b=new gi;return s.claimTx(b,m,p,r),b}static fromData(e){return new a(e)}};import{TransactionBlock as yi}from"@mysten/sui.js/transactions";import{KriyaSDK as Si}from"kriya-dex-sdk";var Ae=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new Si.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,amount:d,kriyaLpToken:p}=this.data,m=new yi,f=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable,h={objectId:s,tokenXType:c,tokenYType:l,isStable:f};return i.removeLiquidity(h,BigInt(d),p,m,r),m}static fromData(e){return new a(e)}};import{TransactionBlock as wi}from"@mysten/sui.js/transactions";import{KriyaSDK as Ci}from"kriya-dex-sdk";var Oe=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new Ci.StakingFarm(N,i),{lpObject:c,lockTime:l,objectId:d,tokenXType:p,tokenYType:m}=this.data,b={objectId:d,tokenXType:p,tokenYType:m},f=new wi;return s.stakeTx(f,c,Number(l),b,r),f}static fromData(e){return new a(e)}};import{TransactionBlock as Ti}from"@mysten/sui.js/transactions";import{KriyaSDK as ki}from"kriya-dex-sdk";var De=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new ki.StakingFarm(N,i),{objectId:c,tokenXType:l,tokenYType:d,positionObjectId:p}=this.data,m={objectId:c,tokenXType:l,tokenYType:d},b=new Ti;return s.withdrawTx(b,m,p,r),b}static fromData(e){return new a(e)}};var Pe=class{application="kriya";async deserialize(t){let{transactionBlock:e}=t,o=new ke(e).decode();return{txType:Ii.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"AddLiquidity":r=Ie.fromData(t.intentionData);break;case"AddLiquiditySingleSided":r=xe.fromData(t.intentionData);break;case"RemoveLiquidity":r=Ae.fromData(t.intentionData);break;case"ClaimRewards":r=ve.fromData(t.intentionData);break;case"StakeLiquidity":r=Oe.fromData(t.intentionData);break;case"UnstakeLiquidity":r=De.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as Ts}from"@msafe/sui3-utils";var ya={};Za(ya,{contractId:()=>Ai,default:()=>ji,feeObjId:()=>Pi,roleObjId:()=>Oi,status:()=>vi,transaction:()=>xi,upgradeCapObjId:()=>_i,vaultObjId:()=>Di});var xi="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",vi="success",Ai="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Oi="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Di="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Pi="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_i="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",ji={transaction:xi,status:vi,contractId:Ai,roleObjId:Oi,vaultObjId:Di,feeObjId:Pi,upgradeCapObjId:_i};var Sa={};Za(Sa,{contractId:()=>Ni,default:()=>Fi,feeObjId:()=>Li,roleObjId:()=>Ei,status:()=>Ri,transaction:()=>Bi,upgradeCapObjId:()=>Wi,vaultObjId:()=>Mi});var Bi="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ri="success",Ni="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ei="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Mi="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Li="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Wi="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fi={transaction:Bi,status:Ri,contractId:Ni,roleObjId:Ei,vaultObjId:Mi,feeObjId:Li,upgradeCapObjId:Wi};var qi="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Ui="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",$i="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qi="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Vi="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Gi="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Ki="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Hi="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Co=ya,To=Sa,zi=new Map([["dev",{env:"dev",rpc:{url:qi},backend:{url:Vi},contract:Co}],["stg",{env:"stg",rpc:{url:Ui},backend:{url:Gi},contract:Co}],["prev",{env:"prev",rpc:{url:$i},backend:{url:Ki},contract:To}],["prod",{env:"prod",rpc:{url:Qi},backend:{url:Hi},contract:To}]]);function ko(a,t){let e=zi.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 Ji}from"@mysten/sui.js/client";var S=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:o,context:r}=n;o?super(`[MPay] ${e}: ${o}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var _e=class extends S{constructor(){super(11,"Backend is not specified")}};var je=class extends S{constructor(){super(1,"Wallet not connected")}};import yt,{AxiosError as Xi}from"axios";var ht=class extends S{constructor(t,e){super(10,t,{context:e})}};var Be=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Xi)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 yt.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await yt.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await yt.post(`${this.apiURL}/stream-events`,t),n=a.parseResponseData(e);return n.data.forEach(o=>{let r=o;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await yt.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await yt.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await yt.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 Ji({url:t.rpc.url}),t.backend&&(this._backend=new Be(t.backend.url))}static new(t,e){let n=ko(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new _e;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 je;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as ys,normalizeStructTag as Ss,normalizeSuiAddress as Ko}from"@mysten/sui.js/utils";import{TransactionBlock as We}from"@mysten/sui.js/transactions";import{TransactionBlock as jo}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Bo,normalizeStructTag as es}from"@mysten/sui.js/utils";var wa=50n,Re=10000n,Io=25n,Ca=100000000n;var Q=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Rt=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 o=i=>new a(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield o(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return o(r)}})}moveArg(){return this.result}};import{Buffer as xo}from"buffer";import{normalizeSuiAddress as Yi}from"@mysten/sui.js/utils";var Nt=class extends S{constructor(t,e){super(3,t,{context:e})}};var Ne=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,o]=this.getValue(t,e);if(o!=="address")throw new Nt("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return Yi(xo.from(n).toString("hex"))}getU64(t=0,e=0){let[n,o]=this.getValue(t,e);if(o!=="u64")throw new Nt("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return xo.from(n).readBigInt64LE()}};import{bcs as Ao}from"@mysten/sui.js/bcs";var v=class extends S{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Oo={groupId:"string",name:"string"},Zi=64;function Do(a){return Po(a),Ao.ser(Oo,a).toString("base64")}function Et(a){let t=Ao.de(Oo,a,"base64");return Po(t),t}function Po(a){if(!vo(a.name))throw new v("Invalid metadata: Name contains unknown character");if(!vo(a.groupId))throw new v("Invalid metadata: Group ID contains unknown character");if(a.name.length>Zi)throw new v("Invalid metadata: Name exceed max length 64")}function vo(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as Ee}from"@mysten/sui.js/utils";function Me(a,t){return Ee(a)===Ee(t)}function et(a,t){return Ee(a)===Ee(t)}var Le="txn.gas";import{nanoid as ts}from"nanoid";function _o(){return ts()}var lt=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Do({name:t.name,groupId:_o()}),coinType:es(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 jo,n=this.calculateFeesInternal(t),o=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(o),i=await this.addMergeCoins(e,r[0]),s;o.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let l=t.recipients[c],d=this.amountForRecipient(l,t.numberEpoch),p=this.getStreamFeeLocal(d),[m]=e.splitCoins(i,[e.pure(d+p,"u64")]),[b]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new tt(m),flatFeeCoin:new tt(b),metadata:t.metadata,recipient:l.address,timeStart:t.startTime,cliff:l.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:wa,denominator:Re},claimFeePercent:{numerator:Io,denominator:Re},flatFeePerStream:Ca}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(o=>t.object(o))),n=t.object(e.primaryCoin)):e.primaryCoin===Le?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return Me(n,Bo)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:Bo,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((o,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:o.totalAmount+i,streamFeeAmount:o.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 Ca}getStreamFeeLocal(t){return t*wa/Re}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new jo,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Ne(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as No}from"@mysten/sui.js/transactions";var Ro="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(No.MoveCall({target:n,arguments:e.arguments.map(o=>o instanceof Rt?o.moveArgs(t):o instanceof Q?o.moveArg(t):o instanceof tt?o.moveArg():t.pure(o)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],o=[]){t.add(No.MoveCall({target:e,arguments:n.map(r=>r instanceof Rt?r.moveArgs(t):r instanceof Q?r.moveArg(t):r instanceof tt?r.moveArg():t.pure(r)),typeArguments:o}))}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(Ro)}};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 o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[o,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,r,n],typeArgs:[]})}setClaimFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[o,r,n],typeArgs:[]})}streamingFee(e,n){let o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[o,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 V=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 o=this.feeObject(),r=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:[o,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let o=this.makeObject(n.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let o=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,r,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 Tt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Ct(e,t),this.streamContract=new V(e,t)}feeContract;streamContract;async createStreams(t){let e=lt.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new lt(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let o=new We;return this.streamContract.setAutoClaim(o,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new We;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new We;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new We;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var O=class extends S{constructor(t,e={}){super(0,t,e)}};async function ka(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 Ta=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)}},kt=class{constructor(t){this.requester=t;this.pager=new Ta(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 Fe=class extends S{constructor(e,n,o){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:o}});this.coinType=e;this.requestAmount=n;this.gotAmount=o}};var ns=25;async function Eo(a,t,e,n="0x2::sui::SUI",o=ns){let r=new Ia(a,t,n,o),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new Fe(n,e,i);return s}var Ia=class extends kt{constructor(e,n,o,r){super(new xa(e,n,o,r));this.suiClient=e;this.owner=n;this.coinType=o;this.reqPageSize=r}},xa=class{constructor(t,e,n,o){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=o;if(o<=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 Qe}from"@mysten/sui.js/transactions";import{normalizeStructTag as Lo,parseStructTag as rs}from"@mysten/sui.js/utils";import{DateTime as is}from"luxon";var qe=class extends S{constructor(){super(7,"Connected wallet is not creator")}};var Mt=class extends S{constructor(){super(8,"Connected wallet is not recipient")}};var Lt=class extends S{constructor(t,e){super(6,t,{context:e})}};var Ue=class extends S{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as as,Duration as os}from"luxon";var Mo=(1n<<64n)-1n,$e=1e3;function va(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/$e);return as.fromMillis(e*$e)}function Aa(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/$e);return os.fromMillis(e*$e)}var nt=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new V(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 o=a.parseRawStreamData(e,n);return new a(t,e,o)}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 qe;let t=new Qe;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Mt;let t=new Qe;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Mt;let e=new Qe;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Qe;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 Lo(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 Aa(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return Et(t).groupId}get name(){let{metadata:t}=this.rawData.config;return Et(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return va(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Aa(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:va((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===Mo?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=is.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 Ue(t):new Lt(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new Lt("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=rs(n.type),r=Lo(o[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};import{normalizeStructTag as Oa,SUI_TYPE_ARG as ss}from"@mysten/sui.js/utils";import{Duration as Wo}from"luxon";var Ve=class extends S{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var cs=1e3,Ge=class{constructor(t){this.globals=t;this.coinMetaHelper=new Da(t.suiClient),this.createStreamHelper=new Tt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Ve(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,o=(t.totalAmount-n)/t.steps,i={realTotalAmount:o*t.steps+n,cliffAmount:n,amountPerStep:o};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(Wo.fromMillis(Number(e*t.steps))),o={timeStart:t.timeStart,timeEnd:n,interval:Wo.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(o),o}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),o=await this.getCoinMeta(e);return{...n,coinType:Oa(n.coinType),coinMeta:o}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(o=>this.getCoinMeta(o.coinType)));return e.map((o,r)=>({...o,coinType:Oa(o.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new v("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new v("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<cs)throw new v("Interval shall be at least 1 second","interval",t.interval)}},Da=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Oa(t||ss);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 Fo,normalizeSuiAddress as He}from"@mysten/sui.js/utils";import{DateTime as qo}from"luxon";var It=class extends S{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var ds=25;async function _a(a,t,e){let n=new Wt(t),o=new Ft(a,n,e);return await ka(o)}var Wt=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]}},Ft=class extends kt{constructor(e,n,o){super(new Pa(e,n,o));this.suiClient=e;this.idIter=n;this.options=o}},Pa=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||ds,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=e.filter(r=>o?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Ke=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new It("stream size 0");let n=e.map(r=>r.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 _a(t.suiClient,e);return n.forEach(o=>{if(!o)throw new O("stream group object data undefined")}),a.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let o=await a.parseGroupStreams(t,e,n);return new a(t,o)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],o=!0;return e.forEach(r=>{ls(n,r)||(o=!1)}),o}async refresh(){let t=await _a(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 o=n.map((r,i)=>nt.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(o.map(r=>r.groupId)).size!==1)throw new It("Not same group ID");if(!this.checkStreamGroup(o))throw new It("Not same stream settings");return o}};function ls(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 qt=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await ze.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await ze.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}},ze=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Xe.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await Xe.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}},Xe=class a{constructor(t,e,n,o){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=o;this.current=0;let r=new Wt(n.flat().map(i=>i.streamId));this.objectIter=new Ft(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=fs(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>He(s.recipient)===He(n)),i=Uo(r);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=gs(t.query),n=await t.globals.walletAddress(),o=await t.globals.backend.getOutgoingStreams(n,e),r=Uo(o);return new a(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await ms(this.globals,t[0].streamId,this.objectIter);return this.current++,$o(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await bs(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,ps(e,this.query)?e:this.doNextRequest()}throw new O("Stream group with no stream")}};function Uo(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)=>qo.fromISO(n[0].createDate).toMillis()-qo.fromISO(e[0].createDate).toMillis())}function $o(a,t){if(t===void 0)return!0;let e=us(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 us(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function ps(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{$o(n,t)&&(e=!0)}),e}async function ms(a,t,e){let n=await Qo(e,t);return nt.fromObjectData(a,t,n)}async function bs(a,t,e){let n=[];for(;n.length<t.length;){let o=await Qo(e,t[n.length]);n.push(o)}return Ke.newFromObjectResponse(a,t,n)}async function Qo(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 fs(a){return{status:ja(a?.status),coinType:Vo(a?.coinType),sender:Go(a?.sender)}}function gs(a){return{status:ja(a?.status),coinType:Vo(a?.coinType),recipient:Go(a?.recipient)}}function ja(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=ja(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 v("Unknown stream filtered status")}}function Vo(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>Fo(t)):void 0:Fo(a)}function Go(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>He(t)):void 0:He(a)}var Ba=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Je=class{constructor(t){this.account=t}async address(){return this.account.address}},Ra=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(Me(t.coinType,ys))return{primaryCoin:Le};if(t.amount<=0)throw new v("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 O("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},Ye=class{globals;helper;constructor(t,e){this.globals=St.new(t,e),this.helper=new Ge(this.globals)}connectSingleWallet(t){let e=new Ra(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Ba(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 qt.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return qt.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=>Ss(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(o=>Ko(o))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(o=>Ko(o))}get wallet(){return this.globals.wallet}builder(){return new Tt(this.globals)}};import ws from"sort-keys-recursive";var Ze=class{constructor(t){this.data=t}serialize(){return JSON.stringify(ws(this.data))}};var M=class extends Ze{application="mpay";getClient(t,e){let n=new Ye(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Je(e)),n}};var Ut=class extends M{constructor(e){super(e);this.data=e}txType=Ts.Stream;txSubType="Cancel";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};import{TransactionType as ks}from"@msafe/sui3-utils";var $t=class extends M{constructor(e){super(e);this.data=e}txType=ks.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Is}from"@msafe/sui3-utils";var Qt=class extends M{constructor(e){super(e);this.data=e}txType=Is.Stream;txSubType="Claim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};import{TransactionType as xs}from"@msafe/sui3-utils";var Vt=class extends M{constructor(e){super(e);this.data=e}txType=xs.Stream;txSubType="CreateStream";async build(e){let{network:n,account:o}=e;return this.getClient(n,o).createStream(this.data)}};import{bcs as Ho}from"@mysten/sui.js/bcs";import{normalizeStructTag as vs,normalizeSuiAddress as Gt}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 Gt(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 Ho.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 Gt(t.value.Object.ImmOrOwned.objectId)}return Gt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Gt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Gt(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 Ho.de(e,new Uint8Array(n))}typeArg(t){return vs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var tn=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:o}=Et(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),p=t.decodeInputBool(11),m=t.typeArg(0);return{name:n,groupId:o,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:p,coinType:m}}aggregateGroupStreamInfo(t){if(new Set(t.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new v("Stream group not have common info");let n=t.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.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 V(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ct(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new lt(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 en=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new V(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 tn(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 As}from"@msafe/sui3-utils";var Kt=class extends M{constructor(e){super(e);this.data=e}txType=As.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var nn=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,o=St.new(e==="sui:mainnet"?"prod":"dev"),i=new en(o,n).decode(),s;switch(i.type){case"CreateStream":s=new Vt(i.info);break;case"SetAutoClaim":s=new Kt({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Qt({streamId:i.streamId});break;case"ClaimByProxy":s=new $t({streamId:i.streamId});break;case"Cancel":s=new Ut({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 Vt(e);break;case"Claim":n=new Qt(e);break;case"ClaimByProxy":n=new $t(e);break;case"SetAutoClaim":n=new Kt(e);break;case"Cancel":n=new Ut(e);break;default:throw new Error("not implemented")}return n.build({...t})}};import{TransactionDefaultApplication as js,TransactionSubTypes as Na}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Os}from"@msafe/sui3-utils";var an=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return Os(n,this.data,o.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as Ds}from"@msafe/sui3-utils";var on=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return Ds(n,this.data,o.address)}static fromData(e){return new a(e)}};import{isSameAddress as Ps}from"@msafe/sui3-utils";import{TransactionBlock as _s}from"@mysten/sui.js/transactions";var rn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,o=_s.from(this.data.content);if(!Ps(o.blockData.sender,n.address))throw new Error("Invalid sender address");return o}static fromData(e){return new a(e)}};var sn=class{application;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,o;switch(t.txSubType){case Na.assets.coin.send:o=an.fromData(t.intentionData);break;case Na.assets.object.send:o=on.fromData(t.intentionData);break;case Na.others.plain:o=rn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionType as Fs}from"@msafe/sui3-utils";var zo=!1,Xo={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"}}};async function Ea(){if(!zo)try{let a=await fetch("https://open-api.naviprotocol.io/api/package").then(e=>e.json()),{packageId:t}=a;Xo.ProtocolPackage=t,zo=!0}catch(a){console.error(a.message)}}var g=Xo;import{TransactionType as Ht}from"@msafe/sui3-utils";import{bcs as Jo}from"@mysten/sui.js/bcs";import{normalizeStructTag as Rs,normalizeSuiAddress as zt}from"@mysten/sui.js/utils";var cn=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.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(`${g.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(g.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===`${g.ProtocolPackage}::incentive_v2::claim_reward`){let n=new dn(e,this.txb),o=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(o),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:o,poolId:i})}}),console.log("decode claims",t),{txType:Ht.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Ht.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:Ht.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:Ht.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:Ht.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(g.ProtocolPackage));return new dn(t,this.txb)}},dn=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 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 Jo.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 Jo.de(e,new Uint8Array(n))}typeArg(t){return Rs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Ns}from"@mysten/sui.js/transactions";function Ma(a,t,e,n){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(g.Incentive),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function Yo(a,t,e){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(g.Incentive),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function Zo(a,t,e){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function La(a,t,e,n){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function tr(a,t,e,n,o){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(g.IncentiveV2),a.object(e),a.object(g.StorageId),a.pure(t),a.pure(n)],typeArguments:o}),a}var ln=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Ns;return e.forEach(o=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=o;tr(n,r,i,s,c)}),n.setGasBudget(g.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Es}from"@mysten/sui.js/transactions";var un=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,o=new Es;o.setGasBudget(g.gasBudget),console.log("build",this.data);let r=g.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(g.pool).join(", ")}.`);return Zo(o,r,n)}static fromData(e){return new a(e)}};import{TransactionBlock as Ms}from"@mysten/sui.js/transactions";async function pn(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var mn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new Ms;if(s.setGasBudget(g.gasBudget),console.log("build",this.data),r==="sui"){let[p]=s.splitCoins(s.gas,[i]);return Ma(s,g.pool.sui,p,i)}let c=g.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(g.pool).join(", ")}.`);let l=await pn(n,o.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let p=1;for(;p<l.data.length;)s.mergeCoins(d,[l.data[p].coinObjectId]),p++}return Ma(s,c,s.object(d),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Ls}from"@mysten/sui.js/transactions";var bn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new Ls;if(s.setGasBudget(g.gasBudget),console.log("build",this.data),r==="sui"){let[p]=s.splitCoins(s.gas,[i]);return La(s,g.pool.sui,p,i)}let c=g.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(g.pool).join(", ")}.`);let l=await pn(n,o.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let p=1;for(;p<l.data.length;)s.mergeCoins(d,[l.data[p].coinObjectId]),p++}return La(s,c,s.object(d),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Ws}from"@mysten/sui.js/transactions";var fn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,o=new Ws;console.log("build",this.data),o.setGasBudget(g.gasBudget);let r=g.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(g.pool).join(", ")}.`);return Yo(o,r,n)}static fromData(e){return new a(e)}};var gn=class{application="navi";async deserialize(t){await Ea();let{transactionBlock:e}=t,o=new cn(e).decode();return{txType:Fs.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(await Ea(),t.txSubType){case"EntryDeposit":o=mn.fromData(t.intentionData);break;case"EntryBorrow":o=un.fromData(t.intentionData);break;case"EntryRepay":o=bn.fromData(t.intentionData);break;case"EntryWithdraw":o=fn.fromData(t.intentionData);break;case"ClaimReward":o=ln.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionSubTypes as qs,TransactionType as Us}from"@msafe/sui3-utils";import{TransactionBlock as $s}from"@mysten/sui.js/transactions";import{fromHEX as Qs,toHEX as Vs}from"@mysten/sui.js/utils";import sS from"sort-keys-recursive";var Gs="msafe-plain-tx",Ks=qs.others.plain;var hn=class{application;constructor(){this.application=Gs}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,o=await e.build({client:n});return{txType:Us.Other,txSubType:Ks,intentionData:{content:Vs(o)}}}async build(t){let{suiClient:e,account:n}=t,o=$s.from(Qs(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:o,sender:n.address});if(!(r.effects.status.status==="success"))throw new Error(r.effects.status.error);return o}};var yn=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}};import{TransactionType as wc}from"@msafe/sui3-utils";import{TransactionType as D}from"@msafe/sui3-utils";import{bcs as Fa}from"@mysten/sui.js/bcs";import{normalizeStructTag as zs,normalizeSuiAddress as Jt}from"@mysten/sui.js/utils";var at="6601955b8b0024600a917079",Sn="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var vt="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",ot="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",pt=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],wn=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],Xt=["seth","ssui","susdc","susdt","scetus","safsui","shasui","svsui"],er=["sui"],At=["sui","usdc","usdt"];var nr={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 Cn={seth:"sui",ssui:"sui",susdc:"sui",susdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui"},ar={sui:["sui","sca"],usdc:["sui","sca"],usdt:["sui","sca"]},or={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"},Wa={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"};var Tn=class{constructor(t,e){this.txb=t;this._builder=e}_builder;decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();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.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();throw new Error("Unknown transaction type")}get coreId(){return{protocolPkg:this._builder.address.get("core.packages.protocol.id"),market:this._builder.address.get("core.market"),version:this._builder.address.get("core.version"),coinDecimalsRegistry:this._builder.address.get("core.coinDecimalsRegistry"),xOracle:this._builder.address.get("core.oracles.xOracle"),spoolPkg:this._builder.address.get("spool.id"),borrowIncentivePkg:this._builder.address.get("borrowIncentive.id"),veScaPkgId:this._builder.address.get("vesca.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)}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`)}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}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}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}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`)}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation_entry`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${vt}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}decodeMigrateAndClaim(){let t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),e=this.helperClaimBorrowReward[0].decodeSharedObjectId(2),n=this.helperClaimBorrowReward[0].decodeOwnedObjectId(3),o=this._builder.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:D.Other,type:"MigrateAndClaim",intentionData:{veScaKey:t,obligationKey:e,obligationId:n,rewardCoinName:o}}}decodeOpenObligation(){return{txType:D.Other,type:"OpenObligation",intentionData:{}}}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:D.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new L(t,this.txb).getAmountInput().reduce((f,h)=>f+h,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,p,m,b=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let f=0;f<b.length;f++)b[f].condition.length>1&&([m,p]=b[f].condition,l=!0,d=b[f].isOld);return{txType:D.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:p,obligationKey:m,veScaKey:o,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:r,isOld:!1}];for(let p=0;p<d.length;p++)d[p].condition.length>1&&([l,c]=d[p].condition,i=!0,s=d[p].isOld);return{txType:D.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:l,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new L(t,this.txb).getAmountInput().reduce((b,f)=>b+f,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,p,m=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,d]=m[b].condition,c=!0,l=m[b].isOld);return{txType:D.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:d,obligationKey:p,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):(t=this.helperStakeMoreSca.getNestedInputParam(4),console.log(t));let n=new L(t,this.txb).getAmountInput().reduce((b,f)=>b+f,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,p,m=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,d]=m[b].condition,c=!0,l=m[b].isOld);return{txType:D.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:d,obligationKey:p,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}decodeSupplyLending(){let t=this._builder.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:D.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this._builder.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:D.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this._builder.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:D.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this._builder.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:D.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:o,obligationId:n}}}decodeBorrow(){let t=this._builder.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let t=this._builder.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:o,veScaKey:e}}}decodeRepay(){let t=this._builder.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:t}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=this.helperStake.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperStake.typeArg(0),r=this._builder.utils.parseCoinNameFromType(o);return{txType:D.Other,type:"StakeSpool",intentionData:{amount:n,marketCoinName:r,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this._builder.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:o,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this._builder.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:D.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(r=>{let i=r.decodeOwnedObjectId(1),s=r.decodeInputU64(2);t.push({id:i,coin:s})});let e=this._builder.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=this.helperRedeems.find(r=>r.isHaveNestedInput(2)),o;return n&&(o=new L(n.getNestedInputParam(2),this.txb).getAmountInput().reduce((r,i)=>r+i,0)),{txType:D.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:o,coinName:e,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let r=o.decodeOwnedObjectId(2),i=o.typeArg(0),s=this._builder.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(o=>{let r=o.decodeSharedObjectId(3),i=o.decodeOwnedObjectId(4),s=this._builder.utils.parseCoinNameFromType(o.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(o=>{let r=o.decodeSharedObjectId(2),i=o.decodeOwnedObjectId(3),s=this._builder.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:D.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new T(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 T(e,this.txb))}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new T(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 T(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 T(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 T(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 T(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${vt}::user::unstake`));return new T(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new T(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 T(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${vt}::user::redeem_rewards`)).map(e=>new T(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new T(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new T(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new T(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new T(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new T(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new T(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 T(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 T(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new T(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new T(t,this.txb)}},L=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(T.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 Fa.de(e,new Uint8Array(n))}return t.value}},T=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 Jt(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 Fa.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 Jt(t.value.Object.ImmOrOwned.objectId)}return Jt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Jt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Jt(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 Fa.de(e,new Uint8Array(n))}typeArg(t){return zs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as x}from"@mysten/sui.js/transactions";import{normalizeSuiAddress as Sc}from"@mysten/sui.js/utils";import Ar from"bignumber.js";var rr={mainnet:{core:{version:"0x07871c4b3c847a0f674510d4978d5cf6f960452795e8ff6f189fd2088a3f6ac7",versionCap:"0x590a4011cb649b3878f3ea14b3a78674642a9548d79b7e091ef679574b158a07",object:"0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf",market:"0xa757975255146dc9686aa823b7838b507f315d704f428cbadad2f4ea061939d9",adminCap:"0x09689d018e71c337d9db6d67cbca06b74ed92196103624028ccc3ecea411777c",coinDecimalsRegistry:"0x200abe9bf19751cc566ae35aa58e2b7e4ff688fc1130f8d8909ea09bc137d668",obligationAccessStore:"0x733e30b7c94d619d78cb8f5bc4bfbb759ced9a531239028caabb2474e5be59c9",coins:{cetus:{id:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",metaData:"0x4c0dce55eff2db5419bbd2d239d1aa22b4a400c01bbb648b058a9883989025da",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"e5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",feedObject:"0x24c0247fb22457a719efac7f670cdc79be321b521460bd6bd2ccfa9f80713b14"}}},apt:{id:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",metaData:"0xc969c5251f372c0f34c32759f1d315cf1ea0ee5e4454b52aea08778eacfdd0a8",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"03ae4db29ed4ae33d323568895aa00337e658e348b37509f5372ae51f0af00d5",feedObject:"0x7c5b7837c44a69b469325463ac0673ac1aa8435ff44ddb4191c9ae380463647f"}}},sol:{id:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",metaData:"0x4d2c39082b4477e3e79dc4562d939147ab90c42fc5f3e4acf03b94383cd69b6e",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d",feedObject:"0x9d0d275efbd37d8a8855f6f2c761fa5983293dd8ce202ee5196626de8fcd4469"}}},btc:{id:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",metaData:"0x5d3c6e60eeff8a05b693b481539e7847dfe33013e7070cdcb387f5c0cac05dfd",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",feedObject:"0x9a62b4863bdeaabdc9500fce769cf7e72d5585eeb28a6d26e4cafadc13f76ab2"}}},eth:{id:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",metaData:"0x8900e4ceede3363bef086d6b50ca89d816d0e90bf6bc46efefe1f8455e08f50f",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"ff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",feedObject:"0x9193fd47f9a0ab99b6e365a464c8a9ae30e6150fc37ed2a89c1586631f6fc4ab"}}},usdc:{id:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",metaData:"0x4fbf84f3029bd0c0b77164b587963be957f853eccf834a67bb9ecba6ec80f189",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"eaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",feedObject:"0x5dec622733a204ca27f5a90d8c2fad453cc6665186fd5dff13a83d0b6c9027ab"}}},usdt:{id:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",metaData:"0xfb0e3eb97dd158a5ae979dddfa24348063843c5b20eb8381dd5fa7c93699e45c",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b",feedObject:"0x985e3db9f93f76ee8bace7c3dd5cc676a096accd5d9e09e9ae0fb6e492b14572"}}},sui:{id:"0x0000000000000000000000000000000000000000000000000000000000000002",metaData:"0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3",treasury:"",oracle:{supra:"",switchboard:"0xbca474133638352ba83ccf7b5c931d50f764b09550e16612c9f70f1e21f3f594",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},afsui:{id:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",metaData:"0x2f9217f533e51334873a39b8026a4aa6919497b47f49d0986a4f1aec66f8a34d",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},hasui:{id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",metaData:"0x2c5f33af93f6511df699aaaa5822d823aac6ed99d4a0de2a4a50b3afa0172e24",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},vsui:{id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",metaData:"0xabd84a23467b33854ab25cf862006fd97479f8f6f53e50fe732c43a274d939bd",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},sca:{id:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6",metaData:"0x5d26a1e9a55c88147ac870bfa31b729d7f49f8804b8b3adfdf3582d301cca844",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"7e17f0ac105abe9214deb9944c30264f5986bf292869c6bd8e8da3ccd92d79bc",feedObject:"0xf6de1d3279a269a597d813cbaca59aa906543ab9a8c64e84a4722f1a20863985"}}}},oracles:{xOracle:"0x93d5bf0936b71eb27255941e532fac33b5a5c7759e377b4923af0a1359ad494f",xOracleCap:"0x1edeae568fde99e090dbdec4bcdbd33a15f53a1ce1f87aeef1a560dedf4b4a90",supra:{registry:"",registryCap:"",holder:""},switchboard:{registry:"",registryCap:""},pyth:{registry:"0xedc293f9413a5a7a5d53bdba1fd889d0a4030894469228f0acdae4aa3c55a213",registryCap:"0xbcb07141eb1f7e01fbda4130ecf5f5adaeabb77f5d9c32158b7532bcd2197acd",state:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole:"0x5306f64e312b581766351c07af79c72fcb1cd25147157fdc2f8ad76de9a3fb6a",wormholeState:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c"}},packages:{coinDecimalsRegistry:{id:"0xca5a5a62f01c79a104bf4d31669e29daa387f325c241de4edbe30986a9bc8b0d",upgradeCap:"0x34e76a945d29f195bc53ca704fa70877d1cf3a5d7bbfdda1b13e633fff13c0f6"},math:{id:"0xad013d5fde39e15eabda32b3dbdafd67dac32b798ce63237c27a8f73339b9b6f",upgradeCap:"0x3a329598231de02e6135c62284b66005b41cad1d9ab7ca2dc79c08293aba2ec6"},whitelist:{id:"0x1318fdc90319ec9c24df1456d960a447521b0a658316155895014a6e39b5482f",upgradeCap:"0xf5a22aea23db664f7b69855b6a546747f17c1ec4230319cfc17225e462b05761"},x:{id:"0x779b5c547976899f5474f3a5bc0db36ddf4697ad7e5a901db0415c2281d28162",upgradeCap:"0x3f203f6fff6a69d151e4f1cd931f22b68c489ef2759765662fc7baf673943c9e"},protocol:{id:"0x38fe42a5a69f7eb3635404389e8003be9457b1a5c873f133184648c7e9bd47b7",upgradeCap:"0x38527d154618d1fd5a644b90717fe07cf0e9f26b46b63e9568e611a3f86d5c1a"},protocolWhitelist:{id:"0x4c262d9343dac53ecb28f482a2a3f62c73d0ebac5b5f03d57383d56ff219acdf",upgradeCap:"0x4a5e88a75039b00988f633f811f58117f31b8627a46bf822aa114d9010049449"},query:{id:"0xb8d603a39114a5efef3dd0bf84df0bed1be1fbd39b78b7dd6e8a61ccc5e6006f",upgradeCap:"0x0d535c35f608b9b01b7ccce11acf43b1dd80c1b72bf8b541744a6e28e8d2745f"},supra:{id:"",upgradeCap:""},pyth:{id:"0x910f30cbc7f601f75a5141a01265cd47c62d468707c5e1aecb32a18f448cb25a",upgradeCap:"0xdf0ffbae1ea5bb25fbca5efba433dcf00c7cced65679af2f04728901275c6157"},switchboard:{id:"",upgradeCap:""},xOracle:{id:"0x1478a432123e4b3d61878b629f2c692969fdb375644f1251cd278a4b1e7d7cd6",upgradeCap:"0x0f928a6b2e26b73330fecaf9b44acfc9800a4a9794d6415c2a3153bc70e3c1f0"},testCoin:{id:"",upgradeCap:""}}},spool:{id:"0xec1ac7f4d01c5bf178ff4e62e523e7df7721453d81d4904a42a0ffc2686c843d",adminCap:"0xdd8a047cbbf802bfcde5288b8ef1910965d789cc614da11d39af05fca0bd020a",object:"0xe87f1b2d498106a2c61421cec75b7b5c5e348512b0dc263949a0e7a3c256571a",pools:{seth:{id:"0xeec40beccb07c575bebd842eeaabb835f77cd3dab73add433477e57f583a6787",rewardPoolId:"0x957de68a18d87817de8309b30c1ec269a4d87ae513abbeed86b5619cb9ce1077"},ssui:{id:"0x4f0ba970d3c11db05c8f40c64a15b6a33322db3702d634ced6536960ab6f3ee4",rewardPoolId:"0x162250ef72393a4ad3d46294c4e1bdfcb03f04c869d390e7efbfc995353a7ee9"},susdc:{id:"0x4ace6648ddc64e646ba47a957c562c32c9599b3bba8f5ac1aadb2ae23a2f8ca0",rewardPoolId:"0xf4268cc9b9413b9bfe09e8966b8de650494c9e5784bf0930759cfef4904daff8"},susdt:{id:"0xcb328f7ffa7f9342ed85af3fdb2f22919e1a06dfb2f713c04c73543870d7548f",rewardPoolId:"0x2c9f934d67a5baa586ceec2cc24163a2f049a6af3d5ba36b84d8ac40f25c4080"},scetus:{id:"0xac1bb13bf4472a637c18c2415fb0e3c1227ea2bcf35242e50563c98215bd298e",rewardPoolId:"0x6835c1224126a45086fc6406adc249e3f30df18d779ca4f4e570e38716a17f3f"},safsui:{id:"0xeedf438abcaa6ce4d9625ffca110920592d5867e4c5637d84ad9f466c4feb800",rewardPoolId:"0x89255a2f86ed7fbfef35ab8b7be48cc7667015975be2685dd9a55a9a64baf76e"},shasui:{id:"0xa6148bc1b623e936d39a952ceb5bea79e8b37228a8f595067bf1852efd3c34aa",rewardPoolId:"0x6f3563644d3e2ef13176dbf9d865bd93479df60ccbe07b7e66db57f6309f5a66"},svsui:{id:"0x69ce8e537e750a95381e6040794afa5ab1758353a1a2e1de7760391b01f91670",rewardPoolId:"0xbca914adce058ad0902c7f3cfcd698392a475f00dcfdc3f76001d0370b98777a"}},version:"",versionCap:""},borrowIncentive:{id:"0x874f1d43d81e2256e120bab2485938fe07ba0cc21d87129a99a1db11cacb382d",adminCap:"0xc486afa253646f4d381e81d7f1df8aa4723b845a6bb356f69bad635ffefffe2c",object:"0x002875153e09f8145ab63527bc85c00f2bd102e12f9573c47f8cdf1a1cb62934",query:"0x529edc54a3dce2207703ceebbccb0ac14133f7825c1f528775ba0d85a4063489",incentivePools:"0x6547e143d406b5ccd5f46aae482497de279cc1a68c406f701df70a05f9212ab4",incentiveAccounts:"0xc4701fdbc1c92f9a636d334d66012b3027659e9fb8aff27279a82edfb6b77d02",config:"0xdf5d04b4691cc67e82fd4db8394d89ff44823a9de29716c924f74bb4f11cc1f7",version:"",versionCap:""},vesca:{id:"0xcfe2d87aa5712b67cad2732edb6a2201bfdf592377e5c0968b7cb02099bd8e21",adminCap:"0x4d105b16467acca81d18c132cdd1a3cee159920a86c1ef4bdbf2e8d7878500c5",tableId:"0x0a0b7f749baeb61e3dfee2b42245e32d0e6b484063f0a536b33e771d573d7246",table:"0xd3a4632b1080f7d96e1c2487d4dabf2c1196916937c505a69954ac9f393be8d0",treasury:"0xafa4b6231e49c15a22d641ce33fda761baaf650fa21899dfa2eb1716146e7306",config:"0x7cbcb0a342179577a117dfdff974cf1ab765d3b571067bf22ddf5f9e3a667922"}}};var G=class{_auth;_id;_network;_currentAddresses;_addressesMap;constructor(t){let{id:e,auth:n,network:o}=t;n&&(this._auth=n),this._id=e,this._network=o||"mainnet",this._addressesMap=new Map}getId(){return this._id||void 0}get(t){if(this._currentAddresses)return t.split(".").reduce((n,o)=>typeof n=="object"?n[o]:n,this._currentAddresses)||void 0}set(t,e){if(this._currentAddresses){let n=t.split(".");n.reduce((o,r,i)=>{if(i===n.length-1){let s=o;s[r]=e}return o[r]},this._currentAddresses)}return this._currentAddresses}switchCurrentAddresses(t){return this._addressesMap.has(t)&&(this._currentAddresses=this._addressesMap.get(t),this._network=t),this._currentAddresses}getAddresses(t){return t?this._addressesMap.get(t):this._currentAddresses??this._addressesMap.get(this._network)}setAddresses(t,e){let n=e||this._network;n===this._network&&(this._currentAddresses=t),this._addressesMap.set(n,t)}getAllAddresses(){return Object.fromEntries(this._addressesMap)}read(){return Object.entries(rr).forEach(([t,e])=>{["localnet","devnet","testnet","mainnet"].includes(t)&&(t===this._network&&(this._currentAddresses=e),this._addressesMap.set(t,e))}),this.getAllAddresses()}};import{TransactionBlock as ec}from"@mysten/sui.js/transactions";import{normalizeSuiAddress as nc}from"@mysten/sui.js/utils";import{SUI_TYPE_ARG as Ys,normalizeStructTag as fr}from"@mysten/sui.js/utils";var j=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},cr=(a,t,e,n)=>{let o=!n,r=!o&&n*1e3<=new Date().getTime();if(o||r)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 ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if(Ot(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)`)}},dr=(a,t,e)=>{if(Ot(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)`)},lr=(a,t)=>{if(Ot(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")},ur=(a,t,e)=>{if(Ot(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)`)},Ot=a=>{if(a===void 0)throw new Error("veSca not found")};import{normalizeStructTag as pr,parseStructTag as Xs}from"@mysten/sui.js/utils";import _S from"bignumber.js";var Js=a=>({pointType:pr(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),mr=a=>({poolType:pr(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=Js(e),o=Xs(n.pointType).name.toLowerCase();return t[o]=n,t},{})});var qa=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...pt,...wn,...er])].includes(t)},Ua=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}};var br=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 it=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this._address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.isTestnet=t.networkType?t.networkType==="testnet":!1,this.client=t.client}init(t=!1,e){t||!this._address.getAddresses()||!e?.getAddresses()?this._address.read():this._address=e}parseSymbol(t){if(qa(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Ua(e)}return Ua(t)}parseCoinType(t){let e=qa(t)?this.parseCoinName(t):t,n=this._address.get(`core.coins.${e}.id`)||or[t]||void 0;if(!n)throw Error(`Coin ${t} is not supported`);if(t==="sui")return fr(`${n}::sui::SUI`);let o=[this._address.get("core.coins.usdc.id")??B.usdc,this._address.get("core.coins.usdt.id")??B.usdt,this._address.get("core.coins.eth.id")??B.eth,this._address.get("core.coins.btc.id")??B.btc,this._address.get("core.coins.sol.id")??B.sol,this._address.get("core.coins.apt.id")??B.apt],r=[this._address.get("core.coins.vsui.id")??Wa.vsui];return o.includes(n)?`${n}::coin::COIN`:r.includes(n)?`${n}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||Sn,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=fr(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,o=t.match(n),r=t.includes("reserve::MarketCoin");e=o?.[1]||t;let i={[`${this._address.get("core.coins.usdc.id")??B.usdc}::coin::COIN`]:"usdc",[`${this._address.get("core.coins.usdt.id")??B.usdt}::coin::COIN`]:"usdt",[`${this._address.get("core.coins.eth.id")??B.eth}::coin::COIN`]:"eth",[`${this._address.get("core.coins.btc.id")??B.btc}::coin::COIN`]:"btc",[`${this._address.get("core.coins.sol.id")??B.sol}::coin::COIN`]:"sol",[`${this._address.get("core.coins.apt.id")??B.apt}::coin::COIN`]:"apt"},s={[`${this._address.get("core.coins.vsui.id")??Wa.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return r?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>Cn[t];getBorrowIncentiveRewardCoinName=t=>ar[t];getCoinDecimal(t){return nr[t]}getCoinWrappedType(t){return t==="usdc"||t==="usdt"||t==="eth"||t==="btc"||t==="apt"||t==="sol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}async selectCoinIds(t,e=Ys,n){let o=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let l=await this.client.getCoins({owner:o,coinType:e,cursor:c});l.data.sort((d,p)=>parseInt(p.balance,10)-parseInt(d.balance,10));for(let d=0;d<l.data.length&&(r.push({objectId:l.data[d].coinObjectId,digest:l.data[d].digest,version:l.data[d].version}),i+=parseInt(l.data[d].balance,10),!(i>=t));d++);c=l.nextCursor,s=l.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r.map(l=>l.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 o=e.map(s=>t.object(s)),r=o[0];o.length>1&&t.mergeCoins(r,o.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),o=e?Math.max(e-n,0):0,r=0;if(o===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+o:o,126144e3);r=n+i}return br(r)}};import{TransactionBlock as Zs}from"@mysten/sui.js/transactions";import In from"bignumber.js";var Dt=async(a,t)=>{let e=t,n=a.address.get("core.object")||Sn,o=[],r=!1,i=null;do{let d=await a.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});o.push(...d.data),d.hasNextPage&&d.nextCursor?(r=!0,i=d.nextCursor):r=!1}while(r);let s=o.map(d=>d?.data?.objectId).filter(d=>d!==void 0),c=await a.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),l=[];for(let d=0;d<c.length;d++){let p=c[d].data.objectId,{content:m}=c[d].data;if(m&&"fields"in m){let b=m.fields,f=String(b.ownership.fields.of),h=await $a(a,f);l.push({id:f,keyId:p,locked:h})}}return l},$a=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},gr=async(a,t,e)=>{let n=e||[...pt],o=t,r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(p=>({StructType:`0x2::coin::Coin<${a.utils.parseCoinType(p)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let p=d.type;if(d.content&&"fields"in d.content){let m=d.content.fields,b=a.utils.parseCoinNameFromType(p);b&&(c[b]=In(c[b]??0).plus(m.balance).toNumber())}}),c},hr=async(a,t,e)=>{let n=e,o=a.utils.parseCoinType(t),r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let p=d.content.fields;c=In(c).plus(p.balance).toNumber()}}),c},yr=async(a,t,e)=>{let n=e||[...pt].map(d=>a.utils.parseMarketCoinName(d)),o=t,r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(p=>({StructType:`0x2::coin::Coin<${a.utils.parseMarketCoinType(p)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let p=d.type;if(d.content&&"fields"in d.content){let m=d.content.fields,b=a.utils.parseCoinNameFromType(p);b&&(c[b]=In(c[b]??0).plus(m.balance).toNumber())}}),c},Sr=async(a,t,e)=>{let n=e,o=a.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let p=d.content.fields;c=In(c).plus(p.balance).toNumber()}}),c},wr=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,o=new Zs;return o.moveCall({target:n,arguments:[o.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:o,sender:a.walletAddress})).events[0].parsedJson};import{normalizeStructTag as C}from"@mysten/sui.js/utils";var Yt=async(a,t)=>{let e=t,n=a.address.get("spool.object"),o=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let m=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},options:{showContent:!0,showType:!0},cursor:s});r.push(...m.data),m.hasNextPage&&m.nextCursor?(i=!0,s=m.nextCursor):i=!1}while(i);let c={seth:[],ssui:[],susdc:[],susdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},l=Object.keys(c).reduce((m,b)=>{let f=a.utils.parseCoinName(b),h=a.utils.parseMarketCoinType(f),w={...m},P=`${n}::spool_account::SpoolAccount<${h}>`;return w[b]=P,w},{}),d=r.map(m=>m?.data?.objectId).filter(m=>m!==void 0);return(await a.client.multiGetObjects({ids:d,options:{showContent:!0,showType:!0}})).forEach(m=>{let b=m.data.objectId,f=m.data.type;if(m.data.content&&"fields"in m.data.content){let h=m.data.content.fields,w=String(h.spool_id),P=String(h.stake_type.fields.name),R=Number(h.stakes),H=Number(h.index),z=Number(h.points),X=Number(h.total_points);C(f)===l.seth?c.seth.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.ssui?c.ssui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.susdc?c.susdc.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.susdt?c.susdt.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.scetus?c.scetus.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.safsui?c.safsui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.shasui?c.shasui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.svsui&&c.svsui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X})}}),c},Qa=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.id`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=Number(c.max_distributed_point),d=Number(c.distributed_point),p=Number(c.distributed_point_per_period),m=Number(c.point_distribution_time),b=Number(c.max_stakes),f=String(c.stake_type.fields.name),h=Number(c.stakes),w=Number(c.index),P=Number(c.created_at),R=Number(c.last_update);n={id:i,type:C(s),maxPoint:l,distributedPoint:d,pointPerPeriod:p,period:m,maxStake:b,stakeType:C(f),totalStaked:h,index:w,createdAt:P,lastUpdate:R}}}return n},Va=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.rewardPoolId`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=String(c.spool_id),d=Number(c.exchange_rate_numerator),p=Number(c.exchange_rate_denominator),m=Number(c.rewards),b=Number(c.claimed_rewards);n={id:i,type:C(s),stakePoolId:l,ratioNumerator:d,ratioDenominator:p,rewards:m,claimedRewards:b}}}return n};import{TransactionBlock as tc}from"@mysten/sui.js/transactions";import{normalizeStructTag as ZS}from"@mysten/sui.js/utils";import e0 from"bignumber.js";var Cr=async(a,t,e,n)=>{let o=n||[...At],r=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new tc;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let d=(await a.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,p={};return d.pool_records.forEach(m=>{let b=mr(m),{poolType:f}=b,h=a.utils.parseCoinNameFromType(f);o.length>=1&&o.includes(h)&&(p[h]=b)},{}),p};var Tr=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 o=n.data;if(o.content&&"fields"in o.content){let r=o.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),l=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(l?-1:1)}}return 0};import Ga from"bignumber.js";var kr=async(a,t)=>{let e=t,o=`${a.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);return r.map(l=>l.data).filter(l=>!!l)},Ir=async(a,t)=>{let n=(await kr(a,t)).map(r=>r.objectId),o=[];for(let r=0;r<n.length;r++){let i=await Ka(a,n[r]);i&&o.push(i)}return o},Ka=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),o=t||(await kr(a,e))[0].objectId,r,s=(await a.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:o}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:o,lockedScaAmount:Ga(c.locked_sca_amount).toNumber(),lockedScaCoin:Ga(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:Ga(c.unlock_at).toNumber()}}return r};var Pt=class{params;address;client;utils;walletAddress;constructor(t,e){this.params=t,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.client=t.client,this.utils=e?.utils??new it(this.params,{address:this.address}),this.walletAddress=t.walletAddress}init(t=!1,e){t||!this.address.getAddresses()||!e?.getAddresses()?this.address.read():this.address=e}async getObligations(t){return Dt(this,t)}async getCoinAmounts(t,e){return gr(this,t,e)}async getCoinAmount(t,e){return hr(this,t,e)}async getMarketCoinAmounts(t,e){return yr(this,t,e)}async getMarketCoinAmount(t,e){return Sr(this,t,e)}async getPriceFromPyth(t){return Tr(this,t)}async getAllStakeAccounts(t){return Yt(this,t)}async getStakeAccounts(t,e){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t){let e=t??[...Xt],n={};for(let o=0;o<e.length;o++){let r=e[o],i=await Qa(this,r);i&&(n[r]=i)}return n}async getStakePool(t){return Qa(this,t)}async getStakeRewardPools(t){let e=t??[...Xt],n={};for(let o=0;o<e.length;o++){let r=await Va(this,e[o]);r&&(n[e[o]]=r)}return n}async getStakeRewardPool(t){return Va(this,t)}async getBorrowIncentiveAccounts(t,e,n){return Cr(this,t,e||this.walletAddress,n)}async getObligationCoinNames(t){let e=await wr(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),o=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...o])].map(s=>this.utils.parseCoinNameFromType(s))}};var _t=class{params;isTestnet;address;query;utils;client;walletAddress;constructor(t,e){this.params=t,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.query=e?.query??new Pt(t,{address:this.address}),this.utils=e?.utils??new it(this.params,{address:this.address,query:this.query}),this.client=t.client,this.walletAddress=nc(t.walletAddress),this.isTestnet=t.networkType?t.networkType==="testnet":!1}async init(t=!1,e){t||!this.address.getAddresses()||!e?.getAddresses()?this.address.read():this.address=e,this.query.init(t,this.address),this.utils.init(t,this.address)}createTxBlock(t){return new ec(t)}async selectCoin(t,e,n,o){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,o),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,o){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoinIds(n,r,o),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}};import{SUI_CLOCK_OBJECT_ID as jt,SUI_TYPE_ARG as ac}from"@mysten/sui.js/utils";var mt=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await Ka(t.query,n);return i||void 0}let o=j(e),r=await Ir(t.query,o);if(r.length!==0)return r[0]},oc=async(a,t)=>{let e=a.address.get("borrowIncentive.object"),n=a.address.get("borrowIncentive.incentivePools"),o=a.address.get("vesca.id"),{client:r}=a,i=await r.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,l=`${e}::typed_id::TypedID<${o}::ve_sca::VeScaKey>`,d=await r.getDynamicFieldObject({parentId:c,name:{type:l,value:t}});return d.data?.content?.dataType!=="moveObject"?!1:d.data.content.fields.value.fields.id},Ha=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&n&&o&&typeof n=="string"){let s=await $a(t.query,n);return{obligationId:n,obligationKey:o,obligationLocked:s}}let r=j(e),i=await Dt(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId,obligationLocked:i[0].locked}},rc=({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"},o={table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(jt)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(o.config),t.object(o.treasury),t.object(o.table),t.object(s),t.object(jt)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(jt)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(jt)],typeArguments:[ac]})},claimBorrowIncentive:(r,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(r),t.object(jt)],typeArguments:[c]})},oldClaimBorrowIncentive(r,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(r),t.object(jt)],typeArguments:[c]})}}},W=({builder:a,txBlock:t})=>{let e=rc({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Ha(a,t,n,o),c=!!t.blockData.transactions.find(l=>l.kind==="MoveCall"&&l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`);(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Ha(a,t,n,o);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,o,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await Ha(a,t,n,o),l=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${vt}::user::unstake`||d.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||l){let d=await mt(a,t,r);if(d){let p=await oc(a,d.keyId);!p||p===i?e.stakeObligationWithVesca(i,s,d.keyId):e.stakeObligation(i,s)}else e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,o,r)=>e.claimBorrowIncentive(o,r,n)}};import{SUI_CLOCK_OBJECT_ID as st}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as An}from"@mysten/sui.js/utils";import ic from"axios";var xr={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};import{bcs as za}from"@mysten/sui.js/bcs";import{SUI_CLOCK_OBJECT_ID as xn}from"@mysten/sui.js/utils";var Xa=16*1024,vn=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(),o=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(za.ser("vector<u8>",Array.from(r),{maxSize:Xa}).toBytes()),e.object(xn)]});o.push(i)}),o}async updatePriceFeeds(t,e,n){let o=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${o}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(za.ser("vector<u8>",Array.from(e[0]),{maxSize:Xa}).toBytes()),s[0],t.object(xn)]});let c=[],l=await this.getBaseUpdateFee(),d=t.splitCoins(t.gas,n.map(()=>t.pure(l))),p=0;for(let m=0;m<n.length;m++){let b=await this.getPriceFeedObjectId(n[m]);if(!b)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(b),[r]=t.moveCall({target:`${o}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(b),d[p],t.object(xn)]}),p++}return t.moveCall({target:`${o}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${o}::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 o=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([o],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(za.ser("vector<u8>",Array.from(e[0]),{maxSize:Xa}).toBytes()),r[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:o}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${o}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,o=t.readUint16BE(n),r=n+2;return t.subarray(r,r+o)}};var sc=async(a,t)=>(await ic.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(o=>Buffer.from(o,"base64")),On=async(a,t,e)=>{let n=e??[...new Set([...pt,...wn])],o=a.isTestnet?["pyth"]:["pyth"];if(o.includes("pyth")){let i=new vn(a.client,a.address.get("core.oracles.pyth.state"),a.address.get("core.oracles.pyth.wormholeState")),s=n.map(l=>a.address.get(`core.coins.${l}.oracle.pyth.feed`)),c=a.params.pythEndpoints??xr[a.isTestnet?"testnet":"mainnet"];try{let l=await sc(c[0],s);await i.updatePriceFeeds(t,l,s)}catch(l){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${l}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await cc(a,t,r[i],o)},cc=async(a,t,e,n)=>{let o=a.utils.parseCoinType(e);dc(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"),o)},dc=(a,t,e,n,o,r,i,s,c,l,d,p,m,b,f)=>{let h=lc(a,e,n,f);return t.includes("pyth")&&bc(a,o,h,i,s,r,f),t.includes("switchboard")&&mc(a,c,h,d,l,f),t.includes("supra")&&pc(a,p,h,b,m,f),uc(a,e,n,h,f),a},lc=(a,t,e,n)=>{let o=typeof e=="string"?a.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return a.moveCall({target:r,arguments:[o],typeArguments:i})},uc=(a,t,e,n,o)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[o],s=typeof e=="string"?a.object(e):e;return a.moveCall({target:r,arguments:[s,n,a.object(An)],typeArguments:i}),a},pc=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(An)],typeArguments:[r]})},mc=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(An)],typeArguments:[r]})},bc=(a,t,e,n,o,r,i)=>{let s=typeof e=="string"?a.object(e):e,c=typeof n=="string"?a.object(n):n,l=typeof o=="string"?a.object(o):o,d=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,l,d,a.object(An)],typeArguments:[i]})};var Dn=async(...a)=>{let[t,e,n,o]=a;if(a.length===3&&n)return{obligationId:n};if(a.length===4&&n&&o)return{obligationId:n,obligationKey:o};let r=j(t),i=await Dt(e.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},fc=({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")};return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.pure(e.version)]}),returnObligation:(n,o)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(n),t.object(o)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(n),t.object(e.market),typeof o!="string"?o:t.pure(o)],typeArguments:[i]})},takeCollateral:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},deposit:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},depositEntry:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},withdraw:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},withdrawEntry:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},borrow:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},borrowEntry:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},repay:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(n),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(st)],typeArguments:[i]})},borrowFlashLoan:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(n)],typeArguments:[r]})},repayFlashLoan:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(n),t.object(o)],typeArguments:[i]})}}},q=({builder:a,txBlock:t})=>{let e=fc({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(n,o,r)=>{let i=j(t),{obligationId:s}=await Dn(t,a,r);if(o==="sui"){let[c]=t.splitCoins(t.gas,[n]);e.addCollateral(s,c,o)}else{let{leftCoin:c,takeCoin:l}=await a.selectCoin(t,o,n,i);e.addCollateral(s,l,o),t.transferObjects([c],i)}},takeCollateralQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r,i),c=await a.query.getObligationCoinNames(s.obligationId);return await On(a,t,c),e.takeCollateral(s.obligationId,s.obligationKey,n,o)},depositQuick:async(n,o,r)=>{if(o==="sui"){let[c]=t.splitCoins(t.gas,[n]);return e.deposit(c,o)}let{leftCoin:i,takeCoin:s}=await a.selectCoin(t,o,n,r);return t.transferObjects([i],r),e.deposit(s,o)},withdrawQuick:async(n,o)=>{let r=j(t),i=a.utils.parseMarketCoinName(o),{leftCoin:s,takeCoin:c}=await a.selectMarketCoin(t,i,n,r);return t.transferObjects([s],r),e.withdraw(c,o)},borrowQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r,i),l=[...await a.query.getObligationCoinNames(s.obligationId),o];return await On(a,t,l),e.borrow(s.obligationId,s.obligationKey,n,o)},repayQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r);if(o==="sui"){let[d]=t.splitCoins(t.gas,[n]);return e.repay(s.obligationId,d,o)}let{leftCoin:c,takeCoin:l}=await a.selectCoin(t,o,n,i);return t.transferObjects([c],i),e.repay(s.obligationId,l,o)},updateAssetPricesQuick:async n=>On(a,t,n)}};import{SUI_CLOCK_OBJECT_ID as Pn}from"@mysten/sui.js/utils";var vr=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&o)return[o];let r=j(e),i=await Yt(t.query,r);if(i[n].length===0)throw new Error(`No stake account id found for sender ${r}`);return i[n].map(s=>s.id)},gc=async(...a)=>{let[t,e,n,o]=a,r=j(e),i=await Yt(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return o?i[n].filter(c=>c.id===o):i[n]},hc=({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")};return{createStakeAccount:n=>{let o=a.utils.parseMarketCoinType(n),r=a.address.get(`spool.pools.${n}.id`);return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(r),t.object(Pn)],typeArguments:[o]})},stake:(n,o,r)=>{let i=a.utils.parseMarketCoinType(r),s=a.address.get(`spool.pools.${r}.id`);t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(s),t.object(n),typeof o=="string"?t.pure(o):o,t.object(Pn)],typeArguments:[i]})},unstake:(n,o,r)=>{let i=a.utils.parseMarketCoinType(r),s=a.address.get(`spool.pools.${r}.id`);return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(s),t.object(n),t.pure(o),t.object(Pn)],typeArguments:[i]})},claim:(n,o)=>{let r=a.address.get(`spool.pools.${o}.id`),i=a.address.get(`spool.pools.${o}.rewardPoolId`),s=a.utils.parseMarketCoinType(o),c=Cn[o],l=a.utils.parseCoinType(c);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(r),t.object(i),t.object(n),t.object(Pn)],typeArguments:[s,l]})}}},bt=({builder:a,txBlock:t})=>{let e=hc({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(n,o,r)=>{let i=j(t),s=await vr(a,t,o,r),c=a.utils.parseMarketCoinType(o);if(typeof n=="number"){let l=await a.utils.selectCoinIds(n,c,i),[d,p]=a.utils.takeAmountFromCoins(t,l,n);e.stake(s[0],d,o),t.transferObjects([p],i)}else e.stake(s[0],n,o)},unstakeQuick:async(n,o,r)=>{let i=n,s=await gc(a,t,o,r),c=[];for(let l=0;l<s.length;l++){if(s[l].staked===0)continue;let d=Math.min(i,s[l].staked),p=e.unstake(s[l].id,d,o);if(c.push(p),i-=d,i===0)break}return c},claimQuick:async(n,o)=>{let r=await vr(a,t,n,o),i=[];return r.forEach(s=>{let c=e.claim(s,n);i.push(c)}),i}}};import{SUI_CLOCK_OBJECT_ID as Zt}from"@mysten/sui.js/utils";var yc=({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,o)=>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(o),t.object(Zt)]}),extendLockPeriod:(n,o)=>{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(o),t.object(Zt)]})},extendLockAmount:(n,o)=>{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 o=="string"?t.pure(o):o,t.object(Zt)]})},renewExpiredVeSca:(n,o,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof o=="string"?t.pure(o):o,t.pure(r),t.object(Zt)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(Zt)]})}},ft=({builder:a,txBlock:t})=>{let e=yc({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,o,r=!0)=>{let i=j(t),s=await mt(a,t),c,l=[];if(n!==void 0&&typeof n=="number"){let b=await a.utils.selectCoinIds(n,ot,i),[f,h]=a.utils.takeAmountFromCoins(t,b,n);c=f,l.push(h)}else c=n;let d=a.utils.getUnlockAt(o,s?.unlockAt);r&&cr(n,o,d,s?.unlockAt),console.log(new Date(d*1e3).toLocaleString("en-CA",{hour12:!0}));let p=!s?.unlockAt,m=!p&&s.unlockAt*1e3<=new Date().getTime();if(p||m){if(c)if(p){let b=e.lockSca(c,d);l.push(b)}else{if(s.lockedScaAmount!==0){let b=e.redeemSca(s.keyId);l.push(b)}e.renewExpiredVeSca(s.keyId,c,d)}}else c&&o?(e.extendLockPeriod(s.keyId,d),e.extendLockAmount(s.keyId,c)):o?e.extendLockPeriod(s.keyId,d):c&&e.extendLockAmount(s.keyId,c);l.length>0&&t.transferObjects(l,i)},extendLockPeriodQuick:async(n,o,r=!0)=>{let i=await mt(a,t,o),s=a.utils.getUnlockAt(n);r&&dr(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,o,r=!0)=>{let i=j(t),s=await mt(a,t,o);if(r&&lr(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,ot,i),[l,d]=a.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,l),t.transferObjects([d],i)}},renewExpiredVeScaQuick:async(n,o,r,i=!0)=>{let s=j(t),c=await mt(a,t,r),l=a.utils.getUnlockAt(o,c?.unlockAt);if(i&&ur(n,o,c?.unlockAt),c){let d=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);d.push(f)}let p=await a.utils.selectCoinIds(n,ot,s),[m,b]=a.utils.takeAmountFromCoins(t,p,n);d.push(b),e.renewExpiredVeSca(c.keyId,m,l),t.transferObjects(d,s)}},redeemScaQuick:async n=>{let o=j(t),r=await mt(a,t,n);if(Ot(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],o)}}}};var y=class{params;client;address;builder;query;utils;walletAddress;constructor(t,e){this.params=t,this.client=t.client,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.query=e?.query??new Pt(t,{address:this.address}),this.utils=e?.utils??new it(t,{address:this.address,query:this.query}),this.builder=e?.builder??new _t(t,{address:this.address,query:this.query,utils:this.utils}),this.walletAddress=Sc(t.walletAddress)}init(t=!1){(t||!this.address.getAddresses())&&this.address.read(),this.builder.init(t,this.address),this.query.init(t,this.address),this.utils.init(t,this.address)}async getObligations(t){let e=t||this.walletAddress;return this.query.getObligations(e)}async getAllStakeAccounts(t){let e=t||this.walletAddress;return this.query.getAllStakeAccounts(e)}async getStakeAccounts(t,e){let n=e||this.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 x,n=q({builder:this.builder,txBlock:e}),o=t||this.walletAddress;return e.setSender(o),n.normalMethod.openObligationEntry(),e}async depositCollateral(t,e,n,o){let r=new x,i=o||this.walletAddress;r.setSender(i);let s=q({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),l=n||c?.[0]?.id;if(l)await s.addCollateralQuick(e,t,l);else{let[d,p,m]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,d),s.normalMethod.returnObligation(d,m),r.transferObjects([p],i)}return r}async withdrawCollateral(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=r||this.walletAddress;i.setSender(c);let l=await s.takeCollateralQuick(e,t,n,o);return i.transferObjects([l],c),i}async deposit(t,e,n){let o=new x,r=q({builder:this.builder,txBlock:o}),i=n||this.walletAddress;o.setSender(i);let s=await r.depositQuick(e,t,n);return o.transferObjects([s],i),o}async withdraw(t,e,n){let o=new x,r=n||this.walletAddress,i=q({builder:this.builder,txBlock:o});o.setSender(r);let s=await i.withdrawQuick(e,t);return o.transferObjects([s],r),o}async borrow(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=W({builder:this.builder,txBlock:i}),l=r||this.walletAddress;i.setSender(l);let d=At.includes(t);d&&await c.unstakeObligationQuick(n,o);let p=await s.borrowQuick(e,t,n,o);return i.transferObjects([p],l),d&&await c.stakeObligationQuick(n,o),i}async borrowWithBoost(t,e,n,o,r,i){let s=new x,c=q({builder:this.builder,txBlock:s}),l=W({builder:this.builder,txBlock:s}),d=i||this.walletAddress;s.setSender(d);let p=At.includes(t);p&&await l.unstakeObligationQuick(n,o);let m=await c.borrowQuick(e,t,n,o);return s.transferObjects([m],d),p&&await l.stakeObligationWithVeScaQuick(n,o,r),s}async repay(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=W({builder:this.builder,txBlock:i}),l=r||this.walletAddress;i.setSender(l);let d=At.includes(t);return d&&await c.unstakeObligationQuick(n,o),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationQuick(n,o),i}async createStakeAccount(t,e){let n=new x,o=bt({builder:this.builder,txBlock:n}),r=e||this.walletAddress;n.setSender(r);let i=o.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,o){let r=new x,i=q({builder:this.builder,txBlock:r}),s=bt({builder:this.builder,txBlock:r}),c=o||this.walletAddress;r.setSender(c);let l=await i.depositQuick(e,t,o),d=this.utils.parseMarketCoinName(t);if(!Xt.find(b=>b===d))return r;let p=await this.query.getStakeAccounts(d,c),m=n||(p.length>0?p[0].id:void 0);if(m)await s.stakeQuick(l,d,m);else{let b=s.normalMethod.createStakeAccount(d);await s.stakeQuick(l,d,b),r.transferObjects([b],c)}return r}async unstakeAndWithdraw(t,e,n){let o=new x,r=q({builder:this.builder,txBlock:o}),i=bt({builder:this.builder,txBlock:o}),s=this.walletAddress,c=[];o.setSender(s);let l=this.utils.parseMarketCoinName(t);for(let d=0;d<n.length;d++){let p=n[d],[m]=await i.unstakeQuick(p.coin,l,p.id);if(m){let b=r.normalMethod.withdraw(m,t);c.push(b)}}if(e>0){let d=await r.withdrawQuick(e,t);c.push(d)}return o.transferObjects(c,s),o}async stake(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=o||this.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),l=n||(c.length>0?c[0].id:void 0);if(l)await i.stakeQuick(e,t,l);else{let d=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,d),r.transferObjects([d],s)}return r}async unstake(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=o||this.walletAddress;r.setSender(s);let c=await i.unstakeQuick(e,t,n);return r.transferObjects(c,s),r}async claim(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=W({builder:this.builder,txBlock:r}),c=o||this.walletAddress;r.setSender(c);let l={sui:[],sca:[]};for(let d=0;d<t.length;d++){let{stakeMarketCoinName:p,stakeAccountId:m}=t[d],b=i.normalMethod.claim(m,p);l.sui.push(b)}for(let d=0;d<e.length;d++){let{obligationId:p,obligationKey:m,rewardCoinName:b}=e[d],f=s.normalMethod.claimBorrowIncentive(p,m,b);l[b].push(f)}for(let d=0;d<n.length;d++){let{obligationId:p,obligationKey:m,rewardCoinName:b}=n[d],f=s.normalMethod.oldClaimBorrowIncentive(p,m,b);l[b].push(f)}return l.sui.length>0&&(l.sui.length>1&&r.mergeCoins(l.sui[0],l.sui.slice(1)),r.transferObjects([l.sui[0]],r.pure(c))),l.sca.length>0&&(l.sca.length>1&&r.mergeCoins(l.sca[0],l.sca.slice(1)),r.transferObjects([l.sca[0]],r.pure(c))),r}async stakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=W({builder:this.builder,txBlock:o}),i=n||this.walletAddress;return o.setSender(i),await r.stakeObligationQuick(t,e),o}async unstakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=W({builder:this.builder,txBlock:o}),i=n||this.walletAddress;return o.setSender(i),await r.unstakeObligationQuick(t,e),o}async stakeSca(t,e=!1,n=!1,o,r,i,s,c){let l=new x,d=ft({builder:this.builder,txBlock:l}),p=W({builder:this.builder,txBlock:l}),m=c||this.walletAddress;l.setSender(m);let b=await this.builder.utils.selectCoinIds(t,ot,m),[f,h]=this.builder.utils.takeAmountFromCoins(l,b,t),w;return s?d.normalMethod.extendLockAmount(s,f):w=d.normalMethod.lockSca(f,i),o&&r&&(e&&(n?p.normalMethod.oldUnstakeObligation(o,r):p.normalMethod.unstakeObligation(o,r)),p.normalMethod.stakeObligationWithVesca(o,r,s||w)),s||l.transferObjects([w,h],m),l}async stakeMoreSca(t,e,n){let o=new x,r=n||this.walletAddress;return o.setSender(r),o}async extendStakeScaLockPeriod(t,e,n,o,r=!1,i=!1,s){let c=new x,l=ft({builder:this.builder,txBlock:c}),d=W({builder:this.builder,txBlock:c}),p=s||this.walletAddress;return c.setSender(p),l.normalMethod.extendLockPeriod(e,t),n&&o&&(r&&(i?d.normalMethod.oldUnstakeObligation(n,o):d.normalMethod.unstakeObligation(n,o)),d.normalMethod.stakeObligationWithVesca(n,o,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,o,r,i=!1,s=!1,c){let l=new x,d=ft({builder:this.builder,txBlock:l}),p=W({builder:this.builder,txBlock:l}),m=c||this.walletAddress;l.setSender(m);let b=await this.builder.utils.selectCoinIds(t,ot,m),[f,h]=this.builder.utils.takeAmountFromCoins(l,b,t);return d.normalMethod.extendLockPeriod(e,n),d.normalMethod.extendLockAmount(e,f),l.transferObjects([h],m),!o||!r||(i&&(s?p.normalMethod.oldUnstakeObligation(o,r):p.normalMethod.unstakeObligation(o,r)),p.normalMethod.stakeObligationWithVesca(o,r,e)),l}async renewExpiredStakeSca(t,e,n,o=!1,r,i,s=!1,c=!1,l){let d=new x,p=ft({builder:this.builder,txBlock:d}),m=W({builder:this.builder,txBlock:d}),b=l||this.walletAddress;if(d.setSender(b),o){let P=p.normalMethod.redeemSca(n);d.transferObjects([P],b)}let f=await this.builder.utils.selectCoinIds(t,ot,b),[h,w]=this.builder.utils.takeAmountFromCoins(d,f,t);return d.transferObjects([w],b),p.normalMethod.renewExpiredVeSca(n,h,e),!r||!i||(s&&(c?m.normalMethod.oldUnstakeObligation(r,i):m.normalMethod.unstakeObligation(r,i)),m.normalMethod.stakeObligationWithVesca(r,i,n)),d}async redeemSca(t){let e=new x,n=ft({builder:this.builder,txBlock:e}),o=this.walletAddress;return e.setSender(o),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,o){let r=new x,i=W({builder:this.builder,txBlock:r}),s=this.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(n,e,o);return r.transferObjects([c],s),i.stakeObligationWithVeScaQuick(n,e,t),r}async withdrawUnlockedSca(t,e){let n=new x,o=ft({builder:this.builder,txBlock:n}),r=e||this.walletAddress;return n.setSender(r),await o.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new Ar(t.weightedAmount),r=e.currentPointIndex?Ar(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}};var _n=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 jn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return await n.init(),n.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 Bn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var Rn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new a(e)}};var Nn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 En=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 Mn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return await n.init(),n.migrateAndClaim(this.data.veScaKey,this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName)}static fromData(e){return new a(e)}};var Ln=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.openObligation()}static fromData(e){return new a(e)}};var Wn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.redeemSca(this.data.veScaKey)}static fromData(e){return new a(e)}};var Fn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 Un=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Qn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Gn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Kn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new a(e)}};var Hn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 zn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Xn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new a(e)}};var Jn=class{application="scallop";async deserialize(t){let e=new _t({client:t.suiClient,walletAddress:t.account.address,networkType:t.network.split(":")[1]});await e.init();let{transactionBlock:n}=t,r=new Tn(n,e).decode();return{txType:wc.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"SupplyLending":r=Vn.fromData(t.intentionData);break;case"WithdrawLending":r=zn.fromData(t.intentionData);break;case"Borrow":r=_n.fromData(t.intentionData);break;case"Repay":r=qn.fromData(t.intentionData);break;case"DepositCollateral":r=Rn.fromData(t.intentionData);break;case"WithdrawCollateral":r=Hn.fromData(t.intentionData);break;case"OpenObligation":r=Ln.fromData(t.intentionData);break;case"StakeSpool":r=$n.fromData(t.intentionData);break;case"UnstakeSpool":r=Gn.fromData(t.intentionData);break;case"ClaimIncentiveReward":r=Bn.fromData(t.intentionData);break;case"BorrowWithBoost":r=jn.fromData(t.intentionData);break;case"StakeSca":r=Un.fromData(t.intentionData);break;case"ExtendStakePeriod":r=En.fromData(t.intentionData);break;case"ExtendPeriodAndStakeMore":r=Nn.fromData(t.intentionData);break;case"RenewExpStakePeriod":r=Fn.fromData(t.intentionData);break;case"WithdrawStakedSca":r=Xn.fromData(t.intentionData);break;case"SupplyAndStakeLending":r=Qn.fromData(t.intentionData);break;case"WithdrawAndUnstakeLending":r=Kn.fromData(t.intentionData);break;case"RedeemSca":r=Wn.fromData(t.intentionData);break;case"MigrateAndClaim":r=Mn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as qc}from"@msafe/sui3-utils";import{TurbosSdk as Uc}from"turbos-clmm-sdk";import{TransactionType as F}from"@msafe/sui3-utils";import{bcs as Or}from"@mysten/sui.js/bcs";import{normalizeStructTag as Tc,normalizeSuiAddress as te}from"@mysten/sui.js/utils";var U={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},$={PackageId:"0xdee9"};import{BN as kc}from"turbos-clmm-sdk";var Ic=(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(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},Yn=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`]}decode(t){if(this.isSwapTransaction())return 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(`${U.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${U.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${$.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${$.PackageId}::clob_v2::swap_exact_quote_for_base`)}decodeSwap(){let t=this.transactions.find(m=>m.kind==="MoveCall"),e=0;this.swap2Layer.includes(t.target)&&(e=1);let n=Ic(e,t.target,this.swap1Layer,this.swap2Layer),o=n.map((m,b)=>{let f=this.helper.decodeSharedObjectId(b),h=this.helper.decodeInputU128(4+b+e),w=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new kc(h.toString()));return{pool:f,a2b:m,nextTickIndex:w}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),l=this.helper.decodeInputBool(5+2*e),d=this.helper.decodeInputU64(2+e),p=this.helper.decodeInputU64(3+e);return{txType:F.Other,type:"Swap",intentionData:{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:p,amountB:l?p:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:F.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:o,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:F.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:o,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:F.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:F.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:o,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:F.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:o,nft:e,deadline:r}}}decodeBurn(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:F.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(p=>p.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:F.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:F.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:F.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:F.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:F.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero");return new ct(t,this.txb)}get collectRewardHelper(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect_reward`).map(e=>new ct(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new ct(t,this.txb)}get decreaseLiquidityHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new ct(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${$.PackageId}::clob_v2::swap_exact_base_for_quote`);return new ct(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${$.PackageId}::clob_v2::swap_exact_quote_for_base`);return new ct(t,this.txb)}},ct=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 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 Or.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 Or.de(e,new Uint8Array(n))}typeArg(t){return Tc(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as xc}from"turbos-clmm-sdk";var Zn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new xc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:p,txb:m}=this.data;return n.pool.addLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as vc}from"turbos-clmm-sdk";var ta=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new vc(e.network.replace("sui:",""),e.suiClient),{pool:o,nft:r,txb:i}=this.data;return n.nft.burn({pool:o,nft:r,txb:i})}static fromData(e){return new a(e)}};import{TurbosSdk as Ac}from"turbos-clmm-sdk";var ea=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ac(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:o,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(e){return new a(e)}};import{TurbosSdk as Oc}from"turbos-clmm-sdk";var na=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Oc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:o,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(e){return new a(e)}};import{TurbosSdk as Dc}from"turbos-clmm-sdk";var aa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Dc(e.network.replace("sui:",""),e.suiClient),{fee:o,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:p,amountA:m,amountB:b,deadline:f,txb:h}=this.data;return n.pool.createPool({fee:o,amountA:m,amountB:b,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:p,deadline:f,txb:h})}static fromData(e){return new a(e)}};import{TurbosSdk as Pc}from"turbos-clmm-sdk";var oa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Pc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:p,txb:m}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as _c}from"turbos-clmm-sdk";var ra=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new _c(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:p}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:p})}static fromData(e){return new a(e)}};import{TransactionBlock as jc}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as Bc}from"@mysten/sui.js/utils";var ia=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new jc;return n.moveCall({target:`${U.PackageId}::claim::claim`,typeArguments:[U.turbosCoinType],arguments:[n.object(U.Claim),n.object(Bc)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Rc}from"@mysten/sui.js/transactions";var sa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Rc;return n.moveCall({target:`${U.PackageId}::claim::join`,typeArguments:[U.turbosCoinType],arguments:[n.object(U.Claim)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Nc}from"@mysten/sui.js/transactions";import{TurbosSdk as Ec}from"turbos-clmm-sdk";var ca=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ec(e.network.replace("sui:",""),e.suiClient),o=new Nc;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(e){return new a(e)}};import{TurbosSdk as Mc}from"turbos-clmm-sdk";var da=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Mc(e.network.replace("sui:",""),e.suiClient),{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:p,deadline:m,txb:b}=this.data;return n.trade.swap({routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:p,slippage:d,deadline:m,txb:b})}static fromData(e){return new a(e)}};import{TurbosSdk as Wc}from"turbos-clmm-sdk";import{normalizeSuiObjectId as Dr}from"@mysten/sui.js/utils";import{TransactionBlock as Pr}from"@mysten/sui.js/transactions";import{unstable_getObjectId as Lc}from"turbos-clmm-sdk";var ee=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let o=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),o.push(...r.data);while(r.hasNextPage);let i=[],s=0;return o.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let o=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(o,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(o,[n.pure(e)]);return[r,o]}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:`${$.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?Lc(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${$.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var _r=89,jr=1e6,Br=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Pr,c=new ee(i),l=await c.getCoinsData(r,e,o),[d,p]=c.splitAndMergeCoin(l,o,s);if(!d)throw new Error(`Not enough balance: ${e}`);let m=await c.IsAccountCap(r),b=m?s.object(m):c.createAccount(s),[f,h,w]=s.moveCall({typeArguments:[t,e],target:`${$.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(_r),b,s.pure(o),s.object(Dr("0x6")),d]});return p&&s.transferObjects([p],s.pure(r)),s.transferObjects([f],s.pure(r)),s.transferObjects([h],s.pure(r)),m||s.transferObjects([b],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(jr),s},Rr=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Pr,c=new ee(i),l=await c.getCoinsData(r,t,o),[d,p]=c.splitAndMergeCoin(l,o,s);if(!d)throw new Error(`Not enough balance: ${t}`);let m=await c.IsAccountCap(r),b=m?s.object(m):c.createAccount(s),f=c.zero(e,s),[h,w,P]=s.moveCall({typeArguments:[t,e],target:`${$.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(_r),b,s.pure(o),d,f,s.object(Dr("0x6"))]});return p&&s.transferObjects([p],s.pure(r)),s.transferObjects([h],s.pure(r)),s.transferObjects([w],s.pure(r)),m||s.transferObjects([b],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(jr),s};var la=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Wc(e.network.replace("sui:",""),e.suiClient);return await Rr({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};import{TurbosSdk as Fc}from"turbos-clmm-sdk";var ua=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Fc(e.network.replace("sui:",""),e.suiClient);return await Br({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var pa=class{application="turbos";async deserialize(t){let e=new Uc(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:o,account:r}=t,s=new Yn(o,e,n).decode(r.address);return{txType:qc.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"CreatePool":r=aa.fromData(t.intentionData);break;case"AddLiquidity":r=Zn.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ra.fromData(t.intentionData);break;case"DecreaseLiquidity":r=oa.fromData(t.intentionData);break;case"RemoveLiquidity":r=ca.fromData(t.intentionData);break;case"CollectFee":r=ea.fromData(t.intentionData);break;case"CollectReward":r=na.fromData(t.intentionData);break;case"Burn":r=ta.fromData(t.intentionData);break;case"Swap":r=da.fromData(t.intentionData);break;case"PrixJoin":r=sa.fromData(t.intentionData);break;case"PrixClaim":r=ia.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=la.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=ua.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as zc}from"@msafe/sui3-utils";import{TransactionType as Ja}from"@msafe/sui3-utils";import{bcs as Nr}from"@mysten/sui.js/bcs";import{normalizeStructTag as Vc,normalizeSuiAddress as ne}from"@mysten/sui.js/utils";var $c={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},k=$c;var ma=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(`${k.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${k.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${k.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:Ja.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Ja.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:Ja.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(k.packageId));return new Ya(t,this.txb)}},Ya=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 ne(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 Nr.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 ne(t.value.Object.ImmOrOwned.objectId)}return ne(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ne(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ne(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 Nr.de(e,new Uint8Array(n))}typeArg(t){return Vc(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Gc}from"@mysten/sui.js/transactions";var ba=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Gc,{ticketId:o}=this.data;return n.moveCall({target:`${k.packageId}::native_pool::burn_ticket`,arguments:[n.object(k.poolObjectId),n.object(k.systemStateObjectId),n.object(o)]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Kc}from"@mysten/sui.js/transactions";var fa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Kc,{amount:o}=this.data,[r]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${k.packageId}::native_pool::stake`,arguments:[n.object(k.poolObjectId),n.object(k.metadataObjectId),n.object(k.systemStateObjectId),r]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Hc}from"@mysten/sui.js/transactions";var ga=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Hc,{amount:o}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===k.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${k.packageId}::native_pool::unstake`,arguments:[n.object(k.poolObjectId),n.object(k.metadataObjectId),n.object(k.systemStateObjectId),l]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};var ha=class{application="volo";async deserialize(t){let{transactionBlock:e}=t,o=new ma(e).decode();return{txType:zc.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(t.txSubType){case"Stake":o=fa.fromData(t.intentionData);break;case"UnStake":o=ga.fromData(t.intentionData);break;case"ClaimTicket":o=ba.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};var lx=new yn([new sn,new gn,new nn,new hn,new Te,new pa,new Pe,new Jn,new ha]);export{lx as appHelpers};
1
+ var Er=Object.defineProperty;var Za=(a,t)=>{for(var e in t)Er(a,e,{get:t[e],enumerable:!0})};import{TransactionType as di}from"@msafe/sui3-utils";import{TransactionType as Qr}from"@msafe/sui3-utils";import Mr from"sort-keys-recursive";var u=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(Mr(this.data))}};import{CetusPeripherySDK as Lr}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as Wr}from"@cetusprotocol/cetus-sui-clmm-sdk";var Fr={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:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",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"},qr={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:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},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:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},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:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Ur={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"},$r={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"}},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"}},haedal:{package_id:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472",published_at:"0x9dac9c5770e5f930d2223ff68782958701acfaee9337e8d8363978ce7670dffb",config:{support_stakings:[{staking_id:"0x6e384d2da5b040b27f973155e25bbe4beb0ad5ca8ee0a36e20dff356094c9fc0",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472::hasui::HASUI"}]}}},dt=(a,t)=>{let e=a==="sui:mainnet"?Fr:Ur,n=new Wr(e);return n.senderAddress=t.address,n},_=(a,t)=>{let e=dt(a,t),n=a==="sui:mainnet"?qr:$r;return new Lr(n,e)};var to=async(a,t,e)=>await dt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),eo=async(a,t,e)=>await dt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),no=async(a,t,e)=>await dt(e,t).Position.closePositionTransactionPayload(a),ao=async(a,t,e)=>await dt(e,t).Position.removeLiquidityTransactionPayload(a),oo=async(a,t,e)=>await dt(e,t).Rewarder.collectRewarderTransactionPayload(a);var ae=class a extends u{constructor(e){super(e);this.data=e}txType=Qr.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await to(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Vr}from"@msafe/sui3-utils";var oe=class a extends u{constructor(e){super(e);this.data=e}txType=Vr.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await oo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Gr}from"@msafe/sui3-utils";var re=class a extends u{constructor(e){super(e);this.data=e}txType=Gr.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ao(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Kr}from"@msafe/sui3-utils";var ro=async(a,t,e)=>await _(e,t).Farms.openPositionAddLiquidityStakePaylod(a),io=async(a,t,e)=>await _(e,t).Farms.addLiquidityFixCoinPayload(a),so=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),co=async(a,t,e)=>await _(e,t).Farms.removeLiquidityPayload(a),lo=async(a,t,e)=>await _(e,t).Farms.claimFeeAndClmmReward(a),uo=async(a,t,e)=>{let n=_(e,t);return console.log("getFarmingHarvest txbParams: ",a),await n.Farms.harvestPayload(a)},po=async(a,t,e)=>{let n=_(e,t),o=Object.values(a);return console.log("getFarmingBatchHarvest params: ",o),await n.Farms.batchHarvestPayload(o)},mo=async(a,t,e)=>await _(e,t).Farms.depositPayload(a),bo=async(a,t,e)=>await _(e,t).Farms.withdrawPayload(a);var ie=class a extends u{constructor(e){super(e);this.data=e}txType=Kr.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ro(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Hr}from"@msafe/sui3-utils";var se=class a extends u{constructor(e){super(e);this.data=e}txType=Hr.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await po(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as zr}from"@msafe/sui3-utils";var ce=class a extends u{constructor(e){super(e);this.data=e}txType=zr.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await lo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Xr}from"@msafe/sui3-utils";var de=class a extends u{constructor(e){super(e);this.data=e}txType=Xr.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await so(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Jr}from"@msafe/sui3-utils";var le=class a extends u{constructor(e){super(e);this.data=e}txType=Jr.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await uo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Yr}from"@msafe/sui3-utils";var ue=class a extends u{constructor(e){super(e);this.data=e}txType=Yr.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await io(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Zr}from"@msafe/sui3-utils";var pe=class a extends u{constructor(e){super(e);this.data=e}txType=Zr.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await co(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ti}from"@msafe/sui3-utils";var me=class a extends u{constructor(e){super(e);this.data=e}txType=ti.Other;txSubType="FarmingStake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await mo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ei}from"@msafe/sui3-utils";var be=class a extends u{constructor(e){super(e);this.data=e}txType=ei.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await bo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ni}from"@msafe/sui3-utils";var fe=class a extends u{constructor(e){super(e);this.data=e}txType=ni.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await eo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ai}from"@msafe/sui3-utils";var ge=class a extends u{constructor(e){super(e);this.data=e}txType=ai.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await no(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as oi}from"@msafe/sui3-utils";var fo=async(a,t,e)=>await _(e,t).XCetusModule.convertPayload(a),go=async(a,t,e)=>await _(e,t).XCetusModule.redeemLockPayload(a),ho=async(a,t,e)=>await _(e,t).XCetusModule.redeemDividendV2Payload(a.venft_id,a.bonus_types,a.xTokenType),yo=async(a,t,e)=>await _(e,t).XCetusModule.cancelRedeemPayload(a),So=async(a,t,e)=>await _(e,t).XCetusModule.redeemPayload(a);var he=class a extends u{constructor(e){super(e);this.data=e}txType=oi.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await yo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ri}from"@msafe/sui3-utils";var ye=class a extends u{constructor(e){super(e);this.data=e}txType=ri.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ho(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ii}from"@msafe/sui3-utils";var Se=class a extends u{constructor(e){super(e);this.data=e}txType=ii.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await fo(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as si}from"@msafe/sui3-utils";var we=class a extends u{constructor(e){super(e);this.data=e}txType=si.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await So(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ci}from"@msafe/sui3-utils";var Ce=class a extends u{constructor(e){super(e);this.data=e}txType=ci.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await go(r,n,o)}static fromData(e){return new a(e)}};var Te=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:di.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:o}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let r;switch(t.txSubType){case"OpenAndAddLiquidity":r=ae.fromData(t.intentionData);break;case"IncreaseLiquidity":r=fe.fromData(t.intentionData);break;case"DecreaseLiquidity":r=re.fromData(t.intentionData);break;case"RemoveLiquidity":r=ge.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=oe.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=ie.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=ue.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=de.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=pe.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=ce.fromData(t.intentionData);break;case"FarmingHarvest":r=le.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=se.fromData(t.intentionData);break;case"FarmingStake":r=me.fromData(t.intentionData);break;case"FarmingUnstake":r=be.fromData(t.intentionData);break;case"xCETUSConvert":r=Se.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Ce.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=ye.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=he.fromData(t.intentionData);break;case"xCETUSRedeem":r=we.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",r),console.log("helper build account: ",n),console.log("helper build network: ",o),r.build({suiClient:e,account:n,network:o})}};import{TransactionType as Ii}from"@msafe/sui3-utils";import{TransactionType as gt}from"@msafe/sui3-utils";import{bcs as wo}from"@mysten/sui.js/bcs";import{normalizeStructTag as ui,normalizeSuiAddress as Bt}from"@mysten/sui.js/utils";var I={packageId:"0xa0eba10b173538c8fecca1dff298e488402cc9ff374f8a12ca7758eebe830b66",farmPackageId:"0x88701243d0445aa38c0a13f02a9af49a58092dfadb93af9754edb41c52f40085",functions:{swapX:"swap_token_x",swapY:"swap_token_y"}};var N="https://fullnode.mainnet.sui.io/";var ke=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isAddLiquiditySingleSidedTransaction())return this.decodeAddLiquiditySingleSided();if(this.isClaimRewardsTransaction())return this.decodeClaimRewards();if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity();if(this.isStakeLiquidityTransaction())return this.decodeStakeLiquidity();if(this.isUnstakeLiquidityTransaction())return this.decodeUnstakeLiquidity();throw new Error("Unknown transaction type")}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::add_liquidity`)}isAddLiquiditySingleSidedTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::add_liquidity`)&&(!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::${I.functions.swapX}`)||!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::${I.functions.swapY}`))}isClaimRewardsTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.packageId}::spot_dex::remove_liquidity`)}isStakeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::stake`)}isUnstakeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${I.farmPackageId}::farm::unstake`)}decodeAddLiquidity(){let t=this.helperLiquidityDex.getInputParam(0).value,e=this.helperLiquidityDex.typeArg(0),n=this.helperLiquidityDex.typeArg(1),o=this.helperLiquidityDex.decodeInputU64String(4),r=this.helperLiquidityDex.decodeInputU64String(3),i=this.helperLiquidityDex.decodeInputU64String(6),s=this.helperLiquidityDex.decodeInputU64String(5),c=this.helperLiquidityDex.getInputParam(2).value,l=this.helperLiquidityDex.getInputParam(1).value;return{txType:gt.Other,type:"AddLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,amountX:o,amountY:r,minAddAmountX:i,minAddAmountY:s,coinX:c,coinY:l}}}decodeAddLiquiditySingleSided(){let t=this.helperLiquidityDex.getInputParam(0).value,e=this.helperLiquidityDex.typeArg(0),n=this.helperLiquidityDex.typeArg(1),o=this.helperSwapDex.moveCall.target===`${I.packageId}::spot_dex::${I.functions.swapX}`?e:n,r=this.helperSwapDex.decodeInputU64String(2),i=this.helperSwapDex.getInputParam(1).value;return{txType:gt.Other,type:"AddLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,inputCoinType:o,inputCoinAmount:r,inputCoin:i}}}decodeRemoveLiquidity(){let t=this.helperRemoveLiqDex.getInputParam(0).value,e=this.helperRemoveLiqDex.typeArg(0),n=this.helperRemoveLiqDex.typeArg(1),o=this.helperRemoveLiqDex.decodeInputU64String(2),r=this.helperRemoveLiqDex.getInputParam(1).value;return{txType:gt.Other,type:"RemoveLiquidity",intentionData:{objectId:t,tokenXType:e,tokenYType:n,amount:o,kriyaLpToken:r}}}decodeClaimRewards(){let t=this.helperFarmClaim.getInputParam(1).value,e=this.helperFarmClaim.getInputParam(2).value,n=this.helperFarmClaim.typeArg(0),o=this.helperFarmClaim.typeArg(1);return{txType:gt.Other,type:"ClaimRewards",intentionData:{objectId:t,tokenXType:n,tokenYType:o,positionObjectId:e}}}decodeStakeLiquidity(){let t=this.helperFarmStake.getInputParam(1).value,e=this.helperFarmStake.typeArg(0),n=this.helperFarmStake.typeArg(1),o=this.helperFarmStake.getInputParam(2).value,r=this.helperFarmStake.decodeInputU64String(3);return{txType:gt.Other,type:"StakeLiquidity",intentionData:{lpObject:o,lockTime:r,objectId:t,tokenXType:e,tokenYType:n}}}decodeUnstakeLiquidity(){let t=this.helperFarmUnstake.getInputParam(1).value,e=this.helperFarmUnstake.getInputParam(2).value,n=this.helperFarmUnstake.typeArg(0),o=this.helperFarmUnstake.typeArg(1);return{txType:gt.Other,type:"UnstakeLiquidity",intentionData:{objectId:t,tokenXType:n,tokenYType:o,positionObjectId:e}}}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}get helperRemoveLiqDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.packageId}::spot_dex::remove_liquidity`);return new J(t,this.txb)}get helperLiquidityDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.packageId}::spot_dex::add_liquidity`);return new J(t,this.txb)}get helperSwapDex(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&(e.target===`${I.packageId}::spot_dex::${I.functions.swapX}`||e.target===`${I.packageId}::spot_dex::${I.functions.swapY}`));return new J(t,this.txb)}get helperFarmClaim(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::claim`);return new J(t,this.txb)}get helperFarmStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::stake`);return new J(t,this.txb)}get helperFarmUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${I.farmPackageId}::farm::unstake`);return new J(t,this.txb)}},J=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)}decodeInputU64String(t){return this.decodePureArg(t,"u64")}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return Bt(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 wo.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 Bt(t.value.Object.ImmOrOwned.objectId)}return Bt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Bt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Bt(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 wo.de(e,new Uint8Array(n))}typeArg(t){return ui(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as pi}from"@mysten/sui.js/transactions";import{KriyaSDK as mi}from"kriya-dex-sdk";var Ie=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new mi.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,amountX:d,amountY:p,minAddAmountX:m,minAddAmountY:b,coinX:f,coinY:h}=this.data,w=new pi,R=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable;return i.addLiquidity({objectId:s,tokenXType:c,tokenYType:l,isStable:R},BigInt(d),BigInt(p),BigInt(m),BigInt(b),f,h,w,r),w}static fromData(e){return new a(e)}};import{TransactionBlock as bi}from"@mysten/sui.js/transactions";import{KriyaSDK as fi}from"kriya-dex-sdk";var xe=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new fi.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,inputCoinType:d,inputCoinAmount:p,inputCoin:m}=this.data,b=new bi,h=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable;return i.addLiquiditySingleSided({objectId:s,tokenXType:c,tokenYType:l,isStable:h},d,BigInt(p),m,1,b,r),b}static fromData(e){return new a(e)}};import{TransactionBlock as gi}from"@mysten/sui.js/transactions";import{KriyaSDK as hi}from"kriya-dex-sdk";var ve=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new hi.StakingFarm(N,i),{objectId:c,tokenXType:l,tokenYType:d,positionObjectId:p}=this.data,m={objectId:c,tokenXType:l,tokenYType:d},b=new gi;return s.claimTx(b,m,p,r),b}static fromData(e){return new a(e)}};import{TransactionBlock as yi}from"@mysten/sui.js/transactions";import{KriyaSDK as Si}from"kriya-dex-sdk";var Ae=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=new Si.Dex(N),{objectId:s,tokenXType:c,tokenYType:l,amount:d,kriyaLpToken:p}=this.data,m=new yi,f=(await n.getObject({id:s,options:{showContent:!0}})).data.content?.fields.is_stable,h={objectId:s,tokenXType:c,tokenYType:l,isStable:f};return i.removeLiquidity(h,BigInt(d),p,m,r),m}static fromData(e){return new a(e)}};import{TransactionBlock as wi}from"@mysten/sui.js/transactions";import{KriyaSDK as Ci}from"kriya-dex-sdk";var Oe=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new Ci.StakingFarm(N,i),{lpObject:c,lockTime:l,objectId:d,tokenXType:p,tokenYType:m}=this.data,b={objectId:d,tokenXType:p,tokenYType:m},f=new wi;return s.stakeTx(f,c,Number(l),b,r),f}static fromData(e){return new a(e)}};import{TransactionBlock as Ti}from"@mysten/sui.js/transactions";import{KriyaSDK as ki}from"kriya-dex-sdk";var De=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,r=o.address,i=e.network==="sui:mainnet",s=new ki.StakingFarm(N,i),{objectId:c,tokenXType:l,tokenYType:d,positionObjectId:p}=this.data,m={objectId:c,tokenXType:l,tokenYType:d},b=new Ti;return s.withdrawTx(b,m,p,r),b}static fromData(e){return new a(e)}};var Pe=class{application="kriya";async deserialize(t){let{transactionBlock:e}=t,o=new ke(e).decode();return{txType:Ii.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"AddLiquidity":r=Ie.fromData(t.intentionData);break;case"AddLiquiditySingleSided":r=xe.fromData(t.intentionData);break;case"RemoveLiquidity":r=Ae.fromData(t.intentionData);break;case"ClaimRewards":r=ve.fromData(t.intentionData);break;case"StakeLiquidity":r=Oe.fromData(t.intentionData);break;case"UnstakeLiquidity":r=De.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as Ts}from"@msafe/sui3-utils";var ya={};Za(ya,{contractId:()=>Ai,default:()=>ji,feeObjId:()=>Pi,roleObjId:()=>Oi,status:()=>vi,transaction:()=>xi,upgradeCapObjId:()=>_i,vaultObjId:()=>Di});var xi="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",vi="success",Ai="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Oi="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Di="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Pi="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_i="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",ji={transaction:xi,status:vi,contractId:Ai,roleObjId:Oi,vaultObjId:Di,feeObjId:Pi,upgradeCapObjId:_i};var Sa={};Za(Sa,{contractId:()=>Ni,default:()=>Fi,feeObjId:()=>Li,roleObjId:()=>Ei,status:()=>Ri,transaction:()=>Bi,upgradeCapObjId:()=>Wi,vaultObjId:()=>Mi});var Bi="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ri="success",Ni="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ei="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Mi="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Li="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Wi="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fi={transaction:Bi,status:Ri,contractId:Ni,roleObjId:Ei,vaultObjId:Mi,feeObjId:Li,upgradeCapObjId:Wi};var qi="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Ui="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",$i="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qi="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Vi="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Gi="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Ki="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Hi="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Co=ya,To=Sa,zi=new Map([["dev",{env:"dev",rpc:{url:qi},backend:{url:Vi},contract:Co}],["stg",{env:"stg",rpc:{url:Ui},backend:{url:Gi},contract:Co}],["prev",{env:"prev",rpc:{url:$i},backend:{url:Ki},contract:To}],["prod",{env:"prod",rpc:{url:Qi},backend:{url:Hi},contract:To}]]);function ko(a,t){let e=zi.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 Ji}from"@mysten/sui.js/client";var S=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:o,context:r}=n;o?super(`[MPay] ${e}: ${o}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var _e=class extends S{constructor(){super(11,"Backend is not specified")}};var je=class extends S{constructor(){super(1,"Wallet not connected")}};import yt,{AxiosError as Xi}from"axios";var ht=class extends S{constructor(t,e){super(10,t,{context:e})}};var Be=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Xi)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 yt.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await yt.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await yt.post(`${this.apiURL}/stream-events`,t),n=a.parseResponseData(e);return n.data.forEach(o=>{let r=o;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await yt.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await yt.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await yt.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 Ji({url:t.rpc.url}),t.backend&&(this._backend=new Be(t.backend.url))}static new(t,e){let n=ko(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new _e;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 je;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as ys,normalizeStructTag as Ss,normalizeSuiAddress as Ko}from"@mysten/sui.js/utils";import{TransactionBlock as We}from"@mysten/sui.js/transactions";import{TransactionBlock as jo}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Bo,normalizeStructTag as es}from"@mysten/sui.js/utils";var wa=50n,Re=10000n,Io=25n,Ca=100000000n;var Q=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Rt=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 o=i=>new a(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield o(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return o(r)}})}moveArg(){return this.result}};import{Buffer as xo}from"buffer";import{normalizeSuiAddress as Yi}from"@mysten/sui.js/utils";var Nt=class extends S{constructor(t,e){super(3,t,{context:e})}};var Ne=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,o]=this.getValue(t,e);if(o!=="address")throw new Nt("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return Yi(xo.from(n).toString("hex"))}getU64(t=0,e=0){let[n,o]=this.getValue(t,e);if(o!=="u64")throw new Nt("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return xo.from(n).readBigInt64LE()}};import{bcs as Ao}from"@mysten/sui.js/bcs";var v=class extends S{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Oo={groupId:"string",name:"string"},Zi=64;function Do(a){return Po(a),Ao.ser(Oo,a).toString("base64")}function Et(a){let t=Ao.de(Oo,a,"base64");return Po(t),t}function Po(a){if(!vo(a.name))throw new v("Invalid metadata: Name contains unknown character");if(!vo(a.groupId))throw new v("Invalid metadata: Group ID contains unknown character");if(a.name.length>Zi)throw new v("Invalid metadata: Name exceed max length 64")}function vo(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as Ee}from"@mysten/sui.js/utils";function Me(a,t){return Ee(a)===Ee(t)}function et(a,t){return Ee(a)===Ee(t)}var Le="txn.gas";import{nanoid as ts}from"nanoid";function _o(){return ts()}var lt=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Do({name:t.name,groupId:_o()}),coinType:es(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 jo,n=this.calculateFeesInternal(t),o=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(o),i=await this.addMergeCoins(e,r[0]),s;o.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let l=t.recipients[c],d=this.amountForRecipient(l,t.numberEpoch),p=this.getStreamFeeLocal(d),[m]=e.splitCoins(i,[e.pure(d+p,"u64")]),[b]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new tt(m),flatFeeCoin:new tt(b),metadata:t.metadata,recipient:l.address,timeStart:t.startTime,cliff:l.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:wa,denominator:Re},claimFeePercent:{numerator:Io,denominator:Re},flatFeePerStream:Ca}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(o=>t.object(o))),n=t.object(e.primaryCoin)):e.primaryCoin===Le?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return Me(n,Bo)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:Bo,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((o,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:o.totalAmount+i,streamFeeAmount:o.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 Ca}getStreamFeeLocal(t){return t*wa/Re}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new jo,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Ne(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as No}from"@mysten/sui.js/transactions";var Ro="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(No.MoveCall({target:n,arguments:e.arguments.map(o=>o instanceof Rt?o.moveArgs(t):o instanceof Q?o.moveArg(t):o instanceof tt?o.moveArg():t.pure(o)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],o=[]){t.add(No.MoveCall({target:e,arguments:n.map(r=>r instanceof Rt?r.moveArgs(t):r instanceof Q?r.moveArg(t):r instanceof tt?r.moveArg():t.pure(r)),typeArguments:o}))}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(Ro)}};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 o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[o,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,r,n],typeArgs:[]})}setClaimFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[o,r,n],typeArgs:[]})}streamingFee(e,n){let o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[o,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 V=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 o=this.feeObject(),r=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:[o,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let o=this.makeObject(n.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let o=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,r,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 Tt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Ct(e,t),this.streamContract=new V(e,t)}feeContract;streamContract;async createStreams(t){let e=lt.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new lt(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let o=new We;return this.streamContract.setAutoClaim(o,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new We;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new We;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new We;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var O=class extends S{constructor(t,e={}){super(0,t,e)}};async function ka(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 Ta=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)}},kt=class{constructor(t){this.requester=t;this.pager=new Ta(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 Fe=class extends S{constructor(e,n,o){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:o}});this.coinType=e;this.requestAmount=n;this.gotAmount=o}};var ns=25;async function Eo(a,t,e,n="0x2::sui::SUI",o=ns){let r=new Ia(a,t,n,o),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new Fe(n,e,i);return s}var Ia=class extends kt{constructor(e,n,o,r){super(new xa(e,n,o,r));this.suiClient=e;this.owner=n;this.coinType=o;this.reqPageSize=r}},xa=class{constructor(t,e,n,o){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=o;if(o<=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 Qe}from"@mysten/sui.js/transactions";import{normalizeStructTag as Lo,parseStructTag as rs}from"@mysten/sui.js/utils";import{DateTime as is}from"luxon";var qe=class extends S{constructor(){super(7,"Connected wallet is not creator")}};var Mt=class extends S{constructor(){super(8,"Connected wallet is not recipient")}};var Lt=class extends S{constructor(t,e){super(6,t,{context:e})}};var Ue=class extends S{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as as,Duration as os}from"luxon";var Mo=(1n<<64n)-1n,$e=1e3;function va(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/$e);return as.fromMillis(e*$e)}function Aa(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/$e);return os.fromMillis(e*$e)}var nt=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new V(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 o=a.parseRawStreamData(e,n);return new a(t,e,o)}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 qe;let t=new Qe;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Mt;let t=new Qe;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Mt;let e=new Qe;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Qe;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 Lo(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 Aa(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return Et(t).groupId}get name(){let{metadata:t}=this.rawData.config;return Et(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return va(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Aa(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:va((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===Mo?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=is.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 Ue(t):new Lt(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new Lt("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=rs(n.type),r=Lo(o[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};import{normalizeStructTag as Oa,SUI_TYPE_ARG as ss}from"@mysten/sui.js/utils";import{Duration as Wo}from"luxon";var Ve=class extends S{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var cs=1e3,Ge=class{constructor(t){this.globals=t;this.coinMetaHelper=new Da(t.suiClient),this.createStreamHelper=new Tt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Ve(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,o=(t.totalAmount-n)/t.steps,i={realTotalAmount:o*t.steps+n,cliffAmount:n,amountPerStep:o};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(Wo.fromMillis(Number(e*t.steps))),o={timeStart:t.timeStart,timeEnd:n,interval:Wo.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(o),o}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),o=await this.getCoinMeta(e);return{...n,coinType:Oa(n.coinType),coinMeta:o}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(o=>this.getCoinMeta(o.coinType)));return e.map((o,r)=>({...o,coinType:Oa(o.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new v("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new v("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<cs)throw new v("Interval shall be at least 1 second","interval",t.interval)}},Da=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Oa(t||ss);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 Fo,normalizeSuiAddress as He}from"@mysten/sui.js/utils";import{DateTime as qo}from"luxon";var It=class extends S{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var ds=25;async function _a(a,t,e){let n=new Wt(t),o=new Ft(a,n,e);return await ka(o)}var Wt=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]}},Ft=class extends kt{constructor(e,n,o){super(new Pa(e,n,o));this.suiClient=e;this.idIter=n;this.options=o}},Pa=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||ds,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=e.filter(r=>o?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Ke=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new It("stream size 0");let n=e.map(r=>r.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 _a(t.suiClient,e);return n.forEach(o=>{if(!o)throw new O("stream group object data undefined")}),a.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let o=await a.parseGroupStreams(t,e,n);return new a(t,o)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],o=!0;return e.forEach(r=>{ls(n,r)||(o=!1)}),o}async refresh(){let t=await _a(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 o=n.map((r,i)=>nt.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(o.map(r=>r.groupId)).size!==1)throw new It("Not same group ID");if(!this.checkStreamGroup(o))throw new It("Not same stream settings");return o}};function ls(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 qt=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await ze.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await ze.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}},ze=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Xe.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await Xe.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}},Xe=class a{constructor(t,e,n,o){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=o;this.current=0;let r=new Wt(n.flat().map(i=>i.streamId));this.objectIter=new Ft(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=fs(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>He(s.recipient)===He(n)),i=Uo(r);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=gs(t.query),n=await t.globals.walletAddress(),o=await t.globals.backend.getOutgoingStreams(n,e),r=Uo(o);return new a(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await ms(this.globals,t[0].streamId,this.objectIter);return this.current++,$o(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await bs(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,ps(e,this.query)?e:this.doNextRequest()}throw new O("Stream group with no stream")}};function Uo(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)=>qo.fromISO(n[0].createDate).toMillis()-qo.fromISO(e[0].createDate).toMillis())}function $o(a,t){if(t===void 0)return!0;let e=us(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 us(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function ps(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{$o(n,t)&&(e=!0)}),e}async function ms(a,t,e){let n=await Qo(e,t);return nt.fromObjectData(a,t,n)}async function bs(a,t,e){let n=[];for(;n.length<t.length;){let o=await Qo(e,t[n.length]);n.push(o)}return Ke.newFromObjectResponse(a,t,n)}async function Qo(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 fs(a){return{status:ja(a?.status),coinType:Vo(a?.coinType),sender:Go(a?.sender)}}function gs(a){return{status:ja(a?.status),coinType:Vo(a?.coinType),recipient:Go(a?.recipient)}}function ja(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=ja(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 v("Unknown stream filtered status")}}function Vo(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>Fo(t)):void 0:Fo(a)}function Go(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>He(t)):void 0:He(a)}var Ba=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Je=class{constructor(t){this.account=t}async address(){return this.account.address}},Ra=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(Me(t.coinType,ys))return{primaryCoin:Le};if(t.amount<=0)throw new v("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 O("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},Ye=class{globals;helper;constructor(t,e){this.globals=St.new(t,e),this.helper=new Ge(this.globals)}connectSingleWallet(t){let e=new Ra(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Ba(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 qt.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return qt.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=>Ss(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(o=>Ko(o))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(o=>Ko(o))}get wallet(){return this.globals.wallet}builder(){return new Tt(this.globals)}};import ws from"sort-keys-recursive";var Ze=class{constructor(t){this.data=t}serialize(){return JSON.stringify(ws(this.data))}};var M=class extends Ze{application="mpay";getClient(t,e){let n=new Ye(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Je(e)),n}};var Ut=class extends M{constructor(e){super(e);this.data=e}txType=Ts.Stream;txSubType="Cancel";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};import{TransactionType as ks}from"@msafe/sui3-utils";var $t=class extends M{constructor(e){super(e);this.data=e}txType=ks.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Is}from"@msafe/sui3-utils";var Qt=class extends M{constructor(e){super(e);this.data=e}txType=Is.Stream;txSubType="Claim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};import{TransactionType as xs}from"@msafe/sui3-utils";var Vt=class extends M{constructor(e){super(e);this.data=e}txType=xs.Stream;txSubType="CreateStream";async build(e){let{network:n,account:o}=e;return this.getClient(n,o).createStream(this.data)}};import{bcs as Ho}from"@mysten/sui.js/bcs";import{normalizeStructTag as vs,normalizeSuiAddress as Gt}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 Gt(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 Ho.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 Gt(t.value.Object.ImmOrOwned.objectId)}return Gt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Gt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Gt(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 Ho.de(e,new Uint8Array(n))}typeArg(t){return vs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var tn=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:o}=Et(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),p=t.decodeInputBool(11),m=t.typeArg(0);return{name:n,groupId:o,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:p,coinType:m}}aggregateGroupStreamInfo(t){if(new Set(t.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new v("Stream group not have common info");let n=t.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.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 V(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ct(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new lt(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 en=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new V(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 tn(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 As}from"@msafe/sui3-utils";var Kt=class extends M{constructor(e){super(e);this.data=e}txType=As.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var nn=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,o=St.new(e==="sui:mainnet"?"prod":"dev"),i=new en(o,n).decode(),s;switch(i.type){case"CreateStream":s=new Vt(i.info);break;case"SetAutoClaim":s=new Kt({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Qt({streamId:i.streamId});break;case"ClaimByProxy":s=new $t({streamId:i.streamId});break;case"Cancel":s=new Ut({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 Vt(e);break;case"Claim":n=new Qt(e);break;case"ClaimByProxy":n=new $t(e);break;case"SetAutoClaim":n=new Kt(e);break;case"Cancel":n=new Ut(e);break;default:throw new Error("not implemented")}return n.build({...t})}};import{TransactionDefaultApplication as js,TransactionSubTypes as Na}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Os}from"@msafe/sui3-utils";var an=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return Os(n,this.data,o.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as Ds}from"@msafe/sui3-utils";var on=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return Ds(n,this.data,o.address)}static fromData(e){return new a(e)}};import{isSameAddress as Ps}from"@msafe/sui3-utils";import{TransactionBlock as _s}from"@mysten/sui.js/transactions";var rn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,o=_s.from(this.data.content);if(!Ps(o.blockData.sender,n.address))throw new Error("Invalid sender address");return o}static fromData(e){return new a(e)}};var sn=class{application;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,o;switch(t.txSubType){case Na.assets.coin.send:o=an.fromData(t.intentionData);break;case Na.assets.object.send:o=on.fromData(t.intentionData);break;case Na.others.plain:o=rn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionType as Fs}from"@msafe/sui3-utils";var zo=!1,Xo={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"}}};async function Ea(){if(!zo)try{let a=await fetch("https://open-api.naviprotocol.io/api/package").then(e=>e.json()),{packageId:t}=a;Xo.ProtocolPackage=t,zo=!0}catch(a){console.error(a.message)}}var g=Xo;import{TransactionType as Ht}from"@msafe/sui3-utils";import{bcs as Jo}from"@mysten/sui.js/bcs";import{normalizeStructTag as Rs,normalizeSuiAddress as zt}from"@mysten/sui.js/utils";var cn=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.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(`${g.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${g.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(g.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===`${g.ProtocolPackage}::incentive_v2::claim_reward`){let n=new dn(e,this.txb),o=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(o),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:o,poolId:i})}}),console.log("decode claims",t),{txType:Ht.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Ht.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:Ht.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:Ht.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:Ht.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(g.ProtocolPackage));return new dn(t,this.txb)}},dn=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 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 Jo.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 Jo.de(e,new Uint8Array(n))}typeArg(t){return Rs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Ns}from"@mysten/sui.js/transactions";function Ma(a,t,e,n){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(g.Incentive),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function Yo(a,t,e){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(g.Incentive),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function Zo(a,t,e){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function La(a,t,e,n){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(g.PriceOracle),a.object(g.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(g.IncentiveV2)],typeArguments:[t.type]}),a}function tr(a,t,e,n,o){return a.moveCall({target:`${g.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(g.IncentiveV2),a.object(e),a.object(g.StorageId),a.pure(t),a.pure(n)],typeArguments:o}),a}var ln=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Ns;return e.forEach(o=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=o;tr(n,r,i,s,c)}),n.setGasBudget(g.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Es}from"@mysten/sui.js/transactions";var un=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,o=new Es;o.setGasBudget(g.gasBudget),console.log("build",this.data);let r=g.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(g.pool).join(", ")}.`);return Zo(o,r,n)}static fromData(e){return new a(e)}};import{TransactionBlock as Ms}from"@mysten/sui.js/transactions";async function pn(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var mn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new Ms;if(s.setGasBudget(g.gasBudget),console.log("build",this.data),r==="sui"){let[p]=s.splitCoins(s.gas,[i]);return Ma(s,g.pool.sui,p,i)}let c=g.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(g.pool).join(", ")}.`);let l=await pn(n,o.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let p=1;for(;p<l.data.length;)s.mergeCoins(d,[l.data[p].coinObjectId]),p++}return Ma(s,c,s.object(d),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Ls}from"@mysten/sui.js/transactions";var bn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new Ls;if(s.setGasBudget(g.gasBudget),console.log("build",this.data),r==="sui"){let[p]=s.splitCoins(s.gas,[i]);return La(s,g.pool.sui,p,i)}let c=g.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(g.pool).join(", ")}.`);let l=await pn(n,o.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let p=1;for(;p<l.data.length;)s.mergeCoins(d,[l.data[p].coinObjectId]),p++}return La(s,c,s.object(d),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Ws}from"@mysten/sui.js/transactions";var fn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,o=new Ws;console.log("build",this.data),o.setGasBudget(g.gasBudget);let r=g.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(g.pool).join(", ")}.`);return Yo(o,r,n)}static fromData(e){return new a(e)}};var gn=class{application="navi";async deserialize(t){await Ea();let{transactionBlock:e}=t,o=new cn(e).decode();return{txType:Fs.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(await Ea(),t.txSubType){case"EntryDeposit":o=mn.fromData(t.intentionData);break;case"EntryBorrow":o=un.fromData(t.intentionData);break;case"EntryRepay":o=bn.fromData(t.intentionData);break;case"EntryWithdraw":o=fn.fromData(t.intentionData);break;case"ClaimReward":o=ln.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionSubTypes as qs,TransactionType as Us}from"@msafe/sui3-utils";import{TransactionBlock as $s}from"@mysten/sui.js/transactions";import{fromHEX as Qs,toHEX as Vs}from"@mysten/sui.js/utils";import sS from"sort-keys-recursive";var Gs="msafe-plain-tx",Ks=qs.others.plain;var hn=class{application;constructor(){this.application=Gs}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,o=await e.build({client:n});return{txType:Us.Other,txSubType:Ks,intentionData:{content:Vs(o)}}}async build(t){let{suiClient:e,account:n}=t,o=$s.from(Qs(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:o,sender:n.address});if(!(r.effects.status.status==="success"))throw new Error(r.effects.status.error);return o}};var yn=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}};import{TransactionType as wc}from"@msafe/sui3-utils";import{TransactionType as D}from"@msafe/sui3-utils";import{bcs as Fa}from"@mysten/sui.js/bcs";import{normalizeStructTag as zs,normalizeSuiAddress as Jt}from"@mysten/sui.js/utils";var at="6601955b8b0024600a917079",Sn="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var vt="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",ot="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",pt=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],wn=["eth","btc","usdc","usdt","sui","apt","sol","cetus","afsui","hasui","vsui","sca"],Xt=["seth","ssui","susdc","susdt","scetus","safsui","shasui","svsui"],er=["sui"],At=["sui","usdc","usdt"];var nr={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 Cn={seth:"sui",ssui:"sui",susdc:"sui",susdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui"},ar={sui:["sui","sca"],usdc:["sui","sca"],usdt:["sui","sca"]},or={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"},Wa={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"};var Tn=class{constructor(t,e){this.txb=t;this._builder=e}_builder;decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();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.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();throw new Error("Unknown transaction type")}get coreId(){return{protocolPkg:this._builder.address.get("core.packages.protocol.id"),market:this._builder.address.get("core.market"),version:this._builder.address.get("core.version"),coinDecimalsRegistry:this._builder.address.get("core.coinDecimalsRegistry"),xOracle:this._builder.address.get("core.oracles.xOracle"),spoolPkg:this._builder.address.get("spool.id"),borrowIncentivePkg:this._builder.address.get("borrowIncentive.id"),veScaPkgId:this._builder.address.get("vesca.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)}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`)}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}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}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}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`)}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation_entry`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${vt}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}decodeMigrateAndClaim(){let t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),e=this.helperClaimBorrowReward[0].decodeSharedObjectId(2),n=this.helperClaimBorrowReward[0].decodeOwnedObjectId(3),o=this._builder.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:D.Other,type:"MigrateAndClaim",intentionData:{veScaKey:t,obligationKey:e,obligationId:n,rewardCoinName:o}}}decodeOpenObligation(){return{txType:D.Other,type:"OpenObligation",intentionData:{}}}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:D.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new L(t,this.txb).getAmountInput().reduce((f,h)=>f+h,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,p,m,b=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let f=0;f<b.length;f++)b[f].condition.length>1&&([m,p]=b[f].condition,l=!0,d=b[f].isOld);return{txType:D.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:p,obligationKey:m,veScaKey:o,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:r,isOld:!1}];for(let p=0;p<d.length;p++)d[p].condition.length>1&&([l,c]=d[p].condition,i=!0,s=d[p].isOld);return{txType:D.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:l,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new L(t,this.txb).getAmountInput().reduce((b,f)=>b+f,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,p,m=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,d]=m[b].condition,c=!0,l=m[b].isOld);return{txType:D.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:d,obligationKey:p,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):(t=this.helperStakeMoreSca.getNestedInputParam(4),console.log(t));let n=new L(t,this.txb).getAmountInput().reduce((b,f)=>b+f,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,p,m=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,d]=m[b].condition,c=!0,l=m[b].isOld);return{txType:D.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:d,obligationKey:p,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}decodeSupplyLending(){let t=this._builder.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:D.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this._builder.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:D.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this._builder.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:D.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this._builder.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:D.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:o,obligationId:n}}}decodeBorrow(){let t=this._builder.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let t=this._builder.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:o,veScaKey:e}}}decodeRepay(){let t=this._builder.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:t}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=this.helperStake.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperStake.typeArg(0),r=this._builder.utils.parseCoinNameFromType(o);return{txType:D.Other,type:"StakeSpool",intentionData:{amount:n,marketCoinName:r,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this._builder.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:o,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this._builder.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new L(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:D.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(r=>{let i=r.decodeOwnedObjectId(1),s=r.decodeInputU64(2);t.push({id:i,coin:s})});let e=this._builder.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=this.helperRedeems.find(r=>r.isHaveNestedInput(2)),o;return n&&(o=new L(n.getNestedInputParam(2),this.txb).getAmountInput().reduce((r,i)=>r+i,0)),{txType:D.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:o,coinName:e,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let r=o.decodeOwnedObjectId(2),i=o.typeArg(0),s=this._builder.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(o=>{let r=o.decodeSharedObjectId(3),i=o.decodeOwnedObjectId(4),s=this._builder.utils.parseCoinNameFromType(o.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(o=>{let r=o.decodeSharedObjectId(2),i=o.decodeOwnedObjectId(3),s=this._builder.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:D.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new T(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 T(e,this.txb))}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new T(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 T(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 T(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 T(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 T(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${vt}::user::unstake`));return new T(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new T(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 T(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${vt}::user::redeem_rewards`)).map(e=>new T(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new T(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new T(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new T(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new T(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new T(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new T(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 T(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 T(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new T(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new T(t,this.txb)}},L=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(T.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 Fa.de(e,new Uint8Array(n))}return t.value}},T=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 Jt(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 Fa.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 Jt(t.value.Object.ImmOrOwned.objectId)}return Jt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Jt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Jt(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 Fa.de(e,new Uint8Array(n))}typeArg(t){return zs(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as x}from"@mysten/sui.js/transactions";import{normalizeSuiAddress as Sc}from"@mysten/sui.js/utils";import Ar from"bignumber.js";var rr={mainnet:{core:{version:"0x07871c4b3c847a0f674510d4978d5cf6f960452795e8ff6f189fd2088a3f6ac7",versionCap:"0x590a4011cb649b3878f3ea14b3a78674642a9548d79b7e091ef679574b158a07",object:"0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf",market:"0xa757975255146dc9686aa823b7838b507f315d704f428cbadad2f4ea061939d9",adminCap:"0x09689d018e71c337d9db6d67cbca06b74ed92196103624028ccc3ecea411777c",coinDecimalsRegistry:"0x200abe9bf19751cc566ae35aa58e2b7e4ff688fc1130f8d8909ea09bc137d668",obligationAccessStore:"0x733e30b7c94d619d78cb8f5bc4bfbb759ced9a531239028caabb2474e5be59c9",coins:{cetus:{id:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",metaData:"0x4c0dce55eff2db5419bbd2d239d1aa22b4a400c01bbb648b058a9883989025da",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"e5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",feedObject:"0x24c0247fb22457a719efac7f670cdc79be321b521460bd6bd2ccfa9f80713b14"}}},apt:{id:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",metaData:"0xc969c5251f372c0f34c32759f1d315cf1ea0ee5e4454b52aea08778eacfdd0a8",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"03ae4db29ed4ae33d323568895aa00337e658e348b37509f5372ae51f0af00d5",feedObject:"0x7c5b7837c44a69b469325463ac0673ac1aa8435ff44ddb4191c9ae380463647f"}}},sol:{id:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",metaData:"0x4d2c39082b4477e3e79dc4562d939147ab90c42fc5f3e4acf03b94383cd69b6e",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d",feedObject:"0x9d0d275efbd37d8a8855f6f2c761fa5983293dd8ce202ee5196626de8fcd4469"}}},btc:{id:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",metaData:"0x5d3c6e60eeff8a05b693b481539e7847dfe33013e7070cdcb387f5c0cac05dfd",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",feedObject:"0x9a62b4863bdeaabdc9500fce769cf7e72d5585eeb28a6d26e4cafadc13f76ab2"}}},eth:{id:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",metaData:"0x8900e4ceede3363bef086d6b50ca89d816d0e90bf6bc46efefe1f8455e08f50f",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"ff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",feedObject:"0x9193fd47f9a0ab99b6e365a464c8a9ae30e6150fc37ed2a89c1586631f6fc4ab"}}},usdc:{id:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",metaData:"0x4fbf84f3029bd0c0b77164b587963be957f853eccf834a67bb9ecba6ec80f189",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"eaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",feedObject:"0x5dec622733a204ca27f5a90d8c2fad453cc6665186fd5dff13a83d0b6c9027ab"}}},usdt:{id:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",metaData:"0xfb0e3eb97dd158a5ae979dddfa24348063843c5b20eb8381dd5fa7c93699e45c",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b",feedObject:"0x985e3db9f93f76ee8bace7c3dd5cc676a096accd5d9e09e9ae0fb6e492b14572"}}},sui:{id:"0x0000000000000000000000000000000000000000000000000000000000000002",metaData:"0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3",treasury:"",oracle:{supra:"",switchboard:"0xbca474133638352ba83ccf7b5c931d50f764b09550e16612c9f70f1e21f3f594",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},afsui:{id:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",metaData:"0x2f9217f533e51334873a39b8026a4aa6919497b47f49d0986a4f1aec66f8a34d",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},hasui:{id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",metaData:"0x2c5f33af93f6511df699aaaa5822d823aac6ed99d4a0de2a4a50b3afa0172e24",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},vsui:{id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",metaData:"0xabd84a23467b33854ab25cf862006fd97479f8f6f53e50fe732c43a274d939bd",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",feedObject:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"}}},sca:{id:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6",metaData:"0x5d26a1e9a55c88147ac870bfa31b729d7f49f8804b8b3adfdf3582d301cca844",treasury:"",oracle:{supra:"",switchboard:"",pyth:{feed:"7e17f0ac105abe9214deb9944c30264f5986bf292869c6bd8e8da3ccd92d79bc",feedObject:"0xf6de1d3279a269a597d813cbaca59aa906543ab9a8c64e84a4722f1a20863985"}}}},oracles:{xOracle:"0x93d5bf0936b71eb27255941e532fac33b5a5c7759e377b4923af0a1359ad494f",xOracleCap:"0x1edeae568fde99e090dbdec4bcdbd33a15f53a1ce1f87aeef1a560dedf4b4a90",supra:{registry:"",registryCap:"",holder:""},switchboard:{registry:"",registryCap:""},pyth:{registry:"0xedc293f9413a5a7a5d53bdba1fd889d0a4030894469228f0acdae4aa3c55a213",registryCap:"0xbcb07141eb1f7e01fbda4130ecf5f5adaeabb77f5d9c32158b7532bcd2197acd",state:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",wormhole:"0x5306f64e312b581766351c07af79c72fcb1cd25147157fdc2f8ad76de9a3fb6a",wormholeState:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c"}},packages:{coinDecimalsRegistry:{id:"0xca5a5a62f01c79a104bf4d31669e29daa387f325c241de4edbe30986a9bc8b0d",upgradeCap:"0x34e76a945d29f195bc53ca704fa70877d1cf3a5d7bbfdda1b13e633fff13c0f6"},math:{id:"0xad013d5fde39e15eabda32b3dbdafd67dac32b798ce63237c27a8f73339b9b6f",upgradeCap:"0x3a329598231de02e6135c62284b66005b41cad1d9ab7ca2dc79c08293aba2ec6"},whitelist:{id:"0x1318fdc90319ec9c24df1456d960a447521b0a658316155895014a6e39b5482f",upgradeCap:"0xf5a22aea23db664f7b69855b6a546747f17c1ec4230319cfc17225e462b05761"},x:{id:"0x779b5c547976899f5474f3a5bc0db36ddf4697ad7e5a901db0415c2281d28162",upgradeCap:"0x3f203f6fff6a69d151e4f1cd931f22b68c489ef2759765662fc7baf673943c9e"},protocol:{id:"0x38fe42a5a69f7eb3635404389e8003be9457b1a5c873f133184648c7e9bd47b7",upgradeCap:"0x38527d154618d1fd5a644b90717fe07cf0e9f26b46b63e9568e611a3f86d5c1a"},protocolWhitelist:{id:"0x4c262d9343dac53ecb28f482a2a3f62c73d0ebac5b5f03d57383d56ff219acdf",upgradeCap:"0x4a5e88a75039b00988f633f811f58117f31b8627a46bf822aa114d9010049449"},query:{id:"0xb8d603a39114a5efef3dd0bf84df0bed1be1fbd39b78b7dd6e8a61ccc5e6006f",upgradeCap:"0x0d535c35f608b9b01b7ccce11acf43b1dd80c1b72bf8b541744a6e28e8d2745f"},supra:{id:"",upgradeCap:""},pyth:{id:"0x910f30cbc7f601f75a5141a01265cd47c62d468707c5e1aecb32a18f448cb25a",upgradeCap:"0xdf0ffbae1ea5bb25fbca5efba433dcf00c7cced65679af2f04728901275c6157"},switchboard:{id:"",upgradeCap:""},xOracle:{id:"0x1478a432123e4b3d61878b629f2c692969fdb375644f1251cd278a4b1e7d7cd6",upgradeCap:"0x0f928a6b2e26b73330fecaf9b44acfc9800a4a9794d6415c2a3153bc70e3c1f0"},testCoin:{id:"",upgradeCap:""}}},spool:{id:"0xec1ac7f4d01c5bf178ff4e62e523e7df7721453d81d4904a42a0ffc2686c843d",adminCap:"0xdd8a047cbbf802bfcde5288b8ef1910965d789cc614da11d39af05fca0bd020a",object:"0xe87f1b2d498106a2c61421cec75b7b5c5e348512b0dc263949a0e7a3c256571a",pools:{seth:{id:"0xeec40beccb07c575bebd842eeaabb835f77cd3dab73add433477e57f583a6787",rewardPoolId:"0x957de68a18d87817de8309b30c1ec269a4d87ae513abbeed86b5619cb9ce1077"},ssui:{id:"0x4f0ba970d3c11db05c8f40c64a15b6a33322db3702d634ced6536960ab6f3ee4",rewardPoolId:"0x162250ef72393a4ad3d46294c4e1bdfcb03f04c869d390e7efbfc995353a7ee9"},susdc:{id:"0x4ace6648ddc64e646ba47a957c562c32c9599b3bba8f5ac1aadb2ae23a2f8ca0",rewardPoolId:"0xf4268cc9b9413b9bfe09e8966b8de650494c9e5784bf0930759cfef4904daff8"},susdt:{id:"0xcb328f7ffa7f9342ed85af3fdb2f22919e1a06dfb2f713c04c73543870d7548f",rewardPoolId:"0x2c9f934d67a5baa586ceec2cc24163a2f049a6af3d5ba36b84d8ac40f25c4080"},scetus:{id:"0xac1bb13bf4472a637c18c2415fb0e3c1227ea2bcf35242e50563c98215bd298e",rewardPoolId:"0x6835c1224126a45086fc6406adc249e3f30df18d779ca4f4e570e38716a17f3f"},safsui:{id:"0xeedf438abcaa6ce4d9625ffca110920592d5867e4c5637d84ad9f466c4feb800",rewardPoolId:"0x89255a2f86ed7fbfef35ab8b7be48cc7667015975be2685dd9a55a9a64baf76e"},shasui:{id:"0xa6148bc1b623e936d39a952ceb5bea79e8b37228a8f595067bf1852efd3c34aa",rewardPoolId:"0x6f3563644d3e2ef13176dbf9d865bd93479df60ccbe07b7e66db57f6309f5a66"},svsui:{id:"0x69ce8e537e750a95381e6040794afa5ab1758353a1a2e1de7760391b01f91670",rewardPoolId:"0xbca914adce058ad0902c7f3cfcd698392a475f00dcfdc3f76001d0370b98777a"}},version:"",versionCap:""},borrowIncentive:{id:"0x874f1d43d81e2256e120bab2485938fe07ba0cc21d87129a99a1db11cacb382d",adminCap:"0xc486afa253646f4d381e81d7f1df8aa4723b845a6bb356f69bad635ffefffe2c",object:"0x002875153e09f8145ab63527bc85c00f2bd102e12f9573c47f8cdf1a1cb62934",query:"0x529edc54a3dce2207703ceebbccb0ac14133f7825c1f528775ba0d85a4063489",incentivePools:"0x6547e143d406b5ccd5f46aae482497de279cc1a68c406f701df70a05f9212ab4",incentiveAccounts:"0xc4701fdbc1c92f9a636d334d66012b3027659e9fb8aff27279a82edfb6b77d02",config:"0xdf5d04b4691cc67e82fd4db8394d89ff44823a9de29716c924f74bb4f11cc1f7",version:"",versionCap:""},vesca:{id:"0xcfe2d87aa5712b67cad2732edb6a2201bfdf592377e5c0968b7cb02099bd8e21",adminCap:"0x4d105b16467acca81d18c132cdd1a3cee159920a86c1ef4bdbf2e8d7878500c5",tableId:"0x0a0b7f749baeb61e3dfee2b42245e32d0e6b484063f0a536b33e771d573d7246",table:"0xd3a4632b1080f7d96e1c2487d4dabf2c1196916937c505a69954ac9f393be8d0",treasury:"0xafa4b6231e49c15a22d641ce33fda761baaf650fa21899dfa2eb1716146e7306",config:"0x7cbcb0a342179577a117dfdff974cf1ab765d3b571067bf22ddf5f9e3a667922"}}};var G=class{_auth;_id;_network;_currentAddresses;_addressesMap;constructor(t){let{id:e,auth:n,network:o}=t;n&&(this._auth=n),this._id=e,this._network=o||"mainnet",this._addressesMap=new Map}getId(){return this._id||void 0}get(t){if(this._currentAddresses)return t.split(".").reduce((n,o)=>typeof n=="object"?n[o]:n,this._currentAddresses)||void 0}set(t,e){if(this._currentAddresses){let n=t.split(".");n.reduce((o,r,i)=>{if(i===n.length-1){let s=o;s[r]=e}return o[r]},this._currentAddresses)}return this._currentAddresses}switchCurrentAddresses(t){return this._addressesMap.has(t)&&(this._currentAddresses=this._addressesMap.get(t),this._network=t),this._currentAddresses}getAddresses(t){return t?this._addressesMap.get(t):this._currentAddresses??this._addressesMap.get(this._network)}setAddresses(t,e){let n=e||this._network;n===this._network&&(this._currentAddresses=t),this._addressesMap.set(n,t)}getAllAddresses(){return Object.fromEntries(this._addressesMap)}read(){return Object.entries(rr).forEach(([t,e])=>{["localnet","devnet","testnet","mainnet"].includes(t)&&(t===this._network&&(this._currentAddresses=e),this._addressesMap.set(t,e))}),this.getAllAddresses()}};import{TransactionBlock as ec}from"@mysten/sui.js/transactions";import{normalizeSuiAddress as nc}from"@mysten/sui.js/utils";import{SUI_TYPE_ARG as Ys,normalizeStructTag as fr}from"@mysten/sui.js/utils";var j=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},cr=(a,t,e,n)=>{let o=!n,r=!o&&n*1e3<=new Date().getTime();if(o||r)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 ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if(Ot(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)`)}},dr=(a,t,e)=>{if(Ot(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)`)},lr=(a,t)=>{if(Ot(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")},ur=(a,t,e)=>{if(Ot(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)`)},Ot=a=>{if(a===void 0)throw new Error("veSca not found")};import{normalizeStructTag as pr,parseStructTag as Xs}from"@mysten/sui.js/utils";import _S from"bignumber.js";var Js=a=>({pointType:pr(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),mr=a=>({poolType:pr(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=Js(e),o=Xs(n.pointType).name.toLowerCase();return t[o]=n,t},{})});var qa=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...pt,...wn,...er])].includes(t)},Ua=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}};var br=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 it=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this._address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.isTestnet=t.networkType?t.networkType==="testnet":!1,this.client=t.client}init(t=!1,e){t||!this._address.getAddresses()||!e?.getAddresses()?this._address.read():this._address=e}parseSymbol(t){if(qa(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Ua(e)}return Ua(t)}parseCoinType(t){let e=qa(t)?this.parseCoinName(t):t,n=this._address.get(`core.coins.${e}.id`)||or[t]||void 0;if(!n)throw Error(`Coin ${t} is not supported`);if(t==="sui")return fr(`${n}::sui::SUI`);let o=[this._address.get("core.coins.usdc.id")??B.usdc,this._address.get("core.coins.usdt.id")??B.usdt,this._address.get("core.coins.eth.id")??B.eth,this._address.get("core.coins.btc.id")??B.btc,this._address.get("core.coins.sol.id")??B.sol,this._address.get("core.coins.apt.id")??B.apt],r=[this._address.get("core.coins.vsui.id")??Wa.vsui];return o.includes(n)?`${n}::coin::COIN`:r.includes(n)?`${n}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||Sn,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=fr(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,o=t.match(n),r=t.includes("reserve::MarketCoin");e=o?.[1]||t;let i={[`${this._address.get("core.coins.usdc.id")??B.usdc}::coin::COIN`]:"usdc",[`${this._address.get("core.coins.usdt.id")??B.usdt}::coin::COIN`]:"usdt",[`${this._address.get("core.coins.eth.id")??B.eth}::coin::COIN`]:"eth",[`${this._address.get("core.coins.btc.id")??B.btc}::coin::COIN`]:"btc",[`${this._address.get("core.coins.sol.id")??B.sol}::coin::COIN`]:"sol",[`${this._address.get("core.coins.apt.id")??B.apt}::coin::COIN`]:"apt"},s={[`${this._address.get("core.coins.vsui.id")??Wa.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return r?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>Cn[t];getBorrowIncentiveRewardCoinName=t=>ar[t];getCoinDecimal(t){return nr[t]}getCoinWrappedType(t){return t==="usdc"||t==="usdt"||t==="eth"||t==="btc"||t==="apt"||t==="sol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}async selectCoinIds(t,e=Ys,n){let o=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let l=await this.client.getCoins({owner:o,coinType:e,cursor:c});l.data.sort((d,p)=>parseInt(p.balance,10)-parseInt(d.balance,10));for(let d=0;d<l.data.length&&(r.push({objectId:l.data[d].coinObjectId,digest:l.data[d].digest,version:l.data[d].version}),i+=parseInt(l.data[d].balance,10),!(i>=t));d++);c=l.nextCursor,s=l.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r.map(l=>l.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 o=e.map(s=>t.object(s)),r=o[0];o.length>1&&t.mergeCoins(r,o.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),o=e?Math.max(e-n,0):0,r=0;if(o===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+o:o,126144e3);r=n+i}return br(r)}};import{TransactionBlock as Zs}from"@mysten/sui.js/transactions";import In from"bignumber.js";var Dt=async(a,t)=>{let e=t,n=a.address.get("core.object")||Sn,o=[],r=!1,i=null;do{let d=await a.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});o.push(...d.data),d.hasNextPage&&d.nextCursor?(r=!0,i=d.nextCursor):r=!1}while(r);let s=o.map(d=>d?.data?.objectId).filter(d=>d!==void 0),c=await a.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),l=[];for(let d=0;d<c.length;d++){let p=c[d].data.objectId,{content:m}=c[d].data;if(m&&"fields"in m){let b=m.fields,f=String(b.ownership.fields.of),h=await $a(a,f);l.push({id:f,keyId:p,locked:h})}}return l},$a=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},gr=async(a,t,e)=>{let n=e||[...pt],o=t,r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(p=>({StructType:`0x2::coin::Coin<${a.utils.parseCoinType(p)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let p=d.type;if(d.content&&"fields"in d.content){let m=d.content.fields,b=a.utils.parseCoinNameFromType(p);b&&(c[b]=In(c[b]??0).plus(m.balance).toNumber())}}),c},hr=async(a,t,e)=>{let n=e,o=a.utils.parseCoinType(t),r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let p=d.content.fields;c=In(c).plus(p.balance).toNumber()}}),c},yr=async(a,t,e)=>{let n=e||[...pt].map(d=>a.utils.parseMarketCoinName(d)),o=t,r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(p=>({StructType:`0x2::coin::Coin<${a.utils.parseMarketCoinType(p)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let p=d.type;if(d.content&&"fields"in d.content){let m=d.content.fields,b=a.utils.parseCoinNameFromType(p);b&&(c[b]=In(c[b]??0).plus(m.balance).toNumber())}}),c},Sr=async(a,t,e)=>{let n=e,o=a.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let p=d.content.fields;c=In(c).plus(p.balance).toNumber()}}),c},wr=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,o=new Zs;return o.moveCall({target:n,arguments:[o.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:o,sender:a.walletAddress})).events[0].parsedJson};import{normalizeStructTag as C}from"@mysten/sui.js/utils";var Yt=async(a,t)=>{let e=t,n=a.address.get("spool.object"),o=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let m=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},options:{showContent:!0,showType:!0},cursor:s});r.push(...m.data),m.hasNextPage&&m.nextCursor?(i=!0,s=m.nextCursor):i=!1}while(i);let c={seth:[],ssui:[],susdc:[],susdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},l=Object.keys(c).reduce((m,b)=>{let f=a.utils.parseCoinName(b),h=a.utils.parseMarketCoinType(f),w={...m},P=`${n}::spool_account::SpoolAccount<${h}>`;return w[b]=P,w},{}),d=r.map(m=>m?.data?.objectId).filter(m=>m!==void 0);return(await a.client.multiGetObjects({ids:d,options:{showContent:!0,showType:!0}})).forEach(m=>{let b=m.data.objectId,f=m.data.type;if(m.data.content&&"fields"in m.data.content){let h=m.data.content.fields,w=String(h.spool_id),P=String(h.stake_type.fields.name),R=Number(h.stakes),H=Number(h.index),z=Number(h.points),X=Number(h.total_points);C(f)===l.seth?c.seth.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.ssui?c.ssui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.susdc?c.susdc.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.susdt?c.susdt.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.scetus?c.scetus.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.safsui?c.safsui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.shasui?c.shasui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X}):C(f)===l.svsui&&c.svsui.push({id:b,type:C(f),stakePoolId:w,stakeType:C(P),staked:R,index:H,points:z,totalPoints:X})}}),c},Qa=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.id`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=Number(c.max_distributed_point),d=Number(c.distributed_point),p=Number(c.distributed_point_per_period),m=Number(c.point_distribution_time),b=Number(c.max_stakes),f=String(c.stake_type.fields.name),h=Number(c.stakes),w=Number(c.index),P=Number(c.created_at),R=Number(c.last_update);n={id:i,type:C(s),maxPoint:l,distributedPoint:d,pointPerPeriod:p,period:m,maxStake:b,stakeType:C(f),totalStaked:h,index:w,createdAt:P,lastUpdate:R}}}return n},Va=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.rewardPoolId`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=String(c.spool_id),d=Number(c.exchange_rate_numerator),p=Number(c.exchange_rate_denominator),m=Number(c.rewards),b=Number(c.claimed_rewards);n={id:i,type:C(s),stakePoolId:l,ratioNumerator:d,ratioDenominator:p,rewards:m,claimedRewards:b}}}return n};import{TransactionBlock as tc}from"@mysten/sui.js/transactions";import{normalizeStructTag as ZS}from"@mysten/sui.js/utils";import e0 from"bignumber.js";var Cr=async(a,t,e,n)=>{let o=n||[...At],r=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new tc;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let d=(await a.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,p={};return d.pool_records.forEach(m=>{let b=mr(m),{poolType:f}=b,h=a.utils.parseCoinNameFromType(f);o.length>=1&&o.includes(h)&&(p[h]=b)},{}),p};var Tr=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 o=n.data;if(o.content&&"fields"in o.content){let r=o.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),l=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(l?-1:1)}}return 0};import Ga from"bignumber.js";var kr=async(a,t)=>{let e=t,o=`${a.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);return r.map(l=>l.data).filter(l=>!!l)},Ir=async(a,t)=>{let n=(await kr(a,t)).map(r=>r.objectId),o=[];for(let r=0;r<n.length;r++){let i=await Ka(a,n[r]);i&&o.push(i)}return o},Ka=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),o=t||(await kr(a,e))[0].objectId,r,s=(await a.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:o}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:o,lockedScaAmount:Ga(c.locked_sca_amount).toNumber(),lockedScaCoin:Ga(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:Ga(c.unlock_at).toNumber()}}return r};var Pt=class{params;address;client;utils;walletAddress;constructor(t,e){this.params=t,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.client=t.client,this.utils=e?.utils??new it(this.params,{address:this.address}),this.walletAddress=t.walletAddress}init(t=!1,e){t||!this.address.getAddresses()||!e?.getAddresses()?this.address.read():this.address=e}async getObligations(t){return Dt(this,t)}async getCoinAmounts(t,e){return gr(this,t,e)}async getCoinAmount(t,e){return hr(this,t,e)}async getMarketCoinAmounts(t,e){return yr(this,t,e)}async getMarketCoinAmount(t,e){return Sr(this,t,e)}async getPriceFromPyth(t){return Tr(this,t)}async getAllStakeAccounts(t){return Yt(this,t)}async getStakeAccounts(t,e){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t){let e=t??[...Xt],n={};for(let o=0;o<e.length;o++){let r=e[o],i=await Qa(this,r);i&&(n[r]=i)}return n}async getStakePool(t){return Qa(this,t)}async getStakeRewardPools(t){let e=t??[...Xt],n={};for(let o=0;o<e.length;o++){let r=await Va(this,e[o]);r&&(n[e[o]]=r)}return n}async getStakeRewardPool(t){return Va(this,t)}async getBorrowIncentiveAccounts(t,e,n){return Cr(this,t,e||this.walletAddress,n)}async getObligationCoinNames(t){let e=await wr(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),o=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...o])].map(s=>this.utils.parseCoinNameFromType(s))}};var _t=class{params;isTestnet;address;query;utils;client;walletAddress;constructor(t,e){this.params=t,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.query=e?.query??new Pt(t,{address:this.address}),this.utils=e?.utils??new it(this.params,{address:this.address,query:this.query}),this.client=t.client,this.walletAddress=nc(t.walletAddress),this.isTestnet=t.networkType?t.networkType==="testnet":!1}async init(t=!1,e){t||!this.address.getAddresses()||!e?.getAddresses()?this.address.read():this.address=e,this.query.init(t,this.address),this.utils.init(t,this.address)}createTxBlock(t){return new ec(t)}async selectCoin(t,e,n,o){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,o),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,o){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoinIds(n,r,o),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}};import{SUI_CLOCK_OBJECT_ID as jt,SUI_TYPE_ARG as ac}from"@mysten/sui.js/utils";var mt=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await Ka(t.query,n);return i||void 0}let o=j(e),r=await Ir(t.query,o);if(r.length!==0)return r[0]},oc=async(a,t)=>{let e=a.address.get("borrowIncentive.object"),n=a.address.get("borrowIncentive.incentivePools"),o=a.address.get("vesca.id"),{client:r}=a,i=await r.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,l=`${e}::typed_id::TypedID<${o}::ve_sca::VeScaKey>`,d=await r.getDynamicFieldObject({parentId:c,name:{type:l,value:t}});return d.data?.content?.dataType!=="moveObject"?!1:d.data.content.fields.value.fields.id},Ha=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&n&&o&&typeof n=="string"){let s=await $a(t.query,n);return{obligationId:n,obligationKey:o,obligationLocked:s}}let r=j(e),i=await Dt(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId,obligationLocked:i[0].locked}},rc=({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"},o={table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(jt)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(o.config),t.object(o.treasury),t.object(o.table),t.object(s),t.object(jt)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(jt)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(jt)],typeArguments:[ac]})},claimBorrowIncentive:(r,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(r),t.object(jt)],typeArguments:[c]})},oldClaimBorrowIncentive(r,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(r),t.object(jt)],typeArguments:[c]})}}},W=({builder:a,txBlock:t})=>{let e=rc({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Ha(a,t,n,o),c=!!t.blockData.transactions.find(l=>l.kind==="MoveCall"&&l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`);(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Ha(a,t,n,o);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,o,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await Ha(a,t,n,o),l=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${vt}::user::unstake`||d.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||l){let d=await mt(a,t,r);if(d){let p=await oc(a,d.keyId);!p||p===i?e.stakeObligationWithVesca(i,s,d.keyId):e.stakeObligation(i,s)}else e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,o,r)=>e.claimBorrowIncentive(o,r,n)}};import{SUI_CLOCK_OBJECT_ID as st}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as An}from"@mysten/sui.js/utils";import ic from"axios";var xr={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};import{bcs as za}from"@mysten/sui.js/bcs";import{SUI_CLOCK_OBJECT_ID as xn}from"@mysten/sui.js/utils";var Xa=16*1024,vn=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(),o=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(za.ser("vector<u8>",Array.from(r),{maxSize:Xa}).toBytes()),e.object(xn)]});o.push(i)}),o}async updatePriceFeeds(t,e,n){let o=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${o}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(za.ser("vector<u8>",Array.from(e[0]),{maxSize:Xa}).toBytes()),s[0],t.object(xn)]});let c=[],l=await this.getBaseUpdateFee(),d=t.splitCoins(t.gas,n.map(()=>t.pure(l))),p=0;for(let m=0;m<n.length;m++){let b=await this.getPriceFeedObjectId(n[m]);if(!b)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(b),[r]=t.moveCall({target:`${o}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(b),d[p],t.object(xn)]}),p++}return t.moveCall({target:`${o}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${o}::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 o=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([o],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(za.ser("vector<u8>",Array.from(e[0]),{maxSize:Xa}).toBytes()),r[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:o}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${o}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,o=t.readUint16BE(n),r=n+2;return t.subarray(r,r+o)}};var sc=async(a,t)=>(await ic.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(o=>Buffer.from(o,"base64")),On=async(a,t,e)=>{let n=e??[...new Set([...pt,...wn])],o=a.isTestnet?["pyth"]:["pyth"];if(o.includes("pyth")){let i=new vn(a.client,a.address.get("core.oracles.pyth.state"),a.address.get("core.oracles.pyth.wormholeState")),s=n.map(l=>a.address.get(`core.coins.${l}.oracle.pyth.feed`)),c=a.params.pythEndpoints??xr[a.isTestnet?"testnet":"mainnet"];try{let l=await sc(c[0],s);await i.updatePriceFeeds(t,l,s)}catch(l){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${l}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await cc(a,t,r[i],o)},cc=async(a,t,e,n)=>{let o=a.utils.parseCoinType(e);dc(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"),o)},dc=(a,t,e,n,o,r,i,s,c,l,d,p,m,b,f)=>{let h=lc(a,e,n,f);return t.includes("pyth")&&bc(a,o,h,i,s,r,f),t.includes("switchboard")&&mc(a,c,h,d,l,f),t.includes("supra")&&pc(a,p,h,b,m,f),uc(a,e,n,h,f),a},lc=(a,t,e,n)=>{let o=typeof e=="string"?a.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return a.moveCall({target:r,arguments:[o],typeArguments:i})},uc=(a,t,e,n,o)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[o],s=typeof e=="string"?a.object(e):e;return a.moveCall({target:r,arguments:[s,n,a.object(An)],typeArguments:i}),a},pc=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(An)],typeArguments:[r]})},mc=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(An)],typeArguments:[r]})},bc=(a,t,e,n,o,r,i)=>{let s=typeof e=="string"?a.object(e):e,c=typeof n=="string"?a.object(n):n,l=typeof o=="string"?a.object(o):o,d=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,l,d,a.object(An)],typeArguments:[i]})};var Dn=async(...a)=>{let[t,e,n,o]=a;if(a.length===3&&n)return{obligationId:n};if(a.length===4&&n&&o)return{obligationId:n,obligationKey:o};let r=j(t),i=await Dt(e.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},fc=({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")};return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.pure(e.version)]}),returnObligation:(n,o)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(n),t.object(o)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(n),t.object(e.market),typeof o!="string"?o:t.pure(o)],typeArguments:[i]})},takeCollateral:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},deposit:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},depositEntry:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},withdraw:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},withdrawEntry:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof n!="string"?n:t.pure(n),t.object(st)],typeArguments:[r]})},borrow:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},borrowEntry:(n,o,r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(n),t.object(o),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(r),t.object(e.xOracle),t.object(st)],typeArguments:[s]})},repay:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(n),t.object(e.market),typeof o!="string"?o:t.pure(o),t.object(st)],typeArguments:[i]})},borrowFlashLoan:(n,o)=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(n)],typeArguments:[r]})},repayFlashLoan:(n,o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(n),t.object(o)],typeArguments:[i]})}}},q=({builder:a,txBlock:t})=>{let e=fc({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(n,o,r)=>{let i=j(t),{obligationId:s}=await Dn(t,a,r);if(o==="sui"){let[c]=t.splitCoins(t.gas,[n]);e.addCollateral(s,c,o)}else{let{leftCoin:c,takeCoin:l}=await a.selectCoin(t,o,n,i);e.addCollateral(s,l,o),t.transferObjects([c],i)}},takeCollateralQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r,i),c=await a.query.getObligationCoinNames(s.obligationId);return await On(a,t,c),e.takeCollateral(s.obligationId,s.obligationKey,n,o)},depositQuick:async(n,o,r)=>{if(o==="sui"){let[c]=t.splitCoins(t.gas,[n]);return e.deposit(c,o)}let{leftCoin:i,takeCoin:s}=await a.selectCoin(t,o,n,r);return t.transferObjects([i],r),e.deposit(s,o)},withdrawQuick:async(n,o)=>{let r=j(t),i=a.utils.parseMarketCoinName(o),{leftCoin:s,takeCoin:c}=await a.selectMarketCoin(t,i,n,r);return t.transferObjects([s],r),e.withdraw(c,o)},borrowQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r,i),l=[...await a.query.getObligationCoinNames(s.obligationId),o];return await On(a,t,l),e.borrow(s.obligationId,s.obligationKey,n,o)},repayQuick:async(n,o,r,i)=>{let s=await Dn(t,a,r);if(o==="sui"){let[d]=t.splitCoins(t.gas,[n]);return e.repay(s.obligationId,d,o)}let{leftCoin:c,takeCoin:l}=await a.selectCoin(t,o,n,i);return t.transferObjects([c],i),e.repay(s.obligationId,l,o)},updateAssetPricesQuick:async n=>On(a,t,n)}};import{SUI_CLOCK_OBJECT_ID as Pn}from"@mysten/sui.js/utils";var vr=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&o)return[o];let r=j(e),i=await Yt(t.query,r);if(i[n].length===0)throw new Error(`No stake account id found for sender ${r}`);return i[n].map(s=>s.id)},gc=async(...a)=>{let[t,e,n,o]=a,r=j(e),i=await Yt(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return o?i[n].filter(c=>c.id===o):i[n]},hc=({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")};return{createStakeAccount:n=>{let o=a.utils.parseMarketCoinType(n),r=a.address.get(`spool.pools.${n}.id`);return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(r),t.object(Pn)],typeArguments:[o]})},stake:(n,o,r)=>{let i=a.utils.parseMarketCoinType(r),s=a.address.get(`spool.pools.${r}.id`);t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(s),t.object(n),typeof o=="string"?t.pure(o):o,t.object(Pn)],typeArguments:[i]})},unstake:(n,o,r)=>{let i=a.utils.parseMarketCoinType(r),s=a.address.get(`spool.pools.${r}.id`);return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(s),t.object(n),t.pure(o),t.object(Pn)],typeArguments:[i]})},claim:(n,o)=>{let r=a.address.get(`spool.pools.${o}.id`),i=a.address.get(`spool.pools.${o}.rewardPoolId`),s=a.utils.parseMarketCoinType(o),c=Cn[o],l=a.utils.parseCoinType(c);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(r),t.object(i),t.object(n),t.object(Pn)],typeArguments:[s,l]})}}},bt=({builder:a,txBlock:t})=>{let e=hc({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(n,o,r)=>{let i=j(t),s=await vr(a,t,o,r),c=a.utils.parseMarketCoinType(o);if(typeof n=="number"){let l=await a.utils.selectCoinIds(n,c,i),[d,p]=a.utils.takeAmountFromCoins(t,l,n);e.stake(s[0],d,o),t.transferObjects([p],i)}else e.stake(s[0],n,o)},unstakeQuick:async(n,o,r)=>{let i=n,s=await gc(a,t,o,r),c=[];for(let l=0;l<s.length;l++){if(s[l].staked===0)continue;let d=Math.min(i,s[l].staked),p=e.unstake(s[l].id,d,o);if(c.push(p),i-=d,i===0)break}return c},claimQuick:async(n,o)=>{let r=await vr(a,t,n,o),i=[];return r.forEach(s=>{let c=e.claim(s,n);i.push(c)}),i}}};import{SUI_CLOCK_OBJECT_ID as Zt}from"@mysten/sui.js/utils";var yc=({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,o)=>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(o),t.object(Zt)]}),extendLockPeriod:(n,o)=>{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(o),t.object(Zt)]})},extendLockAmount:(n,o)=>{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 o=="string"?t.pure(o):o,t.object(Zt)]})},renewExpiredVeSca:(n,o,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof o=="string"?t.pure(o):o,t.pure(r),t.object(Zt)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(Zt)]})}},ft=({builder:a,txBlock:t})=>{let e=yc({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,o,r=!0)=>{let i=j(t),s=await mt(a,t),c,l=[];if(n!==void 0&&typeof n=="number"){let b=await a.utils.selectCoinIds(n,ot,i),[f,h]=a.utils.takeAmountFromCoins(t,b,n);c=f,l.push(h)}else c=n;let d=a.utils.getUnlockAt(o,s?.unlockAt);r&&cr(n,o,d,s?.unlockAt),console.log(new Date(d*1e3).toLocaleString("en-CA",{hour12:!0}));let p=!s?.unlockAt,m=!p&&s.unlockAt*1e3<=new Date().getTime();if(p||m){if(c)if(p){let b=e.lockSca(c,d);l.push(b)}else{if(s.lockedScaAmount!==0){let b=e.redeemSca(s.keyId);l.push(b)}e.renewExpiredVeSca(s.keyId,c,d)}}else c&&o?(e.extendLockPeriod(s.keyId,d),e.extendLockAmount(s.keyId,c)):o?e.extendLockPeriod(s.keyId,d):c&&e.extendLockAmount(s.keyId,c);l.length>0&&t.transferObjects(l,i)},extendLockPeriodQuick:async(n,o,r=!0)=>{let i=await mt(a,t,o),s=a.utils.getUnlockAt(n);r&&dr(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,o,r=!0)=>{let i=j(t),s=await mt(a,t,o);if(r&&lr(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,ot,i),[l,d]=a.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,l),t.transferObjects([d],i)}},renewExpiredVeScaQuick:async(n,o,r,i=!0)=>{let s=j(t),c=await mt(a,t,r),l=a.utils.getUnlockAt(o,c?.unlockAt);if(i&&ur(n,o,c?.unlockAt),c){let d=[];if(c.lockedScaAmount!==0){let f=e.redeemSca(c.keyId);d.push(f)}let p=await a.utils.selectCoinIds(n,ot,s),[m,b]=a.utils.takeAmountFromCoins(t,p,n);d.push(b),e.renewExpiredVeSca(c.keyId,m,l),t.transferObjects(d,s)}},redeemScaQuick:async n=>{let o=j(t),r=await mt(a,t,n);if(Ot(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],o)}}}};var y=class{params;client;address;builder;query;utils;walletAddress;constructor(t,e){this.params=t,this.client=t.client,this.address=e?.address??new G({id:t?.addressesId||at,network:t?.networkType}),this.query=e?.query??new Pt(t,{address:this.address}),this.utils=e?.utils??new it(t,{address:this.address,query:this.query}),this.builder=e?.builder??new _t(t,{address:this.address,query:this.query,utils:this.utils}),this.walletAddress=Sc(t.walletAddress)}init(t=!1){(t||!this.address.getAddresses())&&this.address.read(),this.builder.init(t,this.address),this.query.init(t,this.address),this.utils.init(t,this.address)}async getObligations(t){let e=t||this.walletAddress;return this.query.getObligations(e)}async getAllStakeAccounts(t){let e=t||this.walletAddress;return this.query.getAllStakeAccounts(e)}async getStakeAccounts(t,e){let n=e||this.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 x,n=q({builder:this.builder,txBlock:e}),o=t||this.walletAddress;return e.setSender(o),n.normalMethod.openObligationEntry(),e}async depositCollateral(t,e,n,o){let r=new x,i=o||this.walletAddress;r.setSender(i);let s=q({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),l=n||c?.[0]?.id;if(l)await s.addCollateralQuick(e,t,l);else{let[d,p,m]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,d),s.normalMethod.returnObligation(d,m),r.transferObjects([p],i)}return r}async withdrawCollateral(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=r||this.walletAddress;i.setSender(c);let l=await s.takeCollateralQuick(e,t,n,o);return i.transferObjects([l],c),i}async deposit(t,e,n){let o=new x,r=q({builder:this.builder,txBlock:o}),i=n||this.walletAddress;o.setSender(i);let s=await r.depositQuick(e,t,n);return o.transferObjects([s],i),o}async withdraw(t,e,n){let o=new x,r=n||this.walletAddress,i=q({builder:this.builder,txBlock:o});o.setSender(r);let s=await i.withdrawQuick(e,t);return o.transferObjects([s],r),o}async borrow(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=W({builder:this.builder,txBlock:i}),l=r||this.walletAddress;i.setSender(l);let d=At.includes(t);d&&await c.unstakeObligationQuick(n,o);let p=await s.borrowQuick(e,t,n,o);return i.transferObjects([p],l),d&&await c.stakeObligationQuick(n,o),i}async borrowWithBoost(t,e,n,o,r,i){let s=new x,c=q({builder:this.builder,txBlock:s}),l=W({builder:this.builder,txBlock:s}),d=i||this.walletAddress;s.setSender(d);let p=At.includes(t);p&&await l.unstakeObligationQuick(n,o);let m=await c.borrowQuick(e,t,n,o);return s.transferObjects([m],d),p&&await l.stakeObligationWithVeScaQuick(n,o,r),s}async repay(t,e,n,o,r){let i=new x,s=q({builder:this.builder,txBlock:i}),c=W({builder:this.builder,txBlock:i}),l=r||this.walletAddress;i.setSender(l);let d=At.includes(t);return d&&await c.unstakeObligationQuick(n,o),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationQuick(n,o),i}async createStakeAccount(t,e){let n=new x,o=bt({builder:this.builder,txBlock:n}),r=e||this.walletAddress;n.setSender(r);let i=o.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,o){let r=new x,i=q({builder:this.builder,txBlock:r}),s=bt({builder:this.builder,txBlock:r}),c=o||this.walletAddress;r.setSender(c);let l=await i.depositQuick(e,t,o),d=this.utils.parseMarketCoinName(t);if(!Xt.find(b=>b===d))return r;let p=await this.query.getStakeAccounts(d,c),m=n||(p.length>0?p[0].id:void 0);if(m)await s.stakeQuick(l,d,m);else{let b=s.normalMethod.createStakeAccount(d);await s.stakeQuick(l,d,b),r.transferObjects([b],c)}return r}async unstakeAndWithdraw(t,e,n){let o=new x,r=q({builder:this.builder,txBlock:o}),i=bt({builder:this.builder,txBlock:o}),s=this.walletAddress,c=[];o.setSender(s);let l=this.utils.parseMarketCoinName(t);for(let d=0;d<n.length;d++){let p=n[d],[m]=await i.unstakeQuick(p.coin,l,p.id);if(m){let b=r.normalMethod.withdraw(m,t);c.push(b)}}if(e>0){let d=await r.withdrawQuick(e,t);c.push(d)}return o.transferObjects(c,s),o}async stake(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=o||this.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),l=n||(c.length>0?c[0].id:void 0);if(l)await i.stakeQuick(e,t,l);else{let d=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,d),r.transferObjects([d],s)}return r}async unstake(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=o||this.walletAddress;r.setSender(s);let c=await i.unstakeQuick(e,t,n);return r.transferObjects(c,s),r}async claim(t,e,n,o){let r=new x,i=bt({builder:this.builder,txBlock:r}),s=W({builder:this.builder,txBlock:r}),c=o||this.walletAddress;r.setSender(c);let l={sui:[],sca:[]};for(let d=0;d<t.length;d++){let{stakeMarketCoinName:p,stakeAccountId:m}=t[d],b=i.normalMethod.claim(m,p);l.sui.push(b)}for(let d=0;d<e.length;d++){let{obligationId:p,obligationKey:m,rewardCoinName:b}=e[d],f=s.normalMethod.claimBorrowIncentive(p,m,b);l[b].push(f)}for(let d=0;d<n.length;d++){let{obligationId:p,obligationKey:m,rewardCoinName:b}=n[d],f=s.normalMethod.oldClaimBorrowIncentive(p,m,b);l[b].push(f)}return l.sui.length>0&&(l.sui.length>1&&r.mergeCoins(l.sui[0],l.sui.slice(1)),r.transferObjects([l.sui[0]],r.pure(c))),l.sca.length>0&&(l.sca.length>1&&r.mergeCoins(l.sca[0],l.sca.slice(1)),r.transferObjects([l.sca[0]],r.pure(c))),r}async stakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=W({builder:this.builder,txBlock:o}),i=n||this.walletAddress;return o.setSender(i),await r.stakeObligationQuick(t,e),o}async unstakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=W({builder:this.builder,txBlock:o}),i=n||this.walletAddress;return o.setSender(i),await r.unstakeObligationQuick(t,e),o}async stakeSca(t,e=!1,n=!1,o,r,i,s,c){let l=new x,d=ft({builder:this.builder,txBlock:l}),p=W({builder:this.builder,txBlock:l}),m=c||this.walletAddress;l.setSender(m);let b=await this.builder.utils.selectCoinIds(t,ot,m),[f,h]=this.builder.utils.takeAmountFromCoins(l,b,t),w;return s?d.normalMethod.extendLockAmount(s,f):w=d.normalMethod.lockSca(f,i),o&&r&&(e&&(n?p.normalMethod.oldUnstakeObligation(o,r):p.normalMethod.unstakeObligation(o,r)),p.normalMethod.stakeObligationWithVesca(o,r,s||w)),s||l.transferObjects([w,h],m),l}async stakeMoreSca(t,e,n){let o=new x,r=n||this.walletAddress;return o.setSender(r),o}async extendStakeScaLockPeriod(t,e,n,o,r=!1,i=!1,s){let c=new x,l=ft({builder:this.builder,txBlock:c}),d=W({builder:this.builder,txBlock:c}),p=s||this.walletAddress;return c.setSender(p),l.normalMethod.extendLockPeriod(e,t),n&&o&&(r&&(i?d.normalMethod.oldUnstakeObligation(n,o):d.normalMethod.unstakeObligation(n,o)),d.normalMethod.stakeObligationWithVesca(n,o,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,o,r,i=!1,s=!1,c){let l=new x,d=ft({builder:this.builder,txBlock:l}),p=W({builder:this.builder,txBlock:l}),m=c||this.walletAddress;l.setSender(m);let b=await this.builder.utils.selectCoinIds(t,ot,m),[f,h]=this.builder.utils.takeAmountFromCoins(l,b,t);return d.normalMethod.extendLockPeriod(e,n),d.normalMethod.extendLockAmount(e,f),l.transferObjects([h],m),!o||!r||(i&&(s?p.normalMethod.oldUnstakeObligation(o,r):p.normalMethod.unstakeObligation(o,r)),p.normalMethod.stakeObligationWithVesca(o,r,e)),l}async renewExpiredStakeSca(t,e,n,o=!1,r,i,s=!1,c=!1,l){let d=new x,p=ft({builder:this.builder,txBlock:d}),m=W({builder:this.builder,txBlock:d}),b=l||this.walletAddress;if(d.setSender(b),o){let P=p.normalMethod.redeemSca(n);d.transferObjects([P],b)}let f=await this.builder.utils.selectCoinIds(t,ot,b),[h,w]=this.builder.utils.takeAmountFromCoins(d,f,t);return d.transferObjects([w],b),p.normalMethod.renewExpiredVeSca(n,h,e),!r||!i||(s&&(c?m.normalMethod.oldUnstakeObligation(r,i):m.normalMethod.unstakeObligation(r,i)),m.normalMethod.stakeObligationWithVesca(r,i,n)),d}async redeemSca(t){let e=new x,n=ft({builder:this.builder,txBlock:e}),o=this.walletAddress;return e.setSender(o),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,o){let r=new x,i=W({builder:this.builder,txBlock:r}),s=this.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(n,e,o);return r.transferObjects([c],s),i.stakeObligationWithVeScaQuick(n,e,t),r}async withdrawUnlockedSca(t,e){let n=new x,o=ft({builder:this.builder,txBlock:n}),r=e||this.walletAddress;return n.setSender(r),await o.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new Ar(t.weightedAmount),r=e.currentPointIndex?Ar(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}};var _n=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 jn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return await n.init(),n.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 Bn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var Rn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new a(e)}};var Nn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 En=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 Mn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return await n.init(),n.migrateAndClaim(this.data.veScaKey,this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName)}static fromData(e){return new a(e)}};var Ln=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.openObligation()}static fromData(e){return new a(e)}};var Wn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.redeemSca(this.data.veScaKey)}static fromData(e){return new a(e)}};var Fn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 Un=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Qn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.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 u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Gn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Kn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new a(e)}};var Hn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.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 zn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=e.network.split(":")[1],o=new y({client:e.suiClient,walletAddress:e.account.address,networkType:n});return o.init(),o.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Xn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new y({client:e.suiClient,walletAddress:e.account.address,networkType:e.network.split(":")[1]});return n.init(),n.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new a(e)}};var Jn=class{application="scallop";async deserialize(t){let e=new _t({client:t.suiClient,walletAddress:t.account.address,networkType:t.network.split(":")[1]});await e.init();let{transactionBlock:n}=t,r=new Tn(n,e).decode();return{txType:wc.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"SupplyLending":r=Vn.fromData(t.intentionData);break;case"WithdrawLending":r=zn.fromData(t.intentionData);break;case"Borrow":r=_n.fromData(t.intentionData);break;case"Repay":r=qn.fromData(t.intentionData);break;case"DepositCollateral":r=Rn.fromData(t.intentionData);break;case"WithdrawCollateral":r=Hn.fromData(t.intentionData);break;case"OpenObligation":r=Ln.fromData(t.intentionData);break;case"StakeSpool":r=$n.fromData(t.intentionData);break;case"UnstakeSpool":r=Gn.fromData(t.intentionData);break;case"ClaimIncentiveReward":r=Bn.fromData(t.intentionData);break;case"BorrowWithBoost":r=jn.fromData(t.intentionData);break;case"StakeSca":r=Un.fromData(t.intentionData);break;case"ExtendStakePeriod":r=En.fromData(t.intentionData);break;case"ExtendPeriodAndStakeMore":r=Nn.fromData(t.intentionData);break;case"RenewExpStakePeriod":r=Fn.fromData(t.intentionData);break;case"WithdrawStakedSca":r=Xn.fromData(t.intentionData);break;case"SupplyAndStakeLending":r=Qn.fromData(t.intentionData);break;case"WithdrawAndUnstakeLending":r=Kn.fromData(t.intentionData);break;case"RedeemSca":r=Wn.fromData(t.intentionData);break;case"MigrateAndClaim":r=Mn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as qc}from"@msafe/sui3-utils";import{TurbosSdk as Uc}from"turbos-clmm-sdk";import{TransactionType as F}from"@msafe/sui3-utils";import{bcs as Or}from"@mysten/sui.js/bcs";import{normalizeStructTag as Tc,normalizeSuiAddress as te}from"@mysten/sui.js/utils";var U={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},$={PackageId:"0xdee9"};import{BN as kc}from"turbos-clmm-sdk";var Ic=(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(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},Yn=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`]}decode(t){if(this.isSwapTransaction())return 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(`${U.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${U.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${$.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${$.PackageId}::clob_v2::swap_exact_quote_for_base`)}decodeSwap(){let t=this.transactions.find(m=>m.kind==="MoveCall"),e=0;this.swap2Layer.includes(t.target)&&(e=1);let n=Ic(e,t.target,this.swap1Layer,this.swap2Layer),o=n.map((m,b)=>{let f=this.helper.decodeSharedObjectId(b),h=this.helper.decodeInputU128(4+b+e),w=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new kc(h.toString()));return{pool:f,a2b:m,nextTickIndex:w}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),l=this.helper.decodeInputBool(5+2*e),d=this.helper.decodeInputU64(2+e),p=this.helper.decodeInputU64(3+e);return{txType:F.Other,type:"Swap",intentionData:{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:p,amountB:l?p:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:F.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:o,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:F.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:o,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:F.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:F.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:o,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:F.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:o,nft:e,deadline:r}}}decodeBurn(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:F.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(p=>p.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:F.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:F.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:F.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:F.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:F.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero");return new ct(t,this.txb)}get collectRewardHelper(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect_reward`).map(e=>new ct(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new ct(t,this.txb)}get decreaseLiquidityHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new ct(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${$.PackageId}::clob_v2::swap_exact_base_for_quote`);return new ct(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${$.PackageId}::clob_v2::swap_exact_quote_for_base`);return new ct(t,this.txb)}},ct=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 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 Or.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 Or.de(e,new Uint8Array(n))}typeArg(t){return Tc(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as xc}from"turbos-clmm-sdk";var Zn=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new xc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:p,txb:m}=this.data;return n.pool.addLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as vc}from"turbos-clmm-sdk";var ta=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new vc(e.network.replace("sui:",""),e.suiClient),{pool:o,nft:r,txb:i}=this.data;return n.nft.burn({pool:o,nft:r,txb:i})}static fromData(e){return new a(e)}};import{TurbosSdk as Ac}from"turbos-clmm-sdk";var ea=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ac(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:o,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(e){return new a(e)}};import{TurbosSdk as Oc}from"turbos-clmm-sdk";var na=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Oc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:o,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(e){return new a(e)}};import{TurbosSdk as Dc}from"turbos-clmm-sdk";var aa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Dc(e.network.replace("sui:",""),e.suiClient),{fee:o,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:p,amountA:m,amountB:b,deadline:f,txb:h}=this.data;return n.pool.createPool({fee:o,amountA:m,amountB:b,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:p,deadline:f,txb:h})}static fromData(e){return new a(e)}};import{TurbosSdk as Pc}from"turbos-clmm-sdk";var oa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Pc(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:p,txb:m}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as _c}from"turbos-clmm-sdk";var ra=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new _c(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:p}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:p})}static fromData(e){return new a(e)}};import{TransactionBlock as jc}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as Bc}from"@mysten/sui.js/utils";var ia=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new jc;return n.moveCall({target:`${U.PackageId}::claim::claim`,typeArguments:[U.turbosCoinType],arguments:[n.object(U.Claim),n.object(Bc)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Rc}from"@mysten/sui.js/transactions";var sa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Rc;return n.moveCall({target:`${U.PackageId}::claim::join`,typeArguments:[U.turbosCoinType],arguments:[n.object(U.Claim)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Nc}from"@mysten/sui.js/transactions";import{TurbosSdk as Ec}from"turbos-clmm-sdk";var ca=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ec(e.network.replace("sui:",""),e.suiClient),o=new Nc;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(e){return new a(e)}};import{TurbosSdk as Mc}from"turbos-clmm-sdk";var da=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new Mc(e.network.replace("sui:",""),e.suiClient),{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:p,deadline:m,txb:b}=this.data;return n.trade.swap({routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:p,slippage:d,deadline:m,txb:b})}static fromData(e){return new a(e)}};import{TurbosSdk as Wc}from"turbos-clmm-sdk";import{normalizeSuiObjectId as Dr}from"@mysten/sui.js/utils";import{TransactionBlock as Pr}from"@mysten/sui.js/transactions";import{unstable_getObjectId as Lc}from"turbos-clmm-sdk";var ee=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let o=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),o.push(...r.data);while(r.hasNextPage);let i=[],s=0;return o.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let o=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(o,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(o,[n.pure(e)]);return[r,o]}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:`${$.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?Lc(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${$.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var _r=89,jr=1e6,Br=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Pr,c=new ee(i),l=await c.getCoinsData(r,e,o),[d,p]=c.splitAndMergeCoin(l,o,s);if(!d)throw new Error(`Not enough balance: ${e}`);let m=await c.IsAccountCap(r),b=m?s.object(m):c.createAccount(s),[f,h,w]=s.moveCall({typeArguments:[t,e],target:`${$.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(_r),b,s.pure(o),s.object(Dr("0x6")),d]});return p&&s.transferObjects([p],s.pure(r)),s.transferObjects([f],s.pure(r)),s.transferObjects([h],s.pure(r)),m||s.transferObjects([b],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(jr),s},Rr=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Pr,c=new ee(i),l=await c.getCoinsData(r,t,o),[d,p]=c.splitAndMergeCoin(l,o,s);if(!d)throw new Error(`Not enough balance: ${t}`);let m=await c.IsAccountCap(r),b=m?s.object(m):c.createAccount(s),f=c.zero(e,s),[h,w,P]=s.moveCall({typeArguments:[t,e],target:`${$.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(_r),b,s.pure(o),d,f,s.object(Dr("0x6"))]});return p&&s.transferObjects([p],s.pure(r)),s.transferObjects([h],s.pure(r)),s.transferObjects([w],s.pure(r)),m||s.transferObjects([b],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(jr),s};var la=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Wc(e.network.replace("sui:",""),e.suiClient);return await Rr({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};import{TurbosSdk as Fc}from"turbos-clmm-sdk";var ua=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Fc(e.network.replace("sui:",""),e.suiClient);return await Br({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var pa=class{application="turbos";async deserialize(t){let e=new Uc(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:o,account:r}=t;console.log(t,"input");let s=new Yn(o,e,n).decode(r.address);return{txType:qc.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":r=aa.fromData(t.intentionData);break;case"AddLiquidity":r=Zn.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ra.fromData(t.intentionData);break;case"DecreaseLiquidity":r=oa.fromData(t.intentionData);break;case"RemoveLiquidity":r=ca.fromData(t.intentionData);break;case"CollectFee":r=ea.fromData(t.intentionData);break;case"CollectReward":r=na.fromData(t.intentionData);break;case"Burn":r=ta.fromData(t.intentionData);break;case"Swap":r=da.fromData(t.intentionData);break;case"PrixJoin":r=sa.fromData(t.intentionData);break;case"PrixClaim":r=ia.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=la.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=ua.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as zc}from"@msafe/sui3-utils";import{TransactionType as Ja}from"@msafe/sui3-utils";import{bcs as Nr}from"@mysten/sui.js/bcs";import{normalizeStructTag as Vc,normalizeSuiAddress as ne}from"@mysten/sui.js/utils";var $c={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},k=$c;var ma=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(`${k.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${k.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${k.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:Ja.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Ja.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:Ja.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(k.packageId));return new Ya(t,this.txb)}},Ya=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 ne(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 Nr.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 ne(t.value.Object.ImmOrOwned.objectId)}return ne(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ne(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ne(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 Nr.de(e,new Uint8Array(n))}typeArg(t){return Vc(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Gc}from"@mysten/sui.js/transactions";var ba=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Gc,{ticketId:o}=this.data;return n.moveCall({target:`${k.packageId}::native_pool::burn_ticket`,arguments:[n.object(k.poolObjectId),n.object(k.systemStateObjectId),n.object(o)]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Kc}from"@mysten/sui.js/transactions";var fa=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Kc,{amount:o}=this.data,[r]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${k.packageId}::native_pool::stake`,arguments:[n.object(k.poolObjectId),n.object(k.metadataObjectId),n.object(k.systemStateObjectId),r]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};import{TransactionBlock as Hc}from"@mysten/sui.js/transactions";var ga=class a extends u{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Hc,{amount:o}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===k.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${k.packageId}::native_pool::unstake`,arguments:[n.object(k.poolObjectId),n.object(k.metadataObjectId),n.object(k.systemStateObjectId),l]}),n.setGasBudget(k.gasBudget),n}static fromData(e){return new a(e)}};var ha=class{application="volo";async deserialize(t){let{transactionBlock:e}=t,o=new ma(e).decode();return{txType:zc.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(t.txSubType){case"Stake":o=fa.fromData(t.intentionData);break;case"UnStake":o=ga.fromData(t.intentionData);break;case"ClaimTicket":o=ba.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};var lx=new yn([new sn,new gn,new nn,new hn,new Te,new pa,new Pe,new Jn,new ha]);export{lx as appHelpers};
2
2
  //# sourceMappingURL=index.mjs.map