@msafe/sui-app-store 0.0.228 → 0.0.232
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -8
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ns=Object.defineProperty;var cr=(o,e)=>{for(var t in e)ns(o,t,{get:e[t],enumerable:!0})};import{TransactionType as ps}from"@msafe/sui3-utils";import{coinsList as os,poolIdPoolNameMap as rs,poolInfo as lr,singleAssetPoolCoinMap as is}from"@alphafi/alphafi-sdk";import{TransactionType as Dt}from"@msafe/sui3-utils";import{bcs as te,fromBase64 as ee}from"@mysten/bcs";var ne=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,n=t.pool_id,a=rs[n];if(console.log("Decoder event data - ",t),console.log("Decoder poolName - ",a),this.isWithdrawAlphaEvent(e))return this.decodeWithdrawAlpha(t);if(this.isWithdrawEvent(t))return this.decodeWithdraw(a);if(this.isDoubleAssetDepositEvent(t,a))return this.decodeDoubleAssetDeposit(a,t);if(this.isSingleAssetDepositEvent(t,a))return this.decodeSingleAssetDeposit(a,t);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(){return this.simResult.events.find(e=>this.isLiquidityChangeEventType(e.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(e){return e.includes("LiquidityChangeEvent")||e.includes("LiquidityChangeNewNewEvent")||e.includes("WithdrawEventV2")}isWithdrawAlphaEvent(e){return e.type.includes("WithdrawEventV2")}isWithdrawEvent(e){return e.event_type===1}isDoubleAssetDepositEvent(e,t){return e.event_type===0&&lr[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&lr[t].assetTypes.length===1}extractXTokensAmount(){let e=this.inputs.find(a=>a.Pure!==void 0);if(!e||!e.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:t}=e.Pure,n;return t.length===12?n=te.u64().parse(ee(t)):t.length===24?n=te.u128().parse(ee(t)):t.length===44?n=te.u256().parse(ee(t)):n=te.u64().parse(ee(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:a}=t,r=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,a,r),{txType:Dt.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:r?n:a,isAmountA:r}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:r}=is[e],{expo:i}=os[r];n=Math.floor(Number(n)/10**(9-i)).toString()}return{txType:Dt.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:Dt.Other,type:"withdraw",intentionData:{poolName:e,xTokensAmount:t}}}decodeWithdrawAlpha(e){let t=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=e;return console.log("Decoder.decodeWithdrawAlpha",t,n),{txType:Dt.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:Dt.Other,type:"claimReward",intentionData:{}}}};import{claimRewardTxb as cs}from"@alphafi/alphafi-sdk";import ss from"sort-keys-recursive";var u=class{constructor(e){this.data=e}serialize(){return JSON.stringify(ss(this.data))}};var ae=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t;return await cs(n.address)}static fromData(t){return new o(t)}};import{depositDoubleAssetTxb as ls}from"@alphafi/alphafi-sdk";var oe=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:a,amount:r,isAmountA:i}=this.data;return await ls(a,n.address,r,i)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new o(t)}};import{depositSingleAssetTxb as ds}from"@alphafi/alphafi-sdk";var re=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:a,amount:r}=this.data;return await ds(a,n.address,r)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new o(t)}};import{withdrawTxb as us}from"@alphafi/alphafi-sdk";var ie=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:a,xTokensAmount:r}=this.data;return await us(r,a,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new o(t)}};import{withdrawAlphaTxb as ms}from"@alphafi/alphafi-sdk";var se=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:a,xTokensAmount:r}=this.data;return await ms(r,a,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new o(t)}};var ce=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:a}=e,r=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",r);let s=new ne(t,r).decode();return{txType:ps.Other,txSubType:s.type,intentionData:s.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=re.fromData(e.intentionData);break;case"depositDoubleAsset":n=oe.fromData(e.intentionData);break;case"withdraw":n=ie.fromData(e.intentionData);break;case"withdrawAlpha":n=se.fromData(e.intentionData);break;case"claimReward":n=ae.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};import{TransactionType as Ws}from"@msafe/sui3-utils";import{TransactionType as B}from"@msafe/sui3-utils";import{bcs as wo}from"@mysten/sui/bcs";import{SBUCK_FOUNTAIN_PACKAGE_ID as ko}from"bucket-protocol-sdk";var le=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,n){return this.commands.find(a=>a.$kind==="MoveCall"&&a.MoveCall.package===e&&a.MoveCall.module===t&&a.MoveCall.function===n)}getMoveCallModuleCommands(e,t){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(e=>e.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(e=>e.$kind==="TransferObjects")}isPsmTransaction(){return!!this.getMoveCallCommand("charge_reservoir")||!!this.getMoveCallCommand("discharge_reservoir")}isStrapNewTransaction(){return!!this.getMoveCallModuleCommand("strap","new")}isBorrowTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","high_top_up")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow_with_strap")}isRepayTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","fully_repay")||!!this.getMoveCallModuleCommand("bucket_operations","fully_repay_with_strap")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw_with_strap")}isWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","withdraw")||!!this.getMoveCallModuleCommand("buck","withdraw_with_strap")}isCloseTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","destroy_empty_strap")}isTankDepositTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","deposit")}isTankWithdrawTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","withdraw")}isTankClaimTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","claim")}isSBUCKDepositTransaction(){return!!this.getMoveCallModuleCommand("buck","buck_to_sbuck")}isSBUCKWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","sbuck_to_buck")}isSBUCKStakeTransaction(){return!!this.getMoveCallPackageModuleCommand(ko,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(ko,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(ko,"fountain_core","claim")}isLockedClaimTransaction(){return!!this.getMoveCallModuleCommand("proof_rule","claim")||!!this.getMoveCallModuleCommand("lst_proof_rule","claim")}isLstUnlockTransaction(){return!!this.getMoveCallModuleCommand("lst_proof_rule","unlock")}decodePsm(){let e,t,n="0",a=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return a.$kind==="Input"&&(n=this.getPureInputU64(a.Input)),this.getMoveCallCommand("charge_reservoir")?([e]=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments,t=!1):([e]=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments,t=!0),console.log("Decoder.decodePsm",e,n,t),{txType:B.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,a=this.getStrapId(),r="0",i=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(i.$kind==="Input"&&(r=this.getPureInputU64(i.Input)),this.getMoveCallCommand("high_top_up")){let s=this.getMoveCallCommand("high_top_up").MoveCall;[e]=s.typeArguments;let c=s.arguments[1];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=s.arguments[3];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}else if(this.getMoveCallCommand("high_borrow")){let s=this.getMoveCallCommand("high_borrow").MoveCall;[e]=s.typeArguments;let c=s.arguments[4];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=s.arguments[5];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let s=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=s.typeArguments;let c=s.arguments[5];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=s.arguments[6];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}return{txType:B.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:r,borrowAmount:t,insertionPlace:n,strapId:a}}}decodeRepay(){let e="",t="0",n="0",r,i=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let s=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=s.typeArguments;let c=s.arguments[4];c.$kind==="Input"&&(n=this.getPureInputU64(c.Input));let l=s.arguments[5];if(l.$kind==="Input"){let m=this.getPureAddresses(l.Input);m.length===1&&([r]=m)}let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let s=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=s.typeArguments;let c=s.arguments[5];c.$kind==="Input"&&(n=this.getPureInputU64(c.Input));let l=s.arguments[6];if(l.$kind==="Input"){let m=this.getPureAddresses(l.Input);m.length===1&&([r]=m)}let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input))}return{txType:B.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:r,strapId:i}}}decodeWithdraw(){let e="",t="0",n,a=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let r=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=r.typeArguments;let i=r.arguments[4];i.$kind==="Input"&&(t=this.getPureInputU64(i.Input));let s=r.arguments[5];if(s.$kind==="Input"){let c=this.getPureAddresses(s.Input);c.length===1&&([n]=c)}}else if(this.getMoveCallCommand("withdraw")){let r=this.getMoveCallCommand("withdraw").MoveCall;[e]=r.typeArguments;let i=r.arguments[3];i.$kind==="Input"&&(t=this.getPureInputU64(i.Input));let s=r.arguments[4];if(s.$kind==="Input"){let c=this.getPureAddresses(s.Input);c.length===1&&([n]=c)}}return{txType:B.Other,type:"withdraw",intentionData:{collateralType:e,withdrawAmount:t,insertionPlace:n,strapId:a}}}decodeClose(){let e="",t=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([e]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:B.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",r=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];r.$kind==="Input"&&(n=this.getPureInputU64(r.Input));let i=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,i),{txType:B.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:i}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let c=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];c.$kind==="Input"&&(e=this.getPureInputU64(c.Input))}let n=[],a=this.getMoveCallModuleCommands("proof_rule","unlock");if(a.length>0)for(let s=0;s<a.length;s++){let c=a[s];n.push("")}else{let s=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let c=0;c<s.length;c++){let d=s[c].MoveCall.arguments[2];if(d.$kind==="Input"){let{objectId:m}=this.inputs[d.Input].UnresolvedObject;n.push(m)}}}let r=this.isSBUCKWithdrawTransaction(),i={stakeProofs:n,amount:e,isStake:t,toBuck:r};return console.log("Decoder.decodeSBUCKUnstake",i),{txType:B.Other,type:"sbuck-unstake",intentionData:i}}decodeSBUCKWithdraw(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(e=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:B.Other,type:"sbuck-withdraw",intentionData:{amount:e}}}decodeSBUCKClaim(){let e=[],t=this.getMoveCallModuleCommands("fountain_core","claim");for(let n=0;n<t.length;n++){let r=t[n].MoveCall.arguments[2];if(r.$kind==="Input"){let{objectId:i}=this.inputs[r.Input].UnresolvedObject;e.push(i)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:B.Other,type:"sbuck-claim",intentionData:{stakeProofs:e}}}decodeTankDeposit(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];n.$kind==="Input"&&(e=this.getPureInputU64(n.Input));let r=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",r,e),{txType:B.Other,type:"tank-deposit",intentionData:{coinType:r,amount:e}}}decodeTankWithdraw(){let e=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,t=e.typeArguments[0],n="0",a=e.arguments[5];return a.$kind==="Input"&&(n=this.getPureInputU64(a.Input)),console.log("Decoder.decodeTankWithdraw",t,n),{txType:B.Other,type:"tank-withdraw",intentionData:{coinType:t,amount:n}}}decodeTankClaim(){let t=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",t),{txType:B.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let r=0;r<n.length;r++)[e]=n[r].MoveCall.typeArguments,t++;let a=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let r=0;r<a.length;r++)[e]=a[r].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:B.Other,type:"lock-claim",intentionData:{coinType:e,proofCount:t}}}getCoinInput(e){if(this.inputs[e].$kind!=="Object")throw new Error("not Object argument")}getStrapId(){let e;if(this.isStrapNewTransaction()?e="new":this.isLstUnlockTransaction()&&(e="locked"),!e){let t=this.getMoveCallModuleCommand("fountain","unstake");if(t){let n=t.MoveCall.arguments[2];n.$kind==="Input"&&(e=this.inputs[n.Input].UnresolvedObject.objectId)}}return e}getPureInputU64(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return wo.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return wo.vector(wo.Address).fromBase64(t.Pure.bytes)}};import{TransactionType as gs}from"@msafe/sui3-utils";import{Transaction as bs}from"@mysten/sui/transactions";import{buildPsmTx as hs}from"bucket-protocol-sdk";import{BucketClient as fs}from"bucket-protocol-sdk";var x=(o,e)=>{let t=o==="sui:mainnet"?"mainnet":"testnet";return new fs(t,e.address)};var dr=async(o,e,t)=>{let{coinType:n,amount:a,buckToCoin:r}=o,i=new bs,s=x(t,e);return await hs(s,i,n,a,r,e.address),i};var de=class o extends u{constructor(t){super(t);this.data=t}txType=gs.Other;txSubType="psm";async build(t){let{account:n,network:a}=t;return await dr(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ss}from"@msafe/sui3-utils";import{Transaction as ue}from"@mysten/sui/transactions";import{buildBorrowTx as ys,buildCloseTx as Ts,buildRepayTx as Cs,buildWithdrawTx as Is}from"bucket-protocol-sdk";var ur=async(o,e,t)=>{let{collateralType:n,collateralAmount:a,borrowAmount:r,insertionPlace:i,strapId:s}=o,c=new ue,l=x(t,e);return await ys(l,c,n,a,r,e.address,i,s),c},mr=async(o,e,t)=>{let{collateralType:n,withdrawAmount:a,insertionPlace:r,strapId:i}=o,s=new ue,c=x(t,e);return await Is(c,s,n,a,e.address,r,i),s},pr=async(o,e,t)=>{let{collateralType:n,repayAmount:a,withdrawAmount:r,isSurplus:i,insertionPlace:s,strapId:c}=o,l=new ue,d=x(t,e);return await Cs(d,l,n,a,r,e.address,i,s,c),l},fr=async(o,e,t)=>{let{collateralType:n,recipient:a,strapId:r}=o,i=new ue,s=x(t,e);return await Ts(s,i,n,a,r),i};var me=class o extends u{constructor(t){super(t);this.data=t}txType=Ss.Other;txSubType="borrow";async build(t){let{account:n,network:a}=t;return await ur(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as ws}from"@msafe/sui3-utils";var pe=class o extends u{constructor(t){super(t);this.data=t}txType=ws.Other;txSubType="repay";async build(t){let{account:n,network:a}=t;return await pr(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as ks}from"@msafe/sui3-utils";var fe=class o extends u{constructor(t){super(t);this.data=t}txType=ks.Other;txSubType="withdraw";async build(t){let{account:n,network:a}=t;return await mr(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as xs}from"@msafe/sui3-utils";var be=class o extends u{constructor(t){super(t);this.data=t}txType=xs.Other;txSubType="close";async build(t){let{account:n,network:a}=t;return await fr(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ie}from"@msafe/sui3-utils";import{Transaction as he}from"@mysten/sui/transactions";import{buildSBUCKClaimTx as Ds,buildSBUCKDepositTx as vs,buildSBUCKUnstakeTx as As,buildSBUCKWithdrawTx as Os}from"bucket-protocol-sdk";var br=async(o,e,t)=>{let{coinType:n,amount:a,isStake:r}=o,i=new he,s=x(t,e);return await vs(s,i,n,a,e.address,r),i},hr=async(o,e,t)=>{let{stakeProofs:n,amount:a,isStake:r,toBuck:i}=o,s=new he,c=x(t,e);return await As(c,s,n,a,e.address,r,i),s},gr=async(o,e,t)=>{let{amount:n}=o,a=new he,r=x(t,e);return await Os(r,a,n,e.address),a},yr=async(o,e,t)=>{let{stakeProofs:n}=o,a=new he,r=x(t,e);return await Ds(r,a,n,e.address),a};var ge=class o extends u{constructor(t){super(t);this.data=t}txType=Ie.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:a}=t;return await br(this.data,n,a)}static fromData(t){return new o(t)}},ye=class o extends u{constructor(t){super(t);this.data=t}txType=Ie.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:a}=t;return await hr(this.data,n,a)}static fromData(t){return new o(t)}},Te=class o extends u{constructor(t){super(t);this.data=t}txType=Ie.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:a}=t;return await gr(this.data,n,a)}static fromData(t){return new o(t)}},Ce=class o extends u{constructor(t){super(t);this.data=t}txType=Ie.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:a}=t;return await yr(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Do}from"@msafe/sui3-utils";import{Transaction as xo}from"@mysten/sui/transactions";import{buildTankClaimTx as Ps,buildTankDepositTx as Rs,buildTankWithdrawTx as Bs}from"bucket-protocol-sdk";var Tr=async(o,e,t)=>{let{coinType:n,amount:a}=o,r=new xo,i=x(t,e);return await Rs(i,r,n,a,e.address),r},Cr=async(o,e,t)=>{let{coinType:n,amount:a}=o,r=new xo,i=x(t,e);return await Bs(i,r,n,a,e.address),r},Ir=async(o,e,t)=>{let{coinType:n}=o,a=new xo,r=x(t,e);return await Ps(r,a,n,e.address),a};import{Transaction as _s}from"@mysten/sui/transactions";import{buildLockedClaimTx as Es}from"bucket-protocol-sdk";var Sr=async(o,e,t)=>{let{coinType:n,proofCount:a}=o,r=new _s,i=x(t,e);return await Es(i,r,n,a,e.address),r};var Se=class o extends u{constructor(t){super(t);this.data=t}txType=Do.Other;txSubType="tank-deposit";async build(t){let{account:n,network:a}=t;return await Tr(this.data,n,a)}static fromData(t){return new o(t)}},we=class o extends u{constructor(t){super(t);this.data=t}txType=Do.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:a}=t;return await Cr(this.data,n,a)}static fromData(t){return new o(t)}},ke=class o extends u{constructor(t){super(t);this.data=t}txType=Do.Other;txSubType="tank-claim";async build(t){let{account:n,network:a}=t;return await Ir(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ms}from"@msafe/sui3-utils";var xe=class o extends u{constructor(t){super(t);this.data=t}txType=Ms.Other;txSubType="lock-claim";async build(t){let{account:n,network:a}=t;return await Sr(this.data,n,a)}static fromData(t){return new o(t)}};var De=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,a=new le(t).decode();return{txType:Ws.Other,txSubType:a.type,intentionData:a.intentionData}}async build(e){let{suiClient:t,account:n,network:a}=e,r;switch(e.txSubType){case"psm":r=de.fromData(e.intentionData);break;case"borrow":r=me.fromData(e.intentionData);break;case"withdraw":r=fe.fromData(e.intentionData);break;case"repay":r=pe.fromData(e.intentionData);break;case"close":r=be.fromData(e.intentionData);break;case"tank-deposit":r=Se.fromData(e.intentionData);break;case"tank-withdraw":r=we.fromData(e.intentionData);break;case"tank-claim":r=ke.fromData(e.intentionData);break;case"sbuck-deposit":r=ge.fromData(e.intentionData);break;case"sbuck-unstake":r=ye.fromData(e.intentionData);break;case"sbuck-withdraw":r=Te.fromData(e.intentionData);break;case"sbuck-claim":r=Ce.fromData(e.intentionData);break;case"lock-claim":r=xe.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:a})}};import{TransactionType as Cc}from"@msafe/sui3-utils";import{TransactionType as Qs}from"@msafe/sui3-utils";import{AggregatorClient as Ns,Env as wr}from"@cetusprotocol/aggregator-sdk";import{CetusPeripherySDK as Ls}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as js}from"@cetusprotocol/cetus-sui-clmm-sdk";import{CetusXcetusSDK as Us}from"@cetusprotocol/cetus-xcetus-sdk";import Fs from"@cetusprotocol/vaults-sdk";import{SuiClient as qs,getFullnodeUrl as kr}from"@mysten/sui/client";var Ks={fullRpcUrl:kr("mainnet"),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:"0xc6faf3703b0e8ba9ed06b7851134bbbe7565eb35ff823fd78432baa4cbeaa12e",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x2d8c2e0fc6dd25b0214b3fa747e0fd27fd54608142cd2e4f64c1cd350cc4add4",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"},$s={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0xaabf0856070391df81fad9240049d69c5a51c3d376cc0885eeedd516526cc79b",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Vs={fullRpcUrl:kr("mainnet"),simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",version:4,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"}},at=(o,e)=>{let t=Ks,n=new js(t);return n.senderAddress=e.address,n},F=(o,e)=>{let t=at(o,e),n=$s;return new Ls(n,t)},Hs="https://api-sui.cetus.zone/router_v2/find_routes",xr=(o,e)=>{let t=new qs({url:"https://fullnode.mainnet.sui.io/"});return new Ns({endpoint:Hs,signer:e.address,client:t,env:wr.Mainnet})},Gs={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc6faf3703b0e8ba9ed06b7851134bbbe7565eb35ff823fd78432baa4cbeaa12e",config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x2d8c2e0fc6dd25b0214b3fa747e0fd27fd54608142cd2e4f64c1cd350cc4add4"},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0xaabf0856070391df81fad9240049d69c5a51c3d376cc0885eeedd516526cc79b",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},aggregator:{endPoint:"https://api-sui.cetus.zone/router_v2/find_routes",fullNodeurl:"https://fullnode.mainnet.sui.io/",walletAddress:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb",env:wr.Mainnet,providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"]}},vo=(o,e)=>{let t=new Fs(Gs);return t.senderAddress=e.address,t},dt=(o,e)=>{let t=new Us(Vs);return t.senderAddress=e.address,t};var Dr=async(o,e,t)=>await at(t,e).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),vr=async(o,e,t)=>await at(t,e).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),Ar=async(o,e,t)=>await at(t,e).Position.closePositionTransactionPayload(o),Or=async(o,e,t)=>await at(t,e).Position.removeLiquidityTransactionPayload(o),Pr=async(o,e,t)=>await at(t,e).Rewarder.collectRewarderTransactionPayload(o);var ve=class o extends u{constructor(t){super(t);this.data=t}txType=Qs.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Dr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as zs}from"@msafe/sui3-utils";var Ae=class o extends u{constructor(t){super(t);this.data=t}txType=zs.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Pr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Js}from"@msafe/sui3-utils";var Oe=class o extends u{constructor(t){super(t);this.data=t}txType=Js.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Or(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ys}from"@msafe/sui3-utils";var Rr=async(o,e,t)=>await F(t,e).Farms.openPositionAddLiquidityStakePaylod(o),Br=async(o,e,t)=>await F(t,e).Farms.addLiquidityFixCoinPayload(o),_r=async(o,e,t)=>await F(t,e).Farms.removeLiquidityPayload(o),Er=async(o,e,t)=>await F(t,e).Farms.removeLiquidityPayload(o),Mr=async(o,e,t)=>await F(t,e).Farms.claimFeeAndClmmReward(o),Wr=async(o,e,t)=>await F(t,e).Farms.harvestPayload(o),Nr=async(o,e,t)=>{let n=F(t,e),a=Object.values(o);return await n.Farms.batchHarvestPayload(a)},Lr=async(o,e,t)=>await F(t,e).Farms.depositPayload(o),jr=async(o,e,t)=>await F(t,e).Farms.withdrawPayload(o);var Pe=class o extends u{constructor(t){super(t);this.data=t}txType=Ys.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Rr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Xs}from"@msafe/sui3-utils";var Re=class o extends u{constructor(t){super(t);this.data=t}txType=Xs.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Nr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Zs}from"@msafe/sui3-utils";var Be=class o extends u{constructor(t){super(t);this.data=t}txType=Zs.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Mr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as tc}from"@msafe/sui3-utils";var _e=class o extends u{constructor(t){super(t);this.data=t}txType=tc.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await _r(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as ec}from"@msafe/sui3-utils";var Ee=class o extends u{constructor(t){super(t);this.data=t}txType=ec.Other;txSubType="FarmingHarvest";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Wr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as nc}from"@msafe/sui3-utils";var Me=class o extends u{constructor(t){super(t);this.data=t}txType=nc.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Br(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as ac}from"@msafe/sui3-utils";var We=class o extends u{constructor(t){super(t);this.data=t}txType=ac.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Er(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as oc}from"@msafe/sui3-utils";var Ne=class o extends u{constructor(t){super(t);this.data=t}txType=oc.Other;txSubType="FarmingStake";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Lr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as rc}from"@msafe/sui3-utils";var Le=class o extends u{constructor(t){super(t);this.data=t}txType=rc.Other;txSubType="FarmingUnstake";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await jr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as ic}from"@msafe/sui3-utils";var je=class o extends u{constructor(t){super(t);this.data=t}txType=ic.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await vr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as sc}from"@msafe/sui3-utils";var Ue=class o extends u{constructor(t){super(t);this.data=t}txType=sc.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Ar(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as dc}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as cc}from"@cetusprotocol/aggregator-sdk";import{Transaction as lc}from"@mysten/sui/transactions";var Ur=async(o,e,t)=>{let n=xr(t,e),a=new lc;return await n.fastRouterSwap({...o,routers:cc(o.routers),txb:a}),a};var Fe=class o extends u{constructor(t){super(t);this.data=t}txType=dc.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Ur(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as uc}from"@msafe/sui3-utils";var Fr=async(o,e,t)=>await vo(t,e).Vaults.deposit(o),qr=async(o,e,t)=>await vo(t,e).Vaults.withdraw(o);var qe=class o extends u{constructor(t){super(t);this.data=t}txType=uc.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Fr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as mc}from"@msafe/sui3-utils";var Ke=class o extends u{constructor(t){super(t);this.data=t}txType=mc.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await qr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as fc}from"@msafe/sui3-utils";import{Transaction as pc}from"@mysten/sui/transactions";var Kr={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},$r=async(o,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",o),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:a,periods:r,CLOCK_ADDRESS:i}=o,s=new pc;return r.forEach(c=>{s.moveCall({target:`${Kr.published_at}::router::redeem`,typeArguments:[Kr.cetus_coin_type],arguments:[s.object(n),s.object(a),s.pure(c),s.object(i)]})}),s};var $e=class o extends u{constructor(t){super(t);this.data=t}txType=fc.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await $r(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as bc}from"@msafe/sui3-utils";var Vr=async(o,e,t)=>await dt(t,e).XCetusModule.convertPayload(o),Hr=async(o,e,t)=>await dt(t,e).XCetusModule.redeemLockPayload(o),Gr=async(o,e,t)=>await dt(t,e).XCetusModule.redeemDividendV3Payload(o.veNftId,o.rewardList),Qr=async(o,e,t)=>await dt(t,e).XCetusModule.cancelRedeemPayload(o),zr=async(o,e,t)=>await dt(t,e).XCetusModule.redeemPayload(o);var Ve=class o extends u{constructor(t){super(t);this.data=t}txType=bc.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Qr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as hc}from"@msafe/sui3-utils";var He=class o extends u{constructor(t){super(t);this.data=t}txType=hc.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Gr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as gc}from"@msafe/sui3-utils";var Ge=class o extends u{constructor(t){super(t);this.data=t}txType=gc.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Vr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as yc}from"@msafe/sui3-utils";var Qe=class o extends u{constructor(t){super(t);this.data=t}txType=yc.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await zr(r,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Tc}from"@msafe/sui3-utils";var ze=class o extends u{constructor(t){super(t);this.data=t}txType=Tc.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:a}=t,{txbParams:r}=this.data;return await Hr(r,n,a)}static fromData(t){return new o(t)}};var Je=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:Cc.Other,txSubType:n,intentionData:{txbParams:{...t},action:n}}}async build(e){let{suiClient:t,account:n,network:a}=e,r;switch(e.txSubType){case"OpenAndAddLiquidity":r=ve.fromData(e.intentionData);break;case"IncreaseLiquidity":r=je.fromData(e.intentionData);break;case"DecreaseLiquidity":r=Oe.fromData(e.intentionData);break;case"RemoveLiquidity":r=Ue.fromData(e.intentionData);break;case"ClaimFeeAndMining":r=Ae.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":r=Pe.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":r=Me.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":r=_e.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":r=We.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":r=Be.fromData(e.intentionData);break;case"FarmingHarvest":r=Ee.fromData(e.intentionData);break;case"FarmingBatchHarvest":r=Re.fromData(e.intentionData);break;case"FarmingStake":r=Ne.fromData(e.intentionData);break;case"FarmingUnstake":r=Le.fromData(e.intentionData);break;case"xCETUSConvert":r=Ge.fromData(e.intentionData);break;case"xCETUSRedeemLock":r=ze.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":r=He.fromData(e.intentionData);break;case"xCETUSCancelRedeem":r=Ve.fromData(e.intentionData);break;case"xCETUSRedeem":r=Qe.fromData(e.intentionData);break;case"VestingRedeem":r=$e.fromData(e.intentionData);break;case"AggregatorSwap":r=Fe.fromData(e.intentionData);break;case"AddVaultsPosition":r=qe.fromData(e.intentionData);break;case"RemoveVaultsPosition":r=Ke.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:a})}};import{TransactionType as yl}from"@msafe/sui3-utils";import Ic from"sort-keys-recursive";var h=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Ic(this.data))}};import{getFullnodeUrl as Ye}from"@mysten/sui.js/client";var Ao={};cr(Ao,{contractId:()=>kc,default:()=>Oc,feeObjId:()=>vc,roleObjId:()=>xc,status:()=>wc,transaction:()=>Sc,upgradeCapObjId:()=>Ac,vaultObjId:()=>Dc});var Sc="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",wc="success",kc="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",xc="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Dc="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",vc="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Ac="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Oc={transaction:Sc,status:wc,contractId:kc,roleObjId:xc,vaultObjId:Dc,feeObjId:vc,upgradeCapObjId:Ac};var Oo={};cr(Oo,{contractId:()=>Bc,default:()=>Nc,feeObjId:()=>Mc,roleObjId:()=>_c,status:()=>Rc,transaction:()=>Pc,upgradeCapObjId:()=>Wc,vaultObjId:()=>Ec});var Pc="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Rc="success",Bc="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",_c="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ec="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Mc="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Wc="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Nc={transaction:Pc,status:Rc,contractId:Bc,roleObjId:_c,vaultObjId:Ec,feeObjId:Mc,upgradeCapObjId:Wc};var Lc=Ye("testnet"),jc=Ye("testnet"),Uc=Ye("mainnet"),Fc=Ye("mainnet"),qc="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Kc="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",$c="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Vc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Jr=Ao,Yr=Oo,Hc=new Map([["dev",{env:"dev",rpc:{url:Lc},backend:{url:qc},contract:Jr}],["stg",{env:"stg",rpc:{url:jc},backend:{url:Kc},contract:Jr}],["prev",{env:"prev",rpc:{url:Uc},backend:{url:$c},contract:Yr}],["prod",{env:"prod",rpc:{url:Fc},backend:{url:Vc},contract:Yr}]]);function Xr(o,e){let t=Hc.get(o);if(!t)throw new Error(`Env not supported: ${o}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}import{SuiClient as Qc}from"@mysten/sui.js/client";var C=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:a,context:r}=n;a?super(`[MPay] ${t}: ${a}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=r}};var Xe=class extends C{constructor(){super(11,"Backend is not specified")}};var Ze=class extends C{constructor(){super(1,"Wallet not connected")}};import mt,{AxiosError as Gc}from"axios";var ut=class extends C{constructor(e,t){super(10,e,{context:t})}};var tn=class o{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof Gc)throw new ut(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new ut(e.data.code)}throw new ut(e.status.toString())}async getIncomingStreams(e,t){let n=await mt.post(`${this.apiURL}/stream`,{recipient:e,...t});return o.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await mt.post(`${this.apiURL}/stream`,{sender:e,...t});return o.parseResponseData(n)}async getStreamHistory(e){let t=await mt.post(`${this.apiURL}/stream-events`,e),n=o.parseResponseData(t);return n.data.forEach(a=>{let r=a;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(e){let t=await mt.post(`${this.apiURL}/stream-info`,{address:e});return o.parseResponseData(t)}async getAllRecipients(e,t){let n=await mt.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return o.parseResponseData(n)}async getAllSenders(e,t){let n=await mt.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return o.parseResponseData(n)}};var pt=class o{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Qc({url:e.rpc.url}),e.backend&&(this._backend=new tn(e.backend.url))}static new(e,t){let n=Xr(e,t);return new o(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Xe;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new Ze;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as bl,normalizeStructTag as hl,normalizeSuiAddress as Si}from"@mysten/sui.js/utils";import{TransactionBlock as sn}from"@mysten/sui.js/transactions";import{TransactionBlock as si}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as ci,normalizeStructTag as Xc}from"@mysten/sui.js/utils";var Po=50n,en=10000n,Zr=25n,Ro=100000000n;var q=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},vt=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},z=class o{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let a=i=>new o(t.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return a(r)}})}moveArg(){return this.result}};import{Buffer as ti}from"buffer";import{normalizeSuiAddress as zc}from"@mysten/sui.js/utils";var At=class extends C{constructor(e,t){super(3,e,{context:t})}};var nn=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let n=this.callResult(e);return this.returnValue(n,t)}getAddress(e=0,t=0){let[n,a]=this.getValue(e,t);if(a!=="address")throw new At("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return zc(ti.from(n).toString("hex"))}getU64(e=0,t=0){let[n,a]=this.getValue(e,t);if(a!=="u64")throw new At("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return ti.from(n).readBigInt64LE()}};import{bcs as ni}from"@mysten/sui.js/bcs";var S=class extends C{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var ai={groupId:"string",name:"string"},Jc=64;function oi(o){return ri(o),ni.ser(ai,o).toString("base64")}function Ot(o){let e=ni.de(ai,o,"base64");return ri(e),e}function ri(o){if(!ei(o.name))throw new S("Invalid metadata: Name contains unknown character");if(!ei(o.groupId))throw new S("Invalid metadata: Group ID contains unknown character");if(o.name.length>Jc)throw new S("Invalid metadata: Name exceed max length 64")}function ei(o){return/^[\x00-\x7F]+$/.test(o)}import{normalizeStructTag as an}from"@mysten/sui.js/utils";function on(o,e){return an(o)===an(e)}function J(o,e){return an(o)===an(e)}var rn="txn.gas";import{nanoid as Yc}from"nanoid";function ii(){return Yc()}var ot=class o{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:oi({name:e.name,groupId:ii()}),coinType:Xc(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new si,n=this.calculateFeesInternal(e),a=this.getCreateStreamCoinRequests(e,n),r=await this.wallet.requestCoins(a),i=await this.addMergeCoins(t,r[0]),s;a.length>1?s=await this.addMergeCoins(t,r[1]):s=i;for(let c=0;c<e.recipients.length;c++){let l=e.recipients[c],d=this.amountForRecipient(l,e.numberEpoch),m=this.getStreamFeeLocal(d),[p]=t.splitCoins(i,[t.pure(d+m,"u64")]),[f]=t.splitCoins(s,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new z(p),flatFeeCoin:new z(f),metadata:e.metadata,recipient:l.address,timeStart:e.startTime,cliff:l.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=o.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:Po,denominator:en},claimFeePercent:{numerator:Zr,denominator:en},flatFeePerStream:Ro}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(a=>e.object(a))),n=e.object(t.primaryCoin)):t.primaryCoin===rn?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return on(n,ci)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:ci,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((a,r)=>{let i=this.amountForRecipient(r,e.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:a.totalAmount+i,streamFeeAmount:a.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return Ro}getStreamFeeLocal(e){return e*Po/en}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new si,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new nn(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as di}from"@mysten/sui.js/transactions";var li="0x0000000000000000000000000000000000000000000000000000000000000006";var ft=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(di.MoveCall({target:n,arguments:t.arguments.map(a=>a instanceof vt?a.moveArgs(e):a instanceof q?a.moveArg(e):a instanceof z?a.moveArg():e.pure(a)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,n=[],a=[]){e.add(di.MoveCall({target:t,arguments:n.map(r=>r instanceof vt?r.moveArgs(e):r instanceof q?r.moveArg(e):r instanceof z?r.moveArg():e.pure(r)),typeArguments:a}))}makeObject(e){return typeof e=="string"?new q(e):e}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(li)}};var bt=class o extends ft{constructor(t,n){super(o.ModuleName,t,n);this.config=t;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(t,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:o.MethodName.set_streaming_fee,arguments:[a,r,n],typeArgs:[]})}setStreamingFlatFee(t,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:o.MethodName.set_streaming_flat_fee,arguments:[a,r,n],typeArgs:[]})}setClaimFee(t,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:o.MethodName.set_claim_fee,arguments:[a,r,n],typeArgs:[]})}streamingFee(t,n){let a=this.feeObject();return this.addContractCall(t,{method:o.MethodName.streaming_fee,arguments:[a,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:o.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:o.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var K=class o extends ft{constructor(t,n){super(o.ModuleName,t,n);this.config=t;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(t,n){let a=this.feeObject(),r=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(t,{method:o.MethodName.create_stream,arguments:[a,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(t,n){let a=this.makeObject(n.streamId);return this.addContractCall(t,{method:o.MethodName.set_auto_claim,arguments:[a,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(t,{method:o.MethodName.cancel_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStream(t,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(t,{method:o.MethodName.claim_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let a=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(t,{method:o.MethodName.claim_stream_by_proxy,arguments:[a,r,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream_by_proxy}`}};var ht=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new bt(t,e),this.streamContract=new K(t,e)}feeContract;streamContract;async createStreams(e){let t=ot.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new ot(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let a=new sn;return this.streamContract.setAutoClaim(a,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new sn;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new sn;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new sn;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};import{normalizeStructTag as Bo,SUI_TYPE_ARG as Zc}from"@mysten/sui.js/utils";import{Duration as ui}from"luxon";var cn=class extends C{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var tl=1e3,ln=class{constructor(e){this.globals=e;this.coinMetaHelper=new _o(e.suiClient),this.createStreamHelper=new ht(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new cn(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new S("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},n=e.totalAmount*t.numerator/t.denominator,a=(e.totalAmount-n)/e.steps,i={realTotalAmount:a*e.steps+n,cliffAmount:n,amountPerStep:a};return this.validateStreamAmount(i,e.totalAmount),i}calculateTimelineByInterval(e){if(e.steps===0n)throw new S("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),n={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new S("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(ui.fromMillis(Number(t*e.steps))),a={timeStart:e.timeStart,timeEnd:n,interval:ui.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(a),a}async getBalance(e,t){let n=await this.globals.suiClient.getBalance({owner:e,coinType:t}),a=await this.getCoinMeta(t);return{...n,coinType:Bo(n.coinType),coinMeta:a}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),n=await Promise.all(t.map(a=>this.getCoinMeta(a.coinType)));return t.map((a,r)=>({...a,coinType:Bo(a.coinType),coinMeta:n[r]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new S("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new S("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<tl)throw new S("Interval shall be at least 1 second","interval",e.interval)}},_o=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=Bo(e||Zc);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this.coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};import{normalizeStructTag as fi,normalizeSuiAddress as bn}from"@mysten/sui.js/utils";import{DateTime as bi}from"luxon";import{TransactionBlock as pn}from"@mysten/sui.js/transactions";import{normalizeStructTag as pi,parseStructTag as al}from"@mysten/sui.js/utils";import{DateTime as ol}from"luxon";var dn=class extends C{constructor(){super(7,"Connected wallet is not creator")}};var Pt=class extends C{constructor(){super(8,"Connected wallet is not recipient")}};var Rt=class extends C{constructor(e,t){super(6,e,{context:t})}};var k=class extends C{constructor(e,t={}){super(0,e,t)}};var un=class extends C{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};import{DateTime as el,Duration as nl}from"luxon";var mi=(1n<<64n)-1n,mn=1e3;function Eo(o){let e;typeof o=="number"?e=o:typeof o=="bigint"?e=Number(o):e=o.toMillis();let t=Math.round(e/mn);return el.fromMillis(t*mn)}function Mo(o){let e;typeof o=="number"?e=o:typeof o=="bigint"?e=Number(o):e=o.toMillis();let t=Math.round(e/mn);return nl.fromMillis(t*mn)}var Y=class o{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new K(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await o.fetchStreamData(e,t);return new o(e,t,n)}static fromObjectData(e,t,n){let a=o.parseRawStreamData(t,n);return new o(e,t,a)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await o.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new k("Object Id does not align");this.rawData=o.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new dn;let e=new pn;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Pt;let e=new pn;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Pt;let t=new pn;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new pn;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return pi(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 Mo(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Ot(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Ot(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Eo(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return Mo(t)}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:Eo((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 e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===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===mi?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=ol.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return o.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new un(e):new Rt(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new Rt("Unexpected object type",{gotType:n.dataType});let{typeParams:a}=al(n.type),r=pi(a[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};var gt=class extends C{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function No(o){let e=[];for(;await o.hasNext();){let t=await o.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Wo=class{constructor(e){this.requester=e;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)}},yt=class{constructor(e){this.requester=e;this.pager=new Wo(e),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 rl=25;async function jo(o,e,t){let n=new Bt(e),a=new _t(o,n,t);return await No(a)}var Bt=class{constructor(e){this.ids=e;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]}},_t=class extends yt{constructor(t,n,a){super(new Lo(t,n,a));this.suiClient=t;this.idIter=n;this.options=a}},Lo=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||rl,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&e.push(r)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),n;if(this.filter){let{filter:a}=this;n=t.filter(r=>a?.(r))}else n=t;return{data:n,hasNext:await this.stringIter.hasNext()}}};var fn=class o{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new gt("stream size 0");let n=t.map(r=>r.groupId);if(new Set(n).size!==1)throw new S("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await jo(e.suiClient,t);return n.forEach(a=>{if(!a)throw new k("stream group object data undefined")}),o.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let a=await o.parseGroupStreams(e,t,n);return new o(e,a)}static checkStreamGroup(e){let t=e.map(r=>r.groupCommonInfo),n=t[0],a=!0;return t.forEach(r=>{il(n,r)||(a=!1)}),a}async refresh(){let e=await jo(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[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(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let a=n.map((r,i)=>Y.fromObjectData(e,t[i],r)).filter(r=>!!r);if(new Set(a.map(r=>r.groupId)).size!==1)throw new gt("Not same group ID");if(!this.checkStreamGroup(a))throw new gt("Not same stream settings");return a}};function il(o,e){return o.name===e.name&&o.groupId===e.groupId&&o.creator===e.creator&&o.start.toMillis()===e.start.toMillis()&&o.interval.toMillis()===e.interval.toMillis()&&o.steps===e.steps&&o.cancelable===e.cancelable}var Et=class o{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await hn.newIncoming(e);return new o(t,e.pageSize)}static async newOutgoing(e){let t=await hn.newOutgoing(e);return new o(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},hn=class o{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await gn.newIncomingQuery(e);return new o(t)}static async newOutgoing(e){let t=await gn.newOutgoingQuery(e);return new o(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new k("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new k("No more results");return e}},gn=class o{constructor(e,t,n,a){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=a;this.current=0;let r=new Bt(n.flat().map(i=>i.streamId));this.objectIter=new _t(e.suiClient,r)}current=0;objectIter;static async newIncomingQuery(e){let t=ul(e.query),n=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(n,t)).filter(s=>bn(s.recipient)===bn(n)),i=hi(r);return new o(e.globals,n,i,e.query)}static async newOutgoingQuery(e){let t=ml(e.query),n=await e.globals.walletAddress(),a=await e.globals.backend.getOutgoingStreams(n,t),r=hi(a);return new o(e.globals,n,r,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await ll(this.globals,e[0].streamId,this.objectIter);return this.current++,gi(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await dl(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,cl(t,this.query)?t:this.doNextRequest()}throw new k("Stream group with no stream")}};function hi(o){let e=new Map;return o.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>bi.fromISO(n[0].createDate).toMillis()-bi.fromISO(t[0].createDate).toMillis())}function gi(o,e){if(e===void 0)return!0;let t=sl(o,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?o.progress.claimable!==0n:o.progress.claimable===0n;return t&&n}return t}function sl(o,e){return e===void 0?!0:Array.isArray(e)?e.includes(o.progress.status):o.progress.status===e}function cl(o,e){if(!e)return!0;let t=!1;return o.streams.forEach(n=>{gi(n,e)&&(t=!0)}),t}async function ll(o,e,t){let n=await yi(t,e);return Y.fromObjectData(o,e,n)}async function dl(o,e,t){let n=[];for(;n.length<e.length;){let a=await yi(t,e[n.length]);n.push(a)}return fn.newFromObjectResponse(o,e,n)}async function yi(o,e){if(!await o.hasNext())throw new k("object iterator has been consumed");let t=await o.next();if(!t||t.error||t.data===void 0||t.data===null)throw new k("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new k("stream id not aligned");return t}function ul(o){return{status:Uo(o?.status),coinType:Ti(o?.coinType),sender:Ci(o?.sender)}}function ml(o){return{status:Uo(o?.status),coinType:Ti(o?.coinType),recipient:Ci(o?.recipient)}}function Uo(o){return o===void 0||o.length===0?"all":Array.isArray(o)?o.reduce((e,t)=>{let n=Uo(t);return!e||e===n?n:"all"},void 0):pl(o)}function pl(o){switch(o){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new S("Unknown stream filtered status")}}function Ti(o){if(o)return Array.isArray(o)?o.length!==0?o.map(e=>fi(e)):void 0:fi(o)}function Ci(o){if(o)return Array.isArray(o)?o.length!==0?o.map(e=>bn(e)):void 0:bn(o)}var yn=class extends C{constructor(t,n,a){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:n,gotAmount:a}});this.coinType=t;this.requestAmount=n;this.gotAmount=a}};var fl=25;async function Ii(o,e,t,n="0x2::sui::SUI",a=fl){let r=new Fo(o,e,n,a),i=BigInt(0),s=[];for(;await r.hasNext()&&i<t;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<t)throw new yn(n,t,i);return s}var Fo=class extends yt{constructor(t,n,a,r){super(new qo(t,n,a,r));this.suiClient=t;this.owner=n;this.coinType=a;this.reqPageSize=r}},qo=class{constructor(e,t,n,a){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=a;if(a<=0)throw new k("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var Ko=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Tn=class{constructor(e){this.account=e}async address(){return this.account.address}},$o=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(on(e.coinType,bl))return{primaryCoin:rn};if(e.amount<=0)throw new S("Invalid coin request","coinAmount",e.amount);let t=await Ii(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new k("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},Cn=class{globals;helper;constructor(e,t){this.globals=pt.new(e,t),this.helper=new ln(this.globals)}connectSingleWallet(e){let t=new $o(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new Ko(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return Y.new(this.globals,e)}async getIncomingStreams(e,t=10){return Et.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return Et.newOutgoing({globals:this.globals,query:e,pageSize:t})}async getCoinTypesForStreamFilter(){let e=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(e)).map(n=>hl(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(a=>Si(a))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(a=>Si(a))}get wallet(){return this.globals.wallet}builder(){return new ht(this.globals)}};var E=class extends h{application="mpay";getClient(e,t){let n=new Cn(e==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Tn(t)),n}};var Mt=class extends E{constructor(t){super(t);this.data=t}txType=yl.Stream;txSubType="Cancel";async build(t){let{network:n,account:a}=t;return(await this.getClient(n,a).getStream(this.data.streamId)).cancel()}};import{TransactionType as Tl}from"@msafe/sui3-utils";var Wt=class extends E{constructor(t){super(t);this.data=t}txType=Tl.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:a}=t;return(await this.getClient(n,a).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Cl}from"@msafe/sui3-utils";var Nt=class extends E{constructor(t){super(t);this.data=t}txType=Cl.Stream;txSubType="Claim";async build(t){let{network:n,account:a}=t;return(await this.getClient(n,a).getStream(this.data.streamId)).claim()}};import{TransactionType as Il}from"@msafe/sui3-utils";var Lt=class extends E{constructor(t){super(t);this.data=t}txType=Il.Stream;txSubType="CreateStream";async build(t){let{network:n,account:a}=t;return this.getClient(n,a).createStream(this.data)}};import{bcs as wi}from"@mysten/sui.js/bcs";import{normalizeStructTag as Sl,normalizeSuiAddress as jt}from"@mysten/sui.js/utils";var Tt=class o{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return o.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return o.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return jt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return o.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return wi.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return jt(e.value.Object.ImmOrOwned.objectId)}return jt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return jt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return jt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return wi.de(t,new Uint8Array(n))}typeArg(e){return Sl(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var In=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&J(t.target,this.contract.createStreamTarget));if(e.length===0)throw new k("No create stream transactions");return e.map(t=>new Tt(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:a}=Ot(t),r=e.decodeInputAddress(5),i=e.decodeInputU64(6),s=e.decodeInputU64(7),c=e.decodeInputU64(8),l=e.decodeInputU64(9),d=e.decodeInputU64(10),m=e.decodeInputBool(11),p=e.typeArg(0);return{name:n,groupId:a,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:m,coinType:p}}aggregateGroupStreamInfo(e){if(new Set(e.map(a=>JSON.stringify({name:a.name,groupId:a.groupId,timeStart:String(a.timeStart),epochInterval:String(a.epochInterval),totalEpoch:String(a.totalEpoch),cancelable:a.cancelable,coinType:a.coinType}))).size!==1)throw new S("Stream group not have common info");let n=e.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:n,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new K(this.globals.envConfig.contract,this.globals)}get feeContract(){return new bt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ot(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var Sn=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new K(e.envConfig.contract,e)}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(t=>t.kind==="MoveCall"&&J(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&J(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&J(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&J(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&J(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new In(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new Tt(e,this.txb)}};import{TransactionType as wl}from"@msafe/sui3-utils";var Ut=class extends E{constructor(t){super(t);this.data=t}txType=wl.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:a}=t;return(await this.getClient(n,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var wn=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:n}=e,a=pt.new(t==="sui:mainnet"?"prod":"dev"),i=new Sn(a,n).decode(),s;switch(i.type){case"CreateStream":s=new Lt(i.info);break;case"SetAutoClaim":s=new Ut({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Nt({streamId:i.streamId});break;case"ClaimByProxy":s=new Wt({streamId:i.streamId});break;case"Cancel":s=new Mt({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:s.txType,txSubType:s.txSubType,intentionData:s.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Lt(t);break;case"Claim":n=new Nt(t);break;case"ClaimByProxy":n=new Wt(t);break;case"SetAutoClaim":n=new Ut(t);break;case"Cancel":n=new Mt(t);break;default:throw new Error("not implemented")}return n.build({...e})}};import{TransactionDefaultApplication as Dl,TransactionSubTypes as ki}from"@msafe/sui3-utils";import{buildCoinTransferTxb as kl}from"@msafe/sui3-utils";var kn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a}=t;return kl(n,this.data,a.address)}static fromData(t){return new o(t)}};import{buildObjectTransferTxb as xl}from"@msafe/sui3-utils";var xn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a}=t;return xl(n,this.data,a.address)}static fromData(t){return new o(t)}};var Dn=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Dl}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:n}=e,a;switch(e.txSubType){case ki.assets.coin.send:a=kn.fromData(e.intentionData);break;case ki.assets.object.send:a=xn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:t,account:n})}};import{TransactionType as Fl}from"@msafe/sui3-utils";var xi=!1,Ft={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Vo(){if(!xi)try{let o=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:a}=o;e&&(Ft.ProtocolPackage=e),t&&(Ft.borrowFee=t),n&&(Ft.borrowFeeAddress=n),a&&(Ft.pool=a),xi=!0}catch(o){console.error(o.message)}}var L=Ft;import{TransactionType as it}from"@msafe/sui3-utils";import{bcs as Di}from"@mysten/sui.js/bcs";import{normalizeStructTag as Al,normalizeSuiAddress as qt}from"@mysten/sui.js/utils";var vn=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${L.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${L.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${L.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(a=>a.kind==="MoveCall"&&a.target===e);return this.transactions.find(a=>a.kind==="MoveCall"&&a.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${L.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(a=>a.kind==="MoveCall"&&a.target===e);return!!(this.transactions.find(a=>a.kind==="MoveCall"&&a.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${L.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${L.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${L.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values(L.pool).find(n=>n.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:it.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:it.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:it.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${L.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===t){let a=new An(n,this.txb),r=a.decodeInputU8(3),i=a.decodeInputU64(5);e.push({assetId:r,amount:i})}}),{txType:it.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:it.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:it.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:it.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(L.ProtocolPackage));return new An(e,this.txb)}},An=class o{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return o.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return o.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return qt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return o.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Di.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return qt(e.value.Object.ImmOrOwned.objectId)}return qt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return qt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return qt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Di.de(t,new Uint8Array(n))}typeArg(e){return Al(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{depositCoin as Ol,withdrawCoin as Pl,repayDebt as Rl,borrowCoin as Bl,claimAllRewardsPTB as _l,claimAllRewardsResupplyPTB as El}from"navi-sdk";async function Ct(o,e,t,n){return await Ol(o,e,t,n),o}async function vi(o,e,t,n){let[a]=await Pl(o,e,t);return o.transferObjects([a],o.pure(n)),o}async function Ai(o,e,t,n){let[a]=await Bl(o,e,t);return o.transferObjects([a],o.pure.address(n)),o}async function Ho(o,e,t,n){return await Rl(o,e,t,n),o}async function Oi(o,e){return await _l(o,e)}async function Pi(o,e){return await El(o,e)}var On=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await Oi(t.suiClient,t.account.address)}static fromData(t){return new o(t)}};var Pn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await Pi(t.suiClient,t.account.address)}static fromData(t){return new o(t)}};import{TransactionBlock as Wl}from"@mysten/sui.js/transactions";import{pool as Ml}from"navi-sdk";function $(o){return Object.values(Ml).find(e=>String(e.assetId)===String(o))}var Rn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:a}=this.data,r=new Wl;console.log("build",this.data);let i=$(n);return await Ai(r,i,a,t.account.address)}static fromData(t){return new o(t)}};import{TransactionBlock as Nl}from"@mysten/sui.js/transactions";async function It(o,e,t){let n=await o.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Bn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a}=t,{assetId:r,amount:i}=this.data,s=new Nl;console.log("build",this.data);let c=$(r);if(r===0){let[p]=s.splitCoins(s.gas,[i]);return await Ct(s,c,p,i)}let l=await It(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let p=1;for(;p<l.data.length;)s.mergeCoins(d,[l.data[p].coinObjectId]),p++}return await Ct(s,c,s.object(d),i)}static fromData(t){return new o(t)}};import{TransactionBlock as Ll}from"@mysten/sui.js/transactions";var _n=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a}=t,{assetId:r,amount:i}=this.data,s=new Ll;console.log("build",this.data);let c=$(r);if(r===0){let[m]=s.splitCoins(s.gas,[i]);return Ho(s,c,m,i)}let l=await It(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let m=1;for(;m<l.data.length;)s.mergeCoins(d,[l.data[m].coinObjectId]),m++}return Ho(s,c,s.object(d),i)}static fromData(t){return new o(t)}};import{TransactionBlock as jl}from"@mysten/sui.js/transactions";var En=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:a}=this.data,r=new jl;console.log("build",this.data);let i=$(n);return await vi(r,i,a,t.account.address)}static fromData(t){return new o(t)}};import{TransactionBlock as Ul}from"@mysten/sui.js/transactions";var Mn=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a}=t,{list:r}=this.data,i=new Ul;console.log("build",this.data);for(let s=0;s<r.length;s++){let{assetId:c,amount:l}=r[s],d=$(c);if(c===0){let[f]=i.splitCoins(i.gas,[l]);await Ct(i,d,f,l);continue}let m=await It(n,a.address,d.type);if(!m.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let p=m.data[0].coinObjectId;if(m.data.length>=2){let f=1;for(;f<m.data.length;)i.mergeCoins(p,[m.data[f].coinObjectId]),f++}await Ct(i,d,i.object(p),l)}return i}static fromData(t){return new o(t)}};var Wn=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await Vo();let{transactionBlock:t}=e,a=new vn(t).decode();return{txType:Fl.Other,txSubType:a.type,intentionData:a.intentionData}}async build(e){let{suiClient:t,account:n}=e,a;switch(await Vo(),e.txSubType){case"EntryDeposit":a=Bn.fromData(e.intentionData);break;case"EntryBorrow":a=Rn.fromData(e.intentionData);break;case"EntryRepay":a=_n.fromData(e.intentionData);break;case"EntryWithdraw":a=En.fromData(e.intentionData);break;case"EntryMultiDeposit":a=Mn.fromData(e.intentionData);break;case"ClaimReward":a=On.fromData(e.intentionData);break;case"EntryClaimAndDeposit":a=Pn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:t,account:n})}};import{TransactionSubTypes as ql,TransactionType as Ri}from"@msafe/sui3-utils";import{fromHex as Kl}from"@mysten/bcs";import{Transaction as $l}from"@mysten/sui/transactions";import Vl from"sort-keys-recursive";var Bi="msafe-plain-tx",_i=ql.others.plain,Go=class o{constructor(e){this.data=e}application=Bi;txType=Ri.Other;txSubType=_i;serialize(){return JSON.stringify(Vl(this.data))}async build(e){return $l.from(Kl(this.data.content))}static fromData(e){return new o(e)}},Nn=class{application;supportSDK="@mysten/sui";constructor(){this.application=Bi}async deserialize(e){let{content:t}=e.appContext;return{txType:Ri.Other,txSubType:_i,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:a}=e;return Go.fromData(e.intentionData).build({suiClient:t,network:n,account:a})}};import{SuiClient as Ei}from"@mysten/sui/client";import{Transaction as Xl}from"@mysten/sui/transactions";import{SuiClient as Jo}from"@mysten/sui.js/client";import{TransactionBlock as Zl}from"@mysten/sui.js/transactions";import{RequestManager as zl,HTTPTransport as Jl,Client as Yl}from"@open-rpc/client-js";var Hl={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},Qo=class extends Error{},Ln=class extends Qo{code;type;constructor(e,t){super(e),this.code=t,this.type=Hl[t]??"ServerError"}};function Gl(o){let e=new URL(o);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var Ql={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},jn=class{endpoint;options;#n=0;#o=0;#t=null;#e=null;#r=new Set;#a=new Map;constructor(e,t={}){this.endpoint=e,this.options={...Ql,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=Gl(this.endpoint))}async makeRequest(e,t){let n=await this.#i();return new Promise((a,r)=>{this.#n+=1,this.#a.set(this.#n,{resolve:a,reject:r,timeout:setTimeout(()=>{this.#a.delete(this.#n),r(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:a,result:r})=>{if(a)throw new Ln(a.message,a.code);return r})}#i(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#o=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#o++,this.#o<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(a){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:a}));return}if("id"in n&&n.id!=null&&this.#a.has(n.id)){let{resolve:a,timeout:r}=this.#a.get(n.id);clearTimeout(r),a(n)}else if("params"in n){let{params:a}=n;this.#r.forEach(r=>{r.subscriptionId===a.subscription&&a.subscription===r.subscriptionId&&r.onMessage(a.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#r].map(e=>e.subscribe(this)))}async subscribe(e){let t=new zo(e);return this.#r.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},zo=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var X=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:a}){let r=new Jl(a?.url??e,{headers:{"Content-Type":"application/json",...a?.headers}});this.rpcClient=new Yl(new zl([r])),this.websocketClient=new jn(t??e,n)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var Un=class o{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new o;for(let n=0;n<e.length;n++){let a=e[n];switch(a.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(a);break;case"@mysten/sui":t.addHelper(a);break;default:throw new Error(`${a.application}: ${a.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new Xo(e))}addHelper(e){this.apps.set(e.application,new Yo(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},Yo=class{constructor(e){this.helper=e}async deserialize(e){let t=new Ei({transport:new X({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=new Jo({transport:new X({url:e.clientUrl,rpc:{url:e.clientUrl}})}),a=await e.transactionBlock.build({client:n}),r=Xl.from(a);return this.helper.deserialize({...e,suiClient:t,transaction:r})}async build(e){let t=new Ei({transport:new X({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let a=await this.helper.build({...e,suiClient:t});a.setSender(e.account.address);let r=await a.build({client:t});return Zl.from(r)}},Xo=class{constructor(e){this.helper=e}async deserialize(e){let t=new Jo({transport:new X({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new Jo({transport:new X({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};import{TransactionType as ld}from"@msafe/sui3-utils";import{Scallop as ji}from"@scallop-io/sui-scallop-sdk";import{TransactionType as D}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as Li}from"@scallop-io/sui-scallop-sdk";import{parseStructTag as td}from"@mysten/sui/utils";var Z=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(n=>`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:n,module:a,name:r}=td(t);return e?e.package===n&&e.module===a&&e.function===r:!1}isMoveCall(e){return e.$kind==="MoveCall"&&!!e.MoveCall}filterMoveCallCommands(e,t){return this.isMoveCall(e)&&this.matchMoveCallCommand(e.MoveCall,t)}getMoveCallCommands(e){let t=new Set(e),n=e.reduce((r,i,s)=>(r[i]=s,r),{}),a=[];return this.commands.forEach(r=>{this.isMoveCall(r)&&r.MoveCall&&t.has(r.MoveCall.package)&&(a[n[r.MoveCall.package]]=r.MoveCall)}),a}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};import{bcs as Zo}from"@mysten/sui/bcs";import{normalizeStructTag as ed,normalizeSuiAddress as Kt}from"@mysten/sui/utils";var tr=class o{constructor(e,t){this.moveCall=e;this.transaction=t;this.cmdIdx=e?.MoveCall?t.getData().commands.findIndex(n=>{if(n.$kind==="MoveCall"){let a=`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,r=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return a===r}return!1}):-1}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return o.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return o.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return Kt(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let n=this.getInputParam(e);return o.getPureInputValue(n,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure,a=Zo[t];return Zo[t].parse(new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Kt(e.value.Object.ImmOrOwned.objectId)}return Kt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Kt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Kt(e.value.Object.Shared.objectId)}static getPureInput(e){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let t=e.value.Pure;return Zo.U64.parse(new Uint8Array(t))}typeArg(e){return ed(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},T=tr;var er=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(T.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},O=er;import{normalizeStructTag as Mi,SUI_CLOCK_OBJECT_ID as Wi,SUI_TYPE_ARG as nd}from"@mysten/sui/utils";var Ni=async(o,e)=>{let t=await o.suiKit.client().getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let a=t.data.content.fields.lock_key?.fields.name;if(!a)return!1;let r=o.address.get("borrowIncentive.object");return a===`${r.slice(2)}::incentive_account::IncentiveProgramLockKey`},St={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},M={unstakeObligation:(o,e,t)=>o.moveCall(`${St.id}::user::unstake`,[St.incentivePools,St.incentiveAccounts,o.object(e),o.object(t),Wi],[Mi(nd)]),redeem_rewards:(o,e,t,n)=>o.moveCall(`${St.id}::user::redeem_rewards`,[St.incentivePools,St.incentiveAccounts,o.object(e),o.object(t),Wi],[Mi(n)])};var Fn=class extends Z{decode(){if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMigrateScoinTransaction(){return this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`),t=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`);return e&&t}isUnstakeAndWithdrawTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`),t=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`);return e&&t}isStakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`),t=this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return e&&t}isDepositCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return e&&t}isBorrowWithReferralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return e&&t}isUnstakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return e||t}isOpenObligationTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let e=this.hasMoveCallCommand(`${Li}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new T(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new T(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new T(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Li}::user::redeem_rewards`)).map(t=>new T(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new T(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new T(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new T(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new T(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new T(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new T(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new T(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new T(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new T(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new T(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new T(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new T(e,this.transaction)}decodeMigrateScoin(){return{txType:D.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let t=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),a=this.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:D.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:a,veScaKey:e}}}decodeOpenObligation(){return{txType:D.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new O(t,this.transaction).getAmountInput().reduce((a,r)=>a+r,0);return{txType:D.Other,type:"SupplyLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLending(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperRedeem.getNestedInputParam(2),n=new O(t,this.transaction).getAmountInput().reduce((a,r)=>a+r,0);return{txType:D.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),n=new O(t,this.transaction).getAmountInput().reduce((a,r)=>a+r,0);return{txType:D.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeDepositCollateral(){let e=this.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),t=this.helperDepositCollateral.getNestedInputParam(3),n=new O(t,this.transaction).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:D.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:a,collateralCoinName:e}}}decodeWithdrawCollateral(){let e=this.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),t=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),a=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:D.Other,type:"WithdrawCollateral",intentionData:{amount:t,collateralCoinName:e,obligationKey:a,obligationId:n}}}decodeBorrow(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),a=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"Borrow",intentionData:{amount:t,coinName:e,obligationKey:a,obligationId:n}}}decodeBorrowWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),a=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:r,obligationId:a,veScaKey:t}}}decodeBorrowWithReferral(){let e=this.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),a=this.helperBorrowWithReferral.decodeSharedObjectId(1),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:D.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:r,obligationId:a,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new O(t,this.transaction).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"Repay",intentionData:{amount:n,obligationId:a,coinName:e}}}decodeRepayWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),a=new O(n,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:D.Other,type:"RepayWithBoost",intentionData:{amount:a,obligationId:r,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);t=new O(r,this.transaction).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&t===0){let r=this.helperStake.getNestedInputParam(2);t=new O(r,this.transaction).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),a=this.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"StakeSpool",intentionData:{amount:t,marketCoinName:a,stakeAccountId:e}}}decodeUnstakeSpool(){let e=this.helperUnstake.decodeOwnedObjectId(1),t=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),a=this.utils.parseCoinNameFromType(n);return{txType:D.Other,type:"UnstakeSpool",intentionData:{amount:t,marketCoinName:a,stakeAccountId:e}}}decodeSupplyWithStakeSpool(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new O(t,this.transaction).getAmountInput().reduce((r,i)=>r+i,0),a;return this.isCreateStakeAccountTransaction()||(a=this.helperStake.decodeOwnedObjectId(1)),{txType:D.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:a}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(a=>{let r=a.decodeOwnedObjectId(1),i=a.decodeInputU64(2);e.push({id:r,coin:i})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let a=this.helperBurnScoin.getNestedInputParam(1);n=new O(a,this.transaction).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:D.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(a=>{let r=a.decodeOwnedObjectId(2),i=a.typeArg(0),s=this.utils.parseCoinNameFromType(i);e.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(a=>{let r=a.decodeSharedObjectId(3),i=a.decodeOwnedObjectId(4),s=this.utils.parseCoinNameFromType(a.typeArg(0));t.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(a=>{let r=a.decodeSharedObjectId(2),i=a.decodeOwnedObjectId(3),s=this.utils.parseCoinNameFromType(a.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:D.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};import{TransactionType as ar}from"@msafe/sui3-utils";var qn=class extends Z{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new T(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new T(e,this.transaction)}decodeCreateReferralLink(){return{txType:ar.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:ar.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:ar.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};import{TransactionType as $t}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as ad}from"@scallop-io/sui-scallop-sdk";var Kn=class extends Z{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new T(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new T(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new T(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new T(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new T(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${ad}::user::unstake`));return new T(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake`));return new T(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new T(e,this.transaction)}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:$t.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new O(e,this.transaction).getAmountInput().reduce((b,y)=>b+y,0),a=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,m,p,f=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let b=0;b<f.length;b++)f[b].condition.length>1&&([p,m]=f[b].condition,l=!0,d=f[b].isOld);return{txType:$t.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:m,obligationKey:p,veScaKey:a,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],a=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:a,isOld:!1},{condition:r,isOld:!1}];for(let m=0;m<d.length;m++)d[m].condition.length>1&&([l,c]=d[m].condition,i=!0,s=d[m].isOld);return{txType:$t.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:c,obligationKey:l,veScaKey:t,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new O(e,this.transaction).getAmountInput().reduce((f,b)=>f+b,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,m,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let f=0;f<p.length;f++)p[f].condition.length>1&&([m,d]=p[f].condition,c=!0,l=p[f].isOld);return{txType:$t.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,unlockTime:t,obligationId:d,obligationKey:m,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let n=new O(e,this.transaction).getAmountInput().reduce((f,b)=>f+b,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,m,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let f=0;f<p.length;f++)p[f].condition.length>1&&([m,d]=p[f].condition,c=!0,l=p[f].isOld);return{txType:$t.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:d,obligationKey:m,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}};import od from"sort-keys-recursive";var g=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify(od(this.data))}isObligationLocked=async(e,t)=>{let n=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),a=!1;return n&&n?.data.content?.dataType==="moveObject"&&"lock_key"in n.data.content.fields&&(a=!!n.data.content.fields.lock_key),a};async buildTxWithRefreshObligation(e,t,n){let a=e.builder.createTxBlock();a.setSender(t.walletAddress);let{obligationId:r,obligationKey:i}=t;return await this.isObligationLocked(e.suiKit.client(),r)?(await a.unstakeObligationQuick(r,i),await n(e,a,t),await a.stakeObligationWithVeScaQuick(r,i,t.veScaKey)):await n(e,a,t),a}};var $n=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:a,amount:r,obligationId:i,obligationKey:s}=this.data,c=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:c,obligationId:i,obligationKey:s},async(d,m)=>{let p=await m.borrowQuick(+r,a,i,s);m.transferObjects([p],c)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new o(t)}};var Vn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,n,a){let{obligationId:r,obligationKey:i,veScaKey:s,amount:c,coinName:l}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:a,obligationId:r,obligationKey:i,veScaKey:s},async(m,p)=>{let f=await p.borrowQuick(+c,l,r,i);p.transferObjects([f],a)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,this.data,t.account.address)}static fromData(t){return new o(t)}};var Hn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let a=t.address,{obligationId:r,obligationKey:i,veScaKey:s,coinName:c,amount:l}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:a,obligationId:r,obligationKey:i,veScaKey:s},async(m,p)=>{let f=p.claimReferralTicket(c),b=await p.borrowWithReferralQuick(+l,c,f,r,i);p.burnReferralTicket(f,c),p.transferObjects([b],a)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new o(t)}};import{SUI_TYPE_ARG as rd}from"@mysten/sui/utils";var Gn=class o extends g{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let n=e.builder.createTxBlock();n.setSender(t);let a=await e.query.getAllStakeAccounts(t),r=await e.query.getLendings(void 0,t),i=await e.query.getObligations(t),s=Object.values(await e.query.getObligationAccounts(t)??[]),c=(()=>{let p=[...e.constants.whitelist.spool].map(f=>e.utils.parseCoinName(f));return Object.values(r??[]).filter(f=>!!f&&p.includes(f.coinName)).reduce((f,b)=>{let y=e.utils.parseMarketCoinName(b.coinName);return f[y]||(f[y]=0),f[y]+=b.availableClaimCoin,f},{})})(),l={};Object.entries(a).forEach(([p,f])=>{for(let b=0;b<f.length;b++){let y=f[b];if(!c[p])continue;let A=n.claim(y.id,p);l.sui?l.sui.push(A):l.sui=[A]}});let d=(()=>{let p={};return p.sui=Object.values(c).reduce((f,b)=>f+b,0),s.forEach(f=>{Object.values(f.borrowIncentives).forEach(b=>{b&&b.rewards.forEach(y=>{p[y.coinName]||(p[y.coinName]=0),p[y.coinName]?p[y.coinName]+=y.availableClaimCoin:p[y.coinName]=y.availableClaimCoin})})}),p})();if(i.length>0&&s.length>0)for(let p=0;p<s.length;p++){let f=s[p],b=!1,y=i.find(R=>R.id===f.obligationId)?.keyId,A={};if(y){if(Object.values(f.borrowIncentives).forEach(R=>{if(R){let xt=R.rewards.filter(H=>{let Zt=H.coinName;return H.availableClaimCoin>0&&!A[Zt]});b=xt.length>0,xt.forEach(H=>{let Zt=n.claimBorrowIncentive(f.obligationId,y,H.coinName);A[H.coinName]=!0,l[H.coinName]?l[H.coinName].push(Zt):l[H.coinName]=[Zt]})}}),d.sui>0){let R=M.redeem_rewards(n,y,f.obligationId,rd);l.sui?l.sui.push(R):l.sui=[R]}if(b&&await Ni(e.query,f.obligationId)){n.unstakeObligation(f.obligationId,y);let xt=await e.query.getBindedVeScaKey(f.obligationId);xt?n.stakeObligationWithVesca(f.obligationId,y,xt):n.stakeObligation(f.obligationId,y)}}}let m=(await Promise.all(Object.entries(l).map(async([p,f])=>{let b=f[0];if(f.length>1&&n.mergeCoins(b,f.slice(1)),p==="sui"){n.mergeCoins(n.gas,[b]);return}return await e.builder.utils.mergeSimilarCoins(n,b,e.utils.parseCoinType(p),t),b}))).filter(p=>!!p);return m.length>0&&n.transferObjects(m,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new o(e)}};var Qn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new o(t)}};var zn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let a=t.address,{obligationKey:r,obligationId:i,rewardCoinName:s,veScaKey:c}=this.data,l=n.builder.createTxBlock();l.setSender(a);let d=M.redeem_rewards(l,r,i,n.utils.parseCoinType(s));return l.transferObjects([d],a),await l.unstakeObligationQuick(i,r),c?await l.stakeObligationWithVeScaQuick(i,r,c):await l.stakeObligationQuick(i,r),l.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new o(t)}};var Jn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new o(t)}};var Yn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new o(t)}};var Xn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:n}){let a=t.address,{coinName:r,amount:i,obligationId:s,obligationKey:c}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:a,obligationId:s,obligationKey:c},async(d,m)=>{await m.repayQuick(+i,r,s)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new o(t)}};var Zn=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let a=t.address,{coinName:r,amount:i,obligationId:s,veScaKey:c}=this.data,l=n.builder.createTxBlock();l.setSender(a);let d=n.constants.whitelist.borrowing.has(r);return d&&await l.unstakeObligationQuick(s,void 0),await l.repayQuick(+i,r,s),d&&await l.stakeObligationWithVeScaQuick(s,void 0,c),l.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new o(t)}};var ta=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new o(t)}};var ea=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new o(t)}};var na=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,n,a){let r=t.builder.createTxBlock();r.setSender(a);let{stakeAccountId:i,amount:s,coinName:c}=this.data,l=[];for(let d=0;d<i.length;d++){let{id:m,coin:p}=i[d],f=t.utils.parseMarketCoinName(c),[b]=await r.unstakeQuick(p,f,m);if(b){let y=r.withdraw(b,c);l.push(y)}}if(s>0){let d=await r.withdrawQuick(s,c);l.push(d)}return l.length>1&&r.mergeCoins(l[0],l.slice(1)),r.transferObjects(l,a),r.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new o(t)}};var aa=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new o(t)}};var oa=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new o(t)}};var ra=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:n}){let a=t.address,r=n.builder.createTxBlock();return r.setSender(a),r.bindToReferral(this.data.veScaKey),r.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new o(t)}};var ia=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:a,coins:r}=this.data,i=t.address,s=n.builder.createTxBlock();s.setSender(i);let c=r.map(l=>n.utils.parseCoinNameFromType(l));return await s.claimReferralRevenueQuick(a,c),s.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new o(t)}};var sa=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let a=t.address,r=n.builder.createTxBlock();r.setSender(a);let i=r.mintEmptyVeSca();return r.transferObjects([i],a),r.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new o(t)}};import{SCA_COIN_TYPE as id}from"@scallop-io/sui-scallop-sdk";var ca=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:a,veScaKey:r,unlockTime:i,obligationId:s,obligationKey:c,isOldBorrowIncentive:l,isObligationLocked:d}=this.data,m=t.address,p=n.builder.createTxBlock();p.setSender(m);let f=await n.utils.selectCoins(a,id,m),[b,y]=p.takeAmountFromCoins(f,a);return p.extendLockPeriod(r,i),p.extendLockAmount(r,b),p.transferObjects([y],m),!s||!c||(d&&(l?M.unstakeObligation(p,s,c):p.unstakeObligation(s,c)),p.stakeObligationWithVesca(s,c,r)),p.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new o(t)}};var la=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let a=t.address,{veScaKey:r,unlockTime:i,obligationId:s,obligationKey:c,isObligationLocked:l,isOldBorrowIncentive:d}=this.data,m=n.builder.createTxBlock();return m.setSender(a),m.extendLockPeriod(r,i),s&&c&&(l&&(d?M.unstakeObligation(m,c,s):m.unstakeObligation(s,c)),m.stakeObligationWithVesca(s,c,r)),m.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new o(t)}};var da=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:a}=this.data,r=t.address,i=n.builder.createTxBlock();return i.setSender(r),await i.redeemScaQuick(a),i.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new o(t)}};import{SCA_COIN_TYPE as sd}from"@scallop-io/sui-scallop-sdk";var ua=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let a=t.address,{amount:r,unlockTime:i,vescaKey:s,isHaveRedeem:c,obligation:l,obligationKey:d,isObligationLocked:m,isOldBorrowIncentive:p}=this.data,f=n.builder.createTxBlock();if(f.setSender(a),c){let R=f.redeemSca(s);f.transferObjects([R],a)}let b=await n.builder.utils.selectCoins(r,sd,a),[y,A]=f.takeAmountFromCoins(b,r);return f.transferObjects([A],a),f.renewExpiredVeSca(s,y,i),!l||!d||(m&&(p?M.unstakeObligation(f,d,l):f.unstakeObligation(l,d)),f.stakeObligationWithVesca(l,d,s)),f.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new o(t)}};import{SCA_COIN_TYPE as cd}from"@scallop-io/sui-scallop-sdk";var ma=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:n}){let a=t.address,{amount:r,isObligationLocked:i,isOldBorrowIncentive:s,obligationId:c,obligationKey:l,unlockTime:d,veScaKey:m}=this.data,p=n.builder.createTxBlock();p.setSender(a);let f=await n.utils.selectCoins(r,cd,a),[b,y]=p.takeAmountFromCoins(f,r),A;return m?p.extendLockAmount(m,b):A=p.lockSca(b,d),c&&l&&(i&&(s?M.unstakeObligation(p,l,c):p.unstakeObligation(c,l)),p.stakeObligationWithVesca(c,l,m||A)),m||p.transferObjects([A,y],a),p.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new o(t)}};var pa=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let a=t.address,{amount:r,coinName:i,stakeAccountId:s}=this.data,c=n.builder.createTxBlock();c.setSender(a);let l=await c.depositQuick(+r,i),d=n.utils.parseMarketCoinName(i);if(n.constants.whitelist.spool.has(d))return c.txBlock;let m=await n.query.getStakeAccounts(d,a),p=s||(m.length>0?m[0].id:void 0);if(p)await c.stakeQuick(l,d,p);else{let f=c.createStakeAccount(d);await c.stakeQuick(l,d,f),c.transferObjects([f],a)}return c.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new o(t)}};var fa=class o extends g{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:a}=this.data,r=t.address,i=n.builder.createTxBlock();return i.setSender(r),await i.redeemScaQuick(a),i.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new o(t)}};var ba=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async deserialize(e){if(!this.scallopClient){let s=new ji({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e.account.address,suiClients:[e.suiClient]});this.scallopClient=await s.createScallopClient()}let{transaction:t}=e;console.log("transaction",t);let n=new Fn(t,this.scallopClient),a=new qn(t,this.scallopClient),r=new Kn(t,this.scallopClient),i=n.decode()||a.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:ld.Other,txSubType:i.type,intentionData:i.intentionData}}async build(e){let{suiClient:t,account:n,network:a,txSubType:r,intentionData:i}=e;if(!this.scallopClient){let c=new ji({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e.account.address,suiClients:[e.suiClient]});this.scallopClient=await c.createScallopClient()}let s;switch(r){case"SupplyLending":s=ta.fromData(i);break;case"WithdrawLending":s=oa.fromData(i);break;case"Borrow":s=$n.fromData(i);break;case"Repay":s=Xn.fromData(i);break;case"DepositCollateral":s=Qn.fromData(i);break;case"WithdrawCollateral":s=aa.fromData(i);break;case"OpenObligation":s=Yn.fromData(i);break;case"UnstakeSpool":s=ea.fromData(i);break;case"ClaimIncentiveReward":s=Gn.fromData(i);break;case"BorrowWithBoost":s=Vn.fromData(i);break;case"StakeSca":s=ma.fromData(i);break;case"ExtendStakePeriod":s=la.fromData(i);break;case"ExtendPeriodAndStakeMore":s=ca.fromData(i);break;case"RenewExpStakePeriod":s=ua.fromData(i);break;case"WithdrawStakedSca":s=fa.fromData(i);break;case"SupplyAndStakeLending":s=pa.fromData(i);break;case"WithdrawAndUnstakeLending":s=na.fromData(i);break;case"RedeemSca":s=da.fromData(i);break;case"MigrateAndClaim":s=zn.fromData(i);break;case"BorrowWithReferral":s=Hn.fromData(i);break;case"CreateReferralLink":s=sa.fromData(i);break;case"ClaimRevenueReferral":s=ia.fromData(i);break;case"BindReferral":s=ra.fromData(i);break;case"MigrateScoin":s=Jn.fromData(i);break;case"RepayWithBoost":s=Zn.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:t,account:n,network:a,scallopClient:this.scallopClient})}};import{TransactionType as qd}from"@msafe/sui3-utils";import{TransactionType as Gt}from"@msafe/sui3-utils";import{normalizeStructTag as st}from"@mysten/sui/utils";import{fetchRegistryLiquidStakingInfoMap as xd}from"@suilend/springsui-sdk/client";import{TransactionType as Sd}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as wd,LENDING_MARKET_TYPE as kd,SuilendClient as or}from"@suilend/sdk";import{TransactionType as wt}from"@msafe/sui3-utils";import{fromBase64 as Ui,toHex as Fi}from"@mysten/bcs";import{normalizeStructTag as Vt}from"@mysten/sui/utils";import{MAX_U64 as kt}from"@suilend/frontend-sui";import qi from"bignumber.js";var ha=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(a=>a.type.includes("lending_market::MintEvent"))},t=Vt(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:wt.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=Vt(t.RedeemEvent.parsedJson.coin_type.name),a=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,a);let r=e.withdraw_ctokens.MoveCall.arguments[4].Input,i=new qi(Fi(Ui(this.inputs[r].Pure.bytes)),16).toString(),s=i===kt.toString();return console.log("decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"MAX_U64.toString():",kt.toString()),s&&(a=kt.toString()),{txType:wt.Other,type:"withdraw",intentionData:{coinType:n,value:a}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(c=>c.type.includes("lending_market::BorrowEvent"))},n=Vt(t.BorrowEvent.parsedJson.coin_type.name),a=`${+t.BorrowEvent.parsedJson.liquidity_amount-+t.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,a);let r=e.borrow_request.MoveCall.arguments[4].Input,i=new qi(Fi(Ui(this.inputs[r].Pure.bytes)),16).toString(),s=i===kt.toString();return console.log("decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"MAX_U64.toString():",kt.toString()),s&&(a=kt.toString()),{txType:wt.Other,type:"borrow",intentionData:{coinType:n,value:a}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(a=>a.type.includes("lending_market::RepayEvent"))},t=Vt(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:wt.Other,type:"repay",intentionData:{coinType:t,value:n}}}decodeClaim(){let e={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},t={};for(let n=0;n<e.ClaimReward.length;n++){let a=e.ClaimReward[n],r=Vt(a.parsedJson.coin_type.name),i=a.parsedJson.liquidity_amount;t[r]=`${+(t[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",t),{txType:wt.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:wt.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};import{Transaction as md}from"@mysten/sui/transactions";import ud from"sort-keys-recursive";var P=class{constructor(e){this.data=e}serialize(){return JSON.stringify(ud(this.data))}};var ga=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;if(console.log("BorrowIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new md;return await r.borrowAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(t){return console.log("BorrowIntention.fromData",t),new o(t)}};import{Transaction as gd}from"@mysten/sui/transactions";import{normalizeStructTag as pd}from"@mysten/sui/utils";import{isSendPoints as fd}from"@suilend/frontend-sui";import{Side as Ht}from"@suilend/sdk";import bd from"bignumber.js";var hd=(o,e)=>{let t={[Ht.DEPOSIT]:[],[Ht.BORROW]:[]};return o.lendingMarket.reserves.forEach(n=>{[Ht.DEPOSIT,Ht.BORROW].forEach(a=>{let r=a===Ht.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,i=e.userRewardManagers.find(s=>s.poolRewardManagerId===r.id);i&&(t[a]=r.poolRewards.map((s,c)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(c),rewardCoinType:pd(s.coinType.name),side:a})).filter(s=>!fd(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new bd(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},ya=hd;var Ta=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;if(console.log("ClaimIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new gd;return r.claimRewardsAndSendToUser(a.address,i.id,ya(r,s),c),c}static fromData(t){return console.log("ClaimIntention.fromData",t),new o(t)}};import{Transaction as yd}from"@mysten/sui/transactions";var Ca=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;if(console.log("ClaimAndDepositIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new yd;return r.claimRewardsAndDeposit(a.address,i.id,ya(r,s),c),c}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new o(t)}};import{Transaction as Td}from"@mysten/sui/transactions";var Ia=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;console.log("DepositIntention.build",n,a,r,i,s);let c=new Td;return await r.depositIntoObligation(a.address,this.data.coinType,this.data.value,c,i?.id),c}static fromData(t){return console.log("DepositIntention.fromData",t),new o(t)}};import{Transaction as Cd}from"@mysten/sui/transactions";var Sa=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;if(console.log("RepayIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Cd;return await r.repayIntoObligation(a.address,s.id,this.data.coinType,this.data.value,c),c}static fromData(t){return console.log("RepayIntention.fromData",t),new o(t)}};import{Transaction as Id}from"@mysten/sui/transactions";var wa=class o extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=t;if(console.log("WithdrawIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Id;return await r.withdrawAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(t){return console.log("WithdrawIntention.fromData",t),new o(t)}};var ka=async(o,e)=>{let t=await or.initialize(wd,kd,o),n=await or.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,o),a=await Promise.all(n.map(r=>or.getObligation(r.obligationId,t.lendingMarket.$typeArgs,o)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",a,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:a}},xa=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:a}=e;this.utils||(this.utils=await ka(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",r,"utils:",this.utils,"suiClient:",n);let s=new ha(t,r).decode();return{txType:Sd.Other,txSubType:s.type,intentionData:s.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:a,suiClient:r,account:i}=e;this.utils||(this.utils=await ka(r,i));let s;switch(n){case"deposit":s=Ia.fromData(a);break;case"withdraw":s=wa.fromData(a);break;case"borrow":s=ga.fromData(a);break;case"repay":s=Sa.fromData(a);break;case"claim":s=Ta.fromData(a);break;case"claimAndDeposit":s=Ca.fromData(a);break;default:throw new Error("not implemented")}let c=window.localStorage.getItem("obligationId"),l=this.utils.obligations?.find(m=>m.id===c)??this.utils.obligations?.[0],d=this.utils.obligationOwnerCaps?.find(m=>m.obligationId===l?.id);return s.build({network:t,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:d,obligation:l})}};var rr=async(o,e)=>{let t=await ka(o,e),n=await xd(o);return{...t,LIQUID_STAKING_INFO_MAP:n}};var Da=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::MintEvent"))},t=st(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:Gt.Other,type:"stake",intentionData:{amount:n,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::MintEvent"))},t=st(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:Gt.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},t=st(e.RedeemEvent.parsedJson.event.typename.name),n=st(e.MintEvent.parsedJson.event.typename.name),a=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",a),{txType:Gt.Other,type:"convert",intentionData:{amount:a,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},t=st(e.RedeemEvent.parsedJson.event.typename.name),n=st(e.MintEvent.parsedJson.event.typename.name),a=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",a),{txType:Gt.Other,type:"convertAndDeposit",intentionData:{amount:a,inCoinType:t,outCoinType:n}}}decodeUnstake(){let e={RedeemEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::RedeemEvent"))},t=st(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:Gt.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};import{Transaction as Ad}from"@mysten/sui/transactions";import{convertLstsAndSendToUser as Od,LstClient as Ki}from"@suilend/springsui-sdk";import vd from"sort-keys-recursive";var W=class{constructor(e){this.data=e}serialize(){return JSON.stringify(vd(this.data))}};var va=class o extends W{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=t;console.log("ConvertIntention.build",n,a,r,i,s,c);let l=await Ki.initialize(n,Object.values(i).find(p=>p.type===this.data.inCoinType)),d=await Ki.initialize(n,Object.values(i).find(p=>p.type===this.data.outCoinType)),m=new Ad;return Od(l,d,m,a.address,this.data.amount),m}static fromData(t){return console.log("ConvertIntention.fromData",t),new o(t)}};import{Transaction as Pd}from"@mysten/sui/transactions";import{createObligationIfNoneExists as Rd,sendObligationToUser as Bd}from"@suilend/sdk";import{convertLsts as _d,LstClient as $i}from"@suilend/springsui-sdk";var Aa=class o extends W{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=t;console.log("ConvertAndDepositIntention.build",n,a,r,i,s,c);let l=await $i.initialize(n,Object.values(i).find(y=>y.type===this.data.inCoinType)),d=await $i.initialize(n,Object.values(i).find(y=>y.type===this.data.outCoinType)),m=new Pd,{obligationOwnerCapId:p,didCreate:f}=Rd(r,m,s),b=_d(l,d,m,a.address,this.data.amount);return r.deposit(b,this.data.outCoinType,p,m),f&&Bd(p,a.address,m),m}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new o(t)}};import{Transaction as Ed}from"@mysten/sui/transactions";import{LstClient as Md}from"@suilend/springsui-sdk";var Oa=class o extends W{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=t;console.log("StakeIntention.build",n,a,r,i,s,c);let l=await Md.initialize(n,Object.values(i).find(m=>m.type===this.data.outCoinType)),d=new Ed;return l.mintAmountAndRebalanceAndSendToUser(d,a.address,this.data.amount),d}static fromData(t){return console.log("StakeIntention.fromData",t),new o(t)}};import{Transaction as Wd}from"@mysten/sui/transactions";import{createObligationIfNoneExists as Nd,sendObligationToUser as Ld}from"@suilend/sdk";import{LstClient as jd}from"@suilend/springsui-sdk";var Pa=class o extends W{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=t;console.log("StakeAndDepositIntention.build",n,a,r,i,s,c);let l=await jd.initialize(n,Object.values(i).find(b=>b.type===this.data.outCoinType)),d=new Wd,{obligationOwnerCapId:m,didCreate:p}=Nd(r,d,s),f=l.mintAmountAndRebalance(d,a.address,this.data.amount);return r.deposit(f,this.data.outCoinType,m,d),p&&Ld(m,a.address,d),d}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new o(t)}};import{Transaction as Ud}from"@mysten/sui/transactions";import{LstClient as Fd}from"@suilend/springsui-sdk";var Ra=class o extends W{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:a,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=t;console.log("UnstakeIntention.build",n,a,r,i,s,c);let l=await Fd.initialize(n,Object.values(i).find(m=>m.type===this.data.inCoinType)),d=new Ud;return l.redeemAmountAndSendToUser(d,a.address,this.data.amount),d}static fromData(t){return console.log("UnstakeIntention.fromData",t),new o(t)}};var Ba=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:a}=e;this.utils||(this.utils=await rr(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",r);let s=new Da(t,r).decode();return{txType:qd.Other,txSubType:s.type,intentionData:s.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:a,suiClient:r,account:i}=e;this.utils||(this.utils=await rr(r,i));let s;switch(n){case"stake":s=Oa.fromData(a);break;case"stakeAndDeposit":s=Pa.fromData(a);break;case"convert":s=va.fromData(a);break;case"convertAndDeposit":s=Aa.fromData(a);break;case"unstake":s=Ra.fromData(a);break;default:throw new Error("not implemented")}return s.build({network:t,suiClient:r,account:i,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};import{TransactionType as Hd}from"@msafe/sui3-utils";import{TransactionType as Vi}from"@msafe/sui3-utils";var _a=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:Vi.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Vi.Other,type:"redeem",intentionData:{amount:t}}}};import{LST as $d}from"@alphafi/stsui-sdk";var Ea=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:a}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},s=await new $d(r).mint(a,n.address);return s.setGasBudget(1e8),s}static fromData(t){return console.log("MintIntention.fromData",t),new o(t)}};import{LST as Vd}from"@alphafi/stsui-sdk";var Ma=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:a}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},s=await new Vd(r).redeem(a,n.address);return s.setGasBudget(1e8),s}static fromData(t){return console.log("RedeemIntention.fromData",t),new o(t)}};var Wa=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n}=e,a=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",a);let i=new _a(t,a).decode();return{txType:Hd.Other,txSubType:i.type,intentionData:i.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let n;switch(e.txSubType){case"mint":n=Ea.fromData(e.intentionData);break;case"redeem":n=Ma.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};import{TransactionType as pu}from"@msafe/sui3-utils";import{TurbosSdk as fu}from"turbos-clmm-sdk";import{TransactionType as N}from"@msafe/sui3-utils";import{bcs as Hi}from"@mysten/sui.js/bcs";import{normalizeStructTag as Qd,normalizeSuiAddress as Qt}from"@mysten/sui.js/utils";import{BN as zd}from"turbos-clmm-sdk";var j={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},U={PackageId:"0xdee9"};var Jd=(o,e,t,n)=>{if(o===1)switch(n.findIndex(i=>i===e)){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: ${e}`)}switch(t.findIndex(r=>r===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},Na=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);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(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.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(`${j.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${j.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${U.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${U.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(f=>f.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let n=Jd(t,e.target,this.swap1Layer,this.swap2Layer),a=n.map((f,b)=>{let y=this.helper.decodeSharedObjectId(b),A=this.helper.decodeInputU128(4+b+t),R=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new zd(A.toString()));return{pool:y,a2b:f,nextTickIndex:R}}),r=n[0]||t===1?e.typeArguments[0]:e.typeArguments[1],i=t===1?e.typeArguments[4]:n[0]?e.typeArguments[1]:e.typeArguments[0],s=this.helper.decodeInputAddress(6+2*t),c=this.helper.decodeInputU64(7+2*t),l=this.helper.decodeInputBool(5+2*t),d=this.helper.decodeInputU64(2+t),m=this.helper.decodeInputU64(3+t),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:a[0].pool,a2b:a[0].a2b,amountSpecified:d}],address:s,amountSpecifiedIsInput:l});return{txType:N.Other,type:"Swap",intentionData:{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:m,amountB:l?m:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:N.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:n,amountB:a,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),a=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:N.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:a,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:N.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:e,deadline:s}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:N.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:a,collectAmountB:r,nft:t,deadline:i}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),a=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:N.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:a,nft:t,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:N.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),a=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(m=>m.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:N.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:e,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:N.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:N.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let e=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),t=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),a=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:N.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:e,amountIn:t,token1:n,token2:a}}}decodeSwapExactQuoteForBase(){let e=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),t=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),a=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:N.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:a}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new tt(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new tt(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new tt(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new tt(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${U.PackageId}::clob_v2::swap_exact_base_for_quote`);return new tt(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${U.PackageId}::clob_v2::swap_exact_quote_for_base`);return new tt(e,this.txb)}},tt=class o{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return o.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return o.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Qt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return o.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Hi.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Qt(e.value.Object.ImmOrOwned.objectId)}return Qt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Qt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Qt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Hi.de(t,new Uint8Array(n))}typeArg(e){return Qd(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};import{TurbosSdk as Yd}from"turbos-clmm-sdk";var La=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Yd(t.network.replace("sui:",""),t.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:m,txb:p}=this.data;return n.pool.addLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:m,txb:p})}static fromData(t){return new o(t)}};import{TurbosSdk as Xd}from"turbos-clmm-sdk";var ja=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Xd(t.network.replace("sui:",""),t.suiClient),{pool:a,nft:r,txb:i}=this.data;return n.nft.burn({pool:a,nft:r,txb:i})}static fromData(t){return new o(t)}};import{TurbosSdk as Zd}from"turbos-clmm-sdk";var Ua=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Zd(t.network.replace("sui:",""),t.suiClient),{pool:a,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:a,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(t){return new o(t)}};import{TurbosSdk as tu}from"turbos-clmm-sdk";var Fa=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new tu(t.network.replace("sui:",""),t.suiClient),{pool:a,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:a,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(t){return new o(t)}};import{TurbosSdk as eu}from"turbos-clmm-sdk";var qa=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new eu(t.network.replace("sui:",""),t.suiClient),{fee:a,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:m,amountA:p,amountB:f,deadline:b,txb:y}=this.data;return n.pool.createPool({fee:a,amountA:p,amountB:f,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:m,deadline:b,txb:y})}static fromData(t){return new o(t)}};import{TurbosSdk as nu}from"turbos-clmm-sdk";var Ka=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new nu(t.network.replace("sui:",""),t.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:m,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:m,txb:p})}static fromData(t){return new o(t)}};import{TurbosSdk as au}from"turbos-clmm-sdk";var $a=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new au(t.network.replace("sui:",""),t.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:m}=this.data;return n.pool.increaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:m})}static fromData(t){return new o(t)}};import{TransactionBlock as ou}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as ru}from"@mysten/sui.js/utils";var Va=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new ou;return n.moveCall({target:`${j.PackageId}::claim::claim`,typeArguments:[j.turbosCoinType],arguments:[n.object(j.Claim),n.object(ru)]}),n}static fromData(t){return new o(t)}};import{TransactionBlock as iu}from"@mysten/sui.js/transactions";var Ha=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new iu;return n.moveCall({target:`${j.PackageId}::claim::join`,typeArguments:[j.turbosCoinType],arguments:[n.object(j.Claim)]}),n}static fromData(t){return new o(t)}};import{TransactionBlock as su}from"@mysten/sui.js/transactions";import{TurbosSdk as cu}from"turbos-clmm-sdk";var Ga=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new cu(t.network.replace("sui:",""),t.suiClient),a=new su;return a=await n.pool.collectFee({txb:a,...this.data}),a=await n.pool.collectReward({txb:a,...this.data}),a=await n.pool.decreaseLiquidity({txb:a,...this.data}),a=await n.nft.burn({txb:a,nft:this.data.nft,pool:this.data.pool}),a}static fromData(t){return new o(t)}};import{TurbosSdk as lu}from"turbos-clmm-sdk";var Qa=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new lu(t.network.replace("sui:",""),t.suiClient),{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:m,deadline:p,txb:f}=this.data;return n.trade.swap({routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:m,slippage:d,deadline:p,txb:f})}static fromData(t){return new o(t)}};import{TurbosSdk as uu}from"turbos-clmm-sdk";import{TransactionBlock as Gi}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as Qi}from"@mysten/sui.js/utils";import{unstable_getObjectId as du}from"turbos-clmm-sdk";var zt=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,n){let a=[],r;do r=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:r?.nextCursor}),a.push(...r.data);while(r.hasNextPage);let i=[],s=0;return a.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(e,t,n){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(t)]);return[i,void 0]}let a=n.object(e[0].coinObjectId);e.length>1&&n.mergeCoins(a,e.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(a,[n.pure(t)]);return[r,a]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${U.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?du(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${U.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var zi=89,Ji=1e6,Yi=async o=>{let{token1:e,token2:t,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Gi,c=new zt(i),l=await c.getCoinsData(r,t,a),[d,m]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(r),f=p?s.object(p):c.createAccount(s),[b,y,A]=s.moveCall({typeArguments:[e,t],target:`${U.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(zi),f,s.pure(a),s.object(Qi("0x6")),d]});return m&&s.transferObjects([m],s.pure(r)),s.transferObjects([b],s.pure(r)),s.transferObjects([y],s.pure(r)),p||s.transferObjects([f],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(Ji),s},Xi=async o=>{let{token1:e,token2:t,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Gi,c=new zt(i),l=await c.getCoinsData(r,e,a),[d,m]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(r),f=p?s.object(p):c.createAccount(s),b=c.zero(t,s),[y,A,R]=s.moveCall({typeArguments:[e,t],target:`${U.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(zi),f,s.pure(a),d,b,s.object(Qi("0x6"))]});return m&&s.transferObjects([m],s.pure(r)),s.transferObjects([y],s.pure(r)),s.transferObjects([A],s.pure(r)),p||s.transferObjects([f],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(Ji),s};var za=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new uu(t.network.replace("sui:",""),t.suiClient);return await Xi({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new o(t)}};import{TurbosSdk as mu}from"turbos-clmm-sdk";var Ja=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new mu(t.network.replace("sui:",""),t.suiClient);return await Yi({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new o(t)}};var Ya=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new fu(e.network.replace("sui:",""),e.suiClient),n=await t.contract.getConfig(),{transactionBlock:a,account:r}=e;console.log(e,"input");let s=await new Na(a,t,n).decode(r.address);return{txType:pu.Other,txSubType:s.type,intentionData:s.intentionData}}async build(e){let{suiClient:t,account:n,network:a}=e,r;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":r=qa.fromData(e.intentionData);break;case"AddLiquidity":r=La.fromData(e.intentionData);break;case"IncreaseLiquidity":r=$a.fromData(e.intentionData);break;case"DecreaseLiquidity":r=Ka.fromData(e.intentionData);break;case"RemoveLiquidity":r=Ga.fromData(e.intentionData);break;case"CollectFee":r=Ua.fromData(e.intentionData);break;case"CollectReward":r=Fa.fromData(e.intentionData);break;case"Burn":r=ja.fromData(e.intentionData);break;case"Swap":r=Qa.fromData(e.intentionData);break;case"PrixJoin":r=Ha.fromData(e.intentionData);break;case"PrixClaim":r=Va.fromData(e.intentionData);break;case"SwapExactBaseForQuote":r=za.fromData(e.intentionData);break;case"SwapExactQuoteForBase":r=Ja.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:a})}};import{TransactionType as Iu}from"@msafe/sui3-utils";import{TransactionType as ir}from"@msafe/sui3-utils";import{bcs as Zi}from"@mysten/sui.js/bcs";import{normalizeStructTag as gu,normalizeSuiAddress as Jt}from"@mysten/sui.js/utils";var bu={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},w=bu;var Xa=class{constructor(e){this.txb=e}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(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${w.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${w.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${w.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:ir.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:ir.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:ir.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(w.packageId));return new sr(e,this.txb)}},sr=class o{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return o.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return o.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Jt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return o.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Zi.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Jt(e.value.Object.ImmOrOwned.objectId)}return Jt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Jt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Jt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Zi.de(t,new Uint8Array(n))}typeArg(e){return gu(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{TransactionBlock as yu}from"@mysten/sui.js/transactions";var Za=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new yu,{ticketId:a}=this.data;return n.moveCall({target:`${w.packageId}::native_pool::burn_ticket`,arguments:[n.object(w.poolObjectId),n.object(w.systemStateObjectId),n.object(a)]}),n}static fromData(t){return new o(t)}};import{TransactionBlock as Tu}from"@mysten/sui.js/transactions";var to=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Tu,{amount:a}=this.data,[r]=n.splitCoins(n.gas,[n.pure(a)]);return n.moveCall({target:`${w.packageId}::native_pool::stake`,arguments:[n.object(w.poolObjectId),n.object(w.metadataObjectId),n.object(w.systemStateObjectId),r]}),n}static fromData(t){return new o(t)}};import{TransactionBlock as Cu}from"@mysten/sui.js/transactions";var eo=class o extends h{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Cu,{amount:a}=this.data,r=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===w.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(a)]);return n.moveCall({target:`${w.packageId}::native_pool::unstake`,arguments:[n.object(w.poolObjectId),n.object(w.metadataObjectId),n.object(w.systemStateObjectId),l]}),n}static fromData(t){return new o(t)}};var no=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,a=new Xa(t).decode();return{txType:Iu.Other,txSubType:a.type,intentionData:a.intentionData}}async build(e){let{suiClient:t,account:n}=e,a;switch(e.txSubType){case"Stake":a=to.fromData(e.intentionData);break;case"UnStake":a=eo.fromData(e.intentionData);break;case"ClaimTicket":a=Za.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:t,account:n})}};import{TransactionType as Bu}from"@msafe/sui3-utils";import{asIntN as ts}from"@cetusprotocol/cetus-sui-clmm-sdk";import{TransactionType as ct}from"@msafe/sui3-utils";import{fromBase64 as Yt}from"@mysten/bcs";import{bcs as Xt}from"@mysten/sui/bcs";var ao=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ct.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number(ts(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number(ts(BigInt(this.getU32(this.getInputIndex(e,3)))).toString()),tokenAmount:this.getU64(this.getInputIndex(t,6)),maxAmountTokenA:this.getU64(this.getInputIndex(t,7)),maxAmountTokenB:this.getU64(this.getInputIndex(t,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(t,9))}}}decodeClosePositionTx(){let e=this.getMoveCallCommand("close_position"),t=this.getCollectRewardCallData();return{txType:ct.Other,type:"ClosePosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),transferTokensTo:this.getAddress(this.getInputIndex(e,4)),collectRewardTokens:t.map(n=>n.rewardCoinType),collectFeeTokens:this.getTypeArguments(e)}}}decodeProvideLiquidityTx(){let e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ct.Other,type:"ProvideLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),tokenAmount:this.getU64(this.getInputIndex(e,6)),maxAmountTokenA:this.getU64(this.getInputIndex(e,7)),maxAmountTokenB:this.getU64(this.getInputIndex(e,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(e,9))}}}decodeRemoveLiquidityTx(){let e=this.getMoveCallCommand("remove_liquidity");return{txType:ct.Other,type:"RemoveLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),liquidity:this.getU128(this.getInputIndex(e,4)),maxAmountTokenA:this.getU64(this.getInputIndex(e,5)),maxAmountTokenB:this.getU64(this.getInputIndex(e,6)),transferTokensTo:this.getAddress(this.getInputIndex(e,7)),...this.collectTokens()}}}decodeCollectRewardsTx(){let e=this.getCollectRewardCallData();return{txType:ct.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:ct.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:ct.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(n=>n.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(Xt.u32().parse(Uint8Array.from(Yt(this.inputs[e].Pure.bytes))))}getU64(e){return Xt.u64().parse(Uint8Array.from(Yt(this.inputs[e].Pure.bytes)))}getU128(e){return Xt.u128().parse(Uint8Array.from(Yt(this.inputs[e].Pure.bytes)))}getBoolean(e){return Xt.bool().parse(Uint8Array.from(Yt(this.inputs[e].Pure.bytes)))}getAddress(e){return Xt.Address.parse(Uint8Array.from(Yt(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};import{TransactionType as xu}from"@msafe/sui3-utils";import{BN as lt,ClmmPoolUtil as ku}from"@firefly-exchange/library-sui";import{SuiClient as Su}from"@firefly-exchange/library-sui";import{OnChainCalls as wu}from"@firefly-exchange/library-sui/dist/src/spot";var es={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x6c796c3ab3421a68158e0df18e4657b2827b1f8fed5ed4b82dba9c935988711b"}},nt=(o,e)=>{if(o!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Su({url:es.rpc});return new wu(t,es.objects,{address:e.address,isUIWallet:!1})};var v=class{static async OpenPosition(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool),i=this.prototype.buildLiqInput(r,{...e,slippage:0});return await a.openPositionWithFixedAmount(r,e.lowerTick,e.upperTick,i,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool),i=this.prototype.buildLiqInput(r,e);return await a.provideLiquidityWithFixedAmount(r,e.position,i,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool);return await a.removeLiquidity(r,e.position,{liquidityAmount:new lt(e.liquidity),tokenMaxA:new lt(e.maxAmountTokenA),tokenMaxB:new lt(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool);return await a.closePosition(r,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool);return await a.collectRewards(r,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool);return await a.collectFee(r,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let a=nt(n,t),r=await a.queryChain.getPool(e.pool);return console.log(e.position),await a.collectFeeAndRewards(r,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...ku.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new lt(t.tokenAmount),t.isTokenAFixed,!0,0,new lt(e.current_sqrt_price)),tokenMaxA:new lt(t.maxAmountTokenA),tokenMaxB:new lt(t.maxAmountTokenB)}}};var oo=class o extends u{constructor(t){super(t);this.data=t}txType=xu.Other;txSubType="ClosePosition";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.closePosition(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Du}from"@msafe/sui3-utils";var ro=class o extends u{constructor(t){super(t);this.data=t}txType=Du.Other;txSubType="CollectFee";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.collectFee(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as vu}from"@msafe/sui3-utils";var io=class o extends u{constructor(t){super(t);this.data=t}txType=vu.Other;txSubType="CollectRewards";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.collectRewards(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Au}from"@msafe/sui3-utils";var so=class o extends u{constructor(t){super(t);this.data=t}txType=Au.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.collectRewardsAndFee(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ou}from"@msafe/sui3-utils";var co=class o extends u{constructor(t){super(t);this.data=t}txType=Ou.Other;txSubType="OpenPosition";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.OpenPosition(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Pu}from"@msafe/sui3-utils";var lo=class o extends u{constructor(t){super(t);this.data=t}txType=Pu.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.provideLiquidity(this.data,n,a)}static fromData(t){return new o(t)}};import{TransactionType as Ru}from"@msafe/sui3-utils";var uo=class o extends u{constructor(t){super(t);this.data=t}txType=Ru.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:a}=t;return console.log(this.data),v.removeLiquidity(this.data,n,a)}static fromData(t){return new o(t)}};var mo=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,a=new ao(t).decode();return{txType:Bu.Other,txSubType:a.type,intentionData:a.intentionData}}async build(e){let{suiClient:t,account:n,network:a}=e;console.log(e.txSubType);let r;switch(e.txSubType){case"OpenPosition":r=co.fromData(e.intentionData);break;case"ProvideLiquidity":r=lo.fromData(e.intentionData);break;case"RemoveLiquidity":r=uo.fromData(e.intentionData);break;case"ClosePosition":r=oo.fromData(e.intentionData);break;case"CollectFee":r=ro.fromData(e.intentionData);break;case"CollectRewards":r=io.fromData(e.intentionData);break;case"CollectRewardsAndFee":r=so.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:a})}};import{TransactionType as qu}from"@msafe/sui3-utils";import{KriyaSDK as _u}from"kriya-dev-sdk";var po=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new _u,{params:n}=this.data;return t.Amm.getTxbAddLiquidity(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Eu}from"kriya-dev-sdk";var fo=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Eu,{params:n}=this.data;return t.Amm.getTxbAddLiquiditySingleSided(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Mu}from"kriya-dev-sdk";var bo=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Mu,{params:n}=this.data;return t.Amm.getTxbClaimRewards(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Wu}from"kriya-dev-sdk";var ho=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Wu,{params:n}=this.data;return t.Amm.getTxbRemoveLiquidity(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Nu}from"kriya-dev-sdk";var go=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Nu,{params:n}=this.data;return t.Clmm.getTxbAddLiquiditySingleSided(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Lu}from"kriya-dev-sdk";var yo=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Lu,{params:n}=this.data;return t.Clmm.getTxbAddLiquidity(n)}static fromData(t){return new o(t)}};import{KriyaSDK as ju}from"kriya-dev-sdk";var To=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new ju,{params:n}=this.data;return t.Clmm.getTxbClaimMayaRewards(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Uu}from"kriya-dev-sdk";var Co=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Uu,{params:n}=this.data;return t.Clmm.getTxbClaimRewards(n)}static fromData(t){return new o(t)}};import{KriyaSDK as Fu}from"kriya-dev-sdk";var Io=class o extends u{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=new Fu,{params:n}=this.data;return t.Clmm.getTxbRemoveLiquidity(n)}static fromData(t){return new o(t)}};var So=class{application="kriya";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:qu.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"AddLiquidity":t=po.fromData(e.intentionData);break;case"AddLiquiditySingleSided":t=fo.fromData(e.intentionData);break;case"RemoveLiquidity":t=ho.fromData(e.intentionData);break;case"ClaimRewards":t=bo.fromData(e.intentionData);break;case"ClaimRewardsV3":t=Co.fromData(e.intentionData);break;case"ClaimV3MayaRewards":t=To.fromData(e.intentionData);break;case"AddLiquidityV3":t=yo.fromData(e.intentionData);break;case"AddLiquiditySingleSideV3":t=go.fromData(e.intentionData);break;case"RemoveLiquidityV3":t=Io.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build()}};var LB=Un.fromHelpers([new Dn,new Wn,new wn,new Nn,new Je,new Ya,new So,new ba,new no,new De,new xa,new Ba,new ce,new mo,new Wa]);export{LB as appHelpers};
|
|
1
|
+
var rl=Object.create;var Yr=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var sl=Object.getOwnPropertyNames;var cl=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty;var ul=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ml=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),rs=(a,e)=>{for(var t in e)Yr(a,t,{get:e[t],enumerable:!0})},pl=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sl(e))!ll.call(a,o)&&o!==t&&Yr(a,o,{get:()=>e[o],enumerable:!(n=il(e,o))||n.enumerable});return a};var dl=(a,e,t)=>(t=a!=null?rl(cl(a)):{},pl(e||!a||!a.__esModule?Yr(t,"default",{value:a,enumerable:!0}):t,a));var tl=ml((Zc,ji)=>{"use strict";(function(a,e){"use strict";function t(y,r){if(!y)throw new Error(r||"Assertion failed")}function n(y,r){y.super_=r;var c=function(){};c.prototype=r.prototype,y.prototype=new c,y.prototype.constructor=y}function o(y,r,c){if(o.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((r==="le"||r==="be")&&(c=r,r=10),this._init(y||0,r||10,c||"be"))}typeof a=="object"?a.exports=o:e.BN=o,o.BN=o,o.wordSize=26;var i;try{typeof window<"u"&&typeof window.Buffer<"u"?i=window.Buffer:i=ul("buffer").Buffer}catch{}o.isBN=function(r){return r instanceof o?!0:r!==null&&typeof r=="object"&&r.constructor.wordSize===o.wordSize&&Array.isArray(r.words)},o.max=function(r,c){return r.cmp(c)>0?r:c},o.min=function(r,c){return r.cmp(c)<0?r:c},o.prototype._init=function(r,c,m){if(typeof r=="number")return this._initNumber(r,c,m);if(typeof r=="object")return this._initArray(r,c,m);c==="hex"&&(c=16),t(c===(c|0)&&c>=2&&c<=36),r=r.toString().replace(/\s+/g,"");var p=0;r[0]==="-"&&(p++,this.negative=1),p<r.length&&(c===16?this._parseHex(r,p,m):(this._parseBase(r,c,p),m==="le"&&this._initArray(this.toArray(),c,m)))},o.prototype._initNumber=function(r,c,m){r<0&&(this.negative=1,r=-r),r<67108864?(this.words=[r&67108863],this.length=1):r<4503599627370496?(this.words=[r&67108863,r/67108864&67108863],this.length=2):(t(r<9007199254740992),this.words=[r&67108863,r/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),c,m)},o.prototype._initArray=function(r,c,m){if(t(typeof r.length=="number"),r.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(r.length/3),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var f,b,w=0;if(m==="be")for(p=r.length-1,f=0;p>=0;p-=3)b=r[p]|r[p-1]<<8|r[p-2]<<16,this.words[f]|=b<<w&67108863,this.words[f+1]=b>>>26-w&67108863,w+=24,w>=26&&(w-=26,f++);else if(m==="le")for(p=0,f=0;p<r.length;p+=3)b=r[p]|r[p+1]<<8|r[p+2]<<16,this.words[f]|=b<<w&67108863,this.words[f+1]=b>>>26-w&67108863,w+=24,w>=26&&(w-=26,f++);return this._strip()};function l(y,r){var c=y.charCodeAt(r);if(c>=48&&c<=57)return c-48;if(c>=65&&c<=70)return c-55;if(c>=97&&c<=102)return c-87;t(!1,"Invalid character in "+y)}function u(y,r,c){var m=l(y,c);return c-1>=r&&(m|=l(y,c-1)<<4),m}o.prototype._parseHex=function(r,c,m){this.length=Math.ceil((r.length-c)/6),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var f=0,b=0,w;if(m==="be")for(p=r.length-1;p>=c;p-=2)w=u(r,c,p)<<f,this.words[b]|=w&67108863,f>=18?(f-=18,b+=1,this.words[b]|=w>>>26):f+=8;else{var d=r.length-c;for(p=d%2===0?c+1:c;p<r.length;p+=2)w=u(r,c,p)<<f,this.words[b]|=w&67108863,f>=18?(f-=18,b+=1,this.words[b]|=w>>>26):f+=8}this._strip()};function g(y,r,c,m){for(var p=0,f=0,b=Math.min(y.length,c),w=r;w<b;w++){var d=y.charCodeAt(w)-48;p*=m,d>=49?f=d-49+10:d>=17?f=d-17+10:f=d,t(d>=0&&f<m,"Invalid character"),p+=f}return p}o.prototype._parseBase=function(r,c,m){this.words=[0],this.length=1;for(var p=0,f=1;f<=67108863;f*=c)p++;p--,f=f/c|0;for(var b=r.length-m,w=b%p,d=Math.min(b,b-w)+m,s=0,h=m;h<d;h+=p)s=g(r,h,h+p,c),this.imuln(f),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s);if(w!==0){var D=1;for(s=g(r,h,r.length,c),h=0;h<w;h++)D*=c;this.imuln(D),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s)}this._strip()},o.prototype.copy=function(r){r.words=new Array(this.length);for(var c=0;c<this.length;c++)r.words[c]=this.words[c];r.length=this.length,r.negative=this.negative,r.red=this.red};function T(y,r){y.words=r.words,y.length=r.length,y.negative=r.negative,y.red=r.red}if(o.prototype._move=function(r){T(r,this)},o.prototype.clone=function(){var r=new o(null);return this.copy(r),r},o.prototype._expand=function(r){for(;this.length<r;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},o.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=S}catch{o.prototype.inspect=S}else o.prototype.inspect=S;function S(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var C=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],k=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(r,c){r=r||10,c=c|0||1;var m;if(r===16||r==="hex"){m="";for(var p=0,f=0,b=0;b<this.length;b++){var w=this.words[b],d=((w<<p|f)&16777215).toString(16);f=w>>>24-p&16777215,p+=2,p>=26&&(p-=26,b--),f!==0||b!==this.length-1?m=C[6-d.length]+d+m:m=d+m}for(f!==0&&(m=f.toString(16)+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(r===(r|0)&&r>=2&&r<=36){var s=I[r],h=k[r];m="";var D=this.clone();for(D.negative=0;!D.isZero();){var A=D.modrn(h).toString(r);D=D.idivn(h),D.isZero()?m=A+m:m=C[s-A.length]+A+m}for(this.isZero()&&(m="0"+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}t(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var r=this.words[0];return this.length===2?r+=this.words[1]*67108864:this.length===3&&this.words[2]===1?r+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-r:r},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(r,c){return this.toArrayLike(i,r,c)}),o.prototype.toArray=function(r,c){return this.toArrayLike(Array,r,c)};var v=function(r,c){return r.allocUnsafe?r.allocUnsafe(c):new r(c)};o.prototype.toArrayLike=function(r,c,m){this._strip();var p=this.byteLength(),f=m||Math.max(1,p);t(p<=f,"byte array longer than desired length"),t(f>0,"Requested array length <= 0");var b=v(r,f),w=c==="le"?"LE":"BE";return this["_toArrayLike"+w](b,p),b},o.prototype._toArrayLikeLE=function(r,c){for(var m=0,p=0,f=0,b=0;f<this.length;f++){var w=this.words[f]<<b|p;r[m++]=w&255,m<r.length&&(r[m++]=w>>8&255),m<r.length&&(r[m++]=w>>16&255),b===6?(m<r.length&&(r[m++]=w>>24&255),p=0,b=0):(p=w>>>24,b+=2)}if(m<r.length)for(r[m++]=p;m<r.length;)r[m++]=0},o.prototype._toArrayLikeBE=function(r,c){for(var m=r.length-1,p=0,f=0,b=0;f<this.length;f++){var w=this.words[f]<<b|p;r[m--]=w&255,m>=0&&(r[m--]=w>>8&255),m>=0&&(r[m--]=w>>16&255),b===6?(m>=0&&(r[m--]=w>>24&255),p=0,b=0):(p=w>>>24,b+=2)}if(m>=0)for(r[m--]=p;m>=0;)r[m--]=0},Math.clz32?o.prototype._countBits=function(r){return 32-Math.clz32(r)}:o.prototype._countBits=function(r){var c=r,m=0;return c>=4096&&(m+=13,c>>>=13),c>=64&&(m+=7,c>>>=7),c>=8&&(m+=4,c>>>=4),c>=2&&(m+=2,c>>>=2),m+c},o.prototype._zeroBits=function(r){if(r===0)return 26;var c=r,m=0;return c&8191||(m+=13,c>>>=13),c&127||(m+=7,c>>>=7),c&15||(m+=4,c>>>=4),c&3||(m+=2,c>>>=2),c&1||m++,m},o.prototype.bitLength=function(){var r=this.words[this.length-1],c=this._countBits(r);return(this.length-1)*26+c};function O(y){for(var r=new Array(y.bitLength()),c=0;c<r.length;c++){var m=c/26|0,p=c%26;r[c]=y.words[m]>>>p&1}return r}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,c=0;c<this.length;c++){var m=this._zeroBits(this.words[c]);if(r+=m,m!==26)break}return r},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(r){return this.negative!==0?this.abs().inotn(r).iaddn(1):this.clone()},o.prototype.fromTwos=function(r){return this.testn(r-1)?this.notn(r).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return this.negative!==0},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(r){for(;this.length<r.length;)this.words[this.length++]=0;for(var c=0;c<r.length;c++)this.words[c]=this.words[c]|r.words[c];return this._strip()},o.prototype.ior=function(r){return t((this.negative|r.negative)===0),this.iuor(r)},o.prototype.or=function(r){return this.length>r.length?this.clone().ior(r):r.clone().ior(this)},o.prototype.uor=function(r){return this.length>r.length?this.clone().iuor(r):r.clone().iuor(this)},o.prototype.iuand=function(r){var c;this.length>r.length?c=r:c=this;for(var m=0;m<c.length;m++)this.words[m]=this.words[m]&r.words[m];return this.length=c.length,this._strip()},o.prototype.iand=function(r){return t((this.negative|r.negative)===0),this.iuand(r)},o.prototype.and=function(r){return this.length>r.length?this.clone().iand(r):r.clone().iand(this)},o.prototype.uand=function(r){return this.length>r.length?this.clone().iuand(r):r.clone().iuand(this)},o.prototype.iuxor=function(r){var c,m;this.length>r.length?(c=this,m=r):(c=r,m=this);for(var p=0;p<m.length;p++)this.words[p]=c.words[p]^m.words[p];if(this!==c)for(;p<c.length;p++)this.words[p]=c.words[p];return this.length=c.length,this._strip()},o.prototype.ixor=function(r){return t((this.negative|r.negative)===0),this.iuxor(r)},o.prototype.xor=function(r){return this.length>r.length?this.clone().ixor(r):r.clone().ixor(this)},o.prototype.uxor=function(r){return this.length>r.length?this.clone().iuxor(r):r.clone().iuxor(this)},o.prototype.inotn=function(r){t(typeof r=="number"&&r>=0);var c=Math.ceil(r/26)|0,m=r%26;this._expand(c),m>0&&c--;for(var p=0;p<c;p++)this.words[p]=~this.words[p]&67108863;return m>0&&(this.words[p]=~this.words[p]&67108863>>26-m),this._strip()},o.prototype.notn=function(r){return this.clone().inotn(r)},o.prototype.setn=function(r,c){t(typeof r=="number"&&r>=0);var m=r/26|0,p=r%26;return this._expand(m+1),c?this.words[m]=this.words[m]|1<<p:this.words[m]=this.words[m]&~(1<<p),this._strip()},o.prototype.iadd=function(r){var c;if(this.negative!==0&&r.negative===0)return this.negative=0,c=this.isub(r),this.negative^=1,this._normSign();if(this.negative===0&&r.negative!==0)return r.negative=0,c=this.isub(r),r.negative=1,c._normSign();var m,p;this.length>r.length?(m=this,p=r):(m=r,p=this);for(var f=0,b=0;b<p.length;b++)c=(m.words[b]|0)+(p.words[b]|0)+f,this.words[b]=c&67108863,f=c>>>26;for(;f!==0&&b<m.length;b++)c=(m.words[b]|0)+f,this.words[b]=c&67108863,f=c>>>26;if(this.length=m.length,f!==0)this.words[this.length]=f,this.length++;else if(m!==this)for(;b<m.length;b++)this.words[b]=m.words[b];return this},o.prototype.add=function(r){var c;return r.negative!==0&&this.negative===0?(r.negative=0,c=this.sub(r),r.negative^=1,c):r.negative===0&&this.negative!==0?(this.negative=0,c=r.sub(this),this.negative=1,c):this.length>r.length?this.clone().iadd(r):r.clone().iadd(this)},o.prototype.isub=function(r){if(r.negative!==0){r.negative=0;var c=this.iadd(r);return r.negative=1,c._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(r),this.negative=1,this._normSign();var m=this.cmp(r);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,f;m>0?(p=this,f=r):(p=r,f=this);for(var b=0,w=0;w<f.length;w++)c=(p.words[w]|0)-(f.words[w]|0)+b,b=c>>26,this.words[w]=c&67108863;for(;b!==0&&w<p.length;w++)c=(p.words[w]|0)+b,b=c>>26,this.words[w]=c&67108863;if(b===0&&w<p.length&&p!==this)for(;w<p.length;w++)this.words[w]=p.words[w];return this.length=Math.max(this.length,w),p!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(r){return this.clone().isub(r)};function L(y,r,c){c.negative=r.negative^y.negative;var m=y.length+r.length|0;c.length=m,m=m-1|0;var p=y.words[0]|0,f=r.words[0]|0,b=p*f,w=b&67108863,d=b/67108864|0;c.words[0]=w;for(var s=1;s<m;s++){for(var h=d>>>26,D=d&67108863,A=Math.min(s,r.length-1),M=Math.max(0,s-y.length+1);M<=A;M++){var E=s-M|0;p=y.words[E]|0,f=r.words[M]|0,b=p*f+D,h+=b/67108864|0,D=b&67108863}c.words[s]=D|0,d=h|0}return d!==0?c.words[s]=d|0:c.length--,c._strip()}var $=function(r,c,m){var p=r.words,f=c.words,b=m.words,w=0,d,s,h,D=p[0]|0,A=D&8191,M=D>>>13,E=p[1]|0,_=E&8191,U=E>>>13,Zt=p[2]|0,q=Zt&8191,F=Zt>>>13,Fi=p[3]|0,G=Fi&8191,z=Fi>>>13,Ki=p[4]|0,Q=Ki&8191,J=Ki>>>13,$i=p[5]|0,X=$i&8191,Y=$i>>>13,Vi=p[6]|0,Z=Vi&8191,tt=Vi>>>13,Hi=p[7]|0,et=Hi&8191,nt=Hi>>>13,Gi=p[8]|0,ot=Gi&8191,at=Gi>>>13,zi=p[9]|0,rt=zi&8191,it=zi>>>13,Qi=f[0]|0,st=Qi&8191,ct=Qi>>>13,Ji=f[1]|0,lt=Ji&8191,ut=Ji>>>13,Xi=f[2]|0,mt=Xi&8191,pt=Xi>>>13,Yi=f[3]|0,dt=Yi&8191,ft=Yi>>>13,Zi=f[4]|0,ht=Zi&8191,gt=Zi>>>13,ts=f[5]|0,yt=ts&8191,bt=ts>>>13,es=f[6]|0,Tt=es&8191,wt=es>>>13,ns=f[7]|0,St=ns&8191,Ct=ns>>>13,os=f[8]|0,It=os&8191,kt=os>>>13,as=f[9]|0,xt=as&8191,vt=as>>>13;m.negative=r.negative^c.negative,m.length=19,d=Math.imul(A,st),s=Math.imul(A,ct),s=s+Math.imul(M,st)|0,h=Math.imul(M,ct);var Br=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Br>>>26)|0,Br&=67108863,d=Math.imul(_,st),s=Math.imul(_,ct),s=s+Math.imul(U,st)|0,h=Math.imul(U,ct),d=d+Math.imul(A,lt)|0,s=s+Math.imul(A,ut)|0,s=s+Math.imul(M,lt)|0,h=h+Math.imul(M,ut)|0;var Er=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Er>>>26)|0,Er&=67108863,d=Math.imul(q,st),s=Math.imul(q,ct),s=s+Math.imul(F,st)|0,h=Math.imul(F,ct),d=d+Math.imul(_,lt)|0,s=s+Math.imul(_,ut)|0,s=s+Math.imul(U,lt)|0,h=h+Math.imul(U,ut)|0,d=d+Math.imul(A,mt)|0,s=s+Math.imul(A,pt)|0,s=s+Math.imul(M,mt)|0,h=h+Math.imul(M,pt)|0;var Nr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Nr>>>26)|0,Nr&=67108863,d=Math.imul(G,st),s=Math.imul(G,ct),s=s+Math.imul(z,st)|0,h=Math.imul(z,ct),d=d+Math.imul(q,lt)|0,s=s+Math.imul(q,ut)|0,s=s+Math.imul(F,lt)|0,h=h+Math.imul(F,ut)|0,d=d+Math.imul(_,mt)|0,s=s+Math.imul(_,pt)|0,s=s+Math.imul(U,mt)|0,h=h+Math.imul(U,pt)|0,d=d+Math.imul(A,dt)|0,s=s+Math.imul(A,ft)|0,s=s+Math.imul(M,dt)|0,h=h+Math.imul(M,ft)|0;var Wr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Wr>>>26)|0,Wr&=67108863,d=Math.imul(Q,st),s=Math.imul(Q,ct),s=s+Math.imul(J,st)|0,h=Math.imul(J,ct),d=d+Math.imul(G,lt)|0,s=s+Math.imul(G,ut)|0,s=s+Math.imul(z,lt)|0,h=h+Math.imul(z,ut)|0,d=d+Math.imul(q,mt)|0,s=s+Math.imul(q,pt)|0,s=s+Math.imul(F,mt)|0,h=h+Math.imul(F,pt)|0,d=d+Math.imul(_,dt)|0,s=s+Math.imul(_,ft)|0,s=s+Math.imul(U,dt)|0,h=h+Math.imul(U,ft)|0,d=d+Math.imul(A,ht)|0,s=s+Math.imul(A,gt)|0,s=s+Math.imul(M,ht)|0,h=h+Math.imul(M,gt)|0;var _r=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(_r>>>26)|0,_r&=67108863,d=Math.imul(X,st),s=Math.imul(X,ct),s=s+Math.imul(Y,st)|0,h=Math.imul(Y,ct),d=d+Math.imul(Q,lt)|0,s=s+Math.imul(Q,ut)|0,s=s+Math.imul(J,lt)|0,h=h+Math.imul(J,ut)|0,d=d+Math.imul(G,mt)|0,s=s+Math.imul(G,pt)|0,s=s+Math.imul(z,mt)|0,h=h+Math.imul(z,pt)|0,d=d+Math.imul(q,dt)|0,s=s+Math.imul(q,ft)|0,s=s+Math.imul(F,dt)|0,h=h+Math.imul(F,ft)|0,d=d+Math.imul(_,ht)|0,s=s+Math.imul(_,gt)|0,s=s+Math.imul(U,ht)|0,h=h+Math.imul(U,gt)|0,d=d+Math.imul(A,yt)|0,s=s+Math.imul(A,bt)|0,s=s+Math.imul(M,yt)|0,h=h+Math.imul(M,bt)|0;var Lr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Lr>>>26)|0,Lr&=67108863,d=Math.imul(Z,st),s=Math.imul(Z,ct),s=s+Math.imul(tt,st)|0,h=Math.imul(tt,ct),d=d+Math.imul(X,lt)|0,s=s+Math.imul(X,ut)|0,s=s+Math.imul(Y,lt)|0,h=h+Math.imul(Y,ut)|0,d=d+Math.imul(Q,mt)|0,s=s+Math.imul(Q,pt)|0,s=s+Math.imul(J,mt)|0,h=h+Math.imul(J,pt)|0,d=d+Math.imul(G,dt)|0,s=s+Math.imul(G,ft)|0,s=s+Math.imul(z,dt)|0,h=h+Math.imul(z,ft)|0,d=d+Math.imul(q,ht)|0,s=s+Math.imul(q,gt)|0,s=s+Math.imul(F,ht)|0,h=h+Math.imul(F,gt)|0,d=d+Math.imul(_,yt)|0,s=s+Math.imul(_,bt)|0,s=s+Math.imul(U,yt)|0,h=h+Math.imul(U,bt)|0,d=d+Math.imul(A,Tt)|0,s=s+Math.imul(A,wt)|0,s=s+Math.imul(M,Tt)|0,h=h+Math.imul(M,wt)|0;var jr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(jr>>>26)|0,jr&=67108863,d=Math.imul(et,st),s=Math.imul(et,ct),s=s+Math.imul(nt,st)|0,h=Math.imul(nt,ct),d=d+Math.imul(Z,lt)|0,s=s+Math.imul(Z,ut)|0,s=s+Math.imul(tt,lt)|0,h=h+Math.imul(tt,ut)|0,d=d+Math.imul(X,mt)|0,s=s+Math.imul(X,pt)|0,s=s+Math.imul(Y,mt)|0,h=h+Math.imul(Y,pt)|0,d=d+Math.imul(Q,dt)|0,s=s+Math.imul(Q,ft)|0,s=s+Math.imul(J,dt)|0,h=h+Math.imul(J,ft)|0,d=d+Math.imul(G,ht)|0,s=s+Math.imul(G,gt)|0,s=s+Math.imul(z,ht)|0,h=h+Math.imul(z,gt)|0,d=d+Math.imul(q,yt)|0,s=s+Math.imul(q,bt)|0,s=s+Math.imul(F,yt)|0,h=h+Math.imul(F,bt)|0,d=d+Math.imul(_,Tt)|0,s=s+Math.imul(_,wt)|0,s=s+Math.imul(U,Tt)|0,h=h+Math.imul(U,wt)|0,d=d+Math.imul(A,St)|0,s=s+Math.imul(A,Ct)|0,s=s+Math.imul(M,St)|0,h=h+Math.imul(M,Ct)|0;var Ur=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Ur>>>26)|0,Ur&=67108863,d=Math.imul(ot,st),s=Math.imul(ot,ct),s=s+Math.imul(at,st)|0,h=Math.imul(at,ct),d=d+Math.imul(et,lt)|0,s=s+Math.imul(et,ut)|0,s=s+Math.imul(nt,lt)|0,h=h+Math.imul(nt,ut)|0,d=d+Math.imul(Z,mt)|0,s=s+Math.imul(Z,pt)|0,s=s+Math.imul(tt,mt)|0,h=h+Math.imul(tt,pt)|0,d=d+Math.imul(X,dt)|0,s=s+Math.imul(X,ft)|0,s=s+Math.imul(Y,dt)|0,h=h+Math.imul(Y,ft)|0,d=d+Math.imul(Q,ht)|0,s=s+Math.imul(Q,gt)|0,s=s+Math.imul(J,ht)|0,h=h+Math.imul(J,gt)|0,d=d+Math.imul(G,yt)|0,s=s+Math.imul(G,bt)|0,s=s+Math.imul(z,yt)|0,h=h+Math.imul(z,bt)|0,d=d+Math.imul(q,Tt)|0,s=s+Math.imul(q,wt)|0,s=s+Math.imul(F,Tt)|0,h=h+Math.imul(F,wt)|0,d=d+Math.imul(_,St)|0,s=s+Math.imul(_,Ct)|0,s=s+Math.imul(U,St)|0,h=h+Math.imul(U,Ct)|0,d=d+Math.imul(A,It)|0,s=s+Math.imul(A,kt)|0,s=s+Math.imul(M,It)|0,h=h+Math.imul(M,kt)|0;var qr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(qr>>>26)|0,qr&=67108863,d=Math.imul(rt,st),s=Math.imul(rt,ct),s=s+Math.imul(it,st)|0,h=Math.imul(it,ct),d=d+Math.imul(ot,lt)|0,s=s+Math.imul(ot,ut)|0,s=s+Math.imul(at,lt)|0,h=h+Math.imul(at,ut)|0,d=d+Math.imul(et,mt)|0,s=s+Math.imul(et,pt)|0,s=s+Math.imul(nt,mt)|0,h=h+Math.imul(nt,pt)|0,d=d+Math.imul(Z,dt)|0,s=s+Math.imul(Z,ft)|0,s=s+Math.imul(tt,dt)|0,h=h+Math.imul(tt,ft)|0,d=d+Math.imul(X,ht)|0,s=s+Math.imul(X,gt)|0,s=s+Math.imul(Y,ht)|0,h=h+Math.imul(Y,gt)|0,d=d+Math.imul(Q,yt)|0,s=s+Math.imul(Q,bt)|0,s=s+Math.imul(J,yt)|0,h=h+Math.imul(J,bt)|0,d=d+Math.imul(G,Tt)|0,s=s+Math.imul(G,wt)|0,s=s+Math.imul(z,Tt)|0,h=h+Math.imul(z,wt)|0,d=d+Math.imul(q,St)|0,s=s+Math.imul(q,Ct)|0,s=s+Math.imul(F,St)|0,h=h+Math.imul(F,Ct)|0,d=d+Math.imul(_,It)|0,s=s+Math.imul(_,kt)|0,s=s+Math.imul(U,It)|0,h=h+Math.imul(U,kt)|0,d=d+Math.imul(A,xt)|0,s=s+Math.imul(A,vt)|0,s=s+Math.imul(M,xt)|0,h=h+Math.imul(M,vt)|0;var Fr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Fr>>>26)|0,Fr&=67108863,d=Math.imul(rt,lt),s=Math.imul(rt,ut),s=s+Math.imul(it,lt)|0,h=Math.imul(it,ut),d=d+Math.imul(ot,mt)|0,s=s+Math.imul(ot,pt)|0,s=s+Math.imul(at,mt)|0,h=h+Math.imul(at,pt)|0,d=d+Math.imul(et,dt)|0,s=s+Math.imul(et,ft)|0,s=s+Math.imul(nt,dt)|0,h=h+Math.imul(nt,ft)|0,d=d+Math.imul(Z,ht)|0,s=s+Math.imul(Z,gt)|0,s=s+Math.imul(tt,ht)|0,h=h+Math.imul(tt,gt)|0,d=d+Math.imul(X,yt)|0,s=s+Math.imul(X,bt)|0,s=s+Math.imul(Y,yt)|0,h=h+Math.imul(Y,bt)|0,d=d+Math.imul(Q,Tt)|0,s=s+Math.imul(Q,wt)|0,s=s+Math.imul(J,Tt)|0,h=h+Math.imul(J,wt)|0,d=d+Math.imul(G,St)|0,s=s+Math.imul(G,Ct)|0,s=s+Math.imul(z,St)|0,h=h+Math.imul(z,Ct)|0,d=d+Math.imul(q,It)|0,s=s+Math.imul(q,kt)|0,s=s+Math.imul(F,It)|0,h=h+Math.imul(F,kt)|0,d=d+Math.imul(_,xt)|0,s=s+Math.imul(_,vt)|0,s=s+Math.imul(U,xt)|0,h=h+Math.imul(U,vt)|0;var Kr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Kr>>>26)|0,Kr&=67108863,d=Math.imul(rt,mt),s=Math.imul(rt,pt),s=s+Math.imul(it,mt)|0,h=Math.imul(it,pt),d=d+Math.imul(ot,dt)|0,s=s+Math.imul(ot,ft)|0,s=s+Math.imul(at,dt)|0,h=h+Math.imul(at,ft)|0,d=d+Math.imul(et,ht)|0,s=s+Math.imul(et,gt)|0,s=s+Math.imul(nt,ht)|0,h=h+Math.imul(nt,gt)|0,d=d+Math.imul(Z,yt)|0,s=s+Math.imul(Z,bt)|0,s=s+Math.imul(tt,yt)|0,h=h+Math.imul(tt,bt)|0,d=d+Math.imul(X,Tt)|0,s=s+Math.imul(X,wt)|0,s=s+Math.imul(Y,Tt)|0,h=h+Math.imul(Y,wt)|0,d=d+Math.imul(Q,St)|0,s=s+Math.imul(Q,Ct)|0,s=s+Math.imul(J,St)|0,h=h+Math.imul(J,Ct)|0,d=d+Math.imul(G,It)|0,s=s+Math.imul(G,kt)|0,s=s+Math.imul(z,It)|0,h=h+Math.imul(z,kt)|0,d=d+Math.imul(q,xt)|0,s=s+Math.imul(q,vt)|0,s=s+Math.imul(F,xt)|0,h=h+Math.imul(F,vt)|0;var $r=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+($r>>>26)|0,$r&=67108863,d=Math.imul(rt,dt),s=Math.imul(rt,ft),s=s+Math.imul(it,dt)|0,h=Math.imul(it,ft),d=d+Math.imul(ot,ht)|0,s=s+Math.imul(ot,gt)|0,s=s+Math.imul(at,ht)|0,h=h+Math.imul(at,gt)|0,d=d+Math.imul(et,yt)|0,s=s+Math.imul(et,bt)|0,s=s+Math.imul(nt,yt)|0,h=h+Math.imul(nt,bt)|0,d=d+Math.imul(Z,Tt)|0,s=s+Math.imul(Z,wt)|0,s=s+Math.imul(tt,Tt)|0,h=h+Math.imul(tt,wt)|0,d=d+Math.imul(X,St)|0,s=s+Math.imul(X,Ct)|0,s=s+Math.imul(Y,St)|0,h=h+Math.imul(Y,Ct)|0,d=d+Math.imul(Q,It)|0,s=s+Math.imul(Q,kt)|0,s=s+Math.imul(J,It)|0,h=h+Math.imul(J,kt)|0,d=d+Math.imul(G,xt)|0,s=s+Math.imul(G,vt)|0,s=s+Math.imul(z,xt)|0,h=h+Math.imul(z,vt)|0;var Vr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Vr>>>26)|0,Vr&=67108863,d=Math.imul(rt,ht),s=Math.imul(rt,gt),s=s+Math.imul(it,ht)|0,h=Math.imul(it,gt),d=d+Math.imul(ot,yt)|0,s=s+Math.imul(ot,bt)|0,s=s+Math.imul(at,yt)|0,h=h+Math.imul(at,bt)|0,d=d+Math.imul(et,Tt)|0,s=s+Math.imul(et,wt)|0,s=s+Math.imul(nt,Tt)|0,h=h+Math.imul(nt,wt)|0,d=d+Math.imul(Z,St)|0,s=s+Math.imul(Z,Ct)|0,s=s+Math.imul(tt,St)|0,h=h+Math.imul(tt,Ct)|0,d=d+Math.imul(X,It)|0,s=s+Math.imul(X,kt)|0,s=s+Math.imul(Y,It)|0,h=h+Math.imul(Y,kt)|0,d=d+Math.imul(Q,xt)|0,s=s+Math.imul(Q,vt)|0,s=s+Math.imul(J,xt)|0,h=h+Math.imul(J,vt)|0;var Hr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Hr>>>26)|0,Hr&=67108863,d=Math.imul(rt,yt),s=Math.imul(rt,bt),s=s+Math.imul(it,yt)|0,h=Math.imul(it,bt),d=d+Math.imul(ot,Tt)|0,s=s+Math.imul(ot,wt)|0,s=s+Math.imul(at,Tt)|0,h=h+Math.imul(at,wt)|0,d=d+Math.imul(et,St)|0,s=s+Math.imul(et,Ct)|0,s=s+Math.imul(nt,St)|0,h=h+Math.imul(nt,Ct)|0,d=d+Math.imul(Z,It)|0,s=s+Math.imul(Z,kt)|0,s=s+Math.imul(tt,It)|0,h=h+Math.imul(tt,kt)|0,d=d+Math.imul(X,xt)|0,s=s+Math.imul(X,vt)|0,s=s+Math.imul(Y,xt)|0,h=h+Math.imul(Y,vt)|0;var Gr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Gr>>>26)|0,Gr&=67108863,d=Math.imul(rt,Tt),s=Math.imul(rt,wt),s=s+Math.imul(it,Tt)|0,h=Math.imul(it,wt),d=d+Math.imul(ot,St)|0,s=s+Math.imul(ot,Ct)|0,s=s+Math.imul(at,St)|0,h=h+Math.imul(at,Ct)|0,d=d+Math.imul(et,It)|0,s=s+Math.imul(et,kt)|0,s=s+Math.imul(nt,It)|0,h=h+Math.imul(nt,kt)|0,d=d+Math.imul(Z,xt)|0,s=s+Math.imul(Z,vt)|0,s=s+Math.imul(tt,xt)|0,h=h+Math.imul(tt,vt)|0;var zr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(zr>>>26)|0,zr&=67108863,d=Math.imul(rt,St),s=Math.imul(rt,Ct),s=s+Math.imul(it,St)|0,h=Math.imul(it,Ct),d=d+Math.imul(ot,It)|0,s=s+Math.imul(ot,kt)|0,s=s+Math.imul(at,It)|0,h=h+Math.imul(at,kt)|0,d=d+Math.imul(et,xt)|0,s=s+Math.imul(et,vt)|0,s=s+Math.imul(nt,xt)|0,h=h+Math.imul(nt,vt)|0;var Qr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,d=Math.imul(rt,It),s=Math.imul(rt,kt),s=s+Math.imul(it,It)|0,h=Math.imul(it,kt),d=d+Math.imul(ot,xt)|0,s=s+Math.imul(ot,vt)|0,s=s+Math.imul(at,xt)|0,h=h+Math.imul(at,vt)|0;var Jr=(w+d|0)+((s&8191)<<13)|0;w=(h+(s>>>13)|0)+(Jr>>>26)|0,Jr&=67108863,d=Math.imul(rt,xt),s=Math.imul(rt,vt),s=s+Math.imul(it,xt)|0,h=Math.imul(it,vt);var Xr=(w+d|0)+((s&8191)<<13)|0;return w=(h+(s>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,b[0]=Br,b[1]=Er,b[2]=Nr,b[3]=Wr,b[4]=_r,b[5]=Lr,b[6]=jr,b[7]=Ur,b[8]=qr,b[9]=Fr,b[10]=Kr,b[11]=$r,b[12]=Vr,b[13]=Hr,b[14]=Gr,b[15]=zr,b[16]=Qr,b[17]=Jr,b[18]=Xr,w!==0&&(b[19]=w,m.length++),m};Math.imul||($=L);function Wt(y,r,c){c.negative=r.negative^y.negative,c.length=y.length+r.length;for(var m=0,p=0,f=0;f<c.length-1;f++){var b=p;p=0;for(var w=m&67108863,d=Math.min(f,r.length-1),s=Math.max(0,f-y.length+1);s<=d;s++){var h=f-s,D=y.words[h]|0,A=r.words[s]|0,M=D*A,E=M&67108863;b=b+(M/67108864|0)|0,E=E+w|0,w=E&67108863,b=b+(E>>>26)|0,p+=b>>>26,b&=67108863}c.words[f]=w,m=b,b=p}return m!==0?c.words[f]=m:c.length--,c._strip()}function Bt(y,r,c){return Wt(y,r,c)}o.prototype.mulTo=function(r,c){var m,p=this.length+r.length;return this.length===10&&r.length===10?m=$(this,r,c):p<63?m=L(this,r,c):p<1024?m=Wt(this,r,c):m=Bt(this,r,c),m};function Et(y,r){this.x=y,this.y=r}Et.prototype.makeRBT=function(r){for(var c=new Array(r),m=o.prototype._countBits(r)-1,p=0;p<r;p++)c[p]=this.revBin(p,m,r);return c},Et.prototype.revBin=function(r,c,m){if(r===0||r===m-1)return r;for(var p=0,f=0;f<c;f++)p|=(r&1)<<c-f-1,r>>=1;return p},Et.prototype.permute=function(r,c,m,p,f,b){for(var w=0;w<b;w++)p[w]=c[r[w]],f[w]=m[r[w]]},Et.prototype.transform=function(r,c,m,p,f,b){this.permute(b,r,c,m,p,f);for(var w=1;w<f;w<<=1)for(var d=w<<1,s=Math.cos(2*Math.PI/d),h=Math.sin(2*Math.PI/d),D=0;D<f;D+=d)for(var A=s,M=h,E=0;E<w;E++){var _=m[D+E],U=p[D+E],Zt=m[D+E+w],q=p[D+E+w],F=A*Zt-M*q;q=A*q+M*Zt,Zt=F,m[D+E]=_+Zt,p[D+E]=U+q,m[D+E+w]=_-Zt,p[D+E+w]=U-q,E!==d&&(F=s*A-h*M,M=s*M+h*A,A=F)}},Et.prototype.guessLen13b=function(r,c){var m=Math.max(c,r)|1,p=m&1,f=0;for(m=m/2|0;m;m=m>>>1)f++;return 1<<f+1+p},Et.prototype.conjugate=function(r,c,m){if(!(m<=1))for(var p=0;p<m/2;p++){var f=r[p];r[p]=r[m-p-1],r[m-p-1]=f,f=c[p],c[p]=-c[m-p-1],c[m-p-1]=-f}},Et.prototype.normalize13b=function(r,c){for(var m=0,p=0;p<c/2;p++){var f=Math.round(r[2*p+1]/c)*8192+Math.round(r[2*p]/c)+m;r[p]=f&67108863,f<67108864?m=0:m=f/67108864|0}return r},Et.prototype.convert13b=function(r,c,m,p){for(var f=0,b=0;b<c;b++)f=f+(r[b]|0),m[2*b]=f&8191,f=f>>>13,m[2*b+1]=f&8191,f=f>>>13;for(b=2*c;b<p;++b)m[b]=0;t(f===0),t((f&-8192)===0)},Et.prototype.stub=function(r){for(var c=new Array(r),m=0;m<r;m++)c[m]=0;return c},Et.prototype.mulp=function(r,c,m){var p=2*this.guessLen13b(r.length,c.length),f=this.makeRBT(p),b=this.stub(p),w=new Array(p),d=new Array(p),s=new Array(p),h=new Array(p),D=new Array(p),A=new Array(p),M=m.words;M.length=p,this.convert13b(r.words,r.length,w,p),this.convert13b(c.words,c.length,h,p),this.transform(w,b,d,s,p,f),this.transform(h,b,D,A,p,f);for(var E=0;E<p;E++){var _=d[E]*D[E]-s[E]*A[E];s[E]=d[E]*A[E]+s[E]*D[E],d[E]=_}return this.conjugate(d,s,p),this.transform(d,s,M,b,p,f),this.conjugate(M,b,p),this.normalize13b(M,p),m.negative=r.negative^c.negative,m.length=r.length+c.length,m._strip()},o.prototype.mul=function(r){var c=new o(null);return c.words=new Array(this.length+r.length),this.mulTo(r,c)},o.prototype.mulf=function(r){var c=new o(null);return c.words=new Array(this.length+r.length),Bt(this,r,c)},o.prototype.imul=function(r){return this.clone().mulTo(r,this)},o.prototype.imuln=function(r){var c=r<0;c&&(r=-r),t(typeof r=="number"),t(r<67108864);for(var m=0,p=0;p<this.length;p++){var f=(this.words[p]|0)*r,b=(f&67108863)+(m&67108863);m>>=26,m+=f/67108864|0,m+=b>>>26,this.words[p]=b&67108863}return m!==0&&(this.words[p]=m,this.length++),c?this.ineg():this},o.prototype.muln=function(r){return this.clone().imuln(r)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(r){var c=O(r);if(c.length===0)return new o(1);for(var m=this,p=0;p<c.length&&c[p]===0;p++,m=m.sqr());if(++p<c.length)for(var f=m.sqr();p<c.length;p++,f=f.sqr())c[p]!==0&&(m=m.mul(f));return m},o.prototype.iushln=function(r){t(typeof r=="number"&&r>=0);var c=r%26,m=(r-c)/26,p=67108863>>>26-c<<26-c,f;if(c!==0){var b=0;for(f=0;f<this.length;f++){var w=this.words[f]&p,d=(this.words[f]|0)-w<<c;this.words[f]=d|b,b=w>>>26-c}b&&(this.words[f]=b,this.length++)}if(m!==0){for(f=this.length-1;f>=0;f--)this.words[f+m]=this.words[f];for(f=0;f<m;f++)this.words[f]=0;this.length+=m}return this._strip()},o.prototype.ishln=function(r){return t(this.negative===0),this.iushln(r)},o.prototype.iushrn=function(r,c,m){t(typeof r=="number"&&r>=0);var p;c?p=(c-c%26)/26:p=0;var f=r%26,b=Math.min((r-f)/26,this.length),w=67108863^67108863>>>f<<f,d=m;if(p-=b,p=Math.max(0,p),d){for(var s=0;s<b;s++)d.words[s]=this.words[s];d.length=b}if(b!==0)if(this.length>b)for(this.length-=b,s=0;s<this.length;s++)this.words[s]=this.words[s+b];else this.words[0]=0,this.length=1;var h=0;for(s=this.length-1;s>=0&&(h!==0||s>=p);s--){var D=this.words[s]|0;this.words[s]=h<<26-f|D>>>f,h=D&w}return d&&h!==0&&(d.words[d.length++]=h),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(r,c,m){return t(this.negative===0),this.iushrn(r,c,m)},o.prototype.shln=function(r){return this.clone().ishln(r)},o.prototype.ushln=function(r){return this.clone().iushln(r)},o.prototype.shrn=function(r){return this.clone().ishrn(r)},o.prototype.ushrn=function(r){return this.clone().iushrn(r)},o.prototype.testn=function(r){t(typeof r=="number"&&r>=0);var c=r%26,m=(r-c)/26,p=1<<c;if(this.length<=m)return!1;var f=this.words[m];return!!(f&p)},o.prototype.imaskn=function(r){t(typeof r=="number"&&r>=0);var c=r%26,m=(r-c)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(c!==0&&m++,this.length=Math.min(m,this.length),c!==0){var p=67108863^67108863>>>c<<c;this.words[this.length-1]&=p}return this._strip()},o.prototype.maskn=function(r){return this.clone().imaskn(r)},o.prototype.iaddn=function(r){return t(typeof r=="number"),t(r<67108864),r<0?this.isubn(-r):this.negative!==0?this.length===1&&(this.words[0]|0)<=r?(this.words[0]=r-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(r),this.negative=1,this):this._iaddn(r)},o.prototype._iaddn=function(r){this.words[0]+=r;for(var c=0;c<this.length&&this.words[c]>=67108864;c++)this.words[c]-=67108864,c===this.length-1?this.words[c+1]=1:this.words[c+1]++;return this.length=Math.max(this.length,c+1),this},o.prototype.isubn=function(r){if(t(typeof r=="number"),t(r<67108864),r<0)return this.iaddn(-r);if(this.negative!==0)return this.negative=0,this.iaddn(r),this.negative=1,this;if(this.words[0]-=r,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var c=0;c<this.length&&this.words[c]<0;c++)this.words[c]+=67108864,this.words[c+1]-=1;return this._strip()},o.prototype.addn=function(r){return this.clone().iaddn(r)},o.prototype.subn=function(r){return this.clone().isubn(r)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(r,c,m){var p=r.length+m,f;this._expand(p);var b,w=0;for(f=0;f<r.length;f++){b=(this.words[f+m]|0)+w;var d=(r.words[f]|0)*c;b-=d&67108863,w=(b>>26)-(d/67108864|0),this.words[f+m]=b&67108863}for(;f<this.length-m;f++)b=(this.words[f+m]|0)+w,w=b>>26,this.words[f+m]=b&67108863;if(w===0)return this._strip();for(t(w===-1),w=0,f=0;f<this.length;f++)b=-(this.words[f]|0)+w,w=b>>26,this.words[f]=b&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(r,c){var m=this.length-r.length,p=this.clone(),f=r,b=f.words[f.length-1]|0,w=this._countBits(b);m=26-w,m!==0&&(f=f.ushln(m),p.iushln(m),b=f.words[f.length-1]|0);var d=p.length-f.length,s;if(c!=="mod"){s=new o(null),s.length=d+1,s.words=new Array(s.length);for(var h=0;h<s.length;h++)s.words[h]=0}var D=p.clone()._ishlnsubmul(f,1,d);D.negative===0&&(p=D,s&&(s.words[d]=1));for(var A=d-1;A>=0;A--){var M=(p.words[f.length+A]|0)*67108864+(p.words[f.length+A-1]|0);for(M=Math.min(M/b|0,67108863),p._ishlnsubmul(f,M,A);p.negative!==0;)M--,p.negative=0,p._ishlnsubmul(f,1,A),p.isZero()||(p.negative^=1);s&&(s.words[A]=M)}return s&&s._strip(),p._strip(),c!=="div"&&m!==0&&p.iushrn(m),{div:s||null,mod:p}},o.prototype.divmod=function(r,c,m){if(t(!r.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var p,f,b;return this.negative!==0&&r.negative===0?(b=this.neg().divmod(r,c),c!=="mod"&&(p=b.div.neg()),c!=="div"&&(f=b.mod.neg(),m&&f.negative!==0&&f.iadd(r)),{div:p,mod:f}):this.negative===0&&r.negative!==0?(b=this.divmod(r.neg(),c),c!=="mod"&&(p=b.div.neg()),{div:p,mod:b.mod}):this.negative&r.negative?(b=this.neg().divmod(r.neg(),c),c!=="div"&&(f=b.mod.neg(),m&&f.negative!==0&&f.isub(r)),{div:b.div,mod:f}):r.length>this.length||this.cmp(r)<0?{div:new o(0),mod:this}:r.length===1?c==="div"?{div:this.divn(r.words[0]),mod:null}:c==="mod"?{div:null,mod:new o(this.modrn(r.words[0]))}:{div:this.divn(r.words[0]),mod:new o(this.modrn(r.words[0]))}:this._wordDiv(r,c)},o.prototype.div=function(r){return this.divmod(r,"div",!1).div},o.prototype.mod=function(r){return this.divmod(r,"mod",!1).mod},o.prototype.umod=function(r){return this.divmod(r,"mod",!0).mod},o.prototype.divRound=function(r){var c=this.divmod(r);if(c.mod.isZero())return c.div;var m=c.div.negative!==0?c.mod.isub(r):c.mod,p=r.ushrn(1),f=r.andln(1),b=m.cmp(p);return b<0||f===1&&b===0?c.div:c.div.negative!==0?c.div.isubn(1):c.div.iaddn(1)},o.prototype.modrn=function(r){var c=r<0;c&&(r=-r),t(r<=67108863);for(var m=(1<<26)%r,p=0,f=this.length-1;f>=0;f--)p=(m*p+(this.words[f]|0))%r;return c?-p:p},o.prototype.modn=function(r){return this.modrn(r)},o.prototype.idivn=function(r){var c=r<0;c&&(r=-r),t(r<=67108863);for(var m=0,p=this.length-1;p>=0;p--){var f=(this.words[p]|0)+m*67108864;this.words[p]=f/r|0,m=f%r}return this._strip(),c?this.ineg():this},o.prototype.divn=function(r){return this.clone().idivn(r)},o.prototype.egcd=function(r){t(r.negative===0),t(!r.isZero());var c=this,m=r.clone();c.negative!==0?c=c.umod(r):c=c.clone();for(var p=new o(1),f=new o(0),b=new o(0),w=new o(1),d=0;c.isEven()&&m.isEven();)c.iushrn(1),m.iushrn(1),++d;for(var s=m.clone(),h=c.clone();!c.isZero();){for(var D=0,A=1;!(c.words[0]&A)&&D<26;++D,A<<=1);if(D>0)for(c.iushrn(D);D-- >0;)(p.isOdd()||f.isOdd())&&(p.iadd(s),f.isub(h)),p.iushrn(1),f.iushrn(1);for(var M=0,E=1;!(m.words[0]&E)&&M<26;++M,E<<=1);if(M>0)for(m.iushrn(M);M-- >0;)(b.isOdd()||w.isOdd())&&(b.iadd(s),w.isub(h)),b.iushrn(1),w.iushrn(1);c.cmp(m)>=0?(c.isub(m),p.isub(b),f.isub(w)):(m.isub(c),b.isub(p),w.isub(f))}return{a:b,b:w,gcd:m.iushln(d)}},o.prototype._invmp=function(r){t(r.negative===0),t(!r.isZero());var c=this,m=r.clone();c.negative!==0?c=c.umod(r):c=c.clone();for(var p=new o(1),f=new o(0),b=m.clone();c.cmpn(1)>0&&m.cmpn(1)>0;){for(var w=0,d=1;!(c.words[0]&d)&&w<26;++w,d<<=1);if(w>0)for(c.iushrn(w);w-- >0;)p.isOdd()&&p.iadd(b),p.iushrn(1);for(var s=0,h=1;!(m.words[0]&h)&&s<26;++s,h<<=1);if(s>0)for(m.iushrn(s);s-- >0;)f.isOdd()&&f.iadd(b),f.iushrn(1);c.cmp(m)>=0?(c.isub(m),p.isub(f)):(m.isub(c),f.isub(p))}var D;return c.cmpn(1)===0?D=p:D=f,D.cmpn(0)<0&&D.iadd(r),D},o.prototype.gcd=function(r){if(this.isZero())return r.abs();if(r.isZero())return this.abs();var c=this.clone(),m=r.clone();c.negative=0,m.negative=0;for(var p=0;c.isEven()&&m.isEven();p++)c.iushrn(1),m.iushrn(1);do{for(;c.isEven();)c.iushrn(1);for(;m.isEven();)m.iushrn(1);var f=c.cmp(m);if(f<0){var b=c;c=m,m=b}else if(f===0||m.cmpn(1)===0)break;c.isub(m)}while(!0);return m.iushln(p)},o.prototype.invm=function(r){return this.egcd(r).a.umod(r)},o.prototype.isEven=function(){return(this.words[0]&1)===0},o.prototype.isOdd=function(){return(this.words[0]&1)===1},o.prototype.andln=function(r){return this.words[0]&r},o.prototype.bincn=function(r){t(typeof r=="number");var c=r%26,m=(r-c)/26,p=1<<c;if(this.length<=m)return this._expand(m+1),this.words[m]|=p,this;for(var f=p,b=m;f!==0&&b<this.length;b++){var w=this.words[b]|0;w+=f,f=w>>>26,w&=67108863,this.words[b]=w}return f!==0&&(this.words[b]=f,this.length++),this},o.prototype.isZero=function(){return this.length===1&&this.words[0]===0},o.prototype.cmpn=function(r){var c=r<0;if(this.negative!==0&&!c)return-1;if(this.negative===0&&c)return 1;this._strip();var m;if(this.length>1)m=1;else{c&&(r=-r),t(r<=67108863,"Number is too big");var p=this.words[0]|0;m=p===r?0:p<r?-1:1}return this.negative!==0?-m|0:m},o.prototype.cmp=function(r){if(this.negative!==0&&r.negative===0)return-1;if(this.negative===0&&r.negative!==0)return 1;var c=this.ucmp(r);return this.negative!==0?-c|0:c},o.prototype.ucmp=function(r){if(this.length>r.length)return 1;if(this.length<r.length)return-1;for(var c=0,m=this.length-1;m>=0;m--){var p=this.words[m]|0,f=r.words[m]|0;if(p!==f){p<f?c=-1:p>f&&(c=1);break}}return c},o.prototype.gtn=function(r){return this.cmpn(r)===1},o.prototype.gt=function(r){return this.cmp(r)===1},o.prototype.gten=function(r){return this.cmpn(r)>=0},o.prototype.gte=function(r){return this.cmp(r)>=0},o.prototype.ltn=function(r){return this.cmpn(r)===-1},o.prototype.lt=function(r){return this.cmp(r)===-1},o.prototype.lten=function(r){return this.cmpn(r)<=0},o.prototype.lte=function(r){return this.cmp(r)<=0},o.prototype.eqn=function(r){return this.cmpn(r)===0},o.prototype.eq=function(r){return this.cmp(r)===0},o.red=function(r){return new V(r)},o.prototype.toRed=function(r){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),r.convertTo(this)._forceRed(r)},o.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(r){return this.red=r,this},o.prototype.forceRed=function(r){return t(!this.red,"Already a number in reduction context"),this._forceRed(r)},o.prototype.redAdd=function(r){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,r)},o.prototype.redIAdd=function(r){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,r)},o.prototype.redSub=function(r){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,r)},o.prototype.redISub=function(r){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,r)},o.prototype.redShl=function(r){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,r)},o.prototype.redMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.mul(this,r)},o.prototype.redIMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.imul(this,r)},o.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(r){return t(this.red&&!r.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,r)};var Pr={k256:null,p224:null,p192:null,p25519:null};function Lt(y,r){this.name=y,this.p=new o(r,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Lt.prototype._tmp=function(){var r=new o(null);return r.words=new Array(Math.ceil(this.n/13)),r},Lt.prototype.ireduce=function(r){var c=r,m;do this.split(c,this.tmp),c=this.imulK(c),c=c.iadd(this.tmp),m=c.bitLength();while(m>this.n);var p=m<this.n?-1:c.ucmp(this.p);return p===0?(c.words[0]=0,c.length=1):p>0?c.isub(this.p):c.strip!==void 0?c.strip():c._strip(),c},Lt.prototype.split=function(r,c){r.iushrn(this.n,0,c)},Lt.prototype.imulK=function(r){return r.imul(this.k)};function un(){Lt.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(un,Lt),un.prototype.split=function(r,c){for(var m=4194303,p=Math.min(r.length,9),f=0;f<p;f++)c.words[f]=r.words[f];if(c.length=p,r.length<=9){r.words[0]=0,r.length=1;return}var b=r.words[9];for(c.words[c.length++]=b&m,f=10;f<r.length;f++){var w=r.words[f]|0;r.words[f-10]=(w&m)<<4|b>>>22,b=w}b>>>=22,r.words[f-10]=b,b===0&&r.length>10?r.length-=10:r.length-=9},un.prototype.imulK=function(r){r.words[r.length]=0,r.words[r.length+1]=0,r.length+=2;for(var c=0,m=0;m<r.length;m++){var p=r.words[m]|0;c+=p*977,r.words[m]=c&67108863,c=p*64+(c/67108864|0)}return r.words[r.length-1]===0&&(r.length--,r.words[r.length-1]===0&&r.length--),r};function Ui(){Lt.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(Ui,Lt);function qi(){Lt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(qi,Lt);function Rr(){Lt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(Rr,Lt),Rr.prototype.imulK=function(r){for(var c=0,m=0;m<r.length;m++){var p=(r.words[m]|0)*19+c,f=p&67108863;p>>>=26,r.words[m]=f,c=p}return c!==0&&(r.words[r.length++]=c),r},o._prime=function(r){if(Pr[r])return Pr[r];var c;if(r==="k256")c=new un;else if(r==="p224")c=new Ui;else if(r==="p192")c=new qi;else if(r==="p25519")c=new Rr;else throw new Error("Unknown prime "+r);return Pr[r]=c,c};function V(y){if(typeof y=="string"){var r=o._prime(y);this.m=r.p,this.prime=r}else t(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}V.prototype._verify1=function(r){t(r.negative===0,"red works only with positives"),t(r.red,"red works only with red numbers")},V.prototype._verify2=function(r,c){t((r.negative|c.negative)===0,"red works only with positives"),t(r.red&&r.red===c.red,"red works only with red numbers")},V.prototype.imod=function(r){return this.prime?this.prime.ireduce(r)._forceRed(this):(T(r,r.umod(this.m)._forceRed(this)),r)},V.prototype.neg=function(r){return r.isZero()?r.clone():this.m.sub(r)._forceRed(this)},V.prototype.add=function(r,c){this._verify2(r,c);var m=r.add(c);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},V.prototype.iadd=function(r,c){this._verify2(r,c);var m=r.iadd(c);return m.cmp(this.m)>=0&&m.isub(this.m),m},V.prototype.sub=function(r,c){this._verify2(r,c);var m=r.sub(c);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},V.prototype.isub=function(r,c){this._verify2(r,c);var m=r.isub(c);return m.cmpn(0)<0&&m.iadd(this.m),m},V.prototype.shl=function(r,c){return this._verify1(r),this.imod(r.ushln(c))},V.prototype.imul=function(r,c){return this._verify2(r,c),this.imod(r.imul(c))},V.prototype.mul=function(r,c){return this._verify2(r,c),this.imod(r.mul(c))},V.prototype.isqr=function(r){return this.imul(r,r.clone())},V.prototype.sqr=function(r){return this.mul(r,r)},V.prototype.sqrt=function(r){if(r.isZero())return r.clone();var c=this.m.andln(3);if(t(c%2===1),c===3){var m=this.m.add(new o(1)).iushrn(2);return this.pow(r,m)}for(var p=this.m.subn(1),f=0;!p.isZero()&&p.andln(1)===0;)f++,p.iushrn(1);t(!p.isZero());var b=new o(1).toRed(this),w=b.redNeg(),d=this.m.subn(1).iushrn(1),s=this.m.bitLength();for(s=new o(2*s*s).toRed(this);this.pow(s,d).cmp(w)!==0;)s.redIAdd(w);for(var h=this.pow(s,p),D=this.pow(r,p.addn(1).iushrn(1)),A=this.pow(r,p),M=f;A.cmp(b)!==0;){for(var E=A,_=0;E.cmp(b)!==0;_++)E=E.redSqr();t(_<M);var U=this.pow(h,new o(1).iushln(M-_-1));D=D.redMul(U),h=U.redSqr(),A=A.redMul(h),M=_}return D},V.prototype.invm=function(r){var c=r._invmp(this.m);return c.negative!==0?(c.negative=0,this.imod(c).redNeg()):this.imod(c)},V.prototype.pow=function(r,c){if(c.isZero())return new o(1).toRed(this);if(c.cmpn(1)===0)return r.clone();var m=4,p=new Array(1<<m);p[0]=new o(1).toRed(this),p[1]=r;for(var f=2;f<p.length;f++)p[f]=this.mul(p[f-1],r);var b=p[0],w=0,d=0,s=c.bitLength()%26;for(s===0&&(s=26),f=c.length-1;f>=0;f--){for(var h=c.words[f],D=s-1;D>=0;D--){var A=h>>D&1;if(b!==p[0]&&(b=this.sqr(b)),A===0&&w===0){d=0;continue}w<<=1,w|=A,d++,!(d!==m&&(f!==0||D!==0))&&(b=this.mul(b,p[w]),d=0,w=0)}s=26}return b},V.prototype.convertTo=function(r){var c=r.umod(this.m);return c===r?c.clone():c},V.prototype.convertFrom=function(r){var c=r.clone();return c.red=null,c},o.mont=function(r){return new ue(r)};function ue(y){V.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(ue,V),ue.prototype.convertTo=function(r){return this.imod(r.ushln(this.shift))},ue.prototype.convertFrom=function(r){var c=this.imod(r.mul(this.rinv));return c.red=null,c},ue.prototype.imul=function(r,c){if(r.isZero()||c.isZero())return r.words[0]=0,r.length=1,r;var m=r.imul(c),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),f=m.isub(p).iushrn(this.shift),b=f;return f.cmp(this.m)>=0?b=f.isub(this.m):f.cmpn(0)<0&&(b=f.iadd(this.m)),b._forceRed(this)},ue.prototype.mul=function(r,c){if(r.isZero()||c.isZero())return new o(0)._forceRed(this);var m=r.mul(c),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),f=m.isub(p).iushrn(this.shift),b=f;return f.cmp(this.m)>=0?b=f.isub(this.m):f.cmpn(0)<0&&(b=f.iadd(this.m)),b._forceRed(this)},ue.prototype.invm=function(r){var c=this.imod(r._invmp(this.m).mul(this.r2));return c._forceRed(this)}})(typeof ji>"u"||ji,Zc)});import{TransactionType as kl}from"@msafe/sui3-utils";import{coinsList as hl,poolIdPoolNameMap as gl,poolInfo as is,singleAssetPoolCoinMap as yl}from"@alphafi/alphafi-sdk";import{TransactionType as Ne}from"@msafe/sui3-utils";import{bcs as mn,fromBase64 as pn}from"@mysten/bcs";var dn=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,n=t.pool_id,o=gl[n];if(console.log("Decoder event data - ",t),console.log("Decoder poolName - ",o),this.isWithdrawAlphaEvent(e))return this.decodeWithdrawAlpha(t);if(this.isWithdrawEvent(t))return this.decodeWithdraw(o);if(this.isDoubleAssetDepositEvent(t,o))return this.decodeDoubleAssetDeposit(o,t);if(this.isSingleAssetDepositEvent(t,o))return this.decodeSingleAssetDeposit(o,t);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(){return this.simResult.events.find(e=>this.isLiquidityChangeEventType(e.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(e){return e.includes("LiquidityChangeEvent")||e.includes("LiquidityChangeNewNewEvent")||e.includes("WithdrawEventV2")}isWithdrawAlphaEvent(e){return e.type.includes("WithdrawEventV2")}isWithdrawEvent(e){return e.event_type===1}isDoubleAssetDepositEvent(e,t){return e.event_type===0&&is[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&is[t].assetTypes.length===1}extractXTokensAmount(){let e=this.inputs.find(o=>o.Pure!==void 0);if(!e||!e.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:t}=e.Pure,n;return t.length===12?n=mn.u64().parse(pn(t)):t.length===24?n=mn.u128().parse(pn(t)):t.length===44?n=mn.u256().parse(pn(t)):n=mn.u64().parse(pn(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:o}=t,i=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,i),{txType:Ne.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:i?n:o,isAmountA:i}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:i}=yl[e],{expo:l}=hl[i];n=Math.floor(Number(n)/10**(9-l)).toString()}return{txType:Ne.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:Ne.Other,type:"withdraw",intentionData:{poolName:e,xTokensAmount:t}}}decodeWithdrawAlpha(e){let t=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=e;return console.log("Decoder.decodeWithdrawAlpha",t,n),{txType:Ne.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:Ne.Other,type:"claimReward",intentionData:{}}}};import{claimRewardTxb as Tl}from"@alphafi/alphafi-sdk";import bl from"sort-keys-recursive";var x=class{constructor(e){this.data=e}serialize(){return JSON.stringify(bl(this.data))}};var fn=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t;return await Tl(n.address)}static fromData(t){return new a(t)}};import{depositDoubleAssetTxb as wl}from"@alphafi/alphafi-sdk";var hn=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i,isAmountA:l}=this.data;return await wl(o,n.address,i,l)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};import{depositSingleAssetTxb as Sl}from"@alphafi/alphafi-sdk";var gn=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i}=this.data;return await Sl(o,n.address,i)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};import{withdrawTxb as Cl}from"@alphafi/alphafi-sdk";var yn=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:i}=this.data;return await Cl(i,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};import{withdrawAlphaTxb as Il}from"@alphafi/alphafi-sdk";var bn=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:i}=this.data;return await Il(i,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var Tn=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:o}=e,i=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",i);let u=new dn(t,i).decode();return{txType:kl.Other,txSubType:u.type,intentionData:u.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=gn.fromData(e.intentionData);break;case"depositDoubleAsset":n=hn.fromData(e.intentionData);break;case"withdraw":n=yn.fromData(e.intentionData);break;case"withdrawAlpha":n=bn.fromData(e.intentionData);break;case"claimReward":n=fn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};import{TransactionType as Gl}from"@msafe/sui3-utils";import{TransactionType as _t}from"@msafe/sui3-utils";import{bcs as Zr}from"@mysten/sui/bcs";import{SBUCK_FOUNTAIN_PACKAGE_ID as ti}from"bucket-protocol-sdk";var wn=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,n){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.package===e&&o.MoveCall.module===t&&o.MoveCall.function===n)}getMoveCallModuleCommands(e,t){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(e=>e.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(e=>e.$kind==="TransferObjects")}isPsmTransaction(){return!!this.getMoveCallCommand("charge_reservoir")||!!this.getMoveCallCommand("discharge_reservoir")}isStrapNewTransaction(){return!!this.getMoveCallModuleCommand("strap","new")}isBorrowTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","high_top_up")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow_with_strap")}isRepayTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","fully_repay")||!!this.getMoveCallModuleCommand("bucket_operations","fully_repay_with_strap")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw_with_strap")}isWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","withdraw")||!!this.getMoveCallModuleCommand("buck","withdraw_with_strap")}isCloseTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","destroy_empty_strap")}isTankDepositTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","deposit")}isTankWithdrawTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","withdraw")}isTankClaimTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","claim")}isSBUCKDepositTransaction(){return!!this.getMoveCallModuleCommand("buck","buck_to_sbuck")}isSBUCKWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","sbuck_to_buck")}isSBUCKStakeTransaction(){return!!this.getMoveCallPackageModuleCommand(ti,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(ti,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(ti,"fountain_core","claim")}isLockedClaimTransaction(){return!!this.getMoveCallModuleCommand("proof_rule","claim")||!!this.getMoveCallModuleCommand("lst_proof_rule","claim")}isLstUnlockTransaction(){return!!this.getMoveCallModuleCommand("lst_proof_rule","unlock")}decodePsm(){let e,t,n="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),this.getMoveCallCommand("charge_reservoir")?([e]=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments,t=!1):([e]=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments,t=!0),console.log("Decoder.decodePsm",e,n,t),{txType:_t.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,o=this.getStrapId(),i="0",l=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(l.$kind==="Input"&&(i=this.getPureInputU64(l.Input)),this.getMoveCallCommand("high_top_up")){let u=this.getMoveCallCommand("high_top_up").MoveCall;[e]=u.typeArguments;let g=u.arguments[1];g.$kind==="Input"&&(t=this.getPureInputU64(g.Input));let T=u.arguments[3];if(T.$kind==="Input"){let S=this.getPureAddresses(T.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow")){let u=this.getMoveCallCommand("high_borrow").MoveCall;[e]=u.typeArguments;let g=u.arguments[4];g.$kind==="Input"&&(t=this.getPureInputU64(g.Input));let T=u.arguments[5];if(T.$kind==="Input"){let S=this.getPureAddresses(T.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let u=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=u.typeArguments;let g=u.arguments[5];g.$kind==="Input"&&(t=this.getPureInputU64(g.Input));let T=u.arguments[6];if(T.$kind==="Input"){let S=this.getPureAddresses(T.Input);S.length===1&&([n]=S)}}return{txType:_t.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:i,borrowAmount:t,insertionPlace:n,strapId:o}}}decodeRepay(){let e="",t="0",n="0",i,l=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let u=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=u.typeArguments;let g=u.arguments[4];g.$kind==="Input"&&(n=this.getPureInputU64(g.Input));let T=u.arguments[5];if(T.$kind==="Input"){let C=this.getPureAddresses(T.Input);C.length===1&&([i]=C)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let u=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=u.typeArguments;let g=u.arguments[5];g.$kind==="Input"&&(n=this.getPureInputU64(g.Input));let T=u.arguments[6];if(T.$kind==="Input"){let C=this.getPureAddresses(T.Input);C.length===1&&([i]=C)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}return{txType:_t.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:i,strapId:l}}}decodeWithdraw(){let e="",t="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let i=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=i.typeArguments;let l=i.arguments[4];l.$kind==="Input"&&(t=this.getPureInputU64(l.Input));let u=i.arguments[5];if(u.$kind==="Input"){let g=this.getPureAddresses(u.Input);g.length===1&&([n]=g)}}else if(this.getMoveCallCommand("withdraw")){let i=this.getMoveCallCommand("withdraw").MoveCall;[e]=i.typeArguments;let l=i.arguments[3];l.$kind==="Input"&&(t=this.getPureInputU64(l.Input));let u=i.arguments[4];if(u.$kind==="Input"){let g=this.getPureAddresses(u.Input);g.length===1&&([n]=g)}}return{txType:_t.Other,type:"withdraw",intentionData:{collateralType:e,withdrawAmount:t,insertionPlace:n,strapId:o}}}decodeClose(){let e="",t=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([e]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:_t.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",i=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];i.$kind==="Input"&&(n=this.getPureInputU64(i.Input));let l=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,l),{txType:_t.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:l}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let g=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];g.$kind==="Input"&&(e=this.getPureInputU64(g.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let u=0;u<o.length;u++){let g=o[u];n.push("")}else{let u=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let g=0;g<u.length;g++){let S=u[g].MoveCall.arguments[2];if(S.$kind==="Input"){let{objectId:C}=this.inputs[S.Input].UnresolvedObject;n.push(C)}}}let i=this.isSBUCKWithdrawTransaction(),l={stakeProofs:n,amount:e,isStake:t,toBuck:i};return console.log("Decoder.decodeSBUCKUnstake",l),{txType:_t.Other,type:"sbuck-unstake",intentionData:l}}decodeSBUCKWithdraw(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(e=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:_t.Other,type:"sbuck-withdraw",intentionData:{amount:e}}}decodeSBUCKClaim(){let e=[],t=this.getMoveCallModuleCommands("fountain_core","claim");for(let n=0;n<t.length;n++){let i=t[n].MoveCall.arguments[2];if(i.$kind==="Input"){let{objectId:l}=this.inputs[i.Input].UnresolvedObject;e.push(l)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:_t.Other,type:"sbuck-claim",intentionData:{stakeProofs:e}}}decodeTankDeposit(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];n.$kind==="Input"&&(e=this.getPureInputU64(n.Input));let i=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",i,e),{txType:_t.Other,type:"tank-deposit",intentionData:{coinType:i,amount:e}}}decodeTankWithdraw(){let e=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,t=e.typeArguments[0],n="0",o=e.arguments[5];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),console.log("Decoder.decodeTankWithdraw",t,n),{txType:_t.Other,type:"tank-withdraw",intentionData:{coinType:t,amount:n}}}decodeTankClaim(){let t=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",t),{txType:_t.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let i=0;i<n.length;i++)[e]=n[i].MoveCall.typeArguments,t++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let i=0;i<o.length;i++)[e]=o[i].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:_t.Other,type:"lock-claim",intentionData:{coinType:e,proofCount:t}}}getCoinInput(e){if(this.inputs[e].$kind!=="Object")throw new Error("not Object argument")}getStrapId(){let e;if(this.isStrapNewTransaction()?e="new":this.isLstUnlockTransaction()&&(e="locked"),!e){let t=this.getMoveCallModuleCommand("fountain","unstake");if(t){let n=t.MoveCall.arguments[2];n.$kind==="Input"&&(e=this.inputs[n.Input].UnresolvedObject.objectId)}}return e}getPureInputU64(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return Zr.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return Zr.vector(Zr.Address).fromBase64(t.Pure.bytes)}};import{TransactionType as Al}from"@msafe/sui3-utils";import{Transaction as vl}from"@mysten/sui/transactions";import{buildPsmTx as Dl}from"bucket-protocol-sdk";import{BucketClient as xl}from"bucket-protocol-sdk";var Mt=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new xl(t,e.address)};var ss=async(a,e,t)=>{let{coinType:n,amount:o,buckToCoin:i}=a,l=new vl,u=Mt(t,e);return await Dl(u,l,n,o,i,e.address),l};var Sn=class a extends x{constructor(t){super(t);this.data=t}txType=Al.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await ss(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Bl}from"@msafe/sui3-utils";import{Transaction as Cn}from"@mysten/sui/transactions";import{buildBorrowTx as Ml,buildCloseTx as Ol,buildRepayTx as Pl,buildWithdrawTx as Rl}from"bucket-protocol-sdk";var cs=async(a,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:i,insertionPlace:l,strapId:u}=a,g=new Cn,T=Mt(t,e);return await Ml(T,g,n,o,i,e.address,l,u),g},ls=async(a,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:i,strapId:l}=a,u=new Cn,g=Mt(t,e);return await Rl(g,u,n,o,e.address,i,l),u},us=async(a,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:i,isSurplus:l,insertionPlace:u,strapId:g}=a,T=new Cn,S=Mt(t,e);return await Pl(S,T,n,o,i,e.address,l,u,g),T},ms=async(a,e,t)=>{let{collateralType:n,recipient:o,strapId:i}=a,l=new Cn,u=Mt(t,e);return await Ol(u,l,n,o,i),l};var In=class a extends x{constructor(t){super(t);this.data=t}txType=Bl.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await cs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as El}from"@msafe/sui3-utils";var kn=class a extends x{constructor(t){super(t);this.data=t}txType=El.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await us(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Nl}from"@msafe/sui3-utils";var xn=class a extends x{constructor(t){super(t);this.data=t}txType=Nl.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await ls(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Wl}from"@msafe/sui3-utils";var vn=class a extends x{constructor(t){super(t);this.data=t}txType=Wl.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await ms(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Rn}from"@msafe/sui3-utils";import{Transaction as Dn}from"@mysten/sui/transactions";import{buildSBUCKClaimTx as _l,buildSBUCKDepositTx as Ll,buildSBUCKUnstakeTx as jl,buildSBUCKWithdrawTx as Ul}from"bucket-protocol-sdk";var ps=async(a,e,t)=>{let{coinType:n,amount:o,isStake:i}=a,l=new Dn,u=Mt(t,e);return await Ll(u,l,n,o,e.address,i),l},ds=async(a,e,t)=>{let{stakeProofs:n,amount:o,isStake:i,toBuck:l}=a,u=new Dn,g=Mt(t,e);return await jl(g,u,n,o,e.address,i,l),u},fs=async(a,e,t)=>{let{amount:n}=a,o=new Dn,i=Mt(t,e);return await Ul(i,o,n,e.address),o},hs=async(a,e,t)=>{let{stakeProofs:n}=a,o=new Dn,i=Mt(t,e);return await _l(i,o,n,e.address),o};var An=class a extends x{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await ps(this.data,n,o)}static fromData(t){return new a(t)}},Mn=class a extends x{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await ds(this.data,n,o)}static fromData(t){return new a(t)}},On=class a extends x{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await fs(this.data,n,o)}static fromData(t){return new a(t)}},Pn=class a extends x{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await hs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ni}from"@msafe/sui3-utils";import{Transaction as ei}from"@mysten/sui/transactions";import{buildTankClaimTx as ql,buildTankDepositTx as Fl,buildTankWithdrawTx as Kl}from"bucket-protocol-sdk";var gs=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new ei,l=Mt(t,e);return await Fl(l,i,n,o,e.address),i},ys=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new ei,l=Mt(t,e);return await Kl(l,i,n,o,e.address),i},bs=async(a,e,t)=>{let{coinType:n}=a,o=new ei,i=Mt(t,e);return await ql(i,o,n,e.address),o};import{Transaction as $l}from"@mysten/sui/transactions";import{buildLockedClaimTx as Vl}from"bucket-protocol-sdk";var Ts=async(a,e,t)=>{let{coinType:n,proofCount:o}=a,i=new $l,l=Mt(t,e);return await Vl(l,i,n,o,e.address),i};var Bn=class a extends x{constructor(t){super(t);this.data=t}txType=ni.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await gs(this.data,n,o)}static fromData(t){return new a(t)}},En=class a extends x{constructor(t){super(t);this.data=t}txType=ni.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await ys(this.data,n,o)}static fromData(t){return new a(t)}},Nn=class a extends x{constructor(t){super(t);this.data=t}txType=ni.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await bs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Hl}from"@msafe/sui3-utils";var Wn=class a extends x{constructor(t){super(t);this.data=t}txType=Hl.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Ts(this.data,n,o)}static fromData(t){return new a(t)}};var _n=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new wn(t).decode();return{txType:Gl.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"psm":i=Sn.fromData(e.intentionData);break;case"borrow":i=In.fromData(e.intentionData);break;case"withdraw":i=xn.fromData(e.intentionData);break;case"repay":i=kn.fromData(e.intentionData);break;case"close":i=vn.fromData(e.intentionData);break;case"tank-deposit":i=Bn.fromData(e.intentionData);break;case"tank-withdraw":i=En.fromData(e.intentionData);break;case"tank-claim":i=Nn.fromData(e.intentionData);break;case"sbuck-deposit":i=An.fromData(e.intentionData);break;case"sbuck-unstake":i=Mn.fromData(e.intentionData);break;case"sbuck-withdraw":i=On.fromData(e.intentionData);break;case"sbuck-claim":i=Pn.fromData(e.intentionData);break;case"lock-claim":i=Wn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};import{TransactionType as Du}from"@msafe/sui3-utils";import{TransactionType as eu}from"@msafe/sui3-utils";import{AggregatorClient as zl,Env as Ql}from"@cetusprotocol/aggregator-sdk";import{CetusFarmsSDK as Jl}from"@cetusprotocol/farms-sdk";import{CetusClmmSDK as Xl}from"@cetusprotocol/sui-clmm-sdk";import{CetusVaultsSDK as Yl}from"@cetusprotocol/vaults-sdk";import{CetusXcetusSDK as Zl}from"@cetusprotocol/xcetus-sdk";import{SuiClient as oi,getFullnodeUrl as ws}from"@mysten/sui/client";var ye=(a,e)=>{let t=Xl.createSDK({env:"mainnet",sui_client:new oi({url:ws("mainnet")})});return t.setSenderAddress(e.address),t},zt=(a,e)=>{let t=Jl.createSDK({env:"mainnet",sui_client:new oi({url:ws("mainnet")})});return t.setSenderAddress(e.address),t},tu="https://api-sui.cetus.zone/router_v2/find_routes",Ss=(a,e)=>{let t=new oi({url:"https://fullnode.mainnet.sui.io/"});return new zl({endpoint:tu,signer:e.address,client:t,env:Ql.Mainnet})},ai=(a,e)=>{let t=Yl.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t},be=(a,e)=>{let t=Zl.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t};var Cs=async(a,e,t)=>await ye(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Is=async(a,e,t)=>await ye(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),ks=async(a,e,t)=>await ye(t,e).Position.closePositionPayload(a),xs=async(a,e,t)=>await ye(t,e).Position.removeLiquidityPayload(a),vs=async(a,e,t)=>await ye(t,e).Rewarder.collectRewarderPayload(a);var Ln=class a extends x{constructor(t){super(t);this.data=t}txType=eu.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Cs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as nu}from"@msafe/sui3-utils";var jn=class a extends x{constructor(t){super(t);this.data=t}txType=nu.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await vs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ou}from"@msafe/sui3-utils";var Un=class a extends x{constructor(t){super(t);this.data=t}txType=ou.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await xs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as au}from"@msafe/sui3-utils";var Ds=async(a,e,t)=>await zt(t,e).Farms.openPositionAddLiquidityStakePayload(a),As=async(a,e,t)=>await zt(t,e).Farms.addLiquidityFixCoinPayload(a),Ms=async(a,e,t)=>await zt(t,e).Farms.removeLiquidityPayload(a),Os=async(a,e,t)=>await zt(t,e).Farms.removeLiquidityPayload(a),Ps=async(a,e,t)=>await zt(t,e).Farms.claimFeeAndClmmReward(a),Rs=async(a,e,t)=>await zt(t,e).Farms.harvestPayload(a),Bs=async(a,e,t)=>{let n=zt(t,e),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},Es=async(a,e,t)=>await zt(t,e).Farms.depositPayload(a),Ns=async(a,e,t)=>await zt(t,e).Farms.withdrawPayload(a);var qn=class a extends x{constructor(t){super(t);this.data=t}txType=au.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ds(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ru}from"@msafe/sui3-utils";var Fn=class a extends x{constructor(t){super(t);this.data=t}txType=ru.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Bs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as iu}from"@msafe/sui3-utils";var Kn=class a extends x{constructor(t){super(t);this.data=t}txType=iu.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ps(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as su}from"@msafe/sui3-utils";var $n=class a extends x{constructor(t){super(t);this.data=t}txType=su.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ms(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as cu}from"@msafe/sui3-utils";var Vn=class a extends x{constructor(t){super(t);this.data=t}txType=cu.Other;txSubType="FarmingHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Rs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as lu}from"@msafe/sui3-utils";var Hn=class a extends x{constructor(t){super(t);this.data=t}txType=lu.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await As(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as uu}from"@msafe/sui3-utils";var Gn=class a extends x{constructor(t){super(t);this.data=t}txType=uu.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Os(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as mu}from"@msafe/sui3-utils";var zn=class a extends x{constructor(t){super(t);this.data=t}txType=mu.Other;txSubType="FarmingStake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Es(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as pu}from"@msafe/sui3-utils";var Qn=class a extends x{constructor(t){super(t);this.data=t}txType=pu.Other;txSubType="FarmingUnstake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ns(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as du}from"@msafe/sui3-utils";var Jn=class a extends x{constructor(t){super(t);this.data=t}txType=du.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Is(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as fu}from"@msafe/sui3-utils";var Xn=class a extends x{constructor(t){super(t);this.data=t}txType=fu.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await ks(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as yu}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as hu}from"@cetusprotocol/aggregator-sdk";import{Transaction as gu}from"@mysten/sui/transactions";var Ws=async(a,e,t)=>{let n=Ss(t,e),o=new gu;return await n.fastRouterSwap({...a,routers:hu(a.routers),txb:o}),o};var Yn=class a extends x{constructor(t){super(t);this.data=t}txType=yu.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ws(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as bu}from"@msafe/sui3-utils";import{Transaction as _s}from"@mysten/sui/transactions";var Ls=async(a,e,t)=>{let n=ai(t,e),o=new _s;return o.setSender(e.address),await n.Vaults.deposit(a,o),o},js=async(a,e,t)=>{let n=ai(t,e),o=new _s;return await n.Vaults.withdraw(a,o),o};var Zn=class a extends x{constructor(t){super(t);this.data=t}txType=bu.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ls(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Tu}from"@msafe/sui3-utils";var to=class a extends x{constructor(t){super(t);this.data=t}txType=Tu.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await js(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Su}from"@msafe/sui3-utils";import{Transaction as wu}from"@mysten/sui/transactions";var Us={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},qs=async(a,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:o,periods:i,CLOCK_ADDRESS:l}=a,u=new wu;return i.forEach(g=>{u.moveCall({target:`${Us.published_at}::router::redeem`,typeArguments:[Us.cetus_coin_type],arguments:[u.object(n),u.object(o),u.pure(g),u.object(l)]})}),u};var eo=class a extends x{constructor(t){super(t);this.data=t}txType=Su.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await qs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Cu}from"@msafe/sui3-utils";var Fs=async(a,e,t)=>await be(t,e).XCetusModule.convertPayload(a),Ks=async(a,e,t)=>await be(t,e).XCetusModule.redeemLockPayload(a),$s=async(a,e,t)=>await be(t,e).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),Vs=async(a,e,t)=>await be(t,e).XCetusModule.cancelRedeemPayload(a),Hs=async(a,e,t)=>await be(t,e).XCetusModule.redeemPayload(a);var no=class a extends x{constructor(t){super(t);this.data=t}txType=Cu.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Vs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Iu}from"@msafe/sui3-utils";var oo=class a extends x{constructor(t){super(t);this.data=t}txType=Iu.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await $s(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ku}from"@msafe/sui3-utils";var ao=class a extends x{constructor(t){super(t);this.data=t}txType=ku.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Fs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as xu}from"@msafe/sui3-utils";var ro=class a extends x{constructor(t){super(t);this.data=t}txType=xu.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Hs(i,n,o)}static fromData(t){return new a(t)}};import{TransactionType as vu}from"@msafe/sui3-utils";var io=class a extends x{constructor(t){super(t);this.data=t}txType=vu.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ks(i,n,o)}static fromData(t){return new a(t)}};var so=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:Du.Other,txSubType:n,intentionData:{txbParams:{...t},action:n}}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"OpenAndAddLiquidity":i=Ln.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Jn.fromData(e.intentionData);break;case"DecreaseLiquidity":i=Un.fromData(e.intentionData);break;case"RemoveLiquidity":i=Xn.fromData(e.intentionData);break;case"ClaimFeeAndMining":i=jn.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":i=qn.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":i=Hn.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":i=$n.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":i=Gn.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":i=Kn.fromData(e.intentionData);break;case"FarmingHarvest":i=Vn.fromData(e.intentionData);break;case"FarmingBatchHarvest":i=Fn.fromData(e.intentionData);break;case"FarmingStake":i=zn.fromData(e.intentionData);break;case"FarmingUnstake":i=Qn.fromData(e.intentionData);break;case"xCETUSConvert":i=ao.fromData(e.intentionData);break;case"xCETUSRedeemLock":i=io.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":i=oo.fromData(e.intentionData);break;case"xCETUSCancelRedeem":i=no.fromData(e.intentionData);break;case"xCETUSRedeem":i=ro.fromData(e.intentionData);break;case"VestingRedeem":i=eo.fromData(e.intentionData);break;case"AggregatorSwap":i=Yn.fromData(e.intentionData);break;case"AddVaultsPosition":i=Zn.fromData(e.intentionData);break;case"RemoveVaultsPosition":i=to.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};import{TransactionType as xm}from"@msafe/sui3-utils";import Au from"sort-keys-recursive";var P=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Au(this.data))}};import{getFullnodeUrl as co}from"@mysten/sui.js/client";var ri={};rs(ri,{contractId:()=>Pu,default:()=>Wu,feeObjId:()=>Eu,roleObjId:()=>Ru,status:()=>Ou,transaction:()=>Mu,upgradeCapObjId:()=>Nu,vaultObjId:()=>Bu});var Mu="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ou="success",Pu="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Ru="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Bu="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Eu="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Nu="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Wu={transaction:Mu,status:Ou,contractId:Pu,roleObjId:Ru,vaultObjId:Bu,feeObjId:Eu,upgradeCapObjId:Nu};var ii={};rs(ii,{contractId:()=>ju,default:()=>$u,feeObjId:()=>Fu,roleObjId:()=>Uu,status:()=>Lu,transaction:()=>_u,upgradeCapObjId:()=>Ku,vaultObjId:()=>qu});var _u="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Lu="success",ju="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Uu="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",qu="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Fu="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ku="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",$u={transaction:_u,status:Lu,contractId:ju,roleObjId:Uu,vaultObjId:qu,feeObjId:Fu,upgradeCapObjId:Ku};var Vu=co("testnet"),Hu=co("testnet"),Gu=co("mainnet"),zu=co("mainnet"),Qu="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Ju="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Xu="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Yu="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Gs=ri,zs=ii,Zu=new Map([["dev",{env:"dev",rpc:{url:Vu},backend:{url:Qu},contract:Gs}],["stg",{env:"stg",rpc:{url:Hu},backend:{url:Ju},contract:Gs}],["prev",{env:"prev",rpc:{url:Gu},backend:{url:Xu},contract:zs}],["prod",{env:"prod",rpc:{url:zu},backend:{url:Yu},contract:zs}]]);function Qs(a,e){let t=Zu.get(a);if(!t)throw new Error(`Env not supported: ${a}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}import{SuiClient as em}from"@mysten/sui.js/client";var j=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:o,context:i}=n;o?super(`[MPay] ${t}: ${o}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=i}};var lo=class extends j{constructor(){super(11,"Backend is not specified")}};var uo=class extends j{constructor(){super(1,"Wallet not connected")}};import we,{AxiosError as tm}from"axios";var Te=class extends j{constructor(e,t){super(10,e,{context:t})}};var mo=class a{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof tm)throw new Te(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Te(e.data.code)}throw new Te(e.status.toString())}async getIncomingStreams(e,t){let n=await we.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await we.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(n)}async getStreamHistory(e){let t=await we.post(`${this.apiURL}/stream-events`,e),n=a.parseResponseData(t);return n.data.forEach(o=>{let i=o;return i.data.type==="create_stream"?i.data.balance=BigInt(i.data.balance):i.data.type==="cancel_stream"?i.data.withdrawAmount=BigInt(i.data.withdrawAmount):i.data.type==="claim"||i.data.type==="auto_claim"?i.data.claimAmount=BigInt(i.data.claimAmount):i.data.type==="set_auto_claim"&&(i.data.enabled=!!i.data.enabled),i.createdAt=new Date(i.createdAt),i}),n}async getAllCoinTypes(e){let t=await we.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let n=await we.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(n)}async getAllSenders(e,t){let n=await we.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(n)}};var Se=class a{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new em({url:e.rpc.url}),e.backend&&(this._backend=new mo(e.backend.url))}static new(e,t){let n=Qs(e,t);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new lo;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new uo;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Cm,normalizeStructTag as Im,normalizeSuiAddress as Tc}from"@mysten/sui.js/utils";import{TransactionBlock as bo}from"@mysten/sui.js/transactions";import{TransactionBlock as ac}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as rc,normalizeStructTag as rm}from"@mysten/sui.js/utils";var si=50n,po=10000n,Js=25n,ci=100000000n;var Qt=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},We=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},ne=class a{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let o=l=>new a(t.result[l]);if(n===Symbol.iterator)return function*(){let l=0;for(;;)yield o(l),l++};if(typeof n=="symbol")return;let i=parseInt(n,10);if(!(Number.isNaN(i)||i<0))return o(i)}})}moveArg(){return this.result}};import{Buffer as Xs}from"buffer";import{normalizeSuiAddress as nm}from"@mysten/sui.js/utils";var _e=class extends j{constructor(e,t){super(3,e,{context:t})}};var fo=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let n=this.callResult(e);return this.returnValue(n,t)}getAddress(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="address")throw new _e("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return nm(Xs.from(n).toString("hex"))}getU64(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="u64")throw new _e("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Xs.from(n).readBigInt64LE()}};import{bcs as Zs}from"@mysten/sui.js/bcs";var H=class extends j{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var tc={groupId:"string",name:"string"},om=64;function ec(a){return nc(a),Zs.ser(tc,a).toString("base64")}function Le(a){let e=Zs.de(tc,a,"base64");return nc(e),e}function nc(a){if(!Ys(a.name))throw new H("Invalid metadata: Name contains unknown character");if(!Ys(a.groupId))throw new H("Invalid metadata: Group ID contains unknown character");if(a.name.length>om)throw new H("Invalid metadata: Name exceed max length 64")}function Ys(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as ho}from"@mysten/sui.js/utils";function go(a,e){return ho(a)===ho(e)}function oe(a,e){return ho(a)===ho(e)}var yo="txn.gas";import{nanoid as am}from"nanoid";function oc(){return am()}var me=class a{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:ec({name:e.name,groupId:oc()}),coinType:rm(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new ac,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),i=await this.wallet.requestCoins(o),l=await this.addMergeCoins(t,i[0]),u;o.length>1?u=await this.addMergeCoins(t,i[1]):u=l;for(let g=0;g<e.recipients.length;g++){let T=e.recipients[g],S=this.amountForRecipient(T,e.numberEpoch),C=this.getStreamFeeLocal(S),[I]=t.splitCoins(l,[t.pure(S+C,"u64")]),[k]=t.splitCoins(u,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new ne(I),flatFeeCoin:new ne(k),metadata:e.metadata,recipient:T.address,timeStart:e.startTime,cliff:T.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:T.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:si,denominator:po},claimFeePercent:{numerator:Js,denominator:po},flatFeePerStream:ci}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(o=>e.object(o))),n=e.object(t.primaryCoin)):t.primaryCoin===yo?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return go(n,rc)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:rc,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,i)=>{let l=this.amountForRecipient(i,e.numberEpoch),u=this.getStreamFeeLocal(l);return{totalAmount:o.totalAmount+l,streamFeeAmount:o.streamFeeAmount+u}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return ci}getStreamFeeLocal(e){return e*si/po}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new ac,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new fo(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as sc}from"@mysten/sui.js/transactions";var ic="0x0000000000000000000000000000000000000000000000000000000000000006";var Ce=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(sc.MoveCall({target:n,arguments:t.arguments.map(o=>o instanceof We?o.moveArgs(e):o instanceof Qt?o.moveArg(e):o instanceof ne?o.moveArg():e.pure(o)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,n=[],o=[]){e.add(sc.MoveCall({target:t,arguments:n.map(i=>i instanceof We?i.moveArgs(e):i instanceof Qt?i.moveArg(e):i instanceof ne?i.moveArg():e.pure(i)),typeArguments:o}))}makeObject(e){return typeof e=="string"?new Qt(e):e}vaultObject(){return new Qt(this.config.vaultObjId)}roleObject(){return new Qt(this.config.roleObjId)}feeObject(){return new Qt(this.config.feeObjId)}clockObject(){return new Qt(ic)}};var Ie=class a extends Ce{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_fee,arguments:[o,i,n],typeArgs:[]})}setStreamingFlatFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,i,n],typeArgs:[]})}setClaimFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_claim_fee,arguments:[o,i,n],typeArgs:[]})}streamingFee(t,n){let o=this.feeObject();return this.addContractCall(t,{method:a.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Jt=class a extends Ce{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.feeObject(),i=this.vaultObject(),l=this.makeObject(n.paymentCoin),u=this.makeObject(n.flatFeeCoin),g=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[o,i,l,u,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,g],typeArgs:[n.coinType]})}setAutoClaim(t,n){let o=this.makeObject(n.streamId);return this.addContractCall(t,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.cancel_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let o=this.makeObject(n.streamId),i=this.vaultObject(),l=this.feeObject(),u=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,i,l,u],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 ke=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new Ie(t,e),this.streamContract=new Jt(t,e)}feeContract;streamContract;async createStreams(e){let t=me.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new me(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new bo;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new bo;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new bo;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new bo;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};import{normalizeStructTag as li,SUI_TYPE_ARG as im}from"@mysten/sui.js/utils";import{Duration as cc}from"luxon";var To=class extends j{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var sm=1e3,wo=class{constructor(e){this.globals=e;this.coinMetaHelper=new ui(e.suiClient),this.createStreamHelper=new ke(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new To(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},n=e.totalAmount*t.numerator/t.denominator,o=(e.totalAmount-n)/e.steps,l={realTotalAmount:o*e.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(l,e.totalAmount),l}calculateTimelineByInterval(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),n={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(cc.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:cc.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await this.globals.suiClient.getBalance({owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:li(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,i)=>({...o,coinType:li(o.coinType),coinMeta:n[i]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new H("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new H("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<sm)throw new H("Interval shall be at least 1 second","interval",e.interval)}},ui=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=li(e||im);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this.coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};import{normalizeStructTag as mc,normalizeSuiAddress as vo}from"@mysten/sui.js/utils";import{DateTime as pc}from"luxon";import{TransactionBlock as ko}from"@mysten/sui.js/transactions";import{normalizeStructTag as uc,parseStructTag as um}from"@mysten/sui.js/utils";import{DateTime as mm}from"luxon";var So=class extends j{constructor(){super(7,"Connected wallet is not creator")}};var je=class extends j{constructor(){super(8,"Connected wallet is not recipient")}};var Ue=class extends j{constructor(e,t){super(6,e,{context:t})}};var At=class extends j{constructor(e,t={}){super(0,e,t)}};var Co=class extends j{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};import{DateTime as cm,Duration as lm}from"luxon";var lc=(1n<<64n)-1n,Io=1e3;function mi(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/Io);return cm.fromMillis(t*Io)}function pi(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/Io);return lm.fromMillis(t*Io)}var ae=class a{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new Jt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await a.fetchStreamData(e,t);return new a(e,t,n)}static fromObjectData(e,t,n){let o=a.parseRawStreamData(t,n);return new a(e,t,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(e){if(e.data?.objectId!==this.streamId)throw new At("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new So;let e=new ko;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new je;let e=new ko;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new je;let t=new ko;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new ko;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return uc(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 pi(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Le(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Le(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return mi(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return pi(t)}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:mi((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 e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===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===lc?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=mm.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new Co(e):new Ue(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new Ue("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=um(n.type),i=uc(o[0]),l=n.fields,u=l.config.fields,g=l.status.fields;return{coinType:i,autoClaim:l.auto_claim,balance:BigInt(l.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:g.status,epochCanceled:BigInt(g.epoch_canceled),epochClaimed:BigInt(g.epoch_claimed)}}}};var xe=class extends j{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function fi(a){let e=[];for(;await a.hasNext();){let t=await a.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var di=class{constructor(e){this.requester=e;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)}},ve=class{constructor(e){this.requester=e;this.pager=new di(e),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 pm=25;async function gi(a,e,t){let n=new qe(e),o=new Fe(a,n,t);return await fi(o)}var qe=class{constructor(e){this.ids=e;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]}},Fe=class extends ve{constructor(t,n,o){super(new hi(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}},hi=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||pm,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&e.push(i)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=t.filter(i=>o?.(i))}else n=t;return{data:n,hasNext:await this.stringIter.hasNext()}}};var xo=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new xe("stream size 0");let n=t.map(i=>i.groupId);if(new Set(n).size!==1)throw new H("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await gi(e.suiClient,t);return n.forEach(o=>{if(!o)throw new At("stream group object data undefined")}),a.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let o=await a.parseGroupStreams(e,t,n);return new a(e,o)}static checkStreamGroup(e){let t=e.map(i=>i.groupCommonInfo),n=t[0],o=!0;return t.forEach(i=>{dm(n,i)||(o=!1)}),o}async refresh(){let e=await gi(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[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(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let o=n.map((i,l)=>ae.fromObjectData(e,t[l],i)).filter(i=>!!i);if(new Set(o.map(i=>i.groupId)).size!==1)throw new xe("Not same group ID");if(!this.checkStreamGroup(o))throw new xe("Not same stream settings");return o}};function dm(a,e){return a.name===e.name&&a.groupId===e.groupId&&a.creator===e.creator&&a.start.toMillis()===e.start.toMillis()&&a.interval.toMillis()===e.interval.toMillis()&&a.steps===e.steps&&a.cancelable===e.cancelable}var Ke=class a{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await Do.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await Do.newOutgoing(e);return new a(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Do=class a{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await Ao.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await Ao.newOutgoingQuery(e);return new a(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new At("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new At("No more results");return e}},Ao=class a{constructor(e,t,n,o){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=o;this.current=0;let i=new qe(n.flat().map(l=>l.streamId));this.objectIter=new Fe(e.suiClient,i)}current=0;objectIter;static async newIncomingQuery(e){let t=bm(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,t)).filter(u=>vo(u.recipient)===vo(n)),l=dc(i);return new a(e.globals,n,l,e.query)}static async newOutgoingQuery(e){let t=Tm(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),i=dc(o);return new a(e.globals,n,i,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await gm(this.globals,e[0].streamId,this.objectIter);return this.current++,fc(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await ym(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,hm(t,this.query)?t:this.doNextRequest()}throw new At("Stream group with no stream")}};function dc(a){let e=new Map;return a.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>pc.fromISO(n[0].createDate).toMillis()-pc.fromISO(t[0].createDate).toMillis())}function fc(a,e){if(e===void 0)return!0;let t=fm(a,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return t&&n}return t}function fm(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function hm(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(n=>{fc(n,e)&&(t=!0)}),t}async function gm(a,e,t){let n=await hc(t,e);return ae.fromObjectData(a,e,n)}async function ym(a,e,t){let n=[];for(;n.length<e.length;){let o=await hc(t,e[n.length]);n.push(o)}return xo.newFromObjectResponse(a,e,n)}async function hc(a,e){if(!await a.hasNext())throw new At("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new At("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new At("stream id not aligned");return t}function bm(a){return{status:yi(a?.status),coinType:gc(a?.coinType),sender:yc(a?.sender)}}function Tm(a){return{status:yi(a?.status),coinType:gc(a?.coinType),recipient:yc(a?.recipient)}}function yi(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let n=yi(t);return!e||e===n?n:"all"},void 0):wm(a)}function wm(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new H("Unknown stream filtered status")}}function gc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>mc(e)):void 0:mc(a)}function yc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>vo(e)):void 0:vo(a)}var Mo=class extends j{constructor(t,n,o){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:n,gotAmount:o}});this.coinType=t;this.requestAmount=n;this.gotAmount=o}};var Sm=25;async function bc(a,e,t,n="0x2::sui::SUI",o=Sm){let i=new bi(a,e,n,o),l=BigInt(0),u=[];for(;await i.hasNext()&&l<t;){let g=await i.next();g&&(u.push(g),l+=BigInt(g.balance))}if(l<t)throw new Mo(n,t,l);return u}var bi=class extends ve{constructor(t,n,o,i){super(new Ti(t,n,o,i));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=i}},Ti=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new At("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var wi=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Oo=class{constructor(e){this.account=e}async address(){return this.account.address}},Si=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(go(e.coinType,Cm))return{primaryCoin:yo};if(e.amount<=0)throw new H("Invalid coin request","coinAmount",e.amount);let t=await bc(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new At("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},Po=class{globals;helper;constructor(e,t){this.globals=Se.new(e,t),this.helper=new wo(this.globals)}connectSingleWallet(e){let t=new Si(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new wi(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ae.new(this.globals,e)}async getIncomingStreams(e,t=10){return Ke.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return Ke.newOutgoing({globals:this.globals,query:e,pageSize:t})}async getCoinTypesForStreamFilter(){let e=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(e)).map(n=>Im(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>Tc(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>Tc(o))}get wallet(){return this.globals.wallet}builder(){return new ke(this.globals)}};var Ut=class extends P{application="mpay";getClient(e,t){let n=new Po(e==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Oo(t)),n}};var $e=class extends Ut{constructor(t){super(t);this.data=t}txType=xm.Stream;txSubType="Cancel";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};import{TransactionType as vm}from"@msafe/sui3-utils";var Ve=class extends Ut{constructor(t){super(t);this.data=t}txType=vm.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Dm}from"@msafe/sui3-utils";var He=class extends Ut{constructor(t){super(t);this.data=t}txType=Dm.Stream;txSubType="Claim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};import{TransactionType as Am}from"@msafe/sui3-utils";var Ge=class extends Ut{constructor(t){super(t);this.data=t}txType=Am.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o}=t;return this.getClient(n,o).createStream(this.data)}};import{bcs as wc}from"@mysten/sui.js/bcs";import{normalizeStructTag as Mm,normalizeSuiAddress as ze}from"@mysten/sui.js/utils";var De=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return ze(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return wc.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return ze(e.value.Object.ImmOrOwned.objectId)}return ze(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return ze(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return ze(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return wc.de(t,new Uint8Array(n))}typeArg(e){return Mm(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Ro=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&oe(t.target,this.contract.createStreamTarget));if(e.length===0)throw new At("No create stream transactions");return e.map(t=>new De(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=Le(t),i=e.decodeInputAddress(5),l=e.decodeInputU64(6),u=e.decodeInputU64(7),g=e.decodeInputU64(8),T=e.decodeInputU64(9),S=e.decodeInputU64(10),C=e.decodeInputBool(11),I=e.typeArg(0);return{name:n,groupId:o,recipient:i,timeStart:l,cliff:u,epochInterval:g,totalEpoch:T,amountPerEpoch:S,cancelable:C,coinType:I}}aggregateGroupStreamInfo(e){if(new Set(e.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 H("Stream group not have common info");let n=e.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:n,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Jt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ie(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new me(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var Bo=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new Jt(e.envConfig.contract,e)}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(t=>t.kind==="MoveCall"&&oe(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&oe(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&oe(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&oe(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&oe(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Ro(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new De(e,this.txb)}};import{TransactionType as Om}from"@msafe/sui3-utils";var Qe=class extends Ut{constructor(t){super(t);this.data=t}txType=Om.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Eo=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:n}=e,o=Se.new(t==="sui:mainnet"?"prod":"dev"),l=new Bo(o,n).decode(),u;switch(l.type){case"CreateStream":u=new Ge(l.info);break;case"SetAutoClaim":u=new Qe({streamId:l.streamId,enabled:l.enabled});break;case"Claim":u=new He({streamId:l.streamId});break;case"ClaimByProxy":u=new Ve({streamId:l.streamId});break;case"Cancel":u=new $e({streamId:l.streamId});break;default:throw new Error(`Unknown transaction type: ${l}`)}return{txType:u.txType,txSubType:u.txSubType,intentionData:u.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Ge(t);break;case"Claim":n=new He(t);break;case"ClaimByProxy":n=new Ve(t);break;case"SetAutoClaim":n=new Qe(t);break;case"Cancel":n=new $e(t);break;default:throw new Error("not implemented")}return n.build({...e})}};import{TransactionDefaultApplication as Bm,TransactionSubTypes as Sc}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Pm}from"@msafe/sui3-utils";var No=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return Pm(n,this.data,o.address)}static fromData(t){return new a(t)}};import{buildObjectTransferTxb as Rm}from"@msafe/sui3-utils";var Wo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return Rm(n,this.data,o.address)}static fromData(t){return new a(t)}};var _o=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Bm}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case Sc.assets.coin.send:o=No.fromData(e.intentionData);break;case Sc.assets.object.send:o=Wo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionType as zm}from"@msafe/sui3-utils";var Cc=!1,Je={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Ci(){if(!Cc)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(i=>i.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:o}=a;e&&(Je.ProtocolPackage=e),t&&(Je.borrowFee=t),n&&(Je.borrowFeeAddress=n),o&&(Je.pool=o),Cc=!0}catch(a){console.error(a.message)}}var $t=Je;import{TransactionType as de}from"@msafe/sui3-utils";import{bcs as Ic}from"@mysten/sui.js/bcs";import{normalizeStructTag as Nm,normalizeSuiAddress as Xe}from"@mysten/sui.js/utils";var Lo=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return!!(this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values($t.pool).find(n=>n.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:de.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:de.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:de.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===t){let o=new jo(n,this.txb),i=o.decodeInputU8(3),l=o.decodeInputU64(5);e.push({assetId:i,amount:l})}}),{txType:de.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:de.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:de.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:de.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith($t.ProtocolPackage));return new jo(e,this.txb)}},jo=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Xe(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Ic.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Xe(e.value.Object.ImmOrOwned.objectId)}return Xe(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Xe(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Xe(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Ic.de(t,new Uint8Array(n))}typeArg(e){return Nm(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{depositCoin as Wm,withdrawCoin as _m,repayDebt as Lm,borrowCoin as jm,claimAllRewardsPTB as Um,claimAllRewardsResupplyPTB as qm}from"navi-sdk";async function Ae(a,e,t,n){return await Wm(a,e,t,n),a}async function kc(a,e,t,n){let[o]=await _m(a,e,t);return a.transferObjects([o],a.pure(n)),a}async function xc(a,e,t,n){let[o]=await jm(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function Ii(a,e,t,n){return await Lm(a,e,t,n),a}async function vc(a,e){return await Um(a,e)}async function Dc(a,e){return await qm(a,e)}var Uo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await vc(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var qo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await Dc(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as Km}from"@mysten/sui.js/transactions";import{pool as Fm}from"navi-sdk";function Xt(a){return Object.values(Fm).find(e=>String(e.assetId)===String(a))}var Fo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Km;console.log("build",this.data);let l=Xt(n);return await xc(i,l,o,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as $m}from"@mysten/sui.js/transactions";async function Me(a,e,t){let n=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Ko=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:l}=this.data,u=new $m;console.log("build",this.data);let g=Xt(i);if(i===0){let[I]=u.splitCoins(u.gas,[l]);return await Ae(u,g,I,l)}let T=await Me(n,o.address,g.type);if(!T.data[0])throw new Error(`Insufficient balance for ${g.name} Token`);let S=T.data[0].coinObjectId;if(T.data.length>=2){let I=1;for(;I<T.data.length;)u.mergeCoins(S,[T.data[I].coinObjectId]),I++}return await Ae(u,g,u.object(S),l)}static fromData(t){return new a(t)}};import{TransactionBlock as Vm}from"@mysten/sui.js/transactions";var $o=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:l}=this.data,u=new Vm;console.log("build",this.data);let g=Xt(i);if(i===0){let[C]=u.splitCoins(u.gas,[l]);return Ii(u,g,C,l)}let T=await Me(n,o.address,g.type);if(!T.data[0])throw new Error(`Insufficient balance for ${g.name} Token`);let S=T.data[0].coinObjectId;if(T.data.length>=2){let C=1;for(;C<T.data.length;)u.mergeCoins(S,[T.data[C].coinObjectId]),C++}return Ii(u,g,u.object(S),l)}static fromData(t){return new a(t)}};import{TransactionBlock as Hm}from"@mysten/sui.js/transactions";var Vo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Hm;console.log("build",this.data);let l=Xt(n);return await kc(i,l,o,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as Gm}from"@mysten/sui.js/transactions";var Ho=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:i}=this.data,l=new Gm;console.log("build",this.data);for(let u=0;u<i.length;u++){let{assetId:g,amount:T}=i[u],S=Xt(g);if(g===0){let[k]=l.splitCoins(l.gas,[T]);await Ae(l,S,k,T);continue}let C=await Me(n,o.address,S.type);if(!C.data[0])throw new Error(`Insufficient balance for ${S.name} Token`);let I=C.data[0].coinObjectId;if(C.data.length>=2){let k=1;for(;k<C.data.length;)l.mergeCoins(I,[C.data[k].coinObjectId]),k++}await Ae(l,S,l.object(I),T)}return l}static fromData(t){return new a(t)}};var Go=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await Ci();let{transactionBlock:t}=e,o=new Lo(t).decode();return{txType:zm.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await Ci(),e.txSubType){case"EntryDeposit":o=Ko.fromData(e.intentionData);break;case"EntryBorrow":o=Fo.fromData(e.intentionData);break;case"EntryRepay":o=$o.fromData(e.intentionData);break;case"EntryWithdraw":o=Vo.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Ho.fromData(e.intentionData);break;case"ClaimReward":o=Uo.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=qo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionSubTypes as Qm,TransactionType as Ac}from"@msafe/sui3-utils";import{fromHex as Jm}from"@mysten/bcs";import{Transaction as Xm}from"@mysten/sui/transactions";import Ym from"sort-keys-recursive";var Mc="msafe-plain-tx",Oc=Qm.others.plain,ki=class a{constructor(e){this.data=e}application=Mc;txType=Ac.Other;txSubType=Oc;serialize(){return JSON.stringify(Ym(this.data))}async build(e){return Xm.from(Jm(this.data.content))}static fromData(e){return new a(e)}},zo=class{application;supportSDK="@mysten/sui";constructor(){this.application=Mc}async deserialize(e){let{content:t}=e.appContext;return{txType:Ac.Other,txSubType:Oc,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:o}=e;return ki.fromData(e.intentionData).build({suiClient:t,network:n,account:o})}};import{SuiClient as Pc}from"@mysten/sui/client";import{Transaction as rp}from"@mysten/sui/transactions";import{SuiClient as Di}from"@mysten/sui.js/client";import{TransactionBlock as ip}from"@mysten/sui.js/transactions";import{RequestManager as np,HTTPTransport as op,Client as ap}from"@open-rpc/client-js";var Zm={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},xi=class extends Error{},Qo=class extends xi{code;type;constructor(e,t){super(e),this.code=t,this.type=Zm[t]??"ServerError"}};function tp(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var ep={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Jo=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#r=new Set;#o=new Map;constructor(e,t={}){this.endpoint=e,this.options={...ep,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=tp(this.endpoint))}async makeRequest(e,t){let n=await this.#i();return new Promise((o,i)=>{this.#n+=1,this.#o.set(this.#n,{resolve:o,reject:i,timeout:setTimeout(()=>{this.#o.delete(this.#n),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:o,result:i})=>{if(o)throw new Qo(o.message,o.code);return i})}#i(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(o){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:o}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:o,timeout:i}=this.#o.get(n.id);clearTimeout(i),o(n)}else if("params"in n){let{params:o}=n;this.#r.forEach(i=>{i.subscriptionId===o.subscription&&o.subscription===i.subscriptionId&&i.onMessage(o.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#r].map(e=>e.subscribe(this)))}async subscribe(e){let t=new vi(e);return this.#r.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},vi=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var re=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:o}){let i=new op(o?.url??e,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new ap(new np([i])),this.websocketClient=new Jo(t??e,n)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var Xo=class a{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new a;for(let n=0;n<e.length;n++){let o=e[n];switch(o.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(o);break;case"@mysten/sui":t.addHelper(o);break;default:throw new Error(`${o.application}: ${o.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new Mi(e))}addHelper(e){this.apps.set(e.application,new Ai(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},Ai=class{constructor(e){this.helper=e}async deserialize(e){let t=new Pc({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=new Di({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await e.transactionBlock.build({client:n}),i=rp.from(o);return this.helper.deserialize({...e,suiClient:t,transaction:i})}async build(e){let t=new Pc({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});o.setSender(e.account.address);let i=await o.build({client:t});return ip.from(i)}},Mi=class{constructor(e){this.helper=e}async deserialize(e){let t=new Di({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new Di({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};import{TransactionType as gp}from"@msafe/sui3-utils";import{Scallop as Wc}from"@scallop-io/sui-scallop-sdk";import{TransactionType as Ot}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as Nc}from"@scallop-io/sui-scallop-sdk";import{parseStructTag as sp}from"@mysten/sui/utils";var ie=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(n=>`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:n,module:o,name:i}=sp(t);return e?e.package===n&&e.module===o&&e.function===i:!1}isMoveCall(e){return e.$kind==="MoveCall"&&!!e.MoveCall}filterMoveCallCommands(e,t){return this.isMoveCall(e)&&this.matchMoveCallCommand(e.MoveCall,t)}getMoveCallCommands(e){let t=new Set(e),n=e.reduce((i,l,u)=>(i[l]=u,i),{}),o=[];return this.commands.forEach(i=>{this.isMoveCall(i)&&i.MoveCall&&t.has(i.MoveCall.package)&&(o[n[i.MoveCall.package]]=i.MoveCall)}),o}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};import{bcs as Oi}from"@mysten/sui/bcs";import{normalizeStructTag as cp,normalizeSuiAddress as Ye}from"@mysten/sui/utils";var Pi=class a{constructor(e,t){this.moveCall=e;this.transaction=t;this.cmdIdx=e?.MoveCall?t.getData().commands.findIndex(n=>{if(n.$kind==="MoveCall"){let o=`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,i=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return o===i}return!1}):-1}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return Ye(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure,o=Oi[t];return Oi[t].parse(new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Ye(e.value.Object.ImmOrOwned.objectId)}return Ye(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Ye(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Ye(e.value.Object.Shared.objectId)}static getPureInput(e){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let t=e.value.Pure;return Oi.U64.parse(new Uint8Array(t))}typeArg(e){return cp(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},W=Pi;var Ri=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(W.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Rt=Ri;import{normalizeStructTag as Rc,SUI_CLOCK_OBJECT_ID as Bc,SUI_TYPE_ARG as lp}from"@mysten/sui/utils";var Ec=async(a,e)=>{let t=await a.suiKit.client().getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let o=t.data.content.fields.lock_key?.fields.name;if(!o)return!1;let i=a.address.get("borrowIncentive.object");return o===`${i.slice(2)}::incentive_account::IncentiveProgramLockKey`},Oe={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},qt={unstakeObligation:(a,e,t)=>a.moveCall(`${Oe.id}::user::unstake`,[Oe.incentivePools,Oe.incentiveAccounts,a.object(e),a.object(t),Bc],[Rc(lp)]),redeem_rewards:(a,e,t,n)=>a.moveCall(`${Oe.id}::user::redeem_rewards`,[Oe.incentivePools,Oe.incentiveAccounts,a.object(e),a.object(t),Bc],[Rc(n)])};var Yo=class extends ie{decode(){if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMigrateScoinTransaction(){return this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`),t=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`);return e&&t}isUnstakeAndWithdrawTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`),t=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`);return e&&t}isStakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`),t=this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return e&&t}isDepositCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return e&&t}isBorrowWithReferralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return e&&t}isUnstakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return e||t}isOpenObligationTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let e=this.hasMoveCallCommand(`${Nc}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new W(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Nc}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new W(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new W(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new W(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new W(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new W(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new W(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new W(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new W(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new W(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new W(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new W(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new W(e,this.transaction)}decodeMigrateScoin(){return{txType:Ot.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let t=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),o=this.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:Ot.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Ot.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Rt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.Other,type:"SupplyLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLending(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperRedeem.getNestedInputParam(2),n=new Rt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),n=new Rt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeDepositCollateral(){let e=this.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),t=this.helperDepositCollateral.getNestedInputParam(3),n=new Rt(t,this.transaction).getAmountInput().reduce((i,l)=>i+l,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Ot.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:e}}}decodeWithdrawCollateral(){let e=this.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),t=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:Ot.Other,type:"WithdrawCollateral",intentionData:{amount:t,collateralCoinName:e,obligationKey:o,obligationId:n}}}decodeBorrow(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.Other,type:"Borrow",intentionData:{amount:t,coinName:e,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),i=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeBorrowWithReferral(){let e=this.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),o=this.helperBorrowWithReferral.decodeSharedObjectId(1),i=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Ot.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new Rt(t,this.transaction).getAmountInput().reduce((i,l)=>i+l,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:e}}}decodeRepayWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),o=new Rt(n,this.transaction).getAmountInput().reduce((l,u)=>l+u,0),i=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:i,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);t=new Rt(i,this.transaction).getAmountInput().reduce((l,u)=>l+u,0)}if(this.helperStake.moveCall&&t===0){let i=this.helperStake.getNestedInputParam(2);t=new Rt(i,this.transaction).getAmountInput().reduce((l,u)=>l+u,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.Other,type:"StakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeUnstakeSpool(){let e=this.helperUnstake.decodeOwnedObjectId(1),t=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.Other,type:"UnstakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeSupplyWithStakeSpool(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Rt(t,this.transaction).getAmountInput().reduce((i,l)=>i+l,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Ot.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(o=>{let i=o.decodeOwnedObjectId(1),l=o.decodeInputU64(2);e.push({id:i,coin:l})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);n=new Rt(o,this.transaction).getAmountInput().reduce((i,l)=>i+l,0)}return{txType:Ot.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let i=o.decodeOwnedObjectId(2),l=o.typeArg(0),u=this.utils.parseCoinNameFromType(l);e.push({stakeMarketCoinName:u,stakeAccountId:i})}),this.helperClaimBorrowV2Reward.forEach(o=>{let i=o.decodeSharedObjectId(4),l=o.decodeOwnedObjectId(3),u=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:l,obligationKey:i,rewardCoinName:u})}),this.helperClaimBorrowReward.forEach(o=>{let i=o.decodeSharedObjectId(2),l=o.decodeOwnedObjectId(3),u=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:l,obligationKey:i,rewardCoinName:u})}),{txType:Ot.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};import{TransactionType as Ei}from"@msafe/sui3-utils";var Zo=class extends ie{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new W(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new W(e,this.transaction)}decodeCreateReferralLink(){return{txType:Ei.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Ei.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Ei.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};import{TransactionType as Ze}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as up}from"@scallop-io/sui-scallop-sdk";var ta=class extends ie{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new W(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new W(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new W(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new W(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new W(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${up}::user::unstake`));return new W(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake`));return new W(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new W(e,this.transaction)}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:Ze.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new Rt(e,this.transaction).getAmountInput().reduce((v,O)=>v+O,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),i=!!this.helperRedeemSca.moveCall,l=[],u=[],g=[];this.helperOldUnstakeObligation.moveCall&&(l=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(u=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(g=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let T=!1,S=!1,C,I,k=[{condition:l,isOld:!0},{condition:u,isOld:!1},{condition:g,isOld:!1}];for(let v=0;v<k.length;v++)k[v].condition.length>1&&([I,C]=k[v].condition,T=!0,S=k[v].isOld);return{txType:Ze.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:C,obligationKey:I,veScaKey:o,isHaveRedeem:i,isObligationLocked:T,isOldBorrowIncentive:S}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],i=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(i=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,u=!1,g,T,S=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:i,isOld:!1}];for(let C=0;C<S.length;C++)S[C].condition.length>1&&([T,g]=S[C].condition,l=!0,u=S[C].isOld);return{txType:Ze.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:g,obligationKey:T,veScaKey:t,isObligationLocked:l,isOldBorrowIncentive:u}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new Rt(e,this.transaction).getAmountInput().reduce((k,v)=>k+v,0),o=[],i=[],l,u=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(l=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(u=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let g=!1,T=!1,S,C,I=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:u,isOld:!1}];for(let k=0;k<I.length;k++)I[k].condition.length>1&&([C,S]=I[k].condition,g=!0,T=I[k].isOld);return{txType:Ze.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:l,unlockTime:t,obligationId:S,obligationKey:C,isOldBorrowIncentive:T,isObligationLocked:g}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let n=new Rt(e,this.transaction).getAmountInput().reduce((k,v)=>k+v,0),o=[],i=[],l,u=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(l=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(u=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let g=!1,T=!1,S,C,I=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:u,isOld:!1}];for(let k=0;k<I.length;k++)I[k].condition.length>1&&([C,S]=I[k].condition,g=!0,T=I[k].isOld);return{txType:Ze.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:S,obligationKey:C,veScaKey:l,isObligationLocked:g,isOldBorrowIncentive:T}}}};import mp from"sort-keys-recursive";var R=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify(mp(this.data))}isObligationLocked=async(e,t)=>{let n=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),o=!1;return n&&n?.data.content?.dataType==="moveObject"&&"lock_key"in n.data.content.fields&&(o=!!n.data.content.fields.lock_key),o};async buildTxWithRefreshObligation(e,t,n){let o=e.builder.createTxBlock();o.setSender(t.walletAddress);let{obligationId:i,obligationKey:l}=t;return await this.isObligationLocked(e.suiKit.client(),i)?(await o.unstakeObligationQuick(i,l),await n(e,o,t),await o.stakeObligationWithVeScaQuick(i,l,t.veScaKey)):await n(e,o,t),o}};var ea=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:i,obligationId:l,obligationKey:u}=this.data,g=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:g,obligationId:l,obligationKey:u},async(S,C)=>{let I=await C.borrowQuick(+i,o,l,u);C.transferObjects([I],g)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var na=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,n,o){let{obligationId:i,obligationKey:l,veScaKey:u,amount:g,coinName:T}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:o,obligationId:i,obligationKey:l,veScaKey:u},async(C,I)=>{let k=await I.borrowQuick(+g,T,i,l);I.transferObjects([k],o)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var oa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:i,obligationKey:l,veScaKey:u,coinName:g,amount:T}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:i,obligationKey:l,veScaKey:u},async(C,I)=>{let k=I.claimReferralTicket(g),v=await I.borrowWithReferralQuick(+T,g,k,i,l);I.burnReferralTicket(k,g),I.transferObjects([v],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};import{SUI_TYPE_ARG as pp}from"@mysten/sui/utils";var aa=class a extends R{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let n=e.builder.createTxBlock();n.setSender(t);let o=await e.query.getAllStakeAccounts(t),i=await e.query.getLendings(void 0,t),l=await e.query.getObligations(t),u=Object.values(await e.query.getObligationAccounts(t)??[]),g=(()=>{let I=[...e.constants.whitelist.spool].map(k=>e.utils.parseCoinName(k));return Object.values(i??[]).filter(k=>!!k&&I.includes(k.coinName)).reduce((k,v)=>{let O=e.utils.parseMarketCoinName(v.coinName);return k[O]||(k[O]=0),k[O]+=v.availableClaimCoin,k},{})})(),T={};Object.entries(o).forEach(([I,k])=>{for(let v=0;v<k.length;v++){let O=k[v];if(!g[I])continue;let L=n.claim(O.id,I);T.sui?T.sui.push(L):T.sui=[L]}});let S=(()=>{let I={};return I.sui=Object.values(g).reduce((k,v)=>k+v,0),u.forEach(k=>{Object.values(k.borrowIncentives).forEach(v=>{v&&v.rewards.forEach(O=>{I[O.coinName]||(I[O.coinName]=0),I[O.coinName]?I[O.coinName]+=O.availableClaimCoin:I[O.coinName]=O.availableClaimCoin})})}),I})();if(l.length>0&&u.length>0)for(let I=0;I<u.length;I++){let k=u[I],v=!1,O=l.find($=>$.id===k.obligationId)?.keyId,L={};if(O){if(Object.values(k.borrowIncentives).forEach($=>{if($){let Wt=$.rewards.filter(Bt=>{let Et=Bt.coinName;return Bt.availableClaimCoin>0&&!L[Et]});v=Wt.length>0,Wt.forEach(Bt=>{let Et=n.claimBorrowIncentive(k.obligationId,O,Bt.coinName);L[Bt.coinName]=!0,T[Bt.coinName]?T[Bt.coinName].push(Et):T[Bt.coinName]=[Et]})}}),S.sui>0){let $=qt.redeem_rewards(n,O,k.obligationId,pp);T.sui?T.sui.push($):T.sui=[$]}if(v&&await Ec(e.query,k.obligationId)){n.unstakeObligation(k.obligationId,O);let Wt=await e.query.getBindedVeScaKey(k.obligationId);Wt?n.stakeObligationWithVesca(k.obligationId,O,Wt):n.stakeObligation(k.obligationId,O)}}}let C=(await Promise.all(Object.entries(T).map(async([I,k])=>{let v=k[0];if(k.length>1&&n.mergeCoins(v,k.slice(1)),I==="sui"){n.mergeCoins(n.gas,[v]);return}return await e.builder.utils.mergeSimilarCoins(n,v,e.utils.parseCoinType(I),t),v}))).filter(I=>!!I);return C.length>0&&n.transferObjects(C,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var ra=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var ia=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:i,obligationId:l,rewardCoinName:u,veScaKey:g}=this.data,T=n.builder.createTxBlock();T.setSender(o);let S=qt.redeem_rewards(T,i,l,n.utils.parseCoinType(u));return T.transferObjects([S],o),await T.unstakeObligationQuick(l,i),g?await T.stakeObligationWithVeScaQuick(l,i,g):await T.stakeObligationQuick(l,i),T.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var sa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var ca=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var la=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:l,obligationId:u,obligationKey:g}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:u,obligationKey:g},async(S,C)=>{await C.repayQuick(+l,i,u)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var ua=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:l,obligationId:u,veScaKey:g}=this.data,T=n.builder.createTxBlock();T.setSender(o);let S=n.constants.whitelist.borrowing.has(i);return S&&await T.unstakeObligationQuick(u,void 0),await T.repayQuick(+l,i,u),S&&await T.stakeObligationWithVeScaQuick(u,void 0,g),T.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var ma=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var pa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var da=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,n,o){let i=t.builder.createTxBlock();i.setSender(o);let{stakeAccountId:l,amount:u,coinName:g}=this.data,T=[];for(let S=0;S<l.length;S++){let{id:C,coin:I}=l[S],k=t.utils.parseMarketCoinName(g),[v]=await i.unstakeQuick(I,k,C);if(v){let O=i.withdraw(v,g);T.push(O)}}if(u>0){let S=await i.withdrawQuick(u,g);T.push(S)}return T.length>1&&i.mergeCoins(T[0],T.slice(1)),i.transferObjects(T,o),i.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var fa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new a(t)}};var ha=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var ga=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();return i.setSender(o),i.bindToReferral(this.data.veScaKey),i.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new a(t)}};var ya=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:i}=this.data,l=t.address,u=n.builder.createTxBlock();u.setSender(l);let g=i.map(T=>n.utils.parseCoinNameFromType(T));return await u.claimReferralRevenueQuick(o,g),u.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var ba=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();i.setSender(o);let l=i.mintEmptyVeSca();return i.transferObjects([l],o),i.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as dp}from"@scallop-io/sui-scallop-sdk";var Ta=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:i,unlockTime:l,obligationId:u,obligationKey:g,isOldBorrowIncentive:T,isObligationLocked:S}=this.data,C=t.address,I=n.builder.createTxBlock();I.setSender(C);let k=await n.utils.selectCoins(o,dp,C),[v,O]=I.takeAmountFromCoins(k,o);return I.extendLockPeriod(i,l),I.extendLockAmount(i,v),I.transferObjects([O],C),!u||!g||(S&&(T?qt.unstakeObligation(I,u,g):I.unstakeObligation(u,g)),I.stakeObligationWithVesca(u,g,i)),I.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var wa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:i,unlockTime:l,obligationId:u,obligationKey:g,isObligationLocked:T,isOldBorrowIncentive:S}=this.data,C=n.builder.createTxBlock();return C.setSender(o),C.extendLockPeriod(i,l),u&&g&&(T&&(S?qt.unstakeObligation(C,g,u):C.unstakeObligation(u,g)),C.stakeObligationWithVesca(u,g,i)),C.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var Sa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:o}=this.data,i=t.address,l=n.builder.createTxBlock();return l.setSender(i),await l.redeemScaQuick(o),l.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as fp}from"@scallop-io/sui-scallop-sdk";var Ca=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,unlockTime:l,vescaKey:u,isHaveRedeem:g,obligation:T,obligationKey:S,isObligationLocked:C,isOldBorrowIncentive:I}=this.data,k=n.builder.createTxBlock();if(k.setSender(o),g){let $=k.redeemSca(u);k.transferObjects([$],o)}let v=await n.builder.utils.selectCoins(i,fp,o),[O,L]=k.takeAmountFromCoins(v,i);return k.transferObjects([L],o),k.renewExpiredVeSca(u,O,l),!T||!S||(C&&(I?qt.unstakeObligation(k,S,T):k.unstakeObligation(T,S)),k.stakeObligationWithVesca(T,S,u)),k.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as hp}from"@scallop-io/sui-scallop-sdk";var Ia=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,isObligationLocked:l,isOldBorrowIncentive:u,obligationId:g,obligationKey:T,unlockTime:S,veScaKey:C}=this.data,I=n.builder.createTxBlock();I.setSender(o);let k=await n.utils.selectCoins(i,hp,o),[v,O]=I.takeAmountFromCoins(k,i),L;return C?I.extendLockAmount(C,v):L=I.lockSca(v,S),g&&T&&(l&&(u?qt.unstakeObligation(I,T,g):I.unstakeObligation(g,T)),I.stakeObligationWithVesca(g,T,C||L)),C||I.transferObjects([L,O],o),I.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var ka=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:i,coinName:l,stakeAccountId:u}=this.data,g=n.builder.createTxBlock();g.setSender(o);let T=await g.depositQuick(+i,l),S=n.utils.parseMarketCoinName(l);if(n.constants.whitelist.spool.has(S))return g.txBlock;let C=await n.query.getStakeAccounts(S,o),I=u||(C.length>0?C[0].id:void 0);if(I)await g.stakeQuick(T,S,I);else{let k=g.createStakeAccount(S);await g.stakeQuick(T,S,k),g.transferObjects([k],o)}return g.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var xa=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:o}=this.data,i=t.address,l=n.builder.createTxBlock();return l.setSender(i),await l.redeemScaQuick(o),l.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var va=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async deserialize(e){if(!this.scallopClient){let u=new Wc({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e.account.address,suiClients:[e.suiClient]});this.scallopClient=await u.createScallopClient()}let{transaction:t}=e;console.log("transaction",t);let n=new Yo(t,this.scallopClient),o=new Zo(t,this.scallopClient),i=new ta(t,this.scallopClient),l=n.decode()||o.decode()||i.decode();if(!l)throw new Error("Unknown transaction type");return{txType:gp.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:i,intentionData:l}=e;if(!this.scallopClient){let g=new Wc({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e.account.address,suiClients:[e.suiClient]});this.scallopClient=await g.createScallopClient()}let u;switch(i){case"SupplyLending":u=ma.fromData(l);break;case"WithdrawLending":u=ha.fromData(l);break;case"Borrow":u=ea.fromData(l);break;case"Repay":u=la.fromData(l);break;case"DepositCollateral":u=ra.fromData(l);break;case"WithdrawCollateral":u=fa.fromData(l);break;case"OpenObligation":u=ca.fromData(l);break;case"UnstakeSpool":u=pa.fromData(l);break;case"ClaimIncentiveReward":u=aa.fromData(l);break;case"BorrowWithBoost":u=na.fromData(l);break;case"StakeSca":u=Ia.fromData(l);break;case"ExtendStakePeriod":u=wa.fromData(l);break;case"ExtendPeriodAndStakeMore":u=Ta.fromData(l);break;case"RenewExpStakePeriod":u=Ca.fromData(l);break;case"WithdrawStakedSca":u=xa.fromData(l);break;case"SupplyAndStakeLending":u=ka.fromData(l);break;case"WithdrawAndUnstakeLending":u=da.fromData(l);break;case"RedeemSca":u=Sa.fromData(l);break;case"MigrateAndClaim":u=ia.fromData(l);break;case"BorrowWithReferral":u=oa.fromData(l);break;case"CreateReferralLink":u=ba.fromData(l);break;case"ClaimRevenueReferral":u=ya.fromData(l);break;case"BindReferral":u=ga.fromData(l);break;case"MigrateScoin":u=sa.fromData(l);break;case"RepayWithBoost":u=ua.fromData(l);break;default:throw new Error("not implemented")}return u.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};import{TransactionType as Qp}from"@msafe/sui3-utils";import{TransactionType as nn}from"@msafe/sui3-utils";import{normalizeStructTag as fe}from"@mysten/sui/utils";import{fetchRegistryLiquidStakingInfoMap as Rp}from"@suilend/springsui-sdk/client";import{TransactionType as Mp}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as Op,LENDING_MARKET_TYPE as Pp,SuilendClient as Ni}from"@suilend/sdk";import{TransactionType as Pe}from"@msafe/sui3-utils";import{fromBase64 as _c,toHex as Lc}from"@mysten/bcs";import{normalizeStructTag as tn}from"@mysten/sui/utils";import{MAX_U64 as Re}from"@suilend/frontend-sui";import jc from"bignumber.js";var Da=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},t=tn(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Pe.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(g=>g.type.includes("lending_market::RedeemEvent"))},n=tn(t.RedeemEvent.parsedJson.coin_type.name),o=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let i=e.withdraw_ctokens.MoveCall.arguments[4].Input,l=new jc(Lc(_c(this.inputs[i].Pure.bytes)),16).toString(),u=l===Re.toString();return console.log("decodeWithdraw - isMax:",u,"inputIndex:",i,"inputValue:",l,"MAX_U64.toString():",Re.toString()),u&&(o=Re.toString()),{txType:Pe.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(g=>g.type.includes("lending_market::BorrowEvent"))},n=tn(t.BorrowEvent.parsedJson.coin_type.name),o=`${+t.BorrowEvent.parsedJson.liquidity_amount-+t.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,o);let i=e.borrow_request.MoveCall.arguments[4].Input,l=new jc(Lc(_c(this.inputs[i].Pure.bytes)),16).toString(),u=l===Re.toString();return console.log("decodeBorrow - isMax:",u,"inputIndex:",i,"inputValue:",l,"MAX_U64.toString():",Re.toString()),u&&(o=Re.toString()),{txType:Pe.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},t=tn(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Pe.Other,type:"repay",intentionData:{coinType:t,value:n}}}decodeClaim(){let e={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},t={};for(let n=0;n<e.ClaimReward.length;n++){let o=e.ClaimReward[n],i=tn(o.parsedJson.coin_type.name),l=o.parsedJson.liquidity_amount;t[i]=`${+(t[i]??"0")+ +l}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Pe.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Pe.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};import{Transaction as Tp}from"@mysten/sui/transactions";import bp from"sort-keys-recursive";var Nt=class{constructor(e){this.data=e}serialize(){return JSON.stringify(bp(this.data))}};var Aa=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;if(console.log("BorrowIntention.build",n,o,i,l,u),!l||!u)throw new Error("Obligation not found");let g=new Tp;return await i.borrowAndSendToUser(o.address,l.id,u.id,this.data.coinType,this.data.value,g),g}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};import{Transaction as kp}from"@mysten/sui/transactions";import{normalizeStructTag as wp}from"@mysten/sui/utils";import{isSendPoints as Sp}from"@suilend/frontend-sui";import{Side as en}from"@suilend/sdk";import Cp from"bignumber.js";var Ip=(a,e)=>{let t={[en.DEPOSIT]:[],[en.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[en.DEPOSIT,en.BORROW].forEach(o=>{let i=o===en.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,l=e.userRewardManagers.find(u=>u.poolRewardManagerId===i.id);l&&(t[o]=i.poolRewards.map((u,g)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(g),rewardCoinType:wp(u.coinType.name),side:o})).filter(u=>!Sp(u.rewardCoinType)&&!!l.rewards[Number(u.rewardIndex)]&&new Cp(l.rewards[Number(u.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},Ma=Ip;var Oa=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;if(console.log("ClaimIntention.build",n,o,i,l,u),!l||!u)throw new Error("Obligation not found");let g=new kp;return i.claimRewardsAndSendToUser(o.address,l.id,Ma(i,u),g),g}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};import{Transaction as xp}from"@mysten/sui/transactions";var Pa=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;if(console.log("ClaimAndDepositIntention.build",n,o,i,l,u),!l||!u)throw new Error("Obligation not found");let g=new xp;return i.claimRewardsAndDeposit(o.address,l.id,Ma(i,u),g),g}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};import{Transaction as vp}from"@mysten/sui/transactions";var Ra=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;console.log("DepositIntention.build",n,o,i,l,u);let g=new vp;return await i.depositIntoObligation(o.address,this.data.coinType,this.data.value,g,l?.id),g}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};import{Transaction as Dp}from"@mysten/sui/transactions";var Ba=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;if(console.log("RepayIntention.build",n,o,i,l,u),!l||!u)throw new Error("Obligation not found");let g=new Dp;return await i.repayIntoObligation(o.address,u.id,this.data.coinType,this.data.value,g),g}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};import{Transaction as Ap}from"@mysten/sui/transactions";var Ea=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:l,obligation:u}=t;if(console.log("WithdrawIntention.build",n,o,i,l,u),!l||!u)throw new Error("Obligation not found");let g=new Ap;return await i.withdrawAndSendToUser(o.address,l.id,u.id,this.data.coinType,this.data.value,g),g}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var Na=async(a,e)=>{let t=await Ni.initialize(Op,Pp,a),n=await Ni.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(i=>Ni.getObligation(i.obligationId,t.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:o}},Wa=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Na(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",i,"utils:",this.utils,"suiClient:",n);let u=new Da(t,i).decode();return{txType:Mp.Other,txSubType:u.type,intentionData:u.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:l}=e;this.utils||(this.utils=await Na(i,l));let u;switch(n){case"deposit":u=Ra.fromData(o);break;case"withdraw":u=Ea.fromData(o);break;case"borrow":u=Aa.fromData(o);break;case"repay":u=Ba.fromData(o);break;case"claim":u=Oa.fromData(o);break;case"claimAndDeposit":u=Pa.fromData(o);break;default:throw new Error("not implemented")}let g=window.localStorage.getItem("obligationId"),T=this.utils.obligations?.find(C=>C.id===g)??this.utils.obligations?.[0],S=this.utils.obligationOwnerCaps?.find(C=>C.obligationId===T?.id);return u.build({network:t,suiClient:i,account:l,suilendClient:this.utils.suilendClient,obligationOwnerCap:S,obligation:T})}};var Wi=async(a,e)=>{let t=await Na(a,e),n=await Rp(a);return{...t,LIQUID_STAKING_INFO_MAP:n}};var _a=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=fe(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:nn.Other,type:"stake",intentionData:{amount:n,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=fe(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:nn.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=fe(e.RedeemEvent.parsedJson.event.typename.name),n=fe(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:nn.Other,type:"convert",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=fe(e.RedeemEvent.parsedJson.event.typename.name),n=fe(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:nn.Other,type:"convertAndDeposit",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeUnstake(){let e={RedeemEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::RedeemEvent"))},t=fe(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:nn.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};import{Transaction as Np}from"@mysten/sui/transactions";import{convertLstsAndSendToUser as Wp,LstClient as Uc}from"@suilend/springsui-sdk";import Ep from"sort-keys-recursive";var Ft=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Ep(this.data))}};var La=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:l,obligationOwnerCap:u,obligation:g}=t;console.log("ConvertIntention.build",n,o,i,l,u,g);let T=await Uc.initialize(n,Object.values(l).find(I=>I.type===this.data.inCoinType)),S=await Uc.initialize(n,Object.values(l).find(I=>I.type===this.data.outCoinType)),C=new Np;return Wp(T,S,C,o.address,this.data.amount),C}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};import{Transaction as _p}from"@mysten/sui/transactions";import{createObligationIfNoneExists as Lp,sendObligationToUser as jp}from"@suilend/sdk";import{convertLsts as Up,LstClient as qc}from"@suilend/springsui-sdk";var ja=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:l,obligationOwnerCap:u,obligation:g}=t;console.log("ConvertAndDepositIntention.build",n,o,i,l,u,g);let T=await qc.initialize(n,Object.values(l).find(O=>O.type===this.data.inCoinType)),S=await qc.initialize(n,Object.values(l).find(O=>O.type===this.data.outCoinType)),C=new _p,{obligationOwnerCapId:I,didCreate:k}=Lp(i,C,u),v=Up(T,S,C,o.address,this.data.amount);return i.deposit(v,this.data.outCoinType,I,C),k&&jp(I,o.address,C),C}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};import{Transaction as qp}from"@mysten/sui/transactions";import{LstClient as Fp}from"@suilend/springsui-sdk";var Ua=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:l,obligationOwnerCap:u,obligation:g}=t;console.log("StakeIntention.build",n,o,i,l,u,g);let T=await Fp.initialize(n,Object.values(l).find(C=>C.type===this.data.outCoinType)),S=new qp;return T.mintAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};import{Transaction as Kp}from"@mysten/sui/transactions";import{createObligationIfNoneExists as $p,sendObligationToUser as Vp}from"@suilend/sdk";import{LstClient as Hp}from"@suilend/springsui-sdk";var qa=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:l,obligationOwnerCap:u,obligation:g}=t;console.log("StakeAndDepositIntention.build",n,o,i,l,u,g);let T=await Hp.initialize(n,Object.values(l).find(v=>v.type===this.data.outCoinType)),S=new Kp,{obligationOwnerCapId:C,didCreate:I}=$p(i,S,u),k=T.mintAmountAndRebalance(S,o.address,this.data.amount);return i.deposit(k,this.data.outCoinType,C,S),I&&Vp(C,o.address,S),S}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};import{Transaction as Gp}from"@mysten/sui/transactions";import{LstClient as zp}from"@suilend/springsui-sdk";var Fa=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:l,obligationOwnerCap:u,obligation:g}=t;console.log("UnstakeIntention.build",n,o,i,l,u,g);let T=await zp.initialize(n,Object.values(l).find(C=>C.type===this.data.inCoinType)),S=new Gp;return T.redeemAmountAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Ka=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Wi(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",i);let u=new _a(t,i).decode();return{txType:Qp.Other,txSubType:u.type,intentionData:u.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:l}=e;this.utils||(this.utils=await Wi(i,l));let u;switch(n){case"stake":u=Ua.fromData(o);break;case"stakeAndDeposit":u=qa.fromData(o);break;case"convert":u=La.fromData(o);break;case"convertAndDeposit":u=ja.fromData(o);break;case"unstake":u=Fa.fromData(o);break;default:throw new Error("not implemented")}return u.build({network:t,suiClient:i,account:l,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};import{TransactionType as Zp}from"@msafe/sui3-utils";import{TransactionType as Fc}from"@msafe/sui3-utils";var $a=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:Fc.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Fc.Other,type:"redeem",intentionData:{amount:t}}}};import{LST as Xp}from"@alphafi/stsui-sdk";var Va=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},u=await new Xp(i).mint(o,n.address);return u.setGasBudget(1e8),u}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};import{LST as Yp}from"@alphafi/stsui-sdk";var Ha=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},u=await new Yp(i).redeem(o,n.address);return u.setGasBudget(1e8),u}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var Ga=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n}=e,o=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",o);let l=new $a(t,o).decode();return{txType:Zp.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let n;switch(e.txSubType){case"mint":n=Va.fromData(e.intentionData);break;case"redeem":n=Ha.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};import{TransactionType as wd}from"@msafe/sui3-utils";import{TurbosSdk as Sd}from"turbos-clmm-sdk";import{TransactionType as Kt}from"@msafe/sui3-utils";import{bcs as Kc}from"@mysten/sui.js/bcs";import{normalizeStructTag as ed,normalizeSuiAddress as on}from"@mysten/sui.js/utils";import{BN as nd}from"turbos-clmm-sdk";var Vt={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Ht={PackageId:"0xdee9"};var od=(a,e,t,n)=>{if(a===1)switch(n.findIndex(l=>l===e)){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: ${e}`)}switch(t.findIndex(i=>i===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},za=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);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(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.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(`${Vt.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Vt.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(k=>k.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let n=od(t,e.target,this.swap1Layer,this.swap2Layer),o=n.map((k,v)=>{let O=this.helper.decodeSharedObjectId(v),L=this.helper.decodeInputU128(4+v+t),$=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new nd(L.toString()));return{pool:O,a2b:k,nextTickIndex:$}}),i=n[0]||t===1?e.typeArguments[0]:e.typeArguments[1],l=t===1?e.typeArguments[4]:n[0]?e.typeArguments[1]:e.typeArguments[0],u=this.helper.decodeInputAddress(6+2*t),g=this.helper.decodeInputU64(7+2*t),T=this.helper.decodeInputBool(5+2*t),S=this.helper.decodeInputU64(2+t),C=this.helper.decodeInputU64(3+t),I=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:o[0].pool,a2b:o[0].a2b,amountSpecified:S}],address:u,amountSpecifiedIsInput:T});return{txType:Kt.Other,type:"Swap",intentionData:{routes:o,coinTypeA:i,coinTypeB:l,address:u,amountA:T?S:C,amountB:T?C:S,amountSpecifiedIsInput:T,slippage:"0.1",deadline:g}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),l=this.helper.decodeInputBool(5),u=this.helper.decodeInputU32(6),g=this.helper.decodeInputBool(7),T=this.helper.decodeInputU64(13);return{txType:Kt.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:n,amountB:o,tickLower:l?-i:i,tickUpper:g?-u:u,deadline:T}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),i=this.helper.decodeInputU64(6),l=this.helper.decodeInputU64(9);return{txType:Kt.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:o,amountB:i,nft:n,deadline:l}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),l=this.helper.decodeInputU64(5),u=this.helper.decodeInputU64(6);return{txType:Kt.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:l,slippage:10,address:e,deadline:u}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),l=this.helper.decodeInputU64(6);return{txType:Kt.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:o,collectAmountB:i,nft:t,deadline:l}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(l=>l.decodeInputU64(5)),i=this.helper.decodeInputU64(7);return{txType:Kt.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:o,nft:t,deadline:i}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:Kt.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),i=this.decreaseLiquidityHelper.decodeInputU64(4),l=this.decreaseLiquidityHelper.decodeInputU64(5),u=this.decreaseLiquidityHelper.decodeInputU64(6),g=this.collectRewardHelper.map(C=>C.decodeInputU64(5)),T=this.collectFeeHelper.decodeInputU64(3)||0,S=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:Kt.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:l,slippage:10,address:e,collectAmountA:T,collectAmountB:S,rewardAmounts:g,deadline:u}}}decodePrixClaim(){return{txType:Kt.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:Kt.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let e=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),t=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:Kt.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let e=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),t=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:Kt.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new se(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new se(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new se(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new se(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Ht.PackageId}::clob_v2::swap_exact_base_for_quote`);return new se(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Ht.PackageId}::clob_v2::swap_exact_quote_for_base`);return new se(e,this.txb)}},se=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return on(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Kc.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return on(e.value.Object.ImmOrOwned.objectId)}return on(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return on(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return on(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Kc.de(t,new Uint8Array(n))}typeArg(e){return ed(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};import{TurbosSdk as ad}from"turbos-clmm-sdk";var Qa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new ad(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:l,amountB:u,slippage:g,tickLower:T,tickUpper:S,deadline:C,txb:I}=this.data;return n.pool.addLiquidity({pool:o,slippage:g,address:i,amountA:l,amountB:u,tickLower:T,tickUpper:S,deadline:C,txb:I})}static fromData(t){return new a(t)}};import{TurbosSdk as rd}from"turbos-clmm-sdk";var Ja=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new rd(t.network.replace("sui:",""),t.suiClient),{pool:o,nft:i,txb:l}=this.data;return n.nft.burn({pool:o,nft:i,txb:l})}static fromData(t){return new a(t)}};import{TurbosSdk as id}from"turbos-clmm-sdk";var Xa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new id(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:l,collectAmountA:u,collectAmountB:g,deadline:T,txb:S}=this.data;return n.pool.collectFee({pool:o,address:i,collectAmountA:u,collectAmountB:g,nft:l,deadline:T,txb:S})}static fromData(t){return new a(t)}};import{TurbosSdk as sd}from"turbos-clmm-sdk";var Ya=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new sd(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:l,rewardAmounts:u,deadline:g,txb:T}=this.data;return n.pool.collectReward({pool:o,address:i,rewardAmounts:u,nft:l,deadline:g,txb:T})}static fromData(t){return new a(t)}};import{TurbosSdk as cd}from"turbos-clmm-sdk";var Za=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new cd(t.network.replace("sui:",""),t.suiClient),{fee:o,address:i,tickLower:l,tickUpper:u,sqrtPrice:g,slippage:T,coinTypeA:S,coinTypeB:C,amountA:I,amountB:k,deadline:v,txb:O}=this.data;return n.pool.createPool({fee:o,amountA:I,amountB:k,address:i,tickLower:l,tickUpper:u,sqrtPrice:g,slippage:T,coinTypeA:S,coinTypeB:C,deadline:v,txb:O})}static fromData(t){return new a(t)}};import{TurbosSdk as ld}from"turbos-clmm-sdk";var tr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new ld(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:l,amountB:u,slippage:g,nft:T,decreaseLiquidity:S,deadline:C,txb:I}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:g,address:i,amountA:l,amountB:u,nft:T,decreaseLiquidity:S,deadline:C,txb:I})}static fromData(t){return new a(t)}};import{TurbosSdk as ud}from"turbos-clmm-sdk";var er=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new ud(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:l,amountB:u,slippage:g,nft:T,deadline:S,txb:C}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:g,address:i,amountA:l,amountB:u,nft:T,deadline:S,txb:C})}static fromData(t){return new a(t)}};import{TransactionBlock as md}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as pd}from"@mysten/sui.js/utils";var nr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new md;return n.moveCall({target:`${Vt.PackageId}::claim::claim`,typeArguments:[Vt.turbosCoinType],arguments:[n.object(Vt.Claim),n.object(pd)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as dd}from"@mysten/sui.js/transactions";var or=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new dd;return n.moveCall({target:`${Vt.PackageId}::claim::join`,typeArguments:[Vt.turbosCoinType],arguments:[n.object(Vt.Claim)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as fd}from"@mysten/sui.js/transactions";import{TurbosSdk as hd}from"turbos-clmm-sdk";var ar=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new hd(t.network.replace("sui:",""),t.suiClient),o=new fd;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(t){return new a(t)}};import{TurbosSdk as gd}from"turbos-clmm-sdk";var rr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new gd(t.network.replace("sui:",""),t.suiClient),{routes:o,coinTypeA:i,coinTypeB:l,address:u,amountA:g,amountB:T,slippage:S,amountSpecifiedIsInput:C,deadline:I,txb:k}=this.data;return n.trade.swap({routes:o,coinTypeA:i,coinTypeB:l,address:u,amountA:g,amountB:T,amountSpecifiedIsInput:C,slippage:S,deadline:I,txb:k})}static fromData(t){return new a(t)}};import{TurbosSdk as bd}from"turbos-clmm-sdk";import{TransactionBlock as $c}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as Vc}from"@mysten/sui.js/utils";import{unstable_getObjectId as yd}from"turbos-clmm-sdk";var an=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,n){let o=[],i;do i=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:i?.nextCursor}),o.push(...i.data);while(i.hasNextPage);let l=[],u=0;return o.sort((g,T)=>Number(T.balance)-Number(g.balance)).some(g=>u>=n?!0:(u+=Number(g.balance),l.push(g),!1)),l}splitAndMergeCoin(e,t,n){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[l]=n.splitCoins(n.gas,[n.pure(t)]);return[l,void 0]}let o=n.object(e[0].coinObjectId);e.length>1&&n.mergeCoins(o,e.slice(1).map(l=>n.object(l.coinObjectId)));let[i]=n.splitCoins(o,[n.pure(t)]);return[i,o]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${Ht.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?yd(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Ht.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var Hc=89,Gc=1e6,zc=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:l}=a,u=new $c,g=new an(l),T=await g.getCoinsData(i,t,o),[S,C]=g.splitAndMergeCoin(T,o,u);if(!S)throw new Error(`Not enough balance: ${t}`);let I=await g.IsAccountCap(i),k=I?u.object(I):g.createAccount(u),[v,O,L]=u.moveCall({typeArguments:[e,t],target:`${Ht.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[u.object(String(n)),u.pure(Hc),k,u.pure(o),u.object(Vc("0x6")),S]});return C&&u.transferObjects([C],u.pure(i)),u.transferObjects([v],u.pure(i)),u.transferObjects([O],u.pure(i)),I||u.transferObjects([k],u.pure(i)),u.setSenderIfNotSet(i),u.setGasBudget(Gc),u},Qc=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:l}=a,u=new $c,g=new an(l),T=await g.getCoinsData(i,e,o),[S,C]=g.splitAndMergeCoin(T,o,u);if(!S)throw new Error(`Not enough balance: ${e}`);let I=await g.IsAccountCap(i),k=I?u.object(I):g.createAccount(u),v=g.zero(t,u),[O,L,$]=u.moveCall({typeArguments:[e,t],target:`${Ht.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[u.object(String(n)),u.pure(Hc),k,u.pure(o),S,v,u.object(Vc("0x6"))]});return C&&u.transferObjects([C],u.pure(i)),u.transferObjects([O],u.pure(i)),u.transferObjects([L],u.pure(i)),I||u.transferObjects([k],u.pure(i)),u.setSenderIfNotSet(i),u.setGasBudget(Gc),u};var ir=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new bd(t.network.replace("sui:",""),t.suiClient);return await Qc({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};import{TurbosSdk as Td}from"turbos-clmm-sdk";var sr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Td(t.network.replace("sui:",""),t.suiClient);return await zc({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var cr=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new Sd(e.network.replace("sui:",""),e.suiClient),n=await t.contract.getConfig(),{transactionBlock:o,account:i}=e;console.log(e,"input");let u=await new za(o,t,n).decode(i.address);return{txType:wd.Other,txSubType:u.type,intentionData:u.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":i=Za.fromData(e.intentionData);break;case"AddLiquidity":i=Qa.fromData(e.intentionData);break;case"IncreaseLiquidity":i=er.fromData(e.intentionData);break;case"DecreaseLiquidity":i=tr.fromData(e.intentionData);break;case"RemoveLiquidity":i=ar.fromData(e.intentionData);break;case"CollectFee":i=Xa.fromData(e.intentionData);break;case"CollectReward":i=Ya.fromData(e.intentionData);break;case"Burn":i=Ja.fromData(e.intentionData);break;case"Swap":i=rr.fromData(e.intentionData);break;case"PrixJoin":i=or.fromData(e.intentionData);break;case"PrixClaim":i=nr.fromData(e.intentionData);break;case"SwapExactBaseForQuote":i=ir.fromData(e.intentionData);break;case"SwapExactQuoteForBase":i=sr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};import{TransactionType as Ad}from"@msafe/sui3-utils";import{TransactionType as _i}from"@msafe/sui3-utils";import{bcs as Jc}from"@mysten/sui.js/bcs";import{normalizeStructTag as kd,normalizeSuiAddress as rn}from"@mysten/sui.js/utils";var Cd={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Dt=Cd;var lr=class{constructor(e){this.txb=e}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(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:_i.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:_i.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:_i.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Dt.packageId));return new Li(e,this.txb)}},Li=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return rn(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Jc.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return rn(e.value.Object.ImmOrOwned.objectId)}return rn(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return rn(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return rn(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Jc.de(t,new Uint8Array(n))}typeArg(e){return kd(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{TransactionBlock as xd}from"@mysten/sui.js/transactions";var ur=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new xd,{ticketId:o}=this.data;return n.moveCall({target:`${Dt.packageId}::native_pool::burn_ticket`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as vd}from"@mysten/sui.js/transactions";var mr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new vd,{amount:o}=this.data,[i]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::stake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),i]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as Dd}from"@mysten/sui.js/transactions";var pr=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Dd,{amount:o}=this.data,i=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[l,...u]=i.filter(S=>S.coinType.split("::")[0]===Dt.certType.split("::")[0]),g=n.object(l.coinObjectId);u.length&&n.mergeCoins(g,u.map(S=>n.object(S.coinObjectId)));let T=n.splitCoins(n.object(l.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::unstake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),T]}),n}static fromData(t){return new a(t)}};var dr=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,o=new lr(t).decode();return{txType:Ad.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case"Stake":o=mr.fromData(e.intentionData);break;case"UnStake":o=pr.fromData(e.intentionData);break;case"ClaimTicket":o=ur.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionType as jd}from"@msafe/sui3-utils";import{asIntN as Xc}from"@cetusprotocol/common-sdk";import{TransactionType as he}from"@msafe/sui3-utils";import{fromBase64 as sn}from"@mysten/bcs";import{bcs as cn}from"@mysten/sui/bcs";var fr=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:he.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number(Xc(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number(Xc(BigInt(this.getU32(this.getInputIndex(e,3)))).toString()),tokenAmount:this.getU64(this.getInputIndex(t,6)),maxAmountTokenA:this.getU64(this.getInputIndex(t,7)),maxAmountTokenB:this.getU64(this.getInputIndex(t,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(t,9))}}}decodeClosePositionTx(){let e=this.getMoveCallCommand("close_position"),t=this.getCollectRewardCallData();return{txType:he.Other,type:"ClosePosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),transferTokensTo:this.getAddress(this.getInputIndex(e,4)),collectRewardTokens:t.map(n=>n.rewardCoinType),collectFeeTokens:this.getTypeArguments(e)}}}decodeProvideLiquidityTx(){let e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:he.Other,type:"ProvideLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),tokenAmount:this.getU64(this.getInputIndex(e,6)),maxAmountTokenA:this.getU64(this.getInputIndex(e,7)),maxAmountTokenB:this.getU64(this.getInputIndex(e,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(e,9))}}}decodeRemoveLiquidityTx(){let e=this.getMoveCallCommand("remove_liquidity");return{txType:he.Other,type:"RemoveLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),liquidity:this.getU128(this.getInputIndex(e,4)),maxAmountTokenA:this.getU64(this.getInputIndex(e,5)),maxAmountTokenB:this.getU64(this.getInputIndex(e,6)),transferTokensTo:this.getAddress(this.getInputIndex(e,7)),...this.collectTokens()}}}decodeCollectRewardsTx(){let e=this.getCollectRewardCallData();return{txType:he.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:he.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:he.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(n=>n.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(cn.u32().parse(Uint8Array.from(sn(this.inputs[e].Pure.bytes))))}getU64(e){return cn.u64().parse(Uint8Array.from(sn(this.inputs[e].Pure.bytes)))}getU128(e){return cn.u128().parse(Uint8Array.from(sn(this.inputs[e].Pure.bytes)))}getBoolean(e){return cn.bool().parse(Uint8Array.from(sn(this.inputs[e].Pure.bytes)))}getAddress(e){return cn.Address.parse(Uint8Array.from(sn(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};import{TransactionType as Rd}from"@msafe/sui3-utils";import{BN as ge,ClmmPoolUtil as Pd}from"@firefly-exchange/library-sui";import{SuiClient as Md}from"@firefly-exchange/library-sui";import{OnChainCalls as Od}from"@firefly-exchange/library-sui/dist/src/spot";var Yc={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x6c796c3ab3421a68158e0df18e4657b2827b1f8fed5ed4b82dba9c935988711b"}},le=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Md({url:Yc.rpc});return new Od(t,Yc.objects,{address:e.address,isUIWallet:!1})};var Pt=class{static async OpenPosition(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool),l=this.prototype.buildLiqInput(i,{...e,slippage:0});return await o.openPositionWithFixedAmount(i,e.lowerTick,e.upperTick,l,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool),l=this.prototype.buildLiqInput(i,e);return await o.provideLiquidityWithFixedAmount(i,e.position,l,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(i,e.position,{liquidityAmount:new ge(e.liquidity),tokenMaxA:new ge(e.maxAmountTokenA),tokenMaxB:new ge(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool);return await o.closePosition(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectRewards(i,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectFee(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let o=le(n,t),i=await o.queryChain.getPool(e.pool);return console.log(e.position),await o.collectFeeAndRewards(i,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...Pd.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ge(t.tokenAmount),t.isTokenAFixed,!0,0,new ge(e.current_sqrt_price)),tokenMaxA:new ge(t.maxAmountTokenA),tokenMaxB:new ge(t.maxAmountTokenB)}}};var hr=class a extends x{constructor(t){super(t);this.data=t}txType=Rd.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.closePosition(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Bd}from"@msafe/sui3-utils";var gr=class a extends x{constructor(t){super(t);this.data=t}txType=Bd.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectFee(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Ed}from"@msafe/sui3-utils";var yr=class a extends x{constructor(t){super(t);this.data=t}txType=Ed.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectRewards(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Nd}from"@msafe/sui3-utils";var br=class a extends x{constructor(t){super(t);this.data=t}txType=Nd.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Wd}from"@msafe/sui3-utils";var Tr=class a extends x{constructor(t){super(t);this.data=t}txType=Wd.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.OpenPosition(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as _d}from"@msafe/sui3-utils";var wr=class a extends x{constructor(t){super(t);this.data=t}txType=_d.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.provideLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Ld}from"@msafe/sui3-utils";var Sr=class a extends x{constructor(t){super(t);this.data=t}txType=Ld.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.removeLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var Cr=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,o=new fr(t).decode();return{txType:jd.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let i;switch(e.txSubType){case"OpenPosition":i=Tr.fromData(e.intentionData);break;case"ProvideLiquidity":i=wr.fromData(e.intentionData);break;case"RemoveLiquidity":i=Sr.fromData(e.intentionData);break;case"ClosePosition":i=hr.fromData(e.intentionData);break;case"CollectFee":i=gr.fromData(e.intentionData);break;case"CollectRewards":i=yr.fromData(e.intentionData);break;case"CollectRewardsAndFee":i=br.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};import{TransactionType as sf}from"@msafe/sui3-utils";import{MmtSDK as Hd}from"@mmt-finance/clmm-sdk";import{Transaction as Gd}from"@mysten/sui/transactions";var B=dl(tl());import{convertI32ToSigned as ln,TickMath as el}from"@mmt-finance/clmm-sdk/dist/utils/math/tickMath";var Ud="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Gt=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",qd=async({suiClient:a,address:e,type:t})=>{let n,o=[],i=0;do{try{let l=await a.getCoins({owner:e,coinType:t,cursor:n,limit:50});o=o.concat(l.data),n=l.nextCursor,(!l.hasNextPage||i===8)&&(n=null)}catch(l){console.log(l),n=null}i++}while(n!==null);return o},Fd=(a,e)=>{let t=[],n=BigInt(0);for(let o of e)n<a&&!t.includes(o.objectId)&&(t.push(o.objectId),n+=BigInt(o.balance)),o.balance===BigInt(0)&&!t.includes(o.objectId)&&t.push(o.objectId);if(n>=a)return t;throw new Error("Insufficient balance")},Kd=(a,e,t,n)=>{if(a===Ud){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=Fd(t,e);o.length>1&&n.mergeCoins(n.object(o[0]),o.slice(1).map(l=>n.object(l)));let[i]=n.splitCoins(n.object(o[0]),[n.pure.u64(t)]);return i}};async function Be(a,e,t,n,o){let i=await qd({suiClient:a.rpcClient,address:e,type:t});return Kd(Gt(t),i.map(u=>({balance:BigInt(u.balance),objectId:u.coinObjectId})),n,o)}function N(a,e,t){let n=a.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function $d(a){let e;return a&1?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),a&2&&(e=N(e.mul(new B.default("79236085330515764027303304731")),96,256)),a&4&&(e=N(e.mul(new B.default("79244008939048815603706035061")),96,256)),a&8&&(e=N(e.mul(new B.default("79259858533276714757314932305")),96,256)),a&16&&(e=N(e.mul(new B.default("79291567232598584799939703904")),96,256)),a&32&&(e=N(e.mul(new B.default("79355022692464371645785046466")),96,256)),a&64&&(e=N(e.mul(new B.default("79482085999252804386437311141")),96,256)),a&128&&(e=N(e.mul(new B.default("79736823300114093921829183326")),96,256)),a&256&&(e=N(e.mul(new B.default("80248749790819932309965073892")),96,256)),a&512&&(e=N(e.mul(new B.default("81282483887344747381513967011")),96,256)),a&1024&&(e=N(e.mul(new B.default("83390072131320151908154831281")),96,256)),a&2048&&(e=N(e.mul(new B.default("87770609709833776024991924138")),96,256)),a&4096&&(e=N(e.mul(new B.default("97234110755111693312479820773")),96,256)),a&8192&&(e=N(e.mul(new B.default("119332217159966728226237229890")),96,256)),a&16384&&(e=N(e.mul(new B.default("179736315981702064433883588727")),96,256)),a&32768&&(e=N(e.mul(new B.default("407748233172238350107850275304")),96,256)),a&65536&&(e=N(e.mul(new B.default("2098478828474011932436660412517")),96,256)),a&131072&&(e=N(e.mul(new B.default("55581415166113811149459800483533")),96,256)),a&262144&&(e=N(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),N(e,32,256)}function Vd(a){let e=Math.abs(a),t;return e&1?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),e&2&&(t=N(t.mul(new B.default("18444899583751176498")),64,256)),e&4&&(t=N(t.mul(new B.default("18443055278223354162")),64,256)),e&8&&(t=N(t.mul(new B.default("18439367220385604838")),64,256)),e&16&&(t=N(t.mul(new B.default("18431993317065449817")),64,256)),e&32&&(t=N(t.mul(new B.default("18417254355718160513")),64,256)),e&64&&(t=N(t.mul(new B.default("18387811781193591352")),64,256)),e&128&&(t=N(t.mul(new B.default("18329067761203520168")),64,256)),e&256&&(t=N(t.mul(new B.default("18212142134806087854")),64,256)),e&512&&(t=N(t.mul(new B.default("17980523815641551639")),64,256)),e&1024&&(t=N(t.mul(new B.default("17526086738831147013")),64,256)),e&2048&&(t=N(t.mul(new B.default("16651378430235024244")),64,256)),e&4096&&(t=N(t.mul(new B.default("15030750278693429944")),64,256)),e&8192&&(t=N(t.mul(new B.default("12247334978882834399")),64,256)),e&16384&&(t=N(t.mul(new B.default("8131365268884726200")),64,256)),e&32768&&(t=N(t.mul(new B.default("3584323654723342297")),64,256)),e&65536&&(t=N(t.mul(new B.default("696457651847595233")),64,256)),e&131072&&(t=N(t.mul(new B.default("26294789957452057")),64,256)),e&262144&&(t=N(t.mul(new B.default("37481735321082")),64,256)),t}var Ir=(a,e,t)=>{let n=ln(t?a+a%(e??1):a-a%(e??1));return n>0?new B.default($d(n)):new B.default(Vd(n))},nl=async(a,e,t,n,o,i,l,u,g)=>{let T=Ir(ln(u),i.tickSpacing),S=Ir(ln(g),i.tickSpacing),C=BigInt(Math.ceil(Number(n)*10**i.tokenX.decimals)),I=BigInt(Math.ceil(Number(o)*10**i.tokenY.decimals)),k,v;Number(n)?k=await Be(a,t,Gt(i.tokenX.coinType),C,e):[k]=e.moveCall({target:"0x2::coin::zero",typeArguments:[i.tokenX.coinType],arguments:[]}),Number(o)?v=await Be(a,t,Gt(i.tokenY.coinType),I,e):[v]=e.moveCall({target:"0x2::coin::zero",typeArguments:[i.tokenY.coinType],arguments:[]});let O={objectId:l,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing},L=a.Position.openPosition(e,O,T.toString(),S.toString());a.Pool.addLiquidity(e,O,L,k,v,BigInt(0),BigInt(0),t),e.transferObjects([L],e.pure.address(t))},ol=async(a,e,t,n,o,i,l,u,g)=>{try{let T=BigInt(Math.ceil(Number(o)*10**(i?l.tokenX.decimals:l.tokenY.decimals))),S=i?l.tokenX.coinType:l.tokenY.coinType;S=Gt(S);let C=await Be(a,n,S,T,e),I={objectId:l.objectId,tokenXType:Gt(l.tokenX.coinType),tokenYType:Gt(l.tokenY.coinType),tickSpacing:l.tickSpacing},k=Ir(ln(u),l.tickSpacing),v=Ir(ln(g),l.tickSpacing),O=a.Position.openPosition(e,I,k.toString(),v.toString()),$=(await t.getObject({id:l.objectId,options:{showContent:!0}}))?.data?.content?.fields?.sqrt_price??l.currentSqrtPrice,Wt=el.sqrtPriceX64ToPrice(new B.default($?.toString()),l.tokenX.decimals,l.tokenY.decimals),Bt=el.priceToSqrtPriceX64(Wt.mul(i?.99:1.01),l.tokenX.decimals,l.tokenY.decimals);await a.Pool.addLiquiditySingleSided(e,I,O,C,BigInt(0),BigInt(0),i,n,BigInt(Bt.toString())),e.transferObjects([O],e.pure.address(n))}catch(T){console.error(T)}};var kr=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Hd.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amountA:i,amountB:l,pool:u,selectedLowTick:g,selectedHighTick:T}=n,S=new Gd;return await nl(t,S,o,i,l,u,u.objectId,g,T),S}static fromData(t){return new a(t)}};import{MmtSDK as zd}from"@mmt-finance/clmm-sdk";import{Transaction as Qd}from"@mysten/sui/transactions";var xr=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=zd.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amount:i,isTokenX:l,pool:u,selectedLowTick:g,selectedHighTick:T}=n,S=new Qd;return await ol(t,S,t.rpcClient,o,i,l,u,g,T),S}static fromData(t){return new a(t)}};import{MmtSDK as Jd}from"@mmt-finance/clmm-sdk";import{Transaction as Xd}from"@mysten/sui/transactions";var Ee=(a,e,t,n,o)=>{let i={objectId:n.objectId,tokenXType:n.tokenXType,tokenYType:n.tokenYType};(n?.rewarders?.length??0)>0&&a.Pool.collectAllRewards(o,i,n.rewarders,t.objectId,e),a.Pool.collectFee(o,n,t.objectId,e)};var vr=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Jd.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,positions:i,pools:l}=n,u=new Xd;for(let g of i){let T=l.find(S=>S.objectId===g.poolId);Ee(t,o,g,T,u)}return u}static fromData(t){return new a(t)}};import{MmtSDK as Yd}from"@mmt-finance/clmm-sdk";import{Transaction as Zd}from"@mysten/sui/transactions";var Dr=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Yd.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,position:i,pool:l}=n,u=new Zd;return Ee(t,o,i,l,u),u}static fromData(t){return new a(t)}};import{MmtSDK as tf}from"@mmt-finance/clmm-sdk";import{Transaction as ef}from"@mysten/sui/transactions";import nf from"bignumber.js";var Ar=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=tf.NEW({network:"mainnet"}),{params:n}=this.data,{pool:o,position:i,address:l,withdrawPercentage:u}=n,g=new ef,T=o.tokenX.coinType,S=o.tokenY.coinType,C={objectId:o.objectId,tokenXType:T,tokenYType:S},I=BigInt(u===100?i.liquidity:new nf(i.liquidity).multipliedBy(u/100).toFixed(0));return t.Pool.removeLiquidity(g,C,i.objectId,I,BigInt(0),BigInt(0),l),Ee(t,l,i,o,g),u===100&&t.Position.closePosition(g,i.objectId),g}static fromData(t){return new a(t)}};import{MmtSDK as af}from"@mmt-finance/clmm-sdk";import{Transaction as rf}from"@mysten/sui/transactions";import{mappedMmtV3Pool as of}from"@mmt-finance/clmm-sdk/dist/utils/poolUtils";var al=async(a,e,t,n,o,i)=>{let l=BigInt(Math.ceil(Number(n)*10**t.decimals)),u=await Be(a,o,Gt(t.coinType),l,i),g=t.coinType;for(let T=0;T<e.length;T+=1){let{objectId:S,tokenX:C,tokenY:I,isStable:k}=e[T],{id:v,isReverse:O}=of[S]||{id:S,isReverse:!1},L=Gt(C.coinType)===Gt(g);L=O?!L:L;let $=O?I.coinType:C.coinType,Wt=O?C.coinType:I.coinType,Bt=a.Pool.swap(i,{objectId:v,tokenXType:$,tokenYType:Wt,isStable:k},l,u,L,void 0);i.transferObjects([u],i.pure.address(o)),u=Bt,g=L?Wt:$,[l]=i.moveCall({target:"0x2::coin::value",typeArguments:[g],arguments:[u]})}i.transferObjects([u],i.pure.address(o))};var Mr=class a extends x{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=af.NEW({network:"mainnet"}),{params:n}=this.data,{route:o,tokenIn:i,amountIn:l,address:u}=n,g=new rf;return await al(t,o,i,l,u,g),g}static fromData(t){return new a(t)}};var Or=class{application="mmt-dex";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:sf.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=Mr.fromData(e.intentionData);break;case"AddLiquidity":t=kr.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=xr.fromData(e.intentionData);break;case"ClaimRewards":t=Dr.fromData(e.intentionData);break;case"ClaimAllRewards":t=vr.fromData(e.intentionData);break;case"RemoveLiquidity":t=Ar.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build()}};var hE=Xo.fromHelpers([new _o,new Go,new Eo,new zo,new so,new cr,new Or,new va,new dr,new _n,new Wa,new Ka,new Tn,new Cr,new Ga]);export{hE as appHelpers};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|