@msafe/sui-app-store 0.0.197 → 0.0.198
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 +5 -4
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Cu=Object.create;var en=Object.defineProperty;var Iu=Object.getOwnPropertyDescriptor;var ku=Object.getOwnPropertyNames;var Du=Object.getPrototypeOf,xu=Object.prototype.hasOwnProperty;var Wr=(o,t)=>{for(var e in t)en(o,e,{get:t[e],enumerable:!0})},Ui=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ku(t))!xu.call(o,a)&&a!==e&&en(o,a,{get:()=>t[a],enumerable:!(n=Iu(t,a))||n.enumerable});return o};var j=(o,t,e)=>(e=o!=null?Cu(Du(o)):{},Ui(t||!o||!o.__esModule?en(e,"default",{value:o,enumerable:!0}):e,o)),vu=o=>Ui(en({},"__esModule",{value:!0}),o);var Jp={};Wr(Jp,{appHelpers:()=>zp});module.exports=vu(Jp);var Hi=require("@msafe/sui3-utils");var Fi=j(require("sort-keys-recursive")),f=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Fi.default)(this.data))}};var qi=require("@alphafi/alphafi-sdk"),nn=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r,isAmountA:i}=this.data;return await(0,qi.depositDoubleAssetTxb)(a,n.address,r,i)}static fromData(e){return console.log("DepositDoubleAssetIntention.fromData",e),new o(e)}};var $i=require("@alphafi/alphafi-sdk"),on=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,amount:r}=this.data;return await(0,$i.depositSingleAssetTxb)(a,n.address,r)}static fromData(e){return console.log("DepositSingleAssetIntention.fromData",e),new o(e)}};var Ki=require("@alphafi/alphafi-sdk"),an=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{withdrawFromLocked:a,xTokensAmount:r}=this.data;return await(0,Ki.withdrawAlphaTxb)(r,a,n.address)}static fromData(e){return console.log("WithdrawAlphaIntention.fromData",e),new o(e)}};var Vi=require("@alphafi/alphafi-sdk"),rn=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{poolName:a,xTokensAmount:r}=this.data;return await(0,Vi.withdrawTxb)(r,a,n.address)}static fromData(e){return console.log("WithdrawIntention.fromData",e),new o(e)}};var Qi=require("@alphafi/alphafi-sdk"),sn=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e;return await(0,Qi.claimRewardTxb)(n.address)}static fromData(e){return new o(e)}};var Vt=require("@msafe/sui3-utils");var nt=require("@alphafi/alphafi-sdk"),Y=require("@mysten/bcs"),cn=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let t=this.getLiquidityChangeEvent();if(!t)throw new Error("No liquidity change event found. Unable to decode transaction.");let e=t.parsedJson,n=e.pool_id,a=nt.poolIdPoolNameMap[n];if(console.log("Decoder event data - ",e),console.log("Decoder poolName - ",a),this.isWithdrawAlphaEvent(t))return this.decodeWithdrawAlpha(e);if(this.isWithdrawEvent(e))return this.decodeWithdraw(a);if(this.isDoubleAssetDepositEvent(e,a))return this.decodeDoubleAssetDeposit(a,e);if(this.isSingleAssetDepositEvent(e,a))return this.decodeSingleAssetDeposit(a,e);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}getLiquidityChangeEvent(){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(t){return t.includes("LiquidityChangeEvent")||t.includes("LiquidityChangeNewNewEvent")||t.includes("WithdrawEventV2")}isWithdrawAlphaEvent(t){return t.type.includes("WithdrawEventV2")}isWithdrawEvent(t){return t.event_type===1}isDoubleAssetDepositEvent(t,e){return t.event_type===0&&nt.poolInfo[e].assetTypes.length===2}isSingleAssetDepositEvent(t,e){return t.event_type===0&&nt.poolInfo[e].assetTypes.length===1}extractXTokensAmount(){let t=this.inputs.find(a=>a.Pure!==void 0);if(!t||!t.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let e=t.Pure.bytes,n;return e.length===12?n=Y.bcs.u64().parse((0,Y.fromB64)(e)):e.length===24?n=Y.bcs.u128().parse((0,Y.fromB64)(e)):e.length===44?n=Y.bcs.u256().parse((0,Y.fromB64)(e)):n=n=Y.bcs.u64().parse((0,Y.fromB64)(e)),n}decodeDoubleAssetDeposit(t,e){let{amount_a:n,amount_b:a}=e,r=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,a,r),{txType:Vt.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:t,amount:r?n:a,isAmountA:r}}}decodeSingleAssetDeposit(t,e){let{amount:n}=e;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let r=nt.singleAssetPoolCoinMap[t].coin,i=nt.coinsList[r].expo;n=Math.floor(Number(n)/10**(9-i)).toString()}return{txType:Vt.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:t,amount:n}}}decodeWithdraw(t){let e=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",e),{txType:Vt.TransactionType.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:Vt.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:e}}}decodeClaimReward(){return{txType:Vt.TransactionType.Other,type:"claimReward",intentionData:{}}}};var ln=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(t){let{transaction:e,suiClient:n,account:a}=t,r=await n.devInspectTransactionBlock({sender:e.getData().sender,transactionBlock:e});console.log("AlphaFiHelper Sim result - ",r);let s=new cn(e,r).decode();return{txType:Hi.TransactionType.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=on.fromData(t.intentionData);break;case"depositDoubleAsset":n=nn.fromData(t.intentionData);break;case"withdraw":n=rn.fromData(t.intentionData);break;case"withdrawAlpha":n=an.fromData(t.intentionData);break;case"claimReward":n=sn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({account:e})}};var ys=require("@msafe/sui3-utils");var L=require("@msafe/sui3-utils");var dn=require("bucket-protocol-sdk"),un=require("@mysten/sui/bcs"),pn=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(a=>a.$kind==="MoveCall"&&a.MoveCall.package===t&&a.MoveCall.module===e&&a.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(dn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(dn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(dn.SBUCK_FOUNTAIN_PACKAGE_ID,"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",a=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return a.$kind=="Input"&&(n=this.getPureInputU64(a.Input)),this.getMoveCallCommand("charge_reservoir")?(t=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments[0],e=!1):(t=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments[0],e=!0),console.log("Decoder.decodePsm",t,n,e),{txType:L.TransactionType.Other,type:"psm",intentionData:{coinType:t,amount:n,buckToCoin:e}}}decodeBorrow(){let t="",e="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;t=s.typeArguments[0];let c=s.arguments[1];c.$kind=="Input"&&(e=this.getPureInputU64(c.Input));let l=s.arguments[3];if(l.$kind=="Input"){let d=this.getPureAddresses(l.Input);d.length==1&&(n=d[0])}}else if(this.getMoveCallCommand("high_borrow")){let s=this.getMoveCallCommand("high_borrow").MoveCall;t=s.typeArguments[0];let c=s.arguments[4];c.$kind=="Input"&&(e=this.getPureInputU64(c.Input));let l=s.arguments[5];if(l.$kind=="Input"){let d=this.getPureAddresses(l.Input);d.length==1&&(n=d[0])}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let s=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;t=s.typeArguments[0];let c=s.arguments[5];c.$kind=="Input"&&(e=this.getPureInputU64(c.Input));let l=s.arguments[6];if(l.$kind=="Input"){let d=this.getPureAddresses(l.Input);d.length==1&&(n=d[0])}}return{txType:L.TransactionType.Other,type:"borrow",intentionData:{collateralType:t,collateralAmount:r,borrowAmount:e,insertionPlace:n,strapId:a}}}decodeRepay(){let t="",e="0",n="0",a=!1,r,i=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))t=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments[0];else if(this.getMoveCallCommand("fully_repay_with_strap"))t=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments[0];else if(this.getMoveCallCommand("repay_and_withdraw")){let s=this.getMoveCallCommand("repay_and_withdraw").MoveCall;t=s.typeArguments[0];let c=s.arguments[4];c.$kind=="Input"&&(n=this.getPureInputU64(c.Input));let l=s.arguments[5];if(l.$kind=="Input"){let u=this.getPureAddresses(l.Input);u.length==1&&(r=u[0])}let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind=="Input"&&(e=this.getPureInputU64(d.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let s=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;t=s.typeArguments[0];let c=s.arguments[5];c.$kind=="Input"&&(n=this.getPureInputU64(c.Input));let l=s.arguments[6];if(l.$kind=="Input"){let u=this.getPureAddresses(l.Input);u.length==1&&(r=u[0])}let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind=="Input"&&(e=this.getPureInputU64(d.Input))}return{txType:L.TransactionType.Other,type:"repay",intentionData:{collateralType:t,repayAmount:e,withdrawAmount:n,isSurplus:a,insertionPlace:r,strapId:i}}}decodeWithdraw(){let t="",e="0",n,a=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let r=this.getMoveCallCommand("withdraw_with_strap").MoveCall;t=r.typeArguments[0];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[0])}}else if(this.getMoveCallCommand("withdraw")){let r=this.getMoveCallCommand("withdraw").MoveCall;t=r.typeArguments[0];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[0])}}return{txType:L.TransactionType.Other,type:"withdraw",intentionData:{collateralType:t,withdrawAmount:e,insertionPlace:n,strapId:a}}}decodeClose(){let t="",e=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&(t=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments[0]),{txType:L.TransactionType.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:L.TransactionType.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=[],a=this.getMoveCallModuleCommands("proof_rule","unlock");if(a.length>0)for(let s of a)n.push("");else{let s=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let c of s){let l=c.MoveCall.arguments[2];if(l.$kind=="Input"){let d=this.inputs[l.Input].UnresolvedObject.objectId;n.push(d)}}}let r=this.isSBUCKWithdrawTransaction(),i={stakeProofs:n,amount:t,isStake:e,toBuck:r};return console.log("Decoder.decodeSBUCKUnstake",i),{txType:L.TransactionType.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:L.TransactionType.Other,type:"sbuck-withdraw",intentionData:{amount:t}}}decodeSBUCKClaim(){let t=[],e=this.getMoveCallModuleCommands("fountain_core","claim");for(let n of e){let a=n.MoveCall.arguments[2];if(a.$kind=="Input"){let r=this.inputs[a.Input].UnresolvedObject.objectId;t.push(r)}}return console.log("Decoder.decodeSBUCKClaim",t),{txType:L.TransactionType.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:L.TransactionType.Other,type:"tank-deposit",intentionData:{coinType:r,amount:t}}}decodeTankWithdraw(){let t=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,e=t.typeArguments[0],n="0",a=t.arguments[5];return a.$kind=="Input"&&(n=this.getPureInputU64(a.Input)),console.log("Decoder.decodeTankWithdraw",e,n),{txType:L.TransactionType.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:L.TransactionType.Other,type:"tank-claim",intentionData:{coinType:e}}}decodeLockedClaim(){let t="",e=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let r of n)t=r.MoveCall.typeArguments[0],e++;let a=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let r of a)t=r.MoveCall.typeArguments[0],e++;return console.log("Decoder.decodeLockedClaim",t,e),{txType:L.TransactionType.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 un.bcs.U64.fromBase64(e.Pure.bytes)}getPureAddresses(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return un.bcs.vector(un.bcs.Address).fromBase64(e.Pure.bytes)}};var Xi=require("@msafe/sui3-utils");var zi=require("@mysten/sui/transactions"),Ji=require("bucket-protocol-sdk");var Gi=require("bucket-protocol-sdk"),R=(o,t)=>{let e=o==="sui:mainnet"?"mainnet":"testnet";return new Gi.BucketClient(e,t.address)};var Yi=async(o,t,e)=>{let{coinType:n,amount:a,buckToCoin:r}=o,i=new zi.Transaction,s=R(e,t);return await(0,Ji.buildPsmTx)(s,i,n,a,r,t.address),i};var mn=class o extends f{constructor(e){super(e);this.data=e}txType=Xi.TransactionType.Other;txSubType="psm";async build(e){let{account:n,network:a}=e;return await Yi(this.data,n,a)}static fromData(e){return new o(e)}};var os=require("@msafe/sui3-utils");var he=require("@mysten/sui/transactions");var dt=require("bucket-protocol-sdk"),Zi=async(o,t,e)=>{let{collateralType:n,collateralAmount:a,borrowAmount:r,insertionPlace:i,strapId:s}=o,c=new he.Transaction,l=R(e,t);return await(0,dt.buildBorrowTx)(l,c,n,a,r,t.address,i,s),c},ts=async(o,t,e)=>{let{collateralType:n,withdrawAmount:a,insertionPlace:r,strapId:i}=o,s=new he.Transaction,c=R(e,t);return await(0,dt.buildWithdrawTx)(c,s,n,a,t.address,r,i),s},es=async(o,t,e)=>{let{collateralType:n,repayAmount:a,withdrawAmount:r,isSurplus:i,insertionPlace:s,strapId:c}=o,l=new he.Transaction,d=R(e,t);return await(0,dt.buildRepayTx)(d,l,n,a,r,t.address,i,s,c),l},ns=async(o,t,e)=>{let{collateralType:n,recipient:a,strapId:r}=o,i=new he.Transaction,s=R(e,t);return await(0,dt.buildCloseTx)(s,i,n,a,r),i};var fn=class o extends f{constructor(e){super(e);this.data=e}txType=os.TransactionType.Other;txSubType="borrow";async build(e){let{account:n,network:a}=e;return await Zi(this.data,n,a)}static fromData(e){return new o(e)}};var as=require("@msafe/sui3-utils");var bn=class o extends f{constructor(e){super(e);this.data=e}txType=as.TransactionType.Other;txSubType="repay";async build(e){let{account:n,network:a}=e;return await es(this.data,n,a)}static fromData(e){return new o(e)}};var rs=require("@msafe/sui3-utils");var gn=class o extends f{constructor(e){super(e);this.data=e}txType=rs.TransactionType.Other;txSubType="withdraw";async build(e){let{account:n,network:a}=e;return await ts(this.data,n,a)}static fromData(e){return new o(e)}};var is=require("@msafe/sui3-utils");var hn=class o extends f{constructor(e){super(e);this.data=e}txType=is.TransactionType.Other;txSubType="close";async build(e){let{account:n,network:a}=e;return await ns(this.data,n,a)}static fromData(e){return new o(e)}};var Se=require("@msafe/sui3-utils");var ye=require("@mysten/sui/transactions"),ut=require("bucket-protocol-sdk");var ss=async(o,t,e)=>{let{coinType:n,amount:a,isStake:r}=o,i=new ye.Transaction,s=R(e,t);return await(0,ut.buildSBUCKDepositTx)(s,i,n,a,t.address,r),i},cs=async(o,t,e)=>{let{stakeProofs:n,amount:a,isStake:r,toBuck:i}=o,s=new ye.Transaction,c=R(e,t);return await(0,ut.buildSBUCKUnstakeTx)(c,s,n,a,t.address,r,i),s},ls=async(o,t,e)=>{let{amount:n}=o,a=new ye.Transaction,r=R(e,t);return await(0,ut.buildSBUCKWithdrawTx)(r,a,n,t.address),a},ds=async(o,t,e)=>{let{stakeProofs:n}=o,a=new ye.Transaction,r=R(e,t);return await(0,ut.buildSBUCKClaimTx)(r,a,n,t.address),a};var yn=class o extends f{constructor(e){super(e);this.data=e}txType=Se.TransactionType.Other;txSubType="sbuck-deposit";async build(e){let{account:n,network:a}=e;return await ss(this.data,n,a)}static fromData(e){return new o(e)}},Sn=class o extends f{constructor(e){super(e);this.data=e}txType=Se.TransactionType.Other;txSubType="sbuck-unstake";async build(e){let{account:n,network:a}=e;return await cs(this.data,n,a)}static fromData(e){return new o(e)}},wn=class o extends f{constructor(e){super(e);this.data=e}txType=Se.TransactionType.Other;txSubType="sbuck-withdraw";async build(e){let{account:n,network:a}=e;return await ls(this.data,n,a)}static fromData(e){return new o(e)}},Tn=class o extends f{constructor(e){super(e);this.data=e}txType=Se.TransactionType.Other;txSubType="sbuck-claim";async build(e){let{account:n,network:a}=e;return await ds(this.data,n,a)}static fromData(e){return new o(e)}};var xn=require("@msafe/sui3-utils");var Cn=require("@mysten/sui/transactions");var Qt=require("bucket-protocol-sdk"),us=async(o,t,e)=>{let{coinType:n,amount:a}=o,r=new Cn.Transaction,i=R(e,t);return await(0,Qt.buildTankDepositTx)(i,r,n,a,t.address),r},ps=async(o,t,e)=>{let{coinType:n,amount:a}=o,r=new Cn.Transaction,i=R(e,t);return await(0,Qt.buildTankWithdrawTx)(i,r,n,a,t.address),r},ms=async(o,t,e)=>{let{coinType:n}=o,a=new Cn.Transaction,r=R(e,t);return await(0,Qt.buildTankClaimTx)(r,a,n,t.address),a};var fs=require("@mysten/sui/transactions"),bs=require("bucket-protocol-sdk");var gs=async(o,t,e)=>{let{coinType:n,proofCount:a}=o,r=new fs.Transaction,i=R(e,t);return await(0,bs.buildLockedClaimTx)(i,r,n,a,t.address),r};var In=class o extends f{constructor(e){super(e);this.data=e}txType=xn.TransactionType.Other;txSubType="tank-deposit";async build(e){let{account:n,network:a}=e;return await us(this.data,n,a)}static fromData(e){return new o(e)}},kn=class o extends f{constructor(e){super(e);this.data=e}txType=xn.TransactionType.Other;txSubType="tank-withdraw";async build(e){let{account:n,network:a}=e;return await ps(this.data,n,a)}static fromData(e){return new o(e)}},Dn=class o extends f{constructor(e){super(e);this.data=e}txType=xn.TransactionType.Other;txSubType="tank-claim";async build(e){let{account:n,network:a}=e;return await ms(this.data,n,a)}static fromData(e){return new o(e)}};var hs=require("@msafe/sui3-utils");var vn=class o extends f{constructor(e){super(e);this.data=e}txType=hs.TransactionType.Other;txSubType="lock-claim";async build(e){let{account:n,network:a}=e;return await gs(this.data,n,a)}static fromData(e){return new o(e)}};var An=class{application="bucket";supportSDK="@mysten/sui";async deserialize(t){console.log("Bucket helper deserialize input: ",t);let{transaction:e}=t,a=new pn(e).decode();return{txType:ys.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"psm":r=mn.fromData(t.intentionData);break;case"borrow":r=fn.fromData(t.intentionData);break;case"withdraw":r=gn.fromData(t.intentionData);break;case"repay":r=bn.fromData(t.intentionData);break;case"close":r=hn.fromData(t.intentionData);break;case"tank-deposit":r=In.fromData(t.intentionData);break;case"tank-withdraw":r=kn.fromData(t.intentionData);break;case"tank-claim":r=Dn.fromData(t.intentionData);break;case"sbuck-deposit":r=yn.fromData(t.intentionData);break;case"sbuck-unstake":r=Sn.fromData(t.intentionData);break;case"sbuck-withdraw":r=wn.fromData(t.intentionData);break;case"sbuck-claim":r=Tn.fromData(t.intentionData);break;case"lock-claim":r=vn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Tc=require("@msafe/sui3-utils");var Os=require("@msafe/sui3-utils");var we=require("@cetusprotocol/aggregator-sdk"),Ss=require("@cetusprotocol/cetus-periphery-sdk"),ws=require("@cetusprotocol/cetus-sui-clmm-sdk"),Ts=j(require("@cetusprotocol/vaults-sdk")),Cs=require("@mysten/sui/client"),Ou={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},Pu={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Wt=(o,t)=>{let e=Ou,n=new ws.CetusClmmSDK(e);return n.senderAddress=t.address,n},N=(o,t)=>{let e=Wt(o,t),n=Pu;return new Ss.CetusPeripherySDK(n,e)},Ru="https://api-sui.cetus.zone/router_v2/find_routes",Is=(o,t)=>{let e=new Cs.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new we.AggregatorClient(Ru,t.address,e,we.Env.Mainnet)},_u={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10"},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},aggregator:{endPoint:"https://api-sui.cetus.zone/router_v2/find_routes",fullNodeurl:"https://fullnode.mainnet.sui.io/",walletAddress:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb",env:we.Env.Mainnet,providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"]}},Lr=(o,t)=>{let e=new Ts.default(_u);return e.senderAddress=t.address,e};var ks=async(o,t,e)=>await Wt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),Ds=async(o,t,e)=>await Wt(e,t).Position.createAddLiquidityFixTokenPayload(o?.parameter,o?.gasEstimateArg),xs=async(o,t,e)=>await Wt(e,t).Position.closePositionTransactionPayload(o),vs=async(o,t,e)=>await Wt(e,t).Position.removeLiquidityTransactionPayload(o),As=async(o,t,e)=>await Wt(e,t).Rewarder.collectRewarderTransactionPayload(o);var On=class o extends f{constructor(e){super(e);this.data=e}txType=Os.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await ks(r,n,a)}static fromData(e){return new o(e)}};var Ps=require("@msafe/sui3-utils");var Pn=class o extends f{constructor(e){super(e);this.data=e}txType=Ps.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await As(r,n,a)}static fromData(e){return new o(e)}};var Rs=require("@msafe/sui3-utils");var Rn=class o extends f{constructor(e){super(e);this.data=e}txType=Rs.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await vs(r,n,a)}static fromData(e){return new o(e)}};var Fs=require("@msafe/sui3-utils");var _s=async(o,t,e)=>await N(e,t).Farms.openPositionAddLiquidityStakePaylod(o),Bs=async(o,t,e)=>await N(e,t).Farms.addLiquidityFixCoinPayload(o),Ms=async(o,t,e)=>await N(e,t).Farms.removeLiquidityPayload(o),js=async(o,t,e)=>await N(e,t).Farms.removeLiquidityPayload(o),Ns=async(o,t,e)=>await N(e,t).Farms.claimFeeAndClmmReward(o),Es=async(o,t,e)=>await N(e,t).Farms.harvestPayload(o),Ws=async(o,t,e)=>{let n=N(e,t),a=Object.values(o);return await n.Farms.batchHarvestPayload(a)},Ls=async(o,t,e)=>await N(e,t).Farms.depositPayload(o),Us=async(o,t,e)=>await N(e,t).Farms.withdrawPayload(o);var _n=class o extends f{constructor(e){super(e);this.data=e}txType=Fs.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await _s(r,n,a)}static fromData(e){return new o(e)}};var qs=require("@msafe/sui3-utils");var Bn=class o extends f{constructor(e){super(e);this.data=e}txType=qs.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ws(r,n,a)}static fromData(e){return new o(e)}};var $s=require("@msafe/sui3-utils");var Mn=class o extends f{constructor(e){super(e);this.data=e}txType=$s.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ns(r,n,a)}static fromData(e){return new o(e)}};var Ks=require("@msafe/sui3-utils");var jn=class o extends f{constructor(e){super(e);this.data=e}txType=Ks.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ms(r,n,a)}static fromData(e){return new o(e)}};var Vs=require("@msafe/sui3-utils");var Nn=class o extends f{constructor(e){super(e);this.data=e}txType=Vs.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Es(r,n,a)}static fromData(e){return new o(e)}};var Qs=require("@msafe/sui3-utils");var En=class o extends f{constructor(e){super(e);this.data=e}txType=Qs.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Bs(r,n,a)}static fromData(e){return new o(e)}};var Hs=require("@msafe/sui3-utils");var Wn=class o extends f{constructor(e){super(e);this.data=e}txType=Hs.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await js(r,n,a)}static fromData(e){return new o(e)}};var Gs=require("@msafe/sui3-utils");var Ln=class o extends f{constructor(e){super(e);this.data=e}txType=Gs.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ls(r,n,a)}static fromData(e){return new o(e)}};var zs=require("@msafe/sui3-utils");var Un=class o extends f{constructor(e){super(e);this.data=e}txType=zs.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Us(r,n,a)}static fromData(e){return new o(e)}};var Js=require("@msafe/sui3-utils");var Fn=class o extends f{constructor(e){super(e);this.data=e}txType=Js.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await Ds(r,n,a)}static fromData(e){return new o(e)}};var Ys=require("@msafe/sui3-utils");var qn=class o extends f{constructor(e){super(e);this.data=e}txType=Ys.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await xs(r,n,a)}static fromData(e){return new o(e)}};var ec=require("@msafe/sui3-utils");var Xs=require("@cetusprotocol/aggregator-sdk"),Zs=require("@mysten/sui/transactions");var tc=async(o,t,e)=>{let n=Is(e,t),a=new Zs.Transaction;return await n.fastRouterSwap({...o,routers:(0,Xs.restituteMsafeFastRouterSwapParams)(o.routers),txb:a}),a};var $n=class o extends f{constructor(e){super(e);this.data=e}txType=ec.TransactionType.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await tc(r,n,a)}static fromData(e){return new o(e)}};var ac=require("@msafe/sui3-utils");var nc=async(o,t,e)=>await Lr(e,t).Vaults.deposit(o),oc=async(o,t,e)=>await Lr(e,t).Vaults.withdraw(o);var Kn=class o extends f{constructor(e){super(e);this.data=e}txType=ac.TransactionType.Other;txSubType="AddVaultsPosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await nc(r,n,a)}static fromData(e){return new o(e)}};var rc=require("@msafe/sui3-utils");var Vn=class o extends f{constructor(e){super(e);this.data=e}txType=rc.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await oc(r,n,a)}static fromData(e){return new o(e)}};var lc=require("@msafe/sui3-utils");var sc=require("@mysten/sui/transactions"),ic={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},cc=async(o,t,e)=>{console.log("getVestingRedeemTxb txbParams: ",o),console.log("getVestingRedeemTxb account: ",t),console.log("getVestingRedeemTxb network: ",e);let{pool:n,nftId:a,periods:r,CLOCK_ADDRESS:i}=o,s=new sc.Transaction;return r.forEach(c=>{s.moveCall({target:`${ic.published_at}::router::redeem`,typeArguments:[ic.cetus_coin_type],arguments:[s.object(n),s.object(a),s.pure(c),s.object(i)]})}),s};var Qn=class o extends f{constructor(e){super(e);this.data=e}txType=lc.TransactionType.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await cc(r,n,a)}static fromData(e){return new o(e)}};var gc=require("@msafe/sui3-utils");var dc=require("@mysten/sui/transactions");var uc=async(o,t,e)=>{let n=N(e,t),a=new dc.Transaction;return await n.XCetusModule.convertPayload(o,a)},pc=async(o,t,e)=>await N(e,t).XCetusModule.redeemLockPayload(o),mc=async(o,t,e)=>await N(e,t).XCetusModule.redeemDividendV3Payload(o.phases,o.venft_id,o.bonus_types,o.bonus_types_v2,o.xTokenType),fc=async(o,t,e)=>await N(e,t).XCetusModule.cancelRedeemPayload(o),bc=async(o,t,e)=>await N(e,t).XCetusModule.redeemPayload(o);var Hn=class o extends f{constructor(e){super(e);this.data=e}txType=gc.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await fc(r,n,a)}static fromData(e){return new o(e)}};var hc=require("@msafe/sui3-utils");var Gn=class o extends f{constructor(e){super(e);this.data=e}txType=hc.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await mc(r,n,a)}static fromData(e){return new o(e)}};var yc=require("@msafe/sui3-utils");var zn=class o extends f{constructor(e){super(e);this.data=e}txType=yc.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await uc(r,n,a)}static fromData(e){return new o(e)}};var Sc=require("@msafe/sui3-utils");var Jn=class o extends f{constructor(e){super(e);this.data=e}txType=Sc.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await bc(r,n,a)}static fromData(e){return new o(e)}};var wc=require("@msafe/sui3-utils");var Yn=class o extends f{constructor(e){super(e);this.data=e}txType=wc.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:a}=e,{txbParams:r}=this.data;return await pc(r,n,a)}static fromData(e){return new o(e)}};var Xn=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:Tc.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(t.txSubType){case"OpenAndAddLiquidity":r=On.fromData(t.intentionData);break;case"IncreaseLiquidity":r=Fn.fromData(t.intentionData);break;case"DecreaseLiquidity":r=Rn.fromData(t.intentionData);break;case"RemoveLiquidity":r=qn.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=Pn.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=_n.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=En.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=jn.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=Wn.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=Mn.fromData(t.intentionData);break;case"FarmingHarvest":r=Nn.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=Bn.fromData(t.intentionData);break;case"FarmingStake":r=Ln.fromData(t.intentionData);break;case"FarmingUnstake":r=Un.fromData(t.intentionData);break;case"xCETUSConvert":r=zn.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Yn.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=Gn.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=Hn.fromData(t.intentionData);break;case"xCETUSRedeem":r=Jn.fromData(t.intentionData);break;case"VestingRedeem":r=Qn.fromData(t.intentionData);break;case"AggregatorSwap":r=$n.fromData(t.intentionData);break;case"AddVaultsPosition":r=Kn.fromData(t.intentionData);break;case"RemoveVaultsPosition":r=Vn.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Kc=require("@msafe/sui3-utils");var Cc=j(require("sort-keys-recursive")),y=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Cc.default)(this.data))}};var Te=require("@mysten/sui.js/client");var Ur={};Wr(Ur,{contractId:()=>ju,default:()=>Uu,feeObjId:()=>Wu,roleObjId:()=>Nu,status:()=>Mu,transaction:()=>Bu,upgradeCapObjId:()=>Lu,vaultObjId:()=>Eu});var Bu="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Mu="success",ju="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Nu="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Eu="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Wu="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Lu="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Uu={transaction:Bu,status:Mu,contractId:ju,roleObjId:Nu,vaultObjId:Eu,feeObjId:Wu,upgradeCapObjId:Lu};var Fr={};Wr(Fr,{contractId:()=>$u,default:()=>Gu,feeObjId:()=>Qu,roleObjId:()=>Ku,status:()=>qu,transaction:()=>Fu,upgradeCapObjId:()=>Hu,vaultObjId:()=>Vu});var Fu="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",qu="success",$u="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ku="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Vu="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Qu="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Hu="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Gu={transaction:Fu,status:qu,contractId:$u,roleObjId:Ku,vaultObjId:Vu,feeObjId:Qu,upgradeCapObjId:Hu};var zu=(0,Te.getFullnodeUrl)("testnet"),Ju=(0,Te.getFullnodeUrl)("testnet"),Yu=(0,Te.getFullnodeUrl)("mainnet"),Xu=(0,Te.getFullnodeUrl)("mainnet"),Zu="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tp="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",ep="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",np="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Ic=Ur,kc=Fr,op=new Map([["dev",{env:"dev",rpc:{url:zu},backend:{url:Zu},contract:Ic}],["stg",{env:"stg",rpc:{url:Ju},backend:{url:tp},contract:Ic}],["prev",{env:"prev",rpc:{url:Yu},backend:{url:ep},contract:kc}],["prod",{env:"prod",rpc:{url:Xu},backend:{url:np},contract:kc}]]);function Dc(o,t){let e=op.get(o);if(!e)throw new Error(`Env not supported: ${o}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}var xc=require("@mysten/sui.js/client");var k=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:a,context:r}=n;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}};var Zn=class extends k{constructor(){super(11,"Backend is not specified")}};var to=class extends k{constructor(){super(1,"Wallet not connected")}};var at=j(require("axios"));var Ht=class extends k{constructor(t,e){super(10,t,{context:e})}};var eo=class o{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof at.AxiosError)throw new Ht(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new Ht(t.data.code)}throw new Ht(t.status.toString())}async getIncomingStreams(t,e){let n=await at.default.post(`${this.apiURL}/stream`,{recipient:t,...e});return o.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await at.default.post(`${this.apiURL}/stream`,{sender:t,...e});return o.parseResponseData(n)}async getStreamHistory(t){let e=await at.default.post(`${this.apiURL}/stream-events`,t),n=o.parseResponseData(e);return n.data.forEach(a=>{let r=a;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(t){let e=await at.default.post(`${this.apiURL}/stream-info`,{address:t});return o.parseResponseData(e)}async getAllRecipients(t,e){let n=await at.default.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return o.parseResponseData(n)}async getAllSenders(t,e){let n=await at.default.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return o.parseResponseData(n)}};var Gt=class o{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new xc.SuiClient({url:t.rpc.url}),t.backend&&(this._backend=new eo(t.backend.url))}static new(t,e){let n=Dc(t,e);return new o(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Zn;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 to;return this.signer}async walletAddress(){return this.wallet.address()}};var Ut=require("@mysten/sui.js/utils");var ve=require("@mysten/sui.js/transactions");var Qr=require("@mysten/sui.js/transactions"),xe=require("@mysten/sui.js/utils");var qr=50n,no=10000n,vc=25n,$r=100000000n;var X=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Ce=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ft=class o{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,n){if(n in e)return Reflect.get(e,n);let a=i=>new o(e.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return a(r)}})}moveArg(){return this.result}};var Kr=require("buffer"),Ac=require("@mysten/sui.js/utils");var Ie=class extends k{constructor(t,e){super(3,t,{context:e})}};var oo=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="address")throw new Ie("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return(0,Ac.normalizeSuiAddress)(Kr.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,a]=this.getValue(t,e);if(a!=="u64")throw new Ie("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return Kr.Buffer.from(n).readBigInt64LE()}};var Vr=require("@mysten/sui.js/bcs");var v=class extends k{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var Pc={groupId:"string",name:"string"},ap=64;function Rc(o){return _c(o),Vr.bcs.ser(Pc,o).toString("base64")}function ke(o){let t=Vr.bcs.de(Pc,o,"base64");return _c(t),t}function _c(o){if(!Oc(o.name))throw new v("Invalid metadata: Name contains unknown character");if(!Oc(o.groupId))throw new v("Invalid metadata: Group ID contains unknown character");if(o.name.length>ap)throw new v("Invalid metadata: Name exceed max length 64")}function Oc(o){return/^[\x00-\x7F]+$/.test(o)}var De=require("@mysten/sui.js/utils");function ao(o,t){return(0,De.normalizeStructTag)(o)===(0,De.normalizeStructTag)(t)}function bt(o,t){return(0,De.normalizeStructTag)(o)===(0,De.normalizeStructTag)(t)}var ro="txn.gas";var Bc=require("nanoid");function Mc(){return(0,Bc.nanoid)()}var Lt=class o{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Rc({name:t.name,groupId:Mc()}),coinType:(0,xe.normalizeStructTag)(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new Qr.TransactionBlock,n=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,n),r=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,r[0]),s;a.length>1?s=await this.addMergeCoins(e,r[1]):s=i;for(let c=0;c<t.recipients.length;c++){let l=t.recipients[c],d=this.amountForRecipient(l,t.numberEpoch),u=this.getStreamFeeLocal(d),[p]=e.splitCoins(i,[e.pure(d+u,"u64")]),[m]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new ft(p),flatFeeCoin:new ft(m),metadata:t.metadata,recipient:l.address,timeStart:t.startTime,cliff:l.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=o.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:qr,denominator:no},claimFeePercent:{numerator:vc,denominator:no},flatFeePerStream:$r}}async addMergeCoins(t,e){let n;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),n=t.object(e.primaryCoin)):e.primaryCoin===ro?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return ao(n,xe.SUI_TYPE_ARG)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:xe.SUI_TYPE_ARG,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,r)=>{let i=this.amountForRecipient(r,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:a.totalAmount+i,streamFeeAmount:a.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(t.recipients.length)*this.flatSuiFee,...e}}amountForRecipient(t,e){return BigInt(t.amountPerEpoch)*BigInt(e)+BigInt(t.cliffAmount)}get flatSuiFee(){return $r}getStreamFeeLocal(t){return t*qr/no}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Qr.TransactionBlock,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new oo(n).getU64()}get wallet(){return this.globals.wallet}};var Hr=require("@mysten/sui.js/transactions");var jc="0x0000000000000000000000000000000000000000000000000000000000000006";var zt=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(Hr.Transactions.MoveCall({target:n,arguments:e.arguments.map(a=>a instanceof Ce?a.moveArgs(t):a instanceof X?a.moveArg(t):a instanceof ft?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],a=[]){t.add(Hr.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof Ce?r.moveArgs(t):r instanceof X?r.moveArg(t):r instanceof ft?r.moveArg():t.pure(r)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new X(t):t}vaultObject(){return new X(this.config.vaultObjId)}roleObject(){return new X(this.config.roleObjId)}feeObject(){return new X(this.config.feeObjId)}clockObject(){return new X(jc)}};var Jt=class o extends zt{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_fee,arguments:[a,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_streaming_flat_fee,arguments:[a,r,n],typeArgs:[]})}setClaimFee(e,n){let a=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:o.MethodName.set_claim_fee,arguments:[a,r,n],typeArgs:[]})}streamingFee(e,n){let a=this.feeObject();return this.addContractCall(e,{method:o.MethodName.streaming_fee,arguments:[a,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:o.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:o.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Z=class o extends zt{constructor(e,n){super(o.ModuleName,e,n);this.config=e;this.globals=n}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,n){let a=this.feeObject(),r=this.vaultObject(),i=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),c=this.clockObject();return this.addContractCall(e,{method:o.MethodName.create_stream,arguments:[a,r,i,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,c],typeArgs:[n.coinType]})}setAutoClaim(e,n){let a=this.makeObject(n.streamId);return this.addContractCall(e,{method:o.MethodName.set_auto_claim,arguments:[a,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.cancel_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStream(e,n){let a=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream,arguments:[a,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let a=this.makeObject(n.streamId),r=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:o.MethodName.claim_stream_by_proxy,arguments:[a,r,i,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${o.ModuleName}::${o.MethodName.claim_stream_by_proxy}`}};var Yt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Jt(e,t),this.streamContract=new Z(e,t)}feeContract;streamContract;async createStreams(t){let e=Lt.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Lt(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let a=new ve.TransactionBlock;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new ve.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new ve.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new ve.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var P=class extends k{constructor(t,e={}){super(0,t,e)}};async function zr(o){let t=[];for(;await o.hasNext();){let e=await o.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Gr=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)}},Xt=class{constructor(t){this.requester=t;this.pager=new Gr(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 io=class extends k{constructor(e,n,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:n,gotAmount:a}});this.coinType=e;this.requestAmount=n;this.gotAmount=a}};var rp=25;async function Nc(o,t,e,n="0x2::sui::SUI",a=rp){let r=new Jr(o,t,n,a),i=BigInt(0),s=[];for(;await r.hasNext()&&i<e;){let c=await r.next();c&&(s.push(c),i+=BigInt(c.balance))}if(i<e)throw new io(n,e,i);return s}var Jr=class extends Xt{constructor(e,n,a,r){super(new Yr(e,n,a,r));this.suiClient=e;this.owner=n;this.coinType=a;this.reqPageSize=r}},Yr=class{constructor(t,e,n,a){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=a;if(a<=0)throw new P("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var Pe=require("@mysten/sui.js/transactions"),Re=require("@mysten/sui.js/utils"),Wc=require("luxon");var so=class extends k{constructor(){super(7,"Connected wallet is not creator")}};var Ae=class extends k{constructor(){super(8,"Connected wallet is not recipient")}};var Oe=class extends k{constructor(t,e){super(6,t,{context:e})}};var co=class extends k{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};var uo=require("luxon"),Ec=(1n<<64n)-1n,lo=1e3;function Xr(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/lo);return uo.DateTime.fromMillis(e*lo)}function Zr(o){let t;typeof o=="number"?t=o:typeof o=="bigint"?t=Number(o):t=o.toMillis();let e=Math.round(t/lo);return uo.Duration.fromMillis(e*lo)}var gt=class o{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new Z(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let n=await o.fetchStreamData(t,e);return new o(t,e,n)}static fromObjectData(t,e,n){let a=o.parseRawStreamData(e,n);return new o(t,e,a)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await o.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new P("Object Id does not align");this.rawData=o.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new so;let t=new Pe.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Ae;let t=new Pe.TransactionBlock;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Ae;let e=new Pe.TransactionBlock;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new Pe.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Re.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Zr(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return ke(t).groupId}get name(){let{metadata:t}=this.rawData.config;return ke(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Xr(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Zr(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:Xr((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===Ec?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Wc.DateTime.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let n=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let n=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return o.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new co(t):new Oe(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new Oe("Unexpected object type",{gotType:n.dataType});let{typeParams:a}=(0,Re.parseStructTag)(n.type),r=(0,Re.normalizeStructTag)(a[0]),i=n.fields,s=i.config.fields,c=i.status.fields;return{coinType:r,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}};var Zt=require("@mysten/sui.js/utils"),ti=require("luxon");var po=class extends k{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var ip=1e3,mo=class{constructor(t){this.globals=t;this.coinMetaHelper=new ei(t.suiClient),this.createStreamHelper=new Yt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new po(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-n)/t.steps,i={realTotalAmount:a*t.steps+n,cliffAmount:n,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(ti.Duration.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:n,interval:ti.Duration.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...n,coinType:(0,Zt.normalizeStructTag)(n.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,r)=>({...a,coinType:(0,Zt.normalizeStructTag)(a.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new v("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new v("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<ip)throw new v("Interval shall be at least 1 second","interval",t.interval)}},ei=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Zt.normalizeStructTag)(t||Zt.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};var ht=require("@mysten/sui.js/utils"),ai=require("luxon");var te=class extends k{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var sp=25;async function oi(o,t,e){let n=new _e(t),a=new Be(o,n,e);return await zr(a)}var _e=class{constructor(t){this.ids=t;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Be=class extends Xt{constructor(e,n,a){super(new ni(e,n,a));this.suiClient=e;this.idIter=n;this.options=a}},ni=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||sp,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&t.push(r)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:a}=this;n=e.filter(r=>a?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}};var fo=class o{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new te("stream size 0");let n=e.map(r=>r.groupId);if(new Set(n).size!==1)throw new v("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await oi(t.suiClient,e);return n.forEach(a=>{if(!a)throw new P("stream group object data undefined")}),o.newFromObjectResponse(t,e,n)}static async newFromObjectResponse(t,e,n){let a=await o.parseGroupStreams(t,e,n);return new o(t,a)}static checkStreamGroup(t){let e=t.map(r=>r.groupCommonInfo),n=e[0],a=!0;return e.forEach(r=>{cp(n,r)||(a=!1)}),a}async refresh(){let t=await oi(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,n)=>{e.refreshWithData(t[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(t=>t.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((t,e)=>t+e.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((t,e)=>t+e.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((t,e)=>e.nextReleaseAmount===null?t:t+e.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((t,e)=>t+e.totalAmount,0n),streamed:this.streams.reduce((t,e)=>t+e.streamedAmount,0n),claimed:this.streams.reduce((t,e)=>t+e.claimedAmount,0n),claimable:this.streams.reduce((t,e)=>t+e.claimable,0n),canceled:this.streams.reduce((t,e)=>t+e.canceledAmount,0n)}}async historyEvents(t){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:t})}static async parseGroupStreams(t,e,n){let a=n.map((r,i)=>gt.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(a.map(r=>r.groupId)).size!==1)throw new te("Not same group ID");if(!this.checkStreamGroup(a))throw new te("Not same stream settings");return a}};function cp(o,t){return o.name===t.name&&o.groupId===t.groupId&&o.creator===t.creator&&o.start.toMillis()===t.start.toMillis()&&o.interval.toMillis()===t.interval.toMillis()&&o.steps===t.steps&&o.cancelable===t.cancelable}var Me=class o{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await bo.newIncoming(t);return new o(e,t.pageSize)}static async newOutgoing(t){let e=await bo.newOutgoing(t);return new o(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},bo=class o{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await go.newIncomingQuery(t);return new o(e)}static async newOutgoing(t){let e=await go.newOutgoingQuery(t);return new o(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new P("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new P("No more results");return t}},go=class o{constructor(t,e,n,a){this.globals=t;this.recipient=e;this.groupRefs=n;this.query=a;this.current=0;let r=new _e(n.flat().map(i=>i.streamId));this.objectIter=new Be(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=mp(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>(0,ht.normalizeSuiAddress)(s.recipient)===(0,ht.normalizeSuiAddress)(n)),i=Lc(r);return new o(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=fp(t.query),n=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(n,e),r=Lc(a);return new o(t.globals,n,r,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await up(this.globals,t[0].streamId,this.objectIter);return this.current++,Uc(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await pp(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,dp(e,this.query)?e:this.doNextRequest()}throw new P("Stream group with no stream")}};function Lc(o){let t=new Map;return o.forEach(e=>{let n=t.get(e.groupId);n?(n.push(e),t.set(e.groupId,n)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,n)=>ai.DateTime.fromISO(n[0].createDate).toMillis()-ai.DateTime.fromISO(e[0].createDate).toMillis())}function Uc(o,t){if(t===void 0)return!0;let e=lp(o,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let n=t.claimable?o.progress.claimable!==0n:o.progress.claimable===0n;return e&&n}return e}function lp(o,t){return t===void 0?!0:Array.isArray(t)?t.includes(o.progress.status):o.progress.status===t}function dp(o,t){if(!t)return!0;let e=!1;return o.streams.forEach(n=>{Uc(n,t)&&(e=!0)}),e}async function up(o,t,e){let n=await Fc(e,t);return gt.fromObjectData(o,t,n)}async function pp(o,t,e){let n=[];for(;n.length<t.length;){let a=await Fc(e,t[n.length]);n.push(a)}return fo.newFromObjectResponse(o,t,n)}async function Fc(o,t){if(!await o.hasNext())throw new P("object iterator has been consumed");let e=await o.next();if(!e||e.error||e.data===void 0||e.data===null)throw new P("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new P("stream id not aligned");return e}function mp(o){return{status:ri(o?.status),coinType:qc(o?.coinType),sender:$c(o?.sender)}}function fp(o){return{status:ri(o?.status),coinType:qc(o?.coinType),recipient:$c(o?.recipient)}}function ri(o){return o===void 0||o.length===0?"all":Array.isArray(o)?o.reduce((t,e)=>{let n=ri(e);return!t||t===n?n:"all"},void 0):bp(o)}function bp(o){switch(o){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new v("Unknown stream filtered status")}}function qc(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,ht.normalizeStructTag)(t)):void 0:(0,ht.normalizeStructTag)(o)}function $c(o){if(o)return Array.isArray(o)?o.length!==0?o.map(t=>(0,ht.normalizeSuiAddress)(t)):void 0:(0,ht.normalizeSuiAddress)(o)}var ii=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},ho=class{constructor(t){this.account=t}async address(){return this.account.address}},si=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(ao(t.coinType,Ut.SUI_TYPE_ARG))return{primaryCoin:ro};if(t.amount<=0)throw new v("Invalid coin request","coinAmount",t.amount);let e=await Nc(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new P("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},yo=class{globals;helper;constructor(t,e){this.globals=Gt.new(t,e),this.helper=new mo(this.globals)}connectSingleWallet(t){let e=new si(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new ii(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return gt.new(this.globals,t)}async getIncomingStreams(t,e=10){return Me.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Me.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(n=>(0,Ut.normalizeStructTag)(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>(0,Ut.normalizeSuiAddress)(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>(0,Ut.normalizeSuiAddress)(a))}get wallet(){return this.globals.wallet}builder(){return new Yt(this.globals)}};var G=class extends y{application="mpay";getClient(t,e){let n=new yo(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new ho(e)),n}};var je=class extends G{constructor(e){super(e);this.data=e}txType=Kc.TransactionType.Stream;txSubType="Cancel";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).cancel()}};var Vc=require("@msafe/sui3-utils");var Ne=class extends G{constructor(e){super(e);this.data=e}txType=Vc.TransactionType.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claimByProxy()}};var Qc=require("@msafe/sui3-utils");var Ee=class extends G{constructor(e){super(e);this.data=e}txType=Qc.TransactionType.Stream;txSubType="Claim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).claim()}};var Hc=require("@msafe/sui3-utils");var We=class extends G{constructor(e){super(e);this.data=e}txType=Hc.TransactionType.Stream;txSubType="CreateStream";async build(e){let{network:n,account:a}=e;return this.getClient(n,a).createStream(this.data)}};var ci=require("@mysten/sui.js/bcs"),yt=require("@mysten/sui.js/utils"),ee=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,yt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return ci.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,yt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,yt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,yt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,yt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return ci.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,yt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var So=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"&&bt(e.target,this.contract.createStreamTarget));if(t.length===0)throw new P("No create stream transactions");return t.map(e=>new ee(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:a}=ke(e),r=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),c=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),u=t.decodeInputBool(11),p=t.typeArg(0);return{name:n,groupId:a,recipient:r,timeStart:i,cliff:s,epochInterval:c,totalEpoch:l,amountPerEpoch:d,cancelable:u,coinType:p}}aggregateGroupStreamInfo(t){if(new Set(t.map(a=>JSON.stringify({name:a.name,groupId:a.groupId,timeStart:String(a.timeStart),epochInterval:String(a.epochInterval),totalEpoch:String(a.totalEpoch),cancelable:a.cancelable,coinType:a.coinType}))).size!==1)throw new v("Stream group not have common info");let n=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:n,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Z(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Jt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Lt(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}};var wo=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new Z(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"&&bt(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&bt(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&bt(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&bt(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&bt(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new So(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 ee(t,this.txb)}};var Gc=require("@msafe/sui3-utils");var Le=class extends G{constructor(e){super(e);this.data=e}txType=Gc.TransactionType.Stream;txSubType="SetAutoClaim";async build(e){let{network:n,account:a}=e;return(await this.getClient(n,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var To=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,a=Gt.new(e==="sui:mainnet"?"prod":"dev"),i=new wo(a,n).decode(),s;switch(i.type){case"CreateStream":s=new We(i.info);break;case"SetAutoClaim":s=new Le({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Ee({streamId:i.streamId});break;case"ClaimByProxy":s=new Ne({streamId:i.streamId});break;case"Cancel":s=new je({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:s.txType,txSubType:s.txSubType,intentionData:s.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new We(e);break;case"Claim":n=new Ee(e);break;case"ClaimByProxy":n=new Ne(e);break;case"SetAutoClaim":n=new Le(e);break;case"Cancel":n=new je(e);break;default:throw new Error("not implemented")}return n.build({...t})}};var Ue=require("@msafe/sui3-utils");var zc=require("@msafe/sui3-utils");var Co=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,zc.buildCoinTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var Jc=require("@msafe/sui3-utils");var Io=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e;return(0,Jc.buildObjectTransferTxb)(n,this.data,a.address)}static fromData(e){return new o(e)}};var ko=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Ue.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case Ue.TransactionSubTypes.assets.coin.send:a=Co.fromData(t.intentionData);break;case Ue.TransactionSubTypes.assets.object.send:a=Io.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var sl=require("@msafe/sui3-utils");var Yc=!1,Fe={ProtocolPackage:"0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function li(){if(!Yc)try{let o=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:t,borrowFee:e,borrowFeeAddress:n,pool:a}=o;t&&(Fe.ProtocolPackage=t),e&&(Fe.borrowFee=e),n&&(Fe.borrowFeeAddress=n),a&&(Fe.pool=a),Yc=!0}catch(o){console.error(o.message)}}var h=Fe;var qt=require("@msafe/sui3-utils"),di=require("@mysten/sui.js/bcs"),St=require("@mysten/sui.js/utils");var Do=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::borrow`)}isEntryMultiDepositTransaction(){let t=`${h.ProtocolPackage}::incentive_v2::entry_deposit`,e=this.transactions.filter(a=>a.kind==="MoveCall"&&a.target===t);return this.transactions.find(a=>a.kind==="MoveCall"&&a.target===`${h.ProtocolPackage}::incentive_v2::claim_reward_non_entry`)?!1:e.length>1}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(h.pool).find(n=>n.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${h.ProtocolPackage}::incentive_v2::claim_reward`){let n=new qe(e,this.txb),a=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(a),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:a,poolId:i})}}),console.log("decode claims",t),{txType:qt.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:qt.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryMultiDeposit(){let t=[],e=`${h.ProtocolPackage}::incentive_v2::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===e){let a=new qe(n,this.txb),r=a.decodeInputU8(3),i=a.decodeInputU64(5),s=this.findPoolByAssetId(r);t.push({coinType:s.coinType,amount:i})}}),{txType:qt.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:t}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:qt.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:qt.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:qt.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(h.ProtocolPackage));return new qe(t,this.txb)}},qe=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,St.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return di.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,St.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,St.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,St.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,St.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return di.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,St.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var el=require("@mysten/sui.js/transactions");function ne(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[o.object("0x06"),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Xc(o,t,e){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.Incentive),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function Zc(o,t,e,n){let a=o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),o.pure(e),o.object(h.IncentiveV2)],typeArguments:[t.type]}),[r]=o.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[a]});if(h.borrowFee>0){let[i]=o.splitCoins(r,[o.pure(Math.floor(e*h.borrowFee))]);o.transferObjects([r],o.pure(n)),o.transferObjects([i],o.pure(h.borrowFeeAddress))}else o.transferObjects([r],o.pure(n));return o}function ui(o,t,e,n){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[o.object("0x06"),o.object(h.PriceOracle),o.object(h.StorageId),o.object(t.poolId),o.pure(t.assetId),e,o.pure(n),o.object(h.IncentiveV2)],typeArguments:[t.type]}),o}function tl(o,t,e,n,a){return o.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[o.object("0x06"),o.object(h.IncentiveV2),o.object(e),o.object(h.StorageId),o.pure(t),o.pure(n)],typeArguments:a}),o}var xo=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new el.TransactionBlock;return e.forEach(a=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=a;tl(n,r,i,s,c)}),n}static fromData(e){return new o(e)}};var nl=require("@mysten/sui.js/transactions");var vo=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:a}=this.data,r=new nl.TransactionBlock;console.log("build",this.data);let i=h.pool[n];if(!i)throw new Error(`${n} not support, please use ${Object.keys(h.pool).join(", ")}.`);return Zc(r,i,a,e.account.address)}static fromData(e){return new o(e)}};var ol=require("@mysten/sui.js/transactions");async function oe(o,t,e){let n=await o.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var Ao=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new ol.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return ne(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await oe(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return ne(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var al=require("@mysten/sui.js/transactions");var Oo=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{coinType:r,amount:i}=this.data,s=new al.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return ui(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let l=await oe(n,a.address,c.type);if(!l.data[0])throw new Error(`Insufficient balance for ${c.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let u=1;for(;u<l.data.length;)s.mergeCoins(d,[l.data[u].coinObjectId]),u++}return ui(s,c,s.object(d),i)}static fromData(e){return new o(e)}};var rl=require("@mysten/sui.js/transactions");var Po=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,a=new rl.TransactionBlock;console.log("build",this.data);let r=h.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return Xc(a,r,n)}static fromData(e){return new o(e)}};var il=require("@mysten/sui.js/transactions");var Ro=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a}=e,{list:r}=this.data,i=new il.TransactionBlock;console.log("build",this.data);for(let s=0;s<r.length;s++){let{coinType:c,amount:l}=r[s];if(c==="sui"){let[m]=i.splitCoins(i.gas,[l]);ne(i,h.pool.sui,m,l);continue}let d=h.pool[c];if(!d)throw new Error(`${c} not support, please use ${Object.keys(h.pool).join(", ")}.`);let u=await oe(n,a.address,d.type);if(!u.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let p=u.data[0].coinObjectId;if(u.data.length>=2){let m=1;for(;m<u.data.length;)i.mergeCoins(p,[u.data[s].coinObjectId]),m++}ne(i,d,i.object(p),l)}return i}static fromData(e){return new o(e)}};var _o=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await li();let{transactionBlock:e}=t,a=new Do(e).decode();return{txType:sl.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(await li(),t.txSubType){case"EntryDeposit":a=Ao.fromData(t.intentionData);break;case"EntryBorrow":a=vo.fromData(t.intentionData);break;case"EntryRepay":a=Oo.fromData(t.intentionData);break;case"EntryWithdraw":a=Po.fromData(t.intentionData);break;case"EntryMultiDeposit":a=Ro.fromData(t.intentionData);break;case"ClaimReward":a=xo.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var $e=require("@msafe/sui3-utils"),cl=require("@mysten/bcs"),ll=require("@mysten/sui/transactions"),dl=j(require("sort-keys-recursive")),ul="msafe-plain-tx",pl=$e.TransactionSubTypes.others.plain,pi=class o{constructor(t){this.data=t}application=ul;txType=$e.TransactionType.Other;txSubType=pl;serialize(){return JSON.stringify((0,dl.default)(this.data))}async build(t){return ll.Transaction.from((0,cl.fromHEX)(this.data.content))}static fromData(t){return new o(t)}},Bo=class{application;supportSDK="@mysten/sui";constructor(){this.application=ul}async deserialize(t){let{content:e}=t.appContext;return{txType:$e.TransactionType.Other,txSubType:pl,intentionData:{content:e}}}async build(t){let{suiClient:e,network:n,account:a}=t;return pi.fromData(t.intentionData).build({suiClient:e,network:n,account:a})}};var bi=require("@mysten/sui/client"),ml=require("@mysten/sui/transactions"),No=require("@mysten/sui.js/client"),fl=require("@mysten/sui.js/transactions");var ae=require("@open-rpc/client-js");var yp={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},mi=class extends Error{},Mo=class extends mi{code;type;constructor(t,e){super(t),this.code=e,this.type=yp[e]??"ServerError"}};function Sp(o){let t=new URL(o);return t.protocol=t.protocol.replace("http","ws"),t.toString()}var wp={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},jo=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#r=new Set;#o=new Map;constructor(t,e={}){this.endpoint=t,this.options={...wp,...e},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=Sp(this.endpoint))}async makeRequest(t,e){let n=await this.#i();return new Promise((a,r)=>{this.#n+=1,this.#o.set(this.#n,{resolve:a,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:a,result:r})=>{if(a)throw new Mo(a.message,a.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(a){console.error(new Error(`Failed to parse RPC message: ${e}`,{cause:a}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:a,timeout:r}=this.#o.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(t=>t.subscribe(this)))}async subscribe(t){let e=new fi(t);return this.#r.add(e),await e.subscribe(this),()=>e.unsubscribe(this)}},fi=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 wt=class{rpcClient;websocketClient;constructor({url:t,websocket:{url:e,...n}={},rpc:a}){let r=new ae.HTTPTransport(a?.url??t,{headers:{"Content-Type":"application/json",...a?.headers}});this.rpcClient=new ae.Client(new ae.RequestManager([r])),this.websocketClient=new jo(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 Eo=class o{apps;constructor(){this.apps=new Map}static fromHelpers(t){let e=new o;for(let n=0;n<t.length;n++){let a=t[n];switch(a.supportSDK){case"@mysten/sui.js":e.addLegacyHelper(a);break;case"@mysten/sui":e.addHelper(a);break;default:throw new Error(`${a.application}: ${a.supportSDK} SDK not supported`)}}return e}addLegacyHelper(t){this.apps.set(t.application,new hi(t))}addHelper(t){this.apps.set(t.application,new gi(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},gi=class{constructor(t){this.helper=t}async deserialize(t){let e=new bi.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})}),n=new No.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})}),a=await t.transactionBlock.build({client:n}),r=ml.Transaction.from(a);return this.helper.deserialize({...t,suiClient:e,transaction:r})}async build(t){let e=new bi.SuiClient({transport:new wt({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 a=await this.helper.build({...t,suiClient:e});a.setSender(t.account.address);let r=await a.build({client:e});return fl.TransactionBlock.from(r)}},hi=class{constructor(t){this.helper=t}async deserialize(t){let e=new No.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new No.SuiClient({transport:new wt({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})}};var od=require("@msafe/sui3-utils");var A=require("@msafe/sui3-utils");var Tt=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 bl="https://sui.apis.scallop.io";var gl="675c65cd301dd817ea262e76",Wo="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var Ct="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",It="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",rt=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd","deep","fud"],Lo=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd"],kt=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],it=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc","sfdusd","sdeep","sfud"];var hl=["sui"],Dt=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc","fdusd","deep","fud"];var yl={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 Uo={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},Sl={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"]},wl={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"},K={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},yi={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},Tl={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"};var Si=require("@mysten/sui.js/bcs"),xt=require("@mysten/sui.js/utils"),w=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,xt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}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 Si.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,xt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,xt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,xt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,xt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Si.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,xt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Cl=require("@mysten/sui.js/bcs");var _=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(w.getPureInputValue(t,"u64"))}).filter(t=>t!==void 0)}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Cl.bcs.de(e,new Uint8Array(n))}return t.value}};var Fo=class extends Tt{decode(){if(this.isMoveAsset())return this.decodeMoveAsset();if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMoveAsset(){return!!this.getMoveCallTransaction("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage")}isMigrateScoinTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`),e=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);return!!t&&!!e}isUnstakeAndWithdrawTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`),e=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);return!!t&&!!e}isStakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`),e=!!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return!!t&&!!e}isDepositCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isBorrowWithReferralTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let t=!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);return!!t&&!!e}isUnstakeSpoolTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let t=this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return!!t||!!e}isOpenObligationTransaction(){return!!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let t=this.getMoveCallTransaction(`${It}::user::redeem_rewards`),e=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),n=this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);return!!t&&(!!e||!!n)}get helperClaimLendingReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperClaimBorrowV2Reward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${It}::user::redeem_rewards`)).map(e=>new w(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new w(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new w(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new w(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new w(t,this.txb)}get helperBurnScoin(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new w(t,this.txb)}get helperSlippage(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage"));return new w(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new w(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new w(t,this.txb)}get helperDepositCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new w(t,this.txb)}get helperWithdrawCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new w(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new w(t,this.txb)}get helperBorrowWithReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new w(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new w(t,this.txb)}decodeMigrateScoin(){return{txType:A.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let e=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),a=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:A.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:a,veScaKey:t}}}decodeOpenObligation(){return{txType:A.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLendingScoin(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperBurnScoin.getNestedInputParam(1),n=new _(e,this.txb).getAmountInput().reduce((a,r)=>a+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:a,collateralCoinName:t}}}decodeWithdrawCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),e=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),a=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"WithdrawCollateral",intentionData:{amount:e,collateralCoinName:t,obligationKey:a,obligationId:n}}}decodeBorrow(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),a=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"Borrow",intentionData:{amount:e,coinName:t,obligationKey:a,obligationId:n}}}decodeBorrowWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),a=this.helperBorrow.decodeSharedObjectId(1),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeBorrowWithReferral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),a=this.helperBorrowWithReferral.decodeSharedObjectId(1),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:A.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:t,obligationKey:r,obligationId:a,veScaKey:e}}}decodeRepay(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperRepay.getNestedInputParam(3),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"Repay",intentionData:{amount:n,obligationId:a,coinName:t}}}decodeRepayWithBoost(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),a=new _(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:a,obligationId:r,coinName:t,veScaKey:e}}}decodeStakeSpool(){let t;this.isCreateStakeAccountTransaction()||(t=this.helperStake.decodeOwnedObjectId(1));let e=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);e=new _(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let r=this.helperStake.getNestedInputParam(2);e=new _(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"StakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeUnstakeSpool(){let t=this.helperUnstake.decodeOwnedObjectId(1),e=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),a=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.Other,type:"UnstakeSpool",intentionData:{amount:e,marketCoinName:a,stakeAccountId:t}}}decodeSupplyWithStakeSpool(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),a;return this.isCreateStakeAccountTransaction()||(a=this.helperStake.decodeOwnedObjectId(1)),{txType:A.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:a}}}decodeUnstakeAndWithdraw(){let t=[];this.helperUnstakes.forEach(a=>{let r=a.decodeOwnedObjectId(1),i=a.decodeInputU64(2);t.push({id:r,coin:i})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let a=this.helperBurnScoin.getNestedInputParam(1);n=new _(a,this.txb).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:A.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeMoveAsset(){let t=[];this.helperUnstakes.forEach(i=>{let s=i.decodeOwnedObjectId(1),c=i.decodeInputU64(2);t.push({id:s,coin:c})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);n=new _(i,this.txb).getAmountInput().reduce((s,c)=>s+c,0)}let a=this.helperSlippage.decodePureArg(1,"u64"),r=this.helperSlippage.decodePureArg(2,"string");return{txType:A.TransactionType.Other,type:"MigrateWusdcToUsdc",intentionData:{amount:n,coinName:e,slippage:a,validSwapAmount:r,stakeAccountId:t}}}decodeClaimReward(){let t=[],e=[],n=[];return this.helperClaimLendingReward.forEach(a=>{let r=a.decodeOwnedObjectId(2),i=a.typeArg(0),s=this.scallop.utils.parseCoinNameFromType(i);t.push({stakeMarketCoinName:s,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(a=>{let r=a.decodeSharedObjectId(3),i=a.decodeOwnedObjectId(4),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));e.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),this.helperClaimBorrowReward.forEach(a=>{let r=a.decodeSharedObjectId(2),i=a.decodeOwnedObjectId(3),s=this.scallop.utils.parseCoinNameFromType(a.typeArg(0));n.push({obligationId:i,obligationKey:r,rewardCoinName:s})}),{txType:A.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};var qo=require("@msafe/sui3-utils");var $o=class extends Tt{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return!!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(e=>new w(e,this.txb))}get helperBindReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new w(t,this.txb)}decodeCreateReferralLink(){return{txType:qo.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:qo.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:qo.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};var re=require("@msafe/sui3-utils");var Ko=class extends Tt{decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca()}isStakeScaFirsTime(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let t=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),e=this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!t&&!!e}isRedeemSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return!!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}get helperStakeMoreSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new w(t,this.txb)}get helperStakeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new w(t,this.txb)}get helperExtendStakePeriod(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new w(t,this.txb)}get helperRedeemSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new w(t,this.txb)}get helperRenewExpired(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new w(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${It}::user::unstake`));return new w(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new w(t,this.txb)}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new w(t,this.txb)}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:re.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new _(t,this.txb).getAmountInput().reduce((b,S)=>b+S,0),a=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,i=[],s=[],c=[];this.helperOldUnstakeObligation.moveCall&&(i=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(s=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let l=!1,d=!1,u,p,m=[{condition:i,isOld:!0},{condition:s,isOld:!1},{condition:c,isOld:!1}];for(let b=0;b<m.length;b++)m[b].condition.length>1&&([p,u]=m[b].condition,l=!0,d=m[b].isOld);return{txType:re.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,lockPeriodInDays:e,obligationId:u,obligationKey:p,veScaKey:a,isHaveRedeem:r,isObligationLocked:l,isOldBorrowIncentive:d}}}decodeExtendStakePeriod(){let t=this.helperExtendStakePeriod.decodeInputU64(4),e=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],a=[],r=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(r=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let i=!1,s=!1,c,l,d=[{condition:n,isOld:!0},{condition:a,isOld:!1},{condition:r,isOld:!1}];for(let u=0;u<d.length;u++)d[u].condition.length>1&&([l,c]=d[u].condition,i=!0,s=d[u].isOld);return{txType:re.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:l,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new _(t,this.txb).getAmountInput().reduce((m,b)=>m+b,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:re.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:d,obligationKey:u,isOldBorrowIncentive:l,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):t=this.helperStakeMoreSca.getNestedInputParam(4);let n=new _(t,this.txb).getAmountInput().reduce((m,b)=>m+b,0),a=[],r=[],i,s=[];this.helperOldUnstakeObligation.moveCall&&(a=[this.helperOldUnstakeObligation.decodeSharedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeSharedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(i=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(s=[this.helperStakeObligationWithVeSca.decodeSharedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,u,p=[{condition:a,isOld:!0},{condition:r,isOld:!1},{condition:s,isOld:!1}];for(let m=0;m<p.length;m++)p[m].condition.length>1&&([u,d]=p[m].condition,c=!0,l=p[m].isOld);return{txType:re.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:d,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:l}}}};var Il=j(require("sort-keys-recursive")),g=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Il.default)(this.data))}};var Vo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrow(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var Qo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var Ho=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.borrowWithReferral(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var Go=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claim(this.data.lendingIncentive,this.data.borrowIncentiveV2,this.data.borrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var zo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.depositCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,e.account.address)}static fromData(e){return new o(e)}};var Jo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAndClaim(this.data.obligationKey,this.data.obligationId,this.data.rewardCoinName,this.data.veScaKey)}static fromData(e){return new o(e)}};var Yo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateAllMarketCoin()}static fromData(e){return new o(e)}};var Xo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.migrateLendingWusdcToUsdcNative(this.data.coinName,Number(this.data.amount),this.data.slippage,this.data.validSwapAmount,this.data.stakeAccountId)}static fromData(e){return new o(e)}};var Zo=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.openObligation()}static fromData(e){return new o(e)}};var ta=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repay(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var ea=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.repayWithBoost(this.data.coinName,Number(this.data.amount),this.data.obligationId,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var na=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var oa=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.deposit(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var aa=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstake(this.data.marketCoinName,Number(this.data.amount),void 0,e.account.address)}static fromData(e){return new o(e)}};var ra=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.unstakeAndWithdraw(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId)}static fromData(e){return new o(e)}};var ia=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),this.data.obligationId,this.data.obligationKey,e.account.address)}static fromData(e){return new o(e)}};var sa=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdraw(this.data.coinName,Number(this.data.amount),e.account.address)}static fromData(e){return new o(e)}};var ca=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.bindReferral(this.data.veScaKey)}static fromData(e){return new o(e)}};var la=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.claimRevenuReferral(this.data.veScaKey,this.data.coins)}static fromData(e){return new o(e)}};var da=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.createReferralLink()}static fromData(e){return new o(e)}};var ua=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendPeriodAndStakeMoreSca(this.data.amount,this.data.veScaKey,this.data.lockPeriodInDays,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var pa=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.extendStakeScaLockPeriod(this.data.lockPeriodInDays,this.data.veScaKey,this.data.obligationId,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var ma=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.redeemSca(this.data.veScaKey)}static fromData(e){return new o(e)}};var fa=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.renewExpiredStakeSca(this.data.amount,this.data.lockPeriodInDays,this.data.vescaKey,this.data.isHaveRedeem,this.data.obligation,this.data.obligationKey,this.data.isObligationLocked,this.data.isOldBorrowIncentive,e.account.address)}static fromData(e){return new o(e)}};var ba=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.stakeSca(this.data.amount,this.data.isObligationLocked,this.data.isOldBorrowIncentive,this.data.obligationId,this.data.obligationKey,this.data.lockPeriodInDays,this.data.veScaKey,e.account.address)}static fromData(e){return new o(e)}};var ga=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.supplyAndStake(this.data.coinName,Number(this.data.amount),this.data.stakeAccountId,e.account.address)}static fromData(e){return new o(e)}};var ha=class o extends g{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){return e.scallop.client.withdrawUnlockedSca(this.data.vescaKey,e.account.address)}static fromData(e){return new o(e)}};var ya=class{id;addresses;constructor(t){let{id:e}=t;this.id=e}getId(){return this.id}getAddresses(){return this.addresses}get(t){if(!this.addresses)throw new Error(`Failed to fetch address ${this.id}`);return t.split(".").reduce((n,a)=>typeof n=="object"?n[a]:n,this.addresses)}async read(){let t={method:"GET",headers:new Headers({"Content-Type":"application/json"})},e=await fetch(`${bl}/addresses/${this.id}`,t);if(e.status===200){let n=await e.json();if("mainnet"in n){this.addresses=n.mainnet;return}throw new Error("Mainnet key is not in address!")}throw new Error(`Failed to fetch address with id ${this.id}`)}};var I=require("@mysten/sui.js/transactions"),Pi=j(require("bignumber.js"));var kl=require("@mysten/sui.js/transactions"),Sa=class{params;isTestnet;address;query;utils;client;constructor(t,e){this.params=t,this.client=t.client;let{address:n,query:a,utils:r}=e;this.address=n,this.query=a,this.utils=r,this.isTestnet=t.networkType?t.networkType==="testnet":!1}createTxBlock(t){return new kl.TransactionBlock(t)}async selectCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseCoinType(e),i=await this.utils.selectCoinIds(n,r,a),[s,c]=this.utils.takeAmountFromCoins(t,i,n);return{takeCoin:s,leftCoin:c}}async selectMarketCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseMarketCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.reduce((u,p)=>(u+=Number(p.balance),u),0),c=i.map(u=>u.objectId),[l,d]=this.utils.takeAmountFromCoins(t,c,Math.min(n,s));return{takeCoin:l,leftCoin:d,totalAmount:s}}async selectSCoin(t,e,n,a=this.params.walletAddress){let r=this.utils.parseSCoinType(e),i=await this.utils.selectCoins(n,r,a),s=i.map(u=>u.objectId),c=i.reduce((u,p)=>u+Number(p.balance),0),[l,d]=this.utils.takeAmountFromCoins(t,s,Math.min(c,n));return{takeCoin:l,leftCoin:d,totalAmount:c}}};var Dl=require("@mysten/sui.js/transactions"),Ke=j(require("bignumber.js"));var ie=async(o,t)=>{let e=t,n=o.address.get("core.object")||Wo,a=[],r=!1,i=null;do{let d=await o.client.getOwnedObjects({owner:e,filter:{StructType:`${n}::obligation::ObligationKey`},cursor:i});a.push(...d.data),d.hasNextPage&&d.nextCursor?(r=!0,i=d.nextCursor):r=!1}while(r);let s=a.map(d=>d?.data?.objectId).filter(d=>d!==void 0),c=await o.client.multiGetObjects({ids:s,options:{showContent:!0,showType:!0}}),l=[];for(let d=0;d<c.length;d++){let u=c[d].data.objectId,{content:p}=c[d].data;if(p&&"fields"in p){let m=p.fields,b=String(m.ownership.fields.of),S=await Ti(o,b);l.push({id:b,keyId:u,locked:S})}}return l},Ti=async(o,t)=>{let e=await o.client.getObject({id:t,options:{showContent:!0}}),n=!1;return e.data&&e?.data?.content?.dataType==="moveObject"&&"lock_key"in e.data.content.fields&&(n=!!e.data.content.fields.lock_key),n},xl=async(o,t,e)=>{let n=e||[...rt],a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,Ke.default)(c[m]??0).plus(p.balance).toNumber())}}),c},vl=async(o,t,e)=>{let n=e,a=o.utils.parseCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,Ke.default)(c).plus(u.balance).toNumber()}}),c},Al=async(o,t,e)=>{let n=e||[...rt].map(d=>o.utils.parseMarketCoinName(d)),a=t,r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:a,filter:{MatchAny:n.map(u=>({StructType:`0x2::coin::Coin<${o.utils.parseMarketCoinType(u)}>`}))},options:{showType:!0,showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c={};return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{let u=d.type;if(d.content&&"fields"in d.content){let p=d.content.fields,m=o.utils.parseCoinNameFromType(u);m&&(c[m]=(0,Ke.default)(c[m]??0).plus(p.balance).toNumber())}}),c},Ol=async(o,t,e)=>{let n=e,a=o.utils.parseMarketCoinType(t),r=[],i=!1,s=null;do{let d=await o.client.getOwnedObjects({owner:n,filter:{StructType:`0x2::coin::Coin<${a}>`},options:{showContent:!0},cursor:s});r.push(...d.data),d.hasNextPage&&d.nextCursor?(i=!0,s=d.nextCursor):i=!1}while(i);let c=0;return r.map(d=>d.data).filter(d=>d!=null).forEach(d=>{if(d.content&&"fields"in d.content){let u=d.content.fields;c=(0,Ke.default)(c).plus(u.balance).toNumber()}}),c},Pl=async(o,t)=>{let n=`${o.address.get("core.packages.query.id")}::obligation_query::obligation_data`,a=new Dl.TransactionBlock;return a.moveCall({target:n,arguments:[a.object(t)]}),(await o.client.devInspectTransactionBlock({transactionBlock:a,sender:o.params.walletAddress})).events[0].parsedJson};var T=require("@mysten/sui.js/utils"),Ve=async(o,t)=>{let e=t,n=o.address.get("spool.object"),a=`${n}::spool_account::SpoolAccount`,r=[],i=!1,s=null;do{let p=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},options:{showContent:!0,showType:!0},cursor:s});r.push(...p.data),p.hasNextPage&&p.nextCursor?(i=!0,s=p.nextCursor):i=!1}while(i);let c={sweth:[],ssui:[],susdc:[],swusdc:[],swusdt:[],scetus:[],safsui:[],shasui:[],svsui:[]},l=Object.keys(c).reduce((p,m)=>{let b=o.utils.parseCoinName(m),S=o.utils.parseMarketCoinType(b),C={...p},x=`${n}::spool_account::SpoolAccount<${S}>`;return C[m]=x,C},{}),d=r.map(p=>p?.data?.objectId).filter(p=>p!==void 0);return(await o.client.multiGetObjects({ids:d,options:{showContent:!0,showType:!0}})).forEach(p=>{let m=p.data.objectId,b=p.data.type;if(p.data.content&&"fields"in p.data.content){let S=p.data.content.fields,C=String(S.spool_id),x=String(S.stake_type.fields.name),q=Number(S.stakes),B=Number(S.index),Q=Number(S.points),$=Number(S.total_points);(0,T.normalizeStructTag)(b)===l.sweth?c.sweth.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.ssui?c.ssui.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.swusdc?c.swusdc.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.swusdt?c.swusdt.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.scetus?c.scetus.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.safsui?c.safsui.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.shasui?c.shasui.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.svsui?c.svsui.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,T.normalizeStructTag)(b)===l.susdc&&c.susdc.push({id:m,type:(0,T.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,T.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$})}}),c},Ci=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.id`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=Number(c.max_distributed_point),d=Number(c.distributed_point),u=Number(c.distributed_point_per_period),p=Number(c.point_distribution_time),m=Number(c.max_stakes),b=String(c.stake_type.fields.name),S=Number(c.stakes),C=Number(c.index),x=Number(c.created_at),q=Number(c.last_update);n={id:i,type:(0,T.normalizeStructTag)(s),maxPoint:l,distributedPoint:d,pointPerPeriod:u,period:p,maxStake:m,stakeType:(0,T.normalizeStructTag)(b),totalStaked:S,index:C,createdAt:x,lastUpdate:q}}}return n},Ii=async(o,t)=>{let e=o.address.get(`spool.pools.${t}.rewardPoolId`),n,a=await o.client.getObject({id:e,options:{showContent:!0,showType:!0}});if(a.data){let r=a.data,i=r.objectId,s=r.type;if(r.content&&"fields"in r.content){let c=r.content.fields,l=String(c.spool_id),d=Number(c.exchange_rate_numerator),u=Number(c.exchange_rate_denominator),p=Number(c.rewards),m=Number(c.claimed_rewards);n={id:i,type:(0,T.normalizeStructTag)(s),stakePoolId:l,ratioNumerator:d,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};var Ll=require("@mysten/sui.js/transactions"),Ip=require("@mysten/sui.js/utils"),kp=j(require("bignumber.js"));var E=o=>{let{sender:t}=o.blockData;if(!t)throw new Error("Sender is required");return t},Bl=(o,t,e,n)=>{let a=!n,r=!a&&n*1e3<=new Date().getTime();if(a||r)if(o!==void 0&&t!==void 0){if(t<=0)throw new Error("Lock period must be greater than 0");if(typeof o=="number"&&o<1e10)throw new Error(`Minimum lock amount for ${r?"renewing expired veSca":"initial lock"} is 10 SCA`);if(t*86400>126144e3)throw new Error(`Maximum lock period is ~4 years (${1460} days)`)}else throw new Error(`SCA amount and lock period is required for ${r?"renewing expired veSca":"initial lock"}`);else{if(se(n),typeof o=="number"&&o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(e&&n&&e-n>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)}},Ml=(o,t,e)=>{if(se(e),o<=0)throw new Error("Lock period must be greater than 0");if(!!e&&e*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");if(e&&t-(e??0)>126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},jl=(o,t)=>{if(se(t),o<1e9)throw new Error("Minimum top up amount is 1 SCA");if(!!t&&t*1e3<=new Date().getTime())throw new Error("veSca is expired, use renewExpiredVeScaQuick instead")},Nl=(o,t,e)=>{if(se(e),o<1e10)throw new Error("Minimum lock amount for renewing expired vesca 10 SCA");if(t*86400>=126057600)throw new Error(`Maximum lock period is ~4 years (${1459} days)`)},se=o=>{if(o===void 0)throw new Error("veSca not found")};var Qe=require("@mysten/sui.js/utils"),Tp=j(require("bignumber.js"));var Cp=o=>({pointType:(0,Qe.normalizeStructTag)(o.point_type.name),weightedAmount:Number(o.weighted_amount),points:Number(o.points),totalPoints:Number(o.total_points),index:Number(o.index)}),El=o=>({poolType:(0,Qe.normalizeStructTag)(o.pool_type.name),debtAmount:Number(o.debt_amount),pointList:o.points_list.reduce((t,e)=>{let n=Cp(e),a=(0,Qe.parseStructTag)(n.pointType).name.toLowerCase();return t[a]=n,t},{})});var Ta=o=>{let t=o.slice(1).toLowerCase();return o.charAt(0).toLowerCase()==="s"&&[...new Set([...rt,...Lo,...hl])].includes(t)},ki=o=>{switch(o){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return o.toUpperCase()}},Wl=o=>{let t=new Date(o*1e3),e=new Date(o*1e3);e.setUTCHours(0,0,0,0),t.getUTCHours()>=0&&e.setUTCDate(e.getUTCDate()+1);let n=new Date().getTime();return e.getTime()-n>126144e3*1e3&&e.setUTCDate(e.getUTCDate()-1),Math.floor(e.getTime()/1e3)};var Ul=async(o,t,e,n)=>{let a=n||[...Dt],r=o.address.get("borrowIncentive.query"),i=o.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new Ll.TransactionBlock;c.moveCall({target:s,arguments:[c.object(i),c.object(t)]});let d=(await o.client.devInspectTransactionBlock({transactionBlock:c,sender:e})).events[0].parsedJson,u={};return d.pool_records.forEach(p=>{let m=El(p),{poolType:b}=m,S=o.utils.parseCoinNameFromType(b);a.length>=1&&a.includes(S)&&(u[S]=m)},{}),u};var Fl=async({address:o,client:t},e)=>{let n=o.get("borrowIncentive.object"),a=o.get("borrowIncentive.incentiveAccounts"),r=o.get("core.object"),i=await t.getObject({id:a,options:{showContent:!0}});if(i?.data?.content?.dataType!=="moveObject")return null;let s=i.data.content.fields.accounts.fields.id.id,c=await t.getDynamicFieldObject({parentId:s,name:{type:`${n}::typed_id::TypedID<${r}::obligation::Obligation>`,value:e}});return c?.data?.content?.dataType!=="moveObject"?null:c.data.content.fields.value.fields.binded_ve_sca_key?.fields.id??null};var ql=async(o,t)=>{let e=o.address.get(`core.coins.${t}.oracle.pyth.feedObject`),n=await o.client.getObject({id:e,options:{showContent:!0}});if(n.data){let a=n.data;if(a.content&&"fields"in a.content){let r=a.content.fields,i=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude),s=Number(r.price_info.fields.price_feed.fields.price.fields.expo.fields.negative),c=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude),l=Number(r.price_info.fields.price_feed.fields.price.fields.price.fields.negative);return c*10**((s?-1:1)*i)*(l?-1:1)}}return 0};var Ca=j(require("bignumber.js")),$l=async(o,t)=>{let e=t,a=`${o.address.get("vesca.id")}::ve_sca::VeScaKey`,r=[],i=!1,s=null;do{let l=await o.client.getOwnedObjects({owner:e,filter:{StructType:a},cursor:s});r.push(...l.data),l.hasNextPage&&l.nextCursor?(i=!0,s=l.nextCursor):i=!1}while(i);return r.map(l=>l.data).filter(l=>!!l)},Kl=async(o,t)=>{let n=(await $l(o,t)).map(r=>r.objectId),a=[];for(let r=0;r<n.length;r++){let i=await Di(o,n[r]);i&&a.push(i)}return a},Di=async(o,t,e)=>{let n=o.address.get("vesca.tableId"),a=t||(await $l(o,e))[0].objectId,r,s=(await o.client.getDynamicFieldObject({parentId:n,name:{type:"0x2::object::ID",value:a}})).data;if(s&&s.content&&s.content.dataType==="moveObject"&&"fields"in s.content){let c=s.content.fields.value.fields;r={id:s.objectId,keyId:a,lockedScaAmount:(0,Ca.default)(c.locked_sca_amount).toNumber(),lockedScaCoin:(0,Ca.default)(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:(0,Ca.default)(c.unlock_at).toNumber()}}return r};var Ia=class{params;address;client;utils;constructor(t,e){this.params=t,this.client=t.client;let{address:n,utils:a}=e;this.address=n,this.utils=a}async getObligations(t=this.params.walletAddress){return ie(this,t)}async getCoinAmounts(t,e){return xl(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return vl(this,t,e)}async getMarketCoinAmounts(t,e){return Al(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return Ol(this,t,e)}async getPriceFromPyth(t){return ql(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return Ve(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...kt]){let e={};for(let n=0;n<t.length;n++){let a=t[n],r=await Ci(this,a);r&&(e[a]=r)}return e}async getStakePool(t){return Ci(this,t)}async getStakeRewardPools(t=[...kt]){let e={};for(let n=0;n<t.length;n++){let a=await Ii(this,t[n]);a&&(e[t[n]]=a)}return e}async getStakeRewardPool(t){return Ii(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return Ul(this,t,e,n)}async getObligationCoinNames(t){let e=await Pl(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),a=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...a])].map(s=>this.utils.parseCoinNameFromType(s))}};var ce=require("@mysten/sui.js/utils");var ka=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Ta(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+ki(e)}return ki(t)}parseCoinType(t){let e=Ta(t)?this.parseCoinName(t):t,n=wl[e];return[K.wusdc,K.wusdt,K.weth,K.wbtc,K.wsol,K.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${yi.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||Wo,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=(0,ce.normalizeStructTag)(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,a=t.match(n),r=t.includes("reserve::MarketCoin");e=a?.[1]||t;let i={[`${K.wusdc}::coin::COIN`]:"wusdc",[`${K.wusdt}::coin::COIN`]:"wusdt",[`${K.weth}::coin::COIN`]:"weth",[`${K.wbtc}::coin::COIN`]:"wbtc",[`${K.wsol}::coin::COIN`]:"wsol",[`${K.wapt}::coin::COIN`]:"wapt"},s={[`${yi.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=>Uo[t];getBorrowIncentiveRewardCoinName=t=>Sl[t];getCoinDecimal(t){return yl[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 Tl[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=ce.SUI_TYPE_ARG,n){let a=n,r=[],i=0,s=!0,c=null;for(;s&&i<t;){let l=await this.client.getCoins({owner:a,coinType:e,cursor:c});l.data.sort((d,u)=>parseInt(u.balance,10)-parseInt(d.balance,10));for(let d=0;d<l.data.length&&(r.push({objectId:l.data[d].coinObjectId,digest:l.data[d].digest,version:l.data[d].version,balance:l.data[d].balance}),i+=parseInt(l.data[d].balance,10),!(i>=t));d++);c=l.nextCursor,s=l.hasNextPage}if(!r.length)throw new Error("No valid coins found for the transaction.");return r}async selectCoinsMarketCoin(t=ce.SUI_TYPE_ARG,e){let n=e,a=[],r=!0,i=null;for(;r;){let s=await this.client.getCoins({owner:n,coinType:t,cursor:i});s.data.sort((c,l)=>parseInt(l.balance,10)-parseInt(c.balance,10));for(let c=0;c<s.data.length&&(a.push({objectId:s.data[c].coinObjectId,digest:s.data[c].digest,version:s.data[c].version,balance:s.data[c].balance}),!(a.length>50));c++);i=s.nextCursor,r=s.hasNextPage}return a}async selectCoinIds(t,e=ce.SUI_TYPE_ARG,n){return(await this.selectCoins(t,e,n)).map(r=>r.objectId)}parseAprToApy(t,e=365){return(1+t/e)**e-1}parseApyToApr(t,e=365){return((1+t)**(1/e)-1)*e}takeAmountFromCoins(t,e,n){let a=e.map(s=>t.object(s)),r=a[0];a.length>1&&t.mergeCoins(r,a.slice(1));let[i]=t.splitCoins(r,[t.pure(n)]);return[i,r]}getUnlockAt(t,e){let n=Math.floor(new Date().getTime()/1e3),a=e?Math.max(e-n,0):0,r=0;if(a===0){let i=(t??1)*86400;r=Math.min(n+i,n+126144e3)}else{let i=Math.min(t?t*86400+a:a,126144e3);r=n+i}return Wl(r)}parseSCoinName(t){if(Ta(t)&&it.includes(t))return t;let e=`s${t}`;if(it.includes(e))return e}};var ct=require("@mysten/sui.js/utils");var le=async(...o)=>{let[t,e,n]=o;if(o.length===3&&n&&typeof n=="string"){let i=await Di(t.query,n);return i||void 0}let a=E(e),r=await Kl(t.query,a);if(r.length!==0)return r[0]};var xi=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&n&&a&&typeof n=="string"){let c=await Ti(t.query,n);return{obligationId:n,obligationKey:a,obligationLocked:c}}let r=E(e),i=await ie(t.query,r);if(i.length===0)throw new Error(`No obligation found for sender ${r}`);let s=i.find(c=>c.id===n||c.keyId===a)??i[0];return{obligationId:s.id,obligationKey:s.keyId,obligationLocked:s.locked}},Dp=async({builder:o,txBlock:t})=>{let e={borrowIncentivePkg:o.address.get("borrowIncentive.id"),query:o.address.get("borrowIncentive.query"),incentivePools:o.address.get("borrowIncentive.incentivePools"),incentiveAccounts:o.address.get("borrowIncentive.incentiveAccounts"),obligationAccessStore:o.address.get("core.obligationAccessStore"),config:o.address.get("borrowIncentive.config")},n={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},a={table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{stakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(ct.SUI_CLOCK_OBJECT_ID)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(a.config),t.object(a.treasury),t.object(a.table),t.object(s),t.object(ct.SUI_CLOCK_OBJECT_ID)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(ct.SUI_CLOCK_OBJECT_ID)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(ct.SUI_CLOCK_OBJECT_ID)],typeArguments:[ct.SUI_TYPE_ARG]})},claimBorrowIncentive:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.borrowIncentivePkg}::user::redeem_rewards`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(ct.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},oldClaimBorrowIncentive(r,i,s){let c=o.utils.parseCoinType(s);return t.moveCall({target:`${n.id}::user::redeem_rewards`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(ct.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})}}},W=async({builder:o,txBlock:t})=>{let e=await Dp({builder:o,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await xi(o,t,n,a),c=!!t.blockData.transactions.find(l=>l.kind==="MoveCall"&&(l.target===`${It}::user::unstake`||l.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));(!s||c)&&e.stakeObligation(r,i)},unstakeObligationQuick:async(n,a)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await xi(o,t,n,a);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,a,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await xi(o,t,n,a),l=!!t.blockData.transactions.find(async d=>d.kind==="MoveCall"&&(d.target===`${It}::user::unstake`||d.target===`${o.address.get("borrowIncentive.id")}::user::unstake`));if(!c||l){let d=await Fl({address:o.address,client:o.client},i);if(r&&r!==d)throw new Error("Binded veScaKey is not equal to the provided veScaKey");d?e.stakeObligationWithVesca(i,s,d):e.stakeObligation(i,s)}},claimBorrowIncentiveQuick:(n,a,r)=>e.claimBorrowIncentive(a,r,n)}};var tt=require("@mysten/sui.js/utils");var Ge=require("@mysten/sui.js/utils"),Ql=j(require("axios"));var Vl={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};var Da=require("@mysten/sui.js/bcs"),He=require("@mysten/sui.js/utils"),vi=16*1024,xa=class{provider;pythStateId;wormholeStateId;pythPackageId;wormholePackageId;priceTableInfo;priceFeedObjectIdCache=new Map;baseUpdateFee;constructor(t,e,n){this.provider=t,this.pythStateId=e,this.wormholeStateId=n,this.pythPackageId=void 0,this.wormholePackageId=void 0}async getBaseUpdateFee(){if(this.baseUpdateFee===void 0){let t=await this.provider.getObject({id:this.pythStateId,options:{showContent:!0}});if(!t.data||!t.data.content||t.data.content.dataType!=="moveObject")throw new Error("Unable to fetch pyth state object");this.baseUpdateFee=t.data.content.fields.base_update_fee}return this.baseUpdateFee}async getPackageId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}}).then(n=>{if(n.data?.content?.dataType==="moveObject")return n.data.content.fields;throw new Error(`Cannot fetch package id for object ${t}`)});if("upgrade_cap"in e)return e.upgrade_cap.fields.package;throw new Error("upgrade_cap not found")}async verifyVaas(t,e){let n=await this.getWormholePackageId(),a=[];return t.forEach(r=>{let[i]=e.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[e.object(this.wormholeStateId),e.pure(Da.bcs.ser("vector<u8>",Array.from(r),{maxSize:vi}).toBytes()),e.object(He.SUI_CLOCK_OBJECT_ID)]});a.push(i)}),a}async updatePriceFeeds(t,e,n){let a=await this.getPythPackageId(),r;if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let i=this.extractVaaBytesFromAccumulatorMessage(e[0]),s=await this.verifyVaas([i],t);[r]=t.moveCall({target:`${a}::pyth::create_authenticated_price_infos_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Da.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:vi}).toBytes()),s[0],t.object(He.SUI_CLOCK_OBJECT_ID)]});let c=[],l=await this.getBaseUpdateFee(),d=t.splitCoins(t.gas,n.map(()=>t.pure(l))),u=0;for(let p=0;p<n.length;p++){let m=await this.getPriceFeedObjectId(n[p]);if(!m)throw new Error(`Price feed ${n[0]} not found, please create it first`);c.push(m),[r]=t.moveCall({target:`${a}::pyth::update_single_price_feed`,arguments:[t.object(this.pythStateId),r,t.object(m),d[u],t.object(He.SUI_CLOCK_OBJECT_ID)]}),u++}return t.moveCall({target:`${a}::hot_potato_vector::destroy`,arguments:[r],typeArguments:[`${a}::price_info::PriceInfo`]}),c}async createPriceFeed(t,e){let n=await this.getPythPackageId();if(e.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let a=this.extractVaaBytesFromAccumulatorMessage(e[0]),r=await this.verifyVaas([a],t);t.moveCall({target:`${n}::pyth::create_price_feeds_using_accumulator`,arguments:[t.object(this.pythStateId),t.pure(Da.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:vi}).toBytes()),r[0],t.object(He.SUI_CLOCK_OBJECT_ID)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(t){let e=t.replace("0x","");if(!this.priceFeedObjectIdCache.has(e)){let{id:n,fieldType:a}=await this.getPriceTableInfo(),r=await this.provider.getDynamicFieldObject({parentId:n,name:{type:`${a}::price_identifier::PriceIdentifier`,value:{bytes:Array.from(Buffer.from(e,"hex"))}}});if(!r.data||!r.data.content)return;if(r.data.content.dataType!=="moveObject")throw new Error("Price feed type mismatch");this.priceFeedObjectIdCache.set(e,r.data.content.fields.value)}return this.priceFeedObjectIdCache.get(e)}async getPriceTableInfo(){if(this.priceTableInfo===void 0){let t=await this.provider.getDynamicFieldObject({parentId:this.pythStateId,name:{type:"vector<u8>",value:"price_info"}});if(!t.data||!t.data.type)throw new Error("Price Table not found, contract may not be initialized");let e=t.data.type.replace("0x2::table::Table<","");e=e.replace("::price_identifier::PriceIdentifier, 0x2::object::ID>",""),this.priceTableInfo={id:t.data.objectId,fieldType:e}}return this.priceTableInfo}extractVaaBytesFromAccumulatorMessage(t){let n=7+t.readUint8(6)+1,a=t.readUint16BE(n),r=n+2;return t.subarray(r,r+a)}};var xp=async(o,t)=>(await Ql.default.get(`${o}/api/latest_vaas`,{params:{ids:t}})).data.map(a=>Buffer.from(a,"base64")),ze=async(o,t,e)=>{let n=e??[...new Set([...rt,...Lo])],a=o.isTestnet?["pyth"]:["pyth"];if(a.includes("pyth")){let i=new xa(o.client,o.address.get("core.oracles.pyth.state"),o.address.get("core.oracles.pyth.wormholeState")),s=[];await Promise.all(n.map(async l=>s.push(o.address.get(`core.coins.${l}.oracle.pyth.feed`))));let c=o.params.pythEndpoints??Vl[o.isTestnet?"testnet":"mainnet"];try{let l=await xp(c[0],s);await i.updatePriceFeeds(t,l,s)}catch(l){console.warn(`Failed to update price feeds with endpoint ${c[0]}: ${l}`)}}let r=[...new Set(n)];for(let i=0;i<r.length;i++)await vp(o,t,r[i],a)},vp=async(o,t,e,n)=>{let a=o.utils.parseCoinType(e);Ap(t,n,o.address.get("core.packages.xOracle.id"),o.address.get("core.oracles.xOracle"),o.address.get("core.packages.pyth.id"),o.address.get("core.oracles.pyth.registry"),o.address.get("core.oracles.pyth.state"),o.address.get(`core.coins.${e}.oracle.pyth.feedObject`),o.address.get("core.packages.switchboard.id"),o.address.get("core.oracles.switchboard.registry"),o.address.get(`core.coins.${e}.oracle.switchboard`),o.address.get("core.packages.supra.id"),o.address.get("core.oracles.supra.registry"),o.address.get("core.oracles.supra.holder"),a)},Ap=(o,t,e,n,a,r,i,s,c,l,d,u,p,m,b)=>{let S=Op(o,e,n,b);return t.includes("pyth")&&Bp(o,a,S,i,s,r,b),t.includes("switchboard")&&_p(o,c,S,d,l,b),t.includes("supra")&&Rp(o,u,S,m,p,b),Pp(o,e,n,S,b),o},Op=(o,t,e,n)=>{let a=typeof e=="string"?o.object(e):e,r=`${t}::x_oracle::price_update_request`,i=[n];return o.moveCall({target:r,arguments:[a],typeArguments:i})},Pp=(o,t,e,n,a)=>{let r=`${t}::x_oracle::confirm_price_update_request`,i=[a],s=typeof e=="string"?o.object(e):e;return o.moveCall({target:r,arguments:[s,n,o.object(Ge.SUI_CLOCK_OBJECT_ID)],typeArguments:i}),o},Rp=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(Ge.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},_p=(o,t,e,n,a,r)=>{let i=typeof n=="string"?o.object(n):n,s=typeof a=="string"?o.object(a):a;o.moveCall({target:`${t}::rule::set_price`,arguments:[e,i,s,o.object(Ge.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},Bp=(o,t,e,n,a,r,i)=>{let s=typeof e=="string"?o.object(e):e,c=typeof n=="string"?o.object(n):n,l=typeof a=="string"?o.object(a):a,d=typeof r=="string"?o.object(r):r;o.moveCall({target:`${t}::rule::set_price`,arguments:[s,c,l,d,o.object(Ge.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})};var At=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("scoin.id")},n={};return await Promise.all(it.map(async a=>{let r=o.utils.getSCoinTreasury(a);n[a]=r})),{mintSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::mint_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]}),burnSCoin:(a,r)=>t.moveCall({target:`${e.pkgId}::s_coin_converter::burn_s_coin`,arguments:[t.object(n[a]),typeof r!="string"?r:t.pure(r)],typeArguments:[o.utils.parseSCoinType(a),o.utils.parseUnderlyingSCoinType(a)]})}};var Je=async(...o)=>{let[t,e,n,a]=o;if(o.length===3&&n)return{obligationId:n};if(o.length===4&&n&&a)return{obligationId:n,obligationKey:a};let r=E(t),i=await ie(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}},Mp=async({builder:o,txBlock:t})=>{let e={protocolPkg:o.address.get("core.packages.protocol.id"),market:o.address.get("core.market"),version:o.address.get("core.version"),coinDecimalsRegistry:o.address.get("core.coinDecimalsRegistry"),xOracle:o.address.get("core.oracles.xOracle")},a=`${o.address.get("referral.id")}::scallop_referral_program::REFERRAL_WITNESS`;return{openObligation:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation`,arguments:[t.object(e.version)]}),returnObligation:(r,i)=>t.moveCall({target:`${e.protocolPkg}::open_obligation::return_obligation`,arguments:[t.object(e.version),t.object(r),t.object(i)]}),openObligationEntry:()=>t.moveCall({target:`${e.protocolPkg}::open_obligation::open_obligation_entry`,arguments:[t.object(e.version)]}),addCollateral:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::deposit_collateral::deposit_collateral`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i)],typeArguments:[c]})},takeCollateral:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::withdraw_collateral::withdraw_collateral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},deposit:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},depositEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::mint::mint_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdraw:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},withdrawEntry:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::redeem::redeem_entry`,arguments:[t.object(e.version),t.object(e.market),typeof r!="string"?r:t.pure(r),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},borrow:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowEntry:(r,i,s,c)=>{let l=o.utils.parseCoinType(c);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_entry`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.pure(s),t.object(e.xOracle),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},borrowWithReferral:(r,i,s,c,l)=>{let d=o.utils.parseCoinType(l);return t.moveCall({target:`${e.protocolPkg}::borrow::borrow_with_referral`,arguments:[t.object(e.version),t.object(r),t.object(i),t.object(e.market),t.object(e.coinDecimalsRegistry),t.object(s),t.pure(c),t.object(e.xOracle),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,a]})},repay:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::repay::repay`,arguments:[t.object(e.version),t.object(r),t.object(e.market),typeof i!="string"?i:t.pure(i),t.object(tt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})},borrowFlashLoan:(r,i)=>{let s=o.utils.parseCoinType(i);return t.moveCall({target:`${e.protocolPkg}::flash_loan::borrow_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r)],typeArguments:[s]})},repayFlashLoan:(r,i,s)=>{let c=o.utils.parseCoinType(s);return t.moveCall({target:`${e.protocolPkg}::flash_loan::repay_flash_loan`,arguments:[t.object(e.version),t.object(e.market),t.pure(r),t.object(i)],typeArguments:[c]})}}},U=async({builder:o,txBlock:t})=>{let e=await Mp({builder:o,txBlock:t}),n=await At({builder:o,txBlock:t});return{normalMethod:e,addCollateralQuick:async(a,r,i)=>{let s=E(t),{obligationId:c}=await Je(t,o,i);if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);e.addCollateral(c,l,r)}else{let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);e.addCollateral(c,d,r),t.transferObjects([l],s)}},takeCollateralQuick:async(a,r,i,s)=>{let c=await Je(t,o,i,s),l=await o.query.getObligationCoinNames(c.obligationId);return await ze(o,t,l),e.takeCollateral(c.obligationId,c.obligationKey,a,r)},depositQuick:async(a,r,i)=>{if(r==="sui"){let[l]=t.splitCoins(t.gas,[a]);return e.deposit(l,r)}let{leftCoin:s,takeCoin:c}=await o.selectCoin(t,r,a,i);return t.transferObjects([s],i),e.deposit(c,r)},withdrawQuick:async(a,r)=>{let i=E(t),s=o.utils.parseMarketCoinName(r);try{let c=o.utils.parseSCoinName(r);if(!c)throw new Error(`No sCoin for ${r}`);let{leftCoin:l,takeCoin:d,totalAmount:u}=await o.selectSCoin(t,c,a,i);t.transferObjects([l],i);let p=n.burnSCoin(c,d),m=e.withdraw(p,r),b=a-u;try{if(b>0){let{leftCoin:S,takeCoin:C}=await o.selectMarketCoin(t,s,b,i);t.transferObjects([S],i),t.mergeCoins(m,[e.withdraw(C,r)])}}catch{}return m}catch{let{leftCoin:l,takeCoin:d}=await o.selectMarketCoin(t,s,a,i);return t.transferObjects([l],i),e.withdraw(d,r)}},borrowQuick:async(a,r,i,s)=>{let c=await Je(t,o,i,s),d=[...await o.query.getObligationCoinNames(c.obligationId),r];return await ze(o,t,d),e.borrow(c.obligationId,c.obligationKey,a,r)},borrowWithReferralQuick:async(a,r,i,s,c)=>{let l=await Je(t,o,s,c),u=[...await o.query.getObligationCoinNames(l.obligationId),r];return await ze(o,t,u),e.borrowWithReferral(l.obligationId,l.obligationKey,i,a,r)},repayQuick:async(a,r,i,s)=>{let c=await Je(t,o,i);if(r==="sui"){let[u]=t.splitCoins(t.gas,[a]);return e.repay(c.obligationId,u,r)}let{leftCoin:l,takeCoin:d}=await o.selectCoin(t,r,a,s);return t.transferObjects([l],s),e.repay(c.obligationId,d,r)},updateAssetPricesQuick:async a=>ze(o,t,a)}};var Ye=require("@mysten/sui.js/utils");var va=async({builder:o,txBlock:t})=>{let e={referralPgkId:o.address.get("referral.id"),referralBindings:o.address.get("referral.referralBindings"),referralRevenuePool:o.address.get("referral.referralRevenuePool"),authorizedWitnessList:o.address.get("referral.authorizedWitnessList"),referralTiers:o.address.get("referral.referralTiers"),version:o.address.get("referral.version")},n=o.address.get("vesca.table");return{bindToReferral:a=>t.moveCall({target:`${e.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,arguments:[t.object(e.referralBindings),t.pure(a),t.object(n),t.object(Ye.SUI_CLOCK_OBJECT_ID)],typeArguments:[]}),claimReferralTicket:a=>{let r=o.utils.parseCoinType(a);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(n),t.object(e.referralBindings),t.object(e.authorizedWitnessList),t.object(e.referralTiers),t.object(Ye.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},burnReferralTicket:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,arguments:[t.object(e.version),t.object(a),t.object(e.referralRevenuePool),t.object(Ye.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})},claimReferralRevenue:(a,r)=>{let i=o.utils.parseCoinType(r);return t.moveCall({target:`${e.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,arguments:[t.object(e.version),t.object(e.referralRevenuePool),t.object(a),t.object(Ye.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})}}},Hl=async({builder:o,txBlock:t})=>{let e=await va({builder:o,txBlock:t});return{claimReferralRevenueQuick:async(n,a,r=[...rt])=>{let i=[];for(let s=0;s<r.length;s++)if(r[s]==="sui"){let c=e.claimReferralRevenue(n,r[s]);i.push(c)}else{let c=e.claimReferralRevenue(n,r[s]);try{let l=await o.utils.selectCoinIds(1/0,o.utils.parseCoinType(r[s]),a);t.mergeCoins(c,l.slice(0,500))}catch{}finally{i.push(c)}}i.length>0&&t.transferObjects(i,t.pure(a))}}};var jp={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},Gl={check_slippage:(o,t,e,n,a)=>o.moveCall({target:`${jp.packageId}::slippage_check::check_slippage`,arguments:[t,o.pure(e),o.pure(n)],typeArguments:[a]})};var Xe=require("@mysten/sui.js/utils");var zl=async(o,t,e,n,a,r,i=!1)=>{let s=await At({builder:o,txBlock:t}),c=await Yl({builder:o,txBlock:t});try{let{takeCoin:l,leftCoin:d,totalAmount:u}=i?await o.selectSCoin(t,n,a,r):await o.selectMarketCoin(t,n,a,r);if(i){let p=s.burnSCoin(n,l);c.stake(e,p,n)}else c.stake(e,l,n);return t.transferObjects([d],r),u}catch{return 0}},Jl=async(...o)=>{let[t,e,n,a]=o;if(o.length===4&&a)return[a];let r=E(e);return(await Ve(t.query,r))[n].map(s=>s.id)},Np=async(...o)=>{let[t,e,n,a]=o,r=E(e),i=await Ve(t.query,r);if(i[n].length===0)throw new Error(`No stake account found for sender ${r}`);return a?i[n].filter(c=>c.id===a):i[n]},Yl=async({builder:o,txBlock:t})=>{let e={spoolPkg:o.address.get("spool.id")},n={},a={},r={};return kt.forEach(i=>{let s=o.address.get(`spool.pools.${i}.id`),c=o.address.get(`spool.pools.${i}.rewardPoolId`),l=o.utils.parseMarketCoinType(i);n[i]=s,a[i]=c,r[i]=l}),{createStakeAccount:i=>{let s=r[i],c=n[i];return t.moveCall({target:`${e.spoolPkg}::user::new_spool_account`,arguments:[t.object(c),t.object(Xe.SUI_CLOCK_OBJECT_ID)],typeArguments:[s]})},stake:(i,s,c)=>{let l=r[c],d=n[c];t.moveCall({target:`${e.spoolPkg}::user::stake`,arguments:[t.object(d),t.object(i),typeof s=="string"?t.pure(s):s,t.object(Xe.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},unstake:(i,s,c)=>{let l=r[c],d=n[c];return t.moveCall({target:`${e.spoolPkg}::user::unstake`,arguments:[t.object(d),t.object(i),t.pure(s),t.object(Xe.SUI_CLOCK_OBJECT_ID)],typeArguments:[l]})},claim:(i,s)=>{let c=n[s],l=a[s],d=r[s],u=Uo[s],p=o.utils.parseCoinType(u);return t.moveCall({target:`${e.spoolPkg}::user::redeem_rewards`,arguments:[t.object(c),t.object(l),t.object(i),t.object(Xe.SUI_CLOCK_OBJECT_ID)],typeArguments:[d,p]})}}},lt=async({builder:o,txBlock:t})=>{let e=await Yl({builder:o,txBlock:t}),n=await At({builder:o,txBlock:t});return{normalMethod:e,stakeQuick:async(a,r,i)=>{let s=E(t),c=await Jl(o,t,r,i),l=[];if(c.length===0){let d=e.createStakeAccount(r);l.push(d)}if(typeof a=="number"){let d=await zl(o,t,c.length>0?c[0]:l[0],r,a,s);a-=d,d||await zl(o,t,c.length>0?c[0]:l[0],r,a,s,!0)}else e.stake(c.length>0?c[0]:l[0],a,r);l.length>0&&t.transferObjects(l,s)},unstakeQuick:async(a,r,i,s)=>{let c=await Np(o,t,r,i),l=[],d=a;for(let u of c){if(u.staked===0)continue;let p=Math.min(d,u.staked),m=e.unstake(u.id,p,r);if(s){let b=n.mintSCoin(r,m);l.push(b)}else l.push(m);if(d-=p,a<=0)break}if(l.length>0){let u=l[0];return l.length>1&&t.mergeCoins(u,l.slice(1)),u}},claimQuick:async(a,r)=>{let i=await Jl(o,t,a,r),s=[];return i.forEach(c=>{let l=e.claim(c,a);s.push(l)}),s}}};var de=require("@mysten/sui.js/utils");var Ep=async({builder:o,txBlock:t})=>{let e={pkgId:o.address.get("vesca.id"),table:o.address.get("vesca.table"),treasury:o.address.get("vesca.treasury"),config:o.address.get("vesca.config")};return{lockSca:(n,a)=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_key`,arguments:[t.object(e.config),t.object(e.table),t.object(e.treasury),typeof n=="string"?t.pure(n):n,t.pure(a),t.object(de.SUI_CLOCK_OBJECT_ID)]}),extendLockPeriod:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::extend_lock_period`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.pure(a),t.object(de.SUI_CLOCK_OBJECT_ID)]})},extendLockAmount:(n,a)=>{t.moveCall({target:`${e.pkgId}::ve_sca::lock_more_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.object(de.SUI_CLOCK_OBJECT_ID)]})},renewExpiredVeSca:(n,a,r)=>{t.moveCall({target:`${e.pkgId}::ve_sca::renew_expired_ve_sca`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),typeof a=="string"?t.pure(a):a,t.pure(r),t.object(de.SUI_CLOCK_OBJECT_ID)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(de.SUI_CLOCK_OBJECT_ID)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},Ot=async({builder:o,txBlock:t})=>{let e=await Ep({builder:o,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,a,r=!0)=>{let i=E(t),s=await le(o,t),c,l=[];if(n!==void 0&&typeof n=="number"){let m=await o.utils.selectCoinIds(n,Ct,i),[b,S]=o.utils.takeAmountFromCoins(t,m,n);c=b,l.push(S)}else c=n;let d=o.utils.getUnlockAt(a,s?.unlockAt);r&&Bl(n,a,d,s?.unlockAt),console.log(new Date(d*1e3).toLocaleString("en-CA",{hour12:!0}));let u=!s?.unlockAt,p=!u&&s.unlockAt*1e3<=new Date().getTime();if(u||p){if(c)if(u){let m=e.lockSca(c,d);l.push(m)}else{if(s.lockedScaAmount!==0){let m=e.redeemSca(s.keyId);l.push(m)}e.renewExpiredVeSca(s.keyId,c,d)}}else c&&a?(e.extendLockPeriod(s.keyId,d),e.extendLockAmount(s.keyId,c)):a?e.extendLockPeriod(s.keyId,d):c&&e.extendLockAmount(s.keyId,c);l.length>0&&t.transferObjects(l,i)},extendLockPeriodQuick:async(n,a,r=!0)=>{let i=await le(o,t,a),s=o.utils.getUnlockAt(n);r&&Ml(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,a,r=!0)=>{let i=E(t),s=await le(o,t,a);if(r&&jl(n,s?.unlockAt),s){let c=await o.utils.selectCoinIds(n,Ct,i),[l,d]=o.utils.takeAmountFromCoins(t,c,n);e.extendLockAmount(s.keyId,l),t.transferObjects([d],i)}},renewExpiredVeScaQuick:async(n,a,r,i=!0)=>{let s=E(t),c=await le(o,t,r),l=o.utils.getUnlockAt(a,c?.unlockAt);if(i&&Nl(n,a,c?.unlockAt),c){let d=[];if(c.lockedScaAmount!==0){let b=e.redeemSca(c.keyId);d.push(b)}let u=await o.utils.selectCoinIds(n,Ct,s),[p,m]=o.utils.takeAmountFromCoins(t,u,n);d.push(m),e.renewExpiredVeSca(c.keyId,p,l),t.transferObjects(d,s)}},redeemScaQuick:async n=>{let a=E(t),r=await le(o,t,n);if(se(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],a)}}}};var nd=require("@mysten/sui.js/utils");var ed=require("@mysten/sui.js/utils");var ue={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}}},Xl={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},Ai={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},Zl={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 td={objectId:ed.SUI_CLOCK_OBJECT_ID,initialSharedVersion:"1",mutable:!1},Wp=(o,t)=>{if(o==="sui")switch(t){case"wusdc":return{pool:ue.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdc")switch(t){case"sui":return{pool:ue.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:ue.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:ue.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else if(o==="wusdt")switch(t){case"wusdc":return{pool:ue.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${o} and ${t}`)}else throw new Error(`Invalid coin pair: ${o} and ${t}`)},Oi={createAccount:o=>o.moveCall({target:`${Xl.id}::${Zl.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(o,t,e,n,a,r,i)=>{let{pool:s,aToB:c}=Wp(e,n),l=i.parseCoinType(e),d=i.parseCoinType(n),u=typeof r=="string"?o.object(r):"objectId"in r?o.objectRef(r):o.object(r);if(!s)throw new Error(`Deepbook: No pool found for ${e} to ${n}`);return c?o.moveCall({target:`${Ai.id}::deepbook::deepbook_base_for_quote`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.object(t),o.sharedObjectRef(td),o.pure(s.lotsize)],typeArguments:[l,d]}):o.moveCall({target:`${Ai.id}::deepbook::deepbook_quote_for_base`,arguments:[o.sharedObjectRef(s.object),o.pure(a),u,o.sharedObjectRef(td),o.object(t),o.pure(s.lotsize)],typeArguments:[d,l]})}};var Aa=class{suiClient;scallopUtils;_clientOrderId=0;_accountCap;currentAddress;constructor({client:t,currentAddress:e,accountCap:n,scallopUtils:a}){this.currentAddress=e,this.suiClient=t,this._accountCap=n,this.scallopUtils=a}get clientOrderId(){let t=this._clientOrderId;return this._clientOrderId++,t}async accountCap(t){if(this._accountCap)return this._accountCap;try{let{data:e}=await this.suiClient.getOwnedObjects({owner:this.currentAddress,filter:{StructType:(0,nd.normalizeStructTag)("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?Oi.createAccount(t):{objectId:e[0].data.objectId,version:e[0].data.version,digest:e[0].data.digest}}catch{throw new Error("Failed to create account cap")}}async swapToken({tokenObjectIn:t,baseCoinName:e,quoteCoinName:n,tx:a}){let r=await this.accountCap(a);return{swapResult:Oi.swap(a,t,e,n,this.clientOrderId,r,this.scallopUtils),accountCap:r}}};var Oa=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 ka(t,this.address),this.query=new Ia(t,{address:this.address,utils:this.utils}),this.builder=new Sa(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new Aa({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 I.TransactionBlock,n=await U({builder:this.builder,txBlock:e}),a=await W({builder:this.builder,txBlock:e}),r=t||this.params.walletAddress;e.setSender(r);let[i,s,c]=n.normalMethod.openObligation();return a.normalMethod.stakeObligation(i,s),n.normalMethod.returnObligation(i,c),e.transferObjects([s],r),e}async depositCollateral(t,e,n,a){let r=new I.TransactionBlock,i=a||this.params.walletAddress;r.setSender(i);let s=await U({builder:this.builder,txBlock:r}),c=await this.query.getObligations(i),l=n||c?.[0]?.id;if(l)await s.addCollateralQuick(e,t,l);else{let[d,u,p]=s.normalMethod.openObligation();await s.addCollateralQuick(e,t,d),s.normalMethod.returnObligation(d,p),r.transferObjects([u],i)}return r}async withdrawCollateral(t,e,n,a,r){let i=new I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=r||this.params.walletAddress;i.setSender(c);let l=await s.takeCollateralQuick(e,t,n,a);return i.transferObjects([l],c),i}async deposit(t,e,n){let a=new I.TransactionBlock,r=await U({builder:this.builder,txBlock:a}),i=await At({builder:this.builder,txBlock:a}),s=n||this.params.walletAddress;a.setSender(s);let c=await r.depositQuick(e,t,n),l=this.utils.parseMarketCoinName(t);if(!it.includes(l))a.transferObjects([c],s);else{let d=i.mintSCoin(l,c);a.transferObjects([d],s)}return a}async withdraw(t,e,n){let a=new I.TransactionBlock,r=n||this.params.walletAddress,i=await U({builder:this.builder,txBlock:a});a.setSender(r);let s=await i.withdrawQuick(e,t);return a.transferObjects([s],r),a}async borrow(t,e,n,a,r){let i=new I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=Dt.includes(t);d&&await c.unstakeObligationQuick(n,a);let u=await s.borrowQuick(e,t,n,a);return i.transferObjects([u],l),d&&await c.stakeObligationQuick(n,a),i}async borrowWithBoost(t,e,n,a,r,i){let s=new I.TransactionBlock,c=await U({builder:this.builder,txBlock:s}),l=await W({builder:this.builder,txBlock:s}),d=i||this.params.walletAddress;s.setSender(d);let u=Dt.includes(t);u&&await l.unstakeObligationQuick(n,a);let p=await c.borrowQuick(e,t,n,a);return s.transferObjects([p],d),u&&await l.stakeObligationWithVeScaQuick(n,a,r),s}async borrowWithReferral(t,e,n,a,r,i){let s=new I.TransactionBlock,c=await U({builder:this.builder,txBlock:s}),l=await W({builder:this.builder,txBlock:s}),d=await va({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=Dt.includes(t);p&&await l.unstakeObligationQuick(n,a);let m=d.claimReferralTicket(t),b=await c.borrowWithReferralQuick(e,t,m,n,a);return d.burnReferralTicket(m,t),s.transferObjects([b],u),p&&r?await l.stakeObligationWithVeScaQuick(n,a,r):await l.stakeObligationQuick(n,a),s}async repay(t,e,n,a,r){let i=new I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=Dt.includes(t);return d&&await c.unstakeObligationQuick(n,a),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationQuick(n,a),i}async repayWithBoost(t,e,n,a,r){let i=new I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),l=r||this.params.walletAddress;i.setSender(l);let d=Dt.includes(t);return d&&await c.unstakeObligationQuick(n,void 0),await s.repayQuick(e,t,n,l),d&&await c.stakeObligationWithVeScaQuick(n,void 0,a),i}async createStakeAccount(t,e){let n=new I.TransactionBlock,a=await lt({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;n.setSender(r);let i=a.normalMethod.createStakeAccount(t);return n.transferObjects([i],r),n}async supplyAndStake(t,e,n,a){let r=new I.TransactionBlock,i=await U({builder:this.builder,txBlock:r}),s=await lt({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l=await i.depositQuick(e,t,a),d=this.utils.parseMarketCoinName(t);if(!kt.find(m=>m===d))return r;let u=await this.query.getStakeAccounts(d,c),p=n||(u.length>0?u[0].id:void 0);if(p)await s.stakeQuick(l,d,p);else{let m=s.normalMethod.createStakeAccount(d);await s.stakeQuick(l,d,m),r.transferObjects([m],c)}return r}async unstakeAndWithdraw(t,e,n){let a=new I.TransactionBlock,r=await U({builder:this.builder,txBlock:a}),i=await lt({builder:this.builder,txBlock:a}),s=this.params.walletAddress,c=[];a.setSender(s);let l=this.utils.parseMarketCoinName(t);for(let d=0;d<n.length;d++){let u=n[d],[p]=await i.unstakeQuick(u.coin,l,u.id);if(p){let m=r.normalMethod.withdraw(p,t);c.push(m)}}if(e>0){let d=await r.withdrawQuick(e,t);c.push(d)}return c.length>1&&a.mergeCoins(c[0],c.slice(1)),a.transferObjects(c,s),a}async stake(t,e,n,a){let r=new I.TransactionBlock,i=await lt({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=await this.query.getStakeAccounts(t,s),l=n||(c.length>0?c[0].id:void 0);if(l)await i.stakeQuick(e,t,l);else{let d=i.normalMethod.createStakeAccount(t);await i.stakeQuick(e,t,d),r.transferObjects([d],s)}return r}async unstake(t,e,n,a){let r=new I.TransactionBlock,i=await lt({builder:this.builder,txBlock:r}),s=a||this.params.walletAddress;r.setSender(s);let c=it.includes(t),l=await i.unstakeQuick(e,t,n,c);return r.transferObjects([l],r.pure(s)),r}async claim(t,e,n,a){let r=new I.TransactionBlock,i=await lt({builder:this.builder,txBlock:r}),s=await W({builder:this.builder,txBlock:r}),c=a||this.params.walletAddress;r.setSender(c);let l={sui:[],sca:[],scallop_sui:[],scallop_sca:[],scallop_deep:[],scallop_fud:[]};for(let d=0;d<t.length;d++){let{stakeMarketCoinName:u,stakeAccountId:p}=t[d],m=i.normalMethod.claim(p,u);l.sui.push(m)}for(let d=0;d<e.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=e[d],b=s.normalMethod.claimBorrowIncentive(u,p,m);l[m].push(b)}for(let d=0;d<n.length;d++){let{obligationId:u,obligationKey:p,rewardCoinName:m}=n[d],b=s.normalMethod.oldClaimBorrowIncentive(u,p,m);l[m].push(b)}for(let d in l)l[d].length>0&&(l[d].length>1&&r.mergeCoins(l[d][0],l[d].slice(1)),r.transferObjects([l[d][0]],r.pure(c)));return r}async stakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await W({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.stakeObligationQuick(t,e),a}async unstakeObligation(t,e,n){let a=this.builder.createTxBlock(),r=await W({builder:this.builder,txBlock:a}),i=n||this.params.walletAddress;return a.setSender(i),await r.unstakeObligationQuick(t,e),a}async stakeSca(t,e=!1,n=!1,a,r,i,s,c){let l=new I.TransactionBlock,d=await Ot({builder:this.builder,txBlock:l}),u=await W({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,Ct,p),[b,S]=this.builder.utils.takeAmountFromCoins(l,m,t),C;return s?d.normalMethod.extendLockAmount(s,b):C=d.normalMethod.lockSca(b,i),a&&r&&(e&&(n?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,s||C)),s||l.transferObjects([C,S],p),l}async stakeMoreSca(t,e,n){let a=new I.TransactionBlock,r=n||this.params.walletAddress;return a.setSender(r),a}async extendStakeScaLockPeriod(t,e,n,a,r=!1,i=!1,s){let c=new I.TransactionBlock,l=await Ot({builder:this.builder,txBlock:c}),d=await W({builder:this.builder,txBlock:c}),u=s||this.params.walletAddress;return c.setSender(u),l.normalMethod.extendLockPeriod(e,t),n&&a&&(r&&(i?d.normalMethod.oldUnstakeObligation(n,a):d.normalMethod.unstakeObligation(n,a)),d.normalMethod.stakeObligationWithVesca(n,a,e)),c}async extendPeriodAndStakeMoreSca(t,e,n,a,r,i=!1,s=!1,c){let l=new I.TransactionBlock,d=await Ot({builder:this.builder,txBlock:l}),u=await W({builder:this.builder,txBlock:l}),p=c||this.params.walletAddress;l.setSender(p);let m=await this.builder.utils.selectCoinIds(t,Ct,p),[b,S]=this.builder.utils.takeAmountFromCoins(l,m,t);return d.normalMethod.extendLockPeriod(e,n),d.normalMethod.extendLockAmount(e,b),l.transferObjects([S],p),!a||!r||(i&&(s?u.normalMethod.oldUnstakeObligation(a,r):u.normalMethod.unstakeObligation(a,r)),u.normalMethod.stakeObligationWithVesca(a,r,e)),l}async renewExpiredStakeSca(t,e,n,a=!1,r,i,s=!1,c=!1,l){let d=new I.TransactionBlock,u=await Ot({builder:this.builder,txBlock:d}),p=await W({builder:this.builder,txBlock:d}),m=l||this.params.walletAddress;if(d.setSender(m),a){let x=u.normalMethod.redeemSca(n);d.transferObjects([x],m)}let b=await this.builder.utils.selectCoinIds(t,Ct,m),[S,C]=this.builder.utils.takeAmountFromCoins(d,b,t);return d.transferObjects([C],m),u.normalMethod.renewExpiredVeSca(n,S,e),!r||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(r,i):p.normalMethod.unstakeObligation(r,i)),p.normalMethod.stakeObligationWithVesca(r,i,n)),d}async redeemSca(t){let e=new I.TransactionBlock,n=await Ot({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),await n.redeemScaQuick(t),e}async migrateAndClaim(t,e,n,a){let r=new I.TransactionBlock,i=await W({builder:this.builder,txBlock:r}),s=this.params.walletAddress;r.setSender(s);let c=i.normalMethod.oldClaimBorrowIncentive(e,t,n);return r.transferObjects([c],s),await i.unstakeObligationQuick(e,t),a?await i.stakeObligationWithVeScaQuick(e,t,a):await i.stakeObligationQuick(e,t),r}async withdrawUnlockedSca(t,e){let n=new I.TransactionBlock,a=await Ot({builder:this.builder,txBlock:n}),r=e||this.params.walletAddress;return n.setSender(r),await a.redeemScaQuick(t),n}calculateAvailableClaimCoin(t,e){let n=new Pi.default(t.weightedAmount),r=e.currentPointIndex?(0,Pi.default)(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new I.TransactionBlock,e=await Ot({builder:this.builder,txBlock:t}),n=this.params.walletAddress;t.setSender(n);let a=e.normalMethod.mintEmptyVeSca();return t.transferObjects([a],n),t}async claimRevenuReferral(t,e){let n=new I.TransactionBlock,a=await Hl({builder:this.builder,txBlock:n}),r=this.params.walletAddress;n.setSender(r);let i=e.map(s=>this.utils.parseCoinNameFromType(s));return await a.claimReferralRevenueQuick(t,r,i),n}async bindReferral(t){let e=new I.TransactionBlock,n=await va({builder:this.builder,txBlock:e}),a=this.params.walletAddress;return e.setSender(a),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new I.TransactionBlock,e=await At({builder:this.builder,txBlock:t}),n=await lt({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let a=[];return await Promise.all(it.map(async r=>{let i=[],s;try{let c=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseMarketCoinType(r),this.params.walletAddress),l=c[0];c.length>1&&t.mergeCoins(l,c.slice(1)),s=l}catch(c){if(!c.toString().includes("No valid coins found for the transaction"))throw c}if(s){let c=e.mintSCoin(r,s);try{let l=await this.utils.selectCoinIds(Number.MAX_SAFE_INTEGER,this.utils.parseSCoinType(r),this.params.walletAddress);t.mergeCoins(c,l)}catch(l){console.log(l)}i.push(c)}if(kt.includes(r))try{let c=await n.unstakeQuick(Number.MAX_SAFE_INTEGER,r);c&&i.push(c)}catch(c){console.log(c)}if(i.length>0){let c=i[0];i.length>1&&t.mergeCoins(c,i.slice(1)),a.push(c)}})),a.length>0&&t.transferObjects(a,this.params.walletAddress),t}async migrateLendingWusdcToUsdcNative(t,e,n,a,r){let i=new I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await lt({builder:this.builder,txBlock:i}),l=this.params.walletAddress,d=[],u=this.utils.parseMarketCoinName(t),p=this.utils.parseMarketCoinType(u),b=(await this.utils.selectCoinsMarketCoin(p,l)).map(B=>B.objectId);i.setSender(l);for(let B=0;B<r.length;B++){let Q=r[B],[$]=await c.unstakeQuick(Q.coin,u,Q.id);if($){b.length>0&&i.mergeCoins($,b);let Tu=s.normalMethod.withdraw($,t);d.push(Tu)}}if(e>0){let B=await s.withdrawQuick(e,t);d.push(B)}d.length>1&&i.mergeCoins(d[0],d.slice(1));let[S]=i.splitCoins(d[0],[i.pure(a)]);i.transferObjects([d[0]],l);let{swapResult:C,accountCap:x}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:S,tx:i});typeof x=="string"&&i.transferObjects([x],l),Gl.check_slippage(i,C,n,a,this.query.utils.parseCoinType("usdc"));let q=s.normalMethod.deposit(C,"usdc");return await c.stakeQuick(q,"susdc"),i}};var Ze=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new ya({id:gl})),await this.address.read(),this.client=new Oa(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var Pa=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new Ze({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new Fo(e,this.scallop),a=new $o(e,this.scallop),r=new Ko(e,this.scallop),i=n.decode()||a.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:od.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:a,txSubType:r,intentionData:i}=t;this.scallop||(this.scallop=new Ze({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(r){case"SupplyLending":s=oa.fromData(i);break;case"WithdrawLending":s=sa.fromData(i);break;case"Borrow":s=Vo.fromData(i);break;case"Repay":s=ta.fromData(i);break;case"DepositCollateral":s=zo.fromData(i);break;case"WithdrawCollateral":s=ia.fromData(i);break;case"OpenObligation":s=Zo.fromData(i);break;case"StakeSpool":s=na.fromData(i);break;case"UnstakeSpool":s=aa.fromData(i);break;case"ClaimIncentiveReward":s=Go.fromData(i);break;case"BorrowWithBoost":s=Qo.fromData(i);break;case"StakeSca":s=ba.fromData(i);break;case"ExtendStakePeriod":s=pa.fromData(i);break;case"ExtendPeriodAndStakeMore":s=ua.fromData(i);break;case"RenewExpStakePeriod":s=fa.fromData(i);break;case"WithdrawStakedSca":s=ha.fromData(i);break;case"SupplyAndStakeLending":s=ga.fromData(i);break;case"WithdrawAndUnstakeLending":s=ra.fromData(i);break;case"RedeemSca":s=ma.fromData(i);break;case"MigrateAndClaim":s=Jo.fromData(i);break;case"BorrowWithReferral":s=Ho.fromData(i);break;case"CreateReferralLink":s=da.fromData(i);break;case"ClaimRevenueReferral":s=la.fromData(i);break;case"BindReferral":s=ca.fromData(i);break;case"MigrateScoin":s=Yo.fromData(i);break;case"RepayWithBoost":s=ea.fromData(i);break;case"MigrateWusdcToUsdc":s=Xo.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:a,scallop:this.scallop})}};var Cd=require("@msafe/sui3-utils"),Ha=require("@suilend/frontend-sui"),Id=require("@suilend/springsui-sdk");var Ra=require("@msafe/sui3-utils");var _a=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isMintTransaction())return this.decodeMint();if(this.isMintAndDepositTransaction())return this.decodeMintAndDeposit();if(this.isRedeemTransaction())return this.decodeRedeem();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintTransactionMoveCallCommands(){return!!this.getMoveCallCommand("mint")}isMintTransaction(){return this.hasMintTransactionMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isMintAndDepositTransaction(){return this.hasMintTransactionMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::MintEvent"))}.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeMint",e),{txType:Ra.TransactionType.Other,type:"mint",intentionData:{amount:e}}}decodeMintAndDeposit(){return{txType:Ra.TransactionType.Other,type:"mintAndDeposit",intentionData:this.decodeMint().intentionData}}decodeRedeem(){let e={RedeemEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::RedeemEvent"))}.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeRedeem",e),{txType:Ra.TransactionType.Other,type:"redeem",intentionData:{amount:e}}}};var rd=require("@mysten/sui/transactions");var ad=j(require("sort-keys-recursive")),Pt=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,ad.default)(this.data))}};var Ba=class o extends Pt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintIntention.build",n,a,r,i,s,c);let l=new rd.Transaction;return r.mintAndRebalanceAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("MintIntention.fromData",e),new o(e)}};var id=require("@mysten/sui/transactions");var Ma=class o extends Pt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("MintAndDepositIntention.build",n,a,r,i,s,c);let l=new id.Transaction;return i.depositCoin(a.address,r.mintAndRebalance(l,this.data.amount),r.liquidStakingObject.type,l,s?.id),l}static fromData(e){return console.log("MintAndDepositIntention.fromData",e),new o(e)}};var sd=require("@mysten/sui/transactions");var ja=class o extends Pt{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,lstClient:r,suilendClient:i,obligationOwnerCap:s,obligation:c}=e;console.log("RedeemIntention.build",n,a,r,i,s,c);let l=new sd.Transaction;return await r.redeemAndSendToUser(l,a.address,this.data.amount),l}static fromData(e){return console.log("RedeemIntention.fromData",e),new o(e)}};var yd=require("@msafe/sui3-utils"),Rt=require("@suilend/sdk"),Sd=require("@suilend/sdk/_generated/_framework/reified"),wd=require("@suilend/sdk/_generated/suilend/lending-market/structs");var $t=require("@msafe/sui3-utils"),me=require("@mysten/bcs"),pe=require("@mysten/sui/utils"),Kt=require("@suilend/sdk"),Ri=j(require("bignumber.js"));var Na=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("XXX this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("XXX this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let t={MintEvent:this.simResult.events.find(a=>a.type.includes("lending_market::MintEvent"))},e=(0,pe.normalizeStructTag)(t.MintEvent.parsedJson.coin_type.name),n=t.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",e,n),{txType:$t.TransactionType.Other,type:"deposit",intentionData:{coinType:e,value:n}}}decodeWithdraw(){let t={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},e={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=(0,pe.normalizeStructTag)(e.RedeemEvent.parsedJson.coin_type.name),a=e.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,a);let r=t.withdraw_ctokens.MoveCall.arguments[4].Input,i=new Ri.default((0,me.toHEX)((0,me.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Kt.maxU64.toString();return console.log("XXX decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Kt.maxU64.toString()),s&&(a=Kt.maxU64.toString()),{txType:$t.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:a}}}decodeBorrow(){let t={borrow_request:this.getMoveCallCommand("borrow_request")},e={BorrowEvent:this.simResult.events.find(c=>c.type.includes("lending_market::BorrowEvent"))},n=(0,pe.normalizeStructTag)(e.BorrowEvent.parsedJson.coin_type.name),a=`${+e.BorrowEvent.parsedJson.liquidity_amount-+e.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,a);let r=t.borrow_request.MoveCall.arguments[4].Input,i=new Ri.default((0,me.toHEX)((0,me.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Kt.maxU64.toString();return console.log("XXX decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Kt.maxU64.toString()),s&&(a=Kt.maxU64.toString()),{txType:$t.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:a}}}decodeRepay(){let t={RepayEvent:this.simResult.events.find(a=>a.type.includes("lending_market::RepayEvent"))},e=(0,pe.normalizeStructTag)(t.RepayEvent.parsedJson.coin_type.name),n=t.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",e,n),{txType:$t.TransactionType.Other,type:"repay",intentionData:{coinType:e,value:n}}}decodeClaim(){let t={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},e={};for(let n=0;n<t.ClaimReward.length;n++){let a=t.ClaimReward[n],r=(0,pe.normalizeStructTag)(a.parsedJson.coin_type.name),i=a.parsedJson.liquidity_amount;e[r]=`${+(e[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",e),{txType:$t.TransactionType.Other,type:"claim",intentionData:{value:e}}}decodeClaimAndDeposit(){return{txType:$t.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var ld=require("@mysten/sui/transactions");var cd=j(require("sort-keys-recursive")),F=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,cd.default)(this.data))}};var Ea=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("BorrowIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new ld.Transaction;return await r.borrowAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("BorrowIntention.fromData",e),new o(e)}};var md=require("@mysten/sui/transactions");var ud=require("@mysten/sui/utils"),fe=require("@suilend/sdk"),pd=j(require("bignumber.js"));var _i=require("@mysten/sui/utils"),Fp="0x34fe4f3c9e450fed4d0a3c587ed842eec5313c30c3cc3c0841247c49425e246b::suilend_point::SUILEND_POINT",qp=(0,_i.normalizeStructTag)(Fp),dd=o=>(0,_i.normalizeStructTag)(o)===qp;var $p=(o,t)=>{let e={[fe.Side.DEPOSIT]:[],[fe.Side.BORROW]:[]};return o.lendingMarket.reserves.forEach(n=>{[fe.Side.DEPOSIT,fe.Side.BORROW].forEach(a=>{let r=a===fe.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,i=t.userRewardManagers.find(s=>s.poolRewardManagerId===r.id);i&&(e[a]=r.poolRewards.map((s,c)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(c),rewardCoinType:(0,ud.normalizeStructTag)(s.coinType.name),side:a})).filter(s=>!dd(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new pd.default(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(e).flat()},Wa=$p;var La=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new md.Transaction;return r.claimRewardsAndSendToUser(a.address,i.id,Wa(r,s),c),c}static fromData(e){return console.log("ClaimIntention.fromData",e),new o(e)}};var fd=require("@mysten/sui/transactions");var Ua=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("ClaimAndDepositIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new fd.Transaction;return r.claimRewardsAndDeposit(a.address,i.id,Wa(r,s),c),c}static fromData(e){return console.log("ClaimAndDepositIntention.fromData",e),new o(e)}};var bd=require("@mysten/sui/transactions");var Fa=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;console.log("DepositIntention.build",n,a,r,i,s);let c=new bd.Transaction;return await r.depositIntoObligation(a.address,this.data.coinType,this.data.value,c,i?.id),c}static fromData(e){return console.log("DepositIntention.fromData",e),new o(e)}};var gd=require("@mysten/sui/transactions");var qa=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("RepayIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new gd.Transaction;return await r.repayIntoObligation(a.address,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("RepayIntention.fromData",e),new o(e)}};var hd=require("@mysten/sui/transactions");var $a=class o extends F{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:a,suilendClient:r,obligationOwnerCap:i,obligation:s}=e;if(console.log("WithdrawIntention.build",n,a,r,i,s),!i||!s)throw new Error("Obligation not found");let c=new hd.Transaction;return await r.withdrawAndSendToUser(a.address,i.id,s.id,this.data.coinType,this.data.value,c),c}static fromData(e){return console.log("WithdrawIntention.fromData",e),new o(e)}};var Ka=async(o,t)=>{let e=await Rt.SuilendClient.initializeWithLendingMarket(await wd.LendingMarket.fetch(o,(0,Sd.phantom)(Rt.LENDING_MARKET_TYPE),Rt.LENDING_MARKET_ID),o),n=await Rt.SuilendClient.getObligationOwnerCaps(t.address,e.lendingMarket.$typeArgs,o),a=await Promise.all(n.map(r=>Rt.SuilendClient.getObligation(r.obligationId,e.lendingMarket.$typeArgs,o)));return{suilendClient:e,obligationOwnerCaps:n,obligations:a}},Va=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await Ka(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SuilendAppHelper.deserialize",r);let s=new Na(e,r).decode();return{txType:yd.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await Ka(r,i));let s;switch(n){case"deposit":s=Fa.fromData(a);break;case"withdraw":s=$a.fromData(a);break;case"borrow":s=Ea.fromData(a);break;case"repay":s=qa.fromData(a);break;case"claim":s=La.fromData(a);break;case"claimAndDeposit":s=Ua.fromData(a);break;default:throw new Error("not implemented")}let c=window.localStorage.getItem("obligationId"),l=this.utils.obligations?.find(u=>u.id===c)??this.utils.obligations?.[0],d=this.utils.obligationOwnerCaps?.find(u=>u.obligationId===l?.id);return console.log("XXX obligationId:",c,"obligations:",this.utils.obligations,"obligationOwnerCaps:",this.utils.obligationOwnerCaps),s.build({network:e,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:d,obligation:l})}};var Td=async(o,t)=>{let e=await Id.LstClient.initialize(o,Ha.LIQUID_STAKING_INFO_MAP[Ha.LstId.sSUI]),n=await Ka(o,t);return{lstClient:e,...n}},Qa=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:a}=t;this.utils||(this.utils=await Td(n,a));let r=await n.devInspectTransactionBlock({sender:a.address,transactionBlock:e});console.log("SpringSuiAppHelper.deserialize",r);let s=new _a(e,r).decode();return{txType:Cd.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{network:e,txSubType:n,intentionData:a,suiClient:r,account:i}=t;this.utils||(this.utils=await Td(r,i));let s;switch(n){case"mint":s=Ba.fromData(a);break;case"mintAndDeposit":s=Ma.fromData(a);break;case"redeem":s=ja.fromData(a);break;default:throw new Error("not implemented")}return s.build({network:e,suiClient:r,account:i,lstClient:this.utils.lstClient,suilendClient:this.utils.suilendClient,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};var xd=require("@msafe/sui3-utils");var Bi=require("@msafe/sui3-utils");var Ga=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:Bi.TransactionType.Other,type:"mint",intentionData:{amount:e}}}decodeRedeem(t){let{event:{lst_amount_in:e}}=t;return console.log("Decoder.decodeRedeem",e),{txType:Bi.TransactionType.Other,type:"redeem",intentionData:{amount:e}}}};var kd=require("@alphafi/stsui-sdk"),za=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:a}=this.data;return await(0,kd.mint)(a,{address:n.address})}static fromData(e){return console.log("MintIntention.fromData",e),new o(e)}};var Dd=require("@alphafi/stsui-sdk"),Ja=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:a}=this.data;return await(0,Dd.redeem)(a,{address:n.address})}static fromData(e){return console.log("RedeemIntention.fromData",e),new o(e)}};var Ya=class{application="stsui";supportSDK="@mysten/sui";async deserialize(t){let{transaction:e,suiClient:n}=t,a=await n.devInspectTransactionBlock({sender:e.getData().sender,transactionBlock:e});console.log("StSuiHelper Sim result - ",a);let i=new Ga(e,a).decode();return{txType:xd.TransactionType.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=za.fromData(t.intentionData);break;case"redeem":n=Ja.fromData(t.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:e})}};var Gd=require("@msafe/sui3-utils"),zd=require("turbos-clmm-sdk");var V=require("@msafe/sui3-utils"),Mi=require("@mysten/sui.js/bcs"),Bt=require("@mysten/sui.js/utils"),vd=require("turbos-clmm-sdk");var z={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},J={PackageId:"0xdee9"};var Qp=(o,t,e,n)=>{if(o===1)switch(n.findIndex(i=>i===t)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${t}`)}switch(e.findIndex(r=>r===t)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${t}`)}},Xa=class{constructor(t,e,n){this.txb=t;this.turbosSdk=e;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(t){if(this.isSwapTransaction())return await this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}getMoveCallsTransaction(t){return t.every(e=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===e))}getSwapMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&t.includes(e.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${z.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${z.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${J.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${J.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=Qp(e,t.target,this.swap1Layer,this.swap2Layer),a=n.map((m,b)=>{let S=this.helper.decodeSharedObjectId(b),C=this.helper.decodeInputU128(4+b+e),x=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new vd.BN(C.toString()));return{pool:S,a2b:m,nextTickIndex:x}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),l=this.helper.decodeInputBool(5+2*e),d=this.helper.decodeInputU64(2+e),u=this.helper.decodeInputU64(3+e),p=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:a[0].pool,a2b:a[0].a2b,amountSpecified:d}],address:s,amountSpecifiedIsInput:l});return{txType:V.TransactionType.Other,type:"Swap",intentionData:{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:l?d:u,amountB:l?u:d,amountSpecifiedIsInput:l,slippage:"0.1",deadline:c}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),i=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),c=this.helper.decodeInputBool(7),l=this.helper.decodeInputU64(13);return{txType:V.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:a,tickLower:i?-r:r,tickUpper:c?-s:s,deadline:l}}}decodeIncreaseLiquidity(t){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),a=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),i=this.helper.decodeInputU64(9);return{txType:V.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:a,amountB:r,nft:n,deadline:i}}}decodeDecreaseLiquidity(t){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(5),s=this.helper.decodeInputU64(6);return{txType:V.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,deadline:s}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),a=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),i=this.helper.decodeInputU64(6);return{txType:V.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:a,collectAmountB:r,nft:e,deadline:i}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),a=this.collectRewardHelper.map(i=>i.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:V.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:a,nft:e,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:V.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){console.log(this.helper,"decodeRemoveLiquidity this.helper");let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),a=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),i=this.decreaseLiquidityHelper.decodeInputU64(5),s=this.decreaseLiquidityHelper.decodeInputU64(6),c=this.collectRewardHelper.map(u=>u.decodeInputU64(5)),l=this.collectFeeHelper.decodeInputU64(3)||0,d=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:V.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:e,decreaseLiquidity:a,nft:n,amountA:r,amountB:i,slippage:10,address:t,collectAmountA:l,collectAmountB:d,rewardAmounts:c,deadline:s}}}decodePrixClaim(){return{txType:V.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:V.TransactionType.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let t=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),e=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),a=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:V.TransactionType.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}decodeSwapExactQuoteForBase(){let t=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),e=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),a=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:V.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:t,amountIn:e,token1:n,token2:a}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero"&&e.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new _t(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 _t(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new _t(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 _t(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${J.PackageId}::clob_v2::swap_exact_base_for_quote`);return new _t(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${J.PackageId}::clob_v2::swap_exact_quote_for_base`);return new _t(t,this.txb)}},_t=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU128(t){let e=this.decodePureArg(t,"u128");return Number(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU32(t){let e=this.decodePureArg(t,"u32");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,Bt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Mi.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,Bt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,Bt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,Bt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,Bt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Mi.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,Bt.normalizeStructTag)(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};var Ad=require("turbos-clmm-sdk");var Za=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ad.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,tickLower:l,tickUpper:d,deadline:u,txb:p}=this.data;return n.pool.addLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,tickLower:l,tickUpper:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var Od=require("turbos-clmm-sdk");var tr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Od.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,nft:r,txb:i}=this.data;return n.nft.burn({pool:a,nft:r,txb:i})}static fromData(e){return new o(e)}};var Pd=require("turbos-clmm-sdk");var er=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Pd.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,collectAmountA:s,collectAmountB:c,deadline:l,txb:d}=this.data;return n.pool.collectFee({pool:a,address:r,collectAmountA:s,collectAmountB:c,nft:i,deadline:l,txb:d})}static fromData(e){return new o(e)}};var Rd=require("turbos-clmm-sdk");var nr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Rd.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,nft:i,rewardAmounts:s,deadline:c,txb:l}=this.data;return n.pool.collectReward({pool:a,address:r,rewardAmounts:s,nft:i,deadline:c,txb:l})}static fromData(e){return new o(e)}};var _d=require("turbos-clmm-sdk");var or=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new _d.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{fee:a,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,amountA:p,amountB:m,deadline:b,txb:S}=this.data;return n.pool.createPool({fee:a,amountA:p,amountB:m,address:r,tickLower:i,tickUpper:s,sqrtPrice:c,slippage:l,coinTypeA:d,coinTypeB:u,deadline:b,txb:S})}static fromData(e){return new o(e)}};var Bd=require("turbos-clmm-sdk");var ar=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Bd.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,decreaseLiquidity:d,deadline:u,txb:p}=this.data;return n.pool.decreaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,decreaseLiquidity:d,deadline:u,txb:p})}static fromData(e){return new o(e)}};var Md=require("turbos-clmm-sdk");var rr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Md.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{pool:a,address:r,amountA:i,amountB:s,slippage:c,nft:l,deadline:d,txb:u}=this.data;return n.pool.increaseLiquidity({pool:a,slippage:c,address:r,amountA:i,amountB:s,nft:l,deadline:d,txb:u})}static fromData(e){return new o(e)}};var jd=require("@mysten/sui.js/transactions"),Nd=require("@mysten/sui.js/utils");var ir=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new jd.TransactionBlock;return n.moveCall({target:`${z.PackageId}::claim::claim`,typeArguments:[z.turbosCoinType],arguments:[n.object(z.Claim),n.object(Nd.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(e){return new o(e)}};var Ed=require("@mysten/sui.js/transactions");var sr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ed.TransactionBlock;return n.moveCall({target:`${z.PackageId}::claim::join`,typeArguments:[z.turbosCoinType],arguments:[n.object(z.Claim)]}),n}static fromData(e){return new o(e)}};var Wd=require("@mysten/sui.js/transactions"),Ld=require("turbos-clmm-sdk");var cr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Ld.TurbosSdk(e.network.replace("sui:",""),e.suiClient),a=new Wd.TransactionBlock;return a=await n.pool.collectFee({txb:a,...this.data}),a=await n.pool.collectReward({txb:a,...this.data}),a=await n.pool.decreaseLiquidity({txb:a,...this.data}),a=await n.nft.burn({txb:a,nft:this.data.nft,pool:this.data.pool}),a}static fromData(e){return new o(e)}};var Ud=require("turbos-clmm-sdk");var lr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new Ud.TurbosSdk(e.network.replace("sui:",""),e.suiClient),{routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,slippage:d,amountSpecifiedIsInput:u,deadline:p,txb:m}=this.data;return n.trade.swap({routes:a,coinTypeA:r,coinTypeB:i,address:s,amountA:c,amountB:l,amountSpecifiedIsInput:u,slippage:d,deadline:p,txb:m})}static fromData(e){return new o(e)}};var Qd=require("turbos-clmm-sdk");var ji=require("@mysten/sui.js/utils"),Ni=require("@mysten/sui.js/transactions");var Fd=require("turbos-clmm-sdk");var tn=class{constructor(t){this.turbosSdk=t}async getCoinsData(t,e,n){let a=[],r;do r=await this.turbosSdk.provider.getCoins({owner:t,coinType:e,cursor:r?.nextCursor}),a.push(...r.data);while(r.hasNextPage);let i=[],s=0;return a.sort((c,l)=>Number(l.balance)-Number(c.balance)).some(c=>s>=n?!0:(s+=Number(c.balance),i.push(c),!1)),i}splitAndMergeCoin(t,e,n){if(!t||t.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(t[0].coinType)){let[i]=n.splitCoins(n.gas,[n.pure(e)]);return[i,void 0]}let a=n.object(t[0].coinObjectId);t.length>1&&n.mergeCoins(a,t.slice(1).map(i=>n.object(i.coinObjectId)));let[r]=n.splitCoins(a,[n.pure(e)]);return[r,a]}isSuiCoinAddress(t){return t.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(t){let e=await this.turbosSdk.provider.getOwnedObjects({owner:t,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${J.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?(0,Fd.unstable_getObjectId)(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${J.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var qd=89,$d=1e6,Kd=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Ni.TransactionBlock,c=new tn(i),l=await c.getCoinsData(r,e,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${e}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),[b,S,C]=s.moveCall({typeArguments:[t,e],target:`${J.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(qd),m,s.pure(a),s.object((0,ji.normalizeSuiObjectId)("0x6")),d]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([b],s.pure(r)),s.transferObjects([S],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget($d),s},Vd=async o=>{let{token1:t,token2:e,poolId:n,amountIn:a,currentAddress:r,turbosSdk:i}=o,s=new Ni.TransactionBlock,c=new tn(i),l=await c.getCoinsData(r,t,a),[d,u]=c.splitAndMergeCoin(l,a,s);if(!d)throw new Error(`Not enough balance: ${t}`);let p=await c.IsAccountCap(r),m=p?s.object(p):c.createAccount(s),b=c.zero(e,s),[S,C,x]=s.moveCall({typeArguments:[t,e],target:`${J.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(qd),m,s.pure(a),d,b,s.object((0,ji.normalizeSuiObjectId)("0x6"))]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([S],s.pure(r)),s.transferObjects([C],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget($d),s};var dr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Qd.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await Vd({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var Hd=require("turbos-clmm-sdk");var ur=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Hd.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await Kd({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new o(e)}};var pr=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new zd.TurbosSdk(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:a,account:r}=t;console.log(t,"input");let s=await new Xa(a,e,n).decode(r.address);return{txType:Gd.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t,r;switch(console.log(t.intentionData,"intentionData"),t.txSubType){case"CreatePool":r=or.fromData(t.intentionData);break;case"AddLiquidity":r=Za.fromData(t.intentionData);break;case"IncreaseLiquidity":r=rr.fromData(t.intentionData);break;case"DecreaseLiquidity":r=ar.fromData(t.intentionData);break;case"RemoveLiquidity":r=cr.fromData(t.intentionData);break;case"CollectFee":r=er.fromData(t.intentionData);break;case"CollectReward":r=nr.fromData(t.intentionData);break;case"Burn":r=tr.fromData(t.intentionData);break;case"Swap":r=lr.fromData(t.intentionData);break;case"PrixJoin":r=sr.fromData(t.intentionData);break;case"PrixClaim":r=ir.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=dr.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=ur.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var Zd=require("@msafe/sui3-utils");var mr=require("@msafe/sui3-utils"),Ei=require("@mysten/sui.js/bcs"),Mt=require("@mysten/sui.js/utils");var Hp={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},O=Hp;var fr=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:mr.TransactionType.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:mr.TransactionType.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:mr.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(O.packageId));return new Wi(t,this.txb)}},Wi=class o{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return o.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return o.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,Mt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return o.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Ei.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,Mt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,Mt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,Mt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,Mt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ei.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,Mt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Jd=require("@mysten/sui.js/transactions");var br=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Jd.TransactionBlock,{ticketId:a}=this.data;return n.moveCall({target:`${O.packageId}::native_pool::burn_ticket`,arguments:[n.object(O.poolObjectId),n.object(O.systemStateObjectId),n.object(a)]}),n}static fromData(e){return new o(e)}};var Yd=require("@mysten/sui.js/transactions");var gr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Yd.TransactionBlock,{amount:a}=this.data,[r]=n.splitCoins(n.gas,[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::stake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),r]}),n}static fromData(e){return new o(e)}};var Xd=require("@mysten/sui.js/transactions");var hr=class o extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new Xd.TransactionBlock,{amount:a}=this.data,r=(await e.suiClient.getAllCoins({owner:e.account.address,limit:100})).data,[i,...s]=r.filter(d=>d.coinType.split("::")[0]===O.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(d=>n.object(d.coinObjectId)));let l=n.splitCoins(n.object(i.coinObjectId),[n.pure(a)]);return n.moveCall({target:`${O.packageId}::native_pool::unstake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),l]}),n}static fromData(e){return new o(e)}};var yr=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,a=new fr(e).decode();return{txType:Zd.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n}=t,a;switch(t.txSubType){case"Stake":a=gr.fromData(t.intentionData);break;case"UnStake":a=hr.fromData(t.intentionData);break;case"ClaimTicket":a=br.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:n})}};var du=require("@msafe/sui3-utils");var Li=require("@cetusprotocol/cetus-sui-clmm-sdk"),jt=require("@msafe/sui3-utils"),be=require("@mysten/bcs"),ge=require("@mysten/sui/bcs");var Sr=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:jt.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,1)),lowerTick:Number((0,Li.asIntN)(BigInt(this.getU32(this.getInputIndex(t,2)))).toString()),upperTick:Number((0,Li.asIntN)(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:jt.TransactionType.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:jt.TransactionType.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:jt.TransactionType.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:jt.TransactionType.Other,type:"CollectRewards",intentionData:{pool:t[0].pool,position:t[0].position,collectRewardTokens:t.map(e=>e.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:jt.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let t=this.getFeeCallData();return{txType:jt.TransactionType.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(ge.bcs.u32().parse(Uint8Array.from((0,be.fromB64)(this.inputs[t].Pure.bytes))))}getU64(t){return ge.bcs.u64().parse(Uint8Array.from((0,be.fromB64)(this.inputs[t].Pure.bytes)))}getU128(t){return ge.bcs.u128().parse(Uint8Array.from((0,be.fromB64)(this.inputs[t].Pure.bytes)))}getBoolean(t){return ge.bcs.bool().parse(Uint8Array.from((0,be.fromB64)(this.inputs[t].Pure.bytes)))}getAddress(t){return ge.bcs.Address.parse(Uint8Array.from((0,be.fromB64)(this.inputs[t].Pure.bytes)))}getTypeArguments(t){return t.MoveCall.typeArguments||[]}getInputIndex(t,e){return t.MoveCall.arguments[e].Input}};var ou=require("@msafe/sui3-utils");var et=require("@firefly-exchange/library-sui");var eu=require("@firefly-exchange/library-sui"),nu=require("@firefly-exchange/library-sui/dist/src/spot"),tu={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x702301e7c6ca527a6f6a83f12c5edf2dcd6ec7a23fb5318ec86d88282eab7057"}},Et=(o,t)=>{if(o!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let e=new eu.SuiClient({url:tu.rpc});return new nu.OnChainCalls(e,tu.objects,{address:t.address,isUIWallet:!1})};var M=class{static async OpenPosition(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,{...t,slippage:0});return await a.openPositionWithFixedAmount(r,t.lowerTick,t.upperTick,i,{returnTx:!0,sender:e.address})}static async provideLiquidity(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool),i=this.prototype.buildLiqInput(r,t);return await a.provideLiquidityWithFixedAmount(r,t.position,i,{returnTx:!0,sender:e.address})}static async removeLiquidity(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool);return await a.removeLiquidity(r,t.position,{liquidityAmount:new et.BN(t.liquidity),tokenMaxA:new et.BN(t.maxAmountTokenA),tokenMaxB:new et.BN(t.maxAmountTokenB)},{returnTx:!0,sender:e.address})}static async closePosition(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool);return await a.closePosition(r,t.position,{returnTx:!0,sender:e.address})}static async collectRewards(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectRewards(r,t.position,{rewardCoinsType:t.collectRewardTokens,returnTx:!0,sender:e.address})}static async collectFee(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool);return await a.collectFee(r,t.position,{returnTx:!0,sender:e.address})}static async collectRewardsAndFee(t,e,n){let a=Et(n,e),r=await a.queryChain.getPool(t.pool);return console.log(t.position),await a.collectFeeAndRewards(r,t.position,{returnTx:!0,sender:e.address})}buildLiqInput(t,e){return{...et.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(e.lowerTick,e.upperTick,new et.BN(e.tokenAmount),e.isTokenAFixed,!0,0,new et.BN(t.current_sqrt_price)),tokenMaxA:new et.BN(e.maxAmountTokenA),tokenMaxB:new et.BN(e.maxAmountTokenB)}}};var wr=class o extends f{constructor(e){super(e);this.data=e}txType=ou.TransactionType.Other;txSubType="ClosePosition";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.closePosition(this.data,n,a)}static fromData(e){return new o(e)}};var au=require("@msafe/sui3-utils");var Tr=class o extends f{constructor(e){super(e);this.data=e}txType=au.TransactionType.Other;txSubType="CollectFee";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.collectFee(this.data,n,a)}static fromData(e){return new o(e)}};var ru=require("@msafe/sui3-utils");var Cr=class o extends f{constructor(e){super(e);this.data=e}txType=ru.TransactionType.Other;txSubType="CollectRewards";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.collectRewards(this.data,n,a)}static fromData(e){return new o(e)}};var iu=require("@msafe/sui3-utils");var Ir=class o extends f{constructor(e){super(e);this.data=e}txType=iu.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.collectRewardsAndFee(this.data,n,a)}static fromData(e){return new o(e)}};var su=require("@msafe/sui3-utils");var kr=class o extends f{constructor(e){super(e);this.data=e}txType=su.TransactionType.Other;txSubType="OpenPosition";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.OpenPosition(this.data,n,a)}static fromData(e){return new o(e)}};var cu=require("@msafe/sui3-utils");var Dr=class o extends f{constructor(e){super(e);this.data=e}txType=cu.TransactionType.Other;txSubType="ProvideLiquidity";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.provideLiquidity(this.data,n,a)}static fromData(e){return new o(e)}};var lu=require("@msafe/sui3-utils");var xr=class o extends f{constructor(e){super(e);this.data=e}txType=lu.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:a}=e;return console.log(this.data),M.removeLiquidity(this.data,n,a)}static fromData(e){return new o(e)}};var vr=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(t){console.log("Bluefin helper deserialize input: ",t);let{transaction:e}=t,a=new Sr(e).decode();return{txType:du.TransactionType.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:n,network:a}=t;console.log(t.txSubType);let r;switch(t.txSubType){case"OpenPosition":r=kr.fromData(t.intentionData);break;case"ProvideLiquidity":r=Dr.fromData(t.intentionData);break;case"RemoveLiquidity":r=xr.fromData(t.intentionData);break;case"ClosePosition":r=wr.fromData(t.intentionData);break;case"CollectFee":r=Tr.fromData(t.intentionData);break;case"CollectRewards":r=Cr.fromData(t.intentionData);break;case"CollectRewardsAndFee":r=Ir.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:a})}};var wu=require("@msafe/sui3-utils");var uu=require("kriya-dev-sdk");var Ar=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new uu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbAddLiquidity(n)}static fromData(e){return new o(e)}};var pu=require("kriya-dev-sdk");var Or=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new pu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new o(e)}};var mu=require("kriya-dev-sdk");var Pr=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new mu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbClaimRewards(n)}static fromData(e){return new o(e)}};var fu=require("kriya-dev-sdk");var Rr=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new fu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbRemoveLiquidity(n)}static fromData(e){return new o(e)}};var bu=require("kriya-dev-sdk");var _r=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new bu.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new o(e)}};var gu=require("kriya-dev-sdk");var Br=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new gu.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbAddLiquidity(n)}static fromData(e){return new o(e)}};var hu=require("kriya-dev-sdk");var Mr=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new hu.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbClaimMayaRewards(n)}static fromData(e){return new o(e)}};var yu=require("kriya-dev-sdk");var jr=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new yu.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbClaimRewards(n)}static fromData(e){return new o(e)}};var Su=require("kriya-dev-sdk");var Nr=class o extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Su.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbRemoveLiquidity(n)}static fromData(e){return new o(e)}};var Er=class{application="kriya";supportSDK="@mysten/sui";async deserialize(t){let{appContext:e}=t;return{txType:wu.TransactionType.Other,txSubType:e.action,intentionData:e}}async build(t){let e;switch(t.txSubType){case"AddLiquidity":e=Ar.fromData(t.intentionData);break;case"AddLiquiditySingleSided":e=Or.fromData(t.intentionData);break;case"RemoveLiquidity":e=Rr.fromData(t.intentionData);break;case"ClaimRewards":e=Pr.fromData(t.intentionData);break;case"ClaimRewardsV3":e=jr.fromData(t.intentionData);break;case"ClaimV3MayaRewards":e=Mr.fromData(t.intentionData);break;case"AddLiquidityV3":e=Br.fromData(t.intentionData);break;case"AddLiquiditySingleSideV3":e=_r.fromData(t.intentionData);break;case"RemoveLiquidityV3":e=Nr.fromData(t.intentionData);break;default:throw new Error("not implemented")}return e.build()}};var zp=Eo.fromHelpers([new ko,new _o,new To,new Bo,new Xn,new pr,new Er,new Pa,new yr,new An,new Va,new Qa,new ln,new vr,new Ya]);
|
|
1
|
+
"use strict";var Nu=Object.create;var on=Object.defineProperty;var ju=Object.getOwnPropertyDescriptor;var Eu=Object.getOwnPropertyNames;var Wu=Object.getPrototypeOf,Lu=Object.prototype.hasOwnProperty;var qr=(a,t)=>{for(var e in t)on(a,e,{get:t[e],enumerable:!0})},Qi=(a,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Eu(t))!Lu.call(a,o)&&o!==e&&on(a,o,{get:()=>t[o],enumerable:!(n=ju(t,o))||n.enumerable});return a};var N=(a,t,e)=>(e=a!=null?Nu(Wu(a)):{},Qi(t||!a||!a.__esModule?on(e,"default",{value:a,enumerable:!0}):e,a)),Uu=a=>Qi(on({},"__esModule",{value:!0}),a);var lm={};qr(lm,{appHelpers:()=>cm});module.exports=Uu(lm);var Zi=require("@msafe/sui3-utils");var Hi=N(require("sort-keys-recursive")),f=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Hi.default)(this.data))}};var Gi=require("@alphafi/alphafi-sdk"),an=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(0,Gi.depositDoubleAssetTxb)(o,n.address,r,i)}static fromData(e){return console.log("DepositDoubleAssetIntention.fromData",e),new a(e)}};var zi=require("@alphafi/alphafi-sdk"),rn=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(0,zi.depositSingleAssetTxb)(o,n.address,r)}static fromData(e){return console.log("DepositSingleAssetIntention.fromData",e),new a(e)}};var Ji=require("@alphafi/alphafi-sdk"),sn=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(0,Ji.withdrawAlphaTxb)(r,o,n.address)}static fromData(e){return console.log("WithdrawAlphaIntention.fromData",e),new a(e)}};var Yi=require("@alphafi/alphafi-sdk"),cn=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(0,Yi.withdrawTxb)(r,o,n.address)}static fromData(e){return console.log("WithdrawIntention.fromData",e),new a(e)}};var Xi=require("@alphafi/alphafi-sdk"),ln=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e;return await(0,Xi.claimRewardTxb)(n.address)}static fromData(e){return new a(e)}};var Qt=require("@msafe/sui3-utils");var ot=require("@alphafi/alphafi-sdk"),X=require("@mysten/bcs"),dn=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=ot.poolIdPoolNameMap[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&&ot.poolInfo[e].assetTypes.length===2}isSingleAssetDepositEvent(t,e){return t.event_type===0&&ot.poolInfo[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 e=t.Pure.bytes,n;return e.length===12?n=X.bcs.u64().parse((0,X.fromB64)(e)):e.length===24?n=X.bcs.u128().parse((0,X.fromB64)(e)):e.length===44?n=X.bcs.u256().parse((0,X.fromB64)(e)):n=n=X.bcs.u64().parse((0,X.fromB64)(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:Qt.TransactionType.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 r=ot.singleAssetPoolCoinMap[t].coin,i=ot.coinsList[r].expo;n=Math.floor(Number(n)/10**(9-i)).toString()}return{txType:Qt.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:t,amount:n}}}decodeWithdraw(t){let e=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",e),{txType:Qt.TransactionType.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:Qt.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:e}}}decodeClaimReward(){return{txType:Qt.TransactionType.Other,type:"claimReward",intentionData:{}}}};var un=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 dn(e,r).decode();return{txType:Zi.TransactionType.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=rn.fromData(t.intentionData);break;case"depositDoubleAsset":n=an.fromData(t.intentionData);break;case"withdraw":n=cn.fromData(t.intentionData);break;case"withdrawAlpha":n=sn.fromData(t.intentionData);break;case"claimReward":n=ln.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({account:e})}};var ks=require("@msafe/sui3-utils");var L=require("@msafe/sui3-utils");var pn=require("bucket-protocol-sdk"),mn=require("@mysten/sui/bcs"),fn=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(pn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(pn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(pn.SBUCK_FOUNTAIN_PACKAGE_ID,"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[0],e=!1):(t=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments[0],e=!0),console.log("Decoder.decodePsm",t,n,e),{txType:L.TransactionType.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[0];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[0])}}else if(this.getMoveCallCommand("high_borrow")){let s=this.getMoveCallCommand("high_borrow").MoveCall;t=s.typeArguments[0];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[0])}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let s=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;t=s.typeArguments[0];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[0])}}return{txType:L.TransactionType.Other,type:"borrow",intentionData:{collateralType:t,collateralAmount:r,borrowAmount:e,insertionPlace:n,strapId:o}}}decodeRepay(){let t="",e="0",n="0",o=!1,r,i=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))t=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments[0];else if(this.getMoveCallCommand("fully_repay_with_strap"))t=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments[0];else if(this.getMoveCallCommand("repay_and_withdraw")){let s=this.getMoveCallCommand("repay_and_withdraw").MoveCall;t=s.typeArguments[0];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[0])}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[0];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[0])}let l=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];l.$kind=="Input"&&(e=this.getPureInputU64(l.Input))}return{txType:L.TransactionType.Other,type:"repay",intentionData:{collateralType:t,repayAmount:e,withdrawAmount:n,isSurplus:o,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[0];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[0])}}else if(this.getMoveCallCommand("withdraw")){let r=this.getMoveCallCommand("withdraw").MoveCall;t=r.typeArguments[0];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[0])}}return{txType:L.TransactionType.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[0]),{txType:L.TransactionType.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:L.TransactionType.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 of o)n.push("");else{let s=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let c of s){let d=c.MoveCall.arguments[2];if(d.$kind=="Input"){let l=this.inputs[d.Input].UnresolvedObject.objectId;n.push(l)}}}let r=this.isSBUCKWithdrawTransaction(),i={stakeProofs:n,amount:t,isStake:e,toBuck:r};return console.log("Decoder.decodeSBUCKUnstake",i),{txType:L.TransactionType.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:L.TransactionType.Other,type:"sbuck-withdraw",intentionData:{amount:t}}}decodeSBUCKClaim(){let t=[],e=this.getMoveCallModuleCommands("fountain_core","claim");for(let n of e){let o=n.MoveCall.arguments[2];if(o.$kind=="Input"){let r=this.inputs[o.Input].UnresolvedObject.objectId;t.push(r)}}return console.log("Decoder.decodeSBUCKClaim",t),{txType:L.TransactionType.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:L.TransactionType.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:L.TransactionType.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:L.TransactionType.Other,type:"tank-claim",intentionData:{coinType:e}}}decodeLockedClaim(){let t="",e=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let r of n)t=r.MoveCall.typeArguments[0],e++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let r of o)t=r.MoveCall.typeArguments[0],e++;return console.log("Decoder.decodeLockedClaim",t,e),{txType:L.TransactionType.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 mn.bcs.U64.fromBase64(e.Pure.bytes)}getPureAddresses(t){let e=this.inputs[t];if(e.$kind!=="Pure")throw new Error("not pure argument");return mn.bcs.vector(mn.bcs.Address).fromBase64(e.Pure.bytes)}};var as=require("@msafe/sui3-utils");var es=require("@mysten/sui/transactions"),ns=require("bucket-protocol-sdk");var ts=require("bucket-protocol-sdk"),R=(a,t)=>{let e=a==="sui:mainnet"?"mainnet":"testnet";return new ts.BucketClient(e,t.address)};var os=async(a,t,e)=>{let{coinType:n,amount:o,buckToCoin:r}=a,i=new es.Transaction,s=R(e,t);return await(0,ns.buildPsmTx)(s,i,n,o,r,t.address),i};var bn=class a extends f{constructor(e){super(e);this.data=e}txType=as.TransactionType.Other;txSubType="psm";async build(e){let{account:n,network:o}=e;return await os(this.data,n,o)}static fromData(e){return new a(e)}};var ls=require("@msafe/sui3-utils");var Se=require("@mysten/sui/transactions");var ut=require("bucket-protocol-sdk"),rs=async(a,t,e)=>{let{collateralType:n,collateralAmount:o,borrowAmount:r,insertionPlace:i,strapId:s}=a,c=new Se.Transaction,d=R(e,t);return await(0,ut.buildBorrowTx)(d,c,n,o,r,t.address,i,s),c},is=async(a,t,e)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:r,strapId:i}=a,s=new Se.Transaction,c=R(e,t);return await(0,ut.buildWithdrawTx)(c,s,n,o,t.address,r,i),s},ss=async(a,t,e)=>{let{collateralType:n,repayAmount:o,withdrawAmount:r,isSurplus:i,insertionPlace:s,strapId:c}=a,d=new Se.Transaction,l=R(e,t);return await(0,ut.buildRepayTx)(l,d,n,o,r,t.address,i,s,c),d},cs=async(a,t,e)=>{let{collateralType:n,recipient:o,strapId:r}=a,i=new Se.Transaction,s=R(e,t);return await(0,ut.buildCloseTx)(s,i,n,o,r),i};var gn=class a extends f{constructor(e){super(e);this.data=e}txType=ls.TransactionType.Other;txSubType="borrow";async build(e){let{account:n,network:o}=e;return await rs(this.data,n,o)}static fromData(e){return new a(e)}};var ds=require("@msafe/sui3-utils");var hn=class a extends f{constructor(e){super(e);this.data=e}txType=ds.TransactionType.Other;txSubType="repay";async build(e){let{account:n,network:o}=e;return await ss(this.data,n,o)}static fromData(e){return new a(e)}};var us=require("@msafe/sui3-utils");var yn=class a extends f{constructor(e){super(e);this.data=e}txType=us.TransactionType.Other;txSubType="withdraw";async build(e){let{account:n,network:o}=e;return await is(this.data,n,o)}static fromData(e){return new a(e)}};var ps=require("@msafe/sui3-utils");var Sn=class a extends f{constructor(e){super(e);this.data=e}txType=ps.TransactionType.Other;txSubType="close";async build(e){let{account:n,network:o}=e;return await cs(this.data,n,o)}static fromData(e){return new a(e)}};var we=require("@msafe/sui3-utils");var Te=require("@mysten/sui/transactions"),pt=require("bucket-protocol-sdk");var ms=async(a,t,e)=>{let{coinType:n,amount:o,isStake:r}=a,i=new Te.Transaction,s=R(e,t);return await(0,pt.buildSBUCKDepositTx)(s,i,n,o,t.address,r),i},fs=async(a,t,e)=>{let{stakeProofs:n,amount:o,isStake:r,toBuck:i}=a,s=new Te.Transaction,c=R(e,t);return await(0,pt.buildSBUCKUnstakeTx)(c,s,n,o,t.address,r,i),s},bs=async(a,t,e)=>{let{amount:n}=a,o=new Te.Transaction,r=R(e,t);return await(0,pt.buildSBUCKWithdrawTx)(r,o,n,t.address),o},gs=async(a,t,e)=>{let{stakeProofs:n}=a,o=new Te.Transaction,r=R(e,t);return await(0,pt.buildSBUCKClaimTx)(r,o,n,t.address),o};var Tn=class a extends f{constructor(e){super(e);this.data=e}txType=we.TransactionType.Other;txSubType="sbuck-deposit";async build(e){let{account:n,network:o}=e;return await ms(this.data,n,o)}static fromData(e){return new a(e)}},wn=class a extends f{constructor(e){super(e);this.data=e}txType=we.TransactionType.Other;txSubType="sbuck-unstake";async build(e){let{account:n,network:o}=e;return await fs(this.data,n,o)}static fromData(e){return new a(e)}},Cn=class a extends f{constructor(e){super(e);this.data=e}txType=we.TransactionType.Other;txSubType="sbuck-withdraw";async build(e){let{account:n,network:o}=e;return await bs(this.data,n,o)}static fromData(e){return new a(e)}},In=class a extends f{constructor(e){super(e);this.data=e}txType=we.TransactionType.Other;txSubType="sbuck-claim";async build(e){let{account:n,network:o}=e;return await gs(this.data,n,o)}static fromData(e){return new a(e)}};var An=require("@msafe/sui3-utils");var kn=require("@mysten/sui/transactions");var Ht=require("bucket-protocol-sdk"),hs=async(a,t,e)=>{let{coinType:n,amount:o}=a,r=new kn.Transaction,i=R(e,t);return await(0,Ht.buildTankDepositTx)(i,r,n,o,t.address),r},ys=async(a,t,e)=>{let{coinType:n,amount:o}=a,r=new kn.Transaction,i=R(e,t);return await(0,Ht.buildTankWithdrawTx)(i,r,n,o,t.address),r},Ss=async(a,t,e)=>{let{coinType:n}=a,o=new kn.Transaction,r=R(e,t);return await(0,Ht.buildTankClaimTx)(r,o,n,t.address),o};var Ts=require("@mysten/sui/transactions"),ws=require("bucket-protocol-sdk");var Cs=async(a,t,e)=>{let{coinType:n,proofCount:o}=a,r=new Ts.Transaction,i=R(e,t);return await(0,ws.buildLockedClaimTx)(i,r,n,o,t.address),r};var Dn=class a extends f{constructor(e){super(e);this.data=e}txType=An.TransactionType.Other;txSubType="tank-deposit";async build(e){let{account:n,network:o}=e;return await hs(this.data,n,o)}static fromData(e){return new a(e)}},xn=class a extends f{constructor(e){super(e);this.data=e}txType=An.TransactionType.Other;txSubType="tank-withdraw";async build(e){let{account:n,network:o}=e;return await ys(this.data,n,o)}static fromData(e){return new a(e)}},vn=class a extends f{constructor(e){super(e);this.data=e}txType=An.TransactionType.Other;txSubType="tank-claim";async build(e){let{account:n,network:o}=e;return await Ss(this.data,n,o)}static fromData(e){return new a(e)}};var Is=require("@msafe/sui3-utils");var On=class a extends f{constructor(e){super(e);this.data=e}txType=Is.TransactionType.Other;txSubType="lock-claim";async build(e){let{account:n,network:o}=e;return await Cs(this.data,n,o)}static fromData(e){return new a(e)}};var Pn=class{application="bucket";supportSDK="@mysten/sui";async deserialize(t){console.log("Bucket helper deserialize input: ",t);let{transaction:e}=t,o=new fn(e).decode();return{txType:ks.TransactionType.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=bn.fromData(t.intentionData);break;case"borrow":r=gn.fromData(t.intentionData);break;case"withdraw":r=yn.fromData(t.intentionData);break;case"repay":r=hn.fromData(t.intentionData);break;case"close":r=Sn.fromData(t.intentionData);break;case"tank-deposit":r=Dn.fromData(t.intentionData);break;case"tank-withdraw":r=xn.fromData(t.intentionData);break;case"tank-claim":r=vn.fromData(t.intentionData);break;case"sbuck-deposit":r=Tn.fromData(t.intentionData);break;case"sbuck-unstake":r=wn.fromData(t.intentionData);break;case"sbuck-withdraw":r=Cn.fromData(t.intentionData);break;case"sbuck-claim":r=In.fromData(t.intentionData);break;case"lock-claim":r=On.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};var vc=require("@msafe/sui3-utils");var Ns=require("@msafe/sui3-utils");var Ce=require("@cetusprotocol/aggregator-sdk"),Ds=require("@cetusprotocol/cetus-periphery-sdk"),xs=require("@cetusprotocol/cetus-sui-clmm-sdk"),vs=N(require("@cetusprotocol/vaults-sdk")),As=require("@mysten/sui/client"),qu={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},$u={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc",config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30",dividend_settle_id:"0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5",venft_dividends_id:"0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456",venft_dividends_id_v2:"0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3"}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},dca:{package_id:"",published_at:"",version:0,config:{admin_cap_id:"",global_config_id:"",indexer_id:"",user_indexer_id:"",in_coin_whitelist_id:"",out_coin_whitelist_id:""}}},Lt=(a,t)=>{let e=qu,n=new xs.CetusClmmSDK(e);return n.senderAddress=t.address,n},j=(a,t)=>{let e=Lt(a,t),n=$u;return new Ds.CetusPeripherySDK(n,e)},Ku="https://api-sui.cetus.zone/router_v2/find_routes",Os=(a,t)=>{let e=new As.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new Ce.AggregatorClient(Ku,t.address,e,Ce.Env.Mainnet)},Vu={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xdc67d6de3f00051c505da10d8f6fbab3b3ec21ec65f0dc22a2f36c13fc102110",config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:""}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0x3a5aa90ffa33d09100d7b6941ea1c0ffe6ab66e77062ddd26320c1b073aabb10"},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x7e4ca066f06a1132ab0499c8c0b87f847a0d90684afa902e52501a44dbd81992",config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0x58e5de6e425397eeaf952d55c0f94637bee91b25d6138ce222f89cda0aefec03",config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd",haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}},aggregator:{endPoint:"https://api-sui.cetus.zone/router_v2/find_routes",fullNodeurl:"https://fullnode.mainnet.sui.io/",walletAddress:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb",env:Ce.Env.Mainnet,providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"]}},$r=(a,t)=>{let e=new vs.default(Vu);return e.senderAddress=t.address,e};var Ps=async(a,t,e)=>await Lt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Rs=async(a,t,e)=>await Lt(e,t).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),_s=async(a,t,e)=>await Lt(e,t).Position.closePositionTransactionPayload(a),Bs=async(a,t,e)=>await Lt(e,t).Position.removeLiquidityTransactionPayload(a),Ms=async(a,t,e)=>await Lt(e,t).Rewarder.collectRewarderTransactionPayload(a);var Rn=class a extends f{constructor(e){super(e);this.data=e}txType=Ns.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ps(r,n,o)}static fromData(e){return new a(e)}};var js=require("@msafe/sui3-utils");var _n=class a extends f{constructor(e){super(e);this.data=e}txType=js.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ms(r,n,o)}static fromData(e){return new a(e)}};var Es=require("@msafe/sui3-utils");var Bn=class a extends f{constructor(e){super(e);this.data=e}txType=Es.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Bs(r,n,o)}static fromData(e){return new a(e)}};var Hs=require("@msafe/sui3-utils");var Ws=async(a,t,e)=>await j(e,t).Farms.openPositionAddLiquidityStakePaylod(a),Ls=async(a,t,e)=>await j(e,t).Farms.addLiquidityFixCoinPayload(a),Us=async(a,t,e)=>await j(e,t).Farms.removeLiquidityPayload(a),Fs=async(a,t,e)=>await j(e,t).Farms.removeLiquidityPayload(a),qs=async(a,t,e)=>await j(e,t).Farms.claimFeeAndClmmReward(a),$s=async(a,t,e)=>await j(e,t).Farms.harvestPayload(a),Ks=async(a,t,e)=>{let n=j(e,t),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},Vs=async(a,t,e)=>await j(e,t).Farms.depositPayload(a),Qs=async(a,t,e)=>await j(e,t).Farms.withdrawPayload(a);var Mn=class a extends f{constructor(e){super(e);this.data=e}txType=Hs.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ws(r,n,o)}static fromData(e){return new a(e)}};var Gs=require("@msafe/sui3-utils");var Nn=class a extends f{constructor(e){super(e);this.data=e}txType=Gs.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ks(r,n,o)}static fromData(e){return new a(e)}};var zs=require("@msafe/sui3-utils");var jn=class a extends f{constructor(e){super(e);this.data=e}txType=zs.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await qs(r,n,o)}static fromData(e){return new a(e)}};var Js=require("@msafe/sui3-utils");var En=class a extends f{constructor(e){super(e);this.data=e}txType=Js.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Us(r,n,o)}static fromData(e){return new a(e)}};var Ys=require("@msafe/sui3-utils");var Wn=class a extends f{constructor(e){super(e);this.data=e}txType=Ys.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await $s(r,n,o)}static fromData(e){return new a(e)}};var Xs=require("@msafe/sui3-utils");var Ln=class a extends f{constructor(e){super(e);this.data=e}txType=Xs.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Ls(r,n,o)}static fromData(e){return new a(e)}};var Zs=require("@msafe/sui3-utils");var Un=class a extends f{constructor(e){super(e);this.data=e}txType=Zs.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Fs(r,n,o)}static fromData(e){return new a(e)}};var tc=require("@msafe/sui3-utils");var Fn=class a extends f{constructor(e){super(e);this.data=e}txType=tc.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Vs(r,n,o)}static fromData(e){return new a(e)}};var ec=require("@msafe/sui3-utils");var qn=class a extends f{constructor(e){super(e);this.data=e}txType=ec.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Qs(r,n,o)}static fromData(e){return new a(e)}};var nc=require("@msafe/sui3-utils");var $n=class a extends f{constructor(e){super(e);this.data=e}txType=nc.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Rs(r,n,o)}static fromData(e){return new a(e)}};var oc=require("@msafe/sui3-utils");var Kn=class a extends f{constructor(e){super(e);this.data=e}txType=oc.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await _s(r,n,o)}static fromData(e){return new a(e)}};var sc=require("@msafe/sui3-utils");var ac=require("@cetusprotocol/aggregator-sdk"),rc=require("@mysten/sui/transactions");var ic=async(a,t,e)=>{let n=Os(e,t),o=new rc.Transaction;return await n.fastRouterSwap({...a,routers:(0,ac.restituteMsafeFastRouterSwapParams)(a.routers),txb:o}),o};var Vn=class a extends f{constructor(e){super(e);this.data=e}txType=sc.TransactionType.Other;txSubType="AggregatorSwap";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await ic(r,n,o)}static fromData(e){return new a(e)}};var dc=require("@msafe/sui3-utils");var cc=async(a,t,e)=>await $r(e,t).Vaults.deposit(a),lc=async(a,t,e)=>await $r(e,t).Vaults.withdraw(a);var Qn=class a extends f{constructor(e){super(e);this.data=e}txType=dc.TransactionType.Other;txSubType="AddVaultsPosition";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await cc(r,n,o)}static fromData(e){return new a(e)}};var uc=require("@msafe/sui3-utils");var Hn=class a extends f{constructor(e){super(e);this.data=e}txType=uc.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await lc(r,n,o)}static fromData(e){return new a(e)}};var bc=require("@msafe/sui3-utils");var mc=require("@mysten/sui/transactions"),pc={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},fc=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 mc.Transaction;return r.forEach(c=>{s.moveCall({target:`${pc.published_at}::router::redeem`,typeArguments:[pc.cetus_coin_type],arguments:[s.object(n),s.object(o),s.pure(c),s.object(i)]})}),s};var Gn=class a extends f{constructor(e){super(e);this.data=e}txType=bc.TransactionType.Other;txSubType="VestingRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await fc(r,n,o)}static fromData(e){return new a(e)}};var Cc=require("@msafe/sui3-utils");var gc=require("@mysten/sui/transactions");var hc=async(a,t,e)=>{let n=j(e,t),o=new gc.Transaction;return await n.XCetusModule.convertPayload(a,o)},yc=async(a,t,e)=>await j(e,t).XCetusModule.redeemLockPayload(a),Sc=async(a,t,e)=>await j(e,t).XCetusModule.redeemDividendV3Payload(a.phases,a.venft_id,a.bonus_types,a.bonus_types_v2,a.xTokenType),Tc=async(a,t,e)=>await j(e,t).XCetusModule.cancelRedeemPayload(a),wc=async(a,t,e)=>await j(e,t).XCetusModule.redeemPayload(a);var zn=class a extends f{constructor(e){super(e);this.data=e}txType=Cc.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Tc(r,n,o)}static fromData(e){return new a(e)}};var Ic=require("@msafe/sui3-utils");var Jn=class a extends f{constructor(e){super(e);this.data=e}txType=Ic.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await Sc(r,n,o)}static fromData(e){return new a(e)}};var kc=require("@msafe/sui3-utils");var Yn=class a extends f{constructor(e){super(e);this.data=e}txType=kc.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await hc(r,n,o)}static fromData(e){return new a(e)}};var Dc=require("@msafe/sui3-utils");var Xn=class a extends f{constructor(e){super(e);this.data=e}txType=Dc.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await wc(r,n,o)}static fromData(e){return new a(e)}};var xc=require("@msafe/sui3-utils");var Zn=class a extends f{constructor(e){super(e);this.data=e}txType=xc.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:o}=e,{txbParams:r}=this.data;return await yc(r,n,o)}static fromData(e){return new a(e)}};var to=class{application="cetus";supportSDK="@mysten/sui";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:vc.TransactionType.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=Rn.fromData(t.intentionData);break;case"IncreaseLiquidity":r=$n.fromData(t.intentionData);break;case"DecreaseLiquidity":r=Bn.fromData(t.intentionData);break;case"RemoveLiquidity":r=Kn.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=_n.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=Mn.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=Ln.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=En.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=Un.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=jn.fromData(t.intentionData);break;case"FarmingHarvest":r=Wn.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=Nn.fromData(t.intentionData);break;case"FarmingStake":r=Fn.fromData(t.intentionData);break;case"FarmingUnstake":r=qn.fromData(t.intentionData);break;case"xCETUSConvert":r=Yn.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Zn.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=Jn.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=zn.fromData(t.intentionData);break;case"xCETUSRedeem":r=Xn.fromData(t.intentionData);break;case"VestingRedeem":r=Gn.fromData(t.intentionData);break;case"AggregatorSwap":r=Vn.fromData(t.intentionData);break;case"AddVaultsPosition":r=Qn.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})}};var Jc=require("@msafe/sui3-utils");var Ac=N(require("sort-keys-recursive")),y=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Ac.default)(this.data))}};var Ie=require("@mysten/sui.js/client");var Kr={};qr(Kr,{contractId:()=>Gu,default:()=>Zu,feeObjId:()=>Yu,roleObjId:()=>zu,status:()=>Hu,transaction:()=>Qu,upgradeCapObjId:()=>Xu,vaultObjId:()=>Ju});var Qu="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Hu="success",Gu="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",zu="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Ju="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Yu="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Xu="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zu={transaction:Qu,status:Hu,contractId:Gu,roleObjId:zu,vaultObjId:Ju,feeObjId:Yu,upgradeCapObjId:Xu};var Vr={};qr(Vr,{contractId:()=>np,default:()=>sp,feeObjId:()=>rp,roleObjId:()=>op,status:()=>ep,transaction:()=>tp,upgradeCapObjId:()=>ip,vaultObjId:()=>ap});var tp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ep="success",np="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",op="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",ap="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",rp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",ip="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",sp={transaction:tp,status:ep,contractId:np,roleObjId:op,vaultObjId:ap,feeObjId:rp,upgradeCapObjId:ip};var cp=(0,Ie.getFullnodeUrl)("testnet"),lp=(0,Ie.getFullnodeUrl)("testnet"),dp=(0,Ie.getFullnodeUrl)("mainnet"),up=(0,Ie.getFullnodeUrl)("mainnet"),pp="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",mp="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",fp="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",bp="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Oc=Kr,Pc=Vr,gp=new Map([["dev",{env:"dev",rpc:{url:cp},backend:{url:pp},contract:Oc}],["stg",{env:"stg",rpc:{url:lp},backend:{url:mp},contract:Oc}],["prev",{env:"prev",rpc:{url:dp},backend:{url:fp},contract:Pc}],["prod",{env:"prod",rpc:{url:up},backend:{url:bp},contract:Pc}]]);function Rc(a,t){let e=gp.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}var _c=require("@mysten/sui.js/client");var k=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 eo=class extends k{constructor(){super(11,"Backend is not specified")}};var no=class extends k{constructor(){super(1,"Wallet not connected")}};var rt=N(require("axios"));var Gt=class extends k{constructor(t,e){super(10,t,{context:e})}};var oo=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof rt.AxiosError)throw new Gt(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new Gt(t.data.code)}throw new Gt(t.status.toString())}async getIncomingStreams(t,e){let n=await rt.default.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(n)}async getOutgoingStreams(t,e){let n=await rt.default.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(n)}async getStreamHistory(t){let e=await rt.default.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 rt.default.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let n=await rt.default.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(n)}async getAllSenders(t,e){let n=await rt.default.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(n)}};var zt=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new _c.SuiClient({url:t.rpc.url}),t.backend&&(this._backend=new oo(t.backend.url))}static new(t,e){let n=Rc(t,e);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new eo;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 no;return this.signer}async walletAddress(){return this.wallet.address()}};var Ft=require("@mysten/sui.js/utils");var Oe=require("@mysten/sui.js/transactions");var Jr=require("@mysten/sui.js/transactions"),Ae=require("@mysten/sui.js/utils");var Qr=50n,ao=10000n,Bc=25n,Hr=100000000n;var Z=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},ke=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},bt=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}};var Gr=require("buffer"),Mc=require("@mysten/sui.js/utils");var De=class extends k{constructor(t,e){super(3,t,{context:e})}};var ro=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 De("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return(0,Mc.normalizeSuiAddress)(Gr.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,o]=this.getValue(t,e);if(o!=="u64")throw new De("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Gr.Buffer.from(n).readBigInt64LE()}};var zr=require("@mysten/sui.js/bcs");var v=class extends k{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}};var jc={groupId:"string",name:"string"},hp=64;function Ec(a){return Wc(a),zr.bcs.ser(jc,a).toString("base64")}function xe(a){let t=zr.bcs.de(jc,a,"base64");return Wc(t),t}function Wc(a){if(!Nc(a.name))throw new v("Invalid metadata: Name contains unknown character");if(!Nc(a.groupId))throw new v("Invalid metadata: Group ID contains unknown character");if(a.name.length>hp)throw new v("Invalid metadata: Name exceed max length 64")}function Nc(a){return/^[\x00-\x7F]+$/.test(a)}var ve=require("@mysten/sui.js/utils");function io(a,t){return(0,ve.normalizeStructTag)(a)===(0,ve.normalizeStructTag)(t)}function gt(a,t){return(0,ve.normalizeStructTag)(a)===(0,ve.normalizeStructTag)(t)}var so="txn.gas";var Lc=require("nanoid");function Uc(){return(0,Lc.nanoid)()}var Ut=class a{constructor(t,e,n){this.globals=t;this.feeContract=e;this.streamContract=n}static convertCreateStreamInfoToInternal(t){return{metadata:Ec({name:t.name,groupId:Uc()}),coinType:(0,Ae.normalizeStructTag)(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new Jr.TransactionBlock,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 bt(p),flatFeeCoin:new bt(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:Qr,denominator:ao},claimFeePercent:{numerator:Bc,denominator:ao},flatFeePerStream:Hr}}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===so?n=t.gas:n=t.object(e.primaryCoin),n}getCreateStreamCoinRequests(t,e){let n=t.coinType;return io(n,Ae.SUI_TYPE_ARG)?[{coinType:n,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:n,amount:e.totalAmount+e.streamFeeAmount},{coinType:Ae.SUI_TYPE_ARG,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 Hr}getStreamFeeLocal(t){return t*Qr/ao}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Jr.TransactionBlock,t),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new ro(n).getU64()}get wallet(){return this.globals.wallet}};var Yr=require("@mysten/sui.js/transactions");var Fc="0x0000000000000000000000000000000000000000000000000000000000000006";var Jt=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(Yr.Transactions.MoveCall({target:n,arguments:e.arguments.map(o=>o instanceof ke?o.moveArgs(t):o instanceof Z?o.moveArg(t):o instanceof bt?o.moveArg():t.pure(o)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],o=[]){t.add(Yr.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof ke?r.moveArgs(t):r instanceof Z?r.moveArg(t):r instanceof bt?r.moveArg():t.pure(r)),typeArguments:o}))}makeObject(t){return typeof t=="string"?new Z(t):t}vaultObject(){return new Z(this.config.vaultObjId)}roleObject(){return new Z(this.config.roleObjId)}feeObject(){return new Z(this.config.feeObjId)}clockObject(){return new Z(Fc)}};var Yt=class a extends Jt{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 tt=class a extends Jt{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 Xt=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Yt(e,t),this.streamContract=new tt(e,t)}feeContract;streamContract;async createStreams(t){let e=Ut.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Ut(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let o=new Oe.TransactionBlock;return this.streamContract.setAutoClaim(o,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Oe.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Oe.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Oe.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}};var P=class extends k{constructor(t,e={}){super(0,t,e)}};async function Zr(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 Xr=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)}},Zt=class{constructor(t){this.requester=t;this.pager=new Xr(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 co=class extends k{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 yp=25;async function qc(a,t,e,n="0x2::sui::SUI",o=yp){let r=new ti(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 co(n,e,i);return s}var ti=class extends Zt{constructor(e,n,o,r){super(new ei(e,n,o,r));this.suiClient=e;this.owner=n;this.coinType=o;this.reqPageSize=r}},ei=class{constructor(t,e,n,o){this.suiClient=t;this.owner=e;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new P("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var _e=require("@mysten/sui.js/transactions"),Be=require("@mysten/sui.js/utils"),Kc=require("luxon");var lo=class extends k{constructor(){super(7,"Connected wallet is not creator")}};var Pe=class extends k{constructor(){super(8,"Connected wallet is not recipient")}};var Re=class extends k{constructor(t,e){super(6,t,{context:e})}};var uo=class extends k{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};var mo=require("luxon"),$c=(1n<<64n)-1n,po=1e3;function ni(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/po);return mo.DateTime.fromMillis(e*po)}function oi(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/po);return mo.Duration.fromMillis(e*po)}var ht=class a{constructor(t,e,n){this.globals=t;this.streamId=e;this.rawData=n;this.streamContract=new tt(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 P("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new lo;let t=new _e.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Pe;let t=new _e.TransactionBlock;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Pe;let e=new _e.TransactionBlock;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new _e.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Be.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return oi(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return xe(t).groupId}get name(){let{metadata:t}=this.rawData.config;return xe(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ni(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return oi(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:ni((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===$c?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Kc.DateTime.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let n=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let n=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(e,n)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new uo(t):new Re(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let n=e.data.content;if(n.dataType!=="moveObject")throw new Re("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=(0,Be.parseStructTag)(n.type),r=(0,Be.normalizeStructTag)(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 te=require("@mysten/sui.js/utils"),ai=require("luxon");var fo=class extends k{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Sp=1e3,bo=class{constructor(t){this.globals=t;this.coinMetaHelper=new ri(t.suiClient),this.createStreamHelper=new Xt(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new fo(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,o=(t.totalAmount-n)/t.steps,i={realTotalAmount:o*t.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new v("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(ai.Duration.fromMillis(Number(e*t.steps))),o={timeStart:t.timeStart,timeEnd:n,interval:ai.Duration.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:(0,te.normalizeStructTag)(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:(0,te.normalizeStructTag)(o.coinType),coinMeta:n[r]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new v("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new v("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Sp)throw new v("Interval shall be at least 1 second","interval",t.interval)}},ri=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,te.normalizeStructTag)(t||te.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};var yt=require("@mysten/sui.js/utils"),ci=require("luxon");var ee=class extends k{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};var Tp=25;async function si(a,t,e){let n=new Me(t),o=new Ne(a,n,e);return await Zr(o)}var Me=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 Zt{constructor(e,n,o){super(new ii(e,n,o));this.suiClient=e;this.idIter=n;this.options=o}},ii=class{constructor(t,e,n){this.suiClient=t;this.stringIter=e;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||Tp,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 go=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new ee("stream size 0");let n=e.map(r=>r.groupId);if(new Set(n).size!==1)throw new v("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let n=await si(t.suiClient,e);return n.forEach(o=>{if(!o)throw new P("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=>{wp(n,r)||(o=!1)}),o}async refresh(){let t=await si(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)=>ht.fromObjectData(t,e[i],r)).filter(r=>!!r);if(new Set(o.map(r=>r.groupId)).size!==1)throw new ee("Not same group ID");if(!this.checkStreamGroup(o))throw new ee("Not same stream settings");return o}};function wp(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 je=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await ho.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await ho.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}},ho=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await yo.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await yo.newOutgoingQuery(t);return new a(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new P("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new P("No more results");return t}},yo=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 Me(n.flat().map(i=>i.streamId));this.objectIter=new Ne(t.suiClient,r)}current=0;objectIter;static async newIncomingQuery(t){let e=xp(t.query),n=await t.globals.walletAddress(),r=(await t.globals.backend.getIncomingStreams(n,e)).filter(s=>(0,yt.normalizeSuiAddress)(s.recipient)===(0,yt.normalizeSuiAddress)(n)),i=Vc(r);return new a(t.globals,n,i,t.query)}static async newOutgoingQuery(t){let e=vp(t.query),n=await t.globals.walletAddress(),o=await t.globals.backend.getOutgoingStreams(n,e),r=Vc(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 kp(this.globals,t[0].streamId,this.objectIter);return this.current++,Qc(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Dp(this.globals,t.map(n=>n.streamId),this.objectIter);return this.current++,Ip(e,this.query)?e:this.doNextRequest()}throw new P("Stream group with no stream")}};function Vc(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)=>ci.DateTime.fromISO(n[0].createDate).toMillis()-ci.DateTime.fromISO(e[0].createDate).toMillis())}function Qc(a,t){if(t===void 0)return!0;let e=Cp(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 Cp(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function Ip(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(n=>{Qc(n,t)&&(e=!0)}),e}async function kp(a,t,e){let n=await Hc(e,t);return ht.fromObjectData(a,t,n)}async function Dp(a,t,e){let n=[];for(;n.length<t.length;){let o=await Hc(e,t[n.length]);n.push(o)}return go.newFromObjectResponse(a,t,n)}async function Hc(a,t){if(!await a.hasNext())throw new P("object iterator has been consumed");let e=await a.next();if(!e||e.error||e.data===void 0||e.data===null)throw new P("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new P("stream id not aligned");return e}function xp(a){return{status:li(a?.status),coinType:Gc(a?.coinType),sender:zc(a?.sender)}}function vp(a){return{status:li(a?.status),coinType:Gc(a?.coinType),recipient:zc(a?.recipient)}}function li(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let n=li(e);return!t||t===n?n:"all"},void 0):Ap(a)}function Ap(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new v("Unknown stream filtered status")}}function Gc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>(0,yt.normalizeStructTag)(t)):void 0:(0,yt.normalizeStructTag)(a)}function zc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>(0,yt.normalizeSuiAddress)(t)):void 0:(0,yt.normalizeSuiAddress)(a)}var di=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},So=class{constructor(t){this.account=t}async address(){return this.account.address}},ui=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(io(t.coinType,Ft.SUI_TYPE_ARG))return{primaryCoin:so};if(t.amount<=0)throw new v("Invalid coin request","coinAmount",t.amount);let e=await qc(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new P("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},To=class{globals;helper;constructor(t,e){this.globals=zt.new(t,e),this.helper=new bo(this.globals)}connectSingleWallet(t){let e=new ui(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new di(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ht.new(this.globals,t)}async getIncomingStreams(t,e=10){return je.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return je.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(n=>(0,Ft.normalizeStructTag)(n))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(o=>(0,Ft.normalizeSuiAddress)(o))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(o=>(0,Ft.normalizeSuiAddress)(o))}get wallet(){return this.globals.wallet}builder(){return new Xt(this.globals)}};var G=class extends y{application="mpay";getClient(t,e){let n=new To(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new So(e)),n}};var Ee=class extends G{constructor(e){super(e);this.data=e}txType=Jc.TransactionType.Stream;txSubType="Cancel";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};var Yc=require("@msafe/sui3-utils");var We=class extends G{constructor(e){super(e);this.data=e}txType=Yc.TransactionType.Stream;txSubType="ClaimByProxy";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};var Xc=require("@msafe/sui3-utils");var Le=class extends G{constructor(e){super(e);this.data=e}txType=Xc.TransactionType.Stream;txSubType="Claim";async build(e){let{network:n,account:o}=e;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};var Zc=require("@msafe/sui3-utils");var Ue=class extends G{constructor(e){super(e);this.data=e}txType=Zc.TransactionType.Stream;txSubType="CreateStream";async build(e){let{network:n,account:o}=e;return this.getClient(n,o).createStream(this.data)}};var pi=require("@mysten/sui.js/bcs"),St=require("@mysten/sui.js/utils"),ne=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(0,St.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return 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 pi.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,St.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,St.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,St.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,St.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return pi.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,St.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var wo=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 P("No create stream transactions");return t.map(e=>new ne(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:o}=xe(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 v("Stream group not have common info");let n=t.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:n,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new tt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Yt(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Ut(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 Co=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new tt(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 wo(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 ne(t,this.txb)}};var tl=require("@msafe/sui3-utils");var Fe=class extends G{constructor(e){super(e);this.data=e}txType=tl.TransactionType.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 Io=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(t){let{network:e,transactionBlock:n}=t,o=zt.new(e==="sui:mainnet"?"prod":"dev"),i=new Co(o,n).decode(),s;switch(i.type){case"CreateStream":s=new Ue(i.info);break;case"SetAutoClaim":s=new Fe({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new Le({streamId:i.streamId});break;case"ClaimByProxy":s=new We({streamId:i.streamId});break;case"Cancel":s=new Ee({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 Ue(e);break;case"Claim":n=new Le(e);break;case"ClaimByProxy":n=new We(e);break;case"SetAutoClaim":n=new Fe(e);break;case"Cancel":n=new Ee(e);break;default:throw new Error("not implemented")}return n.build({...t})}};var qe=require("@msafe/sui3-utils");var el=require("@msafe/sui3-utils");var ko=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return(0,el.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(e){return new a(e)}};var nl=require("@msafe/sui3-utils");var Do=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e;return(0,nl.buildObjectTransferTxb)(n,this.data,o.address)}static fromData(e){return new a(e)}};var xo=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=qe.TransactionDefaultApplication}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 qe.TransactionSubTypes.assets.coin.send:o=ko.fromData(t.intentionData);break;case qe.TransactionSubTypes.assets.object.send:o=Do.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};var ml=require("@msafe/sui3-utils");var ol=!1,$e={ProtocolPackage:"0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function mi(){if(!ol)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&&($e.ProtocolPackage=t),e&&($e.borrowFee=e),n&&($e.borrowFeeAddress=n),o&&($e.pool=o),ol=!0}catch(a){console.error(a.message)}}var h=$e;var $t=require("@msafe/sui3-utils"),fi=require("@mysten/sui.js/bcs"),Tt=require("@mysten/sui.js/utils");var vo=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::borrow`)}isEntryMultiDepositTransaction(){let t=`${h.ProtocolPackage}::incentive_v2::entry_deposit`,e=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===t);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target===`${h.ProtocolPackage}::incentive_v2::claim_reward_non_entry`)?!1:e.length>1}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${h.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(h.pool).find(n=>n.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${h.ProtocolPackage}::incentive_v2::claim_reward`){let n=new Ke(e,this.txb),o=n.decodeInputU8(4),r=n.decodeInputU8(5),i=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(o),c=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:c,assetId:o,poolId:i})}}),console.log("decode claims",t),{txType:$t.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:$t.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryMultiDeposit(){let t=[],e=`${h.ProtocolPackage}::incentive_v2::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===e){let o=new Ke(n,this.txb),r=o.decodeInputU8(3),i=o.decodeInputU64(5),s=this.findPoolByAssetId(r);t.push({coinType:s.coinType,amount:i})}}),{txType:$t.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:t}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:$t.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:$t.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:$t.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(h.ProtocolPackage));return new Ke(t,this.txb)}},Ke=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(0,Tt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return a.getPureInputValue(n,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return fi.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,Tt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,Tt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,Tt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,Tt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return fi.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,Tt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var sl=require("@mysten/sui.js/transactions");function oe(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function al(a,t,e){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.Incentive),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function rl(a,t,e,n){let o=a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::borrow`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(h.IncentiveV2)],typeArguments:[t.type]}),[r]=a.moveCall({target:"0x02::coin::from_balance",typeArguments:[t.type],arguments:[o]});if(h.borrowFee>0){let[i]=a.splitCoins(r,[a.pure(Math.floor(e*h.borrowFee))]);a.transferObjects([r],a.pure(n)),a.transferObjects([i],a.pure(h.borrowFeeAddress))}else a.transferObjects([r],a.pure(n));return a}function bi(a,t,e,n){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(h.PriceOracle),a.object(h.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(n),a.object(h.IncentiveV2)],typeArguments:[t.type]}),a}function il(a,t,e,n,o){return a.moveCall({target:`${h.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(h.IncentiveV2),a.object(e),a.object(h.StorageId),a.pure(t),a.pure(n)],typeArguments:o}),a}var Ao=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new sl.TransactionBlock;return e.forEach(o=>{let{assetId:r,poolId:i,option:s,typeArguments:c}=o;il(n,r,i,s,c)}),n}static fromData(e){return new a(e)}};var cl=require("@mysten/sui.js/transactions");var Oo=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{coinType:n,amount:o}=this.data,r=new cl.TransactionBlock;console.log("build",this.data);let i=h.pool[n];if(!i)throw new Error(`${n} not support, please use ${Object.keys(h.pool).join(", ")}.`);return rl(r,i,o,e.account.address)}static fromData(e){return new a(e)}};var ll=require("@mysten/sui.js/transactions");async function ae(a,t,e){let n=await a.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,n),n}var Po=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new ll.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return oe(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await ae(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 oe(s,c,s.object(l),i)}static fromData(e){return new a(e)}};var dl=require("@mysten/sui.js/transactions");var Ro=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{coinType:r,amount:i}=this.data,s=new dl.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[u]=s.splitCoins(s.gas,[i]);return bi(s,h.pool.sui,u,i)}let c=h.pool[r];if(!c)throw new Error(`${r} not support, please use ${Object.keys(h.pool).join(", ")}.`);let d=await ae(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 bi(s,c,s.object(l),i)}static fromData(e){return new a(e)}};var ul=require("@mysten/sui.js/transactions");var _o=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,o=new ul.TransactionBlock;console.log("build",this.data);let r=h.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(h.pool).join(", ")}.`);return al(o,r,n)}static fromData(e){return new a(e)}};var pl=require("@mysten/sui.js/transactions");var Bo=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:o}=e,{list:r}=this.data,i=new pl.TransactionBlock;console.log("build",this.data);for(let s=0;s<r.length;s++){let{coinType:c,amount:d}=r[s];if(c==="sui"){let[m]=i.splitCoins(i.gas,[d]);oe(i,h.pool.sui,m,d);continue}let l=h.pool[c];if(!l)throw new Error(`${c} not support, please use ${Object.keys(h.pool).join(", ")}.`);let u=await ae(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[s].coinObjectId]),m++}oe(i,l,i.object(p),d)}return i}static fromData(e){return new a(e)}};var Mo=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(t){await mi();let{transactionBlock:e}=t,o=new vo(e).decode();return{txType:ml.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(await mi(),t.txSubType){case"EntryDeposit":o=Po.fromData(t.intentionData);break;case"EntryBorrow":o=Oo.fromData(t.intentionData);break;case"EntryRepay":o=Ro.fromData(t.intentionData);break;case"EntryWithdraw":o=_o.fromData(t.intentionData);break;case"EntryMultiDeposit":o=Bo.fromData(t.intentionData);break;case"ClaimReward":o=Ao.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};var Ve=require("@msafe/sui3-utils"),fl=require("@mysten/bcs"),bl=require("@mysten/sui/transactions"),gl=N(require("sort-keys-recursive")),hl="msafe-plain-tx",yl=Ve.TransactionSubTypes.others.plain,gi=class a{constructor(t){this.data=t}application=hl;txType=Ve.TransactionType.Other;txSubType=yl;serialize(){return JSON.stringify((0,gl.default)(this.data))}async build(t){return bl.Transaction.from((0,fl.fromHEX)(this.data.content))}static fromData(t){return new a(t)}},No=class{application;supportSDK="@mysten/sui";constructor(){this.application=hl}async deserialize(t){let{content:e}=t.appContext;return{txType:Ve.TransactionType.Other,txSubType:yl,intentionData:{content:e}}}async build(t){let{suiClient:e,network:n,account:o}=t;return gi.fromData(t.intentionData).build({suiClient:e,network:n,account:o})}};var Si=require("@mysten/sui/client"),Sl=require("@mysten/sui/transactions"),Wo=require("@mysten/sui.js/client"),Tl=require("@mysten/sui.js/transactions");var re=require("@open-rpc/client-js");var Rp={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},hi=class extends Error{},jo=class extends hi{code;type;constructor(t,e){super(t),this.code=e,this.type=Rp[e]??"ServerError"}};function _p(a){let t=new URL(a);return t.protocol=t.protocol.replace("http","ws"),t.toString()}var Bp={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Eo=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={...Bp,...e},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=_p(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 jo(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 yi(t);return this.#r.add(e),await e.subscribe(this),()=>e.unsubscribe(this)}},yi=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 wt=class{rpcClient;websocketClient;constructor({url:t,websocket:{url:e,...n}={},rpc:o}){let r=new re.HTTPTransport(o?.url??t,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new re.Client(new re.RequestManager([r])),this.websocketClient=new Eo(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 Lo=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 wi(t))}addHelper(t){this.apps.set(t.application,new Ti(t))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},Ti=class{constructor(t){this.helper=t}async deserialize(t){let e=new Si.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})}),n=new Wo.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})}),o=await t.transactionBlock.build({client:n}),r=Sl.Transaction.from(o);return this.helper.deserialize({...t,suiClient:e,transaction:r})}async build(t){let e=new Si.SuiClient({transport:new wt({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 Tl.TransactionBlock.from(r)}},wi=class{constructor(t){this.helper=t}async deserialize(t){let e=new Wo.SuiClient({transport:new wt({url:t.clientUrl,rpc:{url:t.clientUrl}})});return this.helper.deserialize({...t,transactionBlock:t.transactionBlock,suiClient:e})}async build(t){let e=new Wo.SuiClient({transport:new wt({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})}};var ld=require("@msafe/sui3-utils");var A=require("@msafe/sui3-utils");var Ct=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 wl="https://sui.apis.scallop.io";var Cl="675c65cd301dd817ea262e76",Uo="0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";var It="0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA",kt="0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",it=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd","deep","fud"],Fo=["weth","wbtc","wusdc","wusdt","sui","wapt","wsol","cetus","afsui","hasui","vsui","sca","usdc","fdusd"],Dt=["sweth","ssui","swusdc","swusdt","scetus","safsui","shasui","svsui","susdc"],st=["ssui","swusdc","swusdt","safsui","shasui","svsui","sweth","ssca","scetus","swbtc","swsol","susdc","sfdusd","sdeep","sfud"];var Il=["sui"],xt=["sui","wusdc","wusdt","afsui","hasui","vsui","weth","sca","wbtc","wsol","usdc","fdusd","deep","fud"];var kl={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 qo={sweth:"sui",ssui:"sui",swusdc:"sui",swusdt:"sui",scetus:"sui",safsui:"sui",shasui:"sui",svsui:"sui",susdc:"sui"},Dl={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"]},xl={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"},K={weth:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",wbtc:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881",wusdc:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf",wusdt:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c",wapt:"0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37",wsol:"0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8"},Ci={vsui:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"},vl={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"};var Ii=require("@mysten/sui.js/bcs"),vt=require("@mysten/sui.js/utils"),T=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,vt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return 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 Ii.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,vt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,vt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,vt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,vt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ii.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,vt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Al=require("@mysten/sui.js/bcs");var _=class{constructor(t,e){this.splitCoin=t;this.txb=e}getAmountInput(){return this.splitCoin.amounts.map(t=>{if(t.kind==="Input")return Number(T.getPureInputValue(t,"u64"))}).filter(t=>t!==void 0)}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let n=t.value.Pure;return Al.bcs.de(e,new Uint8Array(n))}return t.value}};var $o=class extends Ct{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(`${kt}::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 T(e,this.txb))}get helperClaimBorrowV2Reward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(e=>new T(e,this.txb))}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new T(t,this.txb)}get helperClaimBorrowReward(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${kt}::user::redeem_rewards`)).map(e=>new T(e,this.txb))}get helperMint(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`));return new T(t,this.txb)}get helperUnstakes(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`)).map(e=>new T(e,this.txb))}get helperRedeems(){return this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`)).map(e=>new T(e,this.txb))}get helperRedeem(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`));return new T(t,this.txb)}get helperBurnScoin(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new T(t,this.txb)}get helperSlippage(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage"));return new T(t,this.txb)}get helperStake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::stake`));return new T(t,this.txb)}get helperUnstake(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`));return new T(t,this.txb)}get helperDepositCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new T(t,this.txb)}get helperWithdrawCollateral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new T(t,this.txb)}get helperBorrow(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`));return new T(t,this.txb)}get helperBorrowWithReferral(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new T(t,this.txb)}get helperRepay(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`));return new T(t,this.txb)}decodeMigrateScoin(){return{txType:A.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let e=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),o=this.scallop.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:A.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:e,obligationId:n,rewardCoinName:o,veScaKey:t}}}decodeOpenObligation(){return{txType:A.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),e=this.helperMint.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:A.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLending(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperRedeem.getNestedInputParam(2),n=new _(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeWithdrawLendingScoin(){let t=this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),e=this.helperBurnScoin.getNestedInputParam(1),n=new _(e,this.txb).getAmountInput().reduce((o,r)=>o+r,0);return{txType:A.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:t}}}decodeDepositCollateral(){let t=this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),e=this.helperDepositCollateral.getNestedInputParam(3),n=new _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:A.TransactionType.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:A.TransactionType.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:A.TransactionType.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:A.TransactionType.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:A.TransactionType.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 _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.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 _(n,this.txb).getAmountInput().reduce((i,s)=>i+s,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:A.TransactionType.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,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}if(this.helperStake.moveCall&&e===0){let r=this.helperStake.getNestedInputParam(2);e=new _(r,this.txb).getAmountInput().reduce((i,s)=>i+s,0)}let n=this.helperStake.typeArg(0),o=this.scallop.utils.parseCoinNameFromType(n);return{txType:A.TransactionType.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:A.TransactionType.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 _(e,this.txb).getAmountInput().reduce((r,i)=>r+i,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:A.TransactionType.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 _(o,this.txb).getAmountInput().reduce((r,i)=>r+i,0)}return{txType:A.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:t}}}decodeMoveAsset(){let t=[];this.helperUnstakes.forEach(i=>{let s=i.decodeOwnedObjectId(1),c=i.decodeInputU64(2);t.push({id:s,coin:c})});let e=this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);n=new _(i,this.txb).getAmountInput().reduce((s,c)=>s+c,0)}let o=this.helperSlippage.decodePureArg(1,"u64"),r=this.helperSlippage.decodePureArg(2,"string");return{txType:A.TransactionType.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:A.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:t,borrowIncentiveV2:e,borrowIncentive:n}}}};var Ko=require("@msafe/sui3-utils");var Vo=class extends Ct{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 T(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 T(t,this.txb)}decodeCreateReferralLink(){return{txType:Ko.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let t=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),e=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Ko.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:t,coins:e}}}decodeBindReferral(){let t=this.helperBindReferral.decodePureArg(1,"address");return{txType:Ko.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:t}}}};var ie=require("@msafe/sui3-utils");var Qo=class extends Ct{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 T(t,this.txb)}get helperStakeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new T(t,this.txb)}get helperExtendStakePeriod(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new T(t,this.txb)}get helperRedeemSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new T(t,this.txb)}get helperRenewExpired(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new T(t,this.txb)}get helperOldUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${kt}::user::unstake`));return new T(t,this.txb)}get helperUnstakeObligation(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`));return new T(t,this.txb)}get helperStakeObligationWithVeSca(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`));return new T(t,this.txb)}decodeRedeemSca(){let t=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:ie.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:t}}}decodeRenewExpiredVeSca(){let t=this.helperRenewExpired.getNestedInputParam(4),e=this.helperRenewExpired.decodeInputU64(5),n=new _(t,this.txb).getAmountInput().reduce((b,S)=>b+S,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:ie.TransactionType.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:ie.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{lockPeriodInDays:t,obligationId:c,obligationKey:d,veScaKey:e,isObligationLocked:i,isOldBorrowIncentive:s}}}decodePeriodAndStakeMoreSca(){let t=this.helperStakeMoreSca.getNestedInputParam(4),e=this.helperExtendStakePeriod.decodeInputU64(4),n=new _(t,this.txb).getAmountInput().reduce((m,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:ie.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:i,lockPeriodInDays:e,obligationId:l,obligationKey:u,isOldBorrowIncentive:d,isObligationLocked:c}}}decodeStakeSca(){let t,e;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(t=this.helperStakeSca.getNestedInputParam(3),e=this.helperStakeSca.decodeInputU64(4)):t=this.helperStakeMoreSca.getNestedInputParam(4);let n=new _(t,this.txb).getAmountInput().reduce((m,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:ie.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,lockPeriodInDays:e,obligationId:l,obligationKey:u,veScaKey:i,isObligationLocked:c,isOldBorrowIncentive:d}}}};var Ol=N(require("sort-keys-recursive")),g=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Ol.default)(this.data))}};var Ho=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 Go=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 zo=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 Jo=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 Yo=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 Zo=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 ta=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 ea=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 na=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 oa=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 aa=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 ra=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 ia=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 sa=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 ca=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 la=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 da=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 ua=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 pa=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 ma=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 fa=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 ba=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 ga=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 ha=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 ya=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 Sa=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 Ta=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(`${wl}/addresses/${this.id}`,t);if(e.status===200){let n=await e.json();if("mainnet"in n){this.addresses=n.mainnet;return}throw new Error("Mainnet key is not in address!")}throw new Error(`Failed to fetch address with id ${this.id}`)}};var I=require("@mysten/sui.js/transactions"),Mi=N(require("bignumber.js"));var Pl=require("@mysten/sui.js/transactions"),wa=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 Pl.TransactionBlock(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}}};var Rl=require("@mysten/sui.js/transactions"),Qe=N(require("bignumber.js"));var se=async(a,t)=>{let e=t,n=a.address.get("core.object")||Uo,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),S=await Di(a,b);d.push({id:b,keyId:u,locked:S})}}return d},Di=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},_l=async(a,t,e)=>{let n=e||[...it],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]=(0,Qe.default)(c[m]??0).plus(p.balance).toNumber())}}),c},Bl=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=(0,Qe.default)(c).plus(u.balance).toNumber()}}),c},Ml=async(a,t,e)=>{let n=e||[...it].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]=(0,Qe.default)(c[m]??0).plus(p.balance).toNumber())}}),c},Nl=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=(0,Qe.default)(c).plus(u.balance).toNumber()}}),c},jl=async(a,t)=>{let n=`${a.address.get("core.packages.query.id")}::obligation_query::obligation_data`,o=new Rl.TransactionBlock;return o.moveCall({target:n,arguments:[o.object(t)]}),(await a.client.devInspectTransactionBlock({transactionBlock:o,sender:a.params.walletAddress})).events[0].parsedJson};var w=require("@mysten/sui.js/utils"),He=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),S=a.utils.parseMarketCoinType(b),C={...p},x=`${n}::spool_account::SpoolAccount<${S}>`;return C[m]=x,C},{}),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 S=p.data.content.fields,C=String(S.spool_id),x=String(S.stake_type.fields.name),q=Number(S.stakes),B=Number(S.index),Q=Number(S.points),$=Number(S.total_points);(0,w.normalizeStructTag)(b)===d.sweth?c.sweth.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.ssui?c.ssui.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.swusdc?c.swusdc.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.swusdt?c.swusdt.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.scetus?c.scetus.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.safsui?c.safsui.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.shasui?c.shasui.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.svsui?c.svsui.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$}):(0,w.normalizeStructTag)(b)===d.susdc&&c.susdc.push({id:m,type:(0,w.normalizeStructTag)(b),stakePoolId:C,stakeType:(0,w.normalizeStructTag)(x),staked:q,index:B,points:Q,totalPoints:$})}}),c},xi=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),S=Number(c.stakes),C=Number(c.index),x=Number(c.created_at),q=Number(c.last_update);n={id:i,type:(0,w.normalizeStructTag)(s),maxPoint:d,distributedPoint:l,pointPerPeriod:u,period:p,maxStake:m,stakeType:(0,w.normalizeStructTag)(b),totalStaked:S,index:C,createdAt:x,lastUpdate:q}}}return n},vi=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:(0,w.normalizeStructTag)(s),stakePoolId:d,ratioNumerator:l,ratioDenominator:u,rewards:p,claimedRewards:m}}}return n};var Vl=require("@mysten/sui.js/transactions"),jp=require("@mysten/sui.js/utils"),Ep=N(require("bignumber.js"));var E=a=>{let{sender:t}=a.blockData;if(!t)throw new Error("Sender is required");return t},Ll=(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(ce(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)`)}},Ul=(a,t,e)=>{if(ce(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)`)},Fl=(a,t)=>{if(ce(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")},ql=(a,t,e)=>{if(ce(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)`)},ce=a=>{if(a===void 0)throw new Error("veSca not found")};var Ge=require("@mysten/sui.js/utils"),Mp=N(require("bignumber.js"));var Np=a=>({pointType:(0,Ge.normalizeStructTag)(a.point_type.name),weightedAmount:Number(a.weighted_amount),points:Number(a.points),totalPoints:Number(a.total_points),index:Number(a.index)}),$l=a=>({poolType:(0,Ge.normalizeStructTag)(a.pool_type.name),debtAmount:Number(a.debt_amount),pointList:a.points_list.reduce((t,e)=>{let n=Np(e),o=(0,Ge.parseStructTag)(n.pointType).name.toLowerCase();return t[o]=n,t},{})});var Ia=a=>{let t=a.slice(1).toLowerCase();return a.charAt(0).toLowerCase()==="s"&&[...new Set([...it,...Fo,...Il])].includes(t)},Ai=a=>{switch(a){case"afsui":return"afSUI";case"hasui":return"haSUI";case"vsui":return"vSUI";default:return a.toUpperCase()}},Kl=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 Ql=async(a,t,e,n)=>{let o=n||[...xt],r=a.address.get("borrowIncentive.query"),i=a.address.get("borrowIncentive.incentiveAccounts"),s=`${r}::incentive_account_query::incentive_account_data`,c=new Vl.TransactionBlock;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=$l(p),{poolType:b}=m,S=a.utils.parseCoinNameFromType(b);o.length>=1&&o.includes(S)&&(u[S]=m)},{}),u};var Hl=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 Gl=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};var ka=N(require("bignumber.js")),zl=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)},Jl=async(a,t)=>{let n=(await zl(a,t)).map(r=>r.objectId),o=[];for(let r=0;r<n.length;r++){let i=await Oi(a,n[r]);i&&o.push(i)}return o},Oi=async(a,t,e)=>{let n=a.address.get("vesca.tableId"),o=t||(await zl(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:(0,ka.default)(c.locked_sca_amount).toNumber(),lockedScaCoin:(0,ka.default)(c.locked_sca_amount).shiftedBy(-9).toNumber(),unlockAt:(0,ka.default)(c.unlock_at).toNumber()}}return r};var Da=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 se(this,t)}async getCoinAmounts(t,e){return _l(this,t,e)}async getCoinAmount(t,e=this.params.walletAddress){return Bl(this,t,e)}async getMarketCoinAmounts(t,e){return Ml(this,t,e)}async getMarketCoinAmount(t,e=this.params.walletAddress){return Nl(this,t,e)}async getPriceFromPyth(t){return Gl(this,t)}async getAllStakeAccounts(t=this.params.walletAddress){return He(this,t)}async getStakeAccounts(t,e=this.params.walletAddress){return(await this.getAllStakeAccounts(e))[t]??[]}async getStakePools(t=[...Dt]){let e={};for(let n=0;n<t.length;n++){let o=t[n],r=await xi(this,o);r&&(e[o]=r)}return e}async getStakePool(t){return xi(this,t)}async getStakeRewardPools(t=[...Dt]){let e={};for(let n=0;n<t.length;n++){let o=await vi(this,t[n]);o&&(e[t[n]]=o)}return e}async getStakeRewardPool(t){return vi(this,t)}async getBorrowIncentiveAccounts(t,e=this.params.walletAddress,n){return Ql(this,t,e,n)}async getObligationCoinNames(t){let e=await jl(this,t),n=e.collaterals.map(s=>`0x${s.type.name}`),o=e.debts.map(s=>`0x${s.type.name}`);return[...new Set([...n,...o])].map(s=>this.utils.parseCoinNameFromType(s))}};var le=require("@mysten/sui.js/utils");var xa=class{params;isTestnet;_address;client;constructor(t,e){this.params=t,this.client=t.client,this._address=e}parseSymbol(t){if(Ia(t)){let e=t.slice(1).toLowerCase();return t.slice(0,1).toLowerCase()+Ai(e)}return Ai(t)}parseCoinType(t){let e=Ia(t)?this.parseCoinName(t):t,n=xl[e];return[K.wusdc,K.wusdt,K.weth,K.wbtc,K.wsol,K.wapt].includes(n)?`${n}::coin::COIN`:t==="vsui"?`${Ci.vsui}::cert::CERT`:`${n}::${e}::${e.toUpperCase()}`}parseMarketCoinType(t){let e=this._address.get("core.object")||Uo,n=this.parseCoinType(t);return`${e}::reserve::MarketCoin<${n}>`}parseCoinNameFromType(t){let e=(0,le.normalizeStructTag)(t),n=/((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/,o=t.match(n),r=t.includes("reserve::MarketCoin");e=o?.[1]||t;let i={[`${K.wusdc}::coin::COIN`]:"wusdc",[`${K.wusdt}::coin::COIN`]:"wusdt",[`${K.weth}::coin::COIN`]:"weth",[`${K.wbtc}::coin::COIN`]:"wbtc",[`${K.wsol}::coin::COIN`]:"wsol",[`${K.wapt}::coin::COIN`]:"wapt"},s={[`${Ci.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=>qo[t];getBorrowIncentiveRewardCoinName=t=>Dl[t];getCoinDecimal(t){return kl[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 vl[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=le.SUI_TYPE_ARG,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=le.SUI_TYPE_ARG,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=le.SUI_TYPE_ARG,n){return(await this.selectCoins(t,e,n)).map(r=>r.objectId)}parseAprToApy(t,e=365){return(1+t/e)**e-1}parseApyToApr(t,e=365){return((1+t)**(1/e)-1)*e}takeAmountFromCoins(t,e,n){let 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 Kl(r)}parseSCoinName(t){if(Ia(t)&&st.includes(t))return t;let e=`s${t}`;if(st.includes(e))return e}};var lt=require("@mysten/sui.js/utils");var de=async(...a)=>{let[t,e,n]=a;if(a.length===3&&n&&typeof n=="string"){let i=await Oi(t.query,n);return i||void 0}let o=E(e),r=await Jl(t.query,o);if(r.length!==0)return r[0]};var Pi=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&n&&o&&typeof n=="string"){let c=await Di(t.query,n);return{obligationId:n,obligationKey:o,obligationLocked:c}}let r=E(e),i=await se(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}},Wp=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(lt.SUI_CLOCK_OBJECT_ID)]})},stakeObligationWithVesca:(r,i,s)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::stake_with_ve_sca`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(e.obligationAccessStore),t.object(o.config),t.object(o.treasury),t.object(o.table),t.object(s),t.object(lt.SUI_CLOCK_OBJECT_ID)]})},unstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(e.config),t.object(e.incentivePools),t.object(e.incentiveAccounts),t.object(i),t.object(r),t.object(lt.SUI_CLOCK_OBJECT_ID)]})},oldUnstakeObligation:(r,i)=>{t.moveCall({target:`${e.borrowIncentivePkg}::user::unstake`,arguments:[t.object(n.incentivePools),t.object(n.incentiveAccounts),t.object(i),t.object(r),t.object(lt.SUI_CLOCK_OBJECT_ID)],typeArguments:[lt.SUI_TYPE_ARG]})},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(lt.SUI_CLOCK_OBJECT_ID)],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(lt.SUI_CLOCK_OBJECT_ID)],typeArguments:[c]})}}},W=async({builder:a,txBlock:t})=>{let e=await Wp({builder:a,txBlock:t});return{normalMethod:e,stakeObligationQuick:async(n,o)=>{let{obligationId:r,obligationKey:i,obligationLocked:s}=await Pi(a,t,n,o),c=!!t.blockData.transactions.find(d=>d.kind==="MoveCall"&&(d.target===`${kt}::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 Pi(a,t,n,o);s&&e.unstakeObligation(r,i)},stakeObligationWithVeScaQuick:async(n,o,r)=>{let{obligationId:i,obligationKey:s,obligationLocked:c}=await Pi(a,t,n,o),d=!!t.blockData.transactions.find(async l=>l.kind==="MoveCall"&&(l.target===`${kt}::user::unstake`||l.target===`${a.address.get("borrowIncentive.id")}::user::unstake`));if(!c||d){let l=await Hl({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)}};var et=require("@mysten/sui.js/utils");var Je=require("@mysten/sui.js/utils"),Xl=N(require("axios"));var Yl={testnet:["https://hermes-beta.pyth.network"],mainnet:["https://hermes.pyth.network","https://scallop.rpc.p2p.world"]};var va=require("@mysten/sui.js/bcs"),ze=require("@mysten/sui.js/utils"),Ri=16*1024,Aa=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(va.bcs.ser("vector<u8>",Array.from(r),{maxSize:Ri}).toBytes()),e.object(ze.SUI_CLOCK_OBJECT_ID)]});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(va.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:Ri}).toBytes()),s[0],t.object(ze.SUI_CLOCK_OBJECT_ID)]});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(ze.SUI_CLOCK_OBJECT_ID)]}),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(va.bcs.ser("vector<u8>",Array.from(e[0]),{maxSize:Ri}).toBytes()),r[0],t.object(ze.SUI_CLOCK_OBJECT_ID)]})}async getWormholePackageId(){return this.wormholePackageId||(this.wormholePackageId=await this.getPackageId(this.wormholeStateId)),this.wormholePackageId}async getPythPackageId(){return this.pythPackageId||(this.pythPackageId=await this.getPackageId(this.pythStateId)),this.pythPackageId}async getPriceFeedObjectId(t){let e=t.replace("0x","");if(!this.priceFeedObjectIdCache.has(e)){let{id:n,fieldType: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 Lp=async(a,t)=>(await Xl.default.get(`${a}/api/latest_vaas`,{params:{ids:t}})).data.map(o=>Buffer.from(o,"base64")),Ye=async(a,t,e)=>{let n=e??[...new Set([...it,...Fo])],o=a.isTestnet?["pyth"]:["pyth"];if(o.includes("pyth")){let i=new Aa(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??Yl[a.isTestnet?"testnet":"mainnet"];try{let d=await Lp(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 Up(a,t,r[i],o)},Up=async(a,t,e,n)=>{let o=a.utils.parseCoinType(e);Fp(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)},Fp=(a,t,e,n,o,r,i,s,c,d,l,u,p,m,b)=>{let S=qp(a,e,n,b);return t.includes("pyth")&&Qp(a,o,S,i,s,r,b),t.includes("switchboard")&&Vp(a,c,S,l,d,b),t.includes("supra")&&Kp(a,u,S,m,p,b),$p(a,e,n,S,b),a},qp=(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})},$p=(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(Je.SUI_CLOCK_OBJECT_ID)],typeArguments:i}),a},Kp=(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(Je.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},Vp=(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(Je.SUI_CLOCK_OBJECT_ID)],typeArguments:[r]})},Qp=(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(Je.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})};var Ot=async({builder:a,txBlock:t})=>{let e={pkgId:a.address.get("scoin.id")},n={};return await Promise.all(st.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 Xe=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=E(t),i=await se(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}},Hp=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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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(et.SUI_CLOCK_OBJECT_ID)],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]})}}},U=async({builder:a,txBlock:t})=>{let e=await Hp({builder:a,txBlock:t}),n=await Ot({builder:a,txBlock:t});return{normalMethod:e,addCollateralQuick:async(o,r,i)=>{let s=E(t),{obligationId:c}=await Xe(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 Xe(t,a,i,s),d=await a.query.getObligationCoinNames(c.obligationId);return await Ye(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=E(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:S,takeCoin:C}=await a.selectMarketCoin(t,s,b,i);t.transferObjects([S],i),t.mergeCoins(m,[e.withdraw(C,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 Xe(t,a,i,s),l=[...await a.query.getObligationCoinNames(c.obligationId),r];return await Ye(a,t,l),e.borrow(c.obligationId,c.obligationKey,o,r)},borrowWithReferralQuick:async(o,r,i,s,c)=>{let d=await Xe(t,a,s,c),u=[...await a.query.getObligationCoinNames(d.obligationId),r];return await Ye(a,t,u),e.borrowWithReferral(d.obligationId,d.obligationKey,i,o,r)},repayQuick:async(o,r,i,s)=>{let c=await Xe(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=>Ye(a,t,o)}};var Ze=require("@mysten/sui.js/utils");var Oa=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(Ze.SUI_CLOCK_OBJECT_ID)],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(Ze.SUI_CLOCK_OBJECT_ID)],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(Ze.SUI_CLOCK_OBJECT_ID)],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(Ze.SUI_CLOCK_OBJECT_ID)],typeArguments:[i]})}}},Zl=async({builder:a,txBlock:t})=>{let e=await Oa({builder:a,txBlock:t});return{claimReferralRevenueQuick:async(n,o,r=[...it])=>{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 Gp={packageId:"0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603"},td={check_slippage:(a,t,e,n,o)=>a.moveCall({target:`${Gp.packageId}::slippage_check::check_slippage`,arguments:[t,a.pure(e),a.pure(n)],typeArguments:[o]})};var tn=require("@mysten/sui.js/utils");var ed=async(a,t,e,n,o,r,i=!1)=>{let s=await Ot({builder:a,txBlock:t}),c=await od({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}},nd=async(...a)=>{let[t,e,n,o]=a;if(a.length===4&&o)return[o];let r=E(e);return(await He(t.query,r))[n].map(s=>s.id)},zp=async(...a)=>{let[t,e,n,o]=a,r=E(e),i=await He(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]},od=async({builder:a,txBlock:t})=>{let e={spoolPkg:a.address.get("spool.id")},n={},o={},r={};return Dt.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(tn.SUI_CLOCK_OBJECT_ID)],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(tn.SUI_CLOCK_OBJECT_ID)],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(tn.SUI_CLOCK_OBJECT_ID)],typeArguments:[d]})},claim:(i,s)=>{let c=n[s],d=o[s],l=r[s],u=qo[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(tn.SUI_CLOCK_OBJECT_ID)],typeArguments:[l,p]})}}},dt=async({builder:a,txBlock:t})=>{let e=await od({builder:a,txBlock:t}),n=await Ot({builder:a,txBlock:t});return{normalMethod:e,stakeQuick:async(o,r,i)=>{let s=E(t),c=await nd(a,t,r,i),d=[];if(c.length===0){let l=e.createStakeAccount(r);d.push(l)}if(typeof o=="number"){let l=await ed(a,t,c.length>0?c[0]:d[0],r,o,s);o-=l,l||await ed(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 zp(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 nd(a,t,o,r),s=[];return i.forEach(c=>{let d=e.claim(c,o);s.push(d)}),s}}};var ue=require("@mysten/sui.js/utils");var Jp=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(ue.SUI_CLOCK_OBJECT_ID)]}),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(ue.SUI_CLOCK_OBJECT_ID)]})},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(ue.SUI_CLOCK_OBJECT_ID)]})},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(ue.SUI_CLOCK_OBJECT_ID)]})},redeemSca:n=>t.moveCall({target:`${e.pkgId}::ve_sca::redeem`,arguments:[t.object(e.config),t.object(n),t.object(e.table),t.object(e.treasury),t.object(ue.SUI_CLOCK_OBJECT_ID)]}),mintEmptyVeSca:()=>t.moveCall({target:`${e.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,arguments:[t.object(e.config),t.object(e.table)],typeArguments:[]})}},Pt=async({builder:a,txBlock:t})=>{let e=await Jp({builder:a,txBlock:t});return{normalMethod:e,lockScaQuick:async(n,o,r=!0)=>{let i=E(t),s=await de(a,t),c,d=[];if(n!==void 0&&typeof n=="number"){let m=await a.utils.selectCoinIds(n,It,i),[b,S]=a.utils.takeAmountFromCoins(t,m,n);c=b,d.push(S)}else c=n;let l=a.utils.getUnlockAt(o,s?.unlockAt);r&&Ll(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 de(a,t,o),s=a.utils.getUnlockAt(n);r&&Ul(n,s,i?.unlockAt),i&&e.extendLockPeriod(i.keyId,s)},extendLockAmountQuick:async(n,o,r=!0)=>{let i=E(t),s=await de(a,t,o);if(r&&Fl(n,s?.unlockAt),s){let c=await a.utils.selectCoinIds(n,It,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=E(t),c=await de(a,t,r),d=a.utils.getUnlockAt(o,c?.unlockAt);if(i&&ql(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,It,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=E(t),r=await de(a,t,n);if(ce(r?.unlockAt),r){let i=e.redeemSca(r.keyId);t.transferObjects([i],o)}}}};var cd=require("@mysten/sui.js/utils");var sd=require("@mysten/sui.js/utils");var pe={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}}},ad={id:"0x000000000000000000000000000000000000000000000000000000000000dee9"},_i={id:"0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3"},rd={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 id={objectId:sd.SUI_CLOCK_OBJECT_ID,initialSharedVersion:"1",mutable:!1},Yp=(a,t)=>{if(a==="sui")switch(t){case"wusdc":return{pool:pe.pools.sui2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdc")switch(t){case"sui":return{pool:pe.pools.sui2usdc,aToB:!1};case"wusdt":return{pool:pe.pools.usdt2usdc,aToB:!1};case"usdc":return{pool:pe.pools.wusdc2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else if(a==="wusdt")switch(t){case"wusdc":return{pool:pe.pools.usdt2usdc,aToB:!0};default:throw new Error(`Invalid coin pair: ${a} and ${t}`)}else throw new Error(`Invalid coin pair: ${a} and ${t}`)},Bi={createAccount:a=>a.moveCall({target:`${ad.id}::${rd.clob_v2.create_account}`,arguments:[],typeArguments:[]}),swap:(a,t,e,n,o,r,i)=>{let{pool:s,aToB:c}=Yp(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:`${_i.id}::deepbook::deepbook_base_for_quote`,arguments:[a.sharedObjectRef(s.object),a.pure(o),u,a.object(t),a.sharedObjectRef(id),a.pure(s.lotsize)],typeArguments:[d,l]}):a.moveCall({target:`${_i.id}::deepbook::deepbook_quote_for_base`,arguments:[a.sharedObjectRef(s.object),a.pure(o),u,a.sharedObjectRef(id),a.object(t),a.pure(s.lotsize)],typeArguments:[l,d]})}};var Pa=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:(0,cd.normalizeStructTag)("0xdee9::custodian_v2::AccountCap")},limit:1});return e.length===0||!e[0].data?Bi.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:Bi.swap(o,t,e,n,this.clientOrderId,r,this.scallopUtils),accountCap:r}}};var Ra=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 xa(t,this.address),this.query=new Da(t,{address:this.address,utils:this.utils}),this.builder=new wa(t,{address:this.address,query:this.query,utils:this.utils}),this.deepbookSwap=new Pa({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 I.TransactionBlock,n=await U({builder:this.builder,txBlock:e}),o=await W({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 I.TransactionBlock,i=o||this.params.walletAddress;r.setSender(i);let s=await U({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 I.TransactionBlock,s=await U({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 I.TransactionBlock,r=await U({builder:this.builder,txBlock:o}),i=await Ot({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(!st.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 I.TransactionBlock,r=n||this.params.walletAddress,i=await U({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 I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=xt.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 I.TransactionBlock,c=await U({builder:this.builder,txBlock:s}),d=await W({builder:this.builder,txBlock:s}),l=i||this.params.walletAddress;s.setSender(l);let u=xt.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 I.TransactionBlock,c=await U({builder:this.builder,txBlock:s}),d=await W({builder:this.builder,txBlock:s}),l=await Oa({builder:this.builder,txBlock:s}),u=i||this.params.walletAddress;s.setSender(u);let p=xt.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 I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=xt.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 I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await W({builder:this.builder,txBlock:i}),d=r||this.params.walletAddress;i.setSender(d);let l=xt.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 I.TransactionBlock,o=await dt({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 I.TransactionBlock,i=await U({builder:this.builder,txBlock:r}),s=await dt({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(!Dt.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 I.TransactionBlock,r=await U({builder:this.builder,txBlock:o}),i=await dt({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 I.TransactionBlock,i=await dt({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 I.TransactionBlock,i=await dt({builder:this.builder,txBlock:r}),s=o||this.params.walletAddress;r.setSender(s);let c=st.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 I.TransactionBlock,i=await dt({builder:this.builder,txBlock:r}),s=await W({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 W({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 W({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 I.TransactionBlock,l=await Pt({builder:this.builder,txBlock:d}),u=await W({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,It,p),[b,S]=this.builder.utils.takeAmountFromCoins(d,m,t),C;return s?l.normalMethod.extendLockAmount(s,b):C=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||C)),s||d.transferObjects([C,S],p),d}async stakeMoreSca(t,e,n){let o=new I.TransactionBlock,r=n||this.params.walletAddress;return o.setSender(r),o}async extendStakeScaLockPeriod(t,e,n,o,r=!1,i=!1,s){let c=new I.TransactionBlock,d=await Pt({builder:this.builder,txBlock:c}),l=await W({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 I.TransactionBlock,l=await Pt({builder:this.builder,txBlock:d}),u=await W({builder:this.builder,txBlock:d}),p=c||this.params.walletAddress;d.setSender(p);let m=await this.builder.utils.selectCoinIds(t,It,p),[b,S]=this.builder.utils.takeAmountFromCoins(d,m,t);return l.normalMethod.extendLockPeriod(e,n),l.normalMethod.extendLockAmount(e,b),d.transferObjects([S],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 I.TransactionBlock,u=await Pt({builder:this.builder,txBlock:l}),p=await W({builder:this.builder,txBlock:l}),m=d||this.params.walletAddress;if(l.setSender(m),o){let x=u.normalMethod.redeemSca(n);l.transferObjects([x],m)}let b=await this.builder.utils.selectCoinIds(t,It,m),[S,C]=this.builder.utils.takeAmountFromCoins(l,b,t);return l.transferObjects([C],m),u.normalMethod.renewExpiredVeSca(n,S,e),!r||!i||(s&&(c?p.normalMethod.oldUnstakeObligation(r,i):p.normalMethod.unstakeObligation(r,i)),p.normalMethod.stakeObligationWithVesca(r,i,n)),l}async redeemSca(t){let e=new I.TransactionBlock,n=await Pt({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 I.TransactionBlock,i=await W({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 I.TransactionBlock,o=await Pt({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 Mi.default(t.weightedAmount),r=e.currentPointIndex?(0,Mi.default)(e.currentPointIndex-t.index).dividedBy(1e9):1;return n.multipliedBy(r).plus(t.points).shiftedBy(-1*e.coinDecimal)}async createReferralLink(){let t=new I.TransactionBlock,e=await Pt({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 I.TransactionBlock,o=await Zl({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 I.TransactionBlock,n=await Oa({builder:this.builder,txBlock:e}),o=this.params.walletAddress;return e.setSender(o),n.bindToReferral(t),e}async migrateAllMarketCoin(){let t=new I.TransactionBlock,e=await Ot({builder:this.builder,txBlock:t}),n=await dt({builder:this.builder,txBlock:t});t.setSender(this.params.walletAddress);let o=[];return await Promise.all(st.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(Dt.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 I.TransactionBlock,s=await U({builder:this.builder,txBlock:i}),c=await dt({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(B=>B.objectId);i.setSender(d);for(let B=0;B<r.length;B++){let Q=r[B],[$]=await c.unstakeQuick(Q.coin,u,Q.id);if($){b.length>0&&i.mergeCoins($,b);let Mu=s.normalMethod.withdraw($,t);l.push(Mu)}}if(e>0){let B=await s.withdrawQuick(e,t);l.push(B)}l.length>1&&i.mergeCoins(l[0],l.slice(1));let[S]=i.splitCoins(l[0],[i.pure(o)]);i.transferObjects([l[0]],d);let{swapResult:C,accountCap:x}=await this.deepbookSwap.swapToken({baseCoinName:"wusdc",quoteCoinName:"usdc",tokenObjectIn:S,tx:i});typeof x=="string"&&i.transferObjects([x],d),td.check_slippage(i,C,n,o,this.query.utils.parseCoinType("usdc"));let q=s.normalMethod.deposit(C,"usdc");return await c.stakeQuick(q,"susdc"),i}};var en=class{params;client;builder;query;utils;address;constructor(t){this.params=t,this.address=t.address}async init(){this.address||(this.address=new Ta({id:Cl})),await this.address.read(),this.client=new Ra(this.params,this.address);let{builder:t,query:e,utils:n}=this.client;this.builder=t,this.query=e,this.utils=n}};var _a=class{application="scallop";supportSDK="@mysten/sui.js";scallop;async deserialize(t){this.scallop||(this.scallop=new en({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let{transactionBlock:e}=t;console.log("transactionBlock",e);let n=new $o(e,this.scallop),o=new Vo(e,this.scallop),r=new Qo(e,this.scallop),i=n.decode()||o.decode()||r.decode();if(!i)throw new Error("Unknown transaction type");return{txType:ld.TransactionType.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 en({client:t.suiClient,walletAddress:t.account.address}),await this.scallop.init());let s;switch(r){case"SupplyLending":s=ra.fromData(i);break;case"WithdrawLending":s=la.fromData(i);break;case"Borrow":s=Ho.fromData(i);break;case"Repay":s=na.fromData(i);break;case"DepositCollateral":s=Yo.fromData(i);break;case"WithdrawCollateral":s=ca.fromData(i);break;case"OpenObligation":s=ea.fromData(i);break;case"StakeSpool":s=aa.fromData(i);break;case"UnstakeSpool":s=ia.fromData(i);break;case"ClaimIncentiveReward":s=Jo.fromData(i);break;case"BorrowWithBoost":s=Go.fromData(i);break;case"StakeSca":s=ha.fromData(i);break;case"ExtendStakePeriod":s=fa.fromData(i);break;case"ExtendPeriodAndStakeMore":s=ma.fromData(i);break;case"RenewExpStakePeriod":s=ga.fromData(i);break;case"WithdrawStakedSca":s=Sa.fromData(i);break;case"SupplyAndStakeLending":s=ya.fromData(i);break;case"WithdrawAndUnstakeLending":s=sa.fromData(i);break;case"RedeemSca":s=ba.fromData(i);break;case"MigrateAndClaim":s=Xo.fromData(i);break;case"BorrowWithReferral":s=zo.fromData(i);break;case"CreateReferralLink":s=pa.fromData(i);break;case"ClaimRevenueReferral":s=ua.fromData(i);break;case"BindReferral":s=da.fromData(i);break;case"MigrateScoin":s=Zo.fromData(i);break;case"RepayWithBoost":s=oa.fromData(i);break;case"MigrateWusdcToUsdc":s=ta.fromData(i);break;default:throw new Error("not implemented")}return s.build({suiClient:e,account:n,network:o,scallop:this.scallop})}};var jd=require("@msafe/sui3-utils");var dd="https://suilend-assets.s3.us-east-2.amazonaws.com/springsui";var me=require("@msafe/sui3-utils"),Rt=require("@mysten/sui/utils");var Ba=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=(0,Rt.normalizeStructTag)(t.MintEvent.parsedJson.event.typename.name),n=t.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:me.TransactionType.Other,type:"stake",intentionData:{amount:n,outCoinType:e}}}decodeStakeAndDeposit(){let t={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},e=(0,Rt.normalizeStructTag)(t.MintEvent.parsedJson.event.typename.name),n=t.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:me.TransactionType.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=(0,Rt.normalizeStructTag)(t.RedeemEvent.parsedJson.event.typename.name),n=(0,Rt.normalizeStructTag)(t.MintEvent.parsedJson.event.typename.name),o=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:me.TransactionType.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=(0,Rt.normalizeStructTag)(t.RedeemEvent.parsedJson.event.typename.name),n=(0,Rt.normalizeStructTag)(t.MintEvent.parsedJson.event.typename.name),o=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:me.TransactionType.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=(0,Rt.normalizeStructTag)(t.RedeemEvent.parsedJson.event.typename.name),n=t.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:me.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:e}}}};var pd=require("@mysten/sui/transactions"),md=require("@suilend/frontend-sui/lib/springsui"),Ni=require("@suilend/springsui-sdk");var ud=N(require("sort-keys-recursive")),z=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,ud.default)(this.data))}};var Ma=class a extends z{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 Ni.LstClient.initialize(n,Object.values(i).find(p=>p.type===this.data.inCoinType)),l=await Ni.LstClient.initialize(n,Object.values(i).find(p=>p.type===this.data.outCoinType)),u=new pd.Transaction;return(0,md.convertLstsAndSendToUser)(d,l,u,o.address,this.data.amount),u}static fromData(e){return console.log("ConvertIntention.fromData",e),new a(e)}};var fd=require("@mysten/sui/transactions"),ja=require("@suilend/frontend-sui"),bd=require("@suilend/frontend-sui/lib/springsui"),ji=require("@suilend/springsui-sdk");var Na=class a extends z{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 ji.LstClient.initialize(n,Object.values(i).find(S=>S.type===this.data.inCoinType)),l=await ji.LstClient.initialize(n,Object.values(i).find(S=>S.type===this.data.outCoinType)),u=new fd.Transaction,{obligationOwnerCapId:p,didCreate:m}=(0,ja.createObligationIfNoneExists)(r,u,s),b=(0,bd.convertLsts)(d,l,u,o.address,this.data.amount);return r.deposit(b,this.data.outCoinType,p,u),m&&(0,ja.sendObligationToUser)(p,o.address,u),u}static fromData(e){return console.log("ConvertAndDepositIntention.fromData",e),new a(e)}};var gd=require("@mysten/sui/transactions"),hd=require("@suilend/springsui-sdk");var Ea=class a extends z{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 hd.LstClient.initialize(n,Object.values(i).find(u=>u.type===this.data.outCoinType)),l=new gd.Transaction;return d.mintAmountAndRebalanceAndSendToUser(l,o.address,this.data.amount),l}static fromData(e){return console.log("StakeIntention.fromData",e),new a(e)}};var yd=require("@mysten/sui/transactions"),La=require("@suilend/frontend-sui"),Sd=require("@suilend/springsui-sdk");var Wa=class a extends z{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 Sd.LstClient.initialize(n,Object.values(i).find(b=>b.type===this.data.outCoinType)),l=new yd.Transaction,{obligationOwnerCapId:u,didCreate:p}=(0,La.createObligationIfNoneExists)(r,l,s),m=d.mintAmountAndRebalance(l,o.address,this.data.amount);return r.deposit(m,this.data.outCoinType,u,l),p&&(0,La.sendObligationToUser)(u,o.address,l),l}static fromData(e){return console.log("StakeAndDepositIntention.fromData",e),new a(e)}};var Td=require("@mysten/sui/transactions"),wd=require("@suilend/springsui-sdk");var Ua=class a extends z{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 wd.LstClient.initialize(n,Object.values(i).find(u=>u.type===this.data.inCoinType)),l=new Td.Transaction;return d.redeemAmountAndSendToUser(l,o.address,this.data.amount),l}static fromData(e){return console.log("UnstakeIntention.fromData",e),new a(e)}};var _d=require("@msafe/sui3-utils"),_t=require("@suilend/sdk"),Bd=require("@suilend/sdk/_generated/_framework/reified"),Md=require("@suilend/sdk/_generated/suilend/lending-market/structs");var Kt=require("@msafe/sui3-utils"),be=require("@mysten/bcs"),fe=require("@mysten/sui/utils"),Vt=require("@suilend/sdk"),Ei=N(require("bignumber.js"));var Fa=class{constructor(t,e){this.transaction=t;this.simResult=e}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("XXX this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("XXX this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(t){return this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function===t)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let t={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},e=(0,fe.normalizeStructTag)(t.MintEvent.parsedJson.coin_type.name),n=t.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",e,n),{txType:Kt.TransactionType.Other,type:"deposit",intentionData:{coinType:e,value:n}}}decodeWithdraw(){let t={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},e={RedeemEvent:this.simResult.events.find(c=>c.type.includes("lending_market::RedeemEvent"))},n=(0,fe.normalizeStructTag)(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 Ei.default((0,be.toHEX)((0,be.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Vt.maxU64.toString();return console.log("XXX decodeWithdraw - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Vt.maxU64.toString()),s&&(o=Vt.maxU64.toString()),{txType:Kt.TransactionType.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=(0,fe.normalizeStructTag)(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 Ei.default((0,be.toHEX)((0,be.fromB64)(this.inputs[r].Pure.bytes)),16).toString(),s=i===Vt.maxU64.toString();return console.log("XXX decodeBorrow - isMax:",s,"inputIndex:",r,"inputValue:",i,"maxU64.toString():",Vt.maxU64.toString()),s&&(o=Vt.maxU64.toString()),{txType:Kt.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let t={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},e=(0,fe.normalizeStructTag)(t.RepayEvent.parsedJson.coin_type.name),n=t.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",e,n),{txType:Kt.TransactionType.Other,type:"repay",intentionData:{coinType:e,value:n}}}decodeClaim(){let t={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},e={};for(let n=0;n<t.ClaimReward.length;n++){let o=t.ClaimReward[n],r=(0,fe.normalizeStructTag)(o.parsedJson.coin_type.name),i=o.parsedJson.liquidity_amount;e[r]=`${+(e[r]??"0")+ +i}`}return console.log("Decoder.decodeClaimRewards",e),{txType:Kt.TransactionType.Other,type:"claim",intentionData:{value:e}}}decodeClaimAndDeposit(){return{txType:Kt.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var Id=require("@mysten/sui/transactions");var Cd=N(require("sort-keys-recursive")),F=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Cd.default)(this.data))}};var qa=class a extends F{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 Id.Transaction;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)}};var vd=require("@mysten/sui/transactions");var Dd=require("@mysten/sui/utils"),ge=require("@suilend/sdk"),xd=N(require("bignumber.js"));var Wi=require("@mysten/sui/utils"),tm="0x34fe4f3c9e450fed4d0a3c587ed842eec5313c30c3cc3c0841247c49425e246b::suilend_point::SUILEND_POINT",em=(0,Wi.normalizeStructTag)(tm),kd=a=>(0,Wi.normalizeStructTag)(a)===em;var nm=(a,t)=>{let e={[ge.Side.DEPOSIT]:[],[ge.Side.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[ge.Side.DEPOSIT,ge.Side.BORROW].forEach(o=>{let r=o===ge.Side.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:(0,Dd.normalizeStructTag)(s.coinType.name),side:o})).filter(s=>!kd(s.rewardCoinType)&&!!i.rewards[Number(s.rewardIndex)]&&new xd.default(i.rewards[Number(s.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(e).flat()},$a=nm;var Ka=class a extends F{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 vd.Transaction;return r.claimRewardsAndSendToUser(o.address,i.id,$a(r,s),c),c}static fromData(e){return console.log("ClaimIntention.fromData",e),new a(e)}};var Ad=require("@mysten/sui/transactions");var Va=class a extends F{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 Ad.Transaction;return r.claimRewardsAndDeposit(o.address,i.id,$a(r,s),c),c}static fromData(e){return console.log("ClaimAndDepositIntention.fromData",e),new a(e)}};var Od=require("@mysten/sui/transactions");var Qa=class a extends F{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 Od.Transaction;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)}};var Pd=require("@mysten/sui/transactions");var Ha=class a extends F{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 Pd.Transaction;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)}};var Rd=require("@mysten/sui/transactions");var Ga=class a extends F{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 Rd.Transaction;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 za=async(a,t)=>{let e=await _t.SuilendClient.initializeWithLendingMarket(await Md.LendingMarket.fetch(a,(0,Bd.phantom)(_t.LENDING_MARKET_TYPE),_t.LENDING_MARKET_ID),a),n=await _t.SuilendClient.getObligationOwnerCaps(t.address,e.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(r=>_t.SuilendClient.getObligation(r.obligationId,e.lendingMarket.$typeArgs,a)));return{suilendClient:e,obligationOwnerCaps:n,obligations:o}},Ja=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:o}=t;this.utils||(this.utils=await za(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:e});console.log("SuilendAppHelper.deserialize",r);let s=new Fa(e,r).decode();return{txType:_d.TransactionType.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 za(r,i));let s;switch(n){case"deposit":s=Qa.fromData(o);break;case"withdraw":s=Ga.fromData(o);break;case"borrow":s=qa.fromData(o);break;case"repay":s=Ha.fromData(o);break;case"claim":s=Ka.fromData(o);break;case"claimAndDeposit":s=Va.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 console.log("XXX obligationId:",c,"obligations:",this.utils.obligations,"obligationOwnerCaps:",this.utils.obligationOwnerCaps),s.build({network:e,suiClient:r,account:i,suilendClient:this.utils.suilendClient,obligationOwnerCap:l,obligation:d})}};var Nd=async(a,t)=>{let e=await za(a,t),n=await(await fetch(`${dd}/liquid-staking-info-map.json`)).json();return{...e,LIQUID_STAKING_INFO_MAP:n}},Ya=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(t){let{transaction:e,suiClient:n,account:o}=t;this.utils||(this.utils=await Nd(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:e});console.log("SpringSuiAppHelper.deserialize",r);let s=new Ba(e,r).decode();return{txType:jd.TransactionType.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 Nd(r,i));let s;switch(n){case"stake":s=Ea.fromData(o);break;case"stakeAndDeposit":s=Wa.fromData(o);break;case"convert":s=Ma.fromData(o);break;case"convertAndDeposit":s=Na.fromData(o);break;case"unstake":s=Ua.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]})}};var Ld=require("@msafe/sui3-utils");var Li=require("@msafe/sui3-utils");var Xa=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:Li.TransactionType.Other,type:"mint",intentionData:{amount:e}}}decodeRedeem(t){let{event:{lst_amount_in:e}}=t;return console.log("Decoder.decodeRedeem",e),{txType:Li.TransactionType.Other,type:"redeem",intentionData:{amount:e}}}};var Ed=require("@alphafi/stsui-sdk"),Za=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:o}=this.data;return await(0,Ed.mint)(o,{address:n.address})}static fromData(e){return console.log("MintIntention.fromData",e),new a(e)}};var Wd=require("@alphafi/stsui-sdk"),tr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:n}=e,{amount:o}=this.data;return await(0,Wd.redeem)(o,{address:n.address})}static fromData(e){return console.log("RedeemIntention.fromData",e),new a(e)}};var er=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 Xa(e,o).decode();return{txType:Ld.TransactionType.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=Za.fromData(t.intentionData);break;case"redeem":n=tr.fromData(t.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:e})}};var su=require("@msafe/sui3-utils"),cu=require("turbos-clmm-sdk");var V=require("@msafe/sui3-utils"),Ui=require("@mysten/sui.js/bcs"),Mt=require("@mysten/sui.js/utils"),Ud=require("turbos-clmm-sdk");var J={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Y={PackageId:"0xdee9"};var rm=(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}`)}},nr=class{constructor(t,e,n){this.txb=t;this.turbosSdk=e;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(t){if(this.isSwapTransaction())return await this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}getMoveCallsTransaction(t){return t.every(e=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===e))}getSwapMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&t.includes(e.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${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(`${Y.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Y.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=rm(e,t.target,this.swap1Layer,this.swap2Layer),o=n.map((m,b)=>{let S=this.helper.decodeSharedObjectId(b),C=this.helper.decodeInputU128(4+b+e),x=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Ud.BN(C.toString()));return{pool:S,a2b:m,nextTickIndex:x}}),r=n[0]||e===1?t.typeArguments[0]:t.typeArguments[1],i=e===1?t.typeArguments[4]:n[0]?t.typeArguments[1]:t.typeArguments[0],s=this.helper.decodeInputAddress(6+2*e),c=this.helper.decodeInputU64(7+2*e),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:V.TransactionType.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:V.TransactionType.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:V.TransactionType.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:V.TransactionType.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:V.TransactionType.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:V.TransactionType.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:V.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}decodeRemoveLiquidity(t){console.log(this.helper,"decodeRemoveLiquidity this.helper");let e=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),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:V.TransactionType.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:V.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:V.TransactionType.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:V.TransactionType.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:V.TransactionType.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 Bt(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 Bt(e,this.txb))}get collectFeeHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${this.config.PackageId}::position_manager::collect`);return new Bt(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 Bt(t,this.txb)}get swapExactBaseForQuoteHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${Y.PackageId}::clob_v2::swap_exact_base_for_quote`);return new Bt(t,this.txb)}get swapExactQuoteForBaseHelper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target===`${Y.PackageId}::clob_v2::swap_exact_quote_for_base`);return new Bt(t,this.txb)}},Bt=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(0,Mt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return 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 Ui.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,Mt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,Mt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,Mt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,Mt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return Ui.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,Mt.normalizeStructTag)(this.moveCall.typeArguments[t])}shortTypeArg(t){return this.moveCall.typeArguments[t]}txArg(t){return this.moveCall.arguments[t]}};var Fd=require("turbos-clmm-sdk");var or=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Fd.TurbosSdk(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)}};var qd=require("turbos-clmm-sdk");var ar=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new qd.TurbosSdk(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)}};var $d=require("turbos-clmm-sdk");var rr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new $d.TurbosSdk(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)}};var Kd=require("turbos-clmm-sdk");var ir=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Kd.TurbosSdk(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)}};var Vd=require("turbos-clmm-sdk");var sr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Vd.TurbosSdk(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:S}=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:S})}static fromData(e){return new a(e)}};var Qd=require("turbos-clmm-sdk");var cr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Qd.TurbosSdk(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)}};var Hd=require("turbos-clmm-sdk");var lr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Hd.TurbosSdk(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)}};var Gd=require("@mysten/sui.js/transactions"),zd=require("@mysten/sui.js/utils");var dr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Gd.TransactionBlock;return n.moveCall({target:`${J.PackageId}::claim::claim`,typeArguments:[J.turbosCoinType],arguments:[n.object(J.Claim),n.object(zd.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(e){return new a(e)}};var Jd=require("@mysten/sui.js/transactions");var ur=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Jd.TransactionBlock;return n.moveCall({target:`${J.PackageId}::claim::join`,typeArguments:[J.turbosCoinType],arguments:[n.object(J.Claim)]}),n}static fromData(e){return new a(e)}};var Yd=require("@mysten/sui.js/transactions"),Xd=require("turbos-clmm-sdk");var pr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new Xd.TurbosSdk(e.network.replace("sui:",""),e.suiClient),o=new Yd.TransactionBlock;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)}};var Zd=require("turbos-clmm-sdk");var mr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(this.data,"this.data");let n=new Zd.TurbosSdk(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)}};var ru=require("turbos-clmm-sdk");var Fi=require("@mysten/sui.js/utils"),qi=require("@mysten/sui.js/transactions");var tu=require("turbos-clmm-sdk");var nn=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:`${Y.PackageId}::custodian_v2::AccountCap`}});return e.data[0]?.data?(0,tu.unstable_getObjectId)(e.data[0].data):void 0}createAccount(t){let[e]=t.moveCall({typeArguments:[],target:`${Y.PackageId}::clob_v2::create_account`,arguments:[]});return e}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}};var eu=89,nu=1e6,ou=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new qi.TransactionBlock,c=new nn(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,S,C]=s.moveCall({typeArguments:[t,e],target:`${Y.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[s.object(String(n)),s.pure(eu),m,s.pure(o),s.object((0,Fi.normalizeSuiObjectId)("0x6")),l]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([b],s.pure(r)),s.transferObjects([S],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(nu),s},au=async a=>{let{token1:t,token2:e,poolId:n,amountIn:o,currentAddress:r,turbosSdk:i}=a,s=new qi.TransactionBlock,c=new nn(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),[S,C,x]=s.moveCall({typeArguments:[t,e],target:`${Y.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[s.object(String(n)),s.pure(eu),m,s.pure(o),l,b,s.object((0,Fi.normalizeSuiObjectId)("0x6"))]});return u&&s.transferObjects([u],s.pure(r)),s.transferObjects([S],s.pure(r)),s.transferObjects([C],s.pure(r)),p||s.transferObjects([m],s.pure(r)),s.setSenderIfNotSet(r),s.setGasBudget(nu),s};var fr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new ru.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await au({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var iu=require("turbos-clmm-sdk");var br=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let n=new iu.TurbosSdk(e.network.replace("sui:",""),e.suiClient);return await ou({...this.data,turbosSdk:n,currentAddress:e.account.address})}static fromData(e){return new a(e)}};var gr=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(t){let e=new cu.TurbosSdk(t.network.replace("sui:",""),t.suiClient),n=await e.contract.getConfig(),{transactionBlock:o,account:r}=t;console.log(t,"input");let s=await new nr(o,e,n).decode(r.address);return{txType:su.TransactionType.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=sr.fromData(t.intentionData);break;case"AddLiquidity":r=or.fromData(t.intentionData);break;case"IncreaseLiquidity":r=lr.fromData(t.intentionData);break;case"DecreaseLiquidity":r=cr.fromData(t.intentionData);break;case"RemoveLiquidity":r=pr.fromData(t.intentionData);break;case"CollectFee":r=rr.fromData(t.intentionData);break;case"CollectReward":r=ir.fromData(t.intentionData);break;case"Burn":r=ar.fromData(t.intentionData);break;case"Swap":r=mr.fromData(t.intentionData);break;case"PrixJoin":r=ur.fromData(t.intentionData);break;case"PrixClaim":r=dr.fromData(t.intentionData);break;case"SwapExactBaseForQuote":r=fr.fromData(t.intentionData);break;case"SwapExactQuoteForBase":r=br.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};var pu=require("@msafe/sui3-utils");var hr=require("@msafe/sui3-utils"),$i=require("@mysten/sui.js/bcs"),Nt=require("@mysten/sui.js/utils");var im={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},O=im;var yr=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${O.packageId}::native_pool::burn_ticket`)}decodeStake(){let t=this.transactions[0].amounts[0].value.toNumber();return{txType:hr.TransactionType.Other,type:"Stake",intentionData:{amount:t}}}decodeUnStake(){let e=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:hr.TransactionType.Other,type:"UnStake",intentionData:{amount:e}}}decodeClaimTicket(){let t=this.helper.decodeOwnedObjectId(2);return console.log(t),{txType:hr.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:t}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(O.packageId));return new Ki(t,this.txb)}},Ki=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(0,Nt.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let n=this.getInputParam(t);return 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 $i.bcs.de(e,new Uint8Array(n))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,Nt.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,Nt.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,Nt.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,Nt.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let n=t.value.Pure;return $i.bcs.de(e,new Uint8Array(n))}typeArg(t){return(0,Nt.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var lu=require("@mysten/sui.js/transactions");var Sr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new lu.TransactionBlock,{ticketId:o}=this.data;return n.moveCall({target:`${O.packageId}::native_pool::burn_ticket`,arguments:[n.object(O.poolObjectId),n.object(O.systemStateObjectId),n.object(o)]}),n}static fromData(e){return new a(e)}};var du=require("@mysten/sui.js/transactions");var Tr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new du.TransactionBlock,{amount:o}=this.data,[r]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${O.packageId}::native_pool::stake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),r]}),n}static fromData(e){return new a(e)}};var uu=require("@mysten/sui.js/transactions");var wr=class a extends y{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){console.log(e);let n=new uu.TransactionBlock,{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]===O.certType.split("::")[0]),c=n.object(i.coinObjectId);s.length&&n.mergeCoins(c,s.map(l=>n.object(l.coinObjectId)));let d=n.splitCoins(n.object(i.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${O.packageId}::native_pool::unstake`,arguments:[n.object(O.poolObjectId),n.object(O.metadataObjectId),n.object(O.systemStateObjectId),d]}),n}static fromData(e){return new a(e)}};var Cr=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(t){let{transactionBlock:e}=t,o=new yr(e).decode();return{txType:pu.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:n}=t,o;switch(t.txSubType){case"Stake":o=Tr.fromData(t.intentionData);break;case"UnStake":o=wr.fromData(t.intentionData);break;case"ClaimTicket":o=Sr.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:n})}};var Iu=require("@msafe/sui3-utils");var Vi=require("@cetusprotocol/cetus-sui-clmm-sdk"),jt=require("@msafe/sui3-utils"),he=require("@mysten/bcs"),ye=require("@mysten/sui/bcs");var Ir=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:jt.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(t,1)),lowerTick:Number((0,Vi.asIntN)(BigInt(this.getU32(this.getInputIndex(t,2)))).toString()),upperTick:Number((0,Vi.asIntN)(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:jt.TransactionType.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:jt.TransactionType.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:jt.TransactionType.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:jt.TransactionType.Other,type:"CollectRewards",intentionData:{pool:t[0].pool,position:t[0].position,collectRewardTokens:t.map(e=>e.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:jt.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let t=this.getFeeCallData();return{txType:jt.TransactionType.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(ye.bcs.u32().parse(Uint8Array.from((0,he.fromB64)(this.inputs[t].Pure.bytes))))}getU64(t){return ye.bcs.u64().parse(Uint8Array.from((0,he.fromB64)(this.inputs[t].Pure.bytes)))}getU128(t){return ye.bcs.u128().parse(Uint8Array.from((0,he.fromB64)(this.inputs[t].Pure.bytes)))}getBoolean(t){return ye.bcs.bool().parse(Uint8Array.from((0,he.fromB64)(this.inputs[t].Pure.bytes)))}getAddress(t){return ye.bcs.Address.parse(Uint8Array.from((0,he.fromB64)(this.inputs[t].Pure.bytes)))}getTypeArguments(t){return t.MoveCall.typeArguments||[]}getInputIndex(t,e){return t.MoveCall.arguments[e].Input}};var gu=require("@msafe/sui3-utils");var nt=require("@firefly-exchange/library-sui");var fu=require("@firefly-exchange/library-sui"),bu=require("@firefly-exchange/library-sui/dist/src/spot"),mu={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x702301e7c6ca527a6f6a83f12c5edf2dcd6ec7a23fb5318ec86d88282eab7057"}},Wt=(a,t)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let e=new fu.SuiClient({url:mu.rpc});return new bu.OnChainCalls(e,mu.objects,{address:t.address,isUIWallet:!1})};var M=class{static async OpenPosition(t,e,n){let o=Wt(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=Wt(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=Wt(n,e),r=await o.queryChain.getPool(t.pool);return await o.removeLiquidity(r,t.position,{liquidityAmount:new nt.BN(t.liquidity),tokenMaxA:new nt.BN(t.maxAmountTokenA),tokenMaxB:new nt.BN(t.maxAmountTokenB)},{returnTx:!0,sender:e.address})}static async closePosition(t,e,n){let o=Wt(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=Wt(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=Wt(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=Wt(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{...nt.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(e.lowerTick,e.upperTick,new nt.BN(e.tokenAmount),e.isTokenAFixed,!0,0,new nt.BN(t.current_sqrt_price)),tokenMaxA:new nt.BN(e.maxAmountTokenA),tokenMaxB:new nt.BN(e.maxAmountTokenB)}}};var kr=class a extends f{constructor(e){super(e);this.data=e}txType=gu.TransactionType.Other;txSubType="ClosePosition";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.closePosition(this.data,n,o)}static fromData(e){return new a(e)}};var hu=require("@msafe/sui3-utils");var Dr=class a extends f{constructor(e){super(e);this.data=e}txType=hu.TransactionType.Other;txSubType="CollectFee";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.collectFee(this.data,n,o)}static fromData(e){return new a(e)}};var yu=require("@msafe/sui3-utils");var xr=class a extends f{constructor(e){super(e);this.data=e}txType=yu.TransactionType.Other;txSubType="CollectRewards";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.collectRewards(this.data,n,o)}static fromData(e){return new a(e)}};var Su=require("@msafe/sui3-utils");var vr=class a extends f{constructor(e){super(e);this.data=e}txType=Su.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.collectRewardsAndFee(this.data,n,o)}static fromData(e){return new a(e)}};var Tu=require("@msafe/sui3-utils");var Ar=class a extends f{constructor(e){super(e);this.data=e}txType=Tu.TransactionType.Other;txSubType="OpenPosition";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.OpenPosition(this.data,n,o)}static fromData(e){return new a(e)}};var wu=require("@msafe/sui3-utils");var Or=class a extends f{constructor(e){super(e);this.data=e}txType=wu.TransactionType.Other;txSubType="ProvideLiquidity";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.provideLiquidity(this.data,n,o)}static fromData(e){return new a(e)}};var Cu=require("@msafe/sui3-utils");var Pr=class a extends f{constructor(e){super(e);this.data=e}txType=Cu.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:o}=e;return console.log(this.data),M.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 Ir(e).decode();return{txType:Iu.TransactionType.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=Ar.fromData(t.intentionData);break;case"ProvideLiquidity":r=Or.fromData(t.intentionData);break;case"RemoveLiquidity":r=Pr.fromData(t.intentionData);break;case"ClosePosition":r=kr.fromData(t.intentionData);break;case"CollectFee":r=Dr.fromData(t.intentionData);break;case"CollectRewards":r=xr.fromData(t.intentionData);break;case"CollectRewardsAndFee":r=vr.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:o})}};var Bu=require("@msafe/sui3-utils");var ku=require("kriya-dev-sdk");var _r=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new ku.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbAddLiquidity(n)}static fromData(e){return new a(e)}};var Du=require("kriya-dev-sdk");var Br=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Du.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new a(e)}};var xu=require("kriya-dev-sdk");var Mr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new xu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbClaimRewards(n)}static fromData(e){return new a(e)}};var vu=require("kriya-dev-sdk");var Nr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new vu.KriyaSDK,{params:n}=this.data;return e.Amm.getTxbRemoveLiquidity(n)}static fromData(e){return new a(e)}};var Au=require("kriya-dev-sdk");var jr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Au.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbAddLiquiditySingleSided(n)}static fromData(e){return new a(e)}};var Ou=require("kriya-dev-sdk");var Er=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Ou.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbAddLiquidity(n)}static fromData(e){return new a(e)}};var Pu=require("kriya-dev-sdk");var Wr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Pu.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbClaimMayaRewards(n)}static fromData(e){return new a(e)}};var Ru=require("kriya-dev-sdk");var Lr=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new Ru.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbClaimRewards(n)}static fromData(e){return new a(e)}};var _u=require("kriya-dev-sdk");var Ur=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let e=new _u.KriyaSDK,{params:n}=this.data;return e.Clmm.getTxbRemoveLiquidity(n)}static fromData(e){return new a(e)}};var Fr=class{application="kriya";supportSDK="@mysten/sui";async deserialize(t){let{appContext:e}=t;return{txType:Bu.TransactionType.Other,txSubType:e.action,intentionData:e}}async build(t){let e;switch(t.txSubType){case"AddLiquidity":e=_r.fromData(t.intentionData);break;case"AddLiquiditySingleSided":e=Br.fromData(t.intentionData);break;case"RemoveLiquidity":e=Nr.fromData(t.intentionData);break;case"ClaimRewards":e=Mr.fromData(t.intentionData);break;case"ClaimRewardsV3":e=Lr.fromData(t.intentionData);break;case"ClaimV3MayaRewards":e=Wr.fromData(t.intentionData);break;case"AddLiquidityV3":e=Er.fromData(t.intentionData);break;case"AddLiquiditySingleSideV3":e=jr.fromData(t.intentionData);break;case"RemoveLiquidityV3":e=Ur.fromData(t.intentionData);break;default:throw new Error("not implemented")}return e.build()}};var cm=Lo.fromHelpers([new xo,new Mo,new Io,new No,new to,new gr,new Fr,new _a,new Cr,new Pn,new Ja,new Ya,new un,new Rr,new er]);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|