@msafe/sui-app-store 0.0.32 → 0.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ze=Object.defineProperty;var ue=(n,t)=>{for(var e in t)ze(n,e,{get:t[e],enumerable:!0})};import{TransactionType as Je}from"@msafe/sui3-utils";import{toHEX as Ye}from"@mysten/sui.js/utils";import{TransactionBlock as Ve}from"@mysten/sui.js/transactions";import{fromHEX as Qe}from"@mysten/sui.js/utils";import He from"sort-keys-recursive";var p=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(He(this.data))}};var tt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,o=Ve.from(Qe(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 et=class{application="cetus";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:Je.Other,txSubType:"CetusTransaction",intentionData:{content:Ye(a)}}}async build(t){let{suiClient:e,account:r}=t;return tt.fromData(t.intentionData).build({suiClient:e,account:r})}};import{TransactionType as Qr}from"@msafe/sui3-utils";var Ut={};ue(Ut,{contractId:()=>Ze,default:()=>ar,feeObjId:()=>rr,roleObjId:()=>tr,status:()=>Ke,transaction:()=>Xe,upgradeCapObjId:()=>nr,vaultObjId:()=>er});var Xe="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ke="success",Ze="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",tr="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",er="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",rr="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",nr="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",ar={transaction:Xe,status:Ke,contractId:Ze,roleObjId:tr,vaultObjId:er,feeObjId:rr,upgradeCapObjId:nr};var qt={};ue(qt,{contractId:()=>sr,default:()=>pr,feeObjId:()=>mr,roleObjId:()=>cr,status:()=>ir,transaction:()=>or,upgradeCapObjId:()=>ur,vaultObjId:()=>lr});var or="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ir="success",sr="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",cr="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",lr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",mr="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",ur="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",pr={transaction:or,status:ir,contractId:sr,roleObjId:cr,vaultObjId:lr,feeObjId:mr,upgradeCapObjId:ur};var dr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",fr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",gr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",br="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",hr="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",yr="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Sr="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Ir="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",pe=Ut,de=qt,Tr=new Map([["dev",{env:"dev",rpc:{url:dr},backend:{url:hr},contract:pe}],["stg",{env:"stg",rpc:{url:fr},backend:{url:yr},contract:pe}],["prev",{env:"prev",rpc:{url:gr},backend:{url:Sr},contract:de}],["prod",{env:"prod",rpc:{url:br},backend:{url:Ir},contract:de}]]);function fe(n,t){let e=Tr.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 wr}from"@mysten/sui.js/client";var l=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 rt=class extends l{constructor(){super(11,"Backend is not specified")}};var nt=class extends l{constructor(){super(1,"Wallet not connected")}};import E,{AxiosError as Cr}from"axios";var A=class extends l{constructor(t,e){super(10,t,{context:e})}};var at=class n{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Cr)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 E.post(`${this.apiURL}/stream`,{recipient:t,...e});return n.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await E.post(`${this.apiURL}/stream`,{sender:t,...e});return n.parseResponseData(r)}async getStreamHistory(t){let e=await E.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 E.post(`${this.apiURL}/stream-info`,{address:t});return n.parseResponseData(e)}async getAllRecipients(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return n.parseResponseData(r)}async getAllSenders(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return n.parseResponseData(r)}};var O=class n{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new wr({url:t.rpc.url}),t.backend&&(this._backend=new at(t.backend.url))}static new(t,e){let r=fe(t,e);return new n(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new rt;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 nt;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as qr,normalizeStructTag as zr,normalizeSuiAddress as Fe}from"@mysten/sui.js/utils";import{normalizeStructTag as Vt,SUI_TYPE_ARG as Ar}from"@mysten/sui.js/utils";import{Duration as De}from"luxon";import{TransactionBlock as mt}from"@mysten/sui.js/transactions";import{TransactionBlock as we}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as xe,normalizeStructTag as Dr}from"@mysten/sui.js/utils";var zt=50n,ot=10000n,ge=25n,Ht=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 be}from"buffer";import{normalizeSuiAddress as xr}from"@mysten/sui.js/utils";var F=class extends l{constructor(t,e){super(3,t,{context:e})}};var it=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 F("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return xr(be.from(r).toString("hex"))}getU64(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="u64")throw new F("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return be.from(r).readBigInt64LE()}};import{bcs as ye}from"@mysten/sui.js/bcs";var u=class extends l{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var Se={groupId:"string",name:"string"},vr=64;function Ie(n){return Te(n),ye.ser(Se,n).toString("base64")}function G(n){let t=ye.de(Se,n,"base64");return Te(t),t}function Te(n){if(!he(n.name))throw new u("Invalid metadata: Name contains unknown character");if(!he(n.groupId))throw new u("Invalid metadata: Group ID contains unknown character");if(n.name.length>vr)throw new u("Invalid metadata: Name exceed max length 64")}function he(n){return/^[\x00-\x7F]+$/.test(n)}import{normalizeStructTag as st}from"@mysten/sui.js/utils";function ct(n,t){return st(n)===st(t)}function x(n,t){return st(n)===st(t)}var lt="txn.gas";import{nanoid as Pr}from"nanoid";function Ce(){return Pr()}var P=class n{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:Ie({name:t.name,groupId:Ce()}),coinType:Dr(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 we,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 m=0;m<t.recipients.length;m++){let f=t.recipients[m],y=this.amountForRecipient(f,t.numberEpoch),g=this.getStreamFeeLocal(y),[$t]=e.splitCoins(i,[e.pure(y+g,"u64")]),[qe]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new w($t),flatFeeCoin:new w(qe),metadata:t.metadata,recipient:f.address,timeStart:t.startTime,cliff:f.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:f.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=n.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:zt,denominator:ot},claimFeePercent:{numerator:ge,denominator:ot},flatFeePerStream:Ht}}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===lt?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return ct(r,xe)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:xe,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 Ht}getStreamFeeLocal(t){return t*zt/ot}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new we,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new it(r).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as Pe}from"@mysten/sui.js/transactions";var ve="0x0000000000000000000000000000000000000000000000000000000000000006";var k=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(Pe.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(Pe.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(ve)}};var j=class n extends k{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 k{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),m=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,m],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 B=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=P.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new P(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let a=new mt;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new mt;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new mt;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new mt;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var ut=class extends l{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Er=1e3,pt=class{constructor(t){this.globals=t;this.coinMetaHelper=new Qt(t.suiClient),this.createStreamHelper=new B(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new ut(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 u("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 u("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 u("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(De.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:r,interval:De.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:Vt(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:Vt(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 u("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new u("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Er)throw new u("Interval shall be at least 1 second","interval",t.interval)}},Qt=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Vt(t||Ar);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 Oe,normalizeSuiAddress as yt}from"@mysten/sui.js/utils";import{DateTime as ke}from"luxon";import{TransactionBlock as bt}from"@mysten/sui.js/transactions";import{normalizeStructTag as Ee,parseStructTag as jr}from"@mysten/sui.js/utils";import{DateTime as Br}from"luxon";var dt=class extends l{constructor(){super(7,"Connected wallet is not creator")}};var W=class extends l{constructor(){super(8,"Connected wallet is not recipient")}};var L=class extends l{constructor(t,e){super(6,t,{context:e})}};var d=class extends l{constructor(t,e={}){super(0,t,e)}};var ft=class extends l{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Or,Duration as kr}from"luxon";var Ae=(1n<<64n)-1n,gt=1e3;function Jt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/gt);return Or.fromMillis(e*gt)}function Yt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/gt);return kr.fromMillis(e*gt)}var v=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 d("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 dt;let t=new bt;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new W;let t=new bt;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new W;let e=new bt;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new bt;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 Ee(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 Yt(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return G(t).groupId}get name(){let{metadata:t}=this.rawData.config;return G(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Jt(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Yt(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:Jt((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===Ae?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Br.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 ft(t):new L(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new L("Unexpected object type",{gotType:r.dataType});let{typeParams:a}=jr(r.type),o=Ee(a[0]),i=r.fields,s=i.config.fields,m=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:m.status,epochCanceled:BigInt(m.epoch_canceled),epochClaimed:BigInt(m.epoch_claimed)}}}};var R=class extends l{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Kt(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 Xt=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 Xt(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 Rr=25;async function te(n,t,e){let r=new $(t),a=new U(n,r,e);return await Kt(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]}},U=class extends M{constructor(e,r,a){super(new Zt(e,r,a));this.suiClient=e;this.idIter=r;this.options=a}},Zt=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||Rr,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 ht=class n{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new R("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new u("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await te(t.suiClient,e);return r.forEach(a=>{if(!a)throw new d("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=>{Mr(r,o)||(a=!1)}),a}async refresh(){let t=await te(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)=>v.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(a.map(o=>o.groupId)).size!==1)throw new R("Not same group ID");if(!this.checkStreamGroup(a))throw new R("Not same stream settings");return a}};function Mr(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 q=class n{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await St.newIncoming(t);return new n(e,t.pageSize)}static async newOutgoing(t){let e=await St.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}},St=class n{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await It.newIncomingQuery(t);return new n(e)}static async newOutgoing(t){let e=await It.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 d("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new d("No more results");return t}},It=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 U(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Wr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>yt(s.recipient)===yt(r)),i=je(o);return new n(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=Lr(t.query),r=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(r,e),o=je(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 Fr(this.globals,t[0].streamId,this.objectIter);return this.current++,Be(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await Gr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,_r(e,this.query)?e:this.doNextRequest()}throw new d("Stream group with no stream")}};function je(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)=>ke.fromISO(r[0].createDate).toMillis()-ke.fromISO(e[0].createDate).toMillis())}function Be(n,t){if(t===void 0)return!0;let e=Nr(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 Nr(n,t){return t===void 0?!0:Array.isArray(t)?t.includes(n.progress.status):n.progress.status===t}function _r(n,t){if(!t)return!0;let e=!1;return n.streams.forEach(r=>{Be(r,t)&&(e=!0)}),e}async function Fr(n,t,e){let r=await Re(e,t);return v.fromObjectData(n,t,r)}async function Gr(n,t,e){let r=[];for(;r.length<t.length;){let a=await Re(e,t[r.length]);r.push(a)}return ht.newFromObjectResponse(n,t,r)}async function Re(n,t){if(!await n.hasNext())throw new d("object iterator has been consumed");let e=await n.next();if(!e||e.error||e.data===void 0||e.data===null)throw new d("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new d("stream id not aligned");return e}function Wr(n){return{status:ee(n?.status),coinType:Me(n?.coinType),sender:Ne(n?.sender)}}function Lr(n){return{status:ee(n?.status),coinType:Me(n?.coinType),recipient:Ne(n?.recipient)}}function ee(n){return n===void 0||n.length===0?"all":Array.isArray(n)?n.reduce((t,e)=>{let r=ee(e);return!t||t===r?r:"all"},void 0):$r(n)}function $r(n){switch(n){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new u("Unknown stream filtered status")}}function Me(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Oe(t)):void 0:Oe(n)}function Ne(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>yt(t)):void 0:yt(n)}var Tt=class extends l{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 Ur=25;async function _e(n,t,e,r="0x2::sui::SUI",a=Ur){let o=new re(n,t,r,a),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let m=await o.next();m&&(s.push(m),i+=BigInt(m.balance))}if(i<e)throw new Tt(r,e,i);return s}var re=class extends M{constructor(e,r,a,o){super(new ne(e,r,a,o));this.suiClient=e;this.owner=r;this.coinType=a;this.reqPageSize=o}},ne=class{constructor(t,e,r,a){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=a;if(a<=0)throw new d("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 ae=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ct=class{constructor(t){this.account=t}async address(){return this.account.address}},oe=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(ct(t.coinType,qr))return{primaryCoin:lt};if(t.amount<=0)throw new u("Invalid coin request","coinAmount",t.amount);let e=await _e(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new d("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},wt=class{globals;helper;constructor(t,e){this.globals=O.new(t,e),this.helper=new pt(this.globals)}connectSingleWallet(t){let e=new oe(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new ae(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return v.new(this.globals,t)}async getIncomingStreams(t,e=10){return q.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return q.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=>zr(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>Fe(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>Fe(a))}get wallet(){return this.globals.wallet}builder(){return new B(this.globals)}};import Hr from"sort-keys-recursive";var xt=class{constructor(t){this.data=t}serialize(){return JSON.stringify(Hr(this.data))}};var h=class extends xt{application="mpay";getClient(t,e){let r=new wt(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ct(e)),r}};var z=class extends h{constructor(e){super(e);this.data=e}txType=Qr.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 Jr}from"@msafe/sui3-utils";var H=class extends h{constructor(e){super(e);this.data=e}txType=Jr.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 Yr}from"@msafe/sui3-utils";var V=class extends h{constructor(e){super(e);this.data=e}txType=Yr.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 Xr}from"@msafe/sui3-utils";var Q=class extends h{constructor(e){super(e);this.data=e}txType=Xr.Stream;txSubType="CreateStream";async build(e){let{network:r,account:a}=e;return this.getClient(r,a).createStream(this.data)}};import{bcs as Ge}from"@mysten/sui.js/bcs";import{normalizeStructTag as Kr,normalizeSuiAddress as J}from"@mysten/sui.js/utils";var N=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 J(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 Ge.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 J(t.value.Object.ImmOrOwned.objectId)}return J(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return J(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return J(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 Ge.de(e,new Uint8Array(r))}typeArg(t){return Kr(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var vt=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 d("No create stream transactions");return t.map(e=>new N(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:a}=G(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),m=t.decodeInputU64(8),f=t.decodeInputU64(9),y=t.decodeInputU64(10),g=t.decodeInputBool(11),$t=t.typeArg(0);return{name:r,groupId:a,recipient:o,timeStart:i,cliff:s,epochInterval:m,totalEpoch:f,amountPerEpoch:y,cancelable:g,coinType:$t}}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 u("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 P(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 Pt=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()}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 vt(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 N(t,this.txb)}};import{TransactionType as Zr}from"@msafe/sui3-utils";var Y=class extends h{constructor(e){super(e);this.data=e}txType=Zr.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 Dt=class{application="mpay";async deserialize(t){let{chain:e,transactionBlock:r}=t,a=O.new(e==="sui:mainnet"?"prod":"dev"),i=new Pt(a,r).decode(),s;switch(i.type){case"CreateStream":s=new Q(i.info);break;case"SetAutoClaim":s=new Y({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new V({streamId:i.streamId});break;case"ClaimByProxy":s=new H({streamId:i.streamId});break;case"Cancel":s=new z({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 Q(e);break;case"Claim":r=new V(e);break;case"ClaimByProxy":r=new H(e);break;case"SetAutoClaim":r=new Y(e);break;case"Cancel":r=new z(e);break;default:throw new Error("not implemented")}return r.build({...t})}};import{TransactionDefaultApplication as an,TransactionSubTypes as ie}from"@msafe/sui3-utils";import{buildCoinTransferTxb as tn}from"@msafe/sui3-utils";var At=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return tn(r,this.data,a.address)}static fromData(e){return new n(e)}};import{buildObjectTransferTxb as en}from"@msafe/sui3-utils";var Et=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return en(r,this.data,a.address)}static fromData(e){return new n(e)}};import{isSameAddress as rn}from"@msafe/sui3-utils";import{TransactionBlock as nn}from"@mysten/sui.js/transactions";var Ot=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,a=nn.from(this.data.content);if(!rn(a.blockData.sender,r.address))throw new Error("Invalid sender address");return a}static fromData(e){return new n(e)}};var kt=class{application;constructor(){this.application=an}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=At.fromData(t.intentionData);break;case ie.assets.object.send:a=Et.fromData(t.intentionData);break;case ie.others.plain:a=Ot.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};import{TransactionType as dn}from"@msafe/sui3-utils";import{TransactionType as X}from"@msafe/sui3-utils";import{bcs as We}from"@mysten/sui.js/bcs";import{normalizeStructTag as se,normalizeSuiAddress as K}from"@mysten/sui.js/utils";var on={ProtocolPackage:"0xd92d9db3ae5e2e932eda336b15f97e02255d152201d0cf29a29ca0c4fb0205f3",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=on;function Z(n,t){return se(n)===se(t)}var jt=class{constructor(t){this.txb=t}decode(){if(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}isClaimRewardTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Z(this.transactions[0].target,`${c.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Z(this.transactions[0].target,`${c.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Z(this.transactions[0].target,`${c.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Z(this.transactions[0].target,`${c.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Z(this.transactions[0].target,`${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=this.helper.decodeInputU8(4),e=this.helper.decodeInputU8(5),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{coinType:r.coinType,option:e}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions[0];return new ce(t,this.txb)}},ce=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 K(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 We.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 K(t.value.Object.ImmOrOwned.objectId)}return K(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return K(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return K(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 We.de(e,new Uint8Array(r))}typeArg(t){return se(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as cn}from"@mysten/sui.js/transactions";function le(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 Le(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 $e(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 me(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 Ue(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 Bt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,option:r}=this.data,a=new cn,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);if(!o.fondPoolId)throw new Error(`${e} not support claim reward.`);return Ue(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as ln}from"@mysten/sui.js/transactions";var Rt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new ln,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return $e(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as mn}from"@mysten/sui.js/transactions";async function Mt(n,t,e){return await n.getCoins({owner:t,coinType:e})}var Nt=class n extends p{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 mn;if(o==="sui"){let[g]=s.splitCoins(s.gas,[i]);return le(s,c.pool.sui,g,i)}let m=c.pool[o];if(!m)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let f=await Mt(r,a.address,m.type);if(!f.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=f.data[0].coinObjectId;if(f.data.length>=2){let g=1;for(;g<f.data.length;)s.mergeCoins(y,[f.data[g].coinObjectId]),g++}return le(s,m,y,i)}static fromData(e){return new n(e)}};import{TransactionBlock as un}from"@mysten/sui.js/transactions";var _t=class n extends p{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 un;if(o==="sui"){let[g]=s.splitCoins(s.gas,[i]);return me(s,c.pool.sui,g,i)}let m=c.pool[o];if(!m)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let f=await Mt(r,a.address,m.type);if(!f.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=f.data[0].coinObjectId;if(f.data.length>=2){let g=1;for(;g<f.data.length;)s.mergeCoins(y,[f.data[g].coinObjectId]),g++}return me(s,m,y,i)}static fromData(e){return new n(e)}};import{TransactionBlock as pn}from"@mysten/sui.js/transactions";var Ft=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new pn,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return Le(a,o,r)}static fromData(e){return new n(e)}};var Gt=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,a=new jt(e).decode();return{txType:dn.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case"EntryDeposit":a=Nt.fromData(t.intentionData);break;case"EntryBorrow":a=Rt.fromData(t.intentionData);break;case"EntryRepay":a=_t.fromData(t.intentionData);break;case"EntryWithdraw":a=Ft.fromData(t.intentionData);break;case"ClaimReward":a=Bt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};var Wt=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 fn,TransactionType as gn}from"@msafe/sui3-utils";import{TransactionBlock as bn}from"@mysten/sui.js/transactions";import{fromHEX as hn,toHEX as yn}from"@mysten/sui.js/utils";import Al from"sort-keys-recursive";var Sn="msafe-plain-tx",In=fn.others.plain;var Lt=class{application;constructor(){this.application=Sn}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:gn.Other,txSubType:In,intentionData:{content:yn(a)}}}async build(t){let{suiClient:e,account:r}=t,a=bn.from(hn(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}};var Nl=new Wt([new kt,new Gt,new Dt,new Lt,new et]);export{Nl as appHelpers};
|
|
1
|
+
var Ue=Object.defineProperty;var le=(n,t)=>{for(var e in t)Ue(n,e,{get:t[e],enumerable:!0})};import{TransactionType as Ve}from"@msafe/sui3-utils";import{toHEX as Qe}from"@mysten/sui.js/utils";import{TransactionBlock as ze}from"@mysten/sui.js/transactions";import{fromHEX as He}from"@mysten/sui.js/utils";import qe from"sort-keys-recursive";var p=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(qe(this.data))}};var Z=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e,o=ze.from(He(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 tt=class{application="cetus";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:Ve.Other,txSubType:"CetusTransaction",intentionData:{content:Qe(a)}}}async build(t){let{suiClient:e,account:r}=t;return Z.fromData(t.intentionData).build({suiClient:e,account:r})}};import{TransactionType as Hr}from"@msafe/sui3-utils";var $t={};le($t,{contractId:()=>Xe,default:()=>rr,feeObjId:()=>tr,roleObjId:()=>Ke,status:()=>Ye,transaction:()=>Je,upgradeCapObjId:()=>er,vaultObjId:()=>Ze});var Je="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ye="success",Xe="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Ke="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Ze="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",tr="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",er="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",rr={transaction:Je,status:Ye,contractId:Xe,roleObjId:Ke,vaultObjId:Ze,feeObjId:tr,upgradeCapObjId:er};var Ut={};le(Ut,{contractId:()=>or,default:()=>mr,feeObjId:()=>cr,roleObjId:()=>ir,status:()=>ar,transaction:()=>nr,upgradeCapObjId:()=>lr,vaultObjId:()=>sr});var nr="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ar="success",or="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",ir="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",sr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",cr="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",lr="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",mr={transaction:nr,status:ar,contractId:or,roleObjId:ir,vaultObjId:sr,feeObjId:cr,upgradeCapObjId:lr};var ur="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",pr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",dr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",fr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",gr="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",br="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",hr="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",yr="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",me=$t,ue=Ut,Sr=new Map([["dev",{env:"dev",rpc:{url:ur},backend:{url:gr},contract:me}],["stg",{env:"stg",rpc:{url:pr},backend:{url:br},contract:me}],["prev",{env:"prev",rpc:{url:dr},backend:{url:hr},contract:ue}],["prod",{env:"prod",rpc:{url:fr},backend:{url:yr},contract:ue}]]);function pe(n,t){let e=Sr.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 Tr}from"@mysten/sui.js/client";var l=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 et=class extends l{constructor(){super(11,"Backend is not specified")}};var rt=class extends l{constructor(){super(1,"Wallet not connected")}};import E,{AxiosError as Ir}from"axios";var A=class extends l{constructor(t,e){super(10,t,{context:e})}};var nt=class n{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Ir)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 E.post(`${this.apiURL}/stream`,{recipient:t,...e});return n.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await E.post(`${this.apiURL}/stream`,{sender:t,...e});return n.parseResponseData(r)}async getStreamHistory(t){let e=await E.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 E.post(`${this.apiURL}/stream-info`,{address:t});return n.parseResponseData(e)}async getAllRecipients(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return n.parseResponseData(r)}async getAllSenders(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return n.parseResponseData(r)}};var O=class n{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new Tr({url:t.rpc.url}),t.backend&&(this._backend=new nt(t.backend.url))}static new(t,e){let r=pe(t,e);return new n(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new et;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 rt;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as $r,normalizeStructTag as Ur,normalizeSuiAddress as Ne}from"@mysten/sui.js/utils";import{normalizeStructTag as Ht,SUI_TYPE_ARG as Pr}from"@mysten/sui.js/utils";import{Duration as ve}from"luxon";import{TransactionBlock as lt}from"@mysten/sui.js/transactions";import{TransactionBlock as Te}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Ce,normalizeStructTag as vr}from"@mysten/sui.js/utils";var qt=50n,at=10000n,de=25n,zt=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 fe}from"buffer";import{normalizeSuiAddress as Cr}from"@mysten/sui.js/utils";var F=class extends l{constructor(t,e){super(3,t,{context:e})}};var ot=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 F("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return Cr(fe.from(r).toString("hex"))}getU64(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="u64")throw new F("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return fe.from(r).readBigInt64LE()}};import{bcs as be}from"@mysten/sui.js/bcs";var u=class extends l{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var he={groupId:"string",name:"string"},wr=64;function ye(n){return Se(n),be.ser(he,n).toString("base64")}function W(n){let t=be.de(he,n,"base64");return Se(t),t}function Se(n){if(!ge(n.name))throw new u("Invalid metadata: Name contains unknown character");if(!ge(n.groupId))throw new u("Invalid metadata: Group ID contains unknown character");if(n.name.length>wr)throw new u("Invalid metadata: Name exceed max length 64")}function ge(n){return/^[\x00-\x7F]+$/.test(n)}import{normalizeStructTag as it}from"@mysten/sui.js/utils";function st(n,t){return it(n)===it(t)}function x(n,t){return it(n)===it(t)}var ct="txn.gas";import{nanoid as xr}from"nanoid";function Ie(){return xr()}var P=class n{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:ye({name:t.name,groupId:Ie()}),coinType:vr(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 Te,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 m=0;m<t.recipients.length;m++){let f=t.recipients[m],y=this.amountForRecipient(f,t.numberEpoch),g=this.getStreamFeeLocal(y),[Lt]=e.splitCoins(i,[e.pure(y+g,"u64")]),[$e]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new w(Lt),flatFeeCoin:new w($e),metadata:t.metadata,recipient:f.address,timeStart:t.startTime,cliff:f.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:f.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=n.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:qt,denominator:at},claimFeePercent:{numerator:de,denominator:at},flatFeePerStream:zt}}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===ct?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return st(r,Ce)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:Ce,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 zt}getStreamFeeLocal(t){return t*qt/at}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Te,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new ot(r).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as xe}from"@mysten/sui.js/transactions";var we="0x0000000000000000000000000000000000000000000000000000000000000006";var k=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(xe.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(xe.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(we)}};var j=class n extends k{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 k{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),m=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,m],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 B=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=P.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new P(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let a=new lt;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new lt;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new lt;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new lt;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var mt=class extends l{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Dr=1e3,ut=class{constructor(t){this.globals=t;this.coinMetaHelper=new Vt(t.suiClient),this.createStreamHelper=new B(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mt(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 u("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 u("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 u("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(ve.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:r,interval:ve.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:Ht(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:Ht(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 u("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new u("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Dr)throw new u("Interval shall be at least 1 second","interval",t.interval)}},Vt=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Ht(t||Pr);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 Ae,normalizeSuiAddress as ht}from"@mysten/sui.js/utils";import{DateTime as Ee}from"luxon";import{TransactionBlock as gt}from"@mysten/sui.js/transactions";import{normalizeStructTag as De,parseStructTag as Or}from"@mysten/sui.js/utils";import{DateTime as kr}from"luxon";var pt=class extends l{constructor(){super(7,"Connected wallet is not creator")}};var G=class extends l{constructor(){super(8,"Connected wallet is not recipient")}};var L=class extends l{constructor(t,e){super(6,t,{context:e})}};var d=class extends l{constructor(t,e={}){super(0,t,e)}};var dt=class extends l{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as Ar,Duration as Er}from"luxon";var Pe=(1n<<64n)-1n,ft=1e3;function Qt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ft);return Ar.fromMillis(e*ft)}function Jt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ft);return Er.fromMillis(e*ft)}var v=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 d("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 pt;let t=new gt;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 gt;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 gt;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new gt;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 De(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 Jt(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 Qt(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Jt(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:Qt((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===Pe?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=kr.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 dt(t):new L(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new L("Unexpected object type",{gotType:r.dataType});let{typeParams:a}=Or(r.type),o=De(a[0]),i=r.fields,s=i.config.fields,m=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:m.status,epochCanceled:BigInt(m.epoch_canceled),epochClaimed:BigInt(m.epoch_claimed)}}}};var R=class extends l{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Xt(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 Yt=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 Yt(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 jr=25;async function Zt(n,t,e){let r=new $(t),a=new U(n,r,e);return await Xt(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]}},U=class extends M{constructor(e,r,a){super(new Kt(e,r,a));this.suiClient=e;this.idIter=r;this.options=a}},Kt=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||jr,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 bt=class n{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new R("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new u("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await Zt(t.suiClient,e);return r.forEach(a=>{if(!a)throw new d("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=>{Br(r,o)||(a=!1)}),a}async refresh(){let t=await Zt(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)=>v.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(a.map(o=>o.groupId)).size!==1)throw new R("Not same group ID");if(!this.checkStreamGroup(a))throw new R("Not same stream settings");return a}};function Br(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 q=class n{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await yt.newIncoming(t);return new n(e,t.pageSize)}static async newOutgoing(t){let e=await yt.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}},yt=class n{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await St.newIncomingQuery(t);return new n(e)}static async newOutgoing(t){let e=await St.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 d("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new d("No more results");return t}},St=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 U(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=Fr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>ht(s.recipient)===ht(r)),i=Oe(o);return new n(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=Wr(t.query),r=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(r,e),o=Oe(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 Nr(this.globals,t[0].streamId,this.objectIter);return this.current++,ke(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await _r(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,Mr(e,this.query)?e:this.doNextRequest()}throw new d("Stream group with no stream")}};function Oe(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)=>Ee.fromISO(r[0].createDate).toMillis()-Ee.fromISO(e[0].createDate).toMillis())}function ke(n,t){if(t===void 0)return!0;let e=Rr(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 Rr(n,t){return t===void 0?!0:Array.isArray(t)?t.includes(n.progress.status):n.progress.status===t}function Mr(n,t){if(!t)return!0;let e=!1;return n.streams.forEach(r=>{ke(r,t)&&(e=!0)}),e}async function Nr(n,t,e){let r=await je(e,t);return v.fromObjectData(n,t,r)}async function _r(n,t,e){let r=[];for(;r.length<t.length;){let a=await je(e,t[r.length]);r.push(a)}return bt.newFromObjectResponse(n,t,r)}async function je(n,t){if(!await n.hasNext())throw new d("object iterator has been consumed");let e=await n.next();if(!e||e.error||e.data===void 0||e.data===null)throw new d("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new d("stream id not aligned");return e}function Fr(n){return{status:te(n?.status),coinType:Be(n?.coinType),sender:Re(n?.sender)}}function Wr(n){return{status:te(n?.status),coinType:Be(n?.coinType),recipient:Re(n?.recipient)}}function te(n){return n===void 0||n.length===0?"all":Array.isArray(n)?n.reduce((t,e)=>{let r=te(e);return!t||t===r?r:"all"},void 0):Gr(n)}function Gr(n){switch(n){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new u("Unknown stream filtered status")}}function Be(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>Ae(t)):void 0:Ae(n)}function Re(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>ht(t)):void 0:ht(n)}var It=class extends l{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 Lr=25;async function Me(n,t,e,r="0x2::sui::SUI",a=Lr){let o=new ee(n,t,r,a),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let m=await o.next();m&&(s.push(m),i+=BigInt(m.balance))}if(i<e)throw new It(r,e,i);return s}var ee=class extends M{constructor(e,r,a,o){super(new re(e,r,a,o));this.suiClient=e;this.owner=r;this.coinType=a;this.reqPageSize=o}},re=class{constructor(t,e,r,a){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=a;if(a<=0)throw new d("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 ne=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Tt=class{constructor(t){this.account=t}async address(){return this.account.address}},ae=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(st(t.coinType,$r))return{primaryCoin:ct};if(t.amount<=0)throw new u("Invalid coin request","coinAmount",t.amount);let e=await Me(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new d("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Ct=class{globals;helper;constructor(t,e){this.globals=O.new(t,e),this.helper=new ut(this.globals)}connectSingleWallet(t){let e=new ae(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new ne(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return v.new(this.globals,t)}async getIncomingStreams(t,e=10){return q.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return q.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=>Ur(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>Ne(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>Ne(a))}get wallet(){return this.globals.wallet}builder(){return new B(this.globals)}};import qr from"sort-keys-recursive";var wt=class{constructor(t){this.data=t}serialize(){return JSON.stringify(qr(this.data))}};var h=class extends wt{application="mpay";getClient(t,e){let r=new Ct(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Tt(e)),r}};var z=class extends h{constructor(e){super(e);this.data=e}txType=Hr.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 Vr}from"@msafe/sui3-utils";var H=class extends h{constructor(e){super(e);this.data=e}txType=Vr.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 Qr}from"@msafe/sui3-utils";var V=class extends h{constructor(e){super(e);this.data=e}txType=Qr.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 Jr}from"@msafe/sui3-utils";var Q=class extends h{constructor(e){super(e);this.data=e}txType=Jr.Stream;txSubType="CreateStream";async build(e){let{network:r,account:a}=e;return this.getClient(r,a).createStream(this.data)}};import{bcs as _e}from"@mysten/sui.js/bcs";import{normalizeStructTag as Yr,normalizeSuiAddress as J}from"@mysten/sui.js/utils";var N=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 J(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 _e.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 J(t.value.Object.ImmOrOwned.objectId)}return J(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return J(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return J(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 _e.de(e,new Uint8Array(r))}typeArg(t){return Yr(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var xt=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 d("No create stream transactions");return t.map(e=>new N(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),m=t.decodeInputU64(8),f=t.decodeInputU64(9),y=t.decodeInputU64(10),g=t.decodeInputBool(11),Lt=t.typeArg(0);return{name:r,groupId:a,recipient:o,timeStart:i,cliff:s,epochInterval:m,totalEpoch:f,amountPerEpoch:y,cancelable:g,coinType:Lt}}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 u("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 P(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 vt=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()}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 xt(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 N(t,this.txb)}};import{TransactionType as Xr}from"@msafe/sui3-utils";var Y=class extends h{constructor(e){super(e);this.data=e}txType=Xr.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 Pt=class{application="mpay";async deserialize(t){let{chain:e,transactionBlock:r}=t,a=O.new(e==="sui:mainnet"?"prod":"dev"),i=new vt(a,r).decode(),s;switch(i.type){case"CreateStream":s=new Q(i.info);break;case"SetAutoClaim":s=new Y({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new V({streamId:i.streamId});break;case"ClaimByProxy":s=new H({streamId:i.streamId});break;case"Cancel":s=new z({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 Q(e);break;case"Claim":r=new V(e);break;case"ClaimByProxy":r=new H(e);break;case"SetAutoClaim":r=new Y(e);break;case"Cancel":r=new z(e);break;default:throw new Error("not implemented")}return r.build({...t})}};import{TransactionDefaultApplication as rn,TransactionSubTypes as oe}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Kr}from"@msafe/sui3-utils";var Dt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return Kr(r,this.data,a.address)}static fromData(e){return new n(e)}};import{buildObjectTransferTxb as Zr}from"@msafe/sui3-utils";var At=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return Zr(r,this.data,a.address)}static fromData(e){return new n(e)}};import{isSameAddress as tn}from"@msafe/sui3-utils";import{TransactionBlock as en}from"@mysten/sui.js/transactions";var Et=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,a=en.from(this.data.content);if(!tn(a.blockData.sender,r.address))throw new Error("Invalid sender address");return a}static fromData(e){return new n(e)}};var Ot=class{application;constructor(){this.application=rn}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 oe.assets.coin.send:a=Dt.fromData(t.intentionData);break;case oe.assets.object.send:a=At.fromData(t.intentionData);break;case oe.others.plain:a=Et.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};import{TransactionType as pn}from"@msafe/sui3-utils";import{TransactionType as X}from"@msafe/sui3-utils";import{bcs as Fe}from"@mysten/sui.js/bcs";import{normalizeStructTag as on,normalizeSuiAddress as K}from"@mysten/sui.js/utils";var nn={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=nn;var kt=class{constructor(t){this.txb=t}decode(){if(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=this.helper.decodeInputU8(4),e=this.helper.decodeInputU8(5),r=this.findPoolByAssetId(t);return{txType:X.Other,type:"ClaimReward",intentionData:{coinType:r.coinType,option:e}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:X.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:X.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:X.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:X.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 ie(t,this.txb)}},ie=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 K(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 Fe.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 K(t.value.Object.ImmOrOwned.objectId)}return K(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return K(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return K(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 Fe.de(e,new Uint8Array(r))}typeArg(t){return on(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as sn}from"@mysten/sui.js/transactions";function se(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 We(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 Ge(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 Le(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 jt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,option:r}=this.data,a=new sn,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);if(!o.fondPoolId)throw new Error(`${e} not support claim reward.`);return Le(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as cn}from"@mysten/sui.js/transactions";var Bt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new cn,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return Ge(a,o,r)}static fromData(e){return new n(e)}};import{TransactionBlock as ln}from"@mysten/sui.js/transactions";async function Rt(n,t,e){return await n.getCoins({owner:t,coinType:e})}var Mt=class n extends p{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 ln;if(o==="sui"){let[g]=s.splitCoins(s.gas,[i]);return se(s,c.pool.sui,g,i)}let m=c.pool[o];if(!m)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let f=await Rt(r,a.address,m.type);if(!f.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=f.data[0].coinObjectId;if(f.data.length>=2){let g=1;for(;g<f.data.length;)s.mergeCoins(y,[f.data[g].coinObjectId]),g++}return se(s,m,y,i)}static fromData(e){return new n(e)}};import{TransactionBlock as mn}from"@mysten/sui.js/transactions";var Nt=class n extends p{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 mn;if(o==="sui"){let[g]=s.splitCoins(s.gas,[i]);return ce(s,c.pool.sui,g,i)}let m=c.pool[o];if(!m)throw new Error(`${o} not support, please use ${Object.keys(c.pool).join(", ")}.`);let f=await Rt(r,a.address,m.type);if(!f.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=f.data[0].coinObjectId;if(f.data.length>=2){let g=1;for(;g<f.data.length;)s.mergeCoins(y,[f.data[g].coinObjectId]),g++}return ce(s,m,y,i)}static fromData(e){return new n(e)}};import{TransactionBlock as un}from"@mysten/sui.js/transactions";var _t=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,a=new un,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return We(a,o,r)}static fromData(e){return new n(e)}};var Ft=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,a=new kt(e).decode();return{txType:pn.Other,txSubType:a.type,intentionData:a.intentionData}}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case"EntryDeposit":a=Mt.fromData(t.intentionData);break;case"EntryBorrow":a=Bt.fromData(t.intentionData);break;case"EntryRepay":a=Nt.fromData(t.intentionData);break;case"EntryWithdraw":a=_t.fromData(t.intentionData);break;case"ClaimReward":a=jt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};var Wt=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 dn,TransactionType as fn}from"@msafe/sui3-utils";import{TransactionBlock as gn}from"@mysten/sui.js/transactions";import{fromHEX as bn,toHEX as hn}from"@mysten/sui.js/utils";import Dl from"sort-keys-recursive";var yn="msafe-plain-tx",Sn=dn.others.plain;var Gt=class{application;constructor(){this.application=yn}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:fn.Other,txSubType:Sn,intentionData:{content:hn(a)}}}async build(t){let{suiClient:e,account:r}=t,a=gn.from(bn(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}};var Ml=new Wt([new Ot,new Ft,new Pt,new Gt,new tt]);export{Ml as appHelpers};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|