@msafe/sui-app-store 0.0.28 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var we=Object.defineProperty;var Qt=(a,t)=>{for(var e in t)we(a,e,{get:t[e],enumerable:!0})};import{TransactionType as Ir}from"@msafe/sui3-utils";var Et={};Qt(Et,{contractId:()=>ve,default:()=>ke,feeObjId:()=>Ee,roleObjId:()=>Oe,status:()=>Ae,transaction:()=>xe,upgradeCapObjId:()=>De,vaultObjId:()=>Pe});var xe="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ae="success",ve="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Oe="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Pe="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Ee="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",De="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",ke={transaction:xe,status:Ae,contractId:ve,roleObjId:Oe,vaultObjId:Pe,feeObjId:Ee,upgradeCapObjId:De};var Dt={};Qt(Dt,{contractId:()=>je,default:()=>Ge,feeObjId:()=>_e,roleObjId:()=>Be,status:()=>Me,transaction:()=>Re,upgradeCapObjId:()=>Fe,vaultObjId:()=>Ne});var Re="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Me="success",je="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Be="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ne="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",_e="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Fe="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ge={transaction:Re,status:Me,contractId:je,roleObjId:Be,vaultObjId:Ne,feeObjId:_e,upgradeCapObjId:Fe};var Le="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",We="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",qe="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",ze="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Ue="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",$e="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",He="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Qe="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Jt=Et,Vt=Dt,Je=new Map([["dev",{env:"dev",rpc:{url:Le},backend:{url:Ue},contract:Jt}],["stg",{env:"stg",rpc:{url:We},backend:{url:$e},contract:Jt}],["prev",{env:"prev",rpc:{url:qe},backend:{url:He},contract:Vt}],["prod",{env:"prod",rpc:{url:ze},backend:{url:Qe},contract:Vt}]]);function Yt(a,t){let e=Je.get(a);if(!e)throw new Error(`Env not supported: ${a}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as Ye}from"@mysten/sui.js/client";var c=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:o}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var V=class extends c{constructor(){super(11,"Backend is not specified")}};var Y=class extends c{constructor(){super(1,"Wallet not connected")}};import v,{AxiosError as Ve}from"axios";var A=class extends c{constructor(t,e){super(10,t,{context:e})}};var X=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof Ve)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 v.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await v.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(r)}async getStreamHistory(t){let e=await v.post(`${this.apiURL}/stream-events`,t),r=a.parseResponseData(e);return r.data.forEach(n=>{let o=n;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 v.post(`${this.apiURL}/stream-info`,{address:t});return a.parseResponseData(e)}async getAllRecipients(t,e){let r=await v.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(r)}async getAllSenders(t,e){let r=await v.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(r)}};var O=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new Ye({url:t.rpc.url}),t.backend&&(this._backend=new X(t.backend.url))}static new(t,e){let r=Yt(t,e);return new a(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new V;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 Y;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Sr,normalizeStructTag as br,normalizeSuiAddress as Ce}from"@mysten/sui.js/utils";import{normalizeStructTag as Mt,SUI_TYPE_ARG as er}from"@mysten/sui.js/utils";import{Duration as me}from"luxon";import{TransactionBlock as at}from"@mysten/sui.js/transactions";import{TransactionBlock as oe}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as ie,normalizeStructTag as tr}from"@mysten/sui.js/utils";var kt=50n,K=10000n,Xt=25n,Rt=100000000n;var f=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},j=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},b=class a{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,r){if(r in e)return Reflect.get(e,r);let n=i=>new a(e.result[i]);if(r===Symbol.iterator)return function*(){let i=0;for(;;)yield n(i),i++};if(typeof r=="symbol")return;let o=parseInt(r,10);if(!(Number.isNaN(o)||o<0))return n(o)}})}moveArg(){return this.result}};import{Buffer as Kt}from"buffer";import{normalizeSuiAddress as Xe}from"@mysten/sui.js/utils";var B=class extends c{constructor(t,e){super(3,t,{context:e})}};var Z=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,n]=this.getValue(t,e);if(n!=="address")throw new B("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return Xe(Kt.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new B("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Kt.from(r).readBigInt64LE()}};import{bcs as te}from"@mysten/sui.js/bcs";var m=class extends c{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var ee={groupId:"string",name:"string"},Ke=64;function re(a){return ae(a),te.ser(ee,a).toString("base64")}function N(a){let t=te.de(ee,a,"base64");return ae(t),t}function ae(a){if(!Zt(a.name))throw new m("Invalid metadata: Name contains unknown character");if(!Zt(a.groupId))throw new m("Invalid metadata: Group ID contains unknown character");if(a.name.length>Ke)throw new m("Invalid metadata: Name exceed max length 64")}function Zt(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as tt}from"@mysten/sui.js/utils";function et(a,t){return tt(a)===tt(t)}function y(a,t){return tt(a)===tt(t)}var rt="txn.gas";import{nanoid as Ze}from"nanoid";function ne(){return Ze()}var T=class a{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:re({name:t.name,groupId:ne()}),coinType:tr(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 oe,r=this.calculateFeesInternal(t),n=this.getCreateStreamCoinRequests(t,r),o=await this.wallet.requestCoins(n),i=await this.addMergeCoins(e,o[0]),s;n.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let u=0;u<t.recipients.length;u++){let x=t.recipients[u],J=this.amountForRecipient(x,t.numberEpoch),Ot=this.getStreamFeeLocal(J),[Pt]=e.splitCoins(i,[e.pure(J+Ot,"u64")]),[Te]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new b(Pt),flatFeeCoin:new b(Te),metadata:t.metadata,recipient:x.address,timeStart:t.startTime,cliff:x.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:x.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:kt,denominator:K},claimFeePercent:{numerator:Xt,denominator:K},flatFeePerStream:Rt}}async addMergeCoins(t,e){let r;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(n=>t.object(n))),r=t.object(e.primaryCoin)):e.primaryCoin===rt?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return et(r,ie)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:ie,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((n,o)=>{let i=this.amountForRecipient(o,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:n.totalAmount+i,streamFeeAmount:n.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 Rt}getStreamFeeLocal(t){return t*kt/K}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new oe,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new Z(r).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as ce}from"@mysten/sui.js/transactions";var se="0x0000000000000000000000000000000000000000000000000000000000000006";var P=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(ce.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof j?n.moveArgs(t):n instanceof f?n.moveArg(t):n instanceof b?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(ce.MoveCall({target:e,arguments:r.map(o=>o instanceof j?o.moveArgs(t):o instanceof f?o.moveArg(t):o instanceof b?o.moveArg():t.pure(o)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new f(t):t}vaultObject(){return new f(this.config.vaultObjId)}roleObject(){return new f(this.config.roleObjId)}feeObject(){return new f(this.config.feeObjId)}clockObject(){return new f(se)}};var E=class a extends P{constructor(e,r){super(a.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 n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[n,o,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[n,o,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[n,o,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var g=class a extends P{constructor(e,r){super(a.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 n=this.feeObject(),o=this.vaultObject(),i=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:a.MethodName.create_stream,arguments:[n,o,i,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[n,o],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[n,o],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[n,o,i,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var D=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new E(e,t),this.streamContract=new g(e,t)}feeContract;streamContract;async createStreams(t){let e=T.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new T(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new at;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new at;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new at;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new at;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var nt=class extends c{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var rr=1e3,ot=class{constructor(t){this.globals=t;this.coinMetaHelper=new jt(t.suiClient),this.createStreamHelper=new D(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new nt(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 m("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new m("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 m("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(me.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:me.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:Mt(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,o)=>({...n,coinType:Mt(n.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 m("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new m("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<rr)throw new m("Interval shall be at least 1 second","interval",t.interval)}},jt=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=Mt(t||er);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 pe,normalizeSuiAddress as ut}from"@mysten/sui.js/utils";import{DateTime as de}from"luxon";import{TransactionBlock as mt}from"@mysten/sui.js/transactions";import{normalizeStructTag as ue,parseStructTag as or}from"@mysten/sui.js/utils";import{DateTime as ir}from"luxon";var it=class extends c{constructor(){super(7,"Connected wallet is not creator")}};var _=class extends c{constructor(){super(8,"Connected wallet is not recipient")}};var F=class extends c{constructor(t,e){super(6,t,{context:e})}};var l=class extends c{constructor(t,e={}){super(0,t,e)}};var st=class extends c{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as ar,Duration as nr}from"luxon";var le=(1n<<64n)-1n,ct=1e3;function Bt(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/ct);return ar.fromMillis(e*ct)}function Nt(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/ct);return nr.fromMillis(e*ct)}var C=class a{constructor(t,e,r){this.globals=t;this.streamId=e;this.rawData=r;this.streamContract=new g(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let r=await a.fetchStreamData(t,e);return new a(t,e,r)}static fromObjectData(t,e,r){let n=a.parseRawStreamData(e,r);return new a(t,e,n)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new l("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new it;let t=new mt;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new _;let t=new mt;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new _;let e=new mt;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new mt;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 ue(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 Nt(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return N(t).groupId}get name(){let{metadata:t}=this.rawData.config;return N(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Bt(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Nt(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:Bt((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===le?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=ir.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 a.parseRawStreamData(e,r)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new st(t):new F(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new F("Unexpected object type",{gotType:r.dataType});let{typeParams:n}=or(r.type),o=ue(n[0]),i=r.fields,s=i.config.fields,u=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:u.status,epochCanceled:BigInt(u.epoch_canceled),epochClaimed:BigInt(u.epoch_claimed)}}}};var k=class extends c{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Ft(a){let t=[];for(;await a.hasNext();){let e=await a.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var _t=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)}},R=class{constructor(t){this.requester=t;this.pager=new _t(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 sr=25;async function Lt(a,t,e){let r=new G(t),n=new L(a,r,e);return await Ft(n)}var G=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]}},L=class extends R{constructor(e,r,n){super(new Gt(e,r,n));this.suiClient=e;this.idIter=r;this.options=n}},Gt=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||sr,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:n}=this;r=e.filter(o=>n?.(o))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}};var lt=class a{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new k("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new m("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await Lt(t.suiClient,e);return r.forEach(n=>{if(!n)throw new l("stream group object data undefined")}),a.newFromObjectResponse(t,e,r)}static async newFromObjectResponse(t,e,r){let n=await a.parseGroupStreams(t,e,r);return new a(t,n)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),r=e[0],n=!0;return e.forEach(o=>{cr(r,o)||(n=!1)}),n}async refresh(){let t=await Lt(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 n=r.map((o,i)=>C.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(n.map(o=>o.groupId)).size!==1)throw new k("Not same group ID");if(!this.checkStreamGroup(n))throw new k("Not same stream settings");return n}};function cr(a,t){return a.name===t.name&&a.groupId===t.groupId&&a.creator===t.creator&&a.start.toMillis()===t.start.toMillis()&&a.interval.toMillis()===t.interval.toMillis()&&a.steps===t.steps&&a.cancelable===t.cancelable}var W=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await pt.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await pt.newOutgoing(t);return new a(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},pt=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await dt.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await dt.newOutgoingQuery(t);return new a(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new l("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new l("No more results");return t}},dt=class a{constructor(t,e,r,n){this.globals=t;this.recipient=e;this.groupRefs=r;this.query=n;this.current=0;let o=new G(r.flat().map(i=>i.streamId));this.objectIter=new L(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=dr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>ut(s.recipient)===ut(r)),i=fe(o);return new a(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=fr(t.query),r=await t.globals.walletAddress(),n=await t.globals.backend.getOutgoingStreams(r,e),o=fe(n);return new a(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 ur(this.globals,t[0].streamId,this.objectIter);return this.current++,ge(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await pr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,lr(e,this.query)?e:this.doNextRequest()}throw new l("Stream group with no stream")}};function fe(a){let t=new Map;return a.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)=>de.fromISO(r[0].createDate).toMillis()-de.fromISO(e[0].createDate).toMillis())}function ge(a,t){if(t===void 0)return!0;let e=mr(a,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let r=t.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return e&&r}return e}function mr(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function lr(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(r=>{ge(r,t)&&(e=!0)}),e}async function ur(a,t,e){let r=await he(e,t);return C.fromObjectData(a,t,r)}async function pr(a,t,e){let r=[];for(;r.length<t.length;){let n=await he(e,t[r.length]);r.push(n)}return lt.newFromObjectResponse(a,t,r)}async function he(a,t){if(!await a.hasNext())throw new l("object iterator has been consumed");let e=await a.next();if(!e||e.error||e.data===void 0||e.data===null)throw new l("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new l("stream id not aligned");return e}function dr(a){return{status:Wt(a?.status),coinType:Se(a?.coinType),sender:be(a?.sender)}}function fr(a){return{status:Wt(a?.status),coinType:Se(a?.coinType),recipient:be(a?.recipient)}}function Wt(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let r=Wt(e);return!t||t===r?r:"all"},void 0):gr(a)}function gr(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new m("Unknown stream filtered status")}}function Se(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>pe(t)):void 0:pe(a)}function be(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>ut(t)):void 0:ut(a)}var ft=class extends c{constructor(e,r,n){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:r,gotAmount:n}});this.coinType=e;this.requestAmount=r;this.gotAmount=n}};var hr=25;async function ye(a,t,e,r="0x2::sui::SUI",n=hr){let o=new qt(a,t,r,n),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let u=await o.next();u&&(s.push(u),i+=BigInt(u.balance))}if(i<e)throw new ft(r,e,i);return s}var qt=class extends R{constructor(e,r,n,o){super(new zt(e,r,n,o));this.suiClient=e;this.owner=r;this.coinType=n;this.reqPageSize=o}},zt=class{constructor(t,e,r,n){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=n;if(n<=0)throw new l("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 Ut=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},gt=class{constructor(t){this.account=t}async address(){return this.account.address}},$t=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(et(t.coinType,Sr))return{primaryCoin:rt};if(t.amount<=0)throw new m("Invalid coin request","coinAmount",t.amount);let e=await ye(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new l("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},ht=class{globals;helper;constructor(t,e){this.globals=O.new(t,e),this.helper=new ot(this.globals)}connectSingleWallet(t){let e=new $t(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Ut(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return C.new(this.globals,t)}async getIncomingStreams(t,e=10){return W.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return W.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=>br(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>Ce(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>Ce(n))}get wallet(){return this.globals.wallet}builder(){return new D(this.globals)}};import yr from"sort-keys-recursive";var St=class{constructor(t){this.data=t}serialize(){return JSON.stringify(yr(this.data))}};var d=class extends St{application="mpay";getClient(t,e){let r=new ht(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new gt(e)),r}};var q=class extends d{constructor(e){super(e);this.data=e}txType=Ir.Stream;txSubType="Cancel";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).cancel()}};import{TransactionType as Tr}from"@msafe/sui3-utils";var z=class extends d{constructor(e){super(e);this.data=e}txType=Tr.Stream;txSubType="ClaimByProxy";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as wr}from"@msafe/sui3-utils";var U=class extends d{constructor(e){super(e);this.data=e}txType=wr.Stream;txSubType="Claim";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).claim()}};import{TransactionType as xr}from"@msafe/sui3-utils";var $=class extends d{constructor(e){super(e);this.data=e}txType=xr.Stream;txSubType="CreateStream";async build(e){let{network:r,account:n}=e;return this.getClient(r,n).createStream(this.data)}};import{bcs as Ie}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ar,normalizeSuiAddress as H}from"@mysten/sui.js/utils";var M=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return H(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return a.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 Ie.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 H(t.value.Object.ImmOrOwned.objectId)}return H(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return H(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return H(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 Ie.de(e,new Uint8Array(r))}typeArg(t){return Ar(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var bt=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"&&y(e.target,this.contract.createStreamTarget));if(t.length===0)throw new l("No create stream transactions");return t.map(e=>new M(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=N(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),x=t.decodeInputU64(9),J=t.decodeInputU64(10),Ot=t.decodeInputBool(11),Pt=t.typeArg(0);return{name:r,groupId:n,recipient:o,timeStart:i,cliff:s,epochInterval:u,totalEpoch:x,amountPerEpoch:J,cancelable:Ot,coinType:Pt}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new m("Stream group not have common info");let r=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 g(this.globals.envConfig.contract,this.globals)}get feeContract(){return new E(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new T(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 yt=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new g(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"&&y(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&y(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&y(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&y(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&y(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new bt(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 M(t,this.txb)}};import{TransactionType as vr}from"@msafe/sui3-utils";var Q=class extends d{constructor(e){super(e);this.data=e}txType=vr.Stream;txSubType="SetAutoClaim";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Ct=class{application="mpay";async deserialize(t){let{chain:e,transactionBlock:r}=t,n=O.new(e==="sui:mainnet"?"prod":"dev"),i=new yt(n,r).decode(),s;switch(i.type){case"CreateStream":s=new $(i.info);break;case"SetAutoClaim":s=new Q({streamId:i.streamId,enabled:i.enabled});break;case"Claim":s=new U({streamId:i.streamId});break;case"ClaimByProxy":s=new z({streamId:i.streamId});break;case"Cancel":s=new q({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 $(e);break;case"Claim":r=new U(e);break;case"ClaimByProxy":r=new z(e);break;case"SetAutoClaim":r=new Q(e);break;case"Cancel":r=new q(e);break;default:throw new Error("not implemented")}return r.build({...t})}};import{TransactionDefaultApplication as Rr,TransactionSubTypes as Ht}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Pr}from"@msafe/sui3-utils";import Or from"sort-keys-recursive";var I=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(Or(this.data))}};var It=class a extends I{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return Pr(r,this.data,n.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as Er}from"@msafe/sui3-utils";var Tt=class a extends I{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return Er(r,this.data,n.address)}static fromData(e){return new a(e)}};import{isSameAddress as Dr}from"@msafe/sui3-utils";import{TransactionBlock as kr}from"@mysten/sui.js/transactions";var wt=class a extends I{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=kr.from(this.data.content);if(!Dr(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new a(e)}};var xt=class{application;constructor(){this.application=Rr}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case Ht.assets.coin.send:n=It.fromData(t.intentionData);break;case Ht.assets.object.send:n=Tt.fromData(t.intentionData);break;case Ht.others.plain:n=wt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}};var At=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 Mr,TransactionType as jr}from"@msafe/sui3-utils";import{TransactionBlock as Br}from"@mysten/sui.js/transactions";import{fromHEX as Nr,toHEX as _r}from"@mysten/sui.js/utils";import Fs from"sort-keys-recursive";var Fr="msafe-plain-tx",Gr=Mr.others.plain;var vt=class{application;constructor(){this.application=Fr}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:jr.Other,txSubType:Gr,intentionData:{content:_r(n)}}}async build(t){let{suiClient:e,account:r}=t,n=Br.from(Nr(t.intentionData.content)),o=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(!(o.effects.status.status==="success"))throw new Error(o.effects.status.error);return n}};var Us=new At([new xt,new Ct,new vt]);export{Us as appHelpers};
1
+ var Ue=Object.defineProperty;var le=(a,t)=>{for(var e in t)Ue(a,e,{get:t[e],enumerable:!0})};import{TransactionType as Lr}from"@msafe/sui3-utils";var Lt={};le(Lt,{contractId:()=>He,default:()=>Xe,feeObjId:()=>Je,roleObjId:()=>Ve,status:()=>ze,transaction:()=>qe,upgradeCapObjId:()=>Ye,vaultObjId:()=>Qe});var qe="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",ze="success",He="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Ve="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Qe="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Je="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Ye="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Xe={transaction:qe,status:ze,contractId:He,roleObjId:Ve,vaultObjId:Qe,feeObjId:Je,upgradeCapObjId:Ye};var $t={};le($t,{contractId:()=>tr,default:()=>or,feeObjId:()=>ar,roleObjId:()=>er,status:()=>Ze,transaction:()=>Ke,upgradeCapObjId:()=>nr,vaultObjId:()=>rr});var Ke="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ze="success",tr="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",er="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",rr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",ar="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",nr="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",or={transaction:Ke,status:Ze,contractId:tr,roleObjId:er,vaultObjId:rr,feeObjId:ar,upgradeCapObjId:nr};var ir="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",sr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",cr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",lr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",mr="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",ur="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",pr="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",dr="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",me=Lt,ue=$t,fr=new Map([["dev",{env:"dev",rpc:{url:ir},backend:{url:mr},contract:me}],["stg",{env:"stg",rpc:{url:sr},backend:{url:ur},contract:me}],["prev",{env:"prev",rpc:{url:cr},backend:{url:pr},contract:ue}],["prod",{env:"prod",rpc:{url:lr},backend:{url:dr},contract:ue}]]);function pe(a,t){let e=fr.get(a);if(!e)throw new Error(`Env not supported: ${a}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}import{SuiClient as br}from"@mysten/sui.js/client";var l=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:o}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var tt=class extends l{constructor(){super(11,"Backend is not specified")}};var et=class extends l{constructor(){super(1,"Wallet not connected")}};import E,{AxiosError as gr}from"axios";var D=class extends l{constructor(t,e){super(10,t,{context:e})}};var rt=class a{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof gr)throw new D(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new D(t.data.code)}throw new D(t.status.toString())}async getIncomingStreams(t,e){let r=await E.post(`${this.apiURL}/stream`,{recipient:t,...e});return a.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await E.post(`${this.apiURL}/stream`,{sender:t,...e});return a.parseResponseData(r)}async getStreamHistory(t){let e=await E.post(`${this.apiURL}/stream-events`,t),r=a.parseResponseData(e);return r.data.forEach(n=>{let o=n;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 a.parseResponseData(e)}async getAllRecipients(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return a.parseResponseData(r)}async getAllSenders(t,e){let r=await E.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return a.parseResponseData(r)}};var O=class a{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new br({url:t.rpc.url}),t.backend&&(this._backend=new rt(t.backend.url))}static new(t,e){let r=pe(t,e);return new a(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new tt;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 et;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as _r,normalizeStructTag as Fr,normalizeSuiAddress as Ne}from"@mysten/sui.js/utils";import{normalizeStructTag as zt,SUI_TYPE_ARG as Tr}from"@mysten/sui.js/utils";import{Duration as ve}from"luxon";import{TransactionBlock as ct}from"@mysten/sui.js/transactions";import{TransactionBlock as Te}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Ce,normalizeStructTag as Ir}from"@mysten/sui.js/utils";var Ut=50n,at=10000n,de=25n,qt=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 a{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,r){if(r in e)return Reflect.get(e,r);let n=i=>new a(e.result[i]);if(r===Symbol.iterator)return function*(){let i=0;for(;;)yield n(i),i++};if(typeof r=="symbol")return;let o=parseInt(r,10);if(!(Number.isNaN(o)||o<0))return n(o)}})}moveArg(){return this.result}};import{Buffer as fe}from"buffer";import{normalizeSuiAddress as hr}from"@mysten/sui.js/utils";var F=class extends l{constructor(t,e){super(3,t,{context:e})}};var nt=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,n]=this.getValue(t,e);if(n!=="address")throw new F("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return hr(fe.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new F("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});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"},yr=64;function ye(a){return Se(a),be.ser(he,a).toString("base64")}function G(a){let t=be.de(he,a,"base64");return Se(t),t}function Se(a){if(!ge(a.name))throw new u("Invalid metadata: Name contains unknown character");if(!ge(a.groupId))throw new u("Invalid metadata: Group ID contains unknown character");if(a.name.length>yr)throw new u("Invalid metadata: Name exceed max length 64")}function ge(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as ot}from"@mysten/sui.js/utils";function it(a,t){return ot(a)===ot(t)}function x(a,t){return ot(a)===ot(t)}var st="txn.gas";import{nanoid as Sr}from"nanoid";function Ie(){return Sr()}var P=class a{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:Ir(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),n=this.getCreateStreamCoinRequests(t,r),o=await this.wallet.requestCoins(n),i=await this.addMergeCoins(e,o[0]),s;n.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let m=0;m<t.recipients.length;m++){let d=t.recipients[m],y=this.amountForRecipient(d,t.numberEpoch),g=this.getStreamFeeLocal(y),[Wt]=e.splitCoins(i,[e.pure(y+g,"u64")]),[$e]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new w(Wt),flatFeeCoin:new w($e),metadata:t.metadata,recipient:d.address,timeStart:t.startTime,cliff:d.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=a.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:Ut,denominator:at},claimFeePercent:{numerator:de,denominator:at},flatFeePerStream:qt}}async addMergeCoins(t,e){let r;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(n=>t.object(n))),r=t.object(e.primaryCoin)):e.primaryCoin===st?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return it(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((n,o)=>{let i=this.amountForRecipient(o,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:n.totalAmount+i,streamFeeAmount:n.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 qt}getStreamFeeLocal(t){return t*Ut/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 nt(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(n=>n instanceof _?n.moveArgs(t):n instanceof S?n.moveArg(t):n instanceof w?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){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:n}))}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 a extends k{constructor(e,r){super(a.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 n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_fee,arguments:[n,o,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_streaming_flat_fee,arguments:[n,o,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:a.MethodName.set_claim_fee,arguments:[n,o,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:a.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var I=class a extends k{constructor(e,r){super(a.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 n=this.feeObject(),o=this.vaultObject(),i=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),m=this.clockObject();return this.addContractCall(e,{method:a.MethodName.create_stream,arguments:[n,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 n=this.makeObject(r.streamId);return this.addContractCall(e,{method:a.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.cancel_stream,arguments:[n,o],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream,arguments:[n,o],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:a.MethodName.claim_stream_by_proxy,arguments:[n,o,i,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var 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 n=new ct;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new ct;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new ct;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new ct;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var lt=class extends l{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Cr=1e3,mt=class{constructor(t){this.globals=t;this.coinMetaHelper=new Ht(t.suiClient),this.createStreamHelper=new B(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new lt(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,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};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))),n={timeStart:t.timeStart,timeEnd:r,interval:ve.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:zt(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,o)=>({...n,coinType:zt(n.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()<Cr)throw new u("Interval shall be at least 1 second","interval",t.interval)}},Ht=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=zt(t||Tr);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 De,normalizeSuiAddress as bt}from"@mysten/sui.js/utils";import{DateTime as Ee}from"luxon";import{TransactionBlock as ft}from"@mysten/sui.js/transactions";import{normalizeStructTag as Ae,parseStructTag as vr}from"@mysten/sui.js/utils";import{DateTime as Pr}from"luxon";var ut=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 p=class extends l{constructor(t,e={}){super(0,t,e)}};var pt=class extends l{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};import{DateTime as wr,Duration as xr}from"luxon";var Pe=(1n<<64n)-1n,dt=1e3;function Vt(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/dt);return wr.fromMillis(e*dt)}function Qt(a){let t;typeof a=="number"?t=a:typeof a=="bigint"?t=Number(a):t=a.toMillis();let e=Math.round(t/dt);return xr.fromMillis(e*dt)}var v=class a{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 a.fetchStreamData(t,e);return new a(t,e,r)}static fromObjectData(t,e,r){let n=a.parseRawStreamData(e,r);return new a(t,e,n)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new p("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new ut;let t=new ft;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 ft;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 ft;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new ft;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 Ae(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 Qt(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 Vt(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Qt(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:Vt((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=Pr.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 a.parseRawStreamData(e,r)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new pt(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:n}=vr(r.type),o=Ae(n[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 Yt(a){let t=[];for(;await a.hasNext();){let e=await a.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Jt=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 Jt(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 Ar=25;async function Kt(a,t,e){let r=new $(t),n=new U(a,r,e);return await Yt(n)}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,n){super(new Xt(e,r,n));this.suiClient=e;this.idIter=r;this.options=n}},Xt=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||Ar,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:n}=this;r=e.filter(o=>n?.(o))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}};var gt=class a{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 Kt(t.suiClient,e);return r.forEach(n=>{if(!n)throw new p("stream group object data undefined")}),a.newFromObjectResponse(t,e,r)}static async newFromObjectResponse(t,e,r){let n=await a.parseGroupStreams(t,e,r);return new a(t,n)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),r=e[0],n=!0;return e.forEach(o=>{Dr(r,o)||(n=!1)}),n}async refresh(){let t=await Kt(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 n=r.map((o,i)=>v.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(n.map(o=>o.groupId)).size!==1)throw new R("Not same group ID");if(!this.checkStreamGroup(n))throw new R("Not same stream settings");return n}};function Dr(a,t){return a.name===t.name&&a.groupId===t.groupId&&a.creator===t.creator&&a.start.toMillis()===t.start.toMillis()&&a.interval.toMillis()===t.interval.toMillis()&&a.steps===t.steps&&a.cancelable===t.cancelable}var q=class a{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await ht.newIncoming(t);return new a(e,t.pageSize)}static async newOutgoing(t){let e=await ht.newOutgoing(t);return new a(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},ht=class a{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await yt.newIncomingQuery(t);return new a(e)}static async newOutgoing(t){let e=await yt.newOutgoingQuery(t);return new a(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new p("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new p("No more results");return t}},yt=class a{constructor(t,e,r,n){this.globals=t;this.recipient=e;this.groupRefs=r;this.query=n;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=Br(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>bt(s.recipient)===bt(r)),i=Oe(o);return new a(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=Rr(t.query),r=await t.globals.walletAddress(),n=await t.globals.backend.getOutgoingStreams(r,e),o=Oe(n);return new a(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 kr(this.globals,t[0].streamId,this.objectIter);return this.current++,ke(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await jr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,Or(e,this.query)?e:this.doNextRequest()}throw new p("Stream group with no stream")}};function Oe(a){let t=new Map;return a.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(a,t){if(t===void 0)return!0;let e=Er(a,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let r=t.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return e&&r}return e}function Er(a,t){return t===void 0?!0:Array.isArray(t)?t.includes(a.progress.status):a.progress.status===t}function Or(a,t){if(!t)return!0;let e=!1;return a.streams.forEach(r=>{ke(r,t)&&(e=!0)}),e}async function kr(a,t,e){let r=await je(e,t);return v.fromObjectData(a,t,r)}async function jr(a,t,e){let r=[];for(;r.length<t.length;){let n=await je(e,t[r.length]);r.push(n)}return gt.newFromObjectResponse(a,t,r)}async function je(a,t){if(!await a.hasNext())throw new p("object iterator has been consumed");let e=await a.next();if(!e||e.error||e.data===void 0||e.data===null)throw new p("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new p("stream id not aligned");return e}function Br(a){return{status:Zt(a?.status),coinType:Be(a?.coinType),sender:Re(a?.sender)}}function Rr(a){return{status:Zt(a?.status),coinType:Be(a?.coinType),recipient:Re(a?.recipient)}}function Zt(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((t,e)=>{let r=Zt(e);return!t||t===r?r:"all"},void 0):Mr(a)}function Mr(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new u("Unknown stream filtered status")}}function Be(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>De(t)):void 0:De(a)}function Re(a){if(a)return Array.isArray(a)?a.length!==0?a.map(t=>bt(t)):void 0:bt(a)}var St=class extends l{constructor(e,r,n){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:r,gotAmount:n}});this.coinType=e;this.requestAmount=r;this.gotAmount=n}};var Nr=25;async function Me(a,t,e,r="0x2::sui::SUI",n=Nr){let o=new te(a,t,r,n),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 St(r,e,i);return s}var te=class extends M{constructor(e,r,n,o){super(new ee(e,r,n,o));this.suiClient=e;this.owner=r;this.coinType=n;this.reqPageSize=o}},ee=class{constructor(t,e,r,n){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=n;if(n<=0)throw new p("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var re=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},It=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(it(t.coinType,_r))return{primaryCoin:st};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 p("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Tt=class{globals;helper;constructor(t,e){this.globals=O.new(t,e),this.helper=new mt(this.globals)}connectSingleWallet(t){let e=new ae(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new re(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=>Fr(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>Ne(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>Ne(n))}get wallet(){return this.globals.wallet}builder(){return new B(this.globals)}};import Gr from"sort-keys-recursive";var Ct=class{constructor(t){this.data=t}serialize(){return JSON.stringify(Gr(this.data))}};var h=class extends Ct{application="mpay";getClient(t,e){let r=new Tt(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new It(e)),r}};var z=class extends h{constructor(e){super(e);this.data=e}txType=Lr.Stream;txSubType="Cancel";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).cancel()}};import{TransactionType as $r}from"@msafe/sui3-utils";var H=class extends h{constructor(e){super(e);this.data=e}txType=$r.Stream;txSubType="ClaimByProxy";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Ur}from"@msafe/sui3-utils";var V=class extends h{constructor(e){super(e);this.data=e}txType=Ur.Stream;txSubType="Claim";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).claim()}};import{TransactionType as qr}from"@msafe/sui3-utils";var Q=class extends h{constructor(e){super(e);this.data=e}txType=qr.Stream;txSubType="CreateStream";async build(e){let{network:r,account:n}=e;return this.getClient(r,n).createStream(this.data)}};import{bcs as _e}from"@mysten/sui.js/bcs";import{normalizeStructTag as zr,normalizeSuiAddress as J}from"@mysten/sui.js/utils";var N=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return 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 a.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 zr(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var wt=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 p("No create stream transactions");return t.map(e=>new N(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=G(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),m=t.decodeInputU64(8),d=t.decodeInputU64(9),y=t.decodeInputU64(10),g=t.decodeInputBool(11),Wt=t.typeArg(0);return{name:r,groupId:n,recipient:o,timeStart:i,cliff:s,epochInterval:m,totalEpoch:d,amountPerEpoch:y,cancelable:g,coinType:Wt}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new u("Stream group not have common info");let r=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 xt=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 wt(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 Hr}from"@msafe/sui3-utils";var Y=class extends h{constructor(e){super(e);this.data=e}txType=Hr.Stream;txSubType="SetAutoClaim";async build(e){let{network:r,account:n}=e;return(await this.getClient(r,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var vt=class{application="mpay";async deserialize(t){let{chain:e,transactionBlock:r}=t,n=O.new(e==="sui:mainnet"?"prod":"dev"),i=new xt(n,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 Kr,TransactionSubTypes as ne}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Qr}from"@msafe/sui3-utils";import Vr from"sort-keys-recursive";var f=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify(Vr(this.data))}};var Pt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return Qr(r,this.data,n.address)}static fromData(e){return new a(e)}};import{buildObjectTransferTxb as Jr}from"@msafe/sui3-utils";var At=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return Jr(r,this.data,n.address)}static fromData(e){return new a(e)}};import{isSameAddress as Yr}from"@msafe/sui3-utils";import{TransactionBlock as Xr}from"@mysten/sui.js/transactions";var Dt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=Xr.from(this.data.content);if(!Yr(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new a(e)}};var Et=class{application;constructor(){this.application=Kr}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case ne.assets.coin.send:n=Pt.fromData(t.intentionData);break;case ne.assets.object.send:n=At.fromData(t.intentionData);break;case ne.others.plain:n=Dt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}};import{TransactionType as ia}from"@msafe/sui3-utils";import{TransactionType as X}from"@msafe/sui3-utils";import{bcs as Fe}from"@mysten/sui.js/bcs";import{normalizeStructTag as oe,normalizeSuiAddress as K}from"@mysten/sui.js/utils";var Zr={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=Zr;function Z(a,t){return oe(a)===oe(t)}var Ot=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 ie(t,this.txb)}},ie=class a{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return a.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return a.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return Number(e)}decodeInputU8(t){let e=this.decodePureArg(t,"u8");return Number(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return 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 a.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 oe(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};import{TransactionBlock as ea}from"@mysten/sui.js/transactions";function se(a,t,e,r){return a.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[a.object("0x06"),a.object(c.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(r),a.object(c.Incentive),a.object(c.IncentiveV2)],typeArguments:[t.type]}),a}function Ge(a,t,e){return a.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[a.object("0x06"),a.object(c.PriceOracle),a.object(c.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(c.Incentive),a.object(c.IncentiveV2)],typeArguments:[t.type]}),a}function We(a,t,e){return a.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[a.object("0x06"),a.object(c.PriceOracle),a.object(c.StorageId),a.object(t.poolId),a.pure(t.assetId),a.pure(e),a.object(c.IncentiveV2)],typeArguments:[t.type]}),a}function ce(a,t,e,r){return a.moveCall({target:`${c.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[a.object("0x06"),a.object(c.PriceOracle),a.object(c.StorageId),a.object(t.poolId),a.pure(t.assetId),e,a.pure(r),a.object(c.IncentiveV2)],typeArguments:[t.type]}),a}function Le(a,t,e){return a.moveCall({target:`${c.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[a.object("0x06"),a.object(c.IncentiveV2),a.object(t.fondPoolId),a.object(c.StorageId),a.pure(t.assetId),a.pure(e)],typeArguments:[t.type]}),a}var kt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,option:r}=this.data,n=new ea,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(n,o,r)}static fromData(e){return new a(e)}};import{TransactionBlock as ra}from"@mysten/sui.js/transactions";var jt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new ra,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return We(n,o,r)}static fromData(e){return new a(e)}};import{TransactionBlock as aa}from"@mysten/sui.js/transactions";async function Bt(a,t,e){return await a.getCoins({owner:t,coinType:e})}var Rt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:o,amount:i}=this.data,s=new aa;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 d=await Bt(r,n.address,m.type);if(!d.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=d.data[0].coinObjectId;if(d.data.length>=2){let g=1;for(;g<d.data.length;)s.mergeCoins(y,[d.data[g].coinObjectId]),g++}return se(s,m,y,i)}static fromData(e){return new a(e)}};import{TransactionBlock as na}from"@mysten/sui.js/transactions";var Mt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:o,amount:i}=this.data,s=new na;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 d=await Bt(r,n.address,m.type);if(!d.data[0])throw new Error(`Insufficient balance for ${m.name} Token`);let y=d.data[0].coinObjectId;if(d.data.length>=2){let g=1;for(;g<d.data.length;)s.mergeCoins(y,[d.data[g].coinObjectId]),g++}return ce(s,m,y,i)}static fromData(e){return new a(e)}};import{TransactionBlock as oa}from"@mysten/sui.js/transactions";var Nt=class a extends f{constructor(e){super(e);this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new oa,o=c.pool[e];if(!o)throw new Error(`${e} not support, please use ${Object.keys(c.pool).join(", ")}.`);return Ge(n,o,r)}static fromData(e){return new a(e)}};var _t=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new Ot(e).decode();return{txType:ia.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=Rt.fromData(t.intentionData);break;case"EntryBorrow":n=jt.fromData(t.intentionData);break;case"EntryRepay":n=Mt.fromData(t.intentionData);break;case"EntryWithdraw":n=Nt.fromData(t.intentionData);break;case"ClaimReward":n=kt.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}};var Ft=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 sa,TransactionType as ca}from"@msafe/sui3-utils";import{TransactionBlock as la}from"@mysten/sui.js/transactions";import{fromHEX as ma,toHEX as ua}from"@mysten/sui.js/utils";import pl from"sort-keys-recursive";var pa="msafe-plain-tx",da=sa.others.plain;var Gt=class{application;constructor(){this.application=pa}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ca.Other,txSubType:da,intentionData:{content:ua(n)}}}async build(t){let{suiClient:e,account:r}=t,n=la.from(ma(t.intentionData.content)),o=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(!(o.effects.status.status==="success"))throw new Error(o.effects.status.error);return n}};var Sl=new Ft([new Et,new _t,new vt,new Gt]);export{Sl as appHelpers};
2
2
  //# sourceMappingURL=index.mjs.map