@msafe/sui-app-store 0.0.37 → 0.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var ar=Object.defineProperty;var xe=(n,t)=>{for(var e in t)ar(n,e,{get:t[e],enumerable:!0})};import{TransactionType as cr}from"@msafe/sui3-utils";import{toHEX as lr}from"@mysten/sui.js/utils";import{TransactionBlock as ir}from"@mysten/sui.js/transactions";import{fromHEX as sr}from"@mysten/sui.js/utils";import or from"sort-keys-recursive";var m=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(or(this.data))}};var nt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,o=ir.from(sr(this.data.content)),i=await r.devInspectTransactionBlock({transactionBlock:o,sender:a.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return o}static fromData(e){return new n(e)}};var at=class{application="cetus";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:cr.Other,txSubType:"CetusTransaction",intentionData:{content:lr(a)}}}async build(t){let{suiClient:e,account:r}=t;return nt.fromData(t.intentionData).build({suiClient:e,account:r})}};import{TransactionType as cn}from"@msafe/sui3-utils";var ne={};xe(ne,{contractId:()=>pr,default:()=>yr,feeObjId:()=>br,roleObjId:()=>dr,status:()=>ur,transaction:()=>mr,upgradeCapObjId:()=>gr,vaultObjId:()=>fr});var mr="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",ur="success",pr="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",dr="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",fr="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",br="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",gr="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",yr={transaction:mr,status:ur,contractId:pr,roleObjId:dr,vaultObjId:fr,feeObjId:br,upgradeCapObjId:gr};var ae={};xe(ae,{contractId:()=>Ir,default:()=>Dr,feeObjId:()=>wr,roleObjId:()=>Tr,status:()=>Sr,transaction:()=>hr,upgradeCapObjId:()=>xr,vaultObjId:()=>Cr});var hr="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sr="success",Ir="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Tr="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Cr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",wr="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",xr="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Dr={transaction:hr,status:Sr,contractId:Ir,roleObjId:Tr,vaultObjId:Cr,feeObjId:wr,upgradeCapObjId:xr};var kr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",vr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Pr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Ar="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Or="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Er="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Br="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",jr="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",De=ne,ke=ae,Rr=new Map([["dev",{env:"dev",rpc:{url:kr},backend:{url:Or},contract:De}],["stg",{env:"stg",rpc:{url:vr},backend:{url:Er},contract:De}],["prev",{env:"prev",rpc:{url:Pr},backend:{url:Br},contract:ke}],["prod",{env:"prod",rpc:{url:Ar},backend:{url:jr},contract:ke}]]);function ve(n,t){let e=Rr.get(n);if(!e)throw new Error(`Env not supported: ${n}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as Mr}from"@mysten/sui.js/client";var p=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:a,context:o}=r;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var ot=class extends p{constructor(){super(11,"Backend is not specified")}};var it=class extends p{constructor(){super(1,"Wallet not connected")}};import O,{AxiosError as Nr}from"axios";var A=class extends p{constructor(t,e){super(10,t,{context:e})}};var st=class n{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Nr)throw new A(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new A(t.data.code)}throw new A(t.status.toString())}async getIncomingStreams(t,e){let r=await O.post(`${this.apiURL}/stream`,{recipient:t,...e});return n.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await O.post(`${this.apiURL}/stream`,{sender:t,...e});return n.parseResponseData(r)}async getStreamHistory(t){let e=await O.post(`${this.apiURL}/stream-events`,t),r=n.parseResponseData(e);return r.data.forEach(a=>{let o=a;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),r}async getAllCoinTypes(t){let e=await O.post(`${this.apiURL}/stream-info`,{address:t});return n.parseResponseData(e)}async getAllRecipients(t,e){let r=await O.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return n.parseResponseData(r)}async getAllSenders(t,e){let r=await O.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return n.parseResponseData(r)}};var E=class n{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new Mr({url:t.rpc.url}),t.backend&&(this._backend=new st(t.backend.url))}static new(t,e){let r=ve(t,e);return new n(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new ot;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 it;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as nn,normalizeStructTag as an,normalizeSuiAddress as Xe}from"@mysten/sui.js/utils";import{normalizeStructTag as se,SUI_TYPE_ARG as Wr}from"@mysten/sui.js/utils";import{Duration as qe}from"luxon";import{TransactionBlock as dt}from"@mysten/sui.js/transactions";import{TransactionBlock as Me}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Le,normalizeStructTag as qr}from"@mysten/sui.js/utils";var oe=50n,ct=10000n,Pe=25n,ie=100000000n;var S=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},_=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},w=class n{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,r){if(r in e)return Reflect.get(e,r);let a=i=>new n(e.result[i]);if(r===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof r=="symbol")return;let o=parseInt(r,10);if(!(Number.isNaN(o)||o<0))return a(o)}})}moveArg(){return this.result}};import{Buffer as Ae}from"buffer";import{normalizeSuiAddress as Lr}from"@mysten/sui.js/utils";var q=class extends p{constructor(t,e){super(3,t,{context:e})}};var lt=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 r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="address")throw new q("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return Lr(Ae.from(r).toString("hex"))}getU64(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="u64")throw new q("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return Ae.from(r).readBigInt64LE()}};import{bcs as Ee}from"@mysten/sui.js/bcs";var f=class extends p{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var Be={groupId:"string",name:"string"},Fr=64;function je(n){return Re(n),Ee.ser(Be,n).toString("base64")}function W(n){let t=Ee.de(Be,n,"base64");return Re(t),t}function Re(n){if(!Oe(n.name))throw new f("Invalid metadata: Name contains unknown character");if(!Oe(n.groupId))throw new f("Invalid metadata: Group ID contains unknown character");if(n.name.length>Fr)throw new f("Invalid metadata: Name exceed max length 64")}function Oe(n){return/^[\x00-\x7F]+$/.test(n)}import{normalizeStructTag as mt}from"@mysten/sui.js/utils";function ut(n,t){return mt(n)===mt(t)}function x(n,t){return mt(n)===mt(t)}var pt="txn.gas";import{nanoid as _r}from"nanoid";function Ne(){return _r()}var v=class n{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:je({name:t.name,groupId:Ne()}),coinType:qr(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 Me,r=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,r),o=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,o[0]),s;a.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let l=0;l<t.recipients.length;l++){let u=t.recipients[l],b=this.amountForRecipient(u,t.numberEpoch),d=this.getStreamFeeLocal(b),[k]=e.splitCoins(i,[e.pure(b+d,"u64")]),[F]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new w(k),flatFeeCoin:new w(F),metadata:t.metadata,recipient:u.address,timeStart:t.startTime,cliff:u.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=n.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:oe,denominator:ct},claimFeePercent:{numerator:Pe,denominator:ct},flatFeePerStream:ie}}async addMergeCoins(t,e){let r;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),r=t.object(e.primaryCoin)):e.primaryCoin===pt?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return ut(r,Le)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:Le,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,o)=>{let i=this.amountForRecipient(o,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 ie}getStreamFeeLocal(t){return t*oe/ct}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Me,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new lt(r).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as _e}from"@mysten/sui.js/transactions";var Fe="0x0000000000000000000000000000000000000000000000000000000000000006";var B=class{constructor(t,e,r){this.moduleName=t;this.config=e;this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(_e.MoveCall({target:r,arguments:e.arguments.map(a=>a instanceof _?a.moveArgs(t):a instanceof S?a.moveArg(t):a instanceof w?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],a=[]){t.add(_e.MoveCall({target:e,arguments:r.map(o=>o instanceof _?o.moveArgs(t):o instanceof S?o.moveArg(t):o instanceof w?o.moveArg():t.pure(o)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new S(t):t}vaultObject(){return new S(this.config.vaultObjId)}roleObject(){return new S(this.config.roleObjId)}feeObject(){return new S(this.config.feeObjId)}clockObject(){return new S(Fe)}};var j=class n extends B{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}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,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_fee,arguments:[a,o,r],typeArgs:[]})}setStreamingFlatFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_flat_fee,arguments:[a,o,r],typeArgs:[]})}setClaimFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_claim_fee,arguments:[a,o,r],typeArgs:[]})}streamingFee(e,r){let a=this.feeObject();return this.addContractCall(e,{method:n.MethodName.streaming_fee,arguments:[a,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:n.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:n.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var I=class n extends B{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}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,r){let a=this.feeObject(),o=this.vaultObject(),i=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),l=this.clockObject();return this.addContractCall(e,{method:n.MethodName.create_stream,arguments:[a,o,i,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,l],typeArgs:[r.coinType]})}setAutoClaim(e,r){let a=this.makeObject(r.streamId);return this.addContractCall(e,{method:n.MethodName.set_auto_claim,arguments:[a,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.cancel_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let a=this.makeObject(r.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream_by_proxy,arguments:[a,o,i,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream_by_proxy}`}};var R=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new j(e,t),this.streamContract=new I(e,t)}feeContract;streamContract;async createStreams(t){let e=v.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new v(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let a=new dt;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new dt;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new dt;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new dt;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var ft=class extends p{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Gr=1e3,bt=class{constructor(t){this.globals=t;this.coinMetaHelper=new ce(t.suiClient),this.createStreamHelper=new R(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new ft(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 f("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-r)/t.steps,i={realTotalAmount:a*t.steps+r,cliffAmount:r,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new f("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new f("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(qe.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:r,interval:qe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...r,coinType:se(r.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,o)=>({...a,coinType:se(a.coinType),coinMeta:r[o]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new f("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new f("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Gr)throw new f("Interval shall be at least 1 second","interval",t.interval)}},ce=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=se(t||Wr);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};import{normalizeStructTag as Ue,normalizeSuiAddress as Tt}from"@mysten/sui.js/utils";import{DateTime as $e}from"luxon";import{TransactionBlock as St}from"@mysten/sui.js/transactions";import{normalizeStructTag as Ge,parseStructTag as zr}from"@mysten/sui.js/utils";import{DateTime as Hr}from"luxon";var gt=class extends p{constructor(){super(7,"Connected wallet is not creator")}};var G=class extends p{constructor(){super(8,"Connected wallet is not recipient")}};var U=class extends p{constructor(t,e){super(6,t,{context:e})}};var g=class extends p{constructor(t,e={}){super(0,t,e)}};var yt=class extends p{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Ur,Duration as $r}from"luxon";var We=(1n<<64n)-1n,ht=1e3;function le(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ht);return Ur.fromMillis(e*ht)}function me(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ht);return $r.fromMillis(e*ht)}var D=class n{constructor(t,e,r){this.globals=t;this.streamId=e;this.rawData=r;this.streamContract=new I(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let r=await n.fetchStreamData(t,e);return new n(t,e,r)}static fromObjectData(t,e,r){let a=n.parseRawStreamData(e,r);return new n(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 n.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new g("Object Id does not align");this.rawData=n.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 gt;let t=new St;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new G;let t=new St;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new G;let e=new St;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new St;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 Ge(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 me(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return W(t).groupId}get name(){let{metadata:t}=this.rawData.config;return W(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return le(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return me(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:le((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===We?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Hr.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let r=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(r)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(r)}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 r=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return n.parseRawStreamData(e,r)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new yt(t):new U(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new U("Unexpected object type",{gotType:r.dataType});let{typeParams:a}=zr(r.type),o=Ge(a[0]),i=r.fields,s=i.config.fields,l=i.status.fields;return{coinType:o,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}};var N=class extends p{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function pe(n){let t=[];for(;await n.hasNext();){let e=await n.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var ue=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)}},M=class{constructor(t){this.requester=t;this.pager=new ue(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 Vr=25;async function fe(n,t,e){let r=new $(t),a=new z(n,r,e);return await pe(a)}var $=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]}},z=class extends M{constructor(e,r,a){super(new de(e,r,a));this.suiClient=e;this.idIter=r;this.options=a}},de=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||Vr,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let o=await this.stringIter.next();o&&t.push(o)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:a}=this;r=e.filter(o=>a?.(o))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}};var It=class n{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new N("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new f("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await fe(t.suiClient,e);return r.forEach(a=>{if(!a)throw new g("stream group object data undefined")}),n.newFromObjectResponse(t,e,r)}static async newFromObjectResponse(t,e,r){let a=await n.parseGroupStreams(t,e,r);return new n(t,a)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),r=e[0],a=!0;return e.forEach(o=>{Qr(r,o)||(a=!1)}),a}async refresh(){let t=await fe(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,r)=>{e.refreshWithData(t[r])})}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,r){let a=r.map((o,i)=>D.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(a.map(o=>o.groupId)).size!==1)throw new N("Not same group ID");if(!this.checkStreamGroup(a))throw new N("Not same stream settings");return a}};function Qr(n,t){return n.name===t.name&&n.groupId===t.groupId&&n.creator===t.creator&&n.start.toMillis()===t.start.toMillis()&&n.interval.toMillis()===t.interval.toMillis()&&n.steps===t.steps&&n.cancelable===t.cancelable}var H=class n{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await Ct.newIncoming(t);return new n(e,t.pageSize)}static async newOutgoing(t){let e=await Ct.newOutgoing(t);return new n(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}},Ct=class n{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await wt.newIncomingQuery(t);return new n(e)}static async newOutgoing(t){let e=await wt.newOutgoingQuery(t);return new n(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 g("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new g("No more results");return t}},wt=class n{constructor(t,e,r,a){this.globals=t;this.recipient=e;this.groupRefs=r;this.query=a;this.current=0;let o=new $(r.flat().map(i=>i.streamId));this.objectIter=new z(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Zr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>Tt(s.recipient)===Tt(r)),i=ze(o);return new n(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=tn(t.query),r=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(r,e),o=ze(a);return new n(t.globals,r,o,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Xr(this.globals,t[0].streamId,this.objectIter);return this.current++,He(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Kr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,Yr(e,this.query)?e:this.doNextRequest()}throw new g("Stream group with no stream")}};function ze(n){let t=new Map;return n.forEach(e=>{let r=t.get(e.groupId);r?(r.push(e),t.set(e.groupId,r)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,r)=>$e.fromISO(r[0].createDate).toMillis()-$e.fromISO(e[0].createDate).toMillis())}function He(n,t){if(t===void 0)return!0;let e=Jr(n,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let r=t.claimable?n.progress.claimable!==0n:n.progress.claimable===0n;return e&&r}return e}function Jr(n,t){return t===void 0?!0:Array.isArray(t)?t.includes(n.progress.status):n.progress.status===t}function Yr(n,t){if(!t)return!0;let e=!1;return n.streams.forEach(r=>{He(r,t)&&(e=!0)}),e}async function Xr(n,t,e){let r=await Ve(e,t);return D.fromObjectData(n,t,r)}async function Kr(n,t,e){let r=[];for(;r.length<t.length;){let a=await Ve(e,t[r.length]);r.push(a)}return It.newFromObjectResponse(n,t,r)}async function Ve(n,t){if(!await n.hasNext())throw new g("object iterator has been consumed");let e=await n.next();if(!e||e.error||e.data===void 0||e.data===null)throw new g("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new g("stream id not aligned");return e}function Zr(n){return{status:be(n?.status),coinType:Qe(n?.coinType),sender:Je(n?.sender)}}function tn(n){return{status:be(n?.status),coinType:Qe(n?.coinType),recipient:Je(n?.recipient)}}function be(n){return n===void 0||n.length===0?"all":Array.isArray(n)?n.reduce((t,e)=>{let r=be(e);return!t||t===r?r:"all"},void 0):en(n)}function en(n){switch(n){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new f("Unknown stream filtered status")}}function Qe(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Ue(t)):void 0:Ue(n)}function Je(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Tt(t)):void 0:Tt(n)}var xt=class extends p{constructor(e,r,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:r,gotAmount:a}});this.coinType=e;this.requestAmount=r;this.gotAmount=a}};var rn=25;async function Ye(n,t,e,r="0x2::sui::SUI",a=rn){let o=new ge(n,t,r,a),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let l=await o.next();l&&(s.push(l),i+=BigInt(l.balance))}if(i<e)throw new xt(r,e,i);return s}var ge=class extends M{constructor(e,r,a,o){super(new ye(e,r,a,o));this.suiClient=e;this.owner=r;this.coinType=a;this.reqPageSize=o}},ye=class{constructor(t,e,r,a){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=a;if(a<=0)throw new g("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 he=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Dt=class{constructor(t){this.account=t}async address(){return this.account.address}},Se=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(ut(t.coinType,nn))return{primaryCoin:pt};if(t.amount<=0)throw new f("Invalid coin request","coinAmount",t.amount);let e=await Ye(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new g("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},kt=class{globals;helper;constructor(t,e){this.globals=E.new(t,e),this.helper=new bt(this.globals)}connectSingleWallet(t){let e=new Se(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new he(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return D.new(this.globals,t)}async getIncomingStreams(t,e=10){return H.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return H.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(r=>an(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>Xe(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>Xe(a))}get wallet(){return this.globals.wallet}builder(){return new R(this.globals)}};import on from"sort-keys-recursive";var vt=class{constructor(t){this.data=t}serialize(){return JSON.stringify(on(this.data))}};var h=class extends vt{application="mpay";getClient(t,e){let r=new kt(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Dt(e)),r}};var V=class extends h{constructor(e){super(e);this.data=e}txType=cn.Stream;txSubType="Cancel";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).cancel()}};import{TransactionType as ln}from"@msafe/sui3-utils";var Q=class extends h{constructor(e){super(e);this.data=e}txType=ln.Stream;txSubType="ClaimByProxy";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as mn}from"@msafe/sui3-utils";var J=class extends h{constructor(e){super(e);this.data=e}txType=mn.Stream;txSubType="Claim";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).claim()}};import{TransactionType as un}from"@msafe/sui3-utils";var Y=class extends h{constructor(e){super(e);this.data=e}txType=un.Stream;txSubType="CreateStream";async build(e){let{network:r,account:a}=e;return this.getClient(r,a).createStream(this.data)}};import{bcs as Ke}from"@mysten/sui.js/bcs";import{normalizeStructTag as pn,normalizeSuiAddress as X}from"@mysten/sui.js/utils";var L=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return X(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return Ke.de(e,new Uint8Array(r))}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 X(t.value.Object.ImmOrOwned.objectId)}return X(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return X(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return X(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 r=t.value.Pure;return Ke.de(e,new Uint8Array(r))}typeArg(t){return pn(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Pt=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(r=>this.getCreationInfoFromMoveCall(r));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&x(e.target,this.contract.createStreamTarget));if(t.length===0)throw new g("No create stream transactions");return t.map(e=>new L(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:a}=W(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),l=t.decodeInputU64(8),u=t.decodeInputU64(9),b=t.decodeInputU64(10),d=t.decodeInputBool(11),k=t.typeArg(0);return{name:r,groupId:a,recipient:o,timeStart:i,cliff:s,epochInterval:l,totalEpoch:u,amountPerEpoch:b,cancelable:d,coinType:k}}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 f("Stream group not have common info");let r=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:r,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 I(this.globals.envConfig.contract,this.globals)}get feeContract(){return new j(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new v(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 At=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new I(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"&&x(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Pt(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 L(t,this.txb)}};import{TransactionType as dn}from"@msafe/sui3-utils";var K=class extends h{constructor(e){super(e);this.data=e}txType=dn.Stream;txSubType="SetAutoClaim";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Ot=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,a=E.new(e==="sui:mainnet"?"prod":"dev"),i=new At(a,r).decode(),s;switch(i.type){case"CreateStream":s=new Y(i.info);break;case"SetAutoClaim":s=new K({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new J({streamId:i.streamId});break;case"ClaimByProxy":s=new Q({streamId:i.streamId});break;case"Cancel":s=new V({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,r;switch(t.txSubType){case"CreateStream":r=new Y(e);break;case"Claim":r=new J(e);break;case"ClaimByProxy":r=new Q(e);break;case"SetAutoClaim":r=new K(e);break;case"Cancel":r=new V(e);break;default:throw new Error("not implemented")}return r.build({...t})}};import{TransactionDefaultApplication as hn,TransactionSubTypes as Ie}from"@msafe/sui3-utils";import{buildCoinTransferTxb as fn}from"@msafe/sui3-utils";var Et=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return fn(r,this.data,a.address)}static fromData(e){return new n(e)}};import{buildObjectTransferTxb as bn}from"@msafe/sui3-utils";var Bt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return bn(r,this.data,a.address)}static fromData(e){return new n(e)}};import{isSameAddress as gn}from"@msafe/sui3-utils";import{TransactionBlock as yn}from"@mysten/sui.js/transactions";var jt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,a=yn.from(this.data.content);if(!gn(a.blockData.sender,r.address))throw new Error("Invalid sender address");return a}static fromData(e){return new n(e)}};var Rt=class{application;constructor(){this.application=hn}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case Ie.assets.coin.send:a=Et.fromData(t.intentionData);break;case Ie.assets.object.send:a=Bt.fromData(t.intentionData);break;case Ie.others.plain:a=jt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};import{TransactionType as vn}from"@msafe/sui3-utils";import{TransactionType as Z}from"@msafe/sui3-utils";import{bcs as Ze}from"@mysten/sui.js/bcs";import{normalizeStructTag as Tn,normalizeSuiAddress as tt}from"@mysten/sui.js/utils";var Sn={ProtocolPackage:"0x7c9b90b3fda0fa4aa8ee88ae6c4a0b83c773f74936b5354448cb94662e94442d",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},c=Sn;var Nt=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(c.pool).find(r=>r.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===`${c.ProtocolPackage}::incentive_v2::claim_reward`){let r=new Mt(e,this.txb),a=r.decodeInputU8(4),o=r.decodeInputU8(5),i=this.findPoolByAssetId(a);t.push({coinType:i.coinType,option:o})}}),console.log("decode claims",t),{txType:Z.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryRepay",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(c.ProtocolPackage));return new Mt(t,this.txb)}},Mt=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.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 tt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return Ze.de(e,new Uint8Array(r))}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 tt(t.value.Object.ImmOrOwned.objectId)}return tt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return tt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return tt(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 r=t.value.Pure;return Ze.de(e,new Uint8Array(r))}typeArg(t){return Tn(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Cn}from"@mysten/sui.js/transactions";function Te(n,t,e,r){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[n.object("0x06"),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),e,n.pure(r),n.object(c.Incentive),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function tr(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),n.pure(e),n.object(c.Incentive),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function er(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),n.pure(e),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function Ce(n,t,e,r){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),e,n.pure(r),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function rr(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[n.object("0x06"),n.object(c.IncentiveV2),n.object(t.fondPoolId),n.object(c.StorageId),n.pure(t.assetId),n.pure(e)],typeArguments:[t.type]}),n}var Lt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new Cn;return e.forEach(a=>{let{coinType:o,option:i}=a,s=c.pool[o];if(console.log("build",this.data),!s)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);if(!s.fondPoolId)throw new Error(`${o} not support claim reward.`);rr(r,s,i)}),r}static fromData(e){return new n(e)}};import{TransactionBlock as wn}from"@mysten/sui.js/transactions";var Ft=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new wn;console.log("build",this.data);let o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return er(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as xn}from"@mysten/sui.js/transactions";async function _t(n,t,e){let r=await n.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,r),r}var qt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,{coinType:o,amount:i}=this.data,s=new xn;if(console.log("build",this.data),o==="sui"){let[d]=s.splitCoins(s.gas,[i]);return Te(s,c.pool.sui,d,i)}let l=c.pool[o];if(!l)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let u=await _t(r,a.address,l.type);if(!u.data[0])throw new Error(`Insufficient balance for ${l.name} Token`);let b=u.data[0].coinObjectId;if(u.data.length>=2){let d=1;for(;d<u.data.length;)s.mergeCoins(b,[u.data[d].coinObjectId]),d++}return Te(s,l,s.object(b),i)}static fromData(e){return new n(e)}};import{TransactionBlock as Dn}from"@mysten/sui.js/transactions";var Wt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,{coinType:o,amount:i}=this.data,s=new Dn;if(console.log("build",this.data),o==="sui"){let[d]=s.splitCoins(s.gas,[i]);return Ce(s,c.pool.sui,d,i)}let l=c.pool[o];if(!l)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let u=await _t(r,a.address,l.type);if(!u.data[0])throw new Error(`Insufficient balance for ${l.name} Token`);let b=u.data[0].coinObjectId;if(u.data.length>=2){let d=1;for(;d<u.data.length;)s.mergeCoins(b,[u.data[d].coinObjectId]),d++}return Ce(s,l,s.object(b),i)}static fromData(e){return new n(e)}};import{TransactionBlock as kn}from"@mysten/sui.js/transactions";var Gt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new kn;console.log("build",this.data);let o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return tr(a,o,r)}static fromData(e){return new n(e)}};var Ut=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,a=new Nt(e).decode();return{txType:vn.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case"EntryDeposit":a=qt.fromData(t.intentionData);break;case"EntryBorrow":a=Ft.fromData(t.intentionData);break;case"EntryRepay":a=Wt.fromData(t.intentionData);break;case"EntryWithdraw":a=Gt.fromData(t.intentionData);break;case"ClaimReward":a=Lt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};var $t=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}};import{TransactionSubTypes as Pn,TransactionType as An}from"@msafe/sui3-utils";import{TransactionBlock as On}from"@mysten/sui.js/transactions";import{fromHEX as En,toHEX as Bn}from"@mysten/sui.js/utils";import em from"sort-keys-recursive";var jn="msafe-plain-tx",Rn=Pn.others.plain;var zt=class{application;constructor(){this.application=jn}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:An.Other,txSubType:Rn,intentionData:{content:Bn(a)}}}async build(t){let{suiClient:e,account:r}=t,a=On.from(En(t.intentionData.content)),o=await e.devInspectTransactionBlock({transactionBlock:a,sender:r.address});if(!(o.effects.status.status==="success"))throw new Error(o.effects.status.error);return a}};import{TransactionType as Hn}from"@msafe/sui3-utils";import{TransactionType as Mn}from"@msafe/sui3-utils";import{bcs as nr}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ln,normalizeSuiAddress as et}from"@mysten/sui.js/utils";var Ht={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"};var Vt=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){let t=this.helper.decodeOwnedObjectId(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),o=this.helper.decodeInputU32(4),i=this.helper.decodeInputU32(6);return{txType:Mn.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:a,tickLower:o,tickUpper:i}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(""));return new we(t,this.txb)}},we=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.getOwnedObjectId(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 et(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return nr.de(e,new Uint8Array(r))}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 et(t.value.Object.ImmOrOwned.objectId)}return et(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return et(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return et(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 r=t.value.Pure;return nr.de(e,new Uint8Array(r))}typeArg(t){return Ln(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as Fn}from"turbos-clmm-sdk";var Qt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Fn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,tickLower:u,tickUpper:b,txb:d}=this.data;return r.pool.addLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,tickLower:u,tickUpper:b,txb:d})}static fromData(e){return new n(e)}};import{TurbosSdk as _n}from"turbos-clmm-sdk";var Jt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new _n(e.network.replace("sui:",""),e.suiClient),{pool:a,nft:o,txb:i}=this.data;return r.nft.burn({pool:a,nft:o,txb:i})}static fromData(e){return new n(e)}};import{TurbosSdk as qn}from"turbos-clmm-sdk";var Yt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new qn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,nft:i,collectAmountA:s,collectAmountB:l,txb:u}=this.data;return r.pool.collectFee({pool:a,address:o,collectAmountA:s,collectAmountB:l,nft:i,txb:u})}static fromData(e){return new n(e)}};import{TurbosSdk as Wn}from"turbos-clmm-sdk";var Xt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Wn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,nft:i,rewardAmounts:s,txb:l}=this.data;return r.pool.collectReward({pool:a,address:o,rewardAmounts:s,nft:i,txb:l})}static fromData(e){return new n(e)}};import{TurbosSdk as Gn}from"turbos-clmm-sdk";var Kt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Gn(e.network.replace("sui:",""),e.suiClient),{fee:a,address:o,tickLower:i,tickUpper:s,sqrtPrice:l,slippage:u,coinTypeA:b,coinTypeB:d,amountA:k,amountB:F,txb:re}=this.data;return r.pool.createPool({fee:a,amountA:k,amountB:F,address:o,tickLower:i,tickUpper:s,sqrtPrice:l,slippage:u,coinTypeA:b,coinTypeB:d,txb:re})}static fromData(e){return new n(e)}};import{TurbosSdk as Un}from"turbos-clmm-sdk";var Zt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Un(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,decreaseLiquidity:b,txb:d}=this.data;return r.pool.decreaseLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,nft:u,decreaseLiquidity:b,txb:d})}static fromData(e){return new n(e)}};import{TurbosSdk as $n}from"turbos-clmm-sdk";var te=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new $n(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,txb:b}=this.data;return r.pool.increaseLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,nft:u,txb:b})}static fromData(e){return new n(e)}};import{TurbosSdk as zn}from"turbos-clmm-sdk";var ee=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new zn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,decreaseLiquidity:b,collectAmountA:d,collectAmountB:k,rewardAmounts:F,txb:re}=this.data;return r.pool.removeLiquidity({pool:a,decreaseLiquidity:b,nft:u,amountA:i,amountB:s,slippage:l,address:o,collectAmountA:d,collectAmountB:k,rewardAmounts:F,txb:re})}static fromData(e){return new n(e)}};var rt=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,o=new Vt(e).decode();return{txType:Hn.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:r,network:a}=t,o;switch(t.txSubType){case"CreatePool":o=Kt.fromData(t.intentionData);break;case"AddLiquidity":o=Qt.fromData(t.intentionData);break;case"IncreaseLiquidity":o=te.fromData(t.intentionData);break;case"DecreaseLiquidity":o=Zt.fromData(t.intentionData);break;case"RemoveLiquidity":o=ee.fromData(t.intentionData);break;case"CollectFee":o=Yt.fromData(t.intentionData);break;case"CollectReward":o=Xt.fromData(t.intentionData);break;case"Burn":o=Jt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:r,network:a})}};var yu=new $t([new Rt,new Ut,new rt,new Ot,new zt,new at,new rt]);export{yu as appHelpers};
1
+ var ar=Object.defineProperty;var xe=(n,t)=>{for(var e in t)ar(n,e,{get:t[e],enumerable:!0})};import{TransactionType as cr}from"@msafe/sui3-utils";import{toHEX as lr}from"@mysten/sui.js/utils";import{TransactionBlock as ir}from"@mysten/sui.js/transactions";import{fromHEX as sr}from"@mysten/sui.js/utils";import or from"sort-keys-recursive";var m=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(or(this.data))}};var nt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,o=ir.from(sr(this.data.content)),i=await r.devInspectTransactionBlock({transactionBlock:o,sender:a.address});if(!(i.effects.status.status==="success"))throw new Error(i.effects.status.error);return o}static fromData(e){return new n(e)}};var at=class{application="cetus";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:cr.Other,txSubType:"CetusTransaction",intentionData:{content:lr(a)}}}async build(t){let{suiClient:e,account:r}=t;return nt.fromData(t.intentionData).build({suiClient:e,account:r})}};import{TransactionType as cn}from"@msafe/sui3-utils";var ne={};xe(ne,{contractId:()=>pr,default:()=>yr,feeObjId:()=>br,roleObjId:()=>dr,status:()=>ur,transaction:()=>mr,upgradeCapObjId:()=>gr,vaultObjId:()=>fr});var mr="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",ur="success",pr="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",dr="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",fr="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",br="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",gr="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",yr={transaction:mr,status:ur,contractId:pr,roleObjId:dr,vaultObjId:fr,feeObjId:br,upgradeCapObjId:gr};var ae={};xe(ae,{contractId:()=>Ir,default:()=>Dr,feeObjId:()=>wr,roleObjId:()=>Tr,status:()=>Sr,transaction:()=>hr,upgradeCapObjId:()=>xr,vaultObjId:()=>Cr});var hr="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sr="success",Ir="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Tr="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Cr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",wr="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",xr="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Dr={transaction:hr,status:Sr,contractId:Ir,roleObjId:Tr,vaultObjId:Cr,feeObjId:wr,upgradeCapObjId:xr};var kr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",vr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Pr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Ar="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Or="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Er="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Br="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",jr="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",De=ne,ke=ae,Rr=new Map([["dev",{env:"dev",rpc:{url:kr},backend:{url:Or},contract:De}],["stg",{env:"stg",rpc:{url:vr},backend:{url:Er},contract:De}],["prev",{env:"prev",rpc:{url:Pr},backend:{url:Br},contract:ke}],["prod",{env:"prod",rpc:{url:Ar},backend:{url:jr},contract:ke}]]);function ve(n,t){let e=Rr.get(n);if(!e)throw new Error(`Env not supported: ${n}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as Mr}from"@mysten/sui.js/client";var p=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:a,context:o}=r;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var ot=class extends p{constructor(){super(11,"Backend is not specified")}};var it=class extends p{constructor(){super(1,"Wallet not connected")}};import O,{AxiosError as Nr}from"axios";var A=class extends p{constructor(t,e){super(10,t,{context:e})}};var st=class n{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Nr)throw new A(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new A(t.data.code)}throw new A(t.status.toString())}async getIncomingStreams(t,e){let r=await O.post(`${this.apiURL}/stream`,{recipient:t,...e});return n.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await O.post(`${this.apiURL}/stream`,{sender:t,...e});return n.parseResponseData(r)}async getStreamHistory(t){let e=await O.post(`${this.apiURL}/stream-events`,t),r=n.parseResponseData(e);return r.data.forEach(a=>{let o=a;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),r}async getAllCoinTypes(t){let e=await O.post(`${this.apiURL}/stream-info`,{address:t});return n.parseResponseData(e)}async getAllRecipients(t,e){let r=await O.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return n.parseResponseData(r)}async getAllSenders(t,e){let r=await O.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return n.parseResponseData(r)}};var E=class n{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new Mr({url:t.rpc.url}),t.backend&&(this._backend=new st(t.backend.url))}static new(t,e){let r=ve(t,e);return new n(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new ot;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 it;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as nn,normalizeStructTag as an,normalizeSuiAddress as Xe}from"@mysten/sui.js/utils";import{normalizeStructTag as se,SUI_TYPE_ARG as Wr}from"@mysten/sui.js/utils";import{Duration as qe}from"luxon";import{TransactionBlock as dt}from"@mysten/sui.js/transactions";import{TransactionBlock as Me}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Le,normalizeStructTag as qr}from"@mysten/sui.js/utils";var oe=50n,ct=10000n,Pe=25n,ie=100000000n;var S=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},_=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},w=class n{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,r){if(r in e)return Reflect.get(e,r);let a=i=>new n(e.result[i]);if(r===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof r=="symbol")return;let o=parseInt(r,10);if(!(Number.isNaN(o)||o<0))return a(o)}})}moveArg(){return this.result}};import{Buffer as Ae}from"buffer";import{normalizeSuiAddress as Lr}from"@mysten/sui.js/utils";var q=class extends p{constructor(t,e){super(3,t,{context:e})}};var lt=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 r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="address")throw new q("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return Lr(Ae.from(r).toString("hex"))}getU64(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="u64")throw new q("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return Ae.from(r).readBigInt64LE()}};import{bcs as Ee}from"@mysten/sui.js/bcs";var f=class extends p{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var Be={groupId:"string",name:"string"},Fr=64;function je(n){return Re(n),Ee.ser(Be,n).toString("base64")}function W(n){let t=Ee.de(Be,n,"base64");return Re(t),t}function Re(n){if(!Oe(n.name))throw new f("Invalid metadata: Name contains unknown character");if(!Oe(n.groupId))throw new f("Invalid metadata: Group ID contains unknown character");if(n.name.length>Fr)throw new f("Invalid metadata: Name exceed max length 64")}function Oe(n){return/^[\x00-\x7F]+$/.test(n)}import{normalizeStructTag as mt}from"@mysten/sui.js/utils";function ut(n,t){return mt(n)===mt(t)}function x(n,t){return mt(n)===mt(t)}var pt="txn.gas";import{nanoid as _r}from"nanoid";function Ne(){return _r()}var v=class n{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:je({name:t.name,groupId:Ne()}),coinType:qr(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 Me,r=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,r),o=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,o[0]),s;a.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let l=0;l<t.recipients.length;l++){let u=t.recipients[l],b=this.amountForRecipient(u,t.numberEpoch),d=this.getStreamFeeLocal(b),[k]=e.splitCoins(i,[e.pure(b+d,"u64")]),[F]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new w(k),flatFeeCoin:new w(F),metadata:t.metadata,recipient:u.address,timeStart:t.startTime,cliff:u.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=n.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:oe,denominator:ct},claimFeePercent:{numerator:Pe,denominator:ct},flatFeePerStream:ie}}async addMergeCoins(t,e){let r;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),r=t.object(e.primaryCoin)):e.primaryCoin===pt?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return ut(r,Le)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:Le,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,o)=>{let i=this.amountForRecipient(o,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 ie}getStreamFeeLocal(t){return t*oe/ct}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Me,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new lt(r).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as _e}from"@mysten/sui.js/transactions";var Fe="0x0000000000000000000000000000000000000000000000000000000000000006";var B=class{constructor(t,e,r){this.moduleName=t;this.config=e;this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(_e.MoveCall({target:r,arguments:e.arguments.map(a=>a instanceof _?a.moveArgs(t):a instanceof S?a.moveArg(t):a instanceof w?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],a=[]){t.add(_e.MoveCall({target:e,arguments:r.map(o=>o instanceof _?o.moveArgs(t):o instanceof S?o.moveArg(t):o instanceof w?o.moveArg():t.pure(o)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new S(t):t}vaultObject(){return new S(this.config.vaultObjId)}roleObject(){return new S(this.config.roleObjId)}feeObject(){return new S(this.config.feeObjId)}clockObject(){return new S(Fe)}};var j=class n extends B{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}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,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_fee,arguments:[a,o,r],typeArgs:[]})}setStreamingFlatFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_flat_fee,arguments:[a,o,r],typeArgs:[]})}setClaimFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_claim_fee,arguments:[a,o,r],typeArgs:[]})}streamingFee(e,r){let a=this.feeObject();return this.addContractCall(e,{method:n.MethodName.streaming_fee,arguments:[a,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:n.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:n.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var I=class n extends B{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}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,r){let a=this.feeObject(),o=this.vaultObject(),i=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),l=this.clockObject();return this.addContractCall(e,{method:n.MethodName.create_stream,arguments:[a,o,i,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,l],typeArgs:[r.coinType]})}setAutoClaim(e,r){let a=this.makeObject(r.streamId);return this.addContractCall(e,{method:n.MethodName.set_auto_claim,arguments:[a,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.cancel_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let a=this.makeObject(r.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream_by_proxy,arguments:[a,o,i,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream_by_proxy}`}};var R=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new j(e,t),this.streamContract=new I(e,t)}feeContract;streamContract;async createStreams(t){let e=v.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new v(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let a=new dt;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new dt;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new dt;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new dt;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var ft=class extends p{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Gr=1e3,bt=class{constructor(t){this.globals=t;this.coinMetaHelper=new ce(t.suiClient),this.createStreamHelper=new R(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new ft(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 f("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-r)/t.steps,i={realTotalAmount:a*t.steps+r,cliffAmount:r,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new f("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new f("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(qe.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:r,interval:qe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...r,coinType:se(r.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,o)=>({...a,coinType:se(a.coinType),coinMeta:r[o]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new f("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new f("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Gr)throw new f("Interval shall be at least 1 second","interval",t.interval)}},ce=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=se(t||Wr);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};import{normalizeStructTag as Ue,normalizeSuiAddress as Tt}from"@mysten/sui.js/utils";import{DateTime as $e}from"luxon";import{TransactionBlock as St}from"@mysten/sui.js/transactions";import{normalizeStructTag as Ge,parseStructTag as zr}from"@mysten/sui.js/utils";import{DateTime as Hr}from"luxon";var gt=class extends p{constructor(){super(7,"Connected wallet is not creator")}};var G=class extends p{constructor(){super(8,"Connected wallet is not recipient")}};var U=class extends p{constructor(t,e){super(6,t,{context:e})}};var g=class extends p{constructor(t,e={}){super(0,t,e)}};var yt=class extends p{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Ur,Duration as $r}from"luxon";var We=(1n<<64n)-1n,ht=1e3;function le(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ht);return Ur.fromMillis(e*ht)}function me(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ht);return $r.fromMillis(e*ht)}var D=class n{constructor(t,e,r){this.globals=t;this.streamId=e;this.rawData=r;this.streamContract=new I(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let r=await n.fetchStreamData(t,e);return new n(t,e,r)}static fromObjectData(t,e,r){let a=n.parseRawStreamData(e,r);return new n(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 n.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new g("Object Id does not align");this.rawData=n.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 gt;let t=new St;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new G;let t=new St;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new G;let e=new St;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new St;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 Ge(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 me(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return W(t).groupId}get name(){let{metadata:t}=this.rawData.config;return W(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return le(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return me(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:le((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===We?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Hr.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let r=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(r)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(r)}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 r=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return n.parseRawStreamData(e,r)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new yt(t):new U(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new U("Unexpected object type",{gotType:r.dataType});let{typeParams:a}=zr(r.type),o=Ge(a[0]),i=r.fields,s=i.config.fields,l=i.status.fields;return{coinType:o,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}};var N=class extends p{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function pe(n){let t=[];for(;await n.hasNext();){let e=await n.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var ue=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)}},M=class{constructor(t){this.requester=t;this.pager=new ue(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 Vr=25;async function fe(n,t,e){let r=new $(t),a=new z(n,r,e);return await pe(a)}var $=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]}},z=class extends M{constructor(e,r,a){super(new de(e,r,a));this.suiClient=e;this.idIter=r;this.options=a}},de=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||Vr,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let o=await this.stringIter.next();o&&t.push(o)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:a}=this;r=e.filter(o=>a?.(o))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}};var It=class n{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new N("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new f("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await fe(t.suiClient,e);return r.forEach(a=>{if(!a)throw new g("stream group object data undefined")}),n.newFromObjectResponse(t,e,r)}static async newFromObjectResponse(t,e,r){let a=await n.parseGroupStreams(t,e,r);return new n(t,a)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),r=e[0],a=!0;return e.forEach(o=>{Qr(r,o)||(a=!1)}),a}async refresh(){let t=await fe(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,r)=>{e.refreshWithData(t[r])})}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,r){let a=r.map((o,i)=>D.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(a.map(o=>o.groupId)).size!==1)throw new N("Not same group ID");if(!this.checkStreamGroup(a))throw new N("Not same stream settings");return a}};function Qr(n,t){return n.name===t.name&&n.groupId===t.groupId&&n.creator===t.creator&&n.start.toMillis()===t.start.toMillis()&&n.interval.toMillis()===t.interval.toMillis()&&n.steps===t.steps&&n.cancelable===t.cancelable}var H=class n{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await Ct.newIncoming(t);return new n(e,t.pageSize)}static async newOutgoing(t){let e=await Ct.newOutgoing(t);return new n(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}},Ct=class n{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await wt.newIncomingQuery(t);return new n(e)}static async newOutgoing(t){let e=await wt.newOutgoingQuery(t);return new n(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 g("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new g("No more results");return t}},wt=class n{constructor(t,e,r,a){this.globals=t;this.recipient=e;this.groupRefs=r;this.query=a;this.current=0;let o=new $(r.flat().map(i=>i.streamId));this.objectIter=new z(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Zr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>Tt(s.recipient)===Tt(r)),i=ze(o);return new n(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=tn(t.query),r=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(r,e),o=ze(a);return new n(t.globals,r,o,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Xr(this.globals,t[0].streamId,this.objectIter);return this.current++,He(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Kr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,Yr(e,this.query)?e:this.doNextRequest()}throw new g("Stream group with no stream")}};function ze(n){let t=new Map;return n.forEach(e=>{let r=t.get(e.groupId);r?(r.push(e),t.set(e.groupId,r)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,r)=>$e.fromISO(r[0].createDate).toMillis()-$e.fromISO(e[0].createDate).toMillis())}function He(n,t){if(t===void 0)return!0;let e=Jr(n,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let r=t.claimable?n.progress.claimable!==0n:n.progress.claimable===0n;return e&&r}return e}function Jr(n,t){return t===void 0?!0:Array.isArray(t)?t.includes(n.progress.status):n.progress.status===t}function Yr(n,t){if(!t)return!0;let e=!1;return n.streams.forEach(r=>{He(r,t)&&(e=!0)}),e}async function Xr(n,t,e){let r=await Ve(e,t);return D.fromObjectData(n,t,r)}async function Kr(n,t,e){let r=[];for(;r.length<t.length;){let a=await Ve(e,t[r.length]);r.push(a)}return It.newFromObjectResponse(n,t,r)}async function Ve(n,t){if(!await n.hasNext())throw new g("object iterator has been consumed");let e=await n.next();if(!e||e.error||e.data===void 0||e.data===null)throw new g("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new g("stream id not aligned");return e}function Zr(n){return{status:be(n?.status),coinType:Qe(n?.coinType),sender:Je(n?.sender)}}function tn(n){return{status:be(n?.status),coinType:Qe(n?.coinType),recipient:Je(n?.recipient)}}function be(n){return n===void 0||n.length===0?"all":Array.isArray(n)?n.reduce((t,e)=>{let r=be(e);return!t||t===r?r:"all"},void 0):en(n)}function en(n){switch(n){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new f("Unknown stream filtered status")}}function Qe(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Ue(t)):void 0:Ue(n)}function Je(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Tt(t)):void 0:Tt(n)}var xt=class extends p{constructor(e,r,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:r,gotAmount:a}});this.coinType=e;this.requestAmount=r;this.gotAmount=a}};var rn=25;async function Ye(n,t,e,r="0x2::sui::SUI",a=rn){let o=new ge(n,t,r,a),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let l=await o.next();l&&(s.push(l),i+=BigInt(l.balance))}if(i<e)throw new xt(r,e,i);return s}var ge=class extends M{constructor(e,r,a,o){super(new ye(e,r,a,o));this.suiClient=e;this.owner=r;this.coinType=a;this.reqPageSize=o}},ye=class{constructor(t,e,r,a){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=a;if(a<=0)throw new g("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 he=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Dt=class{constructor(t){this.account=t}async address(){return this.account.address}},Se=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(ut(t.coinType,nn))return{primaryCoin:pt};if(t.amount<=0)throw new f("Invalid coin request","coinAmount",t.amount);let e=await Ye(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new g("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},kt=class{globals;helper;constructor(t,e){this.globals=E.new(t,e),this.helper=new bt(this.globals)}connectSingleWallet(t){let e=new Se(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new he(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return D.new(this.globals,t)}async getIncomingStreams(t,e=10){return H.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return H.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(r=>an(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>Xe(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>Xe(a))}get wallet(){return this.globals.wallet}builder(){return new R(this.globals)}};import on from"sort-keys-recursive";var vt=class{constructor(t){this.data=t}serialize(){return JSON.stringify(on(this.data))}};var h=class extends vt{application="mpay";getClient(t,e){let r=new kt(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Dt(e)),r}};var V=class extends h{constructor(e){super(e);this.data=e}txType=cn.Stream;txSubType="Cancel";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).cancel()}};import{TransactionType as ln}from"@msafe/sui3-utils";var Q=class extends h{constructor(e){super(e);this.data=e}txType=ln.Stream;txSubType="ClaimByProxy";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as mn}from"@msafe/sui3-utils";var J=class extends h{constructor(e){super(e);this.data=e}txType=mn.Stream;txSubType="Claim";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).claim()}};import{TransactionType as un}from"@msafe/sui3-utils";var Y=class extends h{constructor(e){super(e);this.data=e}txType=un.Stream;txSubType="CreateStream";async build(e){let{network:r,account:a}=e;return this.getClient(r,a).createStream(this.data)}};import{bcs as Ke}from"@mysten/sui.js/bcs";import{normalizeStructTag as pn,normalizeSuiAddress as X}from"@mysten/sui.js/utils";var L=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return X(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return Ke.de(e,new Uint8Array(r))}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 X(t.value.Object.ImmOrOwned.objectId)}return X(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return X(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return X(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 r=t.value.Pure;return Ke.de(e,new Uint8Array(r))}typeArg(t){return pn(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var Pt=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(r=>this.getCreationInfoFromMoveCall(r));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&x(e.target,this.contract.createStreamTarget));if(t.length===0)throw new g("No create stream transactions");return t.map(e=>new L(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:a}=W(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),l=t.decodeInputU64(8),u=t.decodeInputU64(9),b=t.decodeInputU64(10),d=t.decodeInputBool(11),k=t.typeArg(0);return{name:r,groupId:a,recipient:o,timeStart:i,cliff:s,epochInterval:l,totalEpoch:u,amountPerEpoch:b,cancelable:d,coinType:k}}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 f("Stream group not have common info");let r=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:r,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 I(this.globals.envConfig.contract,this.globals)}get feeContract(){return new j(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new v(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 At=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new I(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"&&x(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&x(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Pt(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 L(t,this.txb)}};import{TransactionType as dn}from"@msafe/sui3-utils";var K=class extends h{constructor(e){super(e);this.data=e}txType=dn.Stream;txSubType="SetAutoClaim";async build(e){let{network:r,account:a}=e;return(await this.getClient(r,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Ot=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,a=E.new(e==="sui:mainnet"?"prod":"dev"),i=new At(a,r).decode(),s;switch(i.type){case"CreateStream":s=new Y(i.info);break;case"SetAutoClaim":s=new K({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new J({streamId:i.streamId});break;case"ClaimByProxy":s=new Q({streamId:i.streamId});break;case"Cancel":s=new V({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,r;switch(t.txSubType){case"CreateStream":r=new Y(e);break;case"Claim":r=new J(e);break;case"ClaimByProxy":r=new Q(e);break;case"SetAutoClaim":r=new K(e);break;case"Cancel":r=new V(e);break;default:throw new Error("not implemented")}return r.build({...t})}};import{TransactionDefaultApplication as hn,TransactionSubTypes as Ie}from"@msafe/sui3-utils";import{buildCoinTransferTxb as fn}from"@msafe/sui3-utils";var Et=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return fn(r,this.data,a.address)}static fromData(e){return new n(e)}};import{buildObjectTransferTxb as bn}from"@msafe/sui3-utils";var Bt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return bn(r,this.data,a.address)}static fromData(e){return new n(e)}};import{isSameAddress as gn}from"@msafe/sui3-utils";import{TransactionBlock as yn}from"@mysten/sui.js/transactions";var jt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,a=yn.from(this.data.content);if(!gn(a.blockData.sender,r.address))throw new Error("Invalid sender address");return a}static fromData(e){return new n(e)}};var Rt=class{application;constructor(){this.application=hn}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case Ie.assets.coin.send:a=Et.fromData(t.intentionData);break;case Ie.assets.object.send:a=Bt.fromData(t.intentionData);break;case Ie.others.plain:a=jt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};import{TransactionType as vn}from"@msafe/sui3-utils";import{TransactionType as Z}from"@msafe/sui3-utils";import{bcs as Ze}from"@mysten/sui.js/bcs";import{normalizeStructTag as Tn,normalizeSuiAddress as tt}from"@mysten/sui.js/utils";var Sn={ProtocolPackage:"0x7c9b90b3fda0fa4aa8ee88ae6c4a0b83c773f74936b5354448cb94662e94442d",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},c=Sn;var Nt=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${c.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(c.pool).find(r=>r.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===`${c.ProtocolPackage}::incentive_v2::claim_reward`){let r=new Mt(e,this.txb),a=r.decodeInputU8(4),o=r.decodeInputU8(5),i=this.findPoolByAssetId(a);t.push({coinType:i.coinType,option:o})}}),console.log("decode claims",t),{txType:Z.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryRepay",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Z.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(c.ProtocolPackage));return new Mt(t,this.txb)}},Mt=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.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 tt(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return Ze.de(e,new Uint8Array(r))}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 tt(t.value.Object.ImmOrOwned.objectId)}return tt(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return tt(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return tt(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 r=t.value.Pure;return Ze.de(e,new Uint8Array(r))}typeArg(t){return Tn(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as Cn}from"@mysten/sui.js/transactions";function Te(n,t,e,r){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[n.object("0x06"),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),e,n.pure(r),n.object(c.Incentive),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function tr(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),n.pure(e),n.object(c.Incentive),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function er(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),n.pure(e),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function Ce(n,t,e,r){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[n.object("0x06"),n.object(c.PriceOracle),n.object(c.StorageId),n.object(t.poolId),n.pure(t.assetId),e,n.pure(r),n.object(c.IncentiveV2)],typeArguments:[t.type]}),n}function rr(n,t,e){return n.moveCall({target:`${c.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[n.object("0x06"),n.object(c.IncentiveV2),n.object(t.fondPoolId),n.object(c.StorageId),n.pure(t.assetId),n.pure(e)],typeArguments:[t.type]}),n}var Lt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new Cn;return e.forEach(a=>{let{coinType:o,option:i}=a,s=c.pool[o];if(console.log("build",this.data),!s)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);if(!s.fondPoolId)throw new Error(`${o} not support claim reward.`);rr(r,s,i)}),r}static fromData(e){return new n(e)}};import{TransactionBlock as wn}from"@mysten/sui.js/transactions";var Ft=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new wn;console.log("build",this.data);let o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return er(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as xn}from"@mysten/sui.js/transactions";async function _t(n,t,e){let r=await n.getCoins({owner:t,coinType:e});return console.log("getTokenObjs",t,r),r}var qt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,{coinType:o,amount:i}=this.data,s=new xn;if(console.log("build",this.data),o==="sui"){let[d]=s.splitCoins(s.gas,[i]);return Te(s,c.pool.sui,d,i)}let l=c.pool[o];if(!l)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let u=await _t(r,a.address,l.type);if(!u.data[0])throw new Error(`Insufficient balance for ${l.name} Token`);let b=u.data[0].coinObjectId;if(u.data.length>=2){let d=1;for(;d<u.data.length;)s.mergeCoins(b,[u.data[d].coinObjectId]),d++}return Te(s,l,s.object(b),i)}static fromData(e){return new n(e)}};import{TransactionBlock as Dn}from"@mysten/sui.js/transactions";var Wt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,{coinType:o,amount:i}=this.data,s=new Dn;if(console.log("build",this.data),o==="sui"){let[d]=s.splitCoins(s.gas,[i]);return Ce(s,c.pool.sui,d,i)}let l=c.pool[o];if(!l)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let u=await _t(r,a.address,l.type);if(!u.data[0])throw new Error(`Insufficient balance for ${l.name} Token`);let b=u.data[0].coinObjectId;if(u.data.length>=2){let d=1;for(;d<u.data.length;)s.mergeCoins(b,[u.data[d].coinObjectId]),d++}return Ce(s,l,s.object(b),i)}static fromData(e){return new n(e)}};import{TransactionBlock as kn}from"@mysten/sui.js/transactions";var Gt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new kn;console.log("build",this.data);let o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return tr(a,o,r)}static fromData(e){return new n(e)}};var Ut=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,a=new Nt(e).decode();return{txType:vn.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case"EntryDeposit":a=qt.fromData(t.intentionData);break;case"EntryBorrow":a=Ft.fromData(t.intentionData);break;case"EntryRepay":a=Wt.fromData(t.intentionData);break;case"EntryWithdraw":a=Gt.fromData(t.intentionData);break;case"ClaimReward":a=Lt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};var $t=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}};import{TransactionSubTypes as Pn,TransactionType as An}from"@msafe/sui3-utils";import{TransactionBlock as On}from"@mysten/sui.js/transactions";import{fromHEX as En,toHEX as Bn}from"@mysten/sui.js/utils";import em from"sort-keys-recursive";var jn="msafe-plain-tx",Rn=Pn.others.plain;var zt=class{application;constructor(){this.application=jn}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:An.Other,txSubType:Rn,intentionData:{content:Bn(a)}}}async build(t){let{suiClient:e,account:r}=t,a=On.from(En(t.intentionData.content)),o=await e.devInspectTransactionBlock({transactionBlock:a,sender:r.address});if(!(o.effects.status.status==="success"))throw new Error(o.effects.status.error);return a}};import{TransactionType as Hn}from"@msafe/sui3-utils";import{TransactionType as Mn}from"@msafe/sui3-utils";import{bcs as nr}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ln,normalizeSuiAddress as et}from"@mysten/sui.js/utils";var Ht={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"};var Vt=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(8),a=this.helper.decodeInputU64(9),o=this.helper.decodeInputU32(4),i=this.helper.decodeInputU32(6);return{txType:Mn.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:a,tickLower:o,tickUpper:i}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(""));return new we(t,this.txb)}},we=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.getOwnedObjectId(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 et(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,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 r=t.value.Pure;return nr.de(e,new Uint8Array(r))}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 et(t.value.Object.ImmOrOwned.objectId)}return et(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return et(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return et(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 r=t.value.Pure;return nr.de(e,new Uint8Array(r))}typeArg(t){return Ln(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TurbosSdk as Fn}from"turbos-clmm-sdk";var Qt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Fn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,tickLower:u,tickUpper:b,txb:d}=this.data;return r.pool.addLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,tickLower:u,tickUpper:b,txb:d})}static fromData(e){return new n(e)}};import{TurbosSdk as _n}from"turbos-clmm-sdk";var Jt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new _n(e.network.replace("sui:",""),e.suiClient),{pool:a,nft:o,txb:i}=this.data;return r.nft.burn({pool:a,nft:o,txb:i})}static fromData(e){return new n(e)}};import{TurbosSdk as qn}from"turbos-clmm-sdk";var Yt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new qn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,nft:i,collectAmountA:s,collectAmountB:l,txb:u}=this.data;return r.pool.collectFee({pool:a,address:o,collectAmountA:s,collectAmountB:l,nft:i,txb:u})}static fromData(e){return new n(e)}};import{TurbosSdk as Wn}from"turbos-clmm-sdk";var Xt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Wn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,nft:i,rewardAmounts:s,txb:l}=this.data;return r.pool.collectReward({pool:a,address:o,rewardAmounts:s,nft:i,txb:l})}static fromData(e){return new n(e)}};import{TurbosSdk as Gn}from"turbos-clmm-sdk";var Kt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Gn(e.network.replace("sui:",""),e.suiClient),{fee:a,address:o,tickLower:i,tickUpper:s,sqrtPrice:l,slippage:u,coinTypeA:b,coinTypeB:d,amountA:k,amountB:F,txb:re}=this.data;return r.pool.createPool({fee:a,amountA:k,amountB:F,address:o,tickLower:i,tickUpper:s,sqrtPrice:l,slippage:u,coinTypeA:b,coinTypeB:d,txb:re})}static fromData(e){return new n(e)}};import{TurbosSdk as Un}from"turbos-clmm-sdk";var Zt=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new Un(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,decreaseLiquidity:b,txb:d}=this.data;return r.pool.decreaseLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,nft:u,decreaseLiquidity:b,txb:d})}static fromData(e){return new n(e)}};import{TurbosSdk as $n}from"turbos-clmm-sdk";var te=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new $n(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,txb:b}=this.data;return r.pool.increaseLiquidity({pool:a,slippage:l,address:o,amountA:i,amountB:s,nft:u,txb:b})}static fromData(e){return new n(e)}};import{TurbosSdk as zn}from"turbos-clmm-sdk";var ee=class n extends m{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let r=new zn(e.network.replace("sui:",""),e.suiClient),{pool:a,address:o,amountA:i,amountB:s,slippage:l,nft:u,decreaseLiquidity:b,collectAmountA:d,collectAmountB:k,rewardAmounts:F,txb:re}=this.data;return r.pool.removeLiquidity({pool:a,decreaseLiquidity:b,nft:u,amountA:i,amountB:s,slippage:l,address:o,collectAmountA:d,collectAmountB:k,rewardAmounts:F,txb:re})}static fromData(e){return new n(e)}};var rt=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,o=new Vt(e).decode();return{txType:Hn.Other,txSubType:o.type,intentionData:o.intentionData}}async build(t){let{suiClient:e,account:r,network:a}=t,o;switch(t.txSubType){case"CreatePool":o=Kt.fromData(t.intentionData);break;case"AddLiquidity":o=Qt.fromData(t.intentionData);break;case"IncreaseLiquidity":o=te.fromData(t.intentionData);break;case"DecreaseLiquidity":o=Zt.fromData(t.intentionData);break;case"RemoveLiquidity":o=ee.fromData(t.intentionData);break;case"CollectFee":o=Yt.fromData(t.intentionData);break;case"CollectReward":o=Xt.fromData(t.intentionData);break;case"Burn":o=Jt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:e,account:r,network:a})}};var yu=new $t([new Rt,new Ut,new rt,new Ot,new zt,new at,new rt]);export{yu as appHelpers};
2
2
  //# sourceMappingURL=index.mjs.map