@msafe/sui-app-store 0.0.221 → 0.0.225
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -2
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Lc=Object.defineProperty;var ui=(a,t)=>{for(var e in t)Lc(a,e,{get:t[e],enumerable:!0})};import{TransactionType as Jc}from"@msafe/sui3-utils";import{coinsList as Fc,poolIdPoolNameMap as qc,poolInfo as pi,singleAssetPoolCoinMap as $c}from"@alphafi/alphafi-sdk";import{TransactionType as zt}from"@msafe/sui3-utils";import{bcs as ve,fromBase64 as Ae}from"@mysten/bcs";var Oe=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let t=this.getLiquidityChangeEvent();if(!t)throw new Error("No liquidity change event found. Unable to decode transaction.");let e=t.parsedJson,n=e.pool_id,o=qc[n];if(console.log("Decoder event data - ",e),console.log("Decoder poolName - ",o),this.isWithdrawAlphaEvent(t))return this.decodeWithdrawAlpha(e);if(this.isWithdrawEvent(e))return this.decodeWithdraw(o);if(this.isDoubleAssetDepositEvent(e,o))return this.decodeDoubleAssetDeposit(o,e);if(this.isSingleAssetDepositEvent(e,o))return this.decodeSingleAssetDeposit(o,e);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getLiquidityChangeEvent(){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(t){return t.includes("LiquidityChangeEvent")||t.includes("LiquidityChangeNewNewEvent")||t.includes("WithdrawEventV2")}isWithdrawAlphaEvent(t){return t.type.includes("WithdrawEventV2")}isWithdrawEvent(t){return t.event_type===1}isDoubleAssetDepositEvent(t,e){return t.event_type===0&&pi[e].assetTypes.length===2}isSingleAssetDepositEvent(t,e){return t.event_type===0&&pi[e].assetTypes.length===1}extractXTokensAmount(){let t=this.inputs.find(o=>o.Pure!==void 0);if(!t||!t.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:e}=t.Pure,n;return e.length===12?n=ve.u64().parse(Ae(e)):e.length===24?n=ve.u128().parse(Ae(e)):e.length===44?n=ve.u256().parse(Ae(e)):n=ve.u64().parse(Ae(e)),n}decodeDoubleAssetDeposit(t,e){let{amount_a:n,amount_b:o}=e,r=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,r),{txType:zt.Other,type:"depositDoubleAsset",intentionData:{poolName:t,amount:r?n:o,isAmountA:r}}}decodeSingleAssetDeposit(t,e){let{amount:n}=e;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:r}=$c[t],{expo:i}=Fc[r];n=Math.floor(Number(n)/10**(9-i)).toString()}return{txType:zt.Other,type:"depositSingleAsset",intentionData:{poolName:t,amount:n}}}decodeWithdraw(t){let e=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",e),{txType:zt.Other,type:"withdraw",intentionData:{poolName:t,xTokensAmount:e}}}decodeWithdrawAlpha(t){let e=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=t;return console.log("Decoder.decodeWithdrawAlpha",e,n),{txType:zt.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:e}}}decodeClaimReward(){return{txType:zt.Other,type:"claimReward",intentionData:{}}}};import{claimRewardTxb as Vc}from"@alphafi/alphafi-sdk";import Kc from"sort-keys-recursive";var f=class{constructor(t){this.data=t}serialize(){return JSON.stringify(Kc(this.data))}};var Pe=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e;return await Vc(n.address)}static fromData(e){return new a(e)}};import{depositDoubleAssetTxb as Qc}from"@alphafi/alphafi-sdk";var Re=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:o,amount:r,isAmountA:i}=this.data;return await Qc(o,n.address,r,i)}static fromData(e){return console.log("DepositDoubleAssetIntention.fromData",e),new a(e)}};import{depositSingleAssetTxb as Hc}from"@alphafi/alphafi-sdk";var _e=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:o,amount:r}=this.data;return await Hc(o,n.address,r)}static fromData(e){return console.log("DepositSingleAssetIntention.fromData",e),new a(e)}};import{withdrawTxb as Gc}from"@alphafi/alphafi-sdk";var Be=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:o,xTokensAmount:r}=this.data;return await Gc(r,o,n.address)}static fromData(e){return console.log("WithdrawIntention.fromData",e),new a(e)}};import{withdrawAlphaTxb as zc}from"@alphafi/alphafi-sdk";var Me=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{withdrawFromLocked:o,xTokensAmount:r}=this.data;return await zc(r,o,n.address)}static fromData(e){return console.log("WithdrawAlphaIntention.fromData",e),new a(e)}};var Ee=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(t){let{transaction:e,suiClient:n,account:o}=t,r=await n.devInspectTransactionBlock({sender:e.getData().sender,transactionBlock:e});console.log("AlphaFiHelper Sim result - ",r);let s=new Oe(e,r).decode();return{txType:Jc.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{account:e}=t;console.log("AlphaFi build transaction type",t.txSubType);let n;switch(t.txSubType){case"depositSingleAsset":n=_e.fromData(t.intentionData);break;case"depositDoubleAsset":n=Re.fromData(t.intentionData);break;case"withdraw":n=Be.fromData(t.intentionData);break;case"withdrawAlpha":n=Me.fromData(t.intentionData);break;case"claimReward":n=Pe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({account:e})}};import{TransactionType as Sl}from"@msafe/sui3-utils";import{TransactionType as U}from"@msafe/sui3-utils";import{bcs as gr}from"@mysten/sui/bcs";import{SBUCK_FOUNTAIN_PACKAGE_ID as hr}from"bucket-protocol-sdk";var Ne=class{constructor(t){this.transaction=t}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(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getMoveCallModuleCommand(t,e){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===t&&n.MoveCall.function===e)}getMoveCallPackageModuleCommand(t,e,n){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.package===t&&o.MoveCall.module===e&&o.MoveCall.function===n)}getMoveCallModuleCommands(t,e){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===t&&n.MoveCall.function===e)}getSplitCoinsCommands(){return this.commands.filter(t=>t.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(t=>t.$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(hr,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(hr,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(hr,"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 t,e,n="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),this.getMoveCallCommand("charge_reservoir")?([t]=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments,e=!1):([t]=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments,e=!0),console.log("Decoder.decodePsm",t,n,e),{txType:U.Other,type:"psm",intentionData:{coinType:t,amount:n,buckToCoin:e}}}decodeBorrow(){let t="",e="0",n,o=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;[t]=s.typeArguments;let c=s.arguments[1];c.$kind==="Input"&&(e=this.getPureInputU64(c.Input));let d=s.arguments[3];if(d.$kind==="Input"){let l=this.getPureAddresses(d.Input);l.length===1&&([n]=l)}}else if(this.getMoveCallCommand("high_borrow")){let s=this.getMoveCallCommand("high_borrow").MoveCall;[t]=s.typeArguments;let c=s.arguments[4];c.$kind==="Input"&&(e=this.getPureInputU64(c.Input));let d=s.arguments[5];if(d.$kind==="Input"){let l=this.getPureAddresses(d.Input);l.length===1&&([n]=l)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let s=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[t]=s.typeArguments;let c=s.arguments[5];c.$kind==="Input"&&(e=this.getPureInputU64(c.Input));let d=s.arguments[6];if(d.$kind==="Input"){let l=this.getPureAddresses(d.Input);l.length===1&&([n]=l)}}return{txType:U.Other,type:"borrow",intentionData:{collateralType:t,collateralAmount:r,borrowAmount:e,insertionPlace:n,strapId:o}}}decodeRepay(){let t="",e="0",n="0",r,i=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[t]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[t]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let s=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[t]=s.typeArguments;let c=s.arguments[4];c.$kind==="Input"&&(n=this.getPureInputU64(c.Input));let d=s.arguments[5];if(d.$kind==="Input"){let u=this.getPureAddresses(d.Input);u.length===1&&([r]=u)}let l=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];l.$kind==="Input"&&(e=this.getPureInputU64(l.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let s=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[t]=s.typeArguments;let c=s.arguments[5];c.$kind==="Input"&&(n=this.getPureInputU64(c.Input));let d=s.arguments[6];if(d.$kind==="Input"){let u=this.getPureAddresses(d.Input);u.length===1&&([r]=u)}let l=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];l.$kind==="Input"&&(e=this.getPureInputU64(l.Input))}return{txType:U.Other,type:"repay",intentionData:{collateralType:t,repayAmount:e,withdrawAmount:n,isSurplus:!1,insertionPlace:r,strapId:i}}}decodeWithdraw(){let t="",e="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let r=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[t]=r.typeArguments;let i=r.arguments[4];i.$kind==="Input"&&(e=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;[t]=r.typeArguments;let i=r.arguments[3];i.$kind==="Input"&&(e=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:U.Other,type:"withdraw",intentionData:{collateralType:t,withdrawAmount:e,insertionPlace:n,strapId:o}}}decodeClose(){let t="",e=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([t]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:U.Other,type:"close",intentionData:{collateralType:t,strapId:e}}}decodeSBUCKDeposit(){let e=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",e,n,i),{txType:U.Other,type:"sbuck-deposit",intentionData:{coinType:e,amount:n,isStake:i}}}decodeSBUCKUnstake(){let t="0",e=this.isSBUCKStakeTransaction();if(e){let c=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let s=0;s<o.length;s++){let c=o[s];n.push("")}else{let s=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let c=0;c<s.length;c++){let l=s[c].MoveCall.arguments[2];if(l.$kind==="Input"){let{objectId:u}=this.inputs[l.Input].UnresolvedObject;n.push(u)}}}let r=this.isSBUCKWithdrawTransaction(),i={stakeProofs:n,amount:t,isStake:e,toBuck:r};return console.log("Decoder.decodeSBUCKUnstake",i),{txType:U.Other,type:"sbuck-unstake",intentionData:i}}decodeSBUCKWithdraw(){let t="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(t=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",t),{txType:U.Other,type:"sbuck-withdraw",intentionData:{amount:t}}}decodeSBUCKClaim(){let t=[],e=this.getMoveCallModuleCommands("fountain_core","claim");for(let n=0;n<e.length;n++){let r=e[n].MoveCall.arguments[2];if(r.$kind==="Input"){let{objectId:i}=this.inputs[r.Input].UnresolvedObject;t.push(i)}}return console.log("Decoder.decodeSBUCKClaim",t),{txType:U.Other,type:"sbuck-claim",intentionData:{stakeProofs:t}}}decodeTankDeposit(){let t="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];n.$kind==="Input"&&(t=this.getPureInputU64(n.Input));let r=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",r,t),{txType:U.Other,type:"tank-deposit",intentionData:{coinType:r,amount:t}}}decodeTankWithdraw(){let t=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,e=t.typeArguments[0],n="0",o=t.arguments[5];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),console.log("Decoder.decodeTankWithdraw",e,n),{txType:U.Other,type:"tank-withdraw",intentionData:{coinType:e,amount:n}}}decodeTankClaim(){let e=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",e),{txType:U.Other,type:"tank-claim",intentionData:{coinType:e}}}decodeLockedClaim(){let t="",e=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let r=0;r<n.length;r++)[t]=n[r].MoveCall.typeArguments,e++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let r=0;r<o.length;r++)[t]=o[r].MoveCall.typeArguments,e++;return console.log("Decoder.decodeLockedClaim",t,e),{txType:U.Other,type:"lock-claim",intentionData:{coinType:t,proofCount:e}}}getCoinInput(t){if(this.inputs[t].$kind!=="Object")throw new Error("not Object argument")}getStrapId(){let t;if(this.isStrapNewTransaction()?t="new":this.isLstUnlockTransaction()&&(t="locked"),!t){let e=this.getMoveCallModuleCommand("fountain","unstake");if(e){let n=e.MoveCall.arguments[2];n.$kind==="Input"&&(t=this.inputs[n.Input].UnresolvedObject.objectId)}}return t}getPureInputU64(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return gr.U64.fromBase64(e.Pure.bytes)}getPureAddresses(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return gr.vector(gr.Address).fromBase64(e.Pure.bytes)}};import{TransactionType as tl}from"@msafe/sui3-utils";import{Transaction as Xc}from"@mysten/sui/transactions";import{buildPsmTx as Zc}from"bucket-protocol-sdk";import{BucketClient as Yc}from"bucket-protocol-sdk";var P=(a,t)=>{let e=a==="sui:mainnet"?"mainnet":"testnet";return new Yc(e,t.address)};var mi=async(a,t,e)=>{let{coinType:n,amount:o,buckToCoin:r}=a,i=new Xc,s=P(e,t);return await Zc(s,i,n,o,r,t.address),i};var je=class a extends f{constructor(e){super(e);this.data=e}txType=tl.Other;txSubType="psm";async build(e){let{account:n,network:o}=e;return await mi(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as rl}from"@msafe/sui3-utils";import{Transaction as We}from"@mysten/sui/transactions";import{buildBorrowTx as el,buildCloseTx as nl,buildRepayTx as ol,buildWithdrawTx as al}from"bucket-protocol-sdk";var fi=async(a,t,e)=>{let{collateralType:n,collateralAmount:o,borrowAmount:r,insertionPlace:i,strapId:s}=a,c=new We,d=P(e,t);return await el(d,c,n,o,r,t.address,i,s),c},bi=async(a,t,e)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:r,strapId:i}=a,s=new We,c=P(e,t);return await al(c,s,n,o,t.address,r,i),s},gi=async(a,t,e)=>{let{collateralType:n,repayAmount:o,withdrawAmount:r,isSurplus:i,insertionPlace:s,strapId:c}=a,d=new We,l=P(e,t);return await ol(l,d,n,o,r,t.address,i,s,c),d},hi=async(a,t,e)=>{let{collateralType:n,recipient:o,strapId:r}=a,i=new We,s=P(e,t);return await nl(s,i,n,o,r),i};var Le=class a extends f{constructor(e){super(e);this.data=e}txType=rl.Other;txSubType="borrow";async build(e){let{account:n,network:o}=e;return await fi(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as il}from"@msafe/sui3-utils";var Ue=class a extends f{constructor(e){super(e);this.data=e}txType=il.Other;txSubType="repay";async build(e){let{account:n,network:o}=e;return await gi(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as sl}from"@msafe/sui3-utils";var Fe=class a extends f{constructor(e){super(e);this.data=e}txType=sl.Other;txSubType="withdraw";async build(e){let{account:n,network:o}=e;return await bi(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as cl}from"@msafe/sui3-utils";var qe=class a extends f{constructor(e){super(e);this.data=e}txType=cl.Other;txSubType="close";async build(e){let{account:n,network:o}=e;return await hi(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Ge}from"@msafe/sui3-utils";import{Transaction as $e}from"@mysten/sui/transactions";import{buildSBUCKClaimTx as ll,buildSBUCKDepositTx as dl,buildSBUCKUnstakeTx as ul,buildSBUCKWithdrawTx as pl}from"bucket-protocol-sdk";var yi=async(a,t,e)=>{let{coinType:n,amount:o,isStake:r}=a,i=new $e,s=P(e,t);return await dl(s,i,n,o,t.address,r),i},Si=async(a,t,e)=>{let{stakeProofs:n,amount:o,isStake:r,toBuck:i}=a,s=new $e,c=P(e,t);return await ul(c,s,n,o,t.address,r,i),s},wi=async(a,t,e)=>{let{amount:n}=a,o=new $e,r=P(e,t);return await pl(r,o,n,t.address),o},Ti=async(a,t,e)=>{let{stakeProofs:n}=a,o=new $e,r=P(e,t);return await ll(r,o,n,t.address),o};var Ke=class a extends f{constructor(e){super(e);this.data=e}txType=Ge.Other;txSubType="sbuck-deposit";async build(e){let{account:n,network:o}=e;return await yi(this.data,n,o)}static fromData(e){return new a(e)}},Ve=class a extends f{constructor(e){super(e);this.data=e}txType=Ge.Other;txSubType="sbuck-unstake";async build(e){let{account:n,network:o}=e;return await Si(this.data,n,o)}static fromData(e){return new a(e)}},Qe=class a extends f{constructor(e){super(e);this.data=e}txType=Ge.Other;txSubType="sbuck-withdraw";async build(e){let{account:n,network:o}=e;return await wi(this.data,n,o)}static fromData(e){return new a(e)}},He=class a extends f{constructor(e){super(e);this.data=e}txType=Ge.Other;txSubType="sbuck-claim";async build(e){let{account:n,network:o}=e;return await Ti(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Sr}from"@msafe/sui3-utils";import{Transaction as yr}from"@mysten/sui/transactions";import{buildTankClaimTx as ml,buildTankDepositTx as fl,buildTankWithdrawTx as bl}from"bucket-protocol-sdk";var Ci=async(a,t,e)=>{let{coinType:n,amount:o}=a,r=new yr,i=P(e,t);return await fl(i,r,n,o,t.address),r},Ii=async(a,t,e)=>{let{coinType:n,amount:o}=a,r=new yr,i=P(e,t);return await bl(i,r,n,o,t.address),r},ki=async(a,t,e)=>{let{coinType:n}=a,o=new yr,r=P(e,t);return await ml(r,o,n,t.address),o};import{Transaction as gl}from"@mysten/sui/transactions";import{buildLockedClaimTx as hl}from"bucket-protocol-sdk";var Di=async(a,t,e)=>{let{coinType:n,proofCount:o}=a,r=new gl,i=P(e,t);return await hl(i,r,n,o,t.address),r};var ze=class a extends f{constructor(e){super(e);this.data=e}txType=Sr.Other;txSubType="tank-deposit";async build(e){let{account:n,network:o}=e;return await Ci(this.data,n,o)}static fromData(e){return new a(e)}},Je=class a extends f{constructor(e){super(e);this.data=e}txType=Sr.Other;txSubType="tank-withdraw";async build(e){let{account:n,network:o}=e;return await Ii(this.data,n,o)}static fromData(e){return new a(e)}},Ye=class a extends f{constructor(e){super(e);this.data=e}txType=Sr.Other;txSubType="tank-claim";async build(e){let{account:n,network:o}=e;return await ki(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as yl}from"@msafe/sui3-utils";var Xe=class a extends f{constructor(e){super(e);this.data=e}txType=yl.Other;txSubType="lock-claim";async build(e){let{account:n,network:o}=e;return await Di(this.data,n,o)}static fromData(e){return new a(e)}};var Ze=class{application="bucket";supportSDK="@mysten/sui";async deserialize(t){console.log("Bucket helper deserialize input: ",t);let{transaction:e}=t,o=new Ne(e).decode();return{txType:Sl.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"psm":r=je.fromData(t.intentionData);break;case"borrow":r=Le.fromData(t.intentionData);break;case"withdraw":r=Fe.fromData(t.intentionData);break;case"repay":r=Ue.fromData(t.intentionData);break;case"close":r=qe.fromData(t.intentionData);break;case"tank-deposit":r=ze.fromData(t.intentionData);break;case"tank-withdraw":r=Je.fromData(t.intentionData);break;case"tank-claim":r=Ye.fromData(t.intentionData);break;case"sbuck-deposit":r=Ke.fromData(t.intentionData);break;case"sbuck-unstake":r=Ve.fromData(t.intentionData);break;case"sbuck-withdraw":r=Qe.fromData(t.intentionData);break;case"sbuck-claim":r=He.fromData(t.intentionData);break;case"lock-claim":r=Xe.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as od}from"@msafe/sui3-utils";import{TransactionType as Rl}from"@msafe/sui3-utils";import{AggregatorClient as wl,Env as xi}from"@cetusprotocol/aggregator-sdk";import{CetusPeripherySDK as Tl}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as Cl}from"@cetusprotocol/cetus-sui-clmm-sdk";import{CetusXcetusSDK as Il}from"@cetusprotocol/cetus-xcetus-sdk";import kl from"@cetusprotocol/vaults-sdk";import{SuiClient as Dl,getFullnodeUrl as vi}from"@mysten/sui/client";var xl={fullRpcUrl:vi("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"},vl={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:""}}},Al={fullRpcUrl:vi("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"}},It=(a,t)=>{let e=xl,n=new Cl(e);return n.senderAddress=t.address,n},J=(a,t)=>{let e=It(a,t),n=vl;return new Tl(n,e)},Ol="https://api-sui.cetus.zone/router_v2/find_routes",Ai=(a,t)=>{let e=new Dl({url:"https://fullnode.mainnet.sui.io/"});return new wl(Ol,t.address,e,xi.Mainnet)},Pl={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:xi.Mainnet,providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"]}},wr=(a,t)=>{let e=new kl(Pl);return e.senderAddress=t.address,e},Pt=(a,t)=>{let e=new Il(Al);return e.senderAddress=t.address,e};var Oi=async(a,t,e)=>await It(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Pi=async(a,t,e)=>await It(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Ri=async(a,t,e)=>await It(e,t).Position.closePositionTransactionPayload(a),_i=async(a,t,e)=>await It(e,t).Position.removeLiquidityTransactionPayload(a),Bi=async(a,t,e)=>await It(e,t).Rewarder.collectRewarderTransactionPayload(a);var tn=class a extends f{constructor(e){super(e);this.data=e}txType=Rl.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Oi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as _l}from"@msafe/sui3-utils";var en=class a extends f{constructor(e){super(e);this.data=e}txType=_l.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Bi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Bl}from"@msafe/sui3-utils";var nn=class a extends f{constructor(e){super(e);this.data=e}txType=Bl.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await _i(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Ml}from"@msafe/sui3-utils";var Mi=async(a,t,e)=>await J(e,t).Farms.openPositionAddLiquidityStakePaylod(a),Ei=async(a,t,e)=>await J(e,t).Farms.addLiquidityFixCoinPayload(a),Ni=async(a,t,e)=>await J(e,t).Farms.removeLiquidityPayload(a),ji=async(a,t,e)=>await J(e,t).Farms.removeLiquidityPayload(a),Wi=async(a,t,e)=>await J(e,t).Farms.claimFeeAndClmmReward(a),Li=async(a,t,e)=>await J(e,t).Farms.harvestPayload(a),Ui=async(a,t,e)=>{let n=J(e,t),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},Fi=async(a,t,e)=>await J(e,t).Farms.depositPayload(a),qi=async(a,t,e)=>await J(e,t).Farms.withdrawPayload(a);var on=class a extends f{constructor(e){super(e);this.data=e}txType=Ml.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Mi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as El}from"@msafe/sui3-utils";var an=class a extends f{constructor(e){super(e);this.data=e}txType=El.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ui(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Nl}from"@msafe/sui3-utils";var rn=class a extends f{constructor(e){super(e);this.data=e}txType=Nl.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Wi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as jl}from"@msafe/sui3-utils";var sn=class a extends f{constructor(e){super(e);this.data=e}txType=jl.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ni(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Wl}from"@msafe/sui3-utils";var cn=class a extends f{constructor(e){super(e);this.data=e}txType=Wl.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Li(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Ll}from"@msafe/sui3-utils";var ln=class a extends f{constructor(e){super(e);this.data=e}txType=Ll.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ei(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Ul}from"@msafe/sui3-utils";var dn=class a extends f{constructor(e){super(e);this.data=e}txType=Ul.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ji(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Fl}from"@msafe/sui3-utils";var un=class a extends f{constructor(e){super(e);this.data=e}txType=Fl.Other;txSubType="FarmingStake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Fi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ql}from"@msafe/sui3-utils";var pn=class a extends f{constructor(e){super(e);this.data=e}txType=ql.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await qi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as $l}from"@msafe/sui3-utils";var mn=class a extends f{constructor(e){super(e);this.data=e}txType=$l.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Pi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Kl}from"@msafe/sui3-utils";var fn=class a extends f{constructor(e){super(e);this.data=e}txType=Kl.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ri(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Hl}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as Vl}from"@cetusprotocol/aggregator-sdk";import{Transaction as Ql}from"@mysten/sui/transactions";var $i=async(a,t,e)=>{let n=Ai(e,t),o=new Ql;return await n.fastRouterSwap({...a,routers:Vl(a.routers),txb:o}),o};var bn=class a extends f{constructor(e){super(e);this.data=e}txType=Hl.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await $i(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Gl}from"@msafe/sui3-utils";var Ki=async(a,t,e)=>await wr(e,t).Vaults.deposit(a),Vi=async(a,t,e)=>await wr(e,t).Vaults.withdraw(a);var gn=class a extends f{constructor(e){super(e);this.data=e}txType=Gl.Other;txSubType="AddVaultsPosition";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ki(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as zl}from"@msafe/sui3-utils";var hn=class a extends f{constructor(e){super(e);this.data=e}txType=zl.Other;txSubType="RemoveVaultsPosition";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Vi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Yl}from"@msafe/sui3-utils";import{Transaction as Jl}from"@mysten/sui/transactions";var Qi={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Hi=async(a,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:o,periods:r,CLOCK_ADDRESS:i}=a,s=new Jl;return r.forEach(c=>{s.moveCall({target:`${Qi.published_at}::router::redeem`,typeArguments:[Qi.cetus_coin_type],arguments:[s.object(n),s.object(o),s.pure(c),s.object(i)]})}),s};var yn=class a extends f{constructor(e){super(e);this.data=e}txType=Yl.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Hi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Xl}from"@msafe/sui3-utils";var Gi=async(a,t,e)=>await Pt(e,t).XCetusModule.convertPayload(a),zi=async(a,t,e)=>await Pt(e,t).XCetusModule.redeemLockPayload(a),Ji=async(a,t,e)=>await Pt(e,t).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),Yi=async(a,t,e)=>await Pt(e,t).XCetusModule.cancelRedeemPayload(a),Xi=async(a,t,e)=>await Pt(e,t).XCetusModule.redeemPayload(a);var Sn=class a extends f{constructor(e){super(e);this.data=e}txType=Xl.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Yi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Zl}from"@msafe/sui3-utils";var wn=class a extends f{constructor(e){super(e);this.data=e}txType=Zl.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ji(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as td}from"@msafe/sui3-utils";var Tn=class a extends f{constructor(e){super(e);this.data=e}txType=td.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Gi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as ed}from"@msafe/sui3-utils";var Cn=class a extends f{constructor(e){super(e);this.data=e}txType=ed.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Xi(r,n,o)}static fromData(e){return new a(e)}};import{TransactionType as nd}from"@msafe/sui3-utils";var In=class a extends f{constructor(e){super(e);this.data=e}txType=nd.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await zi(r,n,o)}static fromData(e){return new a(e)}};var kn=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:od.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=tn.fromData(t.intentionData);break;case"IncreaseLiquidity":r=mn.fromData(t.intentionData);break;case"DecreaseLiquidity":r=nn.fromData(t.intentionData);break;case"RemoveLiquidity":r=fn.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=en.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=on.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=ln.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=sn.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=dn.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=rn.fromData(t.intentionData);break;case"FarmingHarvest":r=cn.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=an.fromData(t.intentionData);break;case"FarmingStake":r=un.fromData(t.intentionData);break;case"FarmingUnstake":r=pn.fromData(t.intentionData);break;case"xCETUSConvert":r=Tn.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=In.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=wn.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=Sn.fromData(t.intentionData);break;case"xCETUSRedeem":r=Cn.fromData(t.intentionData);break;case"VestingRedeem":r=yn.fromData(t.intentionData);break;case"AggregatorSwap":r=bn.fromData(t.intentionData);break;case"AddVaultsPosition":r=gn.fromData(t.intentionData);break;case"RemoveVaultsPosition":r=hn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as eu}from"@msafe/sui3-utils";import ad from"sort-keys-recursive";var h=class{constructor(t){this.data=t}serialize(){return JSON.stringify(ad(this.data))}};import{getFullnodeUrl as Dn}from"@mysten/sui.js/client";var Tr={};ui(Tr,{contractId:()=>sd,default:()=>pd,feeObjId:()=>dd,roleObjId:()=>cd,status:()=>id,transaction:()=>rd,upgradeCapObjId:()=>ud,vaultObjId:()=>ld});var rd="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",id="success",sd="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",cd="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",ld="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",dd="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",ud="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",pd={transaction:rd,status:id,contractId:sd,roleObjId:cd,vaultObjId:ld,feeObjId:dd,upgradeCapObjId:ud};var Cr={};ui(Cr,{contractId:()=>bd,default:()=>wd,feeObjId:()=>yd,roleObjId:()=>gd,status:()=>fd,transaction:()=>md,upgradeCapObjId:()=>Sd,vaultObjId:()=>hd});var md="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",fd="success",bd="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",gd="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",hd="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",yd="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Sd="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",wd={transaction:md,status:fd,contractId:bd,roleObjId:gd,vaultObjId:hd,feeObjId:yd,upgradeCapObjId:Sd};var Td=Dn("testnet"),Cd=Dn("testnet"),Id=Dn("mainnet"),kd=Dn("mainnet"),Dd="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",xd="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",vd="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Ad="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Zi=Tr,ts=Cr,Od=new Map([["dev",{env:"dev",rpc:{url:Td},backend:{url:Dd},contract:Zi}],["stg",{env:"stg",rpc:{url:Cd},backend:{url:xd},contract:Zi}],["prev",{env:"prev",rpc:{url:Id},backend:{url:vd},contract:ts}],["prod",{env:"prod",rpc:{url:kd},backend:{url:Ad},contract:ts}]]);function es(a,t){let e=Od.get(a);if(!e)throw new Error(`Env not supported: ${a}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as Rd}from"@mysten/sui.js/client";var I=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:o,context:r}=n;o?super(`[MPay] ${e}: ${o}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var xn=class extends I{constructor(){super(11,"Backend is not specified")}};var vn=class extends I{constructor(){super(1,"Wallet not connected")}};import _t,{AxiosError as Pd}from"axios";var Rt=class extends I{constructor(t,e){super(10,t,{context:e})}};var An=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Pd)throw new Rt(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new Rt(t.data.code)}throw new Rt(t.status.toString())}async getIncomingStreams(t,e){let n=await _t.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await _t.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await _t.post(`${this.apiURL}/stream-events`,t),n=a.parseResponseData(e);return n.data.forEach(o=>{let r=o;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await _t.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await _t.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await _t.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(n)}};var Bt=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new Rd({url:t.rpc.url}),t.backend&&(this._backend=new An(t.backend.url))}static new(t,e){let n=es(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new xn;return this._backend}set backend(t){this._backend=t}connectWallet(t){this.signer=t}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new vn;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Xd,normalizeStructTag as Zd,normalizeSuiAddress as Ds}from"@mysten/sui.js/utils";import{TransactionBlock as Mn}from"@mysten/sui.js/transactions";import{TransactionBlock as ds}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as us,normalizeStructTag as Ed}from"@mysten/sui.js/utils";var Ir=50n,On=10000n,ns=25n,kr=100000000n;var Y=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Jt=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ct=class a{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);let o=i=>new a(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield o(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return o(r)}})}moveArg(){return this.result}};import{Buffer as os}from"buffer";import{normalizeSuiAddress as _d}from"@mysten/sui.js/utils";var Yt=class extends I{constructor(t,e){super(3,t,{context:e})}};var Pn=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,o]=this.getValue(t,e);if(o!=="address")throw new Yt("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return _d(os.from(n).toString("hex"))}getU64(t=0,e=0){let[n,o]=this.getValue(t,e);if(o!=="u64")throw new Yt("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return os.from(n).readBigInt64LE()}};import{bcs as rs}from"@mysten/sui.js/bcs";var x=class extends I{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var is={groupId:"string",name:"string"},Bd=64;function ss(a){return cs(a),rs.ser(is,a).toString("base64")}function Xt(a){let t=rs.de(is,a,"base64");return cs(t),t}function cs(a){if(!as(a.name))throw new x("Invalid metadata: Name contains unknown character");if(!as(a.groupId))throw new x("Invalid metadata: Group ID contains unknown character");if(a.name.length>Bd)throw new x("Invalid metadata: Name exceed max length 64")}function as(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as Rn}from"@mysten/sui.js/utils";function _n(a,t){return Rn(a)===Rn(t)}function lt(a,t){return Rn(a)===Rn(t)}var Bn="txn.gas";import{nanoid as Md}from"nanoid";function ls(){return Md()}var kt=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:ss({name:t.name,groupId:ls()}),coinType:Ed(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new ds,n=this.calculateFeesInternal(t),o=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(o),i=await this.addMergeCoins(e,r[0]),s;o.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let d=t.recipients[c],l=this.amountForRecipient(d,t.numberEpoch),u=this.getStreamFeeLocal(l),[p]=e.splitCoins(i,[e.pure(l+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new ct(p),flatFeeCoin:new ct(m),metadata:t.metadata,recipient:d.address,timeStart:t.startTime,cliff:d.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:Ir,denominator:On},claimFeePercent:{numerator:ns,denominator:On},flatFeePerStream:kr}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(o=>t.object(o))),n=t.object(e.primaryCoin)):e.primaryCoin===Bn?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return _n(n,us)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:us,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((o,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:o.totalAmount+i,streamFeeAmount:o.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(t.recipients.length)*this.flatSuiFee,...e}}amountForRecipient(t,e){return BigInt(t.amountPerEpoch)*BigInt(e)+BigInt(t.cliffAmount)}get flatSuiFee(){return kr}getStreamFeeLocal(t){return t*Ir/On}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new ds,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Pn(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as ms}from"@mysten/sui.js/transactions";var ps="0x0000000000000000000000000000000000000000000000000000000000000006";var Mt=class{constructor(t,e,n){this.moduleName=t;this.config=e;this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(ms.MoveCall({target:n,arguments:e.arguments.map(o=>o instanceof Jt?o.moveArgs(t):o instanceof Y?o.moveArg(t):o instanceof ct?o.moveArg():t.pure(o)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],o=[]){t.add(ms.MoveCall({target:e,arguments:n.map(r=>r instanceof Jt?r.moveArgs(t):r instanceof Y?r.moveArg(t):r instanceof ct?r.moveArg():t.pure(r)),typeArguments:o}))}makeObject(t){return typeof t=="string"?new Y(t):t}vaultObject(){return new Y(this.config.vaultObjId)}roleObject(){return new Y(this.config.roleObjId)}feeObject(){return new Y(this.config.feeObjId)}clockObject(){return new Y(ps)}};var Et=class a extends Mt{constructor(e,n){super(a.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[o,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,r,n],typeArgs:[]})}setClaimFee(e,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[o,r,n],typeArgs:[]})}streamingFee(e,n){let o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var X=class a extends Mt{constructor(e,n){super(a.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,n){let o=this.feeObject(),r=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:a.MethodName.create_stream,arguments:[o,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let o=this.makeObject(n.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStream(e,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let o=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,r,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var Nt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Et(e,t),this.streamContract=new X(e,t)}feeContract;streamContract;async createStreams(t){let e=kt.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new kt(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let o=new Mn;return this.streamContract.setAutoClaim(o,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Mn;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Mn;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Mn;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};import{normalizeStructTag as Dr,SUI_TYPE_ARG as Nd}from"@mysten/sui.js/utils";import{Duration as fs}from"luxon";var En=class extends I{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var jd=1e3,Nn=class{constructor(t){this.globals=t;this.coinMetaHelper=new xr(t.suiClient),this.createStreamHelper=new Nt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new En(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new x("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,o=(t.totalAmount-n)/t.steps,i={realTotalAmount:o*t.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new x("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new x("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(fs.fromMillis(Number(e*t.steps))),o={timeStart:t.timeStart,timeEnd:n,interval:fs.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(o),o}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),o=await this.getCoinMeta(e);return{...n,coinType:Dr(n.coinType),coinMeta:o}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(o=>this.getCoinMeta(o.coinType)));return e.map((o,r)=>({...o,coinType:Dr(o.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new x("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new x("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<jd)throw new x("Interval shall be at least 1 second","interval",t.interval)}},xr=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Dr(t||Nd);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};import{normalizeStructTag as hs,normalizeSuiAddress as qn}from"@mysten/sui.js/utils";import{DateTime as ys}from"luxon";import{TransactionBlock as Un}from"@mysten/sui.js/transactions";import{normalizeStructTag as gs,parseStructTag as Ud}from"@mysten/sui.js/utils";import{DateTime as Fd}from"luxon";var jn=class extends I{constructor(){super(7,"Connected wallet is not creator")}};var Zt=class extends I{constructor(){super(8,"Connected wallet is not recipient")}};var te=class extends I{constructor(t,e){super(6,t,{context:e})}};var A=class extends I{constructor(t,e={}){super(0,t,e)}};var Wn=class extends I{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Wd,Duration as Ld}from"luxon";var bs=(1n<<64n)-1n,Ln=1e3;function vr(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ln);return Wd.fromMillis(e*Ln)}function Ar(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/Ln);return Ld.fromMillis(e*Ln)}var dt=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new X(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await a.fetchStreamData(t,e);return new a(t,e,n)}static fromObjectData(t,e,n){let o=a.parseRawStreamData(e,n);return new a(t,e,o)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new A("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new jn;let t=new Un;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Zt;let t=new Un;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Zt;let e=new Un;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Un;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return gs(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 Ar(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return Xt(t).groupId}get name(){let{metadata:t}=this.rawData.config;return Xt(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return vr(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Ar(e)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:vr((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let t=this.rawData.status.status;return t===16?"CANCELED":t===17?"SETTLED":t===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===bs?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Fd.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let n=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let n=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new Wn(t):new te(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new te("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=Ud(n.type),r=gs(o[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};var jt=class extends I{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Pr(a){let t=[];for(;await a.hasNext();){let e=await a.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Or=class{constructor(t){this.requester=t;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},Wt=class{constructor(t){this.requester=t;this.pager=new Or(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var qd=25;async function _r(a,t,e){let n=new ee(t),o=new ne(a,n,e);return await Pr(o)}var ee=class{constructor(t){this.ids=t;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},ne=class extends Wt{constructor(e,n,o){super(new Rr(e,n,o));this.suiClient=e;this.idIter=n;this.options=o}},Rr=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||qd,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=e.filter(r=>o?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Fn=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new jt("stream size 0");let n=e.map(r=>r.groupId);if(new Set(n).size!==1)throw new x("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await _r(t.suiClient,e);return n.forEach(o=>{if(!o)throw new A("stream group object data undefined")}),a.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let o=await a.parseGroupStreams(t,e,n);return new a(t,o)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],o=!0;return e.forEach(r=>{$d(n,r)||(o=!1)}),o}async refresh(){let t=await _r(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,n)=>{e.refreshWithData(t[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(t=>t.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((t,e)=>t+e.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((t,e)=>t+e.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((t,e)=>e.nextReleaseAmount===null?t:t+e.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((t,e)=>t+e.totalAmount,0n),streamed:this.streams.reduce((t,e)=>t+e.streamedAmount,0n),claimed:this.streams.reduce((t,e)=>t+e.claimedAmount,0n),claimable:this.streams.reduce((t,e)=>t+e.claimable,0n),canceled:this.streams.reduce((t,e)=>t+e.canceledAmount,0n)}}async historyEvents(t){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:t})}static async parseGroupStreams(t,e,n){let o=n.map((r,i)=>dt.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(o.map(r=>r.groupId)).size!==1)throw new jt("Not same group ID");if(!this.checkStreamGroup(o))throw new jt("Not same stream settings");return o}};function $d(a,t){return a.name===t.name&&a.groupId===t.groupId&&a.creator===t.creator&&a.start.toMillis()===t.start.toMillis()&&a.interval.toMillis()===t.interval.toMillis()&&a.steps===t.steps&&a.cancelable===t.cancelable}var oe=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await $n.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await $n.newOutgoing(t);return new a(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},$n=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await Kn.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await Kn.newOutgoingQuery(t);return new a(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new A("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new A("No more results");return t}},Kn=class a{constructor(t,e,n,o){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=o;this.current=0;let r=new ee(n.flat().map(i=>i.streamId));this.objectIter=new ne(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=Gd(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>qn(s.recipient)===qn(n)),i=Ss(r);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=zd(t.query),n=await t.globals.walletAddress(),o=await t.globals.backend.getOutgoingStreams(n,e),r=Ss(o);return new a(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Qd(this.globals,t[0].streamId,this.objectIter);return this.current++,ws(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Hd(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,Vd(e,this.query)?e:this.doNextRequest()}throw new A("Stream group with no stream")}};function Ss(a){let t=new Map;return a.forEach(e=>{let n=t.get(e.groupId);n?(n.push(e),t.set(e.groupId,n)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,n)=>ys.fromISO(n[0].createDate).toMillis()-ys.fromISO(e[0].createDate).toMillis())}function ws(a,t){if(t===void 0)return!0;let e=Kd(a,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return e&&n}return e}function Kd(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function Vd(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{ws(n,t)&&(e=!0)}),e}async function Qd(a,t,e){let n=await Ts(e,t);return dt.fromObjectData(a,t,n)}async function Hd(a,t,e){let n=[];for(;n.length<t.length;){let o=await Ts(e,t[n.length]);n.push(o)}return Fn.newFromObjectResponse(a,t,n)}async function Ts(a,t){if(!await a.hasNext())throw new A("object iterator has been consumed");let e=await a.next();if(!e||e.error||e.data===void 0||e.data===null)throw new A("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new A("stream id not aligned");return e}function Gd(a){return{status:Br(a?.status),coinType:Cs(a?.coinType),sender:Is(a?.sender)}}function zd(a){return{status:Br(a?.status),coinType:Cs(a?.coinType),recipient:Is(a?.recipient)}}function Br(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=Br(e);return!t||t===n?n:"all"},void 0):Jd(a)}function Jd(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new x("Unknown stream filtered status")}}function Cs(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>hs(t)):void 0:hs(a)}function Is(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>qn(t)):void 0:qn(a)}var Vn=class extends I{constructor(e,n,o){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:o}});this.coinType=e;this.requestAmount=n;this.gotAmount=o}};var Yd=25;async function ks(a,t,e,n="0x2::sui::SUI",o=Yd){let r=new Mr(a,t,n,o),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new Vn(n,e,i);return s}var Mr=class extends Wt{constructor(e,n,o,r){super(new Er(e,n,o,r));this.suiClient=e;this.owner=n;this.coinType=o;this.reqPageSize=r}},Er=class{constructor(t,e,n,o){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new A("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var Nr=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Qn=class{constructor(t){this.account=t}async address(){return this.account.address}},jr=class{constructor(t,e){this.singleWallet=t;this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(_n(t.coinType,Xd))return{primaryCoin:Bn};if(t.amount<=0)throw new x("Invalid coin request","coinAmount",t.amount);let e=await ks(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new A("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},Hn=class{globals;helper;constructor(t,e){this.globals=Bt.new(t,e),this.helper=new Nn(this.globals)}connectSingleWallet(t){let e=new jr(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Nr(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return dt.new(this.globals,t)}async getIncomingStreams(t,e=10){return oe.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return oe.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(n=>Zd(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(o=>Ds(o))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(o=>Ds(o))}get wallet(){return this.globals.wallet}builder(){return new Nt(this.globals)}};var K=class extends h{application="mpay";getClient(t,e){let n=new Hn(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Qn(e)),n}};var ae=class extends K{constructor(e){super(e);this.data=e}txType=eu.Stream;txSubType="Cancel";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};import{TransactionType as nu}from"@msafe/sui3-utils";var re=class extends K{constructor(e){super(e);this.data=e}txType=nu.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as ou}from"@msafe/sui3-utils";var ie=class extends K{constructor(e){super(e);this.data=e}txType=ou.Stream;txSubType="Claim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};import{TransactionType as au}from"@msafe/sui3-utils";var se=class extends K{constructor(e){super(e);this.data=e}txType=au.Stream;txSubType="CreateStream";async build(e){let{network:n,account:o}=e;return this.getClient(n,o).createStream(this.data)}};import{bcs as xs}from"@mysten/sui.js/bcs";import{normalizeStructTag as ru,normalizeSuiAddress as ce}from"@mysten/sui.js/utils";var Lt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return ce(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return xs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return ce(t.value.Object.ImmOrOwned.objectId)}return ce(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ce(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ce(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return xs.de(e,new Uint8Array(n))}typeArg(t){return ru(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Gn=class{constructor(t,e){this.globals=t;this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let e=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&<(e.target,this.contract.createStreamTarget));if(t.length===0)throw new A("No create stream transactions");return t.map(e=>new Lt(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:o}=Xt(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),d=t.decodeInputU64(9),l=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:o,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:d,amountPerEpoch:l,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new x("Stream group not have common info");let n=t.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:n,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new X(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Et(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new kt(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}};var zn=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new X(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(e=>e.kind==="MoveCall"&<(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&<(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&<(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&<(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&<(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Gn(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:t}}decodeClaimByProxyTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:t}}decodeCancelStreamTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:t}}get helper(){let t=this.transactions[0];return new Lt(t,this.txb)}};import{TransactionType as iu}from"@msafe/sui3-utils";var le=class extends K{constructor(e){super(e);this.data=e}txType=iu.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Jn=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,o=Bt.new(e==="sui:mainnet"?"prod":"dev"),i=new zn(o,n).decode(),s;switch(i.type){case"CreateStream":s=new se(i.info);break;case"SetAutoClaim":s=new le({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new ie({streamId:i.streamId});break;case"ClaimByProxy":s=new re({streamId:i.streamId});break;case"Cancel":s=new ae({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:s.txType,txSubType:s.txSubType,intentionData:s.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new se(e);break;case"Claim":n=new ie(e);break;case"ClaimByProxy":n=new re(e);break;case"SetAutoClaim":n=new le(e);break;case"Cancel":n=new ae(e);break;default:throw new Error("not implemented")}return n.build({...t})}};import{TransactionDefaultApplication as lu,TransactionSubTypes as vs}from"@msafe/sui3-utils";import{buildCoinTransferTxb as su}from"@msafe/sui3-utils";var Yn=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return su(n,this.data,o.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as cu}from"@msafe/sui3-utils";var Xn=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return cu(n,this.data,o.address)}static fromData(e){return new a(e)}};var Zn=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=lu}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,o;switch(t.txSubType){case vs.assets.coin.send:o=Yn.fromData(t.intentionData);break;case vs.assets.object.send:o=Xn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionType as ku}from"@msafe/sui3-utils";var As=!1,de={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 Wr(){if(!As)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n,pool:o}=a;t&&(de.ProtocolPackage=t),e&&(de.borrowFee=e),n&&(de.borrowFeeAddress=n),o&&(de.pool=o),As=!0}catch(a){console.error(a.message)}}var H=de;import{TransactionType as xt}from"@msafe/sui3-utils";import{bcs as Os}from"@mysten/sui.js/bcs";import{normalizeStructTag as uu,normalizeSuiAddress as ue}from"@mysten/sui.js/utils";var to=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.transactions.find(e=>!!(e.kind==="MoveCall"&&e.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${H.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${H.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let t=`${H.ProtocolPackage}::incentive_v3::entry_deposit`,e=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===t);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))?!1:e.length>1}isEntryClaimAndDepositTransaction(){let t=`${H.ProtocolPackage}::incentive_v3::entry_deposit`,e=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===t);return!!(this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))&&e.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${H.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${H.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${H.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(t){let e=Object.values(H.pool).find(n=>n.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeEntryClaimAndDeposit(){return{txType:xt.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:xt.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5);return{txType:xt.Other,type:"EntryBorrow",intentionData:{amount:e,assetId:t}}}decodeEntryMultiDeposit(){let t=[],e=`${H.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===e){let o=new eo(n,this.txb),r=o.decodeInputU8(3),i=o.decodeInputU64(5);t.push({assetId:r,amount:i})}}),{txType:xt.Other,type:"EntryMultiDeposit",intentionData:{list:t}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5);return{txType:xt.Other,type:"EntryDeposit",intentionData:{amount:e,assetId:t}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6);return{txType:xt.Other,type:"EntryRepay",intentionData:{amount:e,assetId:t}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5);return{txType:xt.Other,type:"EntryWithdraw",intentionData:{amount:e,assetId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(H.ProtocolPackage));return new eo(t,this.txb)}},eo=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return ue(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Os.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return ue(t.value.Object.ImmOrOwned.objectId)}return ue(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ue(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ue(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Os.de(e,new Uint8Array(n))}typeArg(t){return uu(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{depositCoin as pu,withdrawCoin as mu,repayDebt as fu,borrowCoin as bu,claimAllRewardsPTB as gu,claimAllRewardsResupplyPTB as hu}from"navi-sdk";async function Ut(a,t,e,n){return await pu(a,t,e,n),a}async function Ps(a,t,e,n){let[o]=await mu(a,t,e);return a.transferObjects([o],a.pure(n)),a}async function Rs(a,t,e,n){let[o]=await bu(a,t,e);return a.transferObjects([o],a.pure.address(n)),a}async function Lr(a,t,e,n){return await fu(a,t,e,n),a}async function _s(a,t){return await gu(a,t)}async function Bs(a,t){return await hu(a,t)}var no=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{type:n}=this.data;return console.log("claim reward",n),await _s(e.suiClient,e.account.address)}static fromData(e){return new a(e)}};var oo=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{type:n}=this.data;return console.log("claim reward and supply",n),await Bs(e.suiClient,e.account.address)}static fromData(e){return new a(e)}};import{TransactionBlock as Su}from"@mysten/sui.js/transactions";import{pool as yu}from"navi-sdk";function Z(a){return Object.values(yu).find(t=>String(t.assetId)===String(a))}var ao=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{assetId:n,amount:o}=this.data,r=new Su;console.log("build",this.data);let i=Z(n);return await Rs(r,i,o,e.account.address)}static fromData(e){return new a(e)}};import{TransactionBlock as wu}from"@mysten/sui.js/transactions";async function Ft(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var ro=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{assetId:r,amount:i}=this.data,s=new wu;console.log("build",this.data);let c=Z(r);if(r===0){let[p]=s.splitCoins(s.gas,[i]);return await Ut(s,c,p,i)}let d=await Ft(n,o.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let p=1;for(;p<d.data.length;)s.mergeCoins(l,[d.data[p].coinObjectId]),p++}return await Ut(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Tu}from"@mysten/sui.js/transactions";var io=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{assetId:r,amount:i}=this.data,s=new Tu;console.log("build",this.data);let c=Z(r);if(r===0){let[u]=s.splitCoins(s.gas,[i]);return Lr(s,c,u,i)}let d=await Ft(n,o.address,c.type);if(!d.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let l=d.data[0].coinObjectId;if(d.data.length>=2){let u=1;for(;u<d.data.length;)s.mergeCoins(l,[d.data[u].coinObjectId]),u++}return Lr(s,c,s.object(l),i)}static fromData(e){return new a(e)}};import{TransactionBlock as Cu}from"@mysten/sui.js/transactions";var so=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{assetId:n,amount:o}=this.data,r=new Cu;console.log("build",this.data);let i=Z(n);return await Ps(r,i,o,e.account.address)}static fromData(e){return new a(e)}};import{TransactionBlock as Iu}from"@mysten/sui.js/transactions";var co=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{list:r}=this.data,i=new Iu;console.log("build",this.data);for(let s=0;s<r.length;s++){let{assetId:c,amount:d}=r[s],l=Z(c);if(c===0){let[m]=i.splitCoins(i.gas,[d]);await Ut(i,l,m,d);continue}let u=await Ft(n,o.address,l.type);if(!u.data[0])throw new Error(`Insufficient balance for ${l.name} Token`);let p=u.data[0].coinObjectId;if(u.data.length>=2){let m=1;for(;m<u.data.length;)i.mergeCoins(p,[u.data[m].coinObjectId]),m++}await Ut(i,l,i.object(p),d)}return i}static fromData(e){return new a(e)}};var lo=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await Wr();let{transactionBlock:e}=t,o=new to(e).decode();return{txType:ku.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(await Wr(),t.txSubType){case"EntryDeposit":o=ro.fromData(t.intentionData);break;case"EntryBorrow":o=ao.fromData(t.intentionData);break;case"EntryRepay":o=io.fromData(t.intentionData);break;case"EntryWithdraw":o=so.fromData(t.intentionData);break;case"EntryMultiDeposit":o=co.fromData(t.intentionData);break;case"ClaimReward":o=no.fromData(t.intentionData);break;case"EntryClaimAndDeposit":o=oo.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionSubTypes as Du,TransactionType as Ms}from"@msafe/sui3-utils";import{fromHex as xu}from"@mysten/bcs";import{Transaction as vu}from"@mysten/sui/transactions";import Au from"sort-keys-recursive";var Es="msafe-plain-tx",Ns=Du.others.plain,Ur=class a{constructor(t){this.data=t}application=Es;txType=Ms.Other;txSubType=Ns;serialize(){return JSON.stringify(Au(this.data))}async build(t){return vu.from(xu(this.data.content))}static fromData(t){return new a(t)}},uo=class{application;supportSDK="@mysten/sui";constructor(){this.application=Es}async deserialize(t){let{content:e}=t.appContext;return{txType:Ms.Other,txSubType:Ns,intentionData:{content:e}}}async build(t){let{suiClient:e,network:n,account:o}=t;return Ur.fromData(t.intentionData).build({suiClient:e,network:n,account:o})}};import{SuiClient as js}from"@mysten/sui/client";import{Transaction as Eu}from"@mysten/sui/transactions";import{SuiClient as $r}from"@mysten/sui.js/client";import{TransactionBlock as Nu}from"@mysten/sui.js/transactions";import{RequestManager as _u,HTTPTransport as Bu,Client as Mu}from"@open-rpc/client-js";var Ou={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},Fr=class extends Error{},po=class extends Fr{code;type;constructor(t,e){super(t),this.code=e,this.type=Ou[e]??"ServerError"}};function Pu(a){let t=new URL(a);return t.protocol=t.protocol.replace("http","ws"),t.toString()}var Ru={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},mo=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#r=new Set;#o=new Map;constructor(t,e={}){this.endpoint=t,this.options={...Ru,...e},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=Pu(this.endpoint))}async makeRequest(t,e){let n=await this.#i();return new Promise((o,r)=>{this.#n+=1,this.#o.set(this.#n,{resolve:o,reject:r,timeout:setTimeout(()=>{this.#o.delete(this.#n),r(new Error(`Request timeout: ${t}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:t,params:e}))}).then(({error:o,result:r})=>{if(o)throw new po(o.message,o.code);return r})}#i(){return this.#e?this.#e:(this.#e=new Promise(t=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,t(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:e})=>{let n;try{n=JSON.parse(e)}catch(o){console.error(new Error(`Failed to parse RPC message: ${e}`,{cause:o}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:o,timeout:r}=this.#o.get(n.id);clearTimeout(r),o(n)}else if("params"in n){let{params:o}=n;this.#r.forEach(r=>{r.subscriptionId===o.subscription&&o.subscription===r.subscriptionId&&r.onMessage(o.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#r].map(t=>t.subscribe(this)))}async subscribe(t){let e=new qr(t);return this.#r.add(e),await e.subscribe(this),()=>e.unsubscribe(this)}},qr=class{subscriptionId=null;input;subscribed=!1;constructor(t){this.input=t}onMessage(t){this.subscribed&&this.input.onMessage(t)}async unsubscribe(t){let{subscriptionId:e}=this;return this.subscribed=!1,e==null?!1:(this.subscriptionId=null,t.makeRequest(this.input.unsubscribe,[e]))}async subscribe(t){this.subscriptionId=null,this.subscribed=!0;let e=await t.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=e)}};var ut=class{rpcClient;websocketClient;constructor({url:t,websocket:{url:e,...n}={},rpc:o}){let r=new Bu(o?.url??t,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new Mu(new _u([r])),this.websocketClient=new mo(e??t,n)}async request(t){return await this.rpcClient.request(t)}async subscribe(t){let e=await this.websocketClient.subscribe(t);return async()=>!!await e()}};var fo=class a{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new a;for(let n=0;n<t.length;n++){let o=t[n];switch(o.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(o);break;case"@mysten/sui":e.addHelper(o);break;default:throw new Error(`${o.application}: ${o.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new Vr(t))}addHelper(t){this.apps.set(t.application,new Kr(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},Kr=class{constructor(t){this.helper=t}async deserialize(t){let e=new js({transport:new ut({url:t.clientUrl,rpc:{url:t.clientUrl}})}),n=new $r({transport:new ut({url:t.clientUrl,rpc:{url:t.clientUrl}})}),o=await t.transactionBlock.build({client:n}),r=Eu.from(o);return this.helper.deserialize({...t,suiClient:e,transaction:r})}async build(t){let e=new js({transport:new ut({url:t.clientUrl,rpc:{url:t.clientUrl}})}),n=await e.getBalance({owner:t.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let o=await this.helper.build({...t,suiClient:e});o.setSender(t.account.address);let r=await o.build({client:e});return Nu.from(r)}},Vr=class{constructor(t){this.helper=t}async deserialize(t){let e=new $r({transport:new ut({url:t.clientUrl,rpc:{url:t.clientUrl}})});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new $r({transport:new ut({url:t.clientUrl,rpc:{url:t.clientUrl}})}),n=await e.getBalance({owner:t.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...t,suiClient:e})}};import{TransactionType as dp}from"@msafe/sui3-utils";import{TransactionType as O}from"@msafe/sui3-utils";var pt=class{constructor(t,e){this.txb=t;this.scallop=e}scallop;get coreId(){return{protocolPkg:this.scallop.address.get("core.packages.protocol.id"),market:this.scallop.address.get("core.market"),version:this.scallop.address.get("core.version"),coinDecimalsRegistry:this.scallop.address.get("core.coinDecimalsRegistry"),xOracle:this.scallop.address.get("core.oracles.xOracle"),spoolPkg:this.scallop.address.get("spool.id"),borrowIncentivePkg:this.scallop.address.get("borrowIncentive.id"),veScaPkgId:this.scallop.address.get("vesca.id"),scoin:this.scallop.address.get("scoin.id"),referral:this.scallop.address.get("referral.id")}}get transactions(){return this.txb.blockData.transactions}get inputTransaction(){return this.txb.blockData.inputs}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}};var Ws="https://sui.apis.scallop.io";var Ls="675c65cd301dd817ea262e76",bo="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var mt="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",ft="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",et=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd","deep","fud"],go=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd"],bt=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],nt=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc","sfdusd","sdeep","sfud"];var Us=["sui"],gt=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc","fdusd","deep","fud"];var Fs={weth:8,wbtc:8,wusdc:6,usdc:6,wusdt:6,sui:9,wapt:8,wsol:8,sca:9,cetus:9,afsui:9,hasui:9,vsui:9,fud:5,deep:6,fdusd:6,sweth:8,swbtc:8,susdc:6,swusdt:6,swusdc:6,ssui:9,swapt:8,swsol:8,scetus:9,safsui:9,shasui:9,svsui:9,ssca:9,sdeep:6,sfud:5,sfdusd:6,scallop_deep:6,scallop_fud:5,scallop_sca:9,scallop_sui:9};var ho={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},qs={sui:["sui","sca","scallop_sca","scallop_sui"],wusdc:["sui","sca","scallop_sca","scallop_sui"],wusdt:["sui","sca","scallop_sca","scallop_sui"],afsui:["sui","sca","scallop_sca","scallop_sui"],hasui:["sui","sca","scallop_sca","scallop_sui"],vsui:["sui","sca","scallop_sca","scallop_sui"],sca:["sui","sca","scallop_sca","scallop_sui"],weth:["sui","sca","scallop_sca","scallop_sui"],wbtc:["sui","sca","scallop_sca","scallop_sui"],wsol:["sui","sca","scallop_sca","scallop_sui"],usdc:["sui","sca","scallop_sca","scallop_sui"],fud:["sui","sca","scallop_fud","scallop_sui","scallop_sca"],deep:["sui","sca","scallop_deep","scallop_sui","scallop_sca"],fdusd:["sui","sca","scallop_sca","scallop_sui"]},$s={sui:"0x0000000000000000000000000000000000000000000000000000000000000002",weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8",cetus:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",afsui:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",hasui:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",sca:"0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6",usdc:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7",fud:"0x76cb819b01abed502bee8a702b4c2d547532c12f25001c9dea795a5e631c26f1",deep:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270",fdusd:"0xf16e6b723f242ec745dfd7634ad072c42d5c1d9ac9d62a39c381303eaa57693a",scallop_deep:"0xeb7a05a3224837c5e5503575aed0be73c091d1ce5e43aa3c3e716e0ae614608f",scallop_fud:"0xe56d5167f427cbe597da9e8150ef5c337839aaf46891d62468dcf80bdd8e10d1",scallop_sca:"0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e",scallop_sui:"0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b"},F={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Qr={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},Ks={ssui:"0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI",scetus:"0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS",ssca:"0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA",swusdc:"0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC",swusdt:"0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT",sweth:"0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH",safsui:"0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI",shasui:"0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI",svsui:"0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI",swbtc:"0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC",swsol:"0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL",susdc:"0x854950aa624b1df59fe64e630b2ba7c550642e9342267a33061d59fb31582da5::scallop_usdc::SCALLOP_USDC",sfdusd:"0x6711551c1e7652a270d9fbf0eee25d99594c157cde3cb5fbb49035eb59b1b001::scallop_fdusd::SCALLOP_FDUSD",sdeep:"0xeb7a05a3224837c5e5503575aed0be73c091d1ce5e43aa3c3e716e0ae614608f::scallop_deep::SCALLOP_DEEP",sfud:"0xe56d5167f427cbe597da9e8150ef5c337839aaf46891d62468dcf80bdd8e10d1::scallop_fud::SCALLOP_FUD"};import{bcs as Vs}from"@mysten/sui.js/bcs";import{normalizeStructTag as ju,normalizeSuiAddress as pe}from"@mysten/sui.js/utils";var S=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return pe(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}getNestedInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="NestedResult")throw new Error("not input type");return this.txb.blockData.transactions[e.index]}isHaveNestedInput(t){return this.moveCall.arguments[t].kind==="NestedResult"}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Vs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return pe(t.value.Object.ImmOrOwned.objectId)}return pe(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return pe(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return pe(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Vs.de(e,new Uint8Array(n))}typeArg(t){return ju(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{bcs as Wu}from"@mysten/sui.js/bcs";var R=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(S.getPureInputValue(t,"u64"))}).filter(t=>t!==void 0)}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Wu.de(e,new Uint8Array(n))}return t.value}};var yo=class extends pt{decode(){if(this.isMoveAsset())return this.decodeMoveAsset();if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMoveAsset(){return!!this.getMoveCallTransaction("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage")}isMigrateScoinTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`),e=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);return!!t&&!!e}isUnstakeAndWithdrawTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`),e=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);return!!t&&!!e}isStakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`),e=!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return!!t&&!!e}isDepositCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isBorrowWithReferralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isUnstakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return!!t||!!e}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${ft}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);return!!t&&(!!e||!!n)}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new S(e,this.txb))}get helperClaimBorrowV2Reward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(e=>new S(e,this.txb))}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new S(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::redeem_rewards`)).map(e=>new S(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new S(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new S(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new S(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new S(t,this.txb)}get helperBurnScoin(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new S(t,this.txb)}get helperSlippage(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage"));return new S(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new S(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new S(t,this.txb)}get helperDepositCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new S(t,this.txb)}get helperWithdrawCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new S(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new S(t,this.txb)}get helperBorrowWithReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new S(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new S(t,this.txb)}decodeMigrateScoin(){return{txType:O.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let e=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),o=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:O.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:o,veScaKey:t}}}decodeOpenObligation(){return{txType:O.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:O.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:O.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLendingScoin(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperBurnScoin.getNestedInputParam(1),n=new R(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:O.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:O.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:O.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:o,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:O.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:O.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:o,veScaKey:e}}}decodeBorrowWithReferral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),o=this.helperBorrowWithReferral.decodeSharedObjectId(1),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:O.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:o,veScaKey:e}}}decodeRepay(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:O.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),o=new R(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:O.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:r,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);e=new R(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let r=this.helperStake.getNestedInputParam(2);e=new R(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),o=this.scallop.utils.parseCoinNameFromType(n);return{txType:O.Other,type:"StakeSpool",intentionData:{amount:e,marketCoinName:o,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this.scallop.utils.parseCoinNameFromType(n);return{txType:O.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:o,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new R(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:O.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(o=>{let r=o.decodeOwnedObjectId(1),i=o.decodeInputU64(2);t.push({id:r,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);n=new R(o,this.txb).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:O.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeMoveAsset(){let t=[];this.helperUnstakes.forEach(i=>{let s=i.decodeOwnedObjectId(1),c=i.decodeInputU64(2);t.push({id:s,coin:c})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);n=new R(i,this.txb).getAmountInput().reduce((s,c)=>s+c,0)}let o=this.helperSlippage.decodePureArg(1,"u64"),r=this.helperSlippage.decodePureArg(2,"string");return{txType:O.Other,type:"MigrateWusdcToUsdc",intentionData:{amount:n,coinName:e,slippage:o,validSwapAmount:r,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let r=o.decodeOwnedObjectId(2),i=o.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(o=>{let r=o.decodeSharedObjectId(3),i=o.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(o.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(o=>{let r=o.decodeSharedObjectId(2),i=o.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:O.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};import{TransactionType as Gr}from"@msafe/sui3-utils";var So=class extends pt{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(e=>new S(e,this.txb))}get helperBindReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new S(t,this.txb)}decodeCreateReferralLink(){return{txType:Gr.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Gr.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:Gr.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};import{TransactionType as me}from"@msafe/sui3-utils";var wo=class extends pt{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let t=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),e=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!t&&!!e}isRedeemSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new S(t,this.txb)}get helperStakeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new S(t,this.txb)}get helperExtendStakePeriod(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new S(t,this.txb)}get helperRedeemSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new S(t,this.txb)}get helperRenewExpired(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new S(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${ft}::user::unstake`));return new S(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new S(t,this.txb)}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new S(t,this.txb)}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:me.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new R(t,this.txb).getAmountInput().reduce((b,y)=>b+y,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,l=!1,u,p,m=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,u]=m[b].condition,d=!0,l=m[b].isOld);return{txType:me.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:o,isHaveRedeem:r,isObligationLocked:d,isOldBorrowIncentive:l}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,d,l=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:r,isOld:!1}];for(let u=0;u<l.length;u++)l[u].condition.length>1&&([d,c]=l[u].condition,i=!0,s=l[u].isOld);return{txType:me.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:d,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new R(t,this.txb).getAmountInput().reduce((m,b)=>m+b,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,d=!1,l,u,p=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:me.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:l,obligationKey:u,isOldBorrowIncentive:d,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):t=this.helperStakeMoreSca.getNestedInputParam(4);let n=new R(t,this.txb).getAmountInput().reduce((m,b)=>m+b,0),o=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,d=!1,l,u,p=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,l]=p[m].condition,c=!0,d=p[m].isOld);return{txType:me.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:l,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:d}}}};import Lu from"sort-keys-recursive";var g=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(Lu(this.data))}};var To=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrow(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new a(e)}};var Co=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new a(e)}};var Io=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithReferral(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new a(e)}};var ko=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var Do=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new a(e)}};var xo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAndClaim(this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName,this.data.veScaKey)}static fromData(e){return new a(e)}};var vo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new a(e)}};var Ao=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateLendingWusdcToUsdcNative(this.data.coinName,Number(this.data.amount),this.data.slippage,this.data.validSwapAmount,this.data.stakeAccountId)}static fromData(e){return new a(e)}};var Oo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new a(e)}};var Po=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repay(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new a(e)}};var Ro=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repayWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.veScaKey,e.account.address)}static fromData(e){return new a(e)}};var _o=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Bo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Mo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new a(e)}};var Eo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new a(e)}};var No=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new a(e)}};var jo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new a(e)}};var Wo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.bindReferral(this.data.veScaKey)}static fromData(e){return new a(e)}};var Lo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claimRevenuReferral(this.data.veScaKey,this.data.coins)}static fromData(e){return new a(e)}};var Uo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new a(e)}};var Fo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendPeriodAndStakeMoreSca(this.data.amount,this.data.veScaKey,this.data.lockPeriodInDays,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var qo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendStakeScaLockPeriod(this.data.lockPeriodInDays,this.data.veScaKey,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var $o=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.redeemSca(this.data.veScaKey)}static fromData(e){return new a(e)}};var Ko=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.renewExpiredStakeSca(this.data.amount,this.data.lockPeriodInDays,this.data.vescaKey,this.data.isHaveRedeem,this.data.obligation,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new a(e)}};var Vo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stakeSca(this.data.amount,this.data.isObligationLocked,this.data.isOldBorrowIncentive,this.data.obligationId,this.data.obligationKey,this.data.lockPeriodInDays,this.data.veScaKey,e.account.address)}static fromData(e){return new a(e)}};var Qo=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.supplyAndStake(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId,e.account.address)}static fromData(e){return new a(e)}};var Ho=class a extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new a(e)}};var Go=class{id;addresses;constructor(t){let{id:e}=t;this.id=e}getId(){return this.id}getAddresses(){return this.addresses}get(t){if(!this.addresses)throw new Error(`Failed to fetch address ${this.id}`);return t.split(".").reduce((n,o)=>typeof n=="object"?n[o]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${Ws}/addresses/${this.id}`,t);if(e.status===200){let n=await e.json();if("mainnet"in n){this.addresses=n.mainnet;return}throw new Error("Mainnet key is not in address!")}throw new Error(`Failed to fetch address with id ${this.id}`)}};import{TransactionBlock as C}from"@mysten/sui.js/transactions";import wc from"bignumber.js";import{TransactionBlock as Uu}from"@mysten/sui.js/transactions";var zo=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:o,utils:r}=e;this.address=n,this.query=o,this.utils=r,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new Uu(t)}async selectCoin(t,e,n,o=this.params.walletAddress){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,o),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,o=this.params.walletAddress){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,r,o),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[d,l]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:d,leftCoin:l,totalAmount:s}}async selectSCoin(t,e,n,o=this.params.walletAddress){let r=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,r,o),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[d,l]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:d,leftCoin:l,totalAmount:c}}};import{TransactionBlock as Fu}from"@mysten/sui.js/transactions";import Jo from"bignumber.js";var qt=async(a,t)=>{let e=t,n=a.address.get("core.object")||bo,o=[],r=!1,i=null;do{let l=await a.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});o.push(...l.data),l.hasNextPage&&l.nextCursor?(r=!0,i=l.nextCursor):r=!1}while(r);let s=o.map(l=>l?.data?.objectId).filter(l=>l!==void 0),c=await a.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),d=[];for(let l=0;l<c.length;l++){let u=c[l].data.objectId,{content:p}=c[l].data;if(p&&"fields"in p){let m=p.fields,b=String(m.ownership.fields.of),y=await zr(a,b);d.push({id:b,keyId:u,locked:y})}}return d},zr=async(a,t)=>{let e=await a.client.getObject({id:t,options:{showContent:!0}}),n=!1;return e.data&&e?.data?.content?.dataType==="moveObject"&&"lock_key"in e.data.content.fields&&(n=!!e.data.content.fields.lock_key),n},Qs=async(a,t,e)=>{let n=e||[...et],o=t,r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return r.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Jo(c[m]??0).plus(p.balance).toNumber())}}),c},Hs=async(a,t,e)=>{let n=e,o=a.utils.parseCoinType(t),r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return r.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Jo(c).plus(u.balance).toNumber()}}),c},Gs=async(a,t,e)=>{let n=e||[...et].map(l=>a.utils.parseMarketCoinName(l)),o=t,r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:o,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${a.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c={};return r.map(l=>l.data).filter(l=>l!=null).forEach(l=>{let u=l.type;if(l.content&&"fields"in l.content){let p=l.content.fields,m=a.utils.parseCoinNameFromType(u);m&&(c[m]=Jo(c[m]??0).plus(p.balance).toNumber())}}),c},zs=async(a,t,e)=>{let n=e,o=a.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let l=await a.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${o}>`},options:{showContent:!0},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);let c=0;return r.map(l=>l.data).filter(l=>l!=null).forEach(l=>{if(l.content&&"fields"in l.content){let u=l.content.fields;c=Jo(c).plus(u.balance).toNumber()}}),c},Js=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,o=new Fu;return o.moveCall({target:n,arguments:[o.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:o,sender:a.params.walletAddress})).events[0].parsedJson};import{normalizeStructTag as T}from"@mysten/sui.js/utils";var fe=async(a,t)=>{let e=t,n=a.address.get("spool.object"),o=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let p=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},options:{showContent:!0,showType:!0},cursor:s});r.push(...p.data),p.hasNextPage&&p.nextCursor?(i=!0,s=p.nextCursor):i=!1}while(i);let c={sweth:[],ssui:[],susdc:[],swusdc:[],swusdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},d=Object.keys(c).reduce((p,m)=>{let b=a.utils.parseCoinName(m),y=a.utils.parseMarketCoinType(b),w={...p},D=`${n}::spool_account::SpoolAccount<${y}>`;return w[m]=D,w},{}),l=r.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await a.client.multiGetObjects({ids:l,options:{showContent:!0,showType:!0}})).forEach(p=>{let m=p.data.objectId,b=p.data.type;if(p.data.content&&"fields"in p.data.content){let y=p.data.content.fields,w=String(y.spool_id),D=String(y.stake_type.fields.name),W=Number(y.stakes),_=Number(y.index),q=Number(y.points),L=Number(y.total_points);T(b)===d.sweth?c.sweth.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.ssui?c.ssui.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.swusdc?c.swusdc.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.swusdt?c.swusdt.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.scetus?c.scetus.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.safsui?c.safsui.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.shasui?c.shasui.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.svsui?c.svsui.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L}):T(b)===d.susdc&&c.susdc.push({id:m,type:T(b),stakePoolId:w,stakeType:T(D),staked:W,index:_,points:q,totalPoints:L})}}),c},Jr=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.id`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,d=Number(c.max_distributed_point),l=Number(c.distributed_point),u=Number(c.distributed_point_per_period),p=Number(c.point_distribution_time),m=Number(c.max_stakes),b=String(c.stake_type.fields.name),y=Number(c.stakes),w=Number(c.index),D=Number(c.created_at),W=Number(c.last_update);n={id:i,type:T(s),maxPoint:d,distributedPoint:l,pointPerPeriod:u,period:p,maxStake:m,stakeType:T(b),totalStaked:y,index:w,createdAt:D,lastUpdate:W}}}return n},Yr=async(a,t)=>{let e=a.address.get(`spool.pools.${t}.rewardPoolId`),n,o=await a.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(o.data){let r=o.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,d=String(c.spool_id),l=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:T(s),stakePoolId:d,ratioNumerator:l,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};import{TransactionBlock as Ku}from"@mysten/sui.js/transactions";import{normalizeStructTag as wv}from"@mysten/sui.js/utils";import Cv from"bignumber.js";var M=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},Zs=(a,t,e,n)=>{let o=!n,r=!o&&n*1e3<=new Date().getTime();if(o||r)if(a!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof a=="number"&&a<1e10)throw new Error(`Minimum lock amount for ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if($t(n),typeof a=="number"&&a<1e9)throw new Error("Minimum top up amount is 1 SCA");if(e&&n&&e-n>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)}},tc=(a,t,e)=>{if($t(e),a<=0)throw new Error("Lock period must be greater than 0");if(!!e&&e*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");if(e&&t-(e??0)>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},ec=(a,t)=>{if($t(t),a<1e9)throw new Error("Minimum top up amount is 1 SCA");if(!!t&&t*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead")},nc=(a,t,e)=>{if($t(e),a<1e10)throw new Error("Minimum lock amount for renewing expired vesca 10 SCA");if(t*86400>=126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},$t=a=>{if(a===void 0)throw new Error("veSca not found")};import{normalizeStructTag as oc,parseStructTag as qu}from"@mysten/sui.js/utils";import lv from"bignumber.js";var $u=a=>({pointType:oc(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),ac=a=>({poolType:oc(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=$u(e),o=qu(n.pointType).name.toLowerCase();return t[o]=n,t},{})});var Xo=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...et,...go,...Us])].includes(t)},Xr=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}},rc=a=>{let t=new Date(a*1e3),e=new Date(a*1e3);e.setUTCHours(0,0,0,0),t.getUTCHours()>=0&&e.setUTCDate(e.getUTCDate()+1);let n=new Date().getTime();return e.getTime()-n>126144e3*1e3&&e.setUTCDate(e.getUTCDate()-1),Math.floor(e.getTime()/1e3)};var ic=async(a,t,e,n)=>{let o=n||[...gt],r=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new Ku;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let l=(await a.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return l.pool_records.forEach(p=>{let m=ac(p),{poolType:b}=m,y=a.utils.parseCoinNameFromType(b);o.length>=1&&o.includes(y)&&(u[y]=m)},{}),u};var sc=async({address:a,client:t},e)=>{let n=a.get("borrowIncentive.object"),o=a.get("borrowIncentive.incentiveAccounts"),r=a.get("core.object"),i=await t.getObject({id:o,options:{showContent:!0}});if(i?.data?.content?.dataType!=="moveObject")return null;let s=i.data.content.fields.accounts.fields.id.id,c=await t.getDynamicFieldObject({parentId:s,name:{type:`${n}::typed_id::TypedID<${r}::obligation::Obligation>`,value:e}});return c?.data?.content?.dataType!=="moveObject"?null:c.data.content.fields.value.fields.binded_ve_sca_key?.fields.id??null};var cc=async(a,t)=>{let e=a.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await a.client.getObject({id:e,options:{showContent:!0}});if(n.data){let o=n.data;if(o.content&&"fields"in o.content){let r=o.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),d=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(d?-1:1)}}return 0};import Zr from"bignumber.js";var lc=async(a,t)=>{let e=t,o=`${a.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let d=await a.client.getOwnedObjects({owner:e,filter:{StructType:o},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);return r.map(d=>d.data).filter(d=>!!d)},dc=async(a,t)=>{let n=(await lc(a,t)).map(r=>r.objectId),o=[];for(let r=0;r<n.length;r++){let i=await ti(a,n[r]);i&&o.push(i)}return o},ti=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),o=t||(await lc(a,e))[0].objectId,r,s=(await a.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:o}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:o,lockedScaAmount:Zr(c.locked_sca_amount).toNumber(),lockedScaCoin:Zr(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:Zr(c.unlock_at).toNumber()}}return r};var Zo=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:o}=e;this.address=n,this.utils=o}async getObligations(t=this.params.walletAddress){return qt(this,t)}async getCoinAmounts(t,e){return Qs(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return Hs(this,t,e)}async getMarketCoinAmounts(t,e){return Gs(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return zs(this,t,e)}async getPriceFromPyth(t){return cc(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return fe(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let o=t[n],r=await Jr(this,o);r&&(e[o]=r)}return e}async getStakePool(t){return Jr(this,t)}async getStakeRewardPools(t=[...bt]){let e={};for(let n=0;n<t.length;n++){let o=await Yr(this,t[n]);o&&(e[t[n]]=o)}return e}async getStakeRewardPool(t){return Yr(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return ic(this,t,e,n)}async getObligationCoinNames(t){let e=await Js(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),o=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...o])].map(s=>this.utils.parseCoinNameFromType(s))}};import{SUI_TYPE_ARG as ei,normalizeStructTag as Vu}from"@mysten/sui.js/utils";var ta=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Xo(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Xr(e)}return Xr(t)}parseCoinType(t){let e=Xo(t)?this.parseCoinName(t):t,n=$s[e];return[F.wusdc,F.wusdt,F.weth,F.wbtc,F.wsol,F.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Qr.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||bo,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=Vu(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,o=t.match(n),r=t.includes("reserve::MarketCoin");e=o?.[1]||t;let i={[`${F.wusdc}::coin::COIN`]:"wusdc",[`${F.wusdt}::coin::COIN`]:"wusdt",[`${F.weth}::coin::COIN`]:"weth",[`${F.wbtc}::coin::COIN`]:"wbtc",[`${F.wsol}::coin::COIN`]:"wsol",[`${F.wapt}::coin::COIN`]:"wapt"},s={[`${Qr.vsui}::cert::CERT`]:"vsui"},c=i[e]||s[e]||e.split("::")[2].toLowerCase();return r?this.parseMarketCoinName(c):c}parseCoinName(t){return t.slice(1)}parseMarketCoinName(t){return`s${t}`}getSpoolRewardCoinName=t=>ho[t];getBorrowIncentiveRewardCoinName=t=>qs[t];getCoinDecimal(t){return Fs[t]}getCoinWrappedType(t){return t==="wusdc"||t==="wusdt"||t==="weth"||t==="wbtc"||t==="wapt"||t==="wsol"?{from:"Wormhole",type:"Portal from Ethereum"}:void 0}parseSCoinType(t){return Ks[t]}parseUnderlyingSCoinType(t){let e=this.parseCoinName(t);return this.parseCoinType(e)}getSCoinTreasury(t){return this._address.get(`scoin.coins.${t}.treasury`)}async selectCoins(t,e=ei,n){let o=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let d=await this.client.getCoins({owner:o,coinType:e,cursor:c});d.data.sort((l,u)=>parseInt(u.balance,10)-parseInt(l.balance,10));for(let l=0;l<d.data.length&&(r.push({objectId:d.data[l].coinObjectId,digest:d.data[l].digest,version:d.data[l].version,balance:d.data[l].balance}),i+=parseInt(d.data[l].balance,10),!(i>=t));l++);c=d.nextCursor,s=d.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r}async selectCoinsMarketCoin(t=ei,e){let n=e,o=[],r=!0,i=null;for(;r;){let s=await this.client.getCoins({owner:n,coinType:t,cursor:i});s.data.sort((c,d)=>parseInt(d.balance,10)-parseInt(c.balance,10));for(let c=0;c<s.data.length&&(o.push({objectId:s.data[c].coinObjectId,digest:s.data[c].digest,version:s.data[c].version,balance:s.data[c].balance}),!(o.length>50));c++);i=s.nextCursor,r=s.hasNextPage}return o}async selectCoinIds(t,e=ei,n){return(await this.selectCoins(t,e,n)).map(r=>r.objectId)}parseAprToApy(t,e=365){return(1+t/e)**e-1}parseApyToApr(t,e=365){return((1+t)**(1/e)-1)*e}takeAmountFromCoins(t,e,n){let o=e.map(s=>t.object(s)),r=o[0];o.length>1&&t.mergeCoins(r,o.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),o=e?Math.max(e-n,0):0,r=0;if(o===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+o:o,126144e3);r=n+i}return rc(r)}parseSCoinName(t){if(Xo(t)&&nt.includes(t))return t;let e=`s${t}`;if(nt.includes(e))return e}};import{SUI_CLOCK_OBJECT_ID as Kt,SUI_TYPE_ARG as Qu}from"@mysten/sui.js/utils";var Vt=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await ti(t.query,n);return i||void 0}let o=M(e),r=await dc(t.query,o);if(r.length!==0)return r[0]};var ni=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&n&&o&&typeof n=="string"){let c=await zr(t.query,n);return{obligationId:n,obligationKey:o,obligationLocked:c}}let r=M(e),i=await qt(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);let s=i.find(c=>c.id===n||c.keyId===o)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},Hu=async({builder:a,txBlock:t})=>{let e={borrowIncentivePkg:a.address.get("borrowIncentive.id"),query:a.address.get("borrowIncentive.query"),incentivePools:a.address.get("borrowIncentive.incentivePools"),incentiveAccounts:a.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:a.address.get("core.obligationAccessStore"),config:a.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},o={table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(Kt)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(o.config),t.object(o.treasury),t.object(o.table),t.object(s),t.object(Kt)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(Kt)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(Kt)],typeArguments:[Qu]})},claimBorrowIncentive:(r,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.borrowIncentivePkg}::user::redeem_rewards`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(Kt)],typeArguments:[c]})},oldClaimBorrowIncentive(r,i,s){let c=a.utils.parseCoinType(s);return t.moveCall({target:`${n.id}::user::redeem_rewards`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(Kt)],typeArguments:[c]})}}},E=async({builder:a,txBlock:t})=>{let e=await Hu({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await ni(a,t,n,o),c=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${ft}::user::unstake`||d.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await ni(a,t,n,o);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,o,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await ni(a,t,n,o),d=!!t.blockData.transactions.find(async l=>l.kind==="MoveCall"&&(l.target===`${ft}::user::unstake`||l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||d){let l=await sc({address:a.address,client:a.client},i);if(r&&r!==l)throw new Error("Binded veScaKey is not equal to the provided veScaKey");l?e.stakeObligationWithVesca(i,s,l):e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,o,r)=>e.claimBorrowIncentive(o,r,n)}};import{SUI_CLOCK_OBJECT_ID as at}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as oa}from"@mysten/sui.js/utils";import Gu from"axios";var uc={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};import{bcs as oi}from"@mysten/sui.js/bcs";import{SUI_CLOCK_OBJECT_ID as ea}from"@mysten/sui.js/utils";var ai=16*1024,na=class{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(t,e,n){this.provider=t,this.pythStateId=e,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!t.data||!t.data.content||t.data.content.dataType!=="moveObject")throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=t.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}}).then(n=>{if(n.data?.content?.dataType==="moveObject")return n.data.content.fields;throw new Error(`Cannot fetch package id for object ${t}`)});if("upgrade_cap"in e)return e.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(t,e){let n=await this.getWormholePackageId(),o=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(oi.ser("vector<u8>",Array.from(r),{maxSize:ai}).toBytes()),e.object(ea)]});o.push(i)}),o}async updatePriceFeeds(t,e,n){let o=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${o}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(oi.ser("vector<u8>",Array.from(e[0]),{maxSize:ai}).toBytes()),s[0],t.object(ea)]});let c=[],d=await this.getBaseUpdateFee(),l=t.splitCoins(t.gas,n.map(()=>t.pure(d))),u=0;for(let p=0;p<n.length;p++){let m=await this.getPriceFeedObjectId(n[p]);if(!m)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(m),[r]=t.moveCall({target:`${o}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(m),l[u],t.object(ea)]}),u++}return t.moveCall({target:`${o}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${o}::price_info::PriceInfo`]}),c}async createPriceFeed(t,e){let n=await this.getPythPackageId();if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let o=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([o],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(oi.ser("vector<u8>",Array.from(e[0]),{maxSize:ai}).toBytes()),r[0],t.object(ea)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(t){let e=t.replace("0x","");if(!this.priceFeedObjectIdCache.has(e)){let{id:n,fieldType:o}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${o}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,o=t.readUint16BE(n),r=n+2;return t.subarray(r,r+o)}};var zu=async(a,t)=>(await Gu.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(o=>Buffer.from(o,"base64")),be=async(a,t,e)=>{let n=e??[...new Set([...et,...go])],o=a.isTestnet?["pyth"]:["pyth"];if(o.includes("pyth")){let i=new na(a.client,a.address.get("core.oracles.pyth.state"),a.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async d=>s.push(a.address.get(`core.coins.${d}.oracle.pyth.feed`))));let c=a.params.pythEndpoints??uc[a.isTestnet?"testnet":"mainnet"];try{let d=await zu(c[0],s);await i.updatePriceFeeds(t,d,s)}catch(d){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${d}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await Ju(a,t,r[i],o)},Ju=async(a,t,e,n)=>{let o=a.utils.parseCoinType(e);Yu(t,n,a.address.get("core.packages.xOracle.id"),a.address.get("core.oracles.xOracle"),a.address.get("core.packages.pyth.id"),a.address.get("core.oracles.pyth.registry"),a.address.get("core.oracles.pyth.state"),a.address.get(`core.coins.${e}.oracle.pyth.feedObject`),a.address.get("core.packages.switchboard.id"),a.address.get("core.oracles.switchboard.registry"),a.address.get(`core.coins.${e}.oracle.switchboard`),a.address.get("core.packages.supra.id"),a.address.get("core.oracles.supra.registry"),a.address.get("core.oracles.supra.holder"),o)},Yu=(a,t,e,n,o,r,i,s,c,d,l,u,p,m,b)=>{let y=Xu(a,e,n,b);return t.includes("pyth")&&np(a,o,y,i,s,r,b),t.includes("switchboard")&&ep(a,c,y,l,d,b),t.includes("supra")&&tp(a,u,y,m,p,b),Zu(a,e,n,y,b),a},Xu=(a,t,e,n)=>{let o=typeof e=="string"?a.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return a.moveCall({target:r,arguments:[o],typeArguments:i})},Zu=(a,t,e,n,o)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[o],s=typeof e=="string"?a.object(e):e;return a.moveCall({target:r,arguments:[s,n,a.object(oa)],typeArguments:i}),a},tp=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(oa)],typeArguments:[r]})},ep=(a,t,e,n,o,r)=>{let i=typeof n=="string"?a.object(n):n,s=typeof o=="string"?a.object(o):o;a.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,a.object(oa)],typeArguments:[r]})},np=(a,t,e,n,o,r,i)=>{let s=typeof e=="string"?a.object(e):e,c=typeof n=="string"?a.object(n):n,d=typeof o=="string"?a.object(o):o,l=typeof r=="string"?a.object(r):r;a.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,d,l,a.object(oa)],typeArguments:[i]})};var yt=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("scoin.id")},n={};return await Promise.all(nt.map(async o=>{let r=a.utils.getSCoinTreasury(o);n[o]=r})),{mintSCoin:(o,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[o]),typeof r!="string"?r:t.pure(r)],typeArguments:[a.utils.parseSCoinType(o),a.utils.parseUnderlyingSCoinType(o)]}),burnSCoin:(o,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[o]),typeof r!="string"?r:t.pure(r)],typeArguments:[a.utils.parseSCoinType(o),a.utils.parseUnderlyingSCoinType(o)]})}};var ge=async(...a)=>{let[t,e,n,o]=a;if(a.length===3&&n)return{obligationId:n};if(a.length===4&&n&&o)return{obligationId:n,obligationKey:o};let r=M(t),i=await qt(e.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);return{obligationId:i[0].id,obligationKey:i[0].keyId}},op=async({builder:a,txBlock:t})=>{let e={protocolPkg:a.address.get("core.packages.protocol.id"),market:a.address.get("core.market"),version:a.address.get("core.version"),coinDecimalsRegistry:a.address.get("core.coinDecimalsRegistry"),xOracle:a.address.get("core.oracles.xOracle")},o=`${a.address.get("referral.id")}::scallop_referral_program::REFERRAL_WITNESS`;return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.object(e.version)]}),returnObligation:(r,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(r),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(r,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(r,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(at)],typeArguments:[d]})},deposit:(r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(at)],typeArguments:[s]})},depositEntry:(r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(at)],typeArguments:[s]})},withdraw:(r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(at)],typeArguments:[s]})},withdrawEntry:(r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(at)],typeArguments:[s]})},borrow:(r,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(at)],typeArguments:[d]})},borrowEntry:(r,i,s,c)=>{let d=a.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(at)],typeArguments:[d]})},borrowWithReferral:(r,i,s,c,d)=>{let l=a.utils.parseCoinType(d);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(at)],typeArguments:[l,o]})},repay:(r,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(at)],typeArguments:[c]})},borrowFlashLoan:(r,i)=>{let s=a.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r)],typeArguments:[s]})},repayFlashLoan:(r,i,s)=>{let c=a.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r),t.object(i)],typeArguments:[c]})}}},N=async({builder:a,txBlock:t})=>{let e=await op({builder:a,txBlock:t}),n=await yt({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(o,r,i)=>{let s=M(t),{obligationId:c}=await ge(t,a,i);if(r==="sui"){let[d]=t.splitCoins(t.gas,[o]);e.addCollateral(c,d,r)}else{let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,r,o,s);e.addCollateral(c,l,r),t.transferObjects([d],s)}},takeCollateralQuick:async(o,r,i,s)=>{let c=await ge(t,a,i,s),d=await a.query.getObligationCoinNames(c.obligationId);return await be(a,t,d),e.takeCollateral(c.obligationId,c.obligationKey,o,r)},depositQuick:async(o,r,i)=>{if(r==="sui"){let[d]=t.splitCoins(t.gas,[o]);return e.deposit(d,r)}let{leftCoin:s,takeCoin:c}=await a.selectCoin(t,r,o,i);return t.transferObjects([s],i),e.deposit(c,r)},withdrawQuick:async(o,r)=>{let i=M(t),s=a.utils.parseMarketCoinName(r);try{let c=a.utils.parseSCoinName(r);if(!c)throw new Error(`No sCoin for ${r}`);let{leftCoin:d,takeCoin:l,totalAmount:u}=await a.selectSCoin(t,c,o,i);t.transferObjects([d],i);let p=n.burnSCoin(c,l),m=e.withdraw(p,r),b=o-u;try{if(b>0){let{leftCoin:y,takeCoin:w}=await a.selectMarketCoin(t,s,b,i);t.transferObjects([y],i),t.mergeCoins(m,[e.withdraw(w,r)])}}catch{}return m}catch{let{leftCoin:d,takeCoin:l}=await a.selectMarketCoin(t,s,o,i);return t.transferObjects([d],i),e.withdraw(l,r)}},borrowQuick:async(o,r,i,s)=>{let c=await ge(t,a,i,s),l=[...await a.query.getObligationCoinNames(c.obligationId),r];return await be(a,t,l),e.borrow(c.obligationId,c.obligationKey,o,r)},borrowWithReferralQuick:async(o,r,i,s,c)=>{let d=await ge(t,a,s,c),u=[...await a.query.getObligationCoinNames(d.obligationId),r];return await be(a,t,u),e.borrowWithReferral(d.obligationId,d.obligationKey,i,o,r)},repayQuick:async(o,r,i,s)=>{let c=await ge(t,a,i);if(r==="sui"){let[u]=t.splitCoins(t.gas,[o]);return e.repay(c.obligationId,u,r)}let{leftCoin:d,takeCoin:l}=await a.selectCoin(t,r,o,s);return t.transferObjects([d],s),e.repay(c.obligationId,l,r)},updateAssetPricesQuick:async o=>be(a,t,o)}};import{SUI_CLOCK_OBJECT_ID as aa}from"@mysten/sui.js/utils";var ra=async({builder:a,txBlock:t})=>{let e={referralPgkId:a.address.get("referral.id"),referralBindings:a.address.get("referral.referralBindings"),referralRevenuePool:a.address.get("referral.referralRevenuePool"),authorizedWitnessList:a.address.get("referral.authorizedWitnessList"),referralTiers:a.address.get("referral.referralTiers"),version:a.address.get("referral.version")},n=a.address.get("vesca.table");return{bindToReferral:o=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(o),t.object(n),t.object(aa)],typeArguments:[]}),claimReferralTicket:o=>{let r=a.utils.parseCoinType(o);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(n),t.object(e.referralBindings),t.object(e.authorizedWitnessList),t.object(e.referralTiers),t.object(aa)],typeArguments:[r]})},burnReferralTicket:(o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(o),t.object(e.referralRevenuePool),t.object(aa)],typeArguments:[i]})},claimReferralRevenue:(o,r)=>{let i=a.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,arguments:[t.object(e.version),t.object(e.referralRevenuePool),t.object(o),t.object(aa)],typeArguments:[i]})}}},pc=async({builder:a,txBlock:t})=>{let e=await ra({builder:a,txBlock:t});return{claimReferralRevenueQuick:async(n,o,r=[...et])=>{let i=[];for(let s=0;s<r.length;s++)if(r[s]==="sui"){let c=e.claimReferralRevenue(n,r[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,r[s]);try{let d=await a.utils.selectCoinIds(1/0,a.utils.parseCoinType(r[s]),o);t.mergeCoins(c,d.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(o))}}};var ap={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},mc={check_slippage:(a,t,e,n,o)=>a.moveCall({target:`${ap.packageId}::slippage_check::check_slippage`,arguments:[t,a.pure(e),a.pure(n)],typeArguments:[o]})};import{SUI_CLOCK_OBJECT_ID as ia}from"@mysten/sui.js/utils";var fc=async(a,t,e,n,o,r,i=!1)=>{let s=await yt({builder:a,txBlock:t}),c=await gc({builder:a,txBlock:t});try{let{takeCoin:d,leftCoin:l,totalAmount:u}=i?await a.selectSCoin(t,n,o,r):await a.selectMarketCoin(t,n,o,r);if(i){let p=s.burnSCoin(n,d);c.stake(e,p,n)}else c.stake(e,d,n);return t.transferObjects([l],r),u}catch{return 0}},bc=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&o)return[o];let r=M(e);return(await fe(t.query,r))[n].map(s=>s.id)},rp=async(...a)=>{let[t,e,n,o]=a,r=M(e),i=await fe(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return o?i[n].filter(c=>c.id===o):i[n]},gc=async({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")},n={},o={},r={};return bt.forEach(i=>{let s=a.address.get(`spool.pools.${i}.id`),c=a.address.get(`spool.pools.${i}.rewardPoolId`),d=a.utils.parseMarketCoinType(i);n[i]=s,o[i]=c,r[i]=d}),{createStakeAccount:i=>{let s=r[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(ia)],typeArguments:[s]})},stake:(i,s,c)=>{let d=r[c],l=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(l),t.object(i),typeof s=="string"?t.pure(s):s,t.object(ia)],typeArguments:[d]})},unstake:(i,s,c)=>{let d=r[c],l=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(l),t.object(i),t.pure(s),t.object(ia)],typeArguments:[d]})},claim:(i,s)=>{let c=n[s],d=o[s],l=r[s],u=ho[s],p=a.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(d),t.object(i),t.object(ia)],typeArguments:[l,p]})}}},rt=async({builder:a,txBlock:t})=>{let e=await gc({builder:a,txBlock:t}),n=await yt({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(o,r,i)=>{let s=M(t),c=await bc(a,t,r,i),d=[];if(c.length===0){let l=e.createStakeAccount(r);d.push(l)}if(typeof o=="number"){let l=await fc(a,t,c.length>0?c[0]:d[0],r,o,s);o-=l,l||await fc(a,t,c.length>0?c[0]:d[0],r,o,s,!0)}else e.stake(c.length>0?c[0]:d[0],o,r);d.length>0&&t.transferObjects(d,s)},unstakeQuick:async(o,r,i,s)=>{let c=await rp(a,t,r,i),d=[],l=o;for(let u of c){if(u.staked===0)continue;let p=Math.min(l,u.staked),m=e.unstake(u.id,p,r);if(s){let b=n.mintSCoin(r,m);d.push(b)}else d.push(m);if(l-=p,o<=0)break}if(d.length>0){let u=d[0];return d.length>1&&t.mergeCoins(u,d.slice(1)),u}},claimQuick:async(o,r)=>{let i=await bc(a,t,o,r),s=[];return i.forEach(c=>{let d=e.claim(c,o);s.push(d)}),s}}};import{SUI_CLOCK_OBJECT_ID as he}from"@mysten/sui.js/utils";var ip=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("vesca.id"),table:a.address.get("vesca.table"),treasury:a.address.get("vesca.treasury"),config:a.address.get("vesca.config")};return{lockSca:(n,o)=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_key`,arguments:[t.object(e.config),t.object(e.table),t.object(e.treasury),typeof n=="string"?t.pure(n):n,t.pure(o),t.object(he)]}),extendLockPeriod:(n,o)=>{t.moveCall({target:`${e.pkgId}::ve_sca::extend_lock_period`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.pure(o),t.object(he)]})},extendLockAmount:(n,o)=>{t.moveCall({target:`${e.pkgId}::ve_sca::lock_more_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof o=="string"?t.pure(o):o,t.object(he)]})},renewExpiredVeSca:(n,o,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof o=="string"?t.pure(o):o,t.pure(r),t.object(he)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(he)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},St=async({builder:a,txBlock:t})=>{let e=await ip({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,o,r=!0)=>{let i=M(t),s=await Vt(a,t),c,d=[];if(n!==void 0&&typeof n=="number"){let m=await a.utils.selectCoinIds(n,mt,i),[b,y]=a.utils.takeAmountFromCoins(t,m,n);c=b,d.push(y)}else c=n;let l=a.utils.getUnlockAt(o,s?.unlockAt);r&&Zs(n,o,l,s?.unlockAt),console.log(new Date(l*1e3).toLocaleString("en-CA",{hour12:!0}));let u=!s?.unlockAt,p=!u&&s.unlockAt*1e3<=new Date().getTime();if(u||p){if(c)if(u){let m=e.lockSca(c,l);d.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);d.push(m)}e.renewExpiredVeSca(s.keyId,c,l)}}else c&&o?(e.extendLockPeriod(s.keyId,l),e.extendLockAmount(s.keyId,c)):o?e.extendLockPeriod(s.keyId,l):c&&e.extendLockAmount(s.keyId,c);d.length>0&&t.transferObjects(d,i)},extendLockPeriodQuick:async(n,o,r=!0)=>{let i=await Vt(a,t,o),s=a.utils.getUnlockAt(n);r&&tc(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,o,r=!0)=>{let i=M(t),s=await Vt(a,t,o);if(r&&ec(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,mt,i),[d,l]=a.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,d),t.transferObjects([l],i)}},renewExpiredVeScaQuick:async(n,o,r,i=!0)=>{let s=M(t),c=await Vt(a,t,r),d=a.utils.getUnlockAt(o,c?.unlockAt);if(i&&nc(n,o,c?.unlockAt),c){let l=[];if(c.lockedScaAmount!==0){let b=e.redeemSca(c.keyId);l.push(b)}let u=await a.utils.selectCoinIds(n,mt,s),[p,m]=a.utils.takeAmountFromCoins(t,u,n);l.push(m),e.renewExpiredVeSca(c.keyId,p,d),t.transferObjects(l,s)}},redeemScaQuick:async n=>{let o=M(t),r=await Vt(a,t,n);if($t(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],o)}}}};import{normalizeStructTag as lp}from"@mysten/sui.js/utils";import{SUI_CLOCK_OBJECT_ID as sp}from"@mysten/sui.js/utils";var Qt={id:"0x000000000000000000000000000000000000000000000000000000000000dee9",pools:{sui2usdc:{object:{objectId:"0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33",initialSharedVersion:"32079148",mutable:!0},lotsize:1e8},usdt2usdc:{object:{objectId:"0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238",initialSharedVersion:"32079148",mutable:!0},lotsize:1e5},wusdc2usdc:{object:{objectId:"0x39f2f7c126189b9b5cda6b770ab34031dde22307d19842e95ab576873c77fa14",initialSharedVersion:"82838334",mutable:!0},lotsize:1e5}}},hc={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},ri={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},yc={clob_v2:{swap_exact_quote_for_base:"clob_v2::swap_exact_quote_for_base",swap_exact_base_for_quote:"clob_v2::swap_exact_base_for_quote",create_account:"clob_v2::create_account"}};var Sc={objectId:sp,initialSharedVersion:"1",mutable:!1},cp=(a,t)=>{if(a==="sui")switch(t){case"wusdc":return{pool:Qt.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdc")switch(t){case"sui":return{pool:Qt.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:Qt.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:Qt.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdt")switch(t){case"wusdc":return{pool:Qt.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else throw new Error(`Invalid coin pair: ${a} and ${t}`)},ii={createAccount:a=>a.moveCall({target:`${hc.id}::${yc.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(a,t,e,n,o,r,i)=>{let{pool:s,aToB:c}=cp(e,n),d=i.parseCoinType(e),l=i.parseCoinType(n),u=typeof r=="string"?a.object(r):"objectId"in r?a.objectRef(r):a.object(r);if(!s)throw new Error(`Deepbook: No pool found for ${e} to ${n}`);return c?a.moveCall({target:`${ri.id}::deepbook::deepbook_base_for_quote`,arguments:[a.sharedObjectRef(s.object),a.pure(o),u,a.object(t),a.sharedObjectRef(Sc),a.pure(s.lotsize)],typeArguments:[d,l]}):a.moveCall({target:`${ri.id}::deepbook::deepbook_quote_for_base`,arguments:[a.sharedObjectRef(s.object),a.pure(o),u,a.sharedObjectRef(Sc),a.object(t),a.pure(s.lotsize)],typeArguments:[l,d]})}};var sa=class{suiClient;scallopUtils;_clientOrderId=0;_accountCap;currentAddress;constructor({client:t,currentAddress:e,accountCap:n,scallopUtils:o}){this.currentAddress=e,this.suiClient=t,this._accountCap=n,this.scallopUtils=o}get clientOrderId(){let t=this._clientOrderId;return this._clientOrderId++,t}async accountCap(t){if(this._accountCap)return this._accountCap;try{let{data:e}=await this.suiClient.getOwnedObjects({owner:this.currentAddress,filter:{StructType:lp("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?ii.createAccount(t):{objectId:e[0].data.objectId,version:e[0].data.version,digest:e[0].data.digest}}catch{throw new Error("Failed to create account cap")}}async swapToken({tokenObjectIn:t,baseCoinName:e,quoteCoinName:n,tx:o}){let r=await this.accountCap(o);return{swapResult:ii.swap(o,t,e,n,this.clientOrderId,r,this.scallopUtils),accountCap:r}}};var ca=class{params;client;address;builder;query;utils;walletAddress;deepbookSwap;constructor(t,e){this.params=t,this.client=t.client,this.address=e,this.utils=new ta(t,this.address),this.query=new Zo(t,{address:this.address,utils:this.utils}),this.builder=new zo(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new sa({client:this.client,currentAddress:this.params.walletAddress,scallopUtils:this.utils})}async getObligations(t){let e=t||this.params.walletAddress;return this.query.getObligations(e)}async getAllStakeAccounts(t){let e=t||this.params.walletAddress;return this.query.getAllStakeAccounts(e)}async getStakeAccounts(t,e){let n=e||this.params.walletAddress;return this.query.getStakeAccounts(t,n)}async getStakePool(t){return this.query.getStakePool(t)}async getStakeRewardPool(t){return this.query.getStakeRewardPool(t)}async openObligation(t){let e=new C,n=await N({builder:this.builder,txBlock:e}),o=await E({builder:this.builder,txBlock:e}),r=t||this.params.walletAddress;e.setSender(r);let[i,s,c]=n.normalMethod.openObligation();return o.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],r),e}async depositCollateral(t,e,n,o){let r=new C,i=o||this.params.walletAddress;r.setSender(i);let s=await N({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),d=n||c?.[0]?.id;if(d)await s.addCollateralQuick(e,t,d);else{let[l,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,l),s.normalMethod.returnObligation(l,p),r.transferObjects([u],i)}return r}async withdrawCollateral(t,e,n,o,r){let i=new C,s=await N({builder:this.builder,txBlock:i}),c=r||this.params.walletAddress;i.setSender(c);let d=await s.takeCollateralQuick(e,t,n,o);return i.transferObjects([d],c),i}async deposit(t,e,n){let o=new C,r=await N({builder:this.builder,txBlock:o}),i=await yt({builder:this.builder,txBlock:o}),s=n||this.params.walletAddress;o.setSender(s);let c=await r.depositQuick(e,t,n),d=this.utils.parseMarketCoinName(t);if(!nt.includes(d))o.transferObjects([c],s);else{let l=i.mintSCoin(d,c);o.transferObjects([l],s)}return o}async withdraw(t,e,n){let o=new C,r=n||this.params.walletAddress,i=await N({builder:this.builder,txBlock:o});o.setSender(r);let s=await i.withdrawQuick(e,t);return o.transferObjects([s],r),o}async borrow(t,e,n,o,r){let i=new C,s=await N({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=gt.includes(t);l&&await c.unstakeObligationQuick(n,o);let u=await s.borrowQuick(e,t,n,o);return i.transferObjects([u],d),l&&await c.stakeObligationQuick(n,o),i}async borrowWithBoost(t,e,n,o,r,i){let s=new C,c=await N({builder:this.builder,txBlock:s}),d=await E({builder:this.builder,txBlock:s}),l=i||this.params.walletAddress;s.setSender(l);let u=gt.includes(t);u&&await d.unstakeObligationQuick(n,o);let p=await c.borrowQuick(e,t,n,o);return s.transferObjects([p],l),u&&await d.stakeObligationWithVeScaQuick(n,o,r),s}async borrowWithReferral(t,e,n,o,r,i){let s=new C,c=await N({builder:this.builder,txBlock:s}),d=await E({builder:this.builder,txBlock:s}),l=await ra({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=gt.includes(t);p&&await d.unstakeObligationQuick(n,o);let m=l.claimReferralTicket(t),b=await c.borrowWithReferralQuick(e,t,m,n,o);return l.burnReferralTicket(m,t),s.transferObjects([b],u),p&&r?await d.stakeObligationWithVeScaQuick(n,o,r):await d.stakeObligationQuick(n,o),s}async repay(t,e,n,o,r){let i=new C,s=await N({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=gt.includes(t);return l&&await c.unstakeObligationQuick(n,o),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationQuick(n,o),i}async repayWithBoost(t,e,n,o,r){let i=new C,s=await N({builder:this.builder,txBlock:i}),c=await E({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=gt.includes(t);return l&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,d),l&&await c.stakeObligationWithVeScaQuick(n,void 0,o),i}async createStakeAccount(t,e){let n=new C,o=await rt({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;n.setSender(r);let i=o.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,o){let r=new C,i=await N({builder:this.builder,txBlock:r}),s=await rt({builder:this.builder,txBlock:r}),c=o||this.params.walletAddress;r.setSender(c);let d=await i.depositQuick(e,t,o),l=this.utils.parseMarketCoinName(t);if(!bt.find(m=>m===l))return r;let u=await this.query.getStakeAccounts(l,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(d,l,p);else{let m=s.normalMethod.createStakeAccount(l);await s.stakeQuick(d,l,m),r.transferObjects([m],c)}return r}async unstakeAndWithdraw(t,e,n){let o=new C,r=await N({builder:this.builder,txBlock:o}),i=await rt({builder:this.builder,txBlock:o}),s=this.params.walletAddress,c=[];o.setSender(s);let d=this.utils.parseMarketCoinName(t);for(let l=0;l<n.length;l++){let u=n[l],[p]=await i.unstakeQuick(u.coin,d,u.id);if(p){let m=r.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let l=await r.withdrawQuick(e,t);c.push(l)}return c.length>1&&o.mergeCoins(c[0],c.slice(1)),o.transferObjects(c,s),o}async stake(t,e,n,o){let r=new C,i=await rt({builder:this.builder,txBlock:r}),s=o||this.params.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),d=n||(c.length>0?c[0].id:void 0);if(d)await i.stakeQuick(e,t,d);else{let l=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,l),r.transferObjects([l],s)}return r}async unstake(t,e,n,o){let r=new C,i=await rt({builder:this.builder,txBlock:r}),s=o||this.params.walletAddress;r.setSender(s);let c=nt.includes(t),d=await i.unstakeQuick(e,t,n,c);return r.transferObjects([d],r.pure(s)),r}async claim(t,e,n,o){let r=new C,i=await rt({builder:this.builder,txBlock:r}),s=await E({builder:this.builder,txBlock:r}),c=o||this.params.walletAddress;r.setSender(c);let d={sui:[],sca:[],scallop_sui:[],scallop_sca:[],scallop_deep:[],scallop_fud:[]};for(let l=0;l<t.length;l++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[l],m=i.normalMethod.claim(p,u);d.sui.push(m)}for(let l=0;l<e.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[l],b=s.normalMethod.claimBorrowIncentive(u,p,m);d[m].push(b)}for(let l=0;l<n.length;l++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[l],b=s.normalMethod.oldClaimBorrowIncentive(u,p,m);d[m].push(b)}for(let l in d)d[l].length>0&&(d[l].length>1&&r.mergeCoins(d[l][0],d[l].slice(1)),r.transferObjects([d[l][0]],r.pure(c)));return r}async stakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=await E({builder:this.builder,txBlock:o}),i=n||this.params.walletAddress;return o.setSender(i),await r.stakeObligationQuick(t,e),o}async unstakeObligation(t,e,n){let o=this.builder.createTxBlock(),r=await E({builder:this.builder,txBlock:o}),i=n||this.params.walletAddress;return o.setSender(i),await r.unstakeObligationQuick(t,e),o}async stakeSca(t,e=!1,n=!1,o,r,i,s,c){let d=new C,l=await St({builder:this.builder,txBlock:d}),u=await E({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[b,y]=this.builder.utils.takeAmountFromCoins(d,m,t),w;return s?l.normalMethod.extendLockAmount(s,b):w=l.normalMethod.lockSca(b,i),o&&r&&(e&&(n?u.normalMethod.oldUnstakeObligation(o,r):u.normalMethod.unstakeObligation(o,r)),u.normalMethod.stakeObligationWithVesca(o,r,s||w)),s||d.transferObjects([w,y],p),d}async stakeMoreSca(t,e,n){let o=new C,r=n||this.params.walletAddress;return o.setSender(r),o}async extendStakeScaLockPeriod(t,e,n,o,r=!1,i=!1,s){let c=new C,d=await St({builder:this.builder,txBlock:c}),l=await E({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),d.normalMethod.extendLockPeriod(e,t),n&&o&&(r&&(i?l.normalMethod.oldUnstakeObligation(n,o):l.normalMethod.unstakeObligation(n,o)),l.normalMethod.stakeObligationWithVesca(n,o,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,o,r,i=!1,s=!1,c){let d=new C,l=await St({builder:this.builder,txBlock:d}),u=await E({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,mt,p),[b,y]=this.builder.utils.takeAmountFromCoins(d,m,t);return l.normalMethod.extendLockPeriod(e,n),l.normalMethod.extendLockAmount(e,b),d.transferObjects([y],p),!o||!r||(i&&(s?u.normalMethod.oldUnstakeObligation(o,r):u.normalMethod.unstakeObligation(o,r)),u.normalMethod.stakeObligationWithVesca(o,r,e)),d}async renewExpiredStakeSca(t,e,n,o=!1,r,i,s=!1,c=!1,d){let l=new C,u=await St({builder:this.builder,txBlock:l}),p=await E({builder:this.builder,txBlock:l}),m=d||this.params.walletAddress;if(l.setSender(m),o){let D=u.normalMethod.redeemSca(n);l.transferObjects([D],m)}let b=await this.builder.utils.selectCoinIds(t,mt,m),[y,w]=this.builder.utils.takeAmountFromCoins(l,b,t);return l.transferObjects([w],m),u.normalMethod.renewExpiredVeSca(n,y,e),!r||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(r,i):p.normalMethod.unstakeObligation(r,i)),p.normalMethod.stakeObligationWithVesca(r,i,n)),l}async redeemSca(t){let e=new C,n=await St({builder:this.builder,txBlock:e}),o=this.params.walletAddress;return e.setSender(o),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,o){let r=new C,i=await E({builder:this.builder,txBlock:r}),s=this.params.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return r.transferObjects([c],s),await i.unstakeObligationQuick(e,t),o?await i.stakeObligationWithVeScaQuick(e,t,o):await i.stakeObligationQuick(e,t),r}async withdrawUnlockedSca(t,e){let n=new C,o=await St({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;return n.setSender(r),await o.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new wc(t.weightedAmount),r=e.currentPointIndex?wc(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new C,e=await St({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let o=e.normalMethod.mintEmptyVeSca();return t.transferObjects([o],n),t}async claimRevenuReferral(t,e){let n=new C,o=await pc({builder:this.builder,txBlock:n}),r=this.params.walletAddress;n.setSender(r);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await o.claimReferralRevenueQuick(t,r,i),n}async bindReferral(t){let e=new C,n=await ra({builder:this.builder,txBlock:e}),o=this.params.walletAddress;return e.setSender(o),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new C,e=await yt({builder:this.builder,txBlock:t}),n=await rt({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let o=[];return await Promise.all(nt.map(async r=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(r),this.params.walletAddress),d=c[0];c.length>1&&t.mergeCoins(d,c.slice(1)),s=d}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(r,s);try{let d=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(r),this.params.walletAddress);t.mergeCoins(c,d)}catch(d){console.log(d)}i.push(c)}if(bt.includes(r))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,r);c&&i.push(c)}catch(c){console.log(c)}if(i.length>0){let c=i[0];i.length>1&&t.mergeCoins(c,i.slice(1)),o.push(c)}})),o.length>0&&t.transferObjects(o,this.params.walletAddress),t}async migrateLendingWusdcToUsdcNative(t,e,n,o,r){let i=new C,s=await N({builder:this.builder,txBlock:i}),c=await rt({builder:this.builder,txBlock:i}),d=this.params.walletAddress,l=[],u=this.utils.parseMarketCoinName(t),p=this.utils.parseMarketCoinType(u),b=(await this.utils.selectCoinsMarketCoin(p,d)).map(_=>_.objectId);i.setSender(d);for(let _=0;_<r.length;_++){let q=r[_],[L]=await c.unstakeQuick(q.coin,u,q.id);if(L){b.length>0&&i.mergeCoins(L,b);let Wc=s.normalMethod.withdraw(L,t);l.push(Wc)}}if(e>0){let _=await s.withdrawQuick(e,t);l.push(_)}l.length>1&&i.mergeCoins(l[0],l.slice(1));let[y]=i.splitCoins(l[0],[i.pure(o)]);i.transferObjects([l[0]],d);let{swapResult:w,accountCap:D}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:y,tx:i});typeof D=="string"&&i.transferObjects([D],d),mc.check_slippage(i,w,n,o,this.query.utils.parseCoinType("usdc"));let W=s.normalMethod.deposit(w,"usdc");return await c.stakeQuick(W,"susdc"),i}};var ye=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Go({id:Ls})),await this.address.read(),this.client=new ca(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var la=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new ye({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new yo(e,this.scallop),o=new So(e,this.scallop),r=new wo(e,this.scallop),i=n.decode()||o.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:dp.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:o,txSubType:r,intentionData:i}=t;this.scallop||(this.scallop=new ye({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(r){case"SupplyLending":s=Bo.fromData(i);break;case"WithdrawLending":s=jo.fromData(i);break;case"Borrow":s=To.fromData(i);break;case"Repay":s=Po.fromData(i);break;case"DepositCollateral":s=Do.fromData(i);break;case"WithdrawCollateral":s=No.fromData(i);break;case"OpenObligation":s=Oo.fromData(i);break;case"StakeSpool":s=_o.fromData(i);break;case"UnstakeSpool":s=Mo.fromData(i);break;case"ClaimIncentiveReward":s=ko.fromData(i);break;case"BorrowWithBoost":s=Co.fromData(i);break;case"StakeSca":s=Vo.fromData(i);break;case"ExtendStakePeriod":s=qo.fromData(i);break;case"ExtendPeriodAndStakeMore":s=Fo.fromData(i);break;case"RenewExpStakePeriod":s=Ko.fromData(i);break;case"WithdrawStakedSca":s=Ho.fromData(i);break;case"SupplyAndStakeLending":s=Qo.fromData(i);break;case"WithdrawAndUnstakeLending":s=Eo.fromData(i);break;case"RedeemSca":s=$o.fromData(i);break;case"MigrateAndClaim":s=xo.fromData(i);break;case"BorrowWithReferral":s=Io.fromData(i);break;case"CreateReferralLink":s=Uo.fromData(i);break;case"ClaimRevenueReferral":s=Lo.fromData(i);break;case"BindReferral":s=Wo.fromData(i);break;case"MigrateScoin":s=vo.fromData(i);break;case"RepayWithBoost":s=Ro.fromData(i);break;case"MigrateWusdcToUsdc":s=Ao.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:o,scallop:this.scallop})}};import{TransactionType as qp}from"@msafe/sui3-utils";import{TransactionType as Te}from"@msafe/sui3-utils";import{normalizeStructTag as vt}from"@mysten/sui/utils";var Tc="https://suilend-assets.s3.us-east-2.amazonaws.com/springsui";import{TransactionType as Ip}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as kp,LENDING_MARKET_TYPE as Dp,SuilendClient as si}from"@suilend/sdk";import{TransactionType as Ht}from"@msafe/sui3-utils";import{fromBase64 as Cc,toHex as Ic}from"@mysten/bcs";import{normalizeStructTag as Se}from"@mysten/sui/utils";import{MAX_U64 as Gt}from"@suilend/frontend-sui";import kc from"bignumber.js";var da=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("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(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let t={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},e=Se(t.MintEvent.parsedJson.coin_type.name),n=t.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",e,n),{txType:Ht.Other,type:"deposit",intentionData:{coinType:e,value:n}}}decodeWithdraw(){let t={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},e={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=Se(e.RedeemEvent.parsedJson.coin_type.name),o=e.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let r=t.withdraw_ctokens.MoveCall.arguments[4].Input,i=new kc(Ic(Cc(this.inputs[r].Pure.bytes)),16).toString(),s=i===Gt.toString();return console.log("decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"MAX_U64.toString():",Gt.toString()),s&&(o=Gt.toString()),{txType:Ht.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let t={borrow_request:this.getMoveCallCommand("borrow_request")},e={BorrowEvent:this.simResult.events.find(c=>c.type.includes("lending_market::BorrowEvent"))},n=Se(e.BorrowEvent.parsedJson.coin_type.name),o=`${+e.BorrowEvent.parsedJson.liquidity_amount-+e.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,o);let r=t.borrow_request.MoveCall.arguments[4].Input,i=new kc(Ic(Cc(this.inputs[r].Pure.bytes)),16).toString(),s=i===Gt.toString();return console.log("decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"MAX_U64.toString():",Gt.toString()),s&&(o=Gt.toString()),{txType:Ht.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let t={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},e=Se(t.RepayEvent.parsedJson.coin_type.name),n=t.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",e,n),{txType:Ht.Other,type:"repay",intentionData:{coinType:e,value:n}}}decodeClaim(){let t={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},e={};for(let n=0;n<t.ClaimReward.length;n++){let o=t.ClaimReward[n],r=Se(o.parsedJson.coin_type.name),i=o.parsedJson.liquidity_amount;e[r]=`${+(e[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",e),{txType:Ht.Other,type:"claim",intentionData:{value:e}}}decodeClaimAndDeposit(){return{txType:Ht.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};import{Transaction as mp}from"@mysten/sui/transactions";import pp from"sort-keys-recursive";var j=class{constructor(t){this.data=t}serialize(){return JSON.stringify(pp(this.data))}};var ua=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("BorrowIntention.build",n,o,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new mp;return await r.borrowAndSendToUser(o.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("BorrowIntention.fromData",e),new a(e)}};import{Transaction as yp}from"@mysten/sui/transactions";import{normalizeStructTag as fp}from"@mysten/sui/utils";import{isSendPoints as bp}from"@suilend/frontend-sui";import{Side as we}from"@suilend/sdk";import gp from"bignumber.js";var hp=(a,t)=>{let e={[we.DEPOSIT]:[],[we.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[we.DEPOSIT,we.BORROW].forEach(o=>{let r=o===we.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,i=t.userRewardManagers.find(s=>s.poolRewardManagerId===r.id);i&&(e[o]=r.poolRewards.map((s,c)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(c),rewardCoinType:fp(s.coinType.name),side:o})).filter(s=>!bp(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new gp(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(e).flat()},pa=hp;var ma=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimIntention.build",n,o,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new yp;return r.claimRewardsAndSendToUser(o.address,i.id,pa(r,s),c),c}static fromData(e){return console.log("ClaimIntention.fromData",e),new a(e)}};import{Transaction as Sp}from"@mysten/sui/transactions";var fa=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimAndDepositIntention.build",n,o,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Sp;return r.claimRewardsAndDeposit(o.address,i.id,pa(r,s),c),c}static fromData(e){return console.log("ClaimAndDepositIntention.fromData",e),new a(e)}};import{Transaction as wp}from"@mysten/sui/transactions";var ba=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;console.log("DepositIntention.build",n,o,r,i,s);let c=new wp;return await r.depositIntoObligation(o.address,this.data.coinType,this.data.value,c,i?.id),c}static fromData(e){return console.log("DepositIntention.fromData",e),new a(e)}};import{Transaction as Tp}from"@mysten/sui/transactions";var ga=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("RepayIntention.build",n,o,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Tp;return await r.repayIntoObligation(o.address,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("RepayIntention.fromData",e),new a(e)}};import{Transaction as Cp}from"@mysten/sui/transactions";var ha=class a extends j{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("WithdrawIntention.build",n,o,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new Cp;return await r.withdrawAndSendToUser(o.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("WithdrawIntention.fromData",e),new a(e)}};var ya=async(a,t)=>{let e=await si.initialize(kp,Dp,a),n=await si.getObligationOwnerCaps(t.address,e.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(r=>si.getObligation(r.obligationId,e.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",e,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:e,obligationOwnerCaps:n,obligations:o}},Sa=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:o}=t;this.utils||(this.utils=await ya(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:e});console.log("SuilendAppHelper.deserialize - simResult:",r,"utils:",this.utils,"suiClient:",n);let s=new da(e,r).decode();return{txType:Ip.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:o,suiClient:r,account:i}=t;this.utils||(this.utils=await ya(r,i));let s;switch(n){case"deposit":s=ba.fromData(o);break;case"withdraw":s=ha.fromData(o);break;case"borrow":s=ua.fromData(o);break;case"repay":s=ga.fromData(o);break;case"claim":s=ma.fromData(o);break;case"claimAndDeposit":s=fa.fromData(o);break;default:throw new Error("not implemented")}let c=window.localStorage.getItem("obligationId"),d=this.utils.obligations?.find(u=>u.id===c)??this.utils.obligations?.[0],l=this.utils.obligationOwnerCaps?.find(u=>u.obligationId===d?.id);return s.build({network:e,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:l,obligation:d})}};var ci=async(a,t)=>{let e=await ya(a,t),n=await(await fetch(`${Tc}/liquid-staking-info-map.json`)).json();return{...e,LIQUID_STAKING_INFO_MAP:n}};var wa=class{constructor(t,e){this.transaction=t;this.simResult=e}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(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}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 t={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},e=vt(t.MintEvent.parsedJson.event.typename.name),n=t.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:Te.Other,type:"stake",intentionData:{amount:n,outCoinType:e}}}decodeStakeAndDeposit(){let t={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},e=vt(t.MintEvent.parsedJson.event.typename.name),n=t.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:Te.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:e}}}decodeConvert(){let t={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},e=vt(t.RedeemEvent.parsedJson.event.typename.name),n=vt(t.MintEvent.parsedJson.event.typename.name),o=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:Te.Other,type:"convert",intentionData:{amount:o,inCoinType:e,outCoinType:n}}}decodeConvertAndDeposit(){let t={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},e=vt(t.RedeemEvent.parsedJson.event.typename.name),n=vt(t.MintEvent.parsedJson.event.typename.name),o=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:Te.Other,type:"convertAndDeposit",intentionData:{amount:o,inCoinType:e,outCoinType:n}}}decodeUnstake(){let t={RedeemEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::RedeemEvent"))},e=vt(t.RedeemEvent.parsedJson.event.typename.name),n=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:Te.Other,type:"unstake",intentionData:{amount:n,inCoinType:e}}}};import{Transaction as Ap}from"@mysten/sui/transactions";import{convertLstsAndSendToUser as Op,LstClient as Dc}from"@suilend/springsui-sdk";import vp from"sort-keys-recursive";var V=class{constructor(t){this.data=t}serialize(){return JSON.stringify(vp(this.data))}};var Ta=class a extends V{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=e;console.log("ConvertIntention.build",n,o,r,i,s,c);let d=await Dc.initialize(n,Object.values(i).find(p=>p.type===this.data.inCoinType)),l=await Dc.initialize(n,Object.values(i).find(p=>p.type===this.data.outCoinType)),u=new Ap;return Op(d,l,u,o.address,this.data.amount),u}static fromData(e){return console.log("ConvertIntention.fromData",e),new a(e)}};import{Transaction as Pp}from"@mysten/sui/transactions";import{createObligationIfNoneExists as Rp,sendObligationToUser as _p}from"@suilend/sdk";import{convertLsts as Bp,LstClient as xc}from"@suilend/springsui-sdk";var Ca=class a extends V{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=e;console.log("ConvertAndDepositIntention.build",n,o,r,i,s,c);let d=await xc.initialize(n,Object.values(i).find(y=>y.type===this.data.inCoinType)),l=await xc.initialize(n,Object.values(i).find(y=>y.type===this.data.outCoinType)),u=new Pp,{obligationOwnerCapId:p,didCreate:m}=Rp(r,u,s),b=Bp(d,l,u,o.address,this.data.amount);return r.deposit(b,this.data.outCoinType,p,u),m&&_p(p,o.address,u),u}static fromData(e){return console.log("ConvertAndDepositIntention.fromData",e),new a(e)}};import{Transaction as Mp}from"@mysten/sui/transactions";import{LstClient as Ep}from"@suilend/springsui-sdk";var Ia=class a extends V{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=e;console.log("StakeIntention.build",n,o,r,i,s,c);let d=await Ep.initialize(n,Object.values(i).find(u=>u.type===this.data.outCoinType)),l=new Mp;return d.mintAmountAndRebalanceAndSendToUser(l,o.address,this.data.amount),l}static fromData(e){return console.log("StakeIntention.fromData",e),new a(e)}};import{Transaction as Np}from"@mysten/sui/transactions";import{createObligationIfNoneExists as jp,sendObligationToUser as Wp}from"@suilend/sdk";import{LstClient as Lp}from"@suilend/springsui-sdk";var ka=class a extends V{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=e;console.log("StakeAndDepositIntention.build",n,o,r,i,s,c);let d=await Lp.initialize(n,Object.values(i).find(b=>b.type===this.data.outCoinType)),l=new Np,{obligationOwnerCapId:u,didCreate:p}=jp(r,l,s),m=d.mintAmountAndRebalance(l,o.address,this.data.amount);return r.deposit(m,this.data.outCoinType,u,l),p&&Wp(u,o.address,l),l}static fromData(e){return console.log("StakeAndDepositIntention.fromData",e),new a(e)}};import{Transaction as Up}from"@mysten/sui/transactions";import{LstClient as Fp}from"@suilend/springsui-sdk";var Da=class a extends V{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:i,obligationOwnerCap:s,obligation:c}=e;console.log("UnstakeIntention.build",n,o,r,i,s,c);let d=await Fp.initialize(n,Object.values(i).find(u=>u.type===this.data.inCoinType)),l=new Up;return d.redeemAmountAndSendToUser(l,o.address,this.data.amount),l}static fromData(e){return console.log("UnstakeIntention.fromData",e),new a(e)}};var xa=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:o}=t;this.utils||(this.utils=await ci(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:e});console.log("SpringSuiAppHelper.deserialize",r);let s=new wa(e,r).decode();return{txType:qp.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:o,suiClient:r,account:i}=t;this.utils||(this.utils=await ci(r,i));let s;switch(n){case"stake":s=Ia.fromData(o);break;case"stakeAndDeposit":s=ka.fromData(o);break;case"convert":s=Ta.fromData(o);break;case"convertAndDeposit":s=Ca.fromData(o);break;case"unstake":s=Da.fromData(o);break;default:throw new Error("not implemented")}return s.build({network:e,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 Qp}from"@msafe/sui3-utils";import{TransactionType as vc}from"@msafe/sui3-utils";var va=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isMintTransaction()){let t=this.getLiquidityChangeEvent("MintEvent");if(!t)throw new Error("No liquidity change event found. Unable to decode transaction.");let e=t.parsedJson;return console.log("Decoder event data - ",e),this.decodeMint(e)}if(this.isRedeemTransaction()){let t=this.getLiquidityChangeEvent("RedeemEvent");if(!t)throw new Error("No liquidity change event found. Unable to decode transaction.");let e=t.parsedJson;return console.log("Decoder event data - ",e),this.decodeRedeem(e)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getLiquidityChangeEvent(t){return this.simResult.events.find(e=>this.isLiquidityChangeEventType(e.type,t))}isLiquidityChangeEventType(t,e){return t.includes(e)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(t){let{event:{sui_amount_in:e}}=t;return console.log("Decoder.decodeMint",e),{txType:vc.Other,type:"mint",intentionData:{amount:e}}}decodeRedeem(t){let{event:{lst_amount_in:e}}=t;return console.log("Decoder.decodeRedeem",e),{txType:vc.Other,type:"redeem",intentionData:{amount:e}}}};import{LST as Kp}from"@alphafi/stsui-sdk";var Aa=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:o}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},s=await new Kp(r).mint(o,n.address);return s.setGasBudget(1e8),s}static fromData(e){return console.log("MintIntention.fromData",e),new a(e)}};import{LST as Vp}from"@alphafi/stsui-sdk";var Oa=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:o}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},s=await new Vp(r).redeem(o,n.address);return s.setGasBudget(1e8),s}static fromData(e){return console.log("RedeemIntention.fromData",e),new a(e)}};var Pa=class{application="stsui";supportSDK="@mysten/sui";async deserialize(t){let{transaction:e,suiClient:n}=t,o=await n.devInspectTransactionBlock({sender:e.getData().sender,transactionBlock:e});console.log("StSuiHelper Sim result - ",o);let i=new va(e,o).decode();return{txType:Qp.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{account:e}=t;console.log("StSui build transaction type",t.txSubType);let n;switch(t.txSubType){case"mint":n=Aa.fromData(t.intentionData);break;case"redeem":n=Oa.fromData(t.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:e})}};import{TransactionType as mm}from"@msafe/sui3-utils";import{TurbosSdk as fm}from"turbos-clmm-sdk";import{TransactionType as Q}from"@msafe/sui3-utils";import{bcs as Ac}from"@mysten/sui.js/bcs";import{normalizeStructTag as Gp,normalizeSuiAddress as Ce}from"@mysten/sui.js/utils";import{BN as zp}from"turbos-clmm-sdk";var G={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},z={PackageId:"0xdee9"};var Jp=(a,t,e,n)=>{if(a===1)switch(n.findIndex(i=>i===t)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${t}`)}switch(e.findIndex(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},Ra=class{constructor(t,e,n){this.txb=t;this.turbosSdk=e;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(t){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}getMoveCallsTransaction(t){return t.every(e=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===e))}getSwapMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&t.includes(e.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${G.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${z.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${z.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let t=this.transactions.find(m=>m.kind==="MoveCall"),e=0;this.swap2Layer.includes(t.target)&&(e=1);let n=Jp(e,t.target,this.swap1Layer,this.swap2Layer),o=n.map((m,b)=>{let y=this.helper.decodeSharedObjectId(b),w=this.helper.decodeInputU128(4+b+e),D=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new zp(w.toString()));return{pool:y,a2b:m,nextTickIndex:D}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),d=this.helper.decodeInputBool(5+2*e),l=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:o[0].pool,a2b:o[0].a2b,amountSpecified:l}],address:s,amountSpecifiedIsInput:d});return{txType:Q.Other,type:"Swap",intentionData:{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:d?l:u,amountB:d?u:l,amountSpecifiedIsInput:d,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),d=this.helper.decodeInputU64(13);return{txType:Q.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:o,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:d}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:Q.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:o,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:Q.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:Q.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:o,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:Q.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:o,nft:e,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:Q.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){console.log(this.helper,"decodeRemoveLiquidity this.helper");let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),d=this.collectFeeHelper.decodeInputU64(3)||0,l=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:Q.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:o,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:d,collectAmountB:l,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:Q.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:Q.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:Q.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:Q.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:o}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new wt(t,this.txb)}get collectRewardHelper(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect_reward`).map(e=>new wt(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new wt(t,this.txb)}get decreaseLiquidityHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new wt(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${z.PackageId}::clob_v2::swap_exact_base_for_quote`);return new wt(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${z.PackageId}::clob_v2::swap_exact_quote_for_base`);return new wt(t,this.txb)}},wt=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU128(t){let e=this.decodePureArg(t,"u128");return Number(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU32(t){let e=this.decodePureArg(t,"u32");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return Ce(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Ac.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return Ce(t.value.Object.ImmOrOwned.objectId)}return Ce(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return Ce(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return Ce(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ac.de(e,new Uint8Array(n))}typeArg(t){return Gp(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as Yp}from"turbos-clmm-sdk";var _a=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Yp(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,tickLower:d,tickUpper:l,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,tickLower:d,tickUpper:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as Xp}from"turbos-clmm-sdk";var Ba=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Xp(e.network.replace("sui:",""),e.suiClient),{pool:o,nft:r,txb:i}=this.data;return n.nft.burn({pool:o,nft:r,txb:i})}static fromData(e){return new a(e)}};import{TurbosSdk as Zp}from"turbos-clmm-sdk";var Ma=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Zp(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:d,txb:l}=this.data;return n.pool.collectFee({pool:o,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:d,txb:l})}static fromData(e){return new a(e)}};import{TurbosSdk as tm}from"turbos-clmm-sdk";var Ea=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new tm(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,nft:i,rewardAmounts:s,deadline:c,txb:d}=this.data;return n.pool.collectReward({pool:o,address:r,rewardAmounts:s,nft:i,deadline:c,txb:d})}static fromData(e){return new a(e)}};import{TurbosSdk as em}from"turbos-clmm-sdk";var Na=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new em(e.network.replace("sui:",""),e.suiClient),{fee:o,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,amountA:p,amountB:m,deadline:b,txb:y}=this.data;return n.pool.createPool({fee:o,amountA:p,amountB:m,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:d,coinTypeA:l,coinTypeB:u,deadline:b,txb:y})}static fromData(e){return new a(e)}};import{TurbosSdk as nm}from"turbos-clmm-sdk";var ja=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new nm(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:d,decreaseLiquidity:l,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:d,decreaseLiquidity:l,deadline:u,txb:p})}static fromData(e){return new a(e)}};import{TurbosSdk as om}from"turbos-clmm-sdk";var Wa=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new om(e.network.replace("sui:",""),e.suiClient),{pool:o,address:r,amountA:i,amountB:s,slippage:c,nft:d,deadline:l,txb:u}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:c,address:r,amountA:i,amountB:s,nft:d,deadline:l,txb:u})}static fromData(e){return new a(e)}};import{TransactionBlock as am}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as rm}from"@mysten/sui.js/utils";var La=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new am;return n.moveCall({target:`${G.PackageId}::claim::claim`,typeArguments:[G.turbosCoinType],arguments:[n.object(G.Claim),n.object(rm)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as im}from"@mysten/sui.js/transactions";var Ua=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new im;return n.moveCall({target:`${G.PackageId}::claim::join`,typeArguments:[G.turbosCoinType],arguments:[n.object(G.Claim)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as sm}from"@mysten/sui.js/transactions";import{TurbosSdk as cm}from"turbos-clmm-sdk";var Fa=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new cm(e.network.replace("sui:",""),e.suiClient),o=new sm;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(e){return new a(e)}};import{TurbosSdk as lm}from"turbos-clmm-sdk";var qa=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new lm(e.network.replace("sui:",""),e.suiClient),{routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:d,slippage:l,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:o,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:d,amountSpecifiedIsInput:u,slippage:l,deadline:p,txb:m})}static fromData(e){return new a(e)}};import{TurbosSdk as um}from"turbos-clmm-sdk";import{TransactionBlock as Oc}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as Pc}from"@mysten/sui.js/utils";import{unstable_getObjectId as dm}from"turbos-clmm-sdk";var Ie=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let o=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),o.push(...r.data);while(r.hasNextPage);let i=[],s=0;return o.sort((c,d)=>Number(d.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let o=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(o,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(o,[n.pure(e)]);return[r,o]}isSuiCoinAddress(t){return t.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(t){let e=await this.turbosSdk.provider.getOwnedObjects({owner:t,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${z.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?dm(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${z.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var Rc=89,_c=1e6,Bc=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Oc,c=new Ie(i),d=await c.getCoinsData(r,e,o),[l,u]=c.splitAndMergeCoin(d,o,s);if(!l)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),[b,y,w]=s.moveCall({typeArguments:[t,e],target:`${z.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(Rc),m,s.pure(o),s.object(Pc("0x6")),l]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([b],s.pure(r)),s.transferObjects([y],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(_c),s},Mc=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new Oc,c=new Ie(i),d=await c.getCoinsData(r,t,o),[l,u]=c.splitAndMergeCoin(d,o,s);if(!l)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),b=c.zero(e,s),[y,w,D]=s.moveCall({typeArguments:[t,e],target:`${z.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(Rc),m,s.pure(o),l,b,s.object(Pc("0x6"))]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([y],s.pure(r)),s.transferObjects([w],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(_c),s};var $a=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new um(e.network.replace("sui:",""),e.suiClient);return await Mc({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};import{TurbosSdk as pm}from"turbos-clmm-sdk";var Ka=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new pm(e.network.replace("sui:",""),e.suiClient);return await Bc({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var Va=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new fm(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:o,account:r}=t;console.log(t,"input");let s=await new Ra(o,e,n).decode(r.address);return{txType:mm.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t,r;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":r=Na.fromData(t.intentionData);break;case"AddLiquidity":r=_a.fromData(t.intentionData);break;case"IncreaseLiquidity":r=Wa.fromData(t.intentionData);break;case"DecreaseLiquidity":r=ja.fromData(t.intentionData);break;case"RemoveLiquidity":r=Fa.fromData(t.intentionData);break;case"CollectFee":r=Ma.fromData(t.intentionData);break;case"CollectReward":r=Ea.fromData(t.intentionData);break;case"Burn":r=Ba.fromData(t.intentionData);break;case"Swap":r=qa.fromData(t.intentionData);break;case"PrixJoin":r=Ua.fromData(t.intentionData);break;case"PrixClaim":r=La.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=$a.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=Ka.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as Tm}from"@msafe/sui3-utils";import{TransactionType as li}from"@msafe/sui3-utils";import{bcs as Ec}from"@mysten/sui.js/bcs";import{normalizeStructTag as hm,normalizeSuiAddress as ke}from"@mysten/sui.js/utils";var bm={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},v=bm;var Qa=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${v.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${v.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${v.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:li.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:li.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:li.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(v.packageId));return new di(t,this.txb)}},di=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return ke(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Ec.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return ke(t.value.Object.ImmOrOwned.objectId)}return ke(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return ke(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return ke(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ec.de(e,new Uint8Array(n))}typeArg(t){return hm(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as ym}from"@mysten/sui.js/transactions";var Ha=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new ym,{ticketId:o}=this.data;return n.moveCall({target:`${v.packageId}::native_pool::burn_ticket`,arguments:[n.object(v.poolObjectId),n.object(v.systemStateObjectId),n.object(o)]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as Sm}from"@mysten/sui.js/transactions";var Ga=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Sm,{amount:o}=this.data,[r]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${v.packageId}::native_pool::stake`,arguments:[n.object(v.poolObjectId),n.object(v.metadataObjectId),n.object(v.systemStateObjectId),r]}),n}static fromData(e){return new a(e)}};import{TransactionBlock as wm}from"@mysten/sui.js/transactions";var za=class a extends h{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new wm,{amount:o}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(l=>l.coinType.split("::")[0]===v.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(l=>n.object(l.coinObjectId)));let d=n.splitCoins(n.object(i.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${v.packageId}::native_pool::unstake`,arguments:[n.object(v.poolObjectId),n.object(v.metadataObjectId),n.object(v.systemStateObjectId),d]}),n}static fromData(e){return new a(e)}};var Ja=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,o=new Qa(e).decode();return{txType:Tm.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(t.txSubType){case"Stake":o=Ga.fromData(t.intentionData);break;case"UnStake":o=za.fromData(t.intentionData);break;case"ClaimTicket":o=Ha.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};import{TransactionType as _m}from"@msafe/sui3-utils";import{asIntN as Nc}from"@cetusprotocol/cetus-sui-clmm-sdk";import{TransactionType as At}from"@msafe/sui3-utils";import{fromBase64 as De}from"@mysten/bcs";import{bcs as xe}from"@mysten/sui/bcs";var Ya=class{constructor(t){this.transaction=t}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 t=this.getMoveCallCommand("open_position"),e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:At.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,1)),lowerTick:Number(Nc(BigInt(this.getU32(this.getInputIndex(t,2)))).toString()),upperTick:Number(Nc(BigInt(this.getU32(this.getInputIndex(t,3)))).toString()),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))}}}decodeClosePositionTx(){let t=this.getMoveCallCommand("close_position"),e=this.getCollectRewardCallData();return{txType:At.Other,type:"ClosePosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),transferTokensTo:this.getAddress(this.getInputIndex(t,4)),collectRewardTokens:e.map(n=>n.rewardCoinType),collectFeeTokens:this.getTypeArguments(t)}}}decodeProvideLiquidityTx(){let t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:At.Other,type:"ProvideLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),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))}}}decodeRemoveLiquidityTx(){let t=this.getMoveCallCommand("remove_liquidity");return{txType:At.Other,type:"RemoveLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),liquidity:this.getU128(this.getInputIndex(t,4)),maxAmountTokenA:this.getU64(this.getInputIndex(t,5)),maxAmountTokenB:this.getU64(this.getInputIndex(t,6)),transferTokensTo:this.getAddress(this.getInputIndex(t,7)),...this.collectTokens()}}}decodeCollectRewardsTx(){let t=this.getCollectRewardCallData();return{txType:At.Other,type:"CollectRewards",intentionData:{pool:t[0].pool,position:t[0].position,collectRewardTokens:t.map(e=>e.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:At.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let t=this.getFeeCallData();return{txType:At.Other,type:"CollectRewardsAndFee",intentionData:{pool:t.pool,position:t.position,...this.collectTokens()}}}getFeeCallData(){let t=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),collectFeeTokens:this.getTypeArguments(t)}}getCollectRewardCallData(){let t=[];return this.commands.forEach(e=>{e.$kind==="MoveCall"&&e.MoveCall.function==="collect_reward"&&t.push({pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),rewardCoinType:this.getTypeArguments(e)[2]})}),t}collectTokens(){let t=this.getFeeCallData(),e=this.getCollectRewardCallData();return{collectFeeTokens:t.collectFeeTokens,collectRewardTokens:e.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(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getSharedObjectID(t){return this.inputs[t].Object.SharedObject.objectId}getOwnedObjectID(t){return this.inputs[t].Object.ImmOrOwnedObject.objectId}getU32(t){return String(xe.u32().parse(Uint8Array.from(De(this.inputs[t].Pure.bytes))))}getU64(t){return xe.u64().parse(Uint8Array.from(De(this.inputs[t].Pure.bytes)))}getU128(t){return xe.u128().parse(Uint8Array.from(De(this.inputs[t].Pure.bytes)))}getBoolean(t){return xe.bool().parse(Uint8Array.from(De(this.inputs[t].Pure.bytes)))}getAddress(t){return xe.Address.parse(Uint8Array.from(De(this.inputs[t].Pure.bytes)))}getTypeArguments(t){return t.MoveCall.typeArguments||[]}getInputIndex(t,e){return t.MoveCall.arguments[e].Input}};import{TransactionType as Dm}from"@msafe/sui3-utils";import{BN as Ot,ClmmPoolUtil as km}from"@firefly-exchange/library-sui";import{SuiClient as Cm}from"@firefly-exchange/library-sui";import{OnChainCalls as Im}from"@firefly-exchange/library-sui/dist/src/spot";var jc={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x6c796c3ab3421a68158e0df18e4657b2827b1f8fed5ed4b82dba9c935988711b"}},Ct=(a,t)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let e=new Cm({url:jc.rpc});return new Im(e,jc.objects,{address:t.address,isUIWallet:!1})};var B=class{static async OpenPosition(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,{...t,slippage:0});return await o.openPositionWithFixedAmount(r,t.lowerTick,t.upperTick,i,{returnTx:!0,sender:e.address})}static async provideLiquidity(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await o.provideLiquidityWithFixedAmount(r,t.position,i,{returnTx:!0,sender:e.address})}static async removeLiquidity(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool);return await o.removeLiquidity(r,t.position,{liquidityAmount:new Ot(t.liquidity),tokenMaxA:new Ot(t.maxAmountTokenA),tokenMaxB:new Ot(t.maxAmountTokenB)},{returnTx:!0,sender:e.address})}static async closePosition(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool);return await o.closePosition(r,t.position,{returnTx:!0,sender:e.address})}static async collectRewards(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool);return await o.collectRewards(r,t.position,{rewardCoinsType:t.collectRewardTokens,returnTx:!0,sender:e.address})}static async collectFee(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool);return await o.collectFee(r,t.position,{returnTx:!0,sender:e.address})}static async collectRewardsAndFee(t,e,n){let o=Ct(n,e),r=await o.queryChain.getPool(t.pool);return console.log(t.position),await o.collectFeeAndRewards(r,t.position,{returnTx:!0,sender:e.address})}buildLiqInput(t,e){return{...km.estLiquidityAndCoinAmountFromOneAmounts(e.lowerTick,e.upperTick,new Ot(e.tokenAmount),e.isTokenAFixed,!0,0,new Ot(t.current_sqrt_price)),tokenMaxA:new Ot(e.maxAmountTokenA),tokenMaxB:new Ot(e.maxAmountTokenB)}}};var Xa=class a extends f{constructor(e){super(e);this.data=e}txType=Dm.Other;txSubType="ClosePosition";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.closePosition(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as xm}from"@msafe/sui3-utils";var Za=class a extends f{constructor(e){super(e);this.data=e}txType=xm.Other;txSubType="CollectFee";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.collectFee(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as vm}from"@msafe/sui3-utils";var tr=class a extends f{constructor(e){super(e);this.data=e}txType=vm.Other;txSubType="CollectRewards";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.collectRewards(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Am}from"@msafe/sui3-utils";var er=class a extends f{constructor(e){super(e);this.data=e}txType=Am.Other;txSubType="CollectRewardsAndFee";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.collectRewardsAndFee(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Om}from"@msafe/sui3-utils";var nr=class a extends f{constructor(e){super(e);this.data=e}txType=Om.Other;txSubType="OpenPosition";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.OpenPosition(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Pm}from"@msafe/sui3-utils";var or=class a extends f{constructor(e){super(e);this.data=e}txType=Pm.Other;txSubType="ProvideLiquidity";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.provideLiquidity(this.data,n,o)}static fromData(e){return new a(e)}};import{TransactionType as Rm}from"@msafe/sui3-utils";var ar=class a extends f{constructor(e){super(e);this.data=e}txType=Rm.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e;return console.log(this.data),B.removeLiquidity(this.data,n,o)}static fromData(e){return new a(e)}};var rr=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(t){console.log("Bluefin helper deserialize input: ",t);let{transaction:e}=t,o=new Ya(e).decode();return{txType:_m.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n,network:o}=t;console.log(t.txSubType);let r;switch(t.txSubType){case"OpenPosition":r=nr.fromData(t.intentionData);break;case"ProvideLiquidity":r=or.fromData(t.intentionData);break;case"RemoveLiquidity":r=ar.fromData(t.intentionData);break;case"ClosePosition":r=Xa.fromData(t.intentionData);break;case"CollectFee":r=Za.fromData(t.intentionData);break;case"CollectRewards":r=tr.fromData(t.intentionData);break;case"CollectRewardsAndFee":r=er.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};import{TransactionType as qm}from"@msafe/sui3-utils";import{KriyaSDK as Bm}from"kriya-dev-sdk";var ir=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Bm,{params:n}=this.data;return e.Amm.getTxbAddLiquidity(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Mm}from"kriya-dev-sdk";var sr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Mm,{params:n}=this.data;return e.Amm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Em}from"kriya-dev-sdk";var cr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Em,{params:n}=this.data;return e.Amm.getTxbClaimRewards(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Nm}from"kriya-dev-sdk";var lr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Nm,{params:n}=this.data;return e.Amm.getTxbRemoveLiquidity(n)}static fromData(e){return new a(e)}};import{KriyaSDK as jm}from"kriya-dev-sdk";var dr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new jm,{params:n}=this.data;return e.Clmm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Wm}from"kriya-dev-sdk";var ur=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Wm,{params:n}=this.data;return e.Clmm.getTxbAddLiquidity(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Lm}from"kriya-dev-sdk";var pr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Lm,{params:n}=this.data;return e.Clmm.getTxbClaimMayaRewards(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Um}from"kriya-dev-sdk";var mr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Um,{params:n}=this.data;return e.Clmm.getTxbClaimRewards(n)}static fromData(e){return new a(e)}};import{KriyaSDK as Fm}from"kriya-dev-sdk";var fr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Fm,{params:n}=this.data;return e.Clmm.getTxbRemoveLiquidity(n)}static fromData(e){return new a(e)}};var br=class{application="kriya";supportSDK="@mysten/sui";async deserialize(t){let{appContext:e}=t;return{txType:qm.Other,txSubType:e.action,intentionData:e}}async build(t){let e;switch(t.txSubType){case"AddLiquidity":e=ir.fromData(t.intentionData);break;case"AddLiquiditySingleSided":e=sr.fromData(t.intentionData);break;case"RemoveLiquidity":e=lr.fromData(t.intentionData);break;case"ClaimRewards":e=cr.fromData(t.intentionData);break;case"ClaimRewardsV3":e=mr.fromData(t.intentionData);break;case"ClaimV3MayaRewards":e=pr.fromData(t.intentionData);break;case"AddLiquidityV3":e=ur.fromData(t.intentionData);break;case"AddLiquiditySingleSideV3":e=dr.fromData(t.intentionData);break;case"RemoveLiquidityV3":e=fr.fromData(t.intentionData);break;default:throw new Error("not implemented")}return e.build()}};var q6=fo.fromHelpers([new Zn,new lo,new Jn,new uo,new kn,new Va,new br,new la,new Ja,new Ze,new Sa,new xa,new Ee,new rr,new Pa]);export{q6 as appHelpers};
|
|
1
|
+
var as=Object.defineProperty;var cr=(o,e)=>{for(var t in e)as(o,t,{get:e[t],enumerable:!0})};import{TransactionType as fs}from"@msafe/sui3-utils";import{coinsList as rs,poolIdPoolNameMap as is,poolInfo as lr,singleAssetPoolCoinMap as ss}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=is[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}=ss[e],{expo:i}=rs[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 ls}from"@alphafi/alphafi-sdk";import cs from"sort-keys-recursive";var u=class{constructor(e){this.data=e}serialize(){return JSON.stringify(cs(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 ls(n.address)}static fromData(t){return new o(t)}};import{depositDoubleAssetTxb as ds}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 ds(a,n.address,r,i)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new o(t)}};import{depositSingleAssetTxb as us}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 us(a,n.address,r)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new o(t)}};import{withdrawTxb as ms}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 ms(r,a,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new o(t)}};import{withdrawAlphaTxb as ps}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 ps(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:fs.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 Ns}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 ys}from"@msafe/sui3-utils";import{Transaction as hs}from"@mysten/sui/transactions";import{buildPsmTx as gs}from"bucket-protocol-sdk";import{BucketClient as bs}from"bucket-protocol-sdk";var x=(o,e)=>{let t=o==="sui:mainnet"?"mainnet":"testnet";return new bs(t,e.address)};var dr=async(o,e,t)=>{let{coinType:n,amount:a,buckToCoin:r}=o,i=new hs,s=x(t,e);return await gs(s,i,n,a,r,e.address),i};var de=class o extends u{constructor(t){super(t);this.data=t}txType=ys.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 ws}from"@msafe/sui3-utils";import{Transaction as ue}from"@mysten/sui/transactions";import{buildBorrowTx as Ts,buildCloseTx as Cs,buildRepayTx as Is,buildWithdrawTx as Ss}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 Ts(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 Ss(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 Is(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 Cs(s,i,n,a,r),i};var me=class o extends u{constructor(t){super(t);this.data=t}txType=ws.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 ks}from"@msafe/sui3-utils";var pe=class o extends u{constructor(t){super(t);this.data=t}txType=ks.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 xs}from"@msafe/sui3-utils";var fe=class o extends u{constructor(t){super(t);this.data=t}txType=xs.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 Ds}from"@msafe/sui3-utils";var be=class o extends u{constructor(t){super(t);this.data=t}txType=Ds.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 vs,buildSBUCKDepositTx as As,buildSBUCKUnstakeTx as Os,buildSBUCKWithdrawTx as Ps}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 As(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 Os(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 Ps(r,a,n,e.address),a},yr=async(o,e,t)=>{let{stakeProofs:n}=o,a=new he,r=x(t,e);return await vs(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 Rs,buildTankDepositTx as Bs,buildTankWithdrawTx as _s}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 Bs(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 _s(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 Rs(r,a,n,e.address),a};import{Transaction as Es}from"@mysten/sui/transactions";import{buildLockedClaimTx as Ms}from"bucket-protocol-sdk";var Sr=async(o,e,t)=>{let{coinType:n,proofCount:a}=o,r=new Es,i=x(t,e);return await Ms(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 Ws}from"@msafe/sui3-utils";var xe=class o extends u{constructor(t){super(t);this.data=t}txType=Ws.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:Ns.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 Ic}from"@msafe/sui3-utils";import{TransactionType as zs}from"@msafe/sui3-utils";import{AggregatorClient as Ls,Env as wr}from"@cetusprotocol/aggregator-sdk";import{CetusPeripherySDK as js}from"@cetusprotocol/cetus-periphery-sdk";import{CetusClmmSDK as Us}from"@cetusprotocol/cetus-sui-clmm-sdk";import{CetusXcetusSDK as Fs}from"@cetusprotocol/cetus-xcetus-sdk";import qs from"@cetusprotocol/vaults-sdk";import{SuiClient as Ks,getFullnodeUrl as kr}from"@mysten/sui/client";var $s={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"},Vs={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:""}}},Hs={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=$s,n=new Us(t);return n.senderAddress=e.address,n},F=(o,e)=>{let t=at(o,e),n=Vs;return new js(n,t)},Gs="https://api-sui.cetus.zone/router_v2/find_routes",xr=(o,e)=>{let t=new Ks({url:"https://fullnode.mainnet.sui.io/"});return new Ls(Gs,e.address,t,wr.Mainnet)},Qs={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 qs(Qs);return t.senderAddress=e.address,t},dt=(o,e)=>{let t=new Fs(Hs);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=zs.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 Js}from"@msafe/sui3-utils";var Ae=class o extends u{constructor(t){super(t);this.data=t}txType=Js.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 Ys}from"@msafe/sui3-utils";var Oe=class o extends u{constructor(t){super(t);this.data=t}txType=Ys.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 Xs}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=Xs.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 Zs}from"@msafe/sui3-utils";var Re=class o extends u{constructor(t){super(t);this.data=t}txType=Zs.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 tc}from"@msafe/sui3-utils";var Be=class o extends u{constructor(t){super(t);this.data=t}txType=tc.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 ec}from"@msafe/sui3-utils";var _e=class o extends u{constructor(t){super(t);this.data=t}txType=ec.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 nc}from"@msafe/sui3-utils";var Ee=class o extends u{constructor(t){super(t);this.data=t}txType=nc.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 ac}from"@msafe/sui3-utils";var Me=class o extends u{constructor(t){super(t);this.data=t}txType=ac.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 oc}from"@msafe/sui3-utils";var We=class o extends u{constructor(t){super(t);this.data=t}txType=oc.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 rc}from"@msafe/sui3-utils";var Ne=class o extends u{constructor(t){super(t);this.data=t}txType=rc.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 ic}from"@msafe/sui3-utils";var Le=class o extends u{constructor(t){super(t);this.data=t}txType=ic.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 sc}from"@msafe/sui3-utils";var je=class o extends u{constructor(t){super(t);this.data=t}txType=sc.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 cc}from"@msafe/sui3-utils";var Ue=class o extends u{constructor(t){super(t);this.data=t}txType=cc.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 uc}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as lc}from"@cetusprotocol/aggregator-sdk";import{Transaction as dc}from"@mysten/sui/transactions";var Ur=async(o,e,t)=>{let n=xr(t,e),a=new dc;return await n.fastRouterSwap({...o,routers:lc(o.routers),txb:a}),a};var Fe=class o extends u{constructor(t){super(t);this.data=t}txType=uc.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 mc}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=mc.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 pc}from"@msafe/sui3-utils";var Ke=class o extends u{constructor(t){super(t);this.data=t}txType=pc.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 bc}from"@msafe/sui3-utils";import{Transaction as fc}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 fc;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=bc.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 hc}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=hc.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 gc}from"@msafe/sui3-utils";var He=class o extends u{constructor(t){super(t);this.data=t}txType=gc.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 yc}from"@msafe/sui3-utils";var Ge=class o extends u{constructor(t){super(t);this.data=t}txType=yc.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 Tc}from"@msafe/sui3-utils";var Qe=class o extends u{constructor(t){super(t);this.data=t}txType=Tc.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 Cc}from"@msafe/sui3-utils";var ze=class o extends u{constructor(t){super(t);this.data=t}txType=Cc.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:Ic.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 Tl}from"@msafe/sui3-utils";import Sc from"sort-keys-recursive";var h=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Sc(this.data))}};import{getFullnodeUrl as Ye}from"@mysten/sui.js/client";var Ao={};cr(Ao,{contractId:()=>xc,default:()=>Pc,feeObjId:()=>Ac,roleObjId:()=>Dc,status:()=>kc,transaction:()=>wc,upgradeCapObjId:()=>Oc,vaultObjId:()=>vc});var wc="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",kc="success",xc="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Dc="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",vc="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Ac="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Oc="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Pc={transaction:wc,status:kc,contractId:xc,roleObjId:Dc,vaultObjId:vc,feeObjId:Ac,upgradeCapObjId:Oc};var Oo={};cr(Oo,{contractId:()=>_c,default:()=>Lc,feeObjId:()=>Wc,roleObjId:()=>Ec,status:()=>Bc,transaction:()=>Rc,upgradeCapObjId:()=>Nc,vaultObjId:()=>Mc});var Rc="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Bc="success",_c="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ec="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Mc="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Wc="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Nc="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Lc={transaction:Rc,status:Bc,contractId:_c,roleObjId:Ec,vaultObjId:Mc,feeObjId:Wc,upgradeCapObjId:Nc};var jc=Ye("testnet"),Uc=Ye("testnet"),Fc=Ye("mainnet"),qc=Ye("mainnet"),Kc="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",$c="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Vc="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Hc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Jr=Ao,Yr=Oo,Gc=new Map([["dev",{env:"dev",rpc:{url:jc},backend:{url:Kc},contract:Jr}],["stg",{env:"stg",rpc:{url:Uc},backend:{url:$c},contract:Jr}],["prev",{env:"prev",rpc:{url:Fc},backend:{url:Vc},contract:Yr}],["prod",{env:"prod",rpc:{url:qc},backend:{url:Hc},contract:Yr}]]);function Xr(o,e){let t=Gc.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 zc}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 Qc}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 Qc)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 zc({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 hl,normalizeStructTag as gl,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 Zc}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 Jc}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 Jc(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"},Yc=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>Yc)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 Xc}from"nanoid";function ii(){return Xc()}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:Zc(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 tl}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 el=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()<el)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||tl);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 ol}from"@mysten/sui.js/utils";import{DateTime as rl}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 nl,Duration as al}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 nl.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 al.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=rl.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}=ol(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 il=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||il,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=>{sl(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 sl(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=ml(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=pl(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 dl(this.globals,e[0].streamId,this.objectIter);return this.current++,gi(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await ul(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,ll(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=cl(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 cl(o,e){return e===void 0?!0:Array.isArray(e)?e.includes(o.progress.status):o.progress.status===e}function ll(o,e){if(!e)return!0;let t=!1;return o.streams.forEach(n=>{gi(n,e)&&(t=!0)}),t}async function dl(o,e,t){let n=await yi(t,e);return Y.fromObjectData(o,e,n)}async function ul(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 ml(o){return{status:Uo(o?.status),coinType:Ti(o?.coinType),sender:Ci(o?.sender)}}function pl(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):fl(o)}function fl(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 bl=25;async function Ii(o,e,t,n="0x2::sui::SUI",a=bl){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,hl))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=>gl(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=Tl.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 Cl}from"@msafe/sui3-utils";var Wt=class extends E{constructor(t){super(t);this.data=t}txType=Cl.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 Il}from"@msafe/sui3-utils";var Nt=class extends E{constructor(t){super(t);this.data=t}txType=Il.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 Sl}from"@msafe/sui3-utils";var Lt=class extends E{constructor(t){super(t);this.data=t}txType=Sl.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 wl,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 wl(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 kl}from"@msafe/sui3-utils";var Ut=class extends E{constructor(t){super(t);this.data=t}txType=kl.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 vl,TransactionSubTypes as ki}from"@msafe/sui3-utils";import{buildCoinTransferTxb as xl}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 xl(n,this.data,a.address)}static fromData(t){return new o(t)}};import{buildObjectTransferTxb as Dl}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 Dl(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=vl}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 ql}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 Ol,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 Ol(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{depositCoin as Pl,withdrawCoin as Rl,repayDebt as Bl,borrowCoin as _l,claimAllRewardsPTB as El,claimAllRewardsResupplyPTB as Ml}from"navi-sdk";async function Ct(o,e,t,n){return await Pl(o,e,t,n),o}async function vi(o,e,t,n){let[a]=await Rl(o,e,t);return o.transferObjects([a],o.pure(n)),o}async function Ai(o,e,t,n){let[a]=await _l(o,e,t);return o.transferObjects([a],o.pure.address(n)),o}async function Ho(o,e,t,n){return await Bl(o,e,t,n),o}async function Oi(o,e){return await El(o,e)}async function Pi(o,e){return await Ml(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 Nl}from"@mysten/sui.js/transactions";import{pool as Wl}from"navi-sdk";function $(o){return Object.values(Wl).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 Nl;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 Ll}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 Ll;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 jl}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 jl;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 Ul}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 Ul;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 Fl}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 Fl;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:ql.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 Kl,TransactionType as Ri}from"@msafe/sui3-utils";import{fromHex as $l}from"@mysten/bcs";import{Transaction as Vl}from"@mysten/sui/transactions";import Hl from"sort-keys-recursive";var Bi="msafe-plain-tx",_i=Kl.others.plain,Go=class o{constructor(e){this.data=e}application=Bi;txType=Ri.Other;txSubType=_i;serialize(){return JSON.stringify(Hl(this.data))}async build(e){return Vl.from($l(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 Zl}from"@mysten/sui/transactions";import{SuiClient as Jo}from"@mysten/sui.js/client";import{TransactionBlock as td}from"@mysten/sui.js/transactions";import{RequestManager as Jl,HTTPTransport as Yl,Client as Xl}from"@open-rpc/client-js";var Gl={"-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=Gl[t]??"ServerError"}};function Ql(o){let e=new URL(o);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var zl={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={...zl,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=Ql(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 Yl(a?.url??e,{headers:{"Content-Type":"application/json",...a?.headers}});this.rpcClient=new Xl(new Jl([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=Zl.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 td.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 dd}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 ed}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}=ed(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 nd,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 nd(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 ad}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(ad)]),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 od}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,`${od}::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 rd from"sort-keys-recursive";var g=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify(rd(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 id}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,id);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 sd}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,sd,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 cd}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,cd,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 ld}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,ld,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:dd.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";var Ui="https://suilend-assets.s3.us-east-2.amazonaws.com/springsui";import{TransactionType as wd}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as kd,LENDING_MARKET_TYPE as xd,SuilendClient as or}from"@suilend/sdk";import{TransactionType as wt}from"@msafe/sui3-utils";import{fromBase64 as Fi,toHex as qi}from"@mysten/bcs";import{normalizeStructTag as Vt}from"@mysten/sui/utils";import{MAX_U64 as kt}from"@suilend/frontend-sui";import Ki 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 Ki(qi(Fi(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 Ki(qi(Fi(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 pd}from"@mysten/sui/transactions";import md from"sort-keys-recursive";var P=class{constructor(e){this.data=e}serialize(){return JSON.stringify(md(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 pd;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 yd}from"@mysten/sui/transactions";import{normalizeStructTag as fd}from"@mysten/sui/utils";import{isSendPoints as bd}from"@suilend/frontend-sui";import{Side as Ht}from"@suilend/sdk";import hd from"bignumber.js";var gd=(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:fd(s.coinType.name),side:a})).filter(s=>!bd(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new hd(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},ya=gd;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 yd;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 Td}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 Td;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 Cd}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 Cd;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 Id}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 Id;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 Sd}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 Sd;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(kd,xd,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:wd.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(await fetch(`${Ui}/liquid-staking-info-map.json`)).json();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 $i}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 $i.initialize(n,Object.values(i).find(p=>p.type===this.data.inCoinType)),d=await $i.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 Vi}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 Vi.initialize(n,Object.values(i).find(y=>y.type===this.data.inCoinType)),d=await Vi.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 Hi}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:Hi.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Hi.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 Gi}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 Gi.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 Gi.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 Qi}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as zi}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 Ji=89,Yi=1e6,Xi=async o=>{let{token1:e,token2:t,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Qi,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(Ji),f,s.pure(a),s.object(zi("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(Yi),s},Zi=async o=>{let{token1:e,token2:t,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Qi,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(Ji),f,s.pure(a),d,b,s.object(zi("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(Yi),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 Zi({...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 Xi({...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 ts}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 ts.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 ts.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 es}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(es(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number(es(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 ns={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:ns.rpc});return new wu(t,ns.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};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|