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