@msafe/sui3-sdk 0.0.49-pre-e5b1664.0 → 0.0.49-pre-bf78c8b.0
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.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -2050,7 +2050,7 @@ zebra
|
|
|
2050
2050
|
zero
|
|
2051
2051
|
zone
|
|
2052
2052
|
zoo`.split(`
|
|
2053
|
-
`);var Ii=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,du=typeof process=="object"&&process?process:{},kf=(t,e,r,n)=>{typeof du.emitWarning=="function"?du.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Ho=globalThis.AbortController,Sf=globalThis.AbortSignal;if(typeof Ho>"u"){Sf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Ho=class{constructor(){e()}signal=new Sf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=du.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yy=t=>!xf.has(t),pT=Symbol("type"),Or=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Af=t=>Or(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Nn:null:null,Nn=class extends Array{constructor(e){super(e),this.fill(0)}},fu=class t{heap;length;static#u=!1;static create(e){let r=Af(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zo=class t{#u;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#i;#r;#e;#c;#f;#a;#o;#g;#s;#T;#S;#w;#b;#k;#l;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#w,sizes:e.#T,keyMap:e.#i,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,o)=>e.#P(r,n,i,o),moveToTail:r=>e.#C(r),indexes:r=>e.#_(r),rindexes:r=>e.#v(r),isStale:r=>e.#h(r)}}get max(){return this.#u}get maxSize(){return this.#d}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:u,allowStale:l,dispose:d,disposeAfter:b,noDisposeOnSet:_,noUpdateTTL:T,maxSize:x=0,maxEntrySize:A=0,sizeCalculation:I,fetchMethod:C,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:D,allowStaleOnFetchAbort:L,ignoreFetchAbort:H}=e;if(r!==0&&!Or(r))throw new TypeError("max option must be a nonnegative integer");let W=r?Af(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#u=r,this.#d=x,this.maxEntrySize=A||this.#d,this.sizeCalculation=I,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(C!==void 0&&typeof C!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=C,this.#k=!!C,this.#i=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new W(r),this.#f=new W(r),this.#a=0,this.#o=0,this.#g=fu.create(r),this.#n=0,this.#m=0,typeof d=="function"&&(this.#y=d),typeof b=="function"?(this.#p=b,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!T,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!D,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#d!==0&&!Or(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Or(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!u,this.ttlResolution=Or(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Or(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#u===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#d){let K="LRU_CACHE_UNBOUNDED";yy(K)&&(xf.add(K),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,t))}}getRemainingTTL(e){return this.#i.has(e)?1/0:0}#D(){let e=new Nn(this.#u),r=new Nn(this.#u);this.#w=e,this.#S=r,this.#B=(o,s,u=Ii.now())=>{if(r[o]=s!==0?u:0,e[o]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#h(o)&&this.delete(this.#r[o])},s+1);l.unref&&l.unref()}},this.#A=o=>{r[o]=e[o]!==0?Ii.now():0},this.#x=(o,s)=>{if(e[s]){let u=e[s],l=r[s];o.ttl=u,o.start=l,o.now=n||i();let d=o.now-l;o.remainingTTL=u-d}};let n=0,i=()=>{let o=Ii.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#i.get(o);if(s===void 0)return 0;let u=e[s],l=r[s];if(u===0||l===0)return 1/0;let d=(n||i())-l;return u-d},this.#h=o=>e[o]!==0&&r[o]!==0&&(n||i())-r[o]>e[o]}#A=()=>{};#x=()=>{};#B=()=>{};#h=()=>!1;#F(){let e=new Nn(this.#u);this.#m=0,this.#T=e,this.#I=r=>{this.#m-=e[r],e[r]=0},this.#N=(r,n,i,o)=>{if(this.#t(n))return 0;if(!Or(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(n,r),!Or(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#d){let o=this.#d-e[r];for(;this.#m>o;)this.#E(!0)}this.#m+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#m)}}#I=e=>{};#M=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#o;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#v({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#o));)r=this.#c[r]}#R(e){return e!==void 0&&this.#i.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#_()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#v()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#_())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#v()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#v({allowStale:!0}))this.#h(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#_({allowStale:!0})){let n=this.#r[r],i=this.#e[r],o=this.#t(i)?i.__staleWhileFetching:i;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#w&&this.#S){s.ttl=this.#w[r];let u=Ii.now()-this.#S[r];s.start=Math.floor(Date.now()-u)}this.#T&&(s.size=this.#T[r]),e.unshift([n,s])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ii.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:l}=n,{noUpdateTTL:d=this.noUpdateTTL}=n,b=this.#N(e,r,n.size||0,u);if(this.maxEntrySize&&b>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let _=this.#n===0?void 0:this.#i.get(e);if(_===void 0)_=this.#n===0?this.#o:this.#g.length!==0?this.#g.pop():this.#n===this.#u?this.#E(!1):this.#n,this.#r[_]=e,this.#e[_]=r,this.#i.set(e,_),this.#c[this.#o]=_,this.#f[_]=this.#o,this.#o=_,this.#n++,this.#M(_,b,l),l&&(l.set="add"),d=!1;else{this.#C(_);let T=this.#e[_];if(r!==T){if(this.#k&&this.#t(T)?T.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(T,e,"set"),this.#l&&this.#s?.push([T,e,"set"])),this.#I(_),this.#M(_,b,l),this.#e[_]=r,l){l.set="replace";let x=T&&this.#t(T)?T.__staleWhileFetching:T;x!==void 0&&(l.oldValue=x)}}else l&&(l.set="update")}if(i!==0&&!this.#w&&this.#D(),this.#w&&(d||this.#B(_,i,o),l&&this.#x(l,_)),!s&&this.#l&&this.#s){let T=this.#s,x;for(;x=T?.shift();)this.#p?.(...x)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}}#E(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#k&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,n,"evict"),this.#l&&this.#s?.push([i,n,"evict"])),this.#I(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#g.push(r)),this.#n===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#c[r],this.#i.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,o=this.#i.get(e);if(o!==void 0){let s=this.#e[o];if(this.#t(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#h(o))i&&(i.has="stale",this.#x(i,o));else return n&&this.#A(o),i&&(i.has="hit",this.#x(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#i.get(e);if(i!==void 0&&(n||!this.#h(i))){let o=this.#e[i];return this.#t(o)?o.__staleWhileFetching:o}}#P(e,r,n,i){let o=r===void 0?void 0:this.#e[r];if(this.#t(o))return o;let s=new Ho,{signal:u}=n;u?.addEventListener("abort",()=>s.abort(u.reason),{signal:s.signal});let l={signal:s.signal,options:n,context:i},d=(I,C=!1)=>{let{aborted:E}=s.signal,P=n.ignoreFetchAbort&&I!==void 0;if(n.status&&(E&&!C?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,P&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),E&&!P&&!C)return _(s.signal.reason);let D=x;return this.#e[r]===x&&(I===void 0?D.__staleWhileFetching?this.#e[r]=D.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,I,l.options))),I},b=I=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=I),_(I)),_=I=>{let{aborted:C}=s.signal,E=C&&n.allowStaleOnFetchAbort,P=E||n.allowStaleOnFetchRejection,D=P||n.noDeleteOnFetchRejection,L=x;if(this.#e[r]===x&&(!D||L.__staleWhileFetching===void 0?this.delete(e):E||(this.#e[r]=L.__staleWhileFetching)),P)return n.status&&L.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw I},T=(I,C)=>{let E=this.#O?.(e,o,l);E&&E instanceof Promise&&E.then(P=>I(P),C),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(I(),n.allowStaleOnFetchAbort&&(I=P=>d(P,!0)))})};n.status&&(n.status.fetchDispatched=!0);let x=new Promise(T).then(d,b),A=Object.assign(x,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,A,{...l.options,status:void 0}),r=this.#i.get(e)):this.#e[r]=A,A}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Ho}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:l=0,sizeCalculation:d=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:T=this.allowStaleOnFetchRejection,ignoreFetchAbort:x=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:I,forceRefresh:C=!1,status:E,signal:P}=r;if(!this.#k)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:E});let D={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:u,size:l,sizeCalculation:d,noUpdateTTL:b,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:A,ignoreFetchAbort:x,status:E,signal:P},L=this.#i.get(e);if(L===void 0){E&&(E.fetch="miss");let H=this.#P(e,L,D,I);return H.__returned=H}else{let H=this.#e[L];if(this.#t(H)){let N=n&&H.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=!0)),N?H.__staleWhileFetching:H.__returned=H}let W=this.#h(L);if(!C&&!W)return E&&(E.fetch="hit"),this.#C(L),i&&this.#A(L),E&&this.#x(E,L),H;let K=this.#P(e,L,D,I),U=K.__staleWhileFetching!==void 0&&n;return E&&(E.fetch=W?"stale":"refresh",U&&W&&(E.returnedStale=!0)),U?K.__staleWhileFetching:K.__returned=K}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=r,u=this.#i.get(e);if(u!==void 0){let l=this.#e[u],d=this.#t(l);return s&&this.#x(s,u),this.#h(u)?(s&&(s.get="stale"),d?(s&&n&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?l.__staleWhileFetching:void 0):(o||this.delete(e),s&&n&&(s.returnedStale=!0),n?l:void 0)):(s&&(s.get="hit"),d?l.__staleWhileFetching:(this.#C(u),i&&this.#A(u),l))}else s&&(s.get="miss")}#j(e,r){this.#f[r]=e,this.#c[e]=r}#C(e){e!==this.#o&&(e===this.#a?this.#a=this.#c[e]:this.#j(this.#f[e],this.#c[e]),this.#j(this.#o,e),this.#o=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#i.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#I(n);let i=this.#e[n];this.#t(i)?i.__abortController.abort(new Error("deleted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,e,"delete"),this.#l&&this.#s?.push([i,e,"delete"])),this.#i.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#o?this.#o=this.#f[n]:n===this.#a?this.#a=this.#c[n]:(this.#c[this.#f[n]]=this.#c[n],this.#f[this.#c[n]]=this.#f[n]),this.#n--,this.#g.push(n)}}if(this.#l&&this.#s?.length){let n=this.#s,i;for(;i=n?.shift();)this.#p?.(...i)}return r}clear(){for(let e of this.#v({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#b&&this.#y?.(r,n,"delete"),this.#l&&this.#s?.push([r,n,"delete"])}}if(this.#i.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#w&&this.#S&&(this.#w.fill(0),this.#S.fill(0)),this.#T&&this.#T.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#m=0,this.#n=0,this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}};var Q=de(we(),1);var Yo=de(If(),1),Qr=require("@mysten/sui.js/utils"),en=require("@mysten/sui.js/transactions");var Ci=de(we(),1),Nf=require("@mysten/sui.js/transactions"),Mt=de(we(),1);var Mr=de(we(),1),Lt=de(we(),1);var Ei=de(we(),1);var Rf=require("@mysten/sui.js/utils"),Qo=require("@mysten/sui.js/transactions"),es=require("@mysten/sui.js/utils");var yu=de(we(),1),by=Object.defineProperty,_y=(t,e,r)=>e in t?by(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e,r)=>(_y(t,typeof e!="symbol"?e+"":e,r),r);var Ko=443636,Jo=-443636,mu="79226673515401279992447579055",gu="4295048016",Ty=14,Sy="59543866431248",xy="184467440737095516",ky="15793534762490258745",Ay=class{generateMnemonic(t=24){return vf(Tf,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let r=this.getDerivePath(e);return Ef.Ed25519Keypair.deriveKeypair(t,r)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:r=!1,addressIndex:n=0}=t;return`m/44'/784'/${e}'/${r?1:0}'/${n}'`}},Mi=class{constructor(t){this.sdk=t,rr(this,"_lru"),rr(this,"_fetching",{})}async getCacheOrSet(t,e,r=0){var n;let i=this._lru||(this._lru=new Zo({max:100}));if(i.has(t))return i.get(t);let s=await((n=this._fetching)[t]||(n[t]=e()));return delete this._fetching[t],i.set(t,s,{ttl:r}),s}get provider(){return this.sdk.provider}get math(){return this.sdk.math}get account(){return this.sdk.account}get network(){return this.sdk.network}get contract(){return this.sdk.contract}get nft(){return this.sdk.nft}get coin(){return this.sdk.coin}get trade(){return this.sdk.trade}get pool(){return this.sdk.pool}};function Iy(t){if("reference"in t)return t.reference;let e=bu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Df(t)}function rs(t){var e,r;return"objectId"in t?t.objectId:(r=(e=Iy(t))==null?void 0:e.objectId)!=null?r:Bf(t)}function nr(t){var e;return"fields"in t?t.fields:(e=Pf(t))==null?void 0:e.fields}function Pf(t){let e="data"in t?bu(t):t;if(!(!e||!Cy(e)||e.content.dataType!=="moveObject"))return e.content}function Cy(t){return t.content!==void 0}function bu(t){return t.data}function Df(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let e=t.error;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Bf(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Oy(t){return t.data!==void 0}function My(t){var e;let r=Oy(t)?t.data:t;return!r?.type&&"data"in t?((e=r?.content)==null?void 0:e.dataType)==="package"?"package":ts(t):r?.type}function ts(t){var e;return(e=Pf(t))==null?void 0:e.type}function Ey(t){var e;return(e=bu(t))==null?void 0:e.owner}var Oi=async(t,e,r)=>{let i=e.length;if(i>50){let o=[],s=0,u=Math.ceil(i/50);for(s;s<u;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:r}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:r})},Py=class extends Mi{async getConfig(){return(await this.fetchJSON())[this.network].contract}getFees(){return this.getCacheOrSet("fees",async()=>{let e=(await this.fetchJSON())[this.network].fee;return(await Oi(this.provider,Object.values(e),{showContent:!0})).map(n=>{let i=nr(n),o=rs(n),s=ts(n);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:i.fee,tickSpacing:i.tick_spacing}})})}fetchJSON(){return this.getCacheOrSet("contract-json",async()=>await(await fetch("https://s3.amazonaws.com/app.turbos.finance/sdk/contract.json?t="+Date.now(),{method:"GET"})).json())}},Cf=new Q.default(2).pow(new Q.default(128)),Dy=class{priceToSqrtPriceX64(t,e,r){return new Q.default(new $(t).mul($.pow(10,r-e)).sqrt().mul($.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,r){return new $(t.toString()).mul($.pow(2,-64)).pow(2).mul($.pow(10,e-r))}priceToTickIndex(t,e,r){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,r))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Q.default(mu))||t.lt(new Q.default(gu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,r=new Q.default(e-64),n=this.signedShiftLeft(r,32,128),i=new Q.default("8000000000000000","hex"),o=0,s=new Q.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new Q.default(0))&&o<Ty;){u=u.mul(u);let x=u.shrn(127);u=u.shrn(63+x.toNumber()),s=s.add(i.mul(x)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new Q.default(Sy)),_=this.signedShiftRight(b.sub(new Q.default(xy)),64,128).toNumber(),T=this.signedShiftRight(b.add(new Q.default(ky)),64,128).toNumber();return _==T?_:this.tickIndexToSqrtPriceX64(T).lte(t)?T:_}tickIndexToSqrtPriceX64(t){return t>0?new Q.default(this.tickIndexToSqrtPricePositive(t)):new Q.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,r){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,r)}toX64_Decimal(t){return t.mul($.pow(2,64))}fromX64_Decimal(t){return t.mul($.pow(2,-64))}scaleDown(t,e){return new $(t).div($.pow(10,e)).toString()}scaleUp(t,e){return new $(t).mul($.pow(10,e)).toString()}bitsToNumber(t,e=32){return Yo.default.toNumber(Yo.default.asIntN(e,Yo.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Cf).sub(e).mod(Cf)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Q.default("79232123823359799118286999567"):e=new Q.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Q.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Q.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Q.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Q.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Q.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Q.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Q.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Q.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Q.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Q.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Q.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Q.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Q.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Q.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Q.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Q.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Q.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Q.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),r;return e&1?r=new Q.default("18445821805675392311"):r=new Q.default("18446744073709551616"),e&2&&(r=this.signedShiftRight(r.mul(new Q.default("18444899583751176498")),64,256)),e&4&&(r=this.signedShiftRight(r.mul(new Q.default("18443055278223354162")),64,256)),e&8&&(r=this.signedShiftRight(r.mul(new Q.default("18439367220385604838")),64,256)),e&16&&(r=this.signedShiftRight(r.mul(new Q.default("18431993317065449817")),64,256)),e&32&&(r=this.signedShiftRight(r.mul(new Q.default("18417254355718160513")),64,256)),e&64&&(r=this.signedShiftRight(r.mul(new Q.default("18387811781193591352")),64,256)),e&128&&(r=this.signedShiftRight(r.mul(new Q.default("18329067761203520168")),64,256)),e&256&&(r=this.signedShiftRight(r.mul(new Q.default("18212142134806087854")),64,256)),e&512&&(r=this.signedShiftRight(r.mul(new Q.default("17980523815641551639")),64,256)),e&1024&&(r=this.signedShiftRight(r.mul(new Q.default("17526086738831147013")),64,256)),e&2048&&(r=this.signedShiftRight(r.mul(new Q.default("16651378430235024244")),64,256)),e&4096&&(r=this.signedShiftRight(r.mul(new Q.default("15030750278693429944")),64,256)),e&8192&&(r=this.signedShiftRight(r.mul(new Q.default("12247334978882834399")),64,256)),e&16384&&(r=this.signedShiftRight(r.mul(new Q.default("8131365268884726200")),64,256)),e&32768&&(r=this.signedShiftRight(r.mul(new Q.default("3584323654723342297")),64,256)),e&65536&&(r=this.signedShiftRight(r.mul(new Q.default("696457651847595233")),64,256)),e&131072&&(r=this.signedShiftRight(r.mul(new Q.default("26294789957452057")),64,256)),e&262144&&(r=this.signedShiftRight(r.mul(new Q.default("37481735321082")),64,256)),r}signedShiftLeft(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}signedShiftRight(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}},wu=(t,e)=>{let r=rs(t);if(Df(t))throw new Error(`${e}(${r}) had been deleted`);if(Bf(t))throw new Error(`${e}(${r}) is not found`);return!0},Rn=60*1e3,By=class extends Mi{async getPools(t=!1){let e=await this.contract.getConfig(),r=[],n;do n=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:n?.nextCursor,limit:15}),r.push(...n.data.map(u=>u.objectId));while(n.hasNextPage);if(!r.length)return[];let o=(await Oi(this.provider,r,{showContent:!0})).map(u=>nr(u).value.fields.pool_id);if(!o.length)return[];let s=await Oi(this.provider,o,{showContent:!0});return t||(s=s.filter(u=>nr(u).unlocked)),s.map(u=>this.parsePool(u))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:r,tickLower:n,tickUpper:i,sqrtPrice:o,slippage:s,coinTypeA:u,coinTypeB:l}=t,d=await this.contract.getConfig(),b=new $(t.amountA),_=new $(t.amountB),[T,x]=await Promise.all([this.coin.selectTradeCoins(r,u,b),this.coin.selectTradeCoins(r,l,_)]),A=t.txb||new en.TransactionBlock,I=T.length>0?this.coin.convertTradeCoins(A,T,u,b):[this.coin.zero(u,A)],C=x.length>0?this.coin.convertTradeCoins(A,x,l,_):[this.coin.zero(l,A)];return A.moveCall({target:`${d.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[u,l,e.type],arguments:[A.object(d.PoolConfig),A.object(e.objectId),A.pure(o,"u128"),A.object(d.Positions),A.makeMoveVec({objects:I}),A.makeMoveVec({objects:C}),A.pure(Math.abs(n).toFixed(0),"u32"),A.pure(n<0,"bool"),A.pure(Math.abs(i).toFixed(0),"u32"),A.pure(i<0,"bool"),A.pure(b.toFixed(0),"u64"),A.pure(_.toFixed(0),"u64"),A.pure(this.getMinimumAmountBySlippage(b,s),"u64"),A.pure(this.getMinimumAmountBySlippage(_,s),"u64"),A.pure(r,"address"),A.pure(Date.now()+Rn,"u64"),A.object(Qr.SUI_CLOCK_OBJECT_ID),A.object(d.Versioned)]}),A}async addLiquidity(t){let{address:e,tickLower:r,tickUpper:n,slippage:i,pool:o}=t,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(o),[l,d]=u,[b,_]=await Promise.all([this.coin.getMetadata(l),this.coin.getMetadata(d)]);if(!b||!_)throw new Error("Invalid coin type");let T=new $(t.amountA),x=new $(t.amountB),[A,I]=await Promise.all([this.coin.selectTradeCoins(e,l,T),this.coin.selectTradeCoins(e,d,x)]),C=t.txb||new en.TransactionBlock,E=A.length>0?this.coin.convertTradeCoins(C,A,l,T):[this.coin.zero(l,C)],P=I.length>0?this.coin.convertTradeCoins(C,I,d,x):[this.coin.zero(d,C)];return C.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:u,arguments:[C.object(o),C.object(s.Positions),C.makeMoveVec({objects:E}),C.makeMoveVec({objects:P}),C.pure(Math.abs(r).toFixed(0),"u32"),C.pure(r<0,"bool"),C.pure(Math.abs(n).toFixed(0),"u32"),C.pure(n<0,"bool"),C.pure(T.toFixed(0),"u64"),C.pure(x.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(T,i),"u64"),C.pure(this.getMinimumAmountBySlippage(x,i),"u64"),C.pure(e,"address"),C.pure(Date.now()+Rn,"u64"),C.object(Qr.SUI_CLOCK_OBJECT_ID),C.object(s.Versioned)]}),C}async increaseLiquidity(t){let{pool:e,slippage:r,address:n,nft:i}=t,o=await this.contract.getConfig(),s=new $(t.amountA),u=new $(t.amountB),l=await this.getPoolTypeArguments(e),[d,b]=l,[_,T]=await Promise.all([this.coin.selectTradeCoins(n,d,s),this.coin.selectTradeCoins(n,b,u)]),x=t.txb||new en.TransactionBlock,A=_.length>0?this.coin.convertTradeCoins(x,_,d,s):[this.coin.zero(d,x)],I=T.length>0?this.coin.convertTradeCoins(x,T,b,u):[this.coin.zero(b,x)];return x.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:l,arguments:[x.object(e),x.object(o.Positions),x.makeMoveVec({objects:A}),x.makeMoveVec({objects:I}),x.object(i),x.pure(s.toFixed(0),"u64"),x.pure(u.toFixed(0),"u64"),x.pure(this.getMinimumAmountBySlippage(s,r),"u64"),x.pure(this.getMinimumAmountBySlippage(u,r),"u64"),x.pure(Date.now()+Rn*3,"u64"),x.object(Qr.SUI_CLOCK_OBJECT_ID),x.object(o.Versioned)]}),x}async decreaseLiquidity(t){let{slippage:e,nft:r,pool:n,decreaseLiquidity:i}=t,o=new $(t.amountA),s=new $(t.amountB),u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(n),d=t.txb||new en.TransactionBlock;return d.moveCall({target:`${u.PackageId}::position_manager::decrease_liquidity`,typeArguments:l,arguments:[d.object(n),d.object(u.Positions),d.object(r),d.pure(new Ci.default(i).toString(),"u128"),d.pure(this.getMinimumAmountBySlippage(o,e),"u64"),d.pure(this.getMinimumAmountBySlippage(s,e),"u64"),d.pure(Date.now()+Rn*3,"u64"),d.object(Qr.SUI_CLOCK_OBJECT_ID),d.object(u.Versioned)]}),d}async removeLiquidity(t){let e=await this.decreaseLiquidity(t);return e=await this.collectFee({txb:e,...t}),e=await this.collectReward({txb:e,...t}),e=await this.nft.burn({txb:e,nft:t.nft,pool:t.pool}),e}async collectFee(t){let{pool:e,nft:r,address:n,collectAmountA:i,collectAmountB:o}=t,s=t.txb||new en.TransactionBlock;if(Number(i)===0&&Number(o)===0)return s;let u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(e);return s.moveCall({target:`${u.PackageId}::position_manager::collect`,typeArguments:l,arguments:[s.object(e),s.object(u.Positions),s.object(r),s.pure(i,"u64"),s.pure(o,"u64"),s.pure(n),s.pure(Date.now()+Rn*3,"u64"),s.object(Qr.SUI_CLOCK_OBJECT_ID),s.object(u.Versioned)]}),s}async collectReward(t){let{pool:e,nft:r,rewardAmounts:n,address:i}=t,o=t.txb||new en.TransactionBlock,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((d,b)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...u,d.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(r),o.object(d.fields.vault),o.pure(b,"u64"),o.pure(n[b],"u64"),o.pure(i),o.pure(Date.now()+Rn*3,"u64"),o.object(Qr.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new $((t.liquidity||new Ci.default(1e8)).toString()),r=new $(t.currentSqrtPrice.toString()),n=new $(t.lowerSqrtPrice.toString()),i=new $(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(n)).div(n.mul(i)),s=new $(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(r)).div(r.mul(i)),s=this.math.fromX64_Decimal(e.mul(r.sub(n)))):(o=new $(0),s=this.math.fromX64_Decimal(e.mul(i.sub(n))));let u=t.ceil!==!1?"ceil":"floor";return[new Ci.default(o[u]().toString()),new Ci.default(s[u]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var r;let n=((r=t.replace(">","").split("<")[1])==null?void 0:r.split(/,\s*/))||[];if(e!==void 0&&e!==n.length)throw new Error("Invalid pool type");return n}async getFixedLiquidity(t){var e,r;let{coinTypeA:n,coinTypeB:i,amountA:o,amountB:s}=t,[u,l]=await Promise.all([this.coin.getMetadata(n),this.coin.getMetadata(i)]),d=new $(this.math.scaleDown(o,u.decimals)).mul((e=t.priceA)!=null?e:1),b=new $(this.math.scaleDown(s,l.decimals)).mul((r=t.priceB)!=null?r:1);return{liquidityA:d.toString(),liquidityB:b.toString(),liquidity:d.plus(b).toString()}}parsePool(t){let e=nr(t),r=rs(t),n=My(t),i=this.parsePoolType(n,3);return this.getCacheOrSet("pool-type-"+r,async()=>i),{...e,objectId:r,type:n,types:i}}getMinimumAmountBySlippage(t,e){let r=new $(t),n=new $(1).minus(new $(e).div(100));if(n.lte(0)||n.gt(1))throw new Error("invalid slippage range");return r.mul(n).toFixed(0)}},Ny=(t,e)=>{let{pool:r,position:n,tickLowerDetail:i,tickUpperDetail:o}=e,s=new Mr.default(r.fee_growth_global_a),u=new Mr.default(n.fee_growth_inside_a),l=new Mr.default(n.tokens_owed_a),d=new Mr.default(r.fee_growth_global_b),b=new Mr.default(n.fee_growth_inside_b),_=new Mr.default(n.tokens_owed_b),T=new Mr.default(n.liquidity),x,A,I,C,E=t.bitsToNumber(r.tick_current_index.fields.bits),P=t.bitsToNumber(n.tick_lower_index.fields.bits),D=t.bitsToNumber(n.tick_upper_index.fields.bits);E<P?(x=t.subUnderflowU128(s,i.feeGrowthOutsideA),A=t.subUnderflowU128(d,i.feeGrowthOutsideB)):(x=i.feeGrowthOutsideA,A=i.feeGrowthOutsideB),E<D?(I=o.feeGrowthOutsideA,C=o.feeGrowthOutsideB):(I=t.subUnderflowU128(s,o.feeGrowthOutsideA),C=t.subUnderflowU128(d,o.feeGrowthOutsideB));let L=t.subUnderflowU128(t.subUnderflowU128(s,x),I),H=t.subUnderflowU128(t.subUnderflowU128(d,A),C),W=t.subUnderflowU128(L,u).mul(T).shrn(64),K=t.subUnderflowU128(H,b).mul(T).shrn(64);return{feeOwedA:l.add(W).toString(),feeOwedB:_.add(K).toString()}},Of=new Ei.default(0),Mf=new Ei.default(1),Ry=new Ei.default(2),jy={mul(t,e,r){let n=t.mul(e);if(this.isOverLimit(n,r))throw new Error(`Mul result higher than u${r}`);return n},mulDiv(t,e,r,n){return this.mulDivRoundUpIf(t,e,r,!1,n)},mulDivRoundUpIf(t,e,r,n,i){if(r.eq(Of))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,i),s=o.div(r);return n&&o.mod(r).gt(Of)?s.add(Mf):s},isOverLimit(t,e){let r=Ry.pow(new Ei.default(e)).sub(Mf);return t.gt(r)}},Fy=(t,e)=>{var r,n,i,o;let{pool:s,position:u,tickLowerDetail:l,tickUpperDetail:d,timeStampInSeconds:b}=e,_=new Lt.default(new $(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),x=(b??new Lt.default(Date.now()).div(new Lt.default(1e3))).sub(new Lt.default(_)),A=[],I=new Lt.default(s.liquidity),C=new Lt.default(u.liquidity);for(let E=0;E<3;++E){let P=s.reward_infos[E],D={emissionsPerSecondX64:new Lt.default(P?P.fields.emissions_per_second:"0"),growthGlobalX64:new Lt.default(P?P.fields.growth_global:"0")},L={growthInsideCheckpoint:new Lt.default((n=(r=u.reward_infos[E])==null?void 0:r.fields.reward_growth_inside)!=null?n:"0"),amountOwed:new Lt.default((o=(i=u.reward_infos[E])==null?void 0:i.fields.amount_owed)!=null?o:"0")},H=D.growthGlobalX64;if(!I.isZero()){let S=jy.mulDiv(x,D.emissionsPerSecondX64,I,128);H=D.growthGlobalX64.add(S)}let W=l.rewardGrowthsOutside[E],K=d.rewardGrowthsOutside[E],F=H;l.initialized&&(F=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_lower_index.fields.bits)?t.subUnderflowU128(H,W):W);let U=new Lt.default(0);d.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_upper_index.fields.bits)?K:t.subUnderflowU128(H,K));let N=t.subUnderflowU128(t.subUnderflowU128(H,F),U),j=L.amountOwed.shln(64);A[E]=j.add(t.subUnderflowU128(N,L.growthInsideCheckpoint).mul(C)).shrn(64).toString()}return A},qy=class extends Mi{async getOwner(t){let e=await this.getObject(t),r=Ey(e);if(!(!r||typeof r=="string")){if("ObjectOwner"in r)return r.ObjectOwner;if("AddressOwner"in r)return r.AddressOwner}}async getFields(t){let e=await this.getObject(t);return nr(e)}async getPositionFields(t){let e=await this.contract.getConfig(),r=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return nr(r)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"position"),nr(e)}async getPositionTick(t,e){let r=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),n=nr(r);if(n)return{tickIndex:this.math.bitsToNumber(n.name.fields.bits),initialized:n.value.fields.initialized,liquidityNet:new Mt.default(this.math.bitsToNumber(n.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Mt.default(n.value.fields.liquidity_gross),feeGrowthOutsideA:new Mt.default(n.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Mt.default(n.value.fields.fee_growth_outside_b),rewardGrowthsOutside:n.value.fields.reward_growths_outside.map(i=>new Mt.default(i))}}async getPositionAPR(t){let{poolId:e,getPrice:r,fees24h:n,tickLower:i,tickUpper:o}=t,s=await this.pool.getPool(e),u=this.math.bitsToNumber(s.tick_current_index.fields.bits),[l,d,b,_]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),r(s.types[0]),r(s.types[1])]);if(!b||!_||i>=o||u<i||u>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:T,minTokenB:x}=this.getRemoveLiquidityQuote(s,i,o),A=new $(this.math.scaleDown(T.toString(),l.decimals)).mul(b),I=new $(this.math.scaleDown(x.toString(),d.decimals)).mul(_),C=A.add(I),E=C.isZero()?new $(0):new $(n).mul(365).div(C).mul(100),P=new $(0);return await Promise.all(s.reward_infos.map(async D=>{let{emissions_per_second:L}=D.fields,H=this.coin.formatCoinType(D.fields.vault_coin_type),[W,K]=await Promise.all([r(H),this.coin.getMetadata(H)]);!L||L==="0"||!W||(P=P.add(new $(new Mt.default(L).shrn(64).toString()).div(10**K.decimals).mul(31536e3).mul(W).div(C).mul(100)))})),{fees:E.toString(),rewards:P.toString(),total:E.plus(P).toString()}}getRemoveLiquidityQuote(t,e,r){let n=new Mt.default(0),i=new Mt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),u=this.math.tickIndexToSqrtPriceX64(r);if(o<e){let d=this.getTokenAFromLiquidity(i,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:n}}if(o<r){let d=new Mt.default(t.sqrt_price),b=this.getTokenAFromLiquidity(i,d,u),_=this.getTokenBFromLiquidity(i,s,d);return{minTokenA:this.adjustForSlippage(b),minTokenB:this.adjustForSlippage(_)}}let l=this.getTokenBFromLiquidity(i,s,u);return{minTokenA:n,minTokenB:this.adjustForSlippage(l)}}adjustForSlippage(t){let e={numerator:new Mt.default(0),denominator:new Mt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,r){let n=t.mul(r.sub(e)).shln(64),i=r.mul(e);return n.div(i)}getTokenBFromLiquidity(t,e,r){return t.mul(r.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:r}=t,n=t.txb||new Nf.TransactionBlock,i=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return n.moveCall({target:`${i.PackageId}::position_manager::burn`,typeArguments:o,arguments:[n.object(i.Positions),n.object(r),n.object(i.Versioned)]}),n}async getPositionLiquidityUSD(t){let{position:e,poolId:r,priceA:n,priceB:i}=t,o=await this.pool.getPool(r),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Mt.default(o.sqrt_price),lowerSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_lower_index.fields.bits)),upperSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_upper_index.fields.bits)),liquidity:new Mt.default(e.liquidity===void 0?1e8:e.liquidity)}),[u,l]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),d=new $(s[0].toString()).div(10**u.decimals).mul(n||0),b=new $(s[1].toString()).div(10**l.decimals).mul(i||0);return d.plus(b).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:r}=t,[n,i,o]=await Promise.all([this.pool.getPool(r),this.nft.getPositionTick(r,e.tick_lower_index),this.nft.getPositionTick(r,e.tick_upper_index)]),s={...t,pool:n,tickLowerDetail:i,tickUpperDetail:o},[u,l]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:d,...b}=u,{unclaimedRewards:_,...T}=l;return{fees:u.unclaimedFees.toString(),rewards:_.toString(),total:d.plus(_).toString(),fields:{...b,...T}}}async getUnclaimedFees(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,[s,u,l,d]=await Promise.all([this.coin.getMetadata(r.types[0]),this.coin.getMetadata(r.types[1]),n(r.types[0]),n(r.types[1])]),b=Ny(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),_=this.math.scaleDown(b.feeOwedA,s.decimals),T=this.math.scaleDown(b.feeOwedB,u.decimals);function x(C,E){return new $(1e6).mul($.pow(10,E)).lt(C)}x(_,s.decimals)&&(_="0",b.feeOwedA="0"),x(T,u.decimals)&&(T="0",b.feeOwedB="0");let A=l===void 0?new $(0):new $(l).mul(_),I=d===void 0?new $(0):new $(d).mul(T);return{unclaimedFees:A.plus(I),scaledFeeOwedA:_,scaledFeeOwedB:T,...b}}async getUnclaimedRewards(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,s=Fy(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),u=[...s],l=r.reward_infos.map(T=>this.coin.formatCoinType(T.fields.vault_coin_type)),d=await Promise.all([...r.reward_infos.map((T,x)=>this.coin.getMetadata(l[x]))]),b=await Promise.all(r.reward_infos.map((T,x)=>n(l[x])));d.forEach((T,x)=>{u[x]=this.math.scaleDown(u[x],T.decimals)});let _=new $(0);return r.reward_infos.some((T,x)=>{let A=b[x];return A?(_=_.plus(new $(A).mul(u[x])),!1):(_=_.plus(1),!0)}),{unclaimedRewards:_,collectRewards:s,scaledCollectRewards:u}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return wu(e,"nft"),e})}},Ly=class extends Mi{isSUI(t){return(0,Rf.normalizeSuiAddress)(t)==="0x000000000000000000000000000000000000000000000000000002::sui::sui"}async getMetadata(t){return this.getCacheOrSet(`coin-metadata-${t}`,async()=>{let e=await this.provider.getCoinMetadata({coinType:t});if(!e)throw new Error(`Coin "${t}" is not found`);return e})}async selectTradeCoins(t,e,r){if(r.eq(0))return[];let n=[],i=[],o=new $(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),n.push(...s.data);while(s.hasNextPage);n.sort((u,l)=>Number(l.balance)-Number(u.balance));for(let u of n)if(i.push(u.coinObjectId),o=o.add(u.balance),o.gte(r))break;return i}convertTradeCoins(t,e,r,n){return this.isSUI(r)?[t.splitCoins(t.gas,[t.pure(n.toNumber())])[0]]:e.map(i=>t.object(i))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let n=t.replace(/^0x/i,"");return n=n.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&n.length<64&&t!=="2::sui:SUI"?"0".repeat(64-n.length):"")+n}},Uy=60*1e3,Xo=100,$y=class extends Mi{async swap(t){let{coinTypeA:e,coinTypeB:r,address:n,amountSpecifiedIsInput:i,slippage:o}=t,s=new $(t.amountA),u=new $(t.amountB),l=await this.contract.getConfig(),d=await Promise.all(t.routes.map(async I=>{let C=await this.pool.getPoolTypeArguments(I.pool),[E,P]=await Promise.all([this.coin.getMetadata(C[0]),this.coin.getMetadata(C[1])]);return{...I,coinA:E,coinB:P,typeArguments:C}})),b=await this.coin.selectTradeCoins(n,e,s),{functionName:_,typeArguments:T}=this.getFunctionNameAndTypeArguments(d.map(({typeArguments:I})=>I),e,r),x=d.map(({nextTickIndex:I,coinA:C,coinB:E,a2b:P})=>{let D=this.math.tickIndexToPrice(I,C.decimals,E.decimals);return this.sqrtPriceWithSlippage(D,o,P,C.decimals,E.decimals)}),A=t.txb||new Qo.TransactionBlock;return A.moveCall({target:`${l.PackageId}::swap_router::${_}`,typeArguments:T,arguments:[...d.map(({pool:I})=>A.object(I)),A.makeMoveVec({objects:this.coin.convertTradeCoins(A,b,e,s)}),A.pure((i?s:u).toFixed(0),"u64"),A.pure(this.amountOutWithSlippage(i?u:s,o,i),"u64"),...x.map(I=>A.pure(I,"u128")),A.pure(i,"bool"),A.pure(n,"address"),A.pure(Date.now()+Uy*3,"u64"),A.object(es.SUI_CLOCK_OBJECT_ID),A.object(l.Versioned)]}),A}async computeSwapResult(t){let{pools:e,amountSpecified:r,amountSpecifiedIsInput:n,address:i,tickStep:o}=t,s=await this.contract.getConfig(),u=e.map(_=>_.pool),l=await Oi(this.provider,u,{showContent:!0}),d=new Qo.TransactionBlock;l.map(async _=>{let T=nr(_),x=e.find(P=>P.pool===T.id.id),A=this.math.bitsToNumber(T.tick_current_index.fields.bits),I=A-T.tick_spacing*(o||Xo),C=A+T.tick_spacing*(o||Xo);I=I<Jo?Jo:I,C=C>Ko?Ko:C;let E=this.pool.parsePoolType(ts(_));d.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:E,arguments:[d.object(T.id.id),d.pure(x.a2b,"bool"),d.pure(new $(r).toFixed(0),"u128"),d.pure(n,"bool"),d.pure(this.math.tickIndexToSqrtPriceX64(x.a2b?I:C).toString(),"u128"),d.object(es.SUI_CLOCK_OBJECT_ID),d.object(s.Versioned)]})});let b=await this.provider.devInspectTransactionBlock({transactionBlock:d,sender:i});if(b.error)throw new Error(b.error);return b.events.map(_=>_.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:r,address:n,tickStep:i}=t,o=await this.contract.getConfig(),s=e.map(b=>b.pool),u=await Oi(this.provider,Array.from(new Set(s)),{showContent:!0}),l=new Qo.TransactionBlock;e.forEach(async b=>{let _=u.find(E=>rs(E)===b.pool),T=nr(_),x=this.math.bitsToNumber(T.tick_current_index.fields.bits),A=x-T.tick_spacing*(i||Xo),I=x+T.tick_spacing*(i||Xo);A=A<Jo?Jo:A,I=I>Ko?Ko:I;let C=this.pool.parsePoolType(ts(_));l.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:C,arguments:[l.object(T.id.id),l.pure(b.a2b,"bool"),l.pure(new $(b.amountSpecified).toFixed(0),"u128"),l.pure(r,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(b.a2b?A:I).toString(),"u128"),l.object(es.SUI_CLOCK_OBJECT_ID),l.object(o.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:n});if(d.error)throw new Error(d.error);return d.events.map(b=>b.parsedJson)}getFunctionNameAndTypeArguments(t,e,r){let n=[],i=["swap"];if(t.length===1)n=t[0],e===n[0]?i.push("a","b"):i.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(i.push("a","b"),n.push(o[0],o[2],o[1])):(i.push("b","a"),n.push(o[1],o[2],o[0])),n.push(s[2],r),r===s[0]?i.push("c","b"):i.push("b","c")}return{functionName:i.join("_"),typeArguments:n}}amountOutWithSlippage(t,e,r){if(r){let i=new $(100).minus(e).div(100);return new $(t).mul(i).toFixed(0)}let n=new $(100).plus(e).div(100);return new $(t).mul(n).toFixed(0)}sqrtPriceWithSlippage(t,e,r,n,i){let o=new $(t).mul(r?new $(100).minus(e).div(100):new $(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,n,i);return s.lt(new yu.BN(gu))?gu:s.gt(new yu.BN(mu))?mu:s.toString()}},It=class{constructor(t,e){this.network=t,rr(this,"pool"),rr(this,"contract"),rr(this,"math",new Dy),rr(this,"account",new Ay),rr(this,"coin"),rr(this,"nft"),rr(this,"trade"),rr(this,"provider"),this.provider=e?e instanceof tn.SuiClient?e:new tn.SuiClient(e):new tn.SuiClient({url:t==="mainnet"?(0,tn.getFullnodeUrl)("mainnet"):(0,tn.getFullnodeUrl)("testnet")}),this.contract=new Py(this),this.pool=new By(this),this.nft=new qy(this),this.coin=new Ly(this),this.trade=new $y(this)}};var Gy=Object.defineProperty,uh=(t,e)=>{for(var r in e)Gy(t,r,{get:e[r],enumerable:!0})},St=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,lh.default)(this.data))}},Vy={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},_u=new nd(Vy),zy=async(t,e,r,n,i)=>{console.log("getSwapRouterTxb account2: ",n),console.log("getSwapRouterTxb suiClient: ",i),_u.senderAddress=r;let o=await _u.getOwnerCoinAssets(r);return await Pe.buildAggregatorSwapTransaction(_u,t,o,"",e)},Wy=class dh extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r,suiClient:n}=e,{payloadParams:i}=this.data,o=await zy(i?.createTxParams,i?.slippage,i?.account,r,n);return console.log("Swap intention build txb: ",o),o}static fromData(e){return new dh(e)}},Hy=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{payloadParams:e,action:r}=t;return{txType:ch.TransactionType.Other,txSubType:`Cetus${r}`,intentionData:{payloadParams:e,action:r}}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"CetusSwap":n=Wy.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},hh={};uh(hh,{contractId:()=>gh,default:()=>Zy,feeObjId:()=>bh,roleObjId:()=>wh,status:()=>mh,transaction:()=>ph,upgradeCapObjId:()=>_h,vaultObjId:()=>yh});var ph="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",mh="success",gh="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",wh="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yh="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",bh="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_h="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zy={transaction:ph,status:mh,contractId:gh,roleObjId:wh,vaultObjId:yh,feeObjId:bh,upgradeCapObjId:_h},vh={};uh(vh,{contractId:()=>xh,default:()=>Ky,feeObjId:()=>Ih,roleObjId:()=>kh,status:()=>Sh,transaction:()=>Th,upgradeCapObjId:()=>Ch,vaultObjId:()=>Ah});var Th="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sh="success",xh="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",kh="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ah="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Ih="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ch="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ky={transaction:Th,status:Sh,contractId:xh,roleObjId:kh,vaultObjId:Ah,feeObjId:Ih,upgradeCapObjId:Ch},Jy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Xy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Yy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",eb="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tb="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",rb="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",nb="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",jf=hh,Ff=vh,ib=new Map([["dev",{env:"dev",rpc:{url:Jy},backend:{url:eb},contract:jf}],["stg",{env:"stg",rpc:{url:Xy},backend:{url:tb},contract:jf}],["prev",{env:"prev",rpc:{url:Yy},backend:{url:rb},contract:Ff}],["prod",{env:"prod",rpc:{url:Qy},backend:{url:nb},contract:Ff}]]);function ob(t,e){let r=ib.get(t);if(!r)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(r.rpc=e.rpc),e&&e.backend&&(r.backend=e.backend),e&&e.contract&&(r.contract=e.contract),r}var Nt=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:i}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=i}},sb=class extends Nt{constructor(){super(11,"Backend is not specified")}},ab=class extends Nt{constructor(){super(1,"Wallet not connected")}},vu=class extends Nt{constructor(t,e){super(10,t,{context:e})}},ub=class nn{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof dr.AxiosError)throw new vu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new vu(e.data.code)}throw new vu(e.status.toString())}async getIncomingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{recipient:e,...r});return nn.parseResponseData(n)}async getOutgoingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{sender:e,...r});return nn.parseResponseData(n)}async getStreamHistory(e){let r=await dr.default.post(`${this.apiURL}/stream-events`,e),n=nn.parseResponseData(r);return n.data.forEach(i=>{let o=i;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}),n}async getAllCoinTypes(e){let r=await dr.default.post(`${this.apiURL}/stream-info`,{address:e});return nn.parseResponseData(r)}async getAllRecipients(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:r});return nn.parseResponseData(n)}async getAllSenders(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:r});return nn.parseResponseData(n)}},Mh=class Eh{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Oh.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new ub(e.backend.url))}static new(e,r){let n=ob(e,r);return new Eh(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new sb;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new ab;return this.signer}async walletAddress(){return this.wallet.address()}},qf=50n,Tu=10000n,cb=25n,Lf=100000000n,rn=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Uf=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},as=class Ph{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(r,n){if(n in r)return Reflect.get(r,n);let i=s=>new Ph(r.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield i(s),s++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}moveArg(){return this.result}},$f=class extends Nt{constructor(t,e){super(3,t,{context:e})}},lb=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="address")throw new $f("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Dh.normalizeSuiAddress)(Au.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new $f("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Au.Buffer.from(r).readBigInt64LE()}},Bt=class extends Nt{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}},Bh={groupId:"string",name:"string"},db=64;function fb(t){return Nh(t),Ru.bcs.ser(Bh,t).toString("base64")}function Iu(t){let e=Ru.bcs.de(Bh,t,"base64");return Nh(e),e}function Nh(t){if(!Gf(t.name))throw new Bt("Invalid metadata: Name contains unknown character");if(!Gf(t.groupId))throw new Bt("Invalid metadata: Group ID contains unknown character");if(t.name.length>db)throw new Bt("Invalid metadata: Name exceed max length 64")}function Gf(t){return/^[\x00-\x7F]+$/.test(t)}function Rh(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}function jn(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}var jh="txn.gas";function hb(){return pf()}var Cu=class Fh{constructor(e,r,n){this.globals=e,this.feeContract=r,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:fb({name:e.name,groupId:hb()}),coinType:(0,Bi.normalizeStructTag)(e.coinType),recipients:e.recipients.map(r=>({address:r.address,cliffAmount:r.cliffAmount,amountPerEpoch:r.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let r=new ku.TransactionBlock,n=this.calculateFeesInternal(e),i=this.getCreateStreamCoinRequests(e,n),o=await this.wallet.requestCoins(i),s=await this.addMergeCoins(r,o[0]),u;i.length>1?u=await this.addMergeCoins(r,o[1]):u=s;for(let l=0;l<e.recipients.length;l++){let d=e.recipients[l],b=this.amountForRecipient(d,e.numberEpoch),_=this.getStreamFeeLocal(b),[T]=r.splitCoins(s,[r.pure(b+_,"u64")]),[x]=r.splitCoins(u,[r.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(r,{paymentCoin:new as(T),flatFeeCoin:new as(x),metadata:e.metadata,recipient:d.address,timeStart:e.startTime,cliff:d.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return r}calculateCreateStreamFees(e){let r=Fh.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(r)}feeParams(){return{createFeePercent:{numerator:qf,denominator:Tu},claimFeePercent:{numerator:cb,denominator:Tu},flatFeePerStream:Lf}}async addMergeCoins(e,r){let n;return r.mergedCoins&&r.mergedCoins.length?(e.mergeCoins(e.object(r.primaryCoin),r.mergedCoins.map(i=>e.object(i))),n=e.object(r.primaryCoin)):r.primaryCoin===jh?n=e.gas:n=e.object(r.primaryCoin),n}getCreateStreamCoinRequests(e,r){let n=e.coinType;return Rh(n,Bi.SUI_TYPE_ARG)?[{coinType:n,amount:r.totalAmount+r.streamFeeAmount+r.flatFeeAmount}]:[{coinType:n,amount:r.totalAmount+r.streamFeeAmount},{coinType:Bi.SUI_TYPE_ARG,amount:r.flatFeeAmount}]}calculateFeesInternal(e){let r=e.recipients.reduce((n,i)=>{let o=this.amountForRecipient(i,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:n.totalAmount+o,streamFeeAmount:n.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...r}}amountForRecipient(e,r){return BigInt(e.amountPerEpoch)*BigInt(r)+BigInt(e.cliffAmount)}get flatSuiFee(){return Lf}getStreamFeeLocal(e){return e*qf/Tu}async getStreamFeeRemote(e){let r=this.feeContract.streamingFee(new ku.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:r});return new lb(n).getU64()}get wallet(){return this.globals.wallet}},pb="0x0000000000000000000000000000000000000000000000000000000000000006",qh=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(Ou.Transactions.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof Uf?n.moveArgs(t):n instanceof rn?n.moveArg(t):n instanceof as?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(Ou.Transactions.MoveCall({target:e,arguments:r.map(i=>i instanceof Uf?i.moveArgs(t):i instanceof rn?i.moveArg(t):i instanceof as?i.moveArg():t.pure(i)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new rn(t):t}vaultObject(){return new rn(this.config.vaultObjId)}roleObject(){return new rn(this.config.roleObjId)}feeObject(){return new rn(this.config.feeObjId)}clockObject(){return new rn(pb)}},Lh=class Er extends qh{constructor(e,r){super(Er.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_fee,arguments:[n,i,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_flat_fee,arguments:[n,i,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_claim_fee,arguments:[n,i,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:Er.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:Er.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},cs=class Tt extends qh{constructor(e,r){super(Tt.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let n=this.feeObject(),i=this.vaultObject(),o=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.create_stream,arguments:[n,i,o,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:Tt.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.cancel_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),i=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream_by_proxy,arguments:[n,i,o,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream_by_proxy}`}},Uh=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lh(e,t),this.streamContract=new cs(e,t)}feeContract;streamContract;async createStreams(t){let e=Cu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new Pi.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}},mb=class extends Nt{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},gb=1e3,wb=class{constructor(t){this.globals=t,this.coinMetaHelper=new yb(t.suiClient),this.createStreamHelper=new Uh(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mb(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 Bt("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new Bt("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 Bt("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(_e.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:_e.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:(0,Ln.normalizeStructTag)(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,i)=>({...n,coinType:(0,Ln.normalizeStructTag)(n.coinType),coinMeta:r[i]}))}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 Bt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Bt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<gb)throw new Bt("Interval shall be at least 1 second","interval",t.interval)}},yb=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ln.normalizeStructTag)(t||Ln.SUI_TYPE_ARG);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}},bb=class extends Nt{constructor(){super(7,"Connected wallet is not creator")}},Vf=class extends Nt{constructor(){super(8,"Connected wallet is not recipient")}},zf=class extends Nt{constructor(t,e){super(6,t,{context:e})}},Xt=class extends Nt{constructor(t,e={}){super(0,t,e)}},_b=class extends Nt{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},vb=(1n<<64n)-1n,us=1e3;function Wf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return le.fromMillis(r*us)}function Hf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return _e.fromMillis(r*us)}var ju=class Pr{constructor(e,r,n){this.globals=e,this.streamId=r,this.rawData=n,this.streamContract=new cs(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,r){let n=await Pr.fetchStreamData(e,r);return new Pr(e,r,n)}static fromObjectData(e,r,n){let i=Pr.parseRawStreamData(r,n);return new Pr(e,r,i)}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 Pr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Xt("Object Id does not align");this.rawData=Pr.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new bb;let e=new Di.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let e=new Di.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let r=new Di.TransactionBlock;return this.streamContract.setAutoClaim(r,{streamId:this.streamId,coinType:this.coinType,enabled:e}),r}async claimByProxy(){let e=new Di.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Ri.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Hf(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Iu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Iu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Wf(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,r=e.epochInterval*e.totalEpoch;return Hf(r)}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:Wf((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 e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===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===vb?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=le.now().toMillis(),r=this.timeStart.toMillis();if(e<r)return-1n;let n=Math.floor((e-r)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,r){let n=await e.suiClient.getObject({id:r,options:{showContent:!0,showType:!0}});return Pr.parseRawStreamData(r,n)}static parseRawStreamData(e,r){if(r.error)throw r.error.code==="notExists"?new _b(e):new zf(`get stream data: ${r.error.code}`,{streamId:e,...r.error});let n=r.data.content;if(n.dataType!=="moveObject")throw new zf("Unexpected object type",{gotType:n.dataType});let{typeParams:i}=(0,Ri.parseStructTag)(n.type),o=(0,Ri.normalizeStructTag)(i[0]),s=n.fields,u=s.config.fields,l=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}},Su=class extends Nt{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Tb(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sb=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)}},$h=class{constructor(t){this.requester=t,this.pager=new Sb(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]}},xb=25;async function Zf(t,e,r){let n=new Gh(e),i=new Vh(t,n,r);return await Tb(i)}var Gh=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]}},Vh=class extends $h{constructor(t,e,r){super(new kb(t,e,r)),this.suiClient=t,this.idIter=e,this.options=r}},kb=class{constructor(t,e,r){this.suiClient=t,this.stringIter=e,this.options=r,this.filter=r?.filter,this.pageSize=r?.pageSize||xb,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 n=await this.stringIter.next();n&&t.push(n)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:n}=this;r=e.filter(i=>n?.(i))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}},Ab=class ns{constructor(e,r){if(this.globals=e,this.streams=r,r.length===0)throw new Su("stream size 0");let n=r.map(i=>i.groupId);if(new Set(n).size!==1)throw new Bt("Stream does not have same group ID")}type="StreamGroup";static async new(e,r){let n=await Zf(e.suiClient,r);return n.forEach(i=>{if(!i)throw new Xt("stream group object data undefined")}),ns.newFromObjectResponse(e,r,n)}static async newFromObjectResponse(e,r,n){let i=await ns.parseGroupStreams(e,r,n);return new ns(e,i)}static checkStreamGroup(e){let r=e.map(o=>o.groupCommonInfo),n=r[0],i=!0;return r.forEach(o=>{Ib(n,o)||(i=!1)}),i}async refresh(){let e=await Zf(this.globals.suiClient,this.streams.map(r=>r.streamId));this.streams.forEach((r,n)=>{r.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,r)=>e+r.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,r)=>e+r.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,r)=>r.nextReleaseAmount===null?e:e+r.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,r)=>e+r.totalAmount,0n),streamed:this.streams.reduce((e,r)=>e+r.streamedAmount,0n),claimed:this.streams.reduce((e,r)=>e+r.claimedAmount,0n),claimable:this.streams.reduce((e,r)=>e+r.claimable,0n),canceled:this.streams.reduce((e,r)=>e+r.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,r,n){let i=n.map((o,s)=>ju.fromObjectData(e,r[s],o)).filter(o=>!!o);if(new Set(i.map(o=>o.groupId)).size!==1)throw new Su("Not same group ID");if(!this.checkStreamGroup(i))throw new Su("Not same stream settings");return i}};function Ib(t,e){return t.name===e.name&&t.groupId===e.groupId&&t.creator===e.creator&&t.start.toMillis()===e.start.toMillis()&&t.interval.toMillis()===e.interval.toMillis()&&t.steps===e.steps&&t.cancelable===e.cancelable}var Kf=class Mu{constructor(e,r){this.it=e,this.pageSize=r}static async newIncoming(e){let r=await Jf.newIncoming(e);return new Mu(r,e.pageSize)}static async newOutgoing(e){let r=await Jf.newOutgoing(e);return new Mu(r,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Jf=class Eu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let r=await Xf.newIncomingQuery(e);return new Eu(r)}static async newOutgoing(e){let r=await Xf.newOutgoingQuery(e);return new Eu(r)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let r=await this.requester.doNextRequest();if(r===null)throw new Xt("No more results");return r}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Xt("No more results");return e}},Xf=class Pu{constructor(e,r,n,i){this.globals=e,this.recipient=r,this.groupRefs=n,this.query=i,this.current=0;let o=new Gh(n.flat().map(s=>s.streamId));this.objectIter=new Vh(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let r=Pb(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,r)).filter(s=>(0,Rr.normalizeSuiAddress)(s.recipient)===(0,Rr.normalizeSuiAddress)(n)),o=Yf(i);return new Pu(e.globals,n,o,e.query)}static async newOutgoingQuery(e){let r=Db(e.query),n=await e.globals.walletAddress(),i=await e.globals.backend.getOutgoingStreams(n,r),o=Yf(i);return new Pu(e.globals,n,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let r=await Mb(this.globals,e[0].streamId,this.objectIter);return this.current++,zh(r,this.query)?r:this.doNextRequest()}if(e.length>1){let r=await Eb(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Ob(r,this.query)?r:this.doNextRequest()}throw new Xt("Stream group with no stream")}};function Yf(t){let e=new Map;return t.forEach(r=>{let n=e.get(r.groupId);n?(n.push(r),e.set(r.groupId,n)):e.set(r.groupId,[r])}),Array.from(e.values()).sort((r,n)=>le.fromISO(n[0].createDate).toMillis()-le.fromISO(r[0].createDate).toMillis())}function zh(t,e){if(e===void 0)return!0;let r=Cb(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return r&&n}return r}function Cb(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function Ob(t,e){if(!e)return!0;let r=!1;return t.streams.forEach(n=>{zh(n,e)&&(r=!0)}),r}async function Mb(t,e,r){let n=await Wh(r,e);return ju.fromObjectData(t,e,n)}async function Eb(t,e,r){let n=[];for(;n.length<e.length;){let i=await Wh(r,e[n.length]);n.push(i)}return Ab.newFromObjectResponse(t,e,n)}async function Wh(t,e){if(!await t.hasNext())throw new Xt("object iterator has been consumed");let r=await t.next();if(!r||r.error||r.data===void 0||r.data===null)throw new Xt("object iterator undefined response",{cause:r?.error});if(r?.data?.objectId!==e)throw new Xt("stream id not aligned");return r}function Pb(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),sender:Zh(t?.sender)}}function Db(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),recipient:Zh(t?.recipient)}}function Fu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,r)=>{let n=Fu(r);return!e||e===n?n:"all"},void 0):Bb(t)}function Bb(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Bt("Unknown stream filtered status")}}function Hh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeStructTag)(e)):void 0:(0,Rr.normalizeStructTag)(t)}function Zh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeSuiAddress)(e)):void 0:(0,Rr.normalizeSuiAddress)(t)}var Nb=class extends Nt{constructor(t,e,r){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:r}}),this.coinType=t,this.requestAmount=e,this.gotAmount=r}},Rb=25;async function jb(t,e,r,n="0x2::sui::SUI",i=Rb){let o=new Fb(t,e,n,i),s=BigInt(0),u=[];for(;await o.hasNext()&&s<r;){let l=await o.next();l&&(u.push(l),s+=BigInt(l.balance))}if(s<r)throw new Nb(n,r,s);return u}var Fb=class extends $h{constructor(t,e,r,n){super(new qb(t,e,r,n)),this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n}},qb=class{constructor(t,e,r,n){if(this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n,n<=0)throw new Xt("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}}},Lb=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ub=class{constructor(t){this.account=t}async address(){return this.account.address}},$b=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(Rh(t.coinType,on.SUI_TYPE_ARG))return{primaryCoin:jh};if(t.amount<=0)throw new Bt("Invalid coin request","coinAmount",t.amount);let e=await jb(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new Xt("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Gb=class{globals;helper;constructor(t,e){this.globals=Mh.new(t,e),this.helper=new wb(this.globals)}connectSingleWallet(t){let e=new $b(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Lb(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ju.new(this.globals,t)}async getIncomingStreams(t,e=10){return Kf.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Kf.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(e=>(0,on.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}get wallet(){return this.globals.wallet}builder(){return new Uh(this.globals)}},Vb=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Kh.default)(this.data))}},ji=class extends Vb{application="mpay";getClient(t,e){let r=new Gb(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ub(e)),r}},Qf=class extends ji{constructor(t){super(t),this.data=t}txType=fh.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).cancel()}},eh=class extends ji{constructor(t){super(t),this.data=t}txType=Jh.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claimByProxy()}},th=class extends ji{constructor(t){super(t),this.data=t}txType=Xh.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claim()}},rh=class extends ji{constructor(t){super(t),this.data=t}txType=Yh.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:r}=t;return this.getClient(e,r).createStream(this.data)}},Qh=class is{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return is.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return is.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return BigInt(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Dr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return is.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Dr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Dr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Dr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Dr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Dr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},zb=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 t=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&jn(e.target,this.contract.createStreamTarget));if(t.length===0)throw new Xt("No create stream transactions");return t.map(e=>new Qh(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=Iu(e),i=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),b=t.decodeInputBool(11),_=t.typeArg(0);return{name:r,groupId:n,recipient:i,timeStart:o,cliff:s,epochInterval:u,totalEpoch:l,amountPerEpoch:d,cancelable:b,coinType:_}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new Bt("Stream group not have common info");let e=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:e,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 cs(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lh(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Cu(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]}},Wb=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new cs(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(t=>t.kind==="MoveCall"&&jn(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new zb(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(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let t=this.transactions[0];return new Qh(t,this.txb)}},nh=class extends ji{constructor(t){super(t),this.data=t}txType=ep.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Hb=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,n=Mh.new(e==="sui:mainnet"?"prod":"dev"),i=new Wb(n,r).decode(),o;switch(i.type){case"CreateStream":o=new rh(i.info);break;case"SetAutoClaim":o=new nh({streamId:i.streamId,enabled:i.enabled});break;case"Claim":o=new th({streamId:i.streamId});break;case"ClaimByProxy":o=new eh({streamId:i.streamId});break;case"Cancel":o=new Qf({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,r;switch(t.txSubType){case"CreateStream":r=new rh(e);break;case"Claim":r=new th(e);break;case"ClaimByProxy":r=new eh(e);break;case"SetAutoClaim":r=new nh(e);break;case"Cancel":r=new Qf(e);break;default:throw new Error("not implemented")}return r.build({...t})}},Zb=class rp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,tp.buildCoinTransferTxb)(r,this.data,n.address)}static fromData(e){return new rp(e)}},Kb=class ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,np.buildObjectTransferTxb)(r,this.data,n.address)}static fromData(e){return new ip(e)}},Jb=class ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=sp.TransactionBlock.from(this.data.content);if(!(0,op.isSameAddress)(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ap(e)}},Xb=class{application;constructor(){this.application=qn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case qn.TransactionSubTypes.assets.coin.send:n=Zb.fromData(t.intentionData);break;case qn.TransactionSubTypes.assets.object.send:n=Kb.fromData(t.intentionData);break;case qn.TransactionSubTypes.others.plain:n=Jb.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},Yb={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"}}},ce=Yb,Qb=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ce.pool).find(r=>r.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${ce.ProtocolPackage}::incentive_v2::claim_reward`){let r=new ih(e,this.txb),n=r.decodeInputU8(4),i=r.decodeInputU8(5),o=r.decodeSharedObjectId(2),s=this.findPoolByAssetId(n),u=[...e.typeArguments];t.push({coinType:s.coinType,option:i,typeArguments:u,assetId:n,poolId:o})}}),console.log("decode claims",t),{txType:Fn.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.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:Fn.TransactionType.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:Fn.TransactionType.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:Fn.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ce.ProtocolPackage));return new ih(t,this.txb)}},ih=class os{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return os.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return os.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Br.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return os.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Br.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Br.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Br.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Br.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Br.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function oh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function e_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function t_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function sh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function r_(t,e,r,n,i){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ce.IncentiveV2),t.object(r),t.object(ce.StorageId),t.pure(e),t.pure(n)],typeArguments:i}),t}var n_=class lp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new cp.TransactionBlock;return e.forEach(n=>{let{assetId:i,poolId:o,option:s,typeArguments:u}=n;r_(r,i,o,s,u)}),r}static fromData(e){return new lp(e)}},i_=class fp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new dp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return t_(n,i,r)}static fromData(e){return new fp(e)}};async function pp(t,e,r){let n=await t.getCoins({owner:e,coinType:r});return console.log("getTokenObjs",e,n),n}var o_=class mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new hp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return oh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return oh(s,u,s.object(d),o)}static fromData(e){return new mp(e)}},s_=class wp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new gp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return sh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return sh(s,u,s.object(d),o)}static fromData(e){return new wp(e)}},a_=class bp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new yp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return e_(n,i,r)}static fromData(e){return new bp(e)}},u_=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,r=new Qb(e).decode();return{txType:up.TransactionType.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=o_.fromData(t.intentionData);break;case"EntryBorrow":n=i_.fromData(t.intentionData);break;case"EntryRepay":n=s_.fromData(t.intentionData);break;case"EntryWithdraw":n=a_.fromData(t.intentionData);break;case"ClaimReward":n=n_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},c_=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}},l_="msafe-plain-tx",d_=ls.TransactionSubTypes.others.plain,f_=class{application;constructor(){this.application=l_}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ls.TransactionType.Other,txSubType:d_,intentionData:{content:(0,ds.toHEX)(n)}}}async build(t){let{suiClient:e,account:r}=t,n=_p.TransactionBlock.from((0,ds.fromHEX)(t.intentionData.content)),i=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(i.effects.status.status!=="success")throw new Error(i.effects.status.error);return n}},xu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},h_=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(10),n=this.helper.decodeInputU64(11),i=this.helper.decodeInputU32(6),o=this.helper.decodeInputU32(8);return{txType:Tp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:n,tickLower:i,tickUpper:o}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new p_(t,this.txb)}},p_=class ss{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return ss.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return ss.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU32(e){let r=this.decodePureArg(e,"u32");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Nr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return ss.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Nr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Nr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Nr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Nr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Nr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},m_=class Sp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,tickLower:l,tickUpper:d,txb:b}=this.data;return r.pool.addLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,tickLower:l,tickUpper:d,txb:b})}static fromData(e){return new Sp(e)}},g_=class xp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,nft:i,txb:o}=this.data;return r.nft.burn({pool:n,nft:i,txb:o})}static fromData(e){return new xp(e)}},w_=class kp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,collectAmountA:s,collectAmountB:u,txb:l}=this.data;return r.pool.collectFee({pool:n,address:i,collectAmountA:s,collectAmountB:u,nft:o,txb:l})}static fromData(e){return new kp(e)}},y_=class Ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,rewardAmounts:s,txb:u}=this.data;return r.pool.collectReward({pool:n,address:i,rewardAmounts:s,nft:o,txb:u})}static fromData(e){return new Ap(e)}},b_=class Ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{fee:n,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,amountA:_,amountB:T,txb:x}=this.data;return r.pool.createPool({fee:n,amountA:_,amountB:T,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,txb:x})}static fromData(e){return new Ip(e)}},__=class Cp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,txb:b}=this.data;return r.pool.decreaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,decreaseLiquidity:d,txb:b})}static fromData(e){return new Cp(e)}},v_=class Op extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,txb:d}=this.data;return r.pool.increaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,txb:d})}static fromData(e){return new Op(e)}},T_=class Mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x}=this.data;return r.pool.removeLiquidity({pool:n,decreaseLiquidity:d,nft:l,amountA:o,amountB:s,slippage:u,address:i,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x})}static fromData(e){return new Mp(e)}},ah=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=new h_(e).decode();return{txType:vp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r,network:n}=t,i;switch(t.txSubType){case"CreatePool":i=b_.fromData(t.intentionData);break;case"AddLiquidity":i=m_.fromData(t.intentionData);break;case"IncreaseLiquidity":i=v_.fromData(t.intentionData);break;case"DecreaseLiquidity":i=__.fromData(t.intentionData);break;case"RemoveLiquidity":i=T_.fromData(t.intentionData);break;case"CollectFee":i=w_.fromData(t.intentionData);break;case"CollectReward":i=y_.fromData(t.intentionData);break;case"Burn":i=g_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:r,network:n})}},fs=new c_([new Xb,new u_,new ah,new Hb,new f_,new Hy,new ah]);var me=require("@msafe/sui3-utils"),Hu=require("@mysten/sui.js/transactions"),bs=require("@mysten/sui.js/utils");var Ep=require("@mysten/sui.js/transactions"),S_=1000n,x_=120n,k_=100n,A_={multiplier:{numerator:x_,denominator:k_}};var hs=class{constructor(e){this.globals=e}async simulate(e,r=A_){let n=this.copyTransactionBlock(e.txb),{suiClient:i}=this.globals,o=await this.getGasPrice(r);n.setGasPrice(o);let s=await i.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:u}=s.effects,l=this.toGasBudget(u,o),d=s.effects.status.status==="success",b;return d||(b=s.effects.status.error),{success:d,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:u,gasBudget:l,simulationError:b}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let r=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(r,e)}toGasBudget(e,r){let{computationCost:n,storageCost:i}=e,o=S_*r,s=BigInt(n)+o,u=s+BigInt(i);return u>s?u:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,r){if(this.isFixedValue(r))return r.fixedVal;if(this.isMultiplier(r)){let{multiplier:n}=r;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ep.TransactionBlock.from(e.serialize())}};var qu=require("buffer");function ps(t){return qu.Buffer.from(t,"utf-8")}function I_(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ms(t){return Uint8Array.from(qu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ws=require("@mysten/sui.js/verify");var jr=require("@mysten/sui.js/utils");var gs=require("@mysten/sui.js/utils"),Fi=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let r=(0,gs.normalizeStructTag)(e);if(this._coinMetaReg.has(r))return this._coinMetaReg.get(r);let n=await this.queryCoinMeta(r);return n&&this._coinMetaReg.set(r,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Lu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,qi=class t{static isCoin(e){return e?(0,gs.normalizeStructTag)(e).match(Lu)!=null:!1}static getCoinType(e){let[,r]=(0,gs.normalizeStructTag)(e).match(Lu)??[];return r||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:r}=e.content?.fields;if(r!==void 0)return BigInt(r)}};var fr=class{static normalizeSuiAddress(e){return(0,jr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,jr.normalizeStructTag)(e)}static isSuiAddressEqual(e,r){return(0,jr.normalizeSuiAddress)(e)===(0,jr.normalizeSuiAddress)(r)}static isSuiStructEqual(e,r){return(0,jr.normalizeStructTag)(e)===(0,jr.normalizeStructTag)(r)}static isCoinObjectType(e){return qi.isCoin(e)}};function Uu(t,e){return t.startsWith(e)?t:e+t}var $u=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ws.verifyTransactionBlock)(e.message,e.signature):(0,ws.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let r=ps(e.messageStr);return this.getPublicKeyFromSignature({message:r,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let r=await t.getPublicKeyFromSignature(e);return fr.isSuiAddressEqual(r.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let r=ps(e.messageStr);return this.verifySignature({message:r,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Pp=require("@msafe/sui3-utils"),Dp=require("@mysten/sui.js/cryptography"),Bp=require("@mysten/sui.js/multisig");var C_="0x2::sui::SUI";async function Gu(t,e){let r;try{r=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(r.data.length===0||!r.data[0].transaction?.txSignatures)return;let i=r.data[0].transaction?.txSignatures;for(let o=0;o!==i.length;o++){let s=i[o],u=O_(s,e);if(u)return u}}function O_(t,e){let r=(0,Dp.parseSerializedSignature)(t);switch(r.signatureScheme){case"MultiSig":{let n=new Bp.MultiSigPublicKey(r.multisig.multisig_pk).toSuiAddress();if(fr.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(fr.isSuiAddressEqual(r.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Pp.PublicKeySerde.de({publicKeyEncoded:r.publicKey,schema:r.signatureScheme});return fr.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function M_(t){let e=!0,r,n=[];for(;e;){let i=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:r});n.push(...i.data),e=i.hasNextPage,r=i.nextCursor}return n}var Np=25;async function Rp(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Vu=class{constructor(e){this.requester=e;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)}},ys=class{constructor(e){this.requester=e;this.pager=new Vu(e),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]}};async function jp(t,e,r){let n=new zu(t,e,r);return await Rp(n)}var zu=class extends ys{constructor(r,n,i){super(new Wu(r,n,i));this.provider=r;this.owner=n;this.options=i}},Wu=class{constructor(e,r,n){this.provider=e;this.owner=r;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Np,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let r;if(this.filter){let{filter:n}=this;r=e.data.filter(i=>n?.(i))}else r=e.data;return{data:r.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var sn=class t{constructor(e,r){this.globals=e;this.info=r;this.multiSig=new me.MultiSigAccount({threshold:r.threshold,ownersWithWeight:r.owners,creationNonce:r.creationNonce}),this.coinHelper=new Fi(this.suiClient),this.simulator=new hs(e)}multiSig;coinHelper;simulator;static async New(e,r){let n=await e.backend.getMSafeAccountInfo(r);if(new t(e,n).address!==r)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async r=>{let n=await this.coinHelper.getCoinMeta(r.coinType),i=r.lockedBalance.number?BigInt(r.totalBalance)-BigInt(r.lockedBalance.number):BigInt(r.totalBalance);return{type:(0,bs.normalizeStructTag)(r.coinType),balance:BigInt(i),metadata:n}}))}async ownedObjects(e){let r={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return jp(this.suiClient,this.address,r)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let r=e.pending,n=e.reject;return{application:r.application,txType:r.txType,txSubType:r.txSubType,createdAt:r.createdAt,creator:r.creator,digest:r.digest,intention:r.intention,sequenceNumber:r.sequenceNumber,payload:r.payload,votes:r.votes,approvalWeight:this.calculateWeightFromVotes(r.votes),msafeAddress:r.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let r=me.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:r});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let i=await n.build({client:this.globals.suiClient}),o=await n.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,bs.toHEX)(i),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async proposeCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async simulateObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async proposeObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async simulatePlainPayloadIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async proposePlainPayloadIntention(e){let r=await this.nextSequenceNumber(),n=Hu.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,me.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async voteForTransaction(e,r){let n=ms(r),i=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:i.signature})}async proposePendingTransaction(e){let r=new Hu.TransactionBlock,n=await r.build({client:this.suiClient}),i=await r.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:i,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let r=e.payload,n=(0,me.buildRejectTxb)(this.address,r);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let r=await this.pendingTransaction();if(!r||r.rejectDigest!=="")throw new Error("Already rejected");let n=r.payload,i=(0,me.buildRejectTxb)(this.address,n),o=await i.getDigest({client:this.suiClient}),s=await i.build({client:this.suiClient}),u=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:u.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,r=!1){let n=r?e.rejectVotes:e.votes,i=r?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(n.map(l=>[l.userAddress,l.signature]));for(let l=0;l<this.info.owners.length;l++){let d=this.info.owners[l],b=s.get(d.address);b&&o.push(b)}let u=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ms(i),signature:u,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(r=>r.userAddress))}calculateWeight(e){let r=0;for(let n=0;n<e.length;n++){let i=this.info.owners.find(o=>(0,me.isSameAddress)(o.address,e[n]));i&&(r+=i.weight)}return r}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Fp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/utils");var _s=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let r=this.knownPublicKeys.get(e);if(r)return r;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let r=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];r[o]=this.knownPublicKeys.get(s)}let n=r.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(n.length===0)return r;let i=await this.globals.backend.getPublicKeyBatch(n.map(o=>e[o]));for(let o=0;o<n.length;o++){let s=n[o];r[s]=i[o]}for(let o=0;o<r.length;o++)r[o]===void 0&&(r[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)r[o]&&this.knownPublicKeys.set(e[o],r[o]);return r}addPublicKey(e,r){if(!(0,Fp.isSameAddress)(e,r.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,qp.normalizeSuiAddress)(e),r)}async _getPublicKey(e){let r=await this.getPublicKeyFromBackend(e);if(r)return r;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Gu(this.globals.suiClient,e)}};var vs=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Wp=require("@mysten/sui.js/client");var Ui=require("@msafe/sui3-utils"),Li=de(require("axios"),1);var Ts=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let r=await this.post("/auth/login",e);return this._token=r.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let r={userAddressList:e};return(await this.get("/user/public-keys",{params:r,headers:this.headers()})).data?.map(i=>i?Ui.PublicKeySerde.de(i):void 0)}async getMSafeAccountInfo(e){let r={msafeAddress:e},n=await this.get("/msafe",{params:r,headers:this.headers()});return t.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let r={status:e.status??Ui.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:r,headers:this.headers()});return{data:n.data.data.map(t.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let r=e;await this.post("/msafe/status",r,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(r=>({address:r.address,weight:r.weight,publicKey:Ui.PublicKeySerde.de({publicKeyEncoded:r.publicKeyEncoded,schema:r.schema})}))}}async get(e,r){let n=this.getFullUrl(e);try{return await Li.default.get(n,r)}catch(i){throw Ss.fromError(i)??i}}async post(e,r,n){let i=this.getFullUrl(e);try{return await Li.default.post(i,r,{...n,transformRequest:this.getTransformRequest()})}catch(o){throw Ss.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Uu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:r}=Li.default.defaults;return r?r instanceof Array?e=r:e=[r]:e=[],[n=>JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ss=class t extends Error{constructor(r){super();this.e=r;Error.captureStackTrace(this,this.constructor)}name;static fromError(r){if(Li.default.isAxiosError(r)&&r?.response?.data&&"message"in r.response.data)return new t(r)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Lp=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Lp||{}),xs="https://fullnode.testnet.sui.io",Zu="https://fullnode.mainnet.sui.io",Ku="http://127.0.0.1:3000",Ju="http://127.0.0.1:3001",Up="https://sui-dev.m-safe.link",$p="http://13.56.226.148:81",Gp="https://sui-preview.m-safe.link",Vp="https://sui.m-safe.link",zp=new Map([["unit",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["local",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["dev",{suiClient:{url:xs},backend:{url:Up},syncingURL:$p,network:"sui:testnet"}],["prev",{suiClient:{url:Zu},backend:{url:Gp},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Zu},backend:{url:Vp},syncingURL:"",network:"sui:mainnet"}]]);function Xu(t,e){let r=zp.get(t);if(!r)throw new Error("Unknown environment");return e?.suiClient?.url&&(r.suiClient.url=e.suiClient.url),e?.backend?.url&&(r.backend.url=e.backend.url),r}var $i=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,r){let n=Xu(e,r),i=new Wp.SuiClient(n.suiClient),o=new Ts(n.backend.url);return new t({backend:o,suiClient:i,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var ks=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,r){let n=await $i.New(e,r);return new t(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let r=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(r),r}async authSign(e){let r=As.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:r});return this.backend.authSign({address:await e.address(),message:r,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:As.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new sn(this.globals,e)}async getMSafeAccountFromAddress(e){let r=await this.backend.getMSafeAccountInfo(e);return new sn(this.globals,r)}get creationHelper(){return this._creationHelper||(this._creationHelper=new un(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _s(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new cn(this.globals)}get Invitation(){return new zi(this.globals)}get Report(){return new vs(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2053
|
+
`);var Ii=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,du=typeof process=="object"&&process?process:{},kf=(t,e,r,n)=>{typeof du.emitWarning=="function"?du.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Ho=globalThis.AbortController,Sf=globalThis.AbortSignal;if(typeof Ho>"u"){Sf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Ho=class{constructor(){e()}signal=new Sf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=du.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yy=t=>!xf.has(t),pT=Symbol("type"),Or=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Af=t=>Or(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Nn:null:null,Nn=class extends Array{constructor(e){super(e),this.fill(0)}},fu=class t{heap;length;static#u=!1;static create(e){let r=Af(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zo=class t{#u;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#i;#r;#e;#c;#f;#a;#o;#g;#s;#T;#S;#w;#b;#k;#l;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#w,sizes:e.#T,keyMap:e.#i,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,o)=>e.#P(r,n,i,o),moveToTail:r=>e.#C(r),indexes:r=>e.#_(r),rindexes:r=>e.#v(r),isStale:r=>e.#h(r)}}get max(){return this.#u}get maxSize(){return this.#d}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:u,allowStale:l,dispose:d,disposeAfter:b,noDisposeOnSet:_,noUpdateTTL:T,maxSize:x=0,maxEntrySize:A=0,sizeCalculation:I,fetchMethod:C,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:D,allowStaleOnFetchAbort:L,ignoreFetchAbort:H}=e;if(r!==0&&!Or(r))throw new TypeError("max option must be a nonnegative integer");let W=r?Af(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#u=r,this.#d=x,this.maxEntrySize=A||this.#d,this.sizeCalculation=I,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(C!==void 0&&typeof C!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=C,this.#k=!!C,this.#i=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new W(r),this.#f=new W(r),this.#a=0,this.#o=0,this.#g=fu.create(r),this.#n=0,this.#m=0,typeof d=="function"&&(this.#y=d),typeof b=="function"?(this.#p=b,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!T,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!D,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#d!==0&&!Or(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Or(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!u,this.ttlResolution=Or(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Or(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#u===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#d){let K="LRU_CACHE_UNBOUNDED";yy(K)&&(xf.add(K),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,t))}}getRemainingTTL(e){return this.#i.has(e)?1/0:0}#D(){let e=new Nn(this.#u),r=new Nn(this.#u);this.#w=e,this.#S=r,this.#B=(o,s,u=Ii.now())=>{if(r[o]=s!==0?u:0,e[o]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#h(o)&&this.delete(this.#r[o])},s+1);l.unref&&l.unref()}},this.#A=o=>{r[o]=e[o]!==0?Ii.now():0},this.#x=(o,s)=>{if(e[s]){let u=e[s],l=r[s];o.ttl=u,o.start=l,o.now=n||i();let d=o.now-l;o.remainingTTL=u-d}};let n=0,i=()=>{let o=Ii.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#i.get(o);if(s===void 0)return 0;let u=e[s],l=r[s];if(u===0||l===0)return 1/0;let d=(n||i())-l;return u-d},this.#h=o=>e[o]!==0&&r[o]!==0&&(n||i())-r[o]>e[o]}#A=()=>{};#x=()=>{};#B=()=>{};#h=()=>!1;#F(){let e=new Nn(this.#u);this.#m=0,this.#T=e,this.#I=r=>{this.#m-=e[r],e[r]=0},this.#N=(r,n,i,o)=>{if(this.#t(n))return 0;if(!Or(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(n,r),!Or(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#d){let o=this.#d-e[r];for(;this.#m>o;)this.#E(!0)}this.#m+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#m)}}#I=e=>{};#M=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#o;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#v({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#o));)r=this.#c[r]}#R(e){return e!==void 0&&this.#i.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#_()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#v()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#_())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#v()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#v({allowStale:!0}))this.#h(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#_({allowStale:!0})){let n=this.#r[r],i=this.#e[r],o=this.#t(i)?i.__staleWhileFetching:i;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#w&&this.#S){s.ttl=this.#w[r];let u=Ii.now()-this.#S[r];s.start=Math.floor(Date.now()-u)}this.#T&&(s.size=this.#T[r]),e.unshift([n,s])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ii.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:l}=n,{noUpdateTTL:d=this.noUpdateTTL}=n,b=this.#N(e,r,n.size||0,u);if(this.maxEntrySize&&b>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let _=this.#n===0?void 0:this.#i.get(e);if(_===void 0)_=this.#n===0?this.#o:this.#g.length!==0?this.#g.pop():this.#n===this.#u?this.#E(!1):this.#n,this.#r[_]=e,this.#e[_]=r,this.#i.set(e,_),this.#c[this.#o]=_,this.#f[_]=this.#o,this.#o=_,this.#n++,this.#M(_,b,l),l&&(l.set="add"),d=!1;else{this.#C(_);let T=this.#e[_];if(r!==T){if(this.#k&&this.#t(T)?T.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(T,e,"set"),this.#l&&this.#s?.push([T,e,"set"])),this.#I(_),this.#M(_,b,l),this.#e[_]=r,l){l.set="replace";let x=T&&this.#t(T)?T.__staleWhileFetching:T;x!==void 0&&(l.oldValue=x)}}else l&&(l.set="update")}if(i!==0&&!this.#w&&this.#D(),this.#w&&(d||this.#B(_,i,o),l&&this.#x(l,_)),!s&&this.#l&&this.#s){let T=this.#s,x;for(;x=T?.shift();)this.#p?.(...x)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}}#E(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#k&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,n,"evict"),this.#l&&this.#s?.push([i,n,"evict"])),this.#I(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#g.push(r)),this.#n===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#c[r],this.#i.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,o=this.#i.get(e);if(o!==void 0){let s=this.#e[o];if(this.#t(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#h(o))i&&(i.has="stale",this.#x(i,o));else return n&&this.#A(o),i&&(i.has="hit",this.#x(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#i.get(e);if(i!==void 0&&(n||!this.#h(i))){let o=this.#e[i];return this.#t(o)?o.__staleWhileFetching:o}}#P(e,r,n,i){let o=r===void 0?void 0:this.#e[r];if(this.#t(o))return o;let s=new Ho,{signal:u}=n;u?.addEventListener("abort",()=>s.abort(u.reason),{signal:s.signal});let l={signal:s.signal,options:n,context:i},d=(I,C=!1)=>{let{aborted:E}=s.signal,P=n.ignoreFetchAbort&&I!==void 0;if(n.status&&(E&&!C?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,P&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),E&&!P&&!C)return _(s.signal.reason);let D=x;return this.#e[r]===x&&(I===void 0?D.__staleWhileFetching?this.#e[r]=D.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,I,l.options))),I},b=I=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=I),_(I)),_=I=>{let{aborted:C}=s.signal,E=C&&n.allowStaleOnFetchAbort,P=E||n.allowStaleOnFetchRejection,D=P||n.noDeleteOnFetchRejection,L=x;if(this.#e[r]===x&&(!D||L.__staleWhileFetching===void 0?this.delete(e):E||(this.#e[r]=L.__staleWhileFetching)),P)return n.status&&L.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw I},T=(I,C)=>{let E=this.#O?.(e,o,l);E&&E instanceof Promise&&E.then(P=>I(P),C),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(I(),n.allowStaleOnFetchAbort&&(I=P=>d(P,!0)))})};n.status&&(n.status.fetchDispatched=!0);let x=new Promise(T).then(d,b),A=Object.assign(x,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,A,{...l.options,status:void 0}),r=this.#i.get(e)):this.#e[r]=A,A}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Ho}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:l=0,sizeCalculation:d=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:T=this.allowStaleOnFetchRejection,ignoreFetchAbort:x=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:I,forceRefresh:C=!1,status:E,signal:P}=r;if(!this.#k)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:E});let D={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:u,size:l,sizeCalculation:d,noUpdateTTL:b,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:A,ignoreFetchAbort:x,status:E,signal:P},L=this.#i.get(e);if(L===void 0){E&&(E.fetch="miss");let H=this.#P(e,L,D,I);return H.__returned=H}else{let H=this.#e[L];if(this.#t(H)){let N=n&&H.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=!0)),N?H.__staleWhileFetching:H.__returned=H}let W=this.#h(L);if(!C&&!W)return E&&(E.fetch="hit"),this.#C(L),i&&this.#A(L),E&&this.#x(E,L),H;let K=this.#P(e,L,D,I),U=K.__staleWhileFetching!==void 0&&n;return E&&(E.fetch=W?"stale":"refresh",U&&W&&(E.returnedStale=!0)),U?K.__staleWhileFetching:K.__returned=K}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=r,u=this.#i.get(e);if(u!==void 0){let l=this.#e[u],d=this.#t(l);return s&&this.#x(s,u),this.#h(u)?(s&&(s.get="stale"),d?(s&&n&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?l.__staleWhileFetching:void 0):(o||this.delete(e),s&&n&&(s.returnedStale=!0),n?l:void 0)):(s&&(s.get="hit"),d?l.__staleWhileFetching:(this.#C(u),i&&this.#A(u),l))}else s&&(s.get="miss")}#j(e,r){this.#f[r]=e,this.#c[e]=r}#C(e){e!==this.#o&&(e===this.#a?this.#a=this.#c[e]:this.#j(this.#f[e],this.#c[e]),this.#j(this.#o,e),this.#o=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#i.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#I(n);let i=this.#e[n];this.#t(i)?i.__abortController.abort(new Error("deleted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,e,"delete"),this.#l&&this.#s?.push([i,e,"delete"])),this.#i.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#o?this.#o=this.#f[n]:n===this.#a?this.#a=this.#c[n]:(this.#c[this.#f[n]]=this.#c[n],this.#f[this.#c[n]]=this.#f[n]),this.#n--,this.#g.push(n)}}if(this.#l&&this.#s?.length){let n=this.#s,i;for(;i=n?.shift();)this.#p?.(...i)}return r}clear(){for(let e of this.#v({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#b&&this.#y?.(r,n,"delete"),this.#l&&this.#s?.push([r,n,"delete"])}}if(this.#i.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#w&&this.#S&&(this.#w.fill(0),this.#S.fill(0)),this.#T&&this.#T.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#m=0,this.#n=0,this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}};var Q=de(we(),1);var Yo=de(If(),1),Qr=require("@mysten/sui.js/utils"),en=require("@mysten/sui.js/transactions");var Ci=de(we(),1),Nf=require("@mysten/sui.js/transactions"),Mt=de(we(),1);var Mr=de(we(),1),Lt=de(we(),1);var Ei=de(we(),1);var Rf=require("@mysten/sui.js/utils"),Qo=require("@mysten/sui.js/transactions"),es=require("@mysten/sui.js/utils");var yu=de(we(),1),by=Object.defineProperty,_y=(t,e,r)=>e in t?by(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e,r)=>(_y(t,typeof e!="symbol"?e+"":e,r),r);var Ko=443636,Jo=-443636,mu="79226673515401279992447579055",gu="4295048016",Ty=14,Sy="59543866431248",xy="184467440737095516",ky="15793534762490258745",Ay=class{generateMnemonic(t=24){return vf(Tf,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let r=this.getDerivePath(e);return Ef.Ed25519Keypair.deriveKeypair(t,r)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:r=!1,addressIndex:n=0}=t;return`m/44'/784'/${e}'/${r?1:0}'/${n}'`}},Mi=class{constructor(t){this.sdk=t,rr(this,"_lru"),rr(this,"_fetching",{})}async getCacheOrSet(t,e,r=0){var n;let i=this._lru||(this._lru=new Zo({max:100}));if(i.has(t))return i.get(t);let s=await((n=this._fetching)[t]||(n[t]=e()));return delete this._fetching[t],i.set(t,s,{ttl:r}),s}get provider(){return this.sdk.provider}get math(){return this.sdk.math}get account(){return this.sdk.account}get network(){return this.sdk.network}get contract(){return this.sdk.contract}get nft(){return this.sdk.nft}get coin(){return this.sdk.coin}get trade(){return this.sdk.trade}get pool(){return this.sdk.pool}};function Iy(t){if("reference"in t)return t.reference;let e=bu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Df(t)}function rs(t){var e,r;return"objectId"in t?t.objectId:(r=(e=Iy(t))==null?void 0:e.objectId)!=null?r:Bf(t)}function nr(t){var e;return"fields"in t?t.fields:(e=Pf(t))==null?void 0:e.fields}function Pf(t){let e="data"in t?bu(t):t;if(!(!e||!Cy(e)||e.content.dataType!=="moveObject"))return e.content}function Cy(t){return t.content!==void 0}function bu(t){return t.data}function Df(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let e=t.error;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Bf(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Oy(t){return t.data!==void 0}function My(t){var e;let r=Oy(t)?t.data:t;return!r?.type&&"data"in t?((e=r?.content)==null?void 0:e.dataType)==="package"?"package":ts(t):r?.type}function ts(t){var e;return(e=Pf(t))==null?void 0:e.type}function Ey(t){var e;return(e=bu(t))==null?void 0:e.owner}var Oi=async(t,e,r)=>{let i=e.length;if(i>50){let o=[],s=0,u=Math.ceil(i/50);for(s;s<u;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:r}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:r})},Py=class extends Mi{async getConfig(){return(await this.fetchJSON())[this.network].contract}getFees(){return this.getCacheOrSet("fees",async()=>{let e=(await this.fetchJSON())[this.network].fee;return(await Oi(this.provider,Object.values(e),{showContent:!0})).map(n=>{let i=nr(n),o=rs(n),s=ts(n);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:i.fee,tickSpacing:i.tick_spacing}})})}fetchJSON(){return this.getCacheOrSet("contract-json",async()=>await(await fetch("https://s3.amazonaws.com/app.turbos.finance/sdk/contract.json?t="+Date.now(),{method:"GET"})).json())}},Cf=new Q.default(2).pow(new Q.default(128)),Dy=class{priceToSqrtPriceX64(t,e,r){return new Q.default(new $(t).mul($.pow(10,r-e)).sqrt().mul($.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,r){return new $(t.toString()).mul($.pow(2,-64)).pow(2).mul($.pow(10,e-r))}priceToTickIndex(t,e,r){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,r))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Q.default(mu))||t.lt(new Q.default(gu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,r=new Q.default(e-64),n=this.signedShiftLeft(r,32,128),i=new Q.default("8000000000000000","hex"),o=0,s=new Q.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new Q.default(0))&&o<Ty;){u=u.mul(u);let x=u.shrn(127);u=u.shrn(63+x.toNumber()),s=s.add(i.mul(x)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new Q.default(Sy)),_=this.signedShiftRight(b.sub(new Q.default(xy)),64,128).toNumber(),T=this.signedShiftRight(b.add(new Q.default(ky)),64,128).toNumber();return _==T?_:this.tickIndexToSqrtPriceX64(T).lte(t)?T:_}tickIndexToSqrtPriceX64(t){return t>0?new Q.default(this.tickIndexToSqrtPricePositive(t)):new Q.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,r){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,r)}toX64_Decimal(t){return t.mul($.pow(2,64))}fromX64_Decimal(t){return t.mul($.pow(2,-64))}scaleDown(t,e){return new $(t).div($.pow(10,e)).toString()}scaleUp(t,e){return new $(t).mul($.pow(10,e)).toString()}bitsToNumber(t,e=32){return Yo.default.toNumber(Yo.default.asIntN(e,Yo.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Cf).sub(e).mod(Cf)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Q.default("79232123823359799118286999567"):e=new Q.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Q.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Q.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Q.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Q.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Q.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Q.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Q.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Q.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Q.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Q.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Q.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Q.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Q.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Q.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Q.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Q.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Q.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Q.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),r;return e&1?r=new Q.default("18445821805675392311"):r=new Q.default("18446744073709551616"),e&2&&(r=this.signedShiftRight(r.mul(new Q.default("18444899583751176498")),64,256)),e&4&&(r=this.signedShiftRight(r.mul(new Q.default("18443055278223354162")),64,256)),e&8&&(r=this.signedShiftRight(r.mul(new Q.default("18439367220385604838")),64,256)),e&16&&(r=this.signedShiftRight(r.mul(new Q.default("18431993317065449817")),64,256)),e&32&&(r=this.signedShiftRight(r.mul(new Q.default("18417254355718160513")),64,256)),e&64&&(r=this.signedShiftRight(r.mul(new Q.default("18387811781193591352")),64,256)),e&128&&(r=this.signedShiftRight(r.mul(new Q.default("18329067761203520168")),64,256)),e&256&&(r=this.signedShiftRight(r.mul(new Q.default("18212142134806087854")),64,256)),e&512&&(r=this.signedShiftRight(r.mul(new Q.default("17980523815641551639")),64,256)),e&1024&&(r=this.signedShiftRight(r.mul(new Q.default("17526086738831147013")),64,256)),e&2048&&(r=this.signedShiftRight(r.mul(new Q.default("16651378430235024244")),64,256)),e&4096&&(r=this.signedShiftRight(r.mul(new Q.default("15030750278693429944")),64,256)),e&8192&&(r=this.signedShiftRight(r.mul(new Q.default("12247334978882834399")),64,256)),e&16384&&(r=this.signedShiftRight(r.mul(new Q.default("8131365268884726200")),64,256)),e&32768&&(r=this.signedShiftRight(r.mul(new Q.default("3584323654723342297")),64,256)),e&65536&&(r=this.signedShiftRight(r.mul(new Q.default("696457651847595233")),64,256)),e&131072&&(r=this.signedShiftRight(r.mul(new Q.default("26294789957452057")),64,256)),e&262144&&(r=this.signedShiftRight(r.mul(new Q.default("37481735321082")),64,256)),r}signedShiftLeft(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}signedShiftRight(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}},wu=(t,e)=>{let r=rs(t);if(Df(t))throw new Error(`${e}(${r}) had been deleted`);if(Bf(t))throw new Error(`${e}(${r}) is not found`);return!0},Rn=60*1e3,By=class extends Mi{async getPools(t=!1){let e=await this.contract.getConfig(),r=[],n;do n=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:n?.nextCursor,limit:15}),r.push(...n.data.map(u=>u.objectId));while(n.hasNextPage);if(!r.length)return[];let o=(await Oi(this.provider,r,{showContent:!0})).map(u=>nr(u).value.fields.pool_id);if(!o.length)return[];let s=await Oi(this.provider,o,{showContent:!0});return t||(s=s.filter(u=>nr(u).unlocked)),s.map(u=>this.parsePool(u))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:r,tickLower:n,tickUpper:i,sqrtPrice:o,slippage:s,coinTypeA:u,coinTypeB:l}=t,d=await this.contract.getConfig(),b=new $(t.amountA),_=new $(t.amountB),[T,x]=await Promise.all([this.coin.selectTradeCoins(r,u,b),this.coin.selectTradeCoins(r,l,_)]),A=t.txb||new en.TransactionBlock,I=T.length>0?this.coin.convertTradeCoins(A,T,u,b):[this.coin.zero(u,A)],C=x.length>0?this.coin.convertTradeCoins(A,x,l,_):[this.coin.zero(l,A)];return A.moveCall({target:`${d.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[u,l,e.type],arguments:[A.object(d.PoolConfig),A.object(e.objectId),A.pure(o,"u128"),A.object(d.Positions),A.makeMoveVec({objects:I}),A.makeMoveVec({objects:C}),A.pure(Math.abs(n).toFixed(0),"u32"),A.pure(n<0,"bool"),A.pure(Math.abs(i).toFixed(0),"u32"),A.pure(i<0,"bool"),A.pure(b.toFixed(0),"u64"),A.pure(_.toFixed(0),"u64"),A.pure(this.getMinimumAmountBySlippage(b,s),"u64"),A.pure(this.getMinimumAmountBySlippage(_,s),"u64"),A.pure(r,"address"),A.pure(Date.now()+Rn,"u64"),A.object(Qr.SUI_CLOCK_OBJECT_ID),A.object(d.Versioned)]}),A}async addLiquidity(t){let{address:e,tickLower:r,tickUpper:n,slippage:i,pool:o}=t,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(o),[l,d]=u,[b,_]=await Promise.all([this.coin.getMetadata(l),this.coin.getMetadata(d)]);if(!b||!_)throw new Error("Invalid coin type");let T=new $(t.amountA),x=new $(t.amountB),[A,I]=await Promise.all([this.coin.selectTradeCoins(e,l,T),this.coin.selectTradeCoins(e,d,x)]),C=t.txb||new en.TransactionBlock,E=A.length>0?this.coin.convertTradeCoins(C,A,l,T):[this.coin.zero(l,C)],P=I.length>0?this.coin.convertTradeCoins(C,I,d,x):[this.coin.zero(d,C)];return C.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:u,arguments:[C.object(o),C.object(s.Positions),C.makeMoveVec({objects:E}),C.makeMoveVec({objects:P}),C.pure(Math.abs(r).toFixed(0),"u32"),C.pure(r<0,"bool"),C.pure(Math.abs(n).toFixed(0),"u32"),C.pure(n<0,"bool"),C.pure(T.toFixed(0),"u64"),C.pure(x.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(T,i),"u64"),C.pure(this.getMinimumAmountBySlippage(x,i),"u64"),C.pure(e,"address"),C.pure(Date.now()+Rn,"u64"),C.object(Qr.SUI_CLOCK_OBJECT_ID),C.object(s.Versioned)]}),C}async increaseLiquidity(t){let{pool:e,slippage:r,address:n,nft:i}=t,o=await this.contract.getConfig(),s=new $(t.amountA),u=new $(t.amountB),l=await this.getPoolTypeArguments(e),[d,b]=l,[_,T]=await Promise.all([this.coin.selectTradeCoins(n,d,s),this.coin.selectTradeCoins(n,b,u)]),x=t.txb||new en.TransactionBlock,A=_.length>0?this.coin.convertTradeCoins(x,_,d,s):[this.coin.zero(d,x)],I=T.length>0?this.coin.convertTradeCoins(x,T,b,u):[this.coin.zero(b,x)];return x.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:l,arguments:[x.object(e),x.object(o.Positions),x.makeMoveVec({objects:A}),x.makeMoveVec({objects:I}),x.object(i),x.pure(s.toFixed(0),"u64"),x.pure(u.toFixed(0),"u64"),x.pure(this.getMinimumAmountBySlippage(s,r),"u64"),x.pure(this.getMinimumAmountBySlippage(u,r),"u64"),x.pure(Date.now()+Rn*3,"u64"),x.object(Qr.SUI_CLOCK_OBJECT_ID),x.object(o.Versioned)]}),x}async decreaseLiquidity(t){let{slippage:e,nft:r,pool:n,decreaseLiquidity:i}=t,o=new $(t.amountA),s=new $(t.amountB),u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(n),d=t.txb||new en.TransactionBlock;return d.moveCall({target:`${u.PackageId}::position_manager::decrease_liquidity`,typeArguments:l,arguments:[d.object(n),d.object(u.Positions),d.object(r),d.pure(new Ci.default(i).toString(),"u128"),d.pure(this.getMinimumAmountBySlippage(o,e),"u64"),d.pure(this.getMinimumAmountBySlippage(s,e),"u64"),d.pure(Date.now()+Rn*3,"u64"),d.object(Qr.SUI_CLOCK_OBJECT_ID),d.object(u.Versioned)]}),d}async removeLiquidity(t){let e=await this.decreaseLiquidity(t);return e=await this.collectFee({txb:e,...t}),e=await this.collectReward({txb:e,...t}),e=await this.nft.burn({txb:e,nft:t.nft,pool:t.pool}),e}async collectFee(t){let{pool:e,nft:r,address:n,collectAmountA:i,collectAmountB:o}=t,s=t.txb||new en.TransactionBlock;if(Number(i)===0&&Number(o)===0)return s;let u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(e);return s.moveCall({target:`${u.PackageId}::position_manager::collect`,typeArguments:l,arguments:[s.object(e),s.object(u.Positions),s.object(r),s.pure(i,"u64"),s.pure(o,"u64"),s.pure(n),s.pure(Date.now()+Rn*3,"u64"),s.object(Qr.SUI_CLOCK_OBJECT_ID),s.object(u.Versioned)]}),s}async collectReward(t){let{pool:e,nft:r,rewardAmounts:n,address:i}=t,o=t.txb||new en.TransactionBlock,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((d,b)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...u,d.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(r),o.object(d.fields.vault),o.pure(b,"u64"),o.pure(n[b],"u64"),o.pure(i),o.pure(Date.now()+Rn*3,"u64"),o.object(Qr.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new $((t.liquidity||new Ci.default(1e8)).toString()),r=new $(t.currentSqrtPrice.toString()),n=new $(t.lowerSqrtPrice.toString()),i=new $(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(n)).div(n.mul(i)),s=new $(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(r)).div(r.mul(i)),s=this.math.fromX64_Decimal(e.mul(r.sub(n)))):(o=new $(0),s=this.math.fromX64_Decimal(e.mul(i.sub(n))));let u=t.ceil!==!1?"ceil":"floor";return[new Ci.default(o[u]().toString()),new Ci.default(s[u]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var r;let n=((r=t.replace(">","").split("<")[1])==null?void 0:r.split(/,\s*/))||[];if(e!==void 0&&e!==n.length)throw new Error("Invalid pool type");return n}async getFixedLiquidity(t){var e,r;let{coinTypeA:n,coinTypeB:i,amountA:o,amountB:s}=t,[u,l]=await Promise.all([this.coin.getMetadata(n),this.coin.getMetadata(i)]),d=new $(this.math.scaleDown(o,u.decimals)).mul((e=t.priceA)!=null?e:1),b=new $(this.math.scaleDown(s,l.decimals)).mul((r=t.priceB)!=null?r:1);return{liquidityA:d.toString(),liquidityB:b.toString(),liquidity:d.plus(b).toString()}}parsePool(t){let e=nr(t),r=rs(t),n=My(t),i=this.parsePoolType(n,3);return this.getCacheOrSet("pool-type-"+r,async()=>i),{...e,objectId:r,type:n,types:i}}getMinimumAmountBySlippage(t,e){let r=new $(t),n=new $(1).minus(new $(e).div(100));if(n.lte(0)||n.gt(1))throw new Error("invalid slippage range");return r.mul(n).toFixed(0)}},Ny=(t,e)=>{let{pool:r,position:n,tickLowerDetail:i,tickUpperDetail:o}=e,s=new Mr.default(r.fee_growth_global_a),u=new Mr.default(n.fee_growth_inside_a),l=new Mr.default(n.tokens_owed_a),d=new Mr.default(r.fee_growth_global_b),b=new Mr.default(n.fee_growth_inside_b),_=new Mr.default(n.tokens_owed_b),T=new Mr.default(n.liquidity),x,A,I,C,E=t.bitsToNumber(r.tick_current_index.fields.bits),P=t.bitsToNumber(n.tick_lower_index.fields.bits),D=t.bitsToNumber(n.tick_upper_index.fields.bits);E<P?(x=t.subUnderflowU128(s,i.feeGrowthOutsideA),A=t.subUnderflowU128(d,i.feeGrowthOutsideB)):(x=i.feeGrowthOutsideA,A=i.feeGrowthOutsideB),E<D?(I=o.feeGrowthOutsideA,C=o.feeGrowthOutsideB):(I=t.subUnderflowU128(s,o.feeGrowthOutsideA),C=t.subUnderflowU128(d,o.feeGrowthOutsideB));let L=t.subUnderflowU128(t.subUnderflowU128(s,x),I),H=t.subUnderflowU128(t.subUnderflowU128(d,A),C),W=t.subUnderflowU128(L,u).mul(T).shrn(64),K=t.subUnderflowU128(H,b).mul(T).shrn(64);return{feeOwedA:l.add(W).toString(),feeOwedB:_.add(K).toString()}},Of=new Ei.default(0),Mf=new Ei.default(1),Ry=new Ei.default(2),jy={mul(t,e,r){let n=t.mul(e);if(this.isOverLimit(n,r))throw new Error(`Mul result higher than u${r}`);return n},mulDiv(t,e,r,n){return this.mulDivRoundUpIf(t,e,r,!1,n)},mulDivRoundUpIf(t,e,r,n,i){if(r.eq(Of))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,i),s=o.div(r);return n&&o.mod(r).gt(Of)?s.add(Mf):s},isOverLimit(t,e){let r=Ry.pow(new Ei.default(e)).sub(Mf);return t.gt(r)}},Fy=(t,e)=>{var r,n,i,o;let{pool:s,position:u,tickLowerDetail:l,tickUpperDetail:d,timeStampInSeconds:b}=e,_=new Lt.default(new $(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),x=(b??new Lt.default(Date.now()).div(new Lt.default(1e3))).sub(new Lt.default(_)),A=[],I=new Lt.default(s.liquidity),C=new Lt.default(u.liquidity);for(let E=0;E<3;++E){let P=s.reward_infos[E],D={emissionsPerSecondX64:new Lt.default(P?P.fields.emissions_per_second:"0"),growthGlobalX64:new Lt.default(P?P.fields.growth_global:"0")},L={growthInsideCheckpoint:new Lt.default((n=(r=u.reward_infos[E])==null?void 0:r.fields.reward_growth_inside)!=null?n:"0"),amountOwed:new Lt.default((o=(i=u.reward_infos[E])==null?void 0:i.fields.amount_owed)!=null?o:"0")},H=D.growthGlobalX64;if(!I.isZero()){let S=jy.mulDiv(x,D.emissionsPerSecondX64,I,128);H=D.growthGlobalX64.add(S)}let W=l.rewardGrowthsOutside[E],K=d.rewardGrowthsOutside[E],F=H;l.initialized&&(F=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_lower_index.fields.bits)?t.subUnderflowU128(H,W):W);let U=new Lt.default(0);d.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_upper_index.fields.bits)?K:t.subUnderflowU128(H,K));let N=t.subUnderflowU128(t.subUnderflowU128(H,F),U),j=L.amountOwed.shln(64);A[E]=j.add(t.subUnderflowU128(N,L.growthInsideCheckpoint).mul(C)).shrn(64).toString()}return A},qy=class extends Mi{async getOwner(t){let e=await this.getObject(t),r=Ey(e);if(!(!r||typeof r=="string")){if("ObjectOwner"in r)return r.ObjectOwner;if("AddressOwner"in r)return r.AddressOwner}}async getFields(t){let e=await this.getObject(t);return nr(e)}async getPositionFields(t){let e=await this.contract.getConfig(),r=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return nr(r)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"position"),nr(e)}async getPositionTick(t,e){let r=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),n=nr(r);if(n)return{tickIndex:this.math.bitsToNumber(n.name.fields.bits),initialized:n.value.fields.initialized,liquidityNet:new Mt.default(this.math.bitsToNumber(n.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Mt.default(n.value.fields.liquidity_gross),feeGrowthOutsideA:new Mt.default(n.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Mt.default(n.value.fields.fee_growth_outside_b),rewardGrowthsOutside:n.value.fields.reward_growths_outside.map(i=>new Mt.default(i))}}async getPositionAPR(t){let{poolId:e,getPrice:r,fees24h:n,tickLower:i,tickUpper:o}=t,s=await this.pool.getPool(e),u=this.math.bitsToNumber(s.tick_current_index.fields.bits),[l,d,b,_]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),r(s.types[0]),r(s.types[1])]);if(!b||!_||i>=o||u<i||u>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:T,minTokenB:x}=this.getRemoveLiquidityQuote(s,i,o),A=new $(this.math.scaleDown(T.toString(),l.decimals)).mul(b),I=new $(this.math.scaleDown(x.toString(),d.decimals)).mul(_),C=A.add(I),E=C.isZero()?new $(0):new $(n).mul(365).div(C).mul(100),P=new $(0);return await Promise.all(s.reward_infos.map(async D=>{let{emissions_per_second:L}=D.fields,H=this.coin.formatCoinType(D.fields.vault_coin_type),[W,K]=await Promise.all([r(H),this.coin.getMetadata(H)]);!L||L==="0"||!W||(P=P.add(new $(new Mt.default(L).shrn(64).toString()).div(10**K.decimals).mul(31536e3).mul(W).div(C).mul(100)))})),{fees:E.toString(),rewards:P.toString(),total:E.plus(P).toString()}}getRemoveLiquidityQuote(t,e,r){let n=new Mt.default(0),i=new Mt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),u=this.math.tickIndexToSqrtPriceX64(r);if(o<e){let d=this.getTokenAFromLiquidity(i,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:n}}if(o<r){let d=new Mt.default(t.sqrt_price),b=this.getTokenAFromLiquidity(i,d,u),_=this.getTokenBFromLiquidity(i,s,d);return{minTokenA:this.adjustForSlippage(b),minTokenB:this.adjustForSlippage(_)}}let l=this.getTokenBFromLiquidity(i,s,u);return{minTokenA:n,minTokenB:this.adjustForSlippage(l)}}adjustForSlippage(t){let e={numerator:new Mt.default(0),denominator:new Mt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,r){let n=t.mul(r.sub(e)).shln(64),i=r.mul(e);return n.div(i)}getTokenBFromLiquidity(t,e,r){return t.mul(r.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:r}=t,n=t.txb||new Nf.TransactionBlock,i=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return n.moveCall({target:`${i.PackageId}::position_manager::burn`,typeArguments:o,arguments:[n.object(i.Positions),n.object(r),n.object(i.Versioned)]}),n}async getPositionLiquidityUSD(t){let{position:e,poolId:r,priceA:n,priceB:i}=t,o=await this.pool.getPool(r),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Mt.default(o.sqrt_price),lowerSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_lower_index.fields.bits)),upperSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_upper_index.fields.bits)),liquidity:new Mt.default(e.liquidity===void 0?1e8:e.liquidity)}),[u,l]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),d=new $(s[0].toString()).div(10**u.decimals).mul(n||0),b=new $(s[1].toString()).div(10**l.decimals).mul(i||0);return d.plus(b).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:r}=t,[n,i,o]=await Promise.all([this.pool.getPool(r),this.nft.getPositionTick(r,e.tick_lower_index),this.nft.getPositionTick(r,e.tick_upper_index)]),s={...t,pool:n,tickLowerDetail:i,tickUpperDetail:o},[u,l]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:d,...b}=u,{unclaimedRewards:_,...T}=l;return{fees:u.unclaimedFees.toString(),rewards:_.toString(),total:d.plus(_).toString(),fields:{...b,...T}}}async getUnclaimedFees(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,[s,u,l,d]=await Promise.all([this.coin.getMetadata(r.types[0]),this.coin.getMetadata(r.types[1]),n(r.types[0]),n(r.types[1])]),b=Ny(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),_=this.math.scaleDown(b.feeOwedA,s.decimals),T=this.math.scaleDown(b.feeOwedB,u.decimals);function x(C,E){return new $(1e6).mul($.pow(10,E)).lt(C)}x(_,s.decimals)&&(_="0",b.feeOwedA="0"),x(T,u.decimals)&&(T="0",b.feeOwedB="0");let A=l===void 0?new $(0):new $(l).mul(_),I=d===void 0?new $(0):new $(d).mul(T);return{unclaimedFees:A.plus(I),scaledFeeOwedA:_,scaledFeeOwedB:T,...b}}async getUnclaimedRewards(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,s=Fy(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),u=[...s],l=r.reward_infos.map(T=>this.coin.formatCoinType(T.fields.vault_coin_type)),d=await Promise.all([...r.reward_infos.map((T,x)=>this.coin.getMetadata(l[x]))]),b=await Promise.all(r.reward_infos.map((T,x)=>n(l[x])));d.forEach((T,x)=>{u[x]=this.math.scaleDown(u[x],T.decimals)});let _=new $(0);return r.reward_infos.some((T,x)=>{let A=b[x];return A?(_=_.plus(new $(A).mul(u[x])),!1):(_=_.plus(1),!0)}),{unclaimedRewards:_,collectRewards:s,scaledCollectRewards:u}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return wu(e,"nft"),e})}},Ly=class extends Mi{isSUI(t){return(0,Rf.normalizeSuiAddress)(t)==="0x000000000000000000000000000000000000000000000000000002::sui::sui"}async getMetadata(t){return this.getCacheOrSet(`coin-metadata-${t}`,async()=>{let e=await this.provider.getCoinMetadata({coinType:t});if(!e)throw new Error(`Coin "${t}" is not found`);return e})}async selectTradeCoins(t,e,r){if(r.eq(0))return[];let n=[],i=[],o=new $(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),n.push(...s.data);while(s.hasNextPage);n.sort((u,l)=>Number(l.balance)-Number(u.balance));for(let u of n)if(i.push(u.coinObjectId),o=o.add(u.balance),o.gte(r))break;return i}convertTradeCoins(t,e,r,n){return this.isSUI(r)?[t.splitCoins(t.gas,[t.pure(n.toNumber())])[0]]:e.map(i=>t.object(i))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let n=t.replace(/^0x/i,"");return n=n.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&n.length<64&&t!=="2::sui:SUI"?"0".repeat(64-n.length):"")+n}},Uy=60*1e3,Xo=100,$y=class extends Mi{async swap(t){let{coinTypeA:e,coinTypeB:r,address:n,amountSpecifiedIsInput:i,slippage:o}=t,s=new $(t.amountA),u=new $(t.amountB),l=await this.contract.getConfig(),d=await Promise.all(t.routes.map(async I=>{let C=await this.pool.getPoolTypeArguments(I.pool),[E,P]=await Promise.all([this.coin.getMetadata(C[0]),this.coin.getMetadata(C[1])]);return{...I,coinA:E,coinB:P,typeArguments:C}})),b=await this.coin.selectTradeCoins(n,e,s),{functionName:_,typeArguments:T}=this.getFunctionNameAndTypeArguments(d.map(({typeArguments:I})=>I),e,r),x=d.map(({nextTickIndex:I,coinA:C,coinB:E,a2b:P})=>{let D=this.math.tickIndexToPrice(I,C.decimals,E.decimals);return this.sqrtPriceWithSlippage(D,o,P,C.decimals,E.decimals)}),A=t.txb||new Qo.TransactionBlock;return A.moveCall({target:`${l.PackageId}::swap_router::${_}`,typeArguments:T,arguments:[...d.map(({pool:I})=>A.object(I)),A.makeMoveVec({objects:this.coin.convertTradeCoins(A,b,e,s)}),A.pure((i?s:u).toFixed(0),"u64"),A.pure(this.amountOutWithSlippage(i?u:s,o,i),"u64"),...x.map(I=>A.pure(I,"u128")),A.pure(i,"bool"),A.pure(n,"address"),A.pure(Date.now()+Uy*3,"u64"),A.object(es.SUI_CLOCK_OBJECT_ID),A.object(l.Versioned)]}),A}async computeSwapResult(t){let{pools:e,amountSpecified:r,amountSpecifiedIsInput:n,address:i,tickStep:o}=t,s=await this.contract.getConfig(),u=e.map(_=>_.pool),l=await Oi(this.provider,u,{showContent:!0}),d=new Qo.TransactionBlock;l.map(async _=>{let T=nr(_),x=e.find(P=>P.pool===T.id.id),A=this.math.bitsToNumber(T.tick_current_index.fields.bits),I=A-T.tick_spacing*(o||Xo),C=A+T.tick_spacing*(o||Xo);I=I<Jo?Jo:I,C=C>Ko?Ko:C;let E=this.pool.parsePoolType(ts(_));d.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:E,arguments:[d.object(T.id.id),d.pure(x.a2b,"bool"),d.pure(new $(r).toFixed(0),"u128"),d.pure(n,"bool"),d.pure(this.math.tickIndexToSqrtPriceX64(x.a2b?I:C).toString(),"u128"),d.object(es.SUI_CLOCK_OBJECT_ID),d.object(s.Versioned)]})});let b=await this.provider.devInspectTransactionBlock({transactionBlock:d,sender:i});if(b.error)throw new Error(b.error);return b.events.map(_=>_.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:r,address:n,tickStep:i}=t,o=await this.contract.getConfig(),s=e.map(b=>b.pool),u=await Oi(this.provider,Array.from(new Set(s)),{showContent:!0}),l=new Qo.TransactionBlock;e.forEach(async b=>{let _=u.find(E=>rs(E)===b.pool),T=nr(_),x=this.math.bitsToNumber(T.tick_current_index.fields.bits),A=x-T.tick_spacing*(i||Xo),I=x+T.tick_spacing*(i||Xo);A=A<Jo?Jo:A,I=I>Ko?Ko:I;let C=this.pool.parsePoolType(ts(_));l.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:C,arguments:[l.object(T.id.id),l.pure(b.a2b,"bool"),l.pure(new $(b.amountSpecified).toFixed(0),"u128"),l.pure(r,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(b.a2b?A:I).toString(),"u128"),l.object(es.SUI_CLOCK_OBJECT_ID),l.object(o.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:n});if(d.error)throw new Error(d.error);return d.events.map(b=>b.parsedJson)}getFunctionNameAndTypeArguments(t,e,r){let n=[],i=["swap"];if(t.length===1)n=t[0],e===n[0]?i.push("a","b"):i.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(i.push("a","b"),n.push(o[0],o[2],o[1])):(i.push("b","a"),n.push(o[1],o[2],o[0])),n.push(s[2],r),r===s[0]?i.push("c","b"):i.push("b","c")}return{functionName:i.join("_"),typeArguments:n}}amountOutWithSlippage(t,e,r){if(r){let i=new $(100).minus(e).div(100);return new $(t).mul(i).toFixed(0)}let n=new $(100).plus(e).div(100);return new $(t).mul(n).toFixed(0)}sqrtPriceWithSlippage(t,e,r,n,i){let o=new $(t).mul(r?new $(100).minus(e).div(100):new $(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,n,i);return s.lt(new yu.BN(gu))?gu:s.gt(new yu.BN(mu))?mu:s.toString()}},It=class{constructor(t,e){this.network=t,rr(this,"pool"),rr(this,"contract"),rr(this,"math",new Dy),rr(this,"account",new Ay),rr(this,"coin"),rr(this,"nft"),rr(this,"trade"),rr(this,"provider"),this.provider=e?e instanceof tn.SuiClient?e:new tn.SuiClient(e):new tn.SuiClient({url:t==="mainnet"?(0,tn.getFullnodeUrl)("mainnet"):(0,tn.getFullnodeUrl)("testnet")}),this.contract=new Py(this),this.pool=new By(this),this.nft=new qy(this),this.coin=new Ly(this),this.trade=new $y(this)}};var Gy=Object.defineProperty,uh=(t,e)=>{for(var r in e)Gy(t,r,{get:e[r],enumerable:!0})},St=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,lh.default)(this.data))}},Vy={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},_u=new nd(Vy),zy=async(t,e,r,n,i)=>{console.log("getSwapRouterTxb account2: ",n),console.log("getSwapRouterTxb suiClient: ",i),_u.senderAddress=r;let o=await _u.getOwnerCoinAssets(r);return await Pe.buildAggregatorSwapTransaction(_u,t,o,"",e)},Wy=class dh extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r,suiClient:n}=e,{payloadParams:i}=this.data,o=await zy(i?.createTxParams,i?.slippage,i?.account,r,n);return console.log("Swap intention build txb: ",o),o}static fromData(e){return new dh(e)}},Hy=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{payloadParams:e,action:r}=t;return{txType:ch.TransactionType.Other,txSubType:`Cetus${r}`,intentionData:{payloadParams:e,action:r}}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"CetusSwap":n=Wy.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},hh={};uh(hh,{contractId:()=>gh,default:()=>Zy,feeObjId:()=>bh,roleObjId:()=>wh,status:()=>mh,transaction:()=>ph,upgradeCapObjId:()=>_h,vaultObjId:()=>yh});var ph="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",mh="success",gh="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",wh="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yh="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",bh="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_h="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zy={transaction:ph,status:mh,contractId:gh,roleObjId:wh,vaultObjId:yh,feeObjId:bh,upgradeCapObjId:_h},vh={};uh(vh,{contractId:()=>xh,default:()=>Ky,feeObjId:()=>Ih,roleObjId:()=>kh,status:()=>Sh,transaction:()=>Th,upgradeCapObjId:()=>Ch,vaultObjId:()=>Ah});var Th="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sh="success",xh="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",kh="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ah="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Ih="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ch="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ky={transaction:Th,status:Sh,contractId:xh,roleObjId:kh,vaultObjId:Ah,feeObjId:Ih,upgradeCapObjId:Ch},Jy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Xy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Yy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",eb="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tb="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",rb="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",nb="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",jf=hh,Ff=vh,ib=new Map([["dev",{env:"dev",rpc:{url:Jy},backend:{url:eb},contract:jf}],["stg",{env:"stg",rpc:{url:Xy},backend:{url:tb},contract:jf}],["prev",{env:"prev",rpc:{url:Yy},backend:{url:rb},contract:Ff}],["prod",{env:"prod",rpc:{url:Qy},backend:{url:nb},contract:Ff}]]);function ob(t,e){let r=ib.get(t);if(!r)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(r.rpc=e.rpc),e&&e.backend&&(r.backend=e.backend),e&&e.contract&&(r.contract=e.contract),r}var Nt=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:i}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=i}},sb=class extends Nt{constructor(){super(11,"Backend is not specified")}},ab=class extends Nt{constructor(){super(1,"Wallet not connected")}},vu=class extends Nt{constructor(t,e){super(10,t,{context:e})}},ub=class nn{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof dr.AxiosError)throw new vu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new vu(e.data.code)}throw new vu(e.status.toString())}async getIncomingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{recipient:e,...r});return nn.parseResponseData(n)}async getOutgoingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{sender:e,...r});return nn.parseResponseData(n)}async getStreamHistory(e){let r=await dr.default.post(`${this.apiURL}/stream-events`,e),n=nn.parseResponseData(r);return n.data.forEach(i=>{let o=i;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}),n}async getAllCoinTypes(e){let r=await dr.default.post(`${this.apiURL}/stream-info`,{address:e});return nn.parseResponseData(r)}async getAllRecipients(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:r});return nn.parseResponseData(n)}async getAllSenders(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:r});return nn.parseResponseData(n)}},Mh=class Eh{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Oh.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new ub(e.backend.url))}static new(e,r){let n=ob(e,r);return new Eh(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new sb;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new ab;return this.signer}async walletAddress(){return this.wallet.address()}},qf=50n,Tu=10000n,cb=25n,Lf=100000000n,rn=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Uf=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},as=class Ph{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(r,n){if(n in r)return Reflect.get(r,n);let i=s=>new Ph(r.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield i(s),s++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}moveArg(){return this.result}},$f=class extends Nt{constructor(t,e){super(3,t,{context:e})}},lb=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="address")throw new $f("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Dh.normalizeSuiAddress)(Au.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new $f("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Au.Buffer.from(r).readBigInt64LE()}},Bt=class extends Nt{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}},Bh={groupId:"string",name:"string"},db=64;function fb(t){return Nh(t),Ru.bcs.ser(Bh,t).toString("base64")}function Iu(t){let e=Ru.bcs.de(Bh,t,"base64");return Nh(e),e}function Nh(t){if(!Gf(t.name))throw new Bt("Invalid metadata: Name contains unknown character");if(!Gf(t.groupId))throw new Bt("Invalid metadata: Group ID contains unknown character");if(t.name.length>db)throw new Bt("Invalid metadata: Name exceed max length 64")}function Gf(t){return/^[\x00-\x7F]+$/.test(t)}function Rh(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}function jn(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}var jh="txn.gas";function hb(){return pf()}var Cu=class Fh{constructor(e,r,n){this.globals=e,this.feeContract=r,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:fb({name:e.name,groupId:hb()}),coinType:(0,Bi.normalizeStructTag)(e.coinType),recipients:e.recipients.map(r=>({address:r.address,cliffAmount:r.cliffAmount,amountPerEpoch:r.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let r=new ku.TransactionBlock,n=this.calculateFeesInternal(e),i=this.getCreateStreamCoinRequests(e,n),o=await this.wallet.requestCoins(i),s=await this.addMergeCoins(r,o[0]),u;i.length>1?u=await this.addMergeCoins(r,o[1]):u=s;for(let l=0;l<e.recipients.length;l++){let d=e.recipients[l],b=this.amountForRecipient(d,e.numberEpoch),_=this.getStreamFeeLocal(b),[T]=r.splitCoins(s,[r.pure(b+_,"u64")]),[x]=r.splitCoins(u,[r.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(r,{paymentCoin:new as(T),flatFeeCoin:new as(x),metadata:e.metadata,recipient:d.address,timeStart:e.startTime,cliff:d.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return r}calculateCreateStreamFees(e){let r=Fh.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(r)}feeParams(){return{createFeePercent:{numerator:qf,denominator:Tu},claimFeePercent:{numerator:cb,denominator:Tu},flatFeePerStream:Lf}}async addMergeCoins(e,r){let n;return r.mergedCoins&&r.mergedCoins.length?(e.mergeCoins(e.object(r.primaryCoin),r.mergedCoins.map(i=>e.object(i))),n=e.object(r.primaryCoin)):r.primaryCoin===jh?n=e.gas:n=e.object(r.primaryCoin),n}getCreateStreamCoinRequests(e,r){let n=e.coinType;return Rh(n,Bi.SUI_TYPE_ARG)?[{coinType:n,amount:r.totalAmount+r.streamFeeAmount+r.flatFeeAmount}]:[{coinType:n,amount:r.totalAmount+r.streamFeeAmount},{coinType:Bi.SUI_TYPE_ARG,amount:r.flatFeeAmount}]}calculateFeesInternal(e){let r=e.recipients.reduce((n,i)=>{let o=this.amountForRecipient(i,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:n.totalAmount+o,streamFeeAmount:n.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...r}}amountForRecipient(e,r){return BigInt(e.amountPerEpoch)*BigInt(r)+BigInt(e.cliffAmount)}get flatSuiFee(){return Lf}getStreamFeeLocal(e){return e*qf/Tu}async getStreamFeeRemote(e){let r=this.feeContract.streamingFee(new ku.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:r});return new lb(n).getU64()}get wallet(){return this.globals.wallet}},pb="0x0000000000000000000000000000000000000000000000000000000000000006",qh=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(Ou.Transactions.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof Uf?n.moveArgs(t):n instanceof rn?n.moveArg(t):n instanceof as?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(Ou.Transactions.MoveCall({target:e,arguments:r.map(i=>i instanceof Uf?i.moveArgs(t):i instanceof rn?i.moveArg(t):i instanceof as?i.moveArg():t.pure(i)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new rn(t):t}vaultObject(){return new rn(this.config.vaultObjId)}roleObject(){return new rn(this.config.roleObjId)}feeObject(){return new rn(this.config.feeObjId)}clockObject(){return new rn(pb)}},Lh=class Er extends qh{constructor(e,r){super(Er.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_fee,arguments:[n,i,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_flat_fee,arguments:[n,i,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_claim_fee,arguments:[n,i,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:Er.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:Er.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},cs=class Tt extends qh{constructor(e,r){super(Tt.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let n=this.feeObject(),i=this.vaultObject(),o=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.create_stream,arguments:[n,i,o,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:Tt.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.cancel_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),i=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream_by_proxy,arguments:[n,i,o,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream_by_proxy}`}},Uh=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lh(e,t),this.streamContract=new cs(e,t)}feeContract;streamContract;async createStreams(t){let e=Cu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new Pi.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}},mb=class extends Nt{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},gb=1e3,wb=class{constructor(t){this.globals=t,this.coinMetaHelper=new yb(t.suiClient),this.createStreamHelper=new Uh(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mb(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 Bt("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new Bt("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 Bt("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(_e.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:_e.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:(0,Ln.normalizeStructTag)(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,i)=>({...n,coinType:(0,Ln.normalizeStructTag)(n.coinType),coinMeta:r[i]}))}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 Bt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Bt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<gb)throw new Bt("Interval shall be at least 1 second","interval",t.interval)}},yb=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ln.normalizeStructTag)(t||Ln.SUI_TYPE_ARG);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}},bb=class extends Nt{constructor(){super(7,"Connected wallet is not creator")}},Vf=class extends Nt{constructor(){super(8,"Connected wallet is not recipient")}},zf=class extends Nt{constructor(t,e){super(6,t,{context:e})}},Xt=class extends Nt{constructor(t,e={}){super(0,t,e)}},_b=class extends Nt{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},vb=(1n<<64n)-1n,us=1e3;function Wf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return le.fromMillis(r*us)}function Hf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return _e.fromMillis(r*us)}var ju=class Pr{constructor(e,r,n){this.globals=e,this.streamId=r,this.rawData=n,this.streamContract=new cs(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,r){let n=await Pr.fetchStreamData(e,r);return new Pr(e,r,n)}static fromObjectData(e,r,n){let i=Pr.parseRawStreamData(r,n);return new Pr(e,r,i)}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 Pr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Xt("Object Id does not align");this.rawData=Pr.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new bb;let e=new Di.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let e=new Di.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let r=new Di.TransactionBlock;return this.streamContract.setAutoClaim(r,{streamId:this.streamId,coinType:this.coinType,enabled:e}),r}async claimByProxy(){let e=new Di.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Ri.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Hf(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Iu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Iu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Wf(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,r=e.epochInterval*e.totalEpoch;return Hf(r)}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:Wf((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 e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===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===vb?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=le.now().toMillis(),r=this.timeStart.toMillis();if(e<r)return-1n;let n=Math.floor((e-r)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,r){let n=await e.suiClient.getObject({id:r,options:{showContent:!0,showType:!0}});return Pr.parseRawStreamData(r,n)}static parseRawStreamData(e,r){if(r.error)throw r.error.code==="notExists"?new _b(e):new zf(`get stream data: ${r.error.code}`,{streamId:e,...r.error});let n=r.data.content;if(n.dataType!=="moveObject")throw new zf("Unexpected object type",{gotType:n.dataType});let{typeParams:i}=(0,Ri.parseStructTag)(n.type),o=(0,Ri.normalizeStructTag)(i[0]),s=n.fields,u=s.config.fields,l=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}},Su=class extends Nt{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Tb(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sb=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)}},$h=class{constructor(t){this.requester=t,this.pager=new Sb(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]}},xb=25;async function Zf(t,e,r){let n=new Gh(e),i=new Vh(t,n,r);return await Tb(i)}var Gh=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]}},Vh=class extends $h{constructor(t,e,r){super(new kb(t,e,r)),this.suiClient=t,this.idIter=e,this.options=r}},kb=class{constructor(t,e,r){this.suiClient=t,this.stringIter=e,this.options=r,this.filter=r?.filter,this.pageSize=r?.pageSize||xb,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 n=await this.stringIter.next();n&&t.push(n)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:n}=this;r=e.filter(i=>n?.(i))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}},Ab=class ns{constructor(e,r){if(this.globals=e,this.streams=r,r.length===0)throw new Su("stream size 0");let n=r.map(i=>i.groupId);if(new Set(n).size!==1)throw new Bt("Stream does not have same group ID")}type="StreamGroup";static async new(e,r){let n=await Zf(e.suiClient,r);return n.forEach(i=>{if(!i)throw new Xt("stream group object data undefined")}),ns.newFromObjectResponse(e,r,n)}static async newFromObjectResponse(e,r,n){let i=await ns.parseGroupStreams(e,r,n);return new ns(e,i)}static checkStreamGroup(e){let r=e.map(o=>o.groupCommonInfo),n=r[0],i=!0;return r.forEach(o=>{Ib(n,o)||(i=!1)}),i}async refresh(){let e=await Zf(this.globals.suiClient,this.streams.map(r=>r.streamId));this.streams.forEach((r,n)=>{r.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,r)=>e+r.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,r)=>e+r.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,r)=>r.nextReleaseAmount===null?e:e+r.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,r)=>e+r.totalAmount,0n),streamed:this.streams.reduce((e,r)=>e+r.streamedAmount,0n),claimed:this.streams.reduce((e,r)=>e+r.claimedAmount,0n),claimable:this.streams.reduce((e,r)=>e+r.claimable,0n),canceled:this.streams.reduce((e,r)=>e+r.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,r,n){let i=n.map((o,s)=>ju.fromObjectData(e,r[s],o)).filter(o=>!!o);if(new Set(i.map(o=>o.groupId)).size!==1)throw new Su("Not same group ID");if(!this.checkStreamGroup(i))throw new Su("Not same stream settings");return i}};function Ib(t,e){return t.name===e.name&&t.groupId===e.groupId&&t.creator===e.creator&&t.start.toMillis()===e.start.toMillis()&&t.interval.toMillis()===e.interval.toMillis()&&t.steps===e.steps&&t.cancelable===e.cancelable}var Kf=class Mu{constructor(e,r){this.it=e,this.pageSize=r}static async newIncoming(e){let r=await Jf.newIncoming(e);return new Mu(r,e.pageSize)}static async newOutgoing(e){let r=await Jf.newOutgoing(e);return new Mu(r,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Jf=class Eu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let r=await Xf.newIncomingQuery(e);return new Eu(r)}static async newOutgoing(e){let r=await Xf.newOutgoingQuery(e);return new Eu(r)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let r=await this.requester.doNextRequest();if(r===null)throw new Xt("No more results");return r}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Xt("No more results");return e}},Xf=class Pu{constructor(e,r,n,i){this.globals=e,this.recipient=r,this.groupRefs=n,this.query=i,this.current=0;let o=new Gh(n.flat().map(s=>s.streamId));this.objectIter=new Vh(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let r=Pb(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,r)).filter(s=>(0,Rr.normalizeSuiAddress)(s.recipient)===(0,Rr.normalizeSuiAddress)(n)),o=Yf(i);return new Pu(e.globals,n,o,e.query)}static async newOutgoingQuery(e){let r=Db(e.query),n=await e.globals.walletAddress(),i=await e.globals.backend.getOutgoingStreams(n,r),o=Yf(i);return new Pu(e.globals,n,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let r=await Mb(this.globals,e[0].streamId,this.objectIter);return this.current++,zh(r,this.query)?r:this.doNextRequest()}if(e.length>1){let r=await Eb(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Ob(r,this.query)?r:this.doNextRequest()}throw new Xt("Stream group with no stream")}};function Yf(t){let e=new Map;return t.forEach(r=>{let n=e.get(r.groupId);n?(n.push(r),e.set(r.groupId,n)):e.set(r.groupId,[r])}),Array.from(e.values()).sort((r,n)=>le.fromISO(n[0].createDate).toMillis()-le.fromISO(r[0].createDate).toMillis())}function zh(t,e){if(e===void 0)return!0;let r=Cb(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return r&&n}return r}function Cb(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function Ob(t,e){if(!e)return!0;let r=!1;return t.streams.forEach(n=>{zh(n,e)&&(r=!0)}),r}async function Mb(t,e,r){let n=await Wh(r,e);return ju.fromObjectData(t,e,n)}async function Eb(t,e,r){let n=[];for(;n.length<e.length;){let i=await Wh(r,e[n.length]);n.push(i)}return Ab.newFromObjectResponse(t,e,n)}async function Wh(t,e){if(!await t.hasNext())throw new Xt("object iterator has been consumed");let r=await t.next();if(!r||r.error||r.data===void 0||r.data===null)throw new Xt("object iterator undefined response",{cause:r?.error});if(r?.data?.objectId!==e)throw new Xt("stream id not aligned");return r}function Pb(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),sender:Zh(t?.sender)}}function Db(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),recipient:Zh(t?.recipient)}}function Fu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,r)=>{let n=Fu(r);return!e||e===n?n:"all"},void 0):Bb(t)}function Bb(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Bt("Unknown stream filtered status")}}function Hh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeStructTag)(e)):void 0:(0,Rr.normalizeStructTag)(t)}function Zh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeSuiAddress)(e)):void 0:(0,Rr.normalizeSuiAddress)(t)}var Nb=class extends Nt{constructor(t,e,r){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:r}}),this.coinType=t,this.requestAmount=e,this.gotAmount=r}},Rb=25;async function jb(t,e,r,n="0x2::sui::SUI",i=Rb){let o=new Fb(t,e,n,i),s=BigInt(0),u=[];for(;await o.hasNext()&&s<r;){let l=await o.next();l&&(u.push(l),s+=BigInt(l.balance))}if(s<r)throw new Nb(n,r,s);return u}var Fb=class extends $h{constructor(t,e,r,n){super(new qb(t,e,r,n)),this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n}},qb=class{constructor(t,e,r,n){if(this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n,n<=0)throw new Xt("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}}},Lb=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ub=class{constructor(t){this.account=t}async address(){return this.account.address}},$b=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(Rh(t.coinType,on.SUI_TYPE_ARG))return{primaryCoin:jh};if(t.amount<=0)throw new Bt("Invalid coin request","coinAmount",t.amount);let e=await jb(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new Xt("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Gb=class{globals;helper;constructor(t,e){this.globals=Mh.new(t,e),this.helper=new wb(this.globals)}connectSingleWallet(t){let e=new $b(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Lb(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ju.new(this.globals,t)}async getIncomingStreams(t,e=10){return Kf.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Kf.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(e=>(0,on.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}get wallet(){return this.globals.wallet}builder(){return new Uh(this.globals)}},Vb=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Kh.default)(this.data))}},ji=class extends Vb{application="mpay";getClient(t,e){let r=new Gb(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ub(e)),r}},Qf=class extends ji{constructor(t){super(t),this.data=t}txType=fh.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).cancel()}},eh=class extends ji{constructor(t){super(t),this.data=t}txType=Jh.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claimByProxy()}},th=class extends ji{constructor(t){super(t),this.data=t}txType=Xh.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claim()}},rh=class extends ji{constructor(t){super(t),this.data=t}txType=Yh.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:r}=t;return this.getClient(e,r).createStream(this.data)}},Qh=class is{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return is.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return is.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return BigInt(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Dr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return is.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Dr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Dr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Dr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Dr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Dr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},zb=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 t=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&jn(e.target,this.contract.createStreamTarget));if(t.length===0)throw new Xt("No create stream transactions");return t.map(e=>new Qh(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=Iu(e),i=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),b=t.decodeInputBool(11),_=t.typeArg(0);return{name:r,groupId:n,recipient:i,timeStart:o,cliff:s,epochInterval:u,totalEpoch:l,amountPerEpoch:d,cancelable:b,coinType:_}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new Bt("Stream group not have common info");let e=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:e,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 cs(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lh(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Cu(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]}},Wb=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new cs(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(t=>t.kind==="MoveCall"&&jn(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new zb(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(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let t=this.transactions[0];return new Qh(t,this.txb)}},nh=class extends ji{constructor(t){super(t),this.data=t}txType=ep.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Hb=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,n=Mh.new(e==="sui:mainnet"?"prod":"dev"),i=new Wb(n,r).decode(),o;switch(i.type){case"CreateStream":o=new rh(i.info);break;case"SetAutoClaim":o=new nh({streamId:i.streamId,enabled:i.enabled});break;case"Claim":o=new th({streamId:i.streamId});break;case"ClaimByProxy":o=new eh({streamId:i.streamId});break;case"Cancel":o=new Qf({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,r;switch(t.txSubType){case"CreateStream":r=new rh(e);break;case"Claim":r=new th(e);break;case"ClaimByProxy":r=new eh(e);break;case"SetAutoClaim":r=new nh(e);break;case"Cancel":r=new Qf(e);break;default:throw new Error("not implemented")}return r.build({...t})}},Zb=class rp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,tp.buildCoinTransferTxb)(r,this.data,n.address)}static fromData(e){return new rp(e)}},Kb=class ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,np.buildObjectTransferTxb)(r,this.data,n.address)}static fromData(e){return new ip(e)}},Jb=class ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=sp.TransactionBlock.from(this.data.content);if(!(0,op.isSameAddress)(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ap(e)}},Xb=class{application;constructor(){this.application=qn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case qn.TransactionSubTypes.assets.coin.send:n=Zb.fromData(t.intentionData);break;case qn.TransactionSubTypes.assets.object.send:n=Kb.fromData(t.intentionData);break;case qn.TransactionSubTypes.others.plain:n=Jb.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},Yb={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"}}},ce=Yb,Qb=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ce.pool).find(r=>r.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${ce.ProtocolPackage}::incentive_v2::claim_reward`){let r=new ih(e,this.txb),n=r.decodeInputU8(4),i=r.decodeInputU8(5),o=r.decodeSharedObjectId(2),s=this.findPoolByAssetId(n),u=[...e.typeArguments];t.push({coinType:s.coinType,option:i,typeArguments:u,assetId:n,poolId:o})}}),console.log("decode claims",t),{txType:Fn.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.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:Fn.TransactionType.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:Fn.TransactionType.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:Fn.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ce.ProtocolPackage));return new ih(t,this.txb)}},ih=class os{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return os.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return os.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Br.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return os.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Br.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Br.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Br.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Br.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Br.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function oh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function e_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function t_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function sh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function r_(t,e,r,n,i){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ce.IncentiveV2),t.object(r),t.object(ce.StorageId),t.pure(e),t.pure(n)],typeArguments:i}),t}var n_=class lp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new cp.TransactionBlock;return e.forEach(n=>{let{assetId:i,poolId:o,option:s,typeArguments:u}=n;r_(r,i,o,s,u)}),r}static fromData(e){return new lp(e)}},i_=class fp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new dp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return t_(n,i,r)}static fromData(e){return new fp(e)}};async function pp(t,e,r){let n=await t.getCoins({owner:e,coinType:r});return console.log("getTokenObjs",e,n),n}var o_=class mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new hp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return oh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return oh(s,u,s.object(d),o)}static fromData(e){return new mp(e)}},s_=class wp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new gp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return sh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return sh(s,u,s.object(d),o)}static fromData(e){return new wp(e)}},a_=class bp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new yp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return e_(n,i,r)}static fromData(e){return new bp(e)}},u_=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,r=new Qb(e).decode();return{txType:up.TransactionType.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=o_.fromData(t.intentionData);break;case"EntryBorrow":n=i_.fromData(t.intentionData);break;case"EntryRepay":n=s_.fromData(t.intentionData);break;case"EntryWithdraw":n=a_.fromData(t.intentionData);break;case"ClaimReward":n=n_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},c_=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}},l_="msafe-plain-tx",d_=ls.TransactionSubTypes.others.plain,f_=class{application;constructor(){this.application=l_}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ls.TransactionType.Other,txSubType:d_,intentionData:{content:(0,ds.toHEX)(n)}}}async build(t){let{suiClient:e,account:r}=t,n=_p.TransactionBlock.from((0,ds.fromHEX)(t.intentionData.content)),i=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(i.effects.status.status!=="success")throw new Error(i.effects.status.error);return n}},xu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},h_=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(8),n=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(5),o=this.helper.decodeInputU32(7);return{txType:Tp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:n,tickLower:i,tickUpper:o}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new p_(t,this.txb)}},p_=class ss{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return ss.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return ss.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU32(e){let r=this.decodePureArg(e,"u32");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Nr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return ss.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Nr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Nr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Nr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Nr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Nr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},m_=class Sp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,tickLower:l,tickUpper:d,txb:b}=this.data;return r.pool.addLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,tickLower:l,tickUpper:d,txb:b})}static fromData(e){return new Sp(e)}},g_=class xp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,nft:i,txb:o}=this.data;return r.nft.burn({pool:n,nft:i,txb:o})}static fromData(e){return new xp(e)}},w_=class kp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,collectAmountA:s,collectAmountB:u,txb:l}=this.data;return r.pool.collectFee({pool:n,address:i,collectAmountA:s,collectAmountB:u,nft:o,txb:l})}static fromData(e){return new kp(e)}},y_=class Ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,rewardAmounts:s,txb:u}=this.data;return r.pool.collectReward({pool:n,address:i,rewardAmounts:s,nft:o,txb:u})}static fromData(e){return new Ap(e)}},b_=class Ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{fee:n,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,amountA:_,amountB:T,txb:x}=this.data;return r.pool.createPool({fee:n,amountA:_,amountB:T,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,txb:x})}static fromData(e){return new Ip(e)}},__=class Cp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,txb:b}=this.data;return r.pool.decreaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,decreaseLiquidity:d,txb:b})}static fromData(e){return new Cp(e)}},v_=class Op extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,txb:d}=this.data;return r.pool.increaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,txb:d})}static fromData(e){return new Op(e)}},T_=class Mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x}=this.data;return r.pool.removeLiquidity({pool:n,decreaseLiquidity:d,nft:l,amountA:o,amountB:s,slippage:u,address:i,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x})}static fromData(e){return new Mp(e)}},ah=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=new h_(e).decode();return{txType:vp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r,network:n}=t,i;switch(t.txSubType){case"CreatePool":i=b_.fromData(t.intentionData);break;case"AddLiquidity":i=m_.fromData(t.intentionData);break;case"IncreaseLiquidity":i=v_.fromData(t.intentionData);break;case"DecreaseLiquidity":i=__.fromData(t.intentionData);break;case"RemoveLiquidity":i=T_.fromData(t.intentionData);break;case"CollectFee":i=w_.fromData(t.intentionData);break;case"CollectReward":i=y_.fromData(t.intentionData);break;case"Burn":i=g_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:r,network:n})}},fs=new c_([new Xb,new u_,new ah,new Hb,new f_,new Hy,new ah]);var me=require("@msafe/sui3-utils"),Hu=require("@mysten/sui.js/transactions"),bs=require("@mysten/sui.js/utils");var Ep=require("@mysten/sui.js/transactions"),S_=1000n,x_=120n,k_=100n,A_={multiplier:{numerator:x_,denominator:k_}};var hs=class{constructor(e){this.globals=e}async simulate(e,r=A_){let n=this.copyTransactionBlock(e.txb),{suiClient:i}=this.globals,o=await this.getGasPrice(r);n.setGasPrice(o);let s=await i.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:u}=s.effects,l=this.toGasBudget(u,o),d=s.effects.status.status==="success",b;return d||(b=s.effects.status.error),{success:d,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:u,gasBudget:l,simulationError:b}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let r=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(r,e)}toGasBudget(e,r){let{computationCost:n,storageCost:i}=e,o=S_*r,s=BigInt(n)+o,u=s+BigInt(i);return u>s?u:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,r){if(this.isFixedValue(r))return r.fixedVal;if(this.isMultiplier(r)){let{multiplier:n}=r;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ep.TransactionBlock.from(e.serialize())}};var qu=require("buffer");function ps(t){return qu.Buffer.from(t,"utf-8")}function I_(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ms(t){return Uint8Array.from(qu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ws=require("@mysten/sui.js/verify");var jr=require("@mysten/sui.js/utils");var gs=require("@mysten/sui.js/utils"),Fi=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let r=(0,gs.normalizeStructTag)(e);if(this._coinMetaReg.has(r))return this._coinMetaReg.get(r);let n=await this.queryCoinMeta(r);return n&&this._coinMetaReg.set(r,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Lu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,qi=class t{static isCoin(e){return e?(0,gs.normalizeStructTag)(e).match(Lu)!=null:!1}static getCoinType(e){let[,r]=(0,gs.normalizeStructTag)(e).match(Lu)??[];return r||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:r}=e.content?.fields;if(r!==void 0)return BigInt(r)}};var fr=class{static normalizeSuiAddress(e){return(0,jr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,jr.normalizeStructTag)(e)}static isSuiAddressEqual(e,r){return(0,jr.normalizeSuiAddress)(e)===(0,jr.normalizeSuiAddress)(r)}static isSuiStructEqual(e,r){return(0,jr.normalizeStructTag)(e)===(0,jr.normalizeStructTag)(r)}static isCoinObjectType(e){return qi.isCoin(e)}};function Uu(t,e){return t.startsWith(e)?t:e+t}var $u=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ws.verifyTransactionBlock)(e.message,e.signature):(0,ws.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let r=ps(e.messageStr);return this.getPublicKeyFromSignature({message:r,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let r=await t.getPublicKeyFromSignature(e);return fr.isSuiAddressEqual(r.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let r=ps(e.messageStr);return this.verifySignature({message:r,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Pp=require("@msafe/sui3-utils"),Dp=require("@mysten/sui.js/cryptography"),Bp=require("@mysten/sui.js/multisig");var C_="0x2::sui::SUI";async function Gu(t,e){let r;try{r=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(r.data.length===0||!r.data[0].transaction?.txSignatures)return;let i=r.data[0].transaction?.txSignatures;for(let o=0;o!==i.length;o++){let s=i[o],u=O_(s,e);if(u)return u}}function O_(t,e){let r=(0,Dp.parseSerializedSignature)(t);switch(r.signatureScheme){case"MultiSig":{let n=new Bp.MultiSigPublicKey(r.multisig.multisig_pk).toSuiAddress();if(fr.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(fr.isSuiAddressEqual(r.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Pp.PublicKeySerde.de({publicKeyEncoded:r.publicKey,schema:r.signatureScheme});return fr.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function M_(t){let e=!0,r,n=[];for(;e;){let i=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:r});n.push(...i.data),e=i.hasNextPage,r=i.nextCursor}return n}var Np=25;async function Rp(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Vu=class{constructor(e){this.requester=e;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)}},ys=class{constructor(e){this.requester=e;this.pager=new Vu(e),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]}};async function jp(t,e,r){let n=new zu(t,e,r);return await Rp(n)}var zu=class extends ys{constructor(r,n,i){super(new Wu(r,n,i));this.provider=r;this.owner=n;this.options=i}},Wu=class{constructor(e,r,n){this.provider=e;this.owner=r;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Np,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let r;if(this.filter){let{filter:n}=this;r=e.data.filter(i=>n?.(i))}else r=e.data;return{data:r.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var sn=class t{constructor(e,r){this.globals=e;this.info=r;this.multiSig=new me.MultiSigAccount({threshold:r.threshold,ownersWithWeight:r.owners,creationNonce:r.creationNonce}),this.coinHelper=new Fi(this.suiClient),this.simulator=new hs(e)}multiSig;coinHelper;simulator;static async New(e,r){let n=await e.backend.getMSafeAccountInfo(r);if(new t(e,n).address!==r)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async r=>{let n=await this.coinHelper.getCoinMeta(r.coinType),i=r.lockedBalance.number?BigInt(r.totalBalance)-BigInt(r.lockedBalance.number):BigInt(r.totalBalance);return{type:(0,bs.normalizeStructTag)(r.coinType),balance:BigInt(i),metadata:n}}))}async ownedObjects(e){let r={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return jp(this.suiClient,this.address,r)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let r=e.pending,n=e.reject;return{application:r.application,txType:r.txType,txSubType:r.txSubType,createdAt:r.createdAt,creator:r.creator,digest:r.digest,intention:r.intention,sequenceNumber:r.sequenceNumber,payload:r.payload,votes:r.votes,approvalWeight:this.calculateWeightFromVotes(r.votes),msafeAddress:r.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let r=me.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:r});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let i=await n.build({client:this.globals.suiClient}),o=await n.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,bs.toHEX)(i),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async proposeCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async simulateObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async proposeObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async simulatePlainPayloadIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async proposePlainPayloadIntention(e){let r=await this.nextSequenceNumber(),n=Hu.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,me.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async voteForTransaction(e,r){let n=ms(r),i=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:i.signature})}async proposePendingTransaction(e){let r=new Hu.TransactionBlock,n=await r.build({client:this.suiClient}),i=await r.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:i,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let r=e.payload,n=(0,me.buildRejectTxb)(this.address,r);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let r=await this.pendingTransaction();if(!r||r.rejectDigest!=="")throw new Error("Already rejected");let n=r.payload,i=(0,me.buildRejectTxb)(this.address,n),o=await i.getDigest({client:this.suiClient}),s=await i.build({client:this.suiClient}),u=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:u.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,r=!1){let n=r?e.rejectVotes:e.votes,i=r?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(n.map(l=>[l.userAddress,l.signature]));for(let l=0;l<this.info.owners.length;l++){let d=this.info.owners[l],b=s.get(d.address);b&&o.push(b)}let u=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ms(i),signature:u,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(r=>r.userAddress))}calculateWeight(e){let r=0;for(let n=0;n<e.length;n++){let i=this.info.owners.find(o=>(0,me.isSameAddress)(o.address,e[n]));i&&(r+=i.weight)}return r}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Fp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/utils");var _s=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let r=this.knownPublicKeys.get(e);if(r)return r;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let r=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];r[o]=this.knownPublicKeys.get(s)}let n=r.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(n.length===0)return r;let i=await this.globals.backend.getPublicKeyBatch(n.map(o=>e[o]));for(let o=0;o<n.length;o++){let s=n[o];r[s]=i[o]}for(let o=0;o<r.length;o++)r[o]===void 0&&(r[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)r[o]&&this.knownPublicKeys.set(e[o],r[o]);return r}addPublicKey(e,r){if(!(0,Fp.isSameAddress)(e,r.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,qp.normalizeSuiAddress)(e),r)}async _getPublicKey(e){let r=await this.getPublicKeyFromBackend(e);if(r)return r;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Gu(this.globals.suiClient,e)}};var vs=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Wp=require("@mysten/sui.js/client");var Ui=require("@msafe/sui3-utils"),Li=de(require("axios"),1);var Ts=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let r=await this.post("/auth/login",e);return this._token=r.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let r={userAddressList:e};return(await this.get("/user/public-keys",{params:r,headers:this.headers()})).data?.map(i=>i?Ui.PublicKeySerde.de(i):void 0)}async getMSafeAccountInfo(e){let r={msafeAddress:e},n=await this.get("/msafe",{params:r,headers:this.headers()});return t.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let r={status:e.status??Ui.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:r,headers:this.headers()});return{data:n.data.data.map(t.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let r=e;await this.post("/msafe/status",r,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(r=>({address:r.address,weight:r.weight,publicKey:Ui.PublicKeySerde.de({publicKeyEncoded:r.publicKeyEncoded,schema:r.schema})}))}}async get(e,r){let n=this.getFullUrl(e);try{return await Li.default.get(n,r)}catch(i){throw Ss.fromError(i)??i}}async post(e,r,n){let i=this.getFullUrl(e);try{return await Li.default.post(i,r,{...n,transformRequest:this.getTransformRequest()})}catch(o){throw Ss.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Uu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:r}=Li.default.defaults;return r?r instanceof Array?e=r:e=[r]:e=[],[n=>JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ss=class t extends Error{constructor(r){super();this.e=r;Error.captureStackTrace(this,this.constructor)}name;static fromError(r){if(Li.default.isAxiosError(r)&&r?.response?.data&&"message"in r.response.data)return new t(r)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Lp=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Lp||{}),xs="https://fullnode.testnet.sui.io",Zu="https://fullnode.mainnet.sui.io",Ku="http://127.0.0.1:3000",Ju="http://127.0.0.1:3001",Up="https://sui-dev.m-safe.link",$p="http://13.56.226.148:81",Gp="https://sui-preview.m-safe.link",Vp="https://sui.m-safe.link",zp=new Map([["unit",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["local",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["dev",{suiClient:{url:xs},backend:{url:Up},syncingURL:$p,network:"sui:testnet"}],["prev",{suiClient:{url:Zu},backend:{url:Gp},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Zu},backend:{url:Vp},syncingURL:"",network:"sui:mainnet"}]]);function Xu(t,e){let r=zp.get(t);if(!r)throw new Error("Unknown environment");return e?.suiClient?.url&&(r.suiClient.url=e.suiClient.url),e?.backend?.url&&(r.backend.url=e.backend.url),r}var $i=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,r){let n=Xu(e,r),i=new Wp.SuiClient(n.suiClient),o=new Ts(n.backend.url);return new t({backend:o,suiClient:i,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var ks=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,r){let n=await $i.New(e,r);return new t(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let r=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(r),r}async authSign(e){let r=As.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:r});return this.backend.authSign({address:await e.address(),message:r,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:As.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new sn(this.globals,e)}async getMSafeAccountFromAddress(e){let r=await this.backend.getMSafeAccountInfo(e);return new sn(this.globals,r)}get creationHelper(){return this._creationHelper||(this._creationHelper=new un(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _s(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new cn(this.globals)}get Invitation(){return new zi(this.globals)}get Report(){return new vs(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2054
2054
|
/*! Bundled license information:
|
|
2055
2055
|
|
|
2056
2056
|
@syntsugar/cc-graph/dist/index.umd.js:
|