@msafe/sui3-sdk 0.0.49-pre-9bcd80b.0 → 0.0.49-pre-e5a4c1c.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 To=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=new Set,bu=typeof process=="object"&&process?process:{},Rh=(t,e,n,i)=>{typeof bu.emitWarning=="function"?bu.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},Hs=globalThis.AbortController,Fh=globalThis.AbortSignal;if(typeof Hs>"u"){Fh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},Hs=class{constructor(){e()}signal=new Fh;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let r of this.signal._onabort)r(i);this.signal.onabort?.(i)}}};let t=bu.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Rh("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 Cb=t=>!Nh.has(t),YA=Symbol("type"),ui=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),qh=t=>ui(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ir:null:null,Ir=class extends Array{constructor(e){super(e),this.fill(0)}},vu=class t{heap;length;static#c=!1;static create(e){let n=qh(e);if(!n)return[];t.#c=!0;let i=new t(e,n);return t.#c=!1,i}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zs=class t{#c;#d;#y;#m;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#p;#r;#n;#e;#u;#f;#a;#o;#g;#s;#k;#T;#_;#w;#S;#l;static unsafeExposeInternals(e){return{starts:e.#T,ttls:e.#_,sizes:e.#k,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,i,r,o)=>e.#E(n,i,r,o),moveToTail:n=>e.#I(n),indexes:n=>e.#b(n),rindexes:n=>e.#v(n),isStale:n=>e.#h(n)}}get max(){return this.#c}get maxSize(){return this.#d}get calculatedSize(){return this.#p}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#m}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:u,dispose:l,disposeAfter:h,noDisposeOnSet:w,noUpdateTTL:v,maxSize:T=0,maxEntrySize:I=0,sizeCalculation:x,fetchMethod:P,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:$,ignoreFetchAbort:Z}=e;if(n!==0&&!ui(n))throw new TypeError("max option must be a nonnegative integer");let H=n?qh(n):Array;if(!H)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=T,this.maxEntrySize=I||this.#d,this.sizeCalculation=x,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(P!==void 0&&typeof P!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=P,this.#S=!!P,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new H(n),this.#f=new H(n),this.#a=0,this.#o=0,this.#g=vu.create(n),this.#i=0,this.#p=0,typeof l=="function"&&(this.#y=l),typeof h=="function"?(this.#m=h,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#w=!!this.#y,this.#l=!!this.#m,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!B,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#d!==0&&!ui(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!ui(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#R()}if(this.allowStale=!!u,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=ui(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!ui(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#c===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#d){let te="LRU_CACHE_UNBOUNDED";Cb(te)&&(Nh.add(te),Rh("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",te,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#M(){let e=new Ir(this.#c),n=new Ir(this.#c);this.#_=e,this.#T=n,this.#B=(o,s,a=To.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let u=setTimeout(()=>{this.#h(o)&&this.delete(this.#n[o])},s+1);u.unref&&u.unref()}},this.#A=o=>{n[o]=e[o]!==0?To.now():0},this.#C=(o,s)=>{if(e[s]){let a=e[s],u=n[s];o.ttl=a,o.start=u,o.now=i||r();let l=o.now-u;o.remainingTTL=a-l}};let i=0,r=()=>{let o=To.now();if(this.ttlResolution>0){i=o;let s=setTimeout(()=>i=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],u=n[s];if(a===0||u===0)return 1/0;let l=(i||r())-u;return a-l},this.#h=o=>e[o]!==0&&n[o]!==0&&(i||r())-n[o]>e[o]}#A=()=>{};#C=()=>{};#B=()=>{};#h=()=>!1;#R(){let e=new Ir(this.#c);this.#p=0,this.#k=e,this.#x=n=>{this.#p-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!ui(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!ui(r))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 r},this.#P=(n,i,r)=>{if(e[n]=i,this.#d){let o=this.#d-e[n];for(;this.#p>o;)this.#D(!0)}this.#p+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#p)}}#x=e=>{};#P=(e,n,i)=>{};#j=(e,n,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#F(n)||((e||!this.#h(n))&&(yield n),n===this.#a));)n=this.#f[n]}*#v({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#F(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#F(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#b()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#v()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#b())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,n={}){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&e(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(e,n=this){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}rforEach(e,n=this){for(let i of this.#v()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}purgeStale(){let e=!1;for(let n of this.#v({allowStale:!0}))this.#h(n)&&(this.delete(this.#n[n]),e=!0);return e}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let s={value:o};if(this.#_&&this.#T){s.ttl=this.#_[n];let a=To.now()-this.#T[n];s.start=Math.floor(Date.now()-a)}this.#k&&(s.size=this.#k[n]),e.unshift([i,s])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let r=Date.now()-i.start;i.start=To.now()-r}this.set(n,i.value,i)}}set(e,n,i={}){if(n===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:u}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,h=this.#j(e,n,i.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return u&&(u.set="miss",u.maxEntrySizeExceeded=!0),this.delete(e),this;let w=this.#i===0?void 0:this.#r.get(e);if(w===void 0)w=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[w]=e,this.#e[w]=n,this.#r.set(e,w),this.#u[this.#o]=w,this.#f[w]=this.#o,this.#o=w,this.#i++,this.#P(w,h,u),u&&(u.set="add"),l=!1;else{this.#I(w);let v=this.#e[w];if(n!==v){if(this.#S&&this.#t(v)?v.__abortController.abort(new Error("replaced")):s||(this.#w&&this.#y?.(v,e,"set"),this.#l&&this.#s?.push([v,e,"set"])),this.#x(w),this.#P(w,h,u),this.#e[w]=n,u){u.set="replace";let T=v&&this.#t(v)?v.__staleWhileFetching:v;T!==void 0&&(u.oldValue=T)}}else u&&(u.set="update")}if(r!==0&&!this.#_&&this.#M(),this.#_&&(l||this.#B(w,r,o),u&&this.#C(u,w)),!s&&this.#l&&this.#s){let v=this.#s,T;for(;T=v?.shift();)this.#m?.(...T)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#D(!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,n;for(;n=e?.shift();)this.#m?.(...n)}}}#D(e){let n=this.#a,i=this.#n[n],r=this.#e[n];return this.#S&&this.#t(r)?r.__abortController.abort(new Error("evicted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#x(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#g.push(n)),this.#i===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#u[n],this.#r.delete(i),this.#i--,n}has(e,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#r.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))r&&(r.has="stale",this.#C(r,o));else return i&&this.#A(o),r&&(r.has="hit",this.#C(r,o)),!0}else r&&(r.has="miss");return!1}peek(e,n={}){let{allowStale:i=this.allowStale}=n,r=this.#r.get(e);if(r!==void 0&&(i||!this.#h(r))){let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}}#E(e,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let s=new Hs,{signal:a}=i;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let u={signal:s.signal,options:i,context:r},l=(x,P=!1)=>{let{aborted:O}=s.signal,E=i.ignoreFetchAbort&&x!==void 0;if(i.status&&(O&&!P?(i.status.fetchAborted=!0,i.status.fetchError=s.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),O&&!E&&!P)return w(s.signal.reason);let B=T;return this.#e[n]===T&&(x===void 0?B.__staleWhileFetching?this.#e[n]=B.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,x,u.options))),x},h=x=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=x),w(x)),w=x=>{let{aborted:P}=s.signal,O=P&&i.allowStaleOnFetchAbort,E=O||i.allowStaleOnFetchRejection,B=E||i.noDeleteOnFetchRejection,$=T;if(this.#e[n]===T&&(!B||$.__staleWhileFetching===void 0?this.delete(e):O||(this.#e[n]=$.__staleWhileFetching)),E)return i.status&&$.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),$.__staleWhileFetching;if($.__returned===$)throw x},v=(x,P)=>{let O=this.#O?.(e,o,u);O&&O instanceof Promise&&O.then(E=>x(E),P),s.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(),i.allowStaleOnFetchAbort&&(x=E=>l(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let T=new Promise(v).then(l,h),I=Object.assign(T,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,I,{...u.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=I,I}#t(e){if(!this.#S)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Hs}async fetch(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:u=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:v=this.allowStaleOnFetchRejection,ignoreFetchAbort:T=this.ignoreFetchAbort,allowStaleOnFetchAbort:I=this.allowStaleOnFetchAbort,context:x,forceRefresh:P=!1,status:O,signal:E}=n;if(!this.#S)return O&&(O.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:O});let B={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:u,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:I,ignoreFetchAbort:T,status:O,signal:E},$=this.#r.get(e);if($===void 0){O&&(O.fetch="miss");let Z=this.#E(e,$,B,x);return Z.__returned=Z}else{let Z=this.#e[$];if(this.#t(Z)){let N=i&&Z.__staleWhileFetching!==void 0;return O&&(O.fetch="inflight",N&&(O.returnedStale=!0)),N?Z.__staleWhileFetching:Z.__returned=Z}let H=this.#h($);if(!P&&!H)return O&&(O.fetch="hit"),this.#I($),r&&this.#A($),O&&this.#C(O,$),Z;let te=this.#E(e,$,B,x),V=te.__staleWhileFetching!==void 0&&i;return O&&(O.fetch=H?"stale":"refresh",V&&H&&(O.returnedStale=!0)),V?te.__staleWhileFetching:te.__returned=te}}get(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let u=this.#e[a],l=this.#t(u);return s&&this.#C(s,a),this.#h(a)?(s&&(s.get="stale"),l?(s&&i&&u.__staleWhileFetching!==void 0&&(s.returnedStale=!0),i?u.__staleWhileFetching:void 0):(o||this.delete(e),s&&i&&(s.returnedStale=!0),i?u:void 0)):(s&&(s.get="hit"),l?u.__staleWhileFetching:(this.#I(a),r&&this.#A(a),u))}else s&&(s.get="miss")}#N(e,n){this.#f[n]=e,this.#u[e]=n}#I(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#N(this.#f[e],this.#u[e]),this.#N(this.#o,e),this.#o=e)}delete(e){let n=!1;if(this.#i!==0){let i=this.#r.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.clear();else{this.#x(i);let r=this.#e[i];this.#t(r)?r.__abortController.abort(new Error("deleted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,e,"delete"),this.#l&&this.#s?.push([r,e,"delete"])),this.#r.delete(e),this.#n[i]=void 0,this.#e[i]=void 0,i===this.#o?this.#o=this.#f[i]:i===this.#a?this.#a=this.#u[i]:(this.#u[this.#f[i]]=this.#u[i],this.#f[this.#u[i]]=this.#f[i]),this.#i--,this.#g.push(i)}}if(this.#l&&this.#s?.length){let i=this.#s,r;for(;r=i?.shift();)this.#m?.(...r)}return n}clear(){for(let e of this.#v({allowStale:!0})){let n=this.#e[e];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#n[e];this.#w&&this.#y?.(n,i,"delete"),this.#l&&this.#s?.push([n,i,"delete"])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#_&&this.#T&&(this.#_.fill(0),this.#T.fill(0)),this.#k&&this.#k.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#p=0,this.#i=0,this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#m?.(...n)}}};var ae=ge(ke(),1);var Qs=ge(Lh(),1),Fi=require("@mysten/sui.js/utils"),Ni=require("@mysten/sui.js/transactions");var Co=ge(ke(),1),Hh=require("@mysten/sui.js/transactions"),Wt=ge(ke(),1);var li=ge(ke(),1),ln=ge(ke(),1);var xo=ge(ke(),1);var Zh=require("@mysten/sui.js/utils"),ea=require("@mysten/sui.js/transactions"),ta=require("@mysten/sui.js/utils");var xu=ge(ke(),1),Sb=Object.defineProperty,Ab=(t,e,n)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,On=(t,e,n)=>(Ab(t,typeof e!="symbol"?e+"":e,n),n);var Xs=443636,Js=-443636,Cu="79226673515401279992447579055",Su="4295048016",Ib=14,Ob="59543866431248",Pb="184467440737095516",Db="15793534762490258745",Eb=class{generateMnemonic(t=24){return Bh(jh,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return zh.Ed25519Keypair.deriveKeypair(t,n)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:n=!1,addressIndex:i=0}=t;return`m/44'/784'/${e}'/${n?1:0}'/${i}'`}},Ao=class{constructor(t){this.sdk=t,On(this,"_lru"),On(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new Zs({max:100}));if(r.has(t))return r.get(t);let s=await((i=this._fetching)[t]||(i[t]=e()));return delete this._fetching[t],r.set(t,s,{ttl:n}),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 Mb(t){if("reference"in t)return t.reference;let e=Iu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Gh(t)}function ia(t){var e,n;return"objectId"in t?t.objectId:(n=(e=Mb(t))==null?void 0:e.objectId)!=null?n:Wh(t)}function Pn(t){var e;return"fields"in t?t.fields:(e=Vh(t))==null?void 0:e.fields}function Vh(t){let e="data"in t?Iu(t):t;if(!(!e||!Bb(e)||e.content.dataType!=="moveObject"))return e.content}function Bb(t){return t.content!==void 0}function Iu(t){return t.data}function Gh(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 Wh(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function jb(t){return t.data!==void 0}function Fb(t){var e;let n=jb(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":na(t):n?.type}function na(t){var e;return(e=Vh(t))==null?void 0:e.type}function Nb(t){var e;return(e=Iu(t))==null?void 0:e.owner}var So=async(t,e,n)=>{let r=e.length;if(r>50){let o=[],s=0,a=Math.ceil(r/50);for(s;s<a;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:n}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:n})},Rb=class extends Ao{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 So(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=Pn(i),o=ia(i),s=na(i);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:r.fee,tickSpacing:r.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())}},$h=new ae.default(2).pow(new ae.default(128)),qb=class{priceToSqrtPriceX64(t,e,n){return new ae.default(new F(t).mul(F.pow(10,n-e)).sqrt().mul(F.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new F(t.toString()).mul(F.pow(2,-64)).pow(2).mul(F.pow(10,e-n))}priceToTickIndex(t,e,n){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,n))}sqrtPriceX64ToTickIndex(t){if(t.gt(new ae.default(Cu))||t.lt(new ae.default(Su)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new ae.default(e-64),i=this.signedShiftLeft(n,32,128),r=new ae.default("8000000000000000","hex"),o=0,s=new ae.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ae.default(0))&&o<Ib;){a=a.mul(a);let T=a.shrn(127);a=a.shrn(63+T.toNumber()),s=s.add(r.mul(T)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ae.default(Ob)),w=this.signedShiftRight(h.sub(new ae.default(Pb)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(Db)),64,128).toNumber();return w==v?w:this.tickIndexToSqrtPriceX64(v).lte(t)?v:w}tickIndexToSqrtPriceX64(t){return t>0?new ae.default(this.tickIndexToSqrtPricePositive(t)):new ae.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,n){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,n)}toX64_Decimal(t){return t.mul(F.pow(2,64))}fromX64_Decimal(t){return t.mul(F.pow(2,-64))}scaleDown(t,e){return new F(t).div(F.pow(10,e)).toString()}scaleUp(t,e){return new F(t).mul(F.pow(10,e)).toString()}bitsToNumber(t,e=32){return Qs.default.toNumber(Qs.default.asIntN(e,Qs.default.BigInt(t)))}subUnderflowU128(t,e){return t.add($h).sub(e).mod($h)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new ae.default("79232123823359799118286999567"):e=new ae.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new ae.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new ae.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new ae.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new ae.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new ae.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new ae.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new ae.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new ae.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new ae.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new ae.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new ae.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new ae.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new ae.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new ae.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new ae.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new ae.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new ae.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new ae.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),n;return e&1?n=new ae.default("18445821805675392311"):n=new ae.default("18446744073709551616"),e&2&&(n=this.signedShiftRight(n.mul(new ae.default("18444899583751176498")),64,256)),e&4&&(n=this.signedShiftRight(n.mul(new ae.default("18443055278223354162")),64,256)),e&8&&(n=this.signedShiftRight(n.mul(new ae.default("18439367220385604838")),64,256)),e&16&&(n=this.signedShiftRight(n.mul(new ae.default("18431993317065449817")),64,256)),e&32&&(n=this.signedShiftRight(n.mul(new ae.default("18417254355718160513")),64,256)),e&64&&(n=this.signedShiftRight(n.mul(new ae.default("18387811781193591352")),64,256)),e&128&&(n=this.signedShiftRight(n.mul(new ae.default("18329067761203520168")),64,256)),e&256&&(n=this.signedShiftRight(n.mul(new ae.default("18212142134806087854")),64,256)),e&512&&(n=this.signedShiftRight(n.mul(new ae.default("17980523815641551639")),64,256)),e&1024&&(n=this.signedShiftRight(n.mul(new ae.default("17526086738831147013")),64,256)),e&2048&&(n=this.signedShiftRight(n.mul(new ae.default("16651378430235024244")),64,256)),e&4096&&(n=this.signedShiftRight(n.mul(new ae.default("15030750278693429944")),64,256)),e&8192&&(n=this.signedShiftRight(n.mul(new ae.default("12247334978882834399")),64,256)),e&16384&&(n=this.signedShiftRight(n.mul(new ae.default("8131365268884726200")),64,256)),e&32768&&(n=this.signedShiftRight(n.mul(new ae.default("3584323654723342297")),64,256)),e&65536&&(n=this.signedShiftRight(n.mul(new ae.default("696457651847595233")),64,256)),e&131072&&(n=this.signedShiftRight(n.mul(new ae.default("26294789957452057")),64,256)),e&262144&&(n=this.signedShiftRight(n.mul(new ae.default("37481735321082")),64,256)),n}signedShiftLeft(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}signedShiftRight(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}},Au=(t,e)=>{let n=ia(t);if(Gh(t))throw new Error(`${e}(${n}) had been deleted`);if(Wh(t))throw new Error(`${e}(${n}) is not found`);return!0},Or=60*1e3,Lb=class extends Ao{async getPools(t=!1){let e=await this.contract.getConfig(),n=[],i;do i=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:i?.nextCursor,limit:15}),n.push(...i.data.map(a=>a.objectId));while(i.hasNextPage);if(!n.length)return[];let o=(await So(this.provider,n,{showContent:!0})).map(a=>Pn(a).value.fields.pool_id);if(!o.length)return[];let s=await So(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>Pn(a).unlocked)),s.map(a=>this.parsePool(a))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:n,tickLower:i,tickUpper:r,sqrtPrice:o,slippage:s,coinTypeA:a,coinTypeB:u}=t,l=await this.contract.getConfig(),h=new F(t.amountA),w=new F(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,w)]),I=t.txb||new Ni.TransactionBlock,x=v.length>0?this.coin.convertTradeCoins(I,v,a,h):[this.coin.zero(a,I)],P=T.length>0?this.coin.convertTradeCoins(I,T,u,w):[this.coin.zero(u,I)];return I.moveCall({target:`${l.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[a,u,e.type],arguments:[I.object(l.PoolConfig),I.object(e.objectId),I.pure(o,"u128"),I.object(l.Positions),I.makeMoveVec({objects:x}),I.makeMoveVec({objects:P}),I.pure(Math.abs(i).toFixed(0),"u32"),I.pure(i<0,"bool"),I.pure(Math.abs(r).toFixed(0),"u32"),I.pure(r<0,"bool"),I.pure(h.toFixed(0),"u64"),I.pure(w.toFixed(0),"u64"),I.pure(this.getMinimumAmountBySlippage(h,s),"u64"),I.pure(this.getMinimumAmountBySlippage(w,s),"u64"),I.pure(n,"address"),I.pure(Date.now()+Or,"u64"),I.object(Fi.SUI_CLOCK_OBJECT_ID),I.object(l.Versioned)]}),I}async addLiquidity(t){let{address:e,tickLower:n,tickUpper:i,slippage:r,pool:o}=t,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(o),[u,l]=a,[h,w]=await Promise.all([this.coin.getMetadata(u),this.coin.getMetadata(l)]);if(!h||!w)throw new Error("Invalid coin type");let v=new F(t.amountA),T=new F(t.amountB),[I,x]=await Promise.all([this.coin.selectTradeCoins(e,u,v),this.coin.selectTradeCoins(e,l,T)]),P=t.txb||new Ni.TransactionBlock,O=I.length>0?this.coin.convertTradeCoins(P,I,u,v):[this.coin.zero(u,P)],E=x.length>0?this.coin.convertTradeCoins(P,x,l,T):[this.coin.zero(l,P)];return P.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:a,arguments:[P.object(o),P.object(s.Positions),P.makeMoveVec({objects:O}),P.makeMoveVec({objects:E}),P.pure(Math.abs(n).toFixed(0),"u32"),P.pure(n<0,"bool"),P.pure(Math.abs(i).toFixed(0),"u32"),P.pure(i<0,"bool"),P.pure(v.toFixed(0),"u64"),P.pure(T.toFixed(0),"u64"),P.pure(this.getMinimumAmountBySlippage(v,r),"u64"),P.pure(this.getMinimumAmountBySlippage(T,r),"u64"),P.pure(e,"address"),P.pure(Date.now()+Or,"u64"),P.object(Fi.SUI_CLOCK_OBJECT_ID),P.object(s.Versioned)]}),P}async increaseLiquidity(t){let{pool:e,slippage:n,address:i,nft:r}=t,o=await this.contract.getConfig(),s=new F(t.amountA),a=new F(t.amountB),u=await this.getPoolTypeArguments(e),[l,h]=u,[w,v]=await Promise.all([this.coin.selectTradeCoins(i,l,s),this.coin.selectTradeCoins(i,h,a)]),T=t.txb||new Ni.TransactionBlock,I=w.length>0?this.coin.convertTradeCoins(T,w,l,s):[this.coin.zero(l,T)],x=v.length>0?this.coin.convertTradeCoins(T,v,h,a):[this.coin.zero(h,T)];return T.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:u,arguments:[T.object(e),T.object(o.Positions),T.makeMoveVec({objects:I}),T.makeMoveVec({objects:x}),T.object(r),T.pure(s.toFixed(0),"u64"),T.pure(a.toFixed(0),"u64"),T.pure(this.getMinimumAmountBySlippage(s,n),"u64"),T.pure(this.getMinimumAmountBySlippage(a,n),"u64"),T.pure(Date.now()+Or*3,"u64"),T.object(Fi.SUI_CLOCK_OBJECT_ID),T.object(o.Versioned)]}),T}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new F(t.amountA),s=new F(t.amountB),a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(i),l=t.txb||new Ni.TransactionBlock;return l.moveCall({target:`${a.PackageId}::position_manager::decrease_liquidity`,typeArguments:u,arguments:[l.object(i),l.object(a.Positions),l.object(n),l.pure(new Co.default(r).toString(),"u128"),l.pure(this.getMinimumAmountBySlippage(o,e),"u64"),l.pure(this.getMinimumAmountBySlippage(s,e),"u64"),l.pure(Date.now()+Or*3,"u64"),l.object(Fi.SUI_CLOCK_OBJECT_ID),l.object(a.Versioned)]}),l}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:n,address:i,collectAmountA:r,collectAmountB:o}=t,s=t.txb||new Ni.TransactionBlock;if(Number(r)===0&&Number(o)===0)return s;let a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return s.moveCall({target:`${a.PackageId}::position_manager::collect`,typeArguments:u,arguments:[s.object(e),s.object(a.Positions),s.object(n),s.pure(r,"u64"),s.pure(o,"u64"),s.pure(i),s.pure(Date.now()+Or*3,"u64"),s.object(Fi.SUI_CLOCK_OBJECT_ID),s.object(a.Versioned)]}),s}async collectReward(t){let{pool:e,nft:n,rewardAmounts:i,address:r}=t,o=t.txb||new Ni.TransactionBlock,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((l,h)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...a,l.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(n),o.object(l.fields.vault),o.pure(h,"u64"),o.pure(i[h],"u64"),o.pure(r),o.pure(Date.now()+Or*3,"u64"),o.object(Fi.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new F((t.liquidity||new Co.default(1e8)).toString()),n=new F(t.currentSqrtPrice.toString()),i=new F(t.lowerSqrtPrice.toString()),r=new F(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(i)).div(i.mul(r)),s=new F(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(n)).div(n.mul(r)),s=this.math.fromX64_Decimal(e.mul(n.sub(i)))):(o=new F(0),s=this.math.fromX64_Decimal(e.mul(r.sub(i))));let a=t.ceil!==!1?"ceil":"floor";return[new Co.default(o[a]().toString()),new Co.default(s[a]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var n;let i=((n=t.replace(">","").split("<")[1])==null?void 0:n.split(/,\s*/))||[];if(e!==void 0&&e!==i.length)throw new Error("Invalid pool type");return i}async getFixedLiquidity(t){var e,n;let{coinTypeA:i,coinTypeB:r,amountA:o,amountB:s}=t,[a,u]=await Promise.all([this.coin.getMetadata(i),this.coin.getMetadata(r)]),l=new F(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),h=new F(this.math.scaleDown(s,u.decimals)).mul((n=t.priceB)!=null?n:1);return{liquidityA:l.toString(),liquidityB:h.toString(),liquidity:l.plus(h).toString()}}parsePool(t){let e=Pn(t),n=ia(t),i=Fb(t),r=this.parsePoolType(i,3);return this.getCacheOrSet("pool-type-"+n,async()=>r),{...e,objectId:n,type:i,types:r}}getMinimumAmountBySlippage(t,e){let n=new F(t),i=new F(1).minus(new F(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},$b=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new li.default(n.fee_growth_global_a),a=new li.default(i.fee_growth_inside_a),u=new li.default(i.tokens_owed_a),l=new li.default(n.fee_growth_global_b),h=new li.default(i.fee_growth_inside_b),w=new li.default(i.tokens_owed_b),v=new li.default(i.liquidity),T,I,x,P,O=t.bitsToNumber(n.tick_current_index.fields.bits),E=t.bitsToNumber(i.tick_lower_index.fields.bits),B=t.bitsToNumber(i.tick_upper_index.fields.bits);O<E?(T=t.subUnderflowU128(s,r.feeGrowthOutsideA),I=t.subUnderflowU128(l,r.feeGrowthOutsideB)):(T=r.feeGrowthOutsideA,I=r.feeGrowthOutsideB),O<B?(x=o.feeGrowthOutsideA,P=o.feeGrowthOutsideB):(x=t.subUnderflowU128(s,o.feeGrowthOutsideA),P=t.subUnderflowU128(l,o.feeGrowthOutsideB));let $=t.subUnderflowU128(t.subUnderflowU128(s,T),x),Z=t.subUnderflowU128(t.subUnderflowU128(l,I),P),H=t.subUnderflowU128($,a).mul(v).shrn(64),te=t.subUnderflowU128(Z,h).mul(v).shrn(64);return{feeOwedA:u.add(H).toString(),feeOwedB:w.add(te).toString()}},Uh=new xo.default(0),Kh=new xo.default(1),Ub=new xo.default(2),Kb={mul(t,e,n){let i=t.mul(e);if(this.isOverLimit(i,n))throw new Error(`Mul result higher than u${n}`);return i},mulDiv(t,e,n,i){return this.mulDivRoundUpIf(t,e,n,!1,i)},mulDivRoundUpIf(t,e,n,i,r){if(n.eq(Uh))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt(Uh)?s.add(Kh):s},isOverLimit(t,e){let n=Ub.pow(new xo.default(e)).sub(Kh);return t.gt(n)}},zb=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,w=new ln.default(new F(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),T=(h??new ln.default(Date.now()).div(new ln.default(1e3))).sub(new ln.default(w)),I=[],x=new ln.default(s.liquidity),P=new ln.default(a.liquidity);for(let O=0;O<3;++O){let E=s.reward_infos[O],B={emissionsPerSecondX64:new ln.default(E?E.fields.emissions_per_second:"0"),growthGlobalX64:new ln.default(E?E.fields.growth_global:"0")},$={growthInsideCheckpoint:new ln.default((i=(n=a.reward_infos[O])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new ln.default((o=(r=a.reward_infos[O])==null?void 0:r.fields.amount_owed)!=null?o:"0")},Z=B.growthGlobalX64;if(!x.isZero()){let C=Kb.mulDiv(T,B.emissionsPerSecondX64,x,128);Z=B.growthGlobalX64.add(C)}let H=u.rewardGrowthsOutside[O],te=l.rewardGrowthsOutside[O],U=Z;u.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_lower_index.fields.bits)?t.subUnderflowU128(Z,H):H);let V=new ln.default(0);l.initialized&&(V=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_upper_index.fields.bits)?te:t.subUnderflowU128(Z,te));let N=t.subUnderflowU128(t.subUnderflowU128(Z,U),V),K=$.amountOwed.shln(64);I[O]=K.add(t.subUnderflowU128(N,$.growthInsideCheckpoint).mul(P)).shrn(64).toString()}return I},Vb=class extends Ao{async getOwner(t){let e=await this.getObject(t),n=Nb(e);if(!(!n||typeof n=="string")){if("ObjectOwner"in n)return n.ObjectOwner;if("AddressOwner"in n)return n.AddressOwner}}async getFields(t){let e=await this.getObject(t);return Pn(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return Pn(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"position"),Pn(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=Pn(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new Wt.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Wt.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new Wt.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Wt.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new Wt.default(r))}}async getPositionAPR(t){let{poolId:e,getPrice:n,fees24h:i,tickLower:r,tickUpper:o}=t,s=await this.pool.getPool(e),a=this.math.bitsToNumber(s.tick_current_index.fields.bits),[u,l,h,w]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),n(s.types[0]),n(s.types[1])]);if(!h||!w||r>=o||a<r||a>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:v,minTokenB:T}=this.getRemoveLiquidityQuote(s,r,o),I=new F(this.math.scaleDown(v.toString(),u.decimals)).mul(h),x=new F(this.math.scaleDown(T.toString(),l.decimals)).mul(w),P=I.add(x),O=P.isZero()?new F(0):new F(i).mul(365).div(P).mul(100),E=new F(0);return await Promise.all(s.reward_infos.map(async B=>{let{emissions_per_second:$}=B.fields,Z=this.coin.formatCoinType(B.fields.vault_coin_type),[H,te]=await Promise.all([n(Z),this.coin.getMetadata(Z)]);!$||$==="0"||!H||(E=E.add(new F(new Wt.default($).shrn(64).toString()).div(10**te.decimals).mul(31536e3).mul(H).div(P).mul(100)))})),{fees:O.toString(),rewards:E.toString(),total:O.plus(E).toString()}}getRemoveLiquidityQuote(t,e,n){let i=new Wt.default(0),r=new Wt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),a=this.math.tickIndexToSqrtPriceX64(n);if(o<e){let l=this.getTokenAFromLiquidity(r,s,a);return{minTokenA:this.adjustForSlippage(l),minTokenB:i}}if(o<n){let l=new Wt.default(t.sqrt_price),h=this.getTokenAFromLiquidity(r,l,a),w=this.getTokenBFromLiquidity(r,s,l);return{minTokenA:this.adjustForSlippage(h),minTokenB:this.adjustForSlippage(w)}}let u=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(u)}}adjustForSlippage(t){let e={numerator:new Wt.default(0),denominator:new Wt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,n){let i=t.mul(n.sub(e)).shln(64),r=n.mul(e);return i.div(r)}getTokenBFromLiquidity(t,e,n){return t.mul(n.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:n}=t,i=t.txb||new Hh.TransactionBlock,r=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return i.moveCall({target:`${r.PackageId}::position_manager::burn`,typeArguments:o,arguments:[i.object(r.Positions),i.object(n),i.object(r.Versioned)]}),i}async getPositionLiquidityUSD(t){let{position:e,poolId:n,priceA:i,priceB:r}=t,o=await this.pool.getPool(n),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Wt.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 Wt.default(e.liquidity===void 0?1e8:e.liquidity)}),[a,u]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),l=new F(s[0].toString()).div(10**a.decimals).mul(i||0),h=new F(s[1].toString()).div(10**u.decimals).mul(r||0);return l.plus(h).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:n}=t,[i,r,o]=await Promise.all([this.pool.getPool(n),this.nft.getPositionTick(n,e.tick_lower_index),this.nft.getPositionTick(n,e.tick_upper_index)]),s={...t,pool:i,tickLowerDetail:r,tickUpperDetail:o},[a,u]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:l,...h}=a,{unclaimedRewards:w,...v}=u;return{fees:a.unclaimedFees.toString(),rewards:w.toString(),total:l.plus(w).toString(),fields:{...h,...v}}}async getUnclaimedFees(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,[s,a,u,l]=await Promise.all([this.coin.getMetadata(n.types[0]),this.coin.getMetadata(n.types[1]),i(n.types[0]),i(n.types[1])]),h=$b(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),w=this.math.scaleDown(h.feeOwedA,s.decimals),v=this.math.scaleDown(h.feeOwedB,a.decimals);function T(P,O){return new F(1e6).mul(F.pow(10,O)).lt(P)}T(w,s.decimals)&&(w="0",h.feeOwedA="0"),T(v,a.decimals)&&(v="0",h.feeOwedB="0");let I=u===void 0?new F(0):new F(u).mul(w),x=l===void 0?new F(0):new F(l).mul(v);return{unclaimedFees:I.plus(x),scaledFeeOwedA:w,scaledFeeOwedB:v,...h}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=zb(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),a=[...s],u=n.reward_infos.map(v=>this.coin.formatCoinType(v.fields.vault_coin_type)),l=await Promise.all([...n.reward_infos.map((v,T)=>this.coin.getMetadata(u[T]))]),h=await Promise.all(n.reward_infos.map((v,T)=>i(u[T])));l.forEach((v,T)=>{a[T]=this.math.scaleDown(a[T],v.decimals)});let w=new F(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(w=w.plus(new F(I).mul(a[T])),!1):(w=w.plus(1),!0)}),{unclaimedRewards:w,collectRewards:s,scaledCollectRewards:a}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return Au(e,"nft"),e})}},Gb=class extends Ao{isSUI(t){return(0,Zh.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,n){if(n.eq(0))return[];let i=[],r=[],o=new F(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),i.push(...s.data);while(s.hasNextPage);i.sort((a,u)=>Number(u.balance)-Number(a.balance));for(let a of i)if(r.push(a.coinObjectId),o=o.add(a.balance),o.gte(n))break;return r}convertTradeCoins(t,e,n,i){return this.isSUI(n)?[t.splitCoins(t.gas,[t.pure(i.toNumber())])[0]]:e.map(r=>t.object(r))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let i=t.replace(/^0x/i,"");return i=i.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&i.length<64&&t!=="2::sui:SUI"?"0".repeat(64-i.length):"")+i}},Wb=60*1e3,Ys=100,Hb=class extends Ao{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new F(t.amountA),a=new F(t.amountB),u=await this.contract.getConfig(),l=await Promise.all(t.routes.map(async x=>{let P=await this.pool.getPoolTypeArguments(x.pool),[O,E]=await Promise.all([this.coin.getMetadata(P[0]),this.coin.getMetadata(P[1])]);return{...x,coinA:O,coinB:E,typeArguments:P}})),h=await this.coin.selectTradeCoins(i,e,s),{functionName:w,typeArguments:v}=this.getFunctionNameAndTypeArguments(l.map(({typeArguments:x})=>x),e,n),T=l.map(({nextTickIndex:x,coinA:P,coinB:O,a2b:E})=>{let B=this.math.tickIndexToPrice(x,P.decimals,O.decimals);return this.sqrtPriceWithSlippage(B,o,E,P.decimals,O.decimals)}),I=t.txb||new ea.TransactionBlock;return I.moveCall({target:`${u.PackageId}::swap_router::${w}`,typeArguments:v,arguments:[...l.map(({pool:x})=>I.object(x)),I.makeMoveVec({objects:this.coin.convertTradeCoins(I,h,e,s)}),I.pure((r?s:a).toFixed(0),"u64"),I.pure(this.amountOutWithSlippage(r?a:s,o,r),"u64"),...T.map(x=>I.pure(x,"u128")),I.pure(r,"bool"),I.pure(i,"address"),I.pure(Date.now()+Wb*3,"u64"),I.object(ta.SUI_CLOCK_OBJECT_ID),I.object(u.Versioned)]}),I}async computeSwapResult(t){let{pools:e,amountSpecified:n,amountSpecifiedIsInput:i,address:r,tickStep:o}=t,s=await this.contract.getConfig(),a=e.map(w=>w.pool),u=await So(this.provider,a,{showContent:!0}),l=new ea.TransactionBlock;u.map(async w=>{let v=Pn(w),T=e.find(E=>E.pool===v.id.id),I=this.math.bitsToNumber(v.tick_current_index.fields.bits),x=I-v.tick_spacing*(o||Ys),P=I+v.tick_spacing*(o||Ys);x=x<Js?Js:x,P=P>Xs?Xs:P;let O=this.pool.parsePoolType(na(w));l.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:O,arguments:[l.object(v.id.id),l.pure(T.a2b,"bool"),l.pure(new F(n).toFixed(0),"u128"),l.pure(i,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(T.a2b?x:P).toString(),"u128"),l.object(ta.SUI_CLOCK_OBJECT_ID),l.object(s.Versioned)]})});let h=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:r});if(h.error)throw new Error(h.error);return h.events.map(w=>w.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:n,address:i,tickStep:r}=t,o=await this.contract.getConfig(),s=e.map(h=>h.pool),a=await So(this.provider,Array.from(new Set(s)),{showContent:!0}),u=new ea.TransactionBlock;e.forEach(async h=>{let w=a.find(O=>ia(O)===h.pool),v=Pn(w),T=this.math.bitsToNumber(v.tick_current_index.fields.bits),I=T-v.tick_spacing*(r||Ys),x=T+v.tick_spacing*(r||Ys);I=I<Js?Js:I,x=x>Xs?Xs:x;let P=this.pool.parsePoolType(na(w));u.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:P,arguments:[u.object(v.id.id),u.pure(h.a2b,"bool"),u.pure(new F(h.amountSpecified).toFixed(0),"u128"),u.pure(n,"bool"),u.pure(this.math.tickIndexToSqrtPriceX64(h.a2b?I:x).toString(),"u128"),u.object(ta.SUI_CLOCK_OBJECT_ID),u.object(o.Versioned)]})});let l=await this.provider.devInspectTransactionBlock({transactionBlock:u,sender:i});if(l.error)throw new Error(l.error);return l.events.map(h=>h.parsedJson)}getFunctionNameAndTypeArguments(t,e,n){let i=[],r=["swap"];if(t.length===1)i=t[0],e===i[0]?r.push("a","b"):r.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(r.push("a","b"),i.push(o[0],o[2],o[1])):(r.push("b","a"),i.push(o[1],o[2],o[0])),i.push(s[2],n),n===s[0]?r.push("c","b"):r.push("b","c")}return{functionName:r.join("_"),typeArguments:i}}amountOutWithSlippage(t,e,n){if(n){let r=new F(100).minus(e).div(100);return new F(t).mul(r).toFixed(0)}let i=new F(100).plus(e).div(100);return new F(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new F(t).mul(n?new F(100).minus(e).div(100):new F(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,i,r);return s.lt(new xu.BN(Su))?Su:s.gt(new xu.BN(Cu))?Cu:s.toString()}},Lt=class{constructor(t,e){this.network=t,On(this,"pool"),On(this,"contract"),On(this,"math",new qb),On(this,"account",new Eb),On(this,"coin"),On(this,"nft"),On(this,"trade"),On(this,"provider"),this.provider=e?e instanceof Ri.SuiClient?e:new Ri.SuiClient(e):new Ri.SuiClient({url:t==="mainnet"?(0,Ri.getFullnodeUrl)("mainnet"):(0,Ri.getFullnodeUrl)("testnet")}),this.contract=new Rb(this),this.pool=new Lb(this),this.nft=new Vb(this),this.coin=new Gb(this),this.trade=new Hb(this)}};var Zb=Object.defineProperty,vm=(t,e)=>{for(var n in e)Zb(t,n,{get:e[n],enumerable:!0})},ve=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Cm.default)(this.data))}},Ku={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"},Ht={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Dn=new cr(Ku),Xb=async(t,e,n)=>(console.log("getAddLiquidityTxb suiClient: ",n),console.log("getAddLiquidityTxb txbParams: ",t),Dn.senderAddress=e.address,await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Jb=async(t,e,n)=>(console.log("getIncreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,console.log("getIncreaseLiquidityTxb txbParams: ",t),await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Yb=async(t,e,n)=>(console.log("getRemoveLiquidityTxb txbParams: ",t),console.log("getRemoveLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.closePositionTransactionPayload(t)),Qb=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb txbParams: ",t),console.log("getDecreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.removeLiquidityTransactionPayload(t)),ev=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb txbParams: ",t),console.log("getClaimFeeAndMiningTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Rewarder.collectRewarderTransactionPayload(t)),tv=class Sm extends ve{constructor(e){super(e),this.data=e}txType=Tm.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("AddLiquidityIntention this.data: ",this.data),console.log("AddLiquidityIntention txbParams: ",r);let o=await Xb(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Sm(e)}},nv=class xm extends ve{constructor(e){super(e),this.data=e}txType=Am.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("ClaimFeeAndMiningIntention this.data: ",this.data),console.log("ClaimFeeAndMiningIntention txbParams: ",r);let o=await ev(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new xm(e)}},iv=class Om extends ve{constructor(e){super(e),this.data=e}txType=Im.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("DecreaseLiquidityIntention this.data: ",this.data),console.log("DecreaseLiquidityIntention txbParams: ",r);let o=await Qb(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Om(e)}},xt=new cr(Ku),rv=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.openPositionAddLiquidityStakePaylod(t)),ov=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.addLiquidityFixCoinPayload(t)),sv=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),av=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),cv=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.claimFeeAndClmmReward(t)),uv=async(t,e,n)=>{console.log("getFarmingHarvest account: ",e),console.log("getFarmingHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt);return console.log("getFarmingHarvest txbParams: ",t),await i.Farms.harvestPayload(t)},lv=async(t,e,n)=>{console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt),r=Object.values(t);return console.log("getFarmingBatchHarvest params: ",r),await i.Farms.batchHarvestPayload(r)},dv=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.depositPayload(t)),fv=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.withdrawPayload(t)),hv=class Dm extends ve{constructor(e){super(e),this.data=e}txType=Pm.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingAddLiquidityIntention this.data: ",this.data),console.log("FarmingAddLiquidityIntention txbParams: ",r);let o=await rv(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new Dm(e)}},mv=class Mm extends ve{constructor(e){super(e),this.data=e}txType=Em.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingBatchHarvestIntention this.data: ",this.data),console.log("FarmingBatchHarvestIntention txbParams: ",r);let o=await lv(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Mm(e)}},pv=class jm extends ve{constructor(e){super(e),this.data=e}txType=Bm.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingClaimFeeAndRewardIntention this.data: ",this.data),console.log("FarmingClaimFeeAndRewardIntention txbParams: ",r);let o=await cv(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new jm(e)}},gv=class Nm extends ve{constructor(e){super(e),this.data=e}txType=Fm.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingDecreaseLiquidityIntention this.data: ",this.data),console.log("FarmingDecreaseLiquidityIntention txbParams: ",r);let o=await sv(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Nm(e)}},_v=class qm extends ve{constructor(e){super(e),this.data=e}txType=Rm.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingHarvestIntention this.data: ",this.data),console.log("FarmingHarvestIntention txbParams: ",r);let o=await uv(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new qm(e)}},yv=class $m extends ve{constructor(e){super(e),this.data=e}txType=Lm.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingIncreaseLiquidityIntention this.data: ",this.data),console.log("FarmingIncreaseLiquidityIntention txbParams: ",r);let o=await ov(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new $m(e)}},wv=class Km extends ve{constructor(e){super(e),this.data=e}txType=Um.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingRemoveLiquidityIntention this.data: ",this.data),console.log("FarmingRemoveLiquidityIntention txbParams: ",r);let o=await av(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Km(e)}},bv=class Vm extends ve{constructor(e){super(e),this.data=e}txType=zm.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingStakeIntention this.data: ",this.data),console.log("FarmingStakeIntention txbParams: ",r);let o=await dv(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new Vm(e)}},vv=class Wm extends ve{constructor(e){super(e),this.data=e}txType=Gm.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingUnstakeIntention this.data: ",this.data),console.log("FarmingUnstakeIntention txbParams: ",r);let o=await fv(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new Wm(e)}},kv=class Zm extends ve{constructor(e){super(e),this.data=e}txType=Hm.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("IncreaseLiquidityIntention this.data: ",this.data),console.log("IncreaseLiquidityIntention txbParams: ",r);let o=await Jb(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Zm(e)}},Tv=class Jm extends ve{constructor(e){super(e),this.data=e}txType=Xm.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("RemoveLiquidityIntention this.data: ",this.data),console.log("RemoveLiquidityIntention txbParams: ",r);let o=await Yb(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Jm(e)}},En=new cr(Ku),Cv=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.convertPayload(t)),Sv=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemLockPayload(t)),Av=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemDividendV2Payload(t.venft_id,t.bonus_types,t.xTokenType)),xv=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.cancelRedeemPayload(t)),Iv=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemPayload(t)),Ov=class Qm extends ve{constructor(e){super(e),this.data=e}txType=Ym.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusCancelIntention this.data: ",this.data),console.log("XcetusCancelIntention txbParams: ",r);let o=await xv(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Qm(e)}},Pv=class tp extends ve{constructor(e){super(e),this.data=e}txType=ep.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusClaimingStakeRewardsIntention this.data: ",this.data),console.log("XcetusClaimingStakeRewardsIntention txbParams: ",r);let o=await Av(r,n,i);return console.log("XcetusClaimingStakeRewardsIntention build txb: ",o),o}static fromData(e){return new tp(e)}},Dv=class ip extends ve{constructor(e){super(e),this.data=e}txType=np.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusConvertIntention this.data: ",this.data),console.log("XcetusConvertIntention txbParams: ",r);let o=await Cv(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new ip(e)}},Ev=class op extends ve{constructor(e){super(e),this.data=e}txType=rp.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemIntention this.data: ",this.data),console.log("XcetusRedeemIntention txbParams: ",r);let o=await Iv(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new op(e)}},Mv=class ap extends ve{constructor(e){super(e),this.data=e}txType=sp.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemLockIntention this.data: ",this.data),console.log("XcetusRedeemLockIntention txbParams: ",r);let o=await Sv(r,n,i);return console.log("XcetusRedeemLockIntention build txb: ",o),o}static fromData(e){return new ap(e)}},Bv=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:km.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let i;switch(t.txSubType){case"OpenAndAddLiquidity":i=tv.fromData(t.intentionData);break;case"IncreaseLiquidity":i=kv.fromData(t.intentionData);break;case"DecreaseLiquidity":i=iv.fromData(t.intentionData);break;case"RemoveLiquidity":i=Tv.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=nv.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=hv.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=yv.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=gv.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=wv.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=pv.fromData(t.intentionData);break;case"FarmingHarvest":i=_v.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=mv.fromData(t.intentionData);break;case"FarmingStake":i=bv.fromData(t.intentionData);break;case"FarmingUnstake":i=vv.fromData(t.intentionData);break;case"xCETUSConvert":i=Dv.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=Mv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=Pv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=Ov.fromData(t.intentionData);break;case"xCETUSRedeem":i=Ev.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",i),i.build({suiClient:e,account:n})}},up={};vm(up,{contractId:()=>fp,default:()=>jv,feeObjId:()=>pp,roleObjId:()=>hp,status:()=>dp,transaction:()=>lp,upgradeCapObjId:()=>gp,vaultObjId:()=>mp});var lp="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",dp="success",fp="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",hp="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",mp="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",pp="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",gp="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",jv={transaction:lp,status:dp,contractId:fp,roleObjId:hp,vaultObjId:mp,feeObjId:pp,upgradeCapObjId:gp},_p={};vm(_p,{contractId:()=>bp,default:()=>Fv,feeObjId:()=>Tp,roleObjId:()=>vp,status:()=>wp,transaction:()=>yp,upgradeCapObjId:()=>Cp,vaultObjId:()=>kp});var yp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",wp="success",bp="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",vp="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",kp="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Tp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Cp="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fv={transaction:yp,status:wp,contractId:bp,roleObjId:vp,vaultObjId:kp,feeObjId:Tp,upgradeCapObjId:Cp},Nv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Rv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",qv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Lv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$v="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Uv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Kv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",zv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Xh=up,Jh=_p,Vv=new Map([["dev",{env:"dev",rpc:{url:Nv},backend:{url:$v},contract:Xh}],["stg",{env:"stg",rpc:{url:Rv},backend:{url:Uv},contract:Xh}],["prev",{env:"prev",rpc:{url:qv},backend:{url:Kv},contract:Jh}],["prod",{env:"prod",rpc:{url:Lv},backend:{url:zv},contract:Jh}]]);function Gv(t,e){let n=Vv.get(t);if(!n)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(n.rpc=e.rpc),e&&e.backend&&(n.backend=e.backend),e&&e.contract&&(n.contract=e.contract),n}var nn=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:i,context:r}=n;i?super(`[MPay] ${e}: ${i}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}},Wv=class extends nn{constructor(){super(11,"Backend is not specified")}},Hv=class extends nn{constructor(){super(1,"Wallet not connected")}},Ou=class extends nn{constructor(t,e){super(10,t,{context:e})}},Zv=class $i{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof zn.AxiosError)throw new Ou(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Ou(e.data.code)}throw new Ou(e.status.toString())}async getIncomingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return $i.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{sender:e,...n});return $i.parseResponseData(i)}async getStreamHistory(e){let n=await zn.default.post(`${this.apiURL}/stream-events`,e),i=$i.parseResponseData(n);return i.data.forEach(r=>{let o=r;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}),i}async getAllCoinTypes(e){let n=await zn.default.post(`${this.apiURL}/stream-info`,{address:e});return $i.parseResponseData(n)}async getAllRecipients(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return $i.parseResponseData(i)}async getAllSenders(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return $i.parseResponseData(i)}},Ap=class xp{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Sp.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Zv(e.backend.url))}static new(e,n){let i=Gv(e,n);return new xp(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Wv;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 Hv;return this.signer}async walletAddress(){return this.wallet.address()}},Yh=50n,Pu=10000n,Xv=25n,Qh=100000000n,qi=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},em=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ca=class Ip{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(n,i){if(i in n)return Reflect.get(n,i);let r=s=>new Ip(n.result[s]);if(i===Symbol.iterator)return function*(){let s=0;for(;;)yield r(s),s++};if(typeof i=="symbol")return;let o=parseInt(i,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}},tm=class extends nn{constructor(t,e){super(3,t,{context:e})}},Jv=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 n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="address")throw new tm("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,Op.normalizeSuiAddress)(Mu.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new tm("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Mu.Buffer.from(n).readBigInt64LE()}},tn=class extends nn{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},Pp={groupId:"string",name:"string"},Yv=64;function Qv(t){return Dp(t),zu.bcs.ser(Pp,t).toString("base64")}function Bu(t){let e=zu.bcs.de(Pp,t,"base64");return Dp(e),e}function Dp(t){if(!nm(t.name))throw new tn("Invalid metadata: Name contains unknown character");if(!nm(t.groupId))throw new tn("Invalid metadata: Group ID contains unknown character");if(t.name.length>Yv)throw new tn("Invalid metadata: Name exceed max length 64")}function nm(t){return/^[\x00-\x7F]+$/.test(t)}function Ep(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}function Pr(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}var Mp="txn.gas";function e1(){return yf()}var ju=class Bp{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:Qv({name:e.name,groupId:e1()}),coinType:(0,Po.normalizeStructTag)(e.coinType),recipients:e.recipients.map(n=>({address:n.address,cliffAmount:n.cliffAmount,amountPerEpoch:n.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let n=new Eu.TransactionBlock,i=this.calculateFeesInternal(e),r=this.getCreateStreamCoinRequests(e,i),o=await this.wallet.requestCoins(r),s=await this.addMergeCoins(n,o[0]),a;r.length>1?a=await this.addMergeCoins(n,o[1]):a=s;for(let u=0;u<e.recipients.length;u++){let l=e.recipients[u],h=this.amountForRecipient(l,e.numberEpoch),w=this.getStreamFeeLocal(h),[v]=n.splitCoins(s,[n.pure(h+w,"u64")]),[T]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new ca(v),flatFeeCoin:new ca(T),metadata:e.metadata,recipient:l.address,timeStart:e.startTime,cliff:l.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return n}calculateCreateStreamFees(e){let n=Bp.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Yh,denominator:Pu},claimFeePercent:{numerator:Xv,denominator:Pu},flatFeePerStream:Qh}}async addMergeCoins(e,n){let i;return n.mergedCoins&&n.mergedCoins.length?(e.mergeCoins(e.object(n.primaryCoin),n.mergedCoins.map(r=>e.object(r))),i=e.object(n.primaryCoin)):n.primaryCoin===Mp?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return Ep(i,Po.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Po.SUI_TYPE_ARG,amount:n.flatFeeAmount}]}calculateFeesInternal(e){let n=e.recipients.reduce((i,r)=>{let o=this.amountForRecipient(r,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:i.totalAmount+o,streamFeeAmount:i.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...n}}amountForRecipient(e,n){return BigInt(e.amountPerEpoch)*BigInt(n)+BigInt(e.cliffAmount)}get flatSuiFee(){return Qh}getStreamFeeLocal(e){return e*Yh/Pu}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new Eu.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new Jv(i).getU64()}get wallet(){return this.globals.wallet}},t1="0x0000000000000000000000000000000000000000000000000000000000000006",jp=class{constructor(t,e,n){this.moduleName=t,this.config=e,this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Fu.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof em?i.moveArgs(t):i instanceof qi?i.moveArg(t):i instanceof ca?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(Fu.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof em?r.moveArgs(t):r instanceof qi?r.moveArg(t):r instanceof ca?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new qi(t):t}vaultObject(){return new qi(this.config.vaultObjId)}roleObject(){return new qi(this.config.roleObjId)}feeObject(){return new qi(this.config.feeObjId)}clockObject(){return new qi(t1)}},Fp=class di extends jp{constructor(e,n){super(di.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_flat_fee,arguments:[i,r,n],typeArgs:[]})}setClaimFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:di.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:di.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:di.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},la=class jt extends jp{constructor(e,n){super(jt.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.feeObject(),r=this.vaultObject(),o=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),a=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.create_stream,arguments:[i,r,o,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,a],typeArgs:[n.coinType]})}setAutoClaim(e,n){let i=this.makeObject(n.streamId);return this.addContractCall(e,{method:jt.MethodName.set_auto_claim,arguments:[i,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.cancel_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.claim_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let i=this.makeObject(n.streamId),r=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream_by_proxy}`}},Np=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Fp(e,t),this.streamContract=new la(e,t)}feeContract;streamContract;async createStreams(t){let e=ju.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new ju(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new Io.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},kn=class extends nn{constructor(t,e={}){super(0,t,e)}};async function n1(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var i1=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)}},Rp=class{constructor(t){this.requester=t,this.pager=new i1(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]}},r1=class extends nn{constructor(t,e,n){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:n}}),this.coinType=t,this.requestAmount=e,this.gotAmount=n}},o1=25;async function s1(t,e,n,i="0x2::sui::SUI",r=o1){let o=new a1(t,e,i,r),s=BigInt(0),a=[];for(;await o.hasNext()&&s<n;){let u=await o.next();u&&(a.push(u),s+=BigInt(u.balance))}if(s<n)throw new r1(i,n,s);return a}var a1=class extends Rp{constructor(t,e,n,i){super(new c1(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},c1=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new kn("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}}},u1=class extends nn{constructor(){super(7,"Connected wallet is not creator")}},im=class extends nn{constructor(){super(8,"Connected wallet is not recipient")}},rm=class extends nn{constructor(t,e){super(6,t,{context:e})}},l1=class extends nn{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},d1=(1n<<64n)-1n,ua=1e3;function om(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return be.fromMillis(n*ua)}function sm(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return Pe.fromMillis(n*ua)}var Vu=class fi{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new la(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await fi.fetchStreamData(e,n);return new fi(e,n,i)}static fromObjectData(e,n,i){let r=fi.parseRawStreamData(n,i);return new fi(e,n,r)}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 fi.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new kn("Object Id does not align");this.rawData=fi.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 u1;let e=new Oo.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new im;let e=new Oo.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 im;let n=new Oo.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new Oo.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,Eo.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 sm(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Bu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Bu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return om(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return sm(n)}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:om((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===d1?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=be.now().toMillis(),n=this.timeStart.toMillis();if(e<n)return-1n;let i=Math.floor((e-n)/Number(this.rawData.config.epochInterval));return BigInt(i)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(i)}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,n){let i=await e.suiClient.getObject({id:n,options:{showContent:!0,showType:!0}});return fi.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new l1(e):new rm(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new rm("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Eo.parseStructTag)(i.type),o=(0,Eo.normalizeStructTag)(r[0]),s=i.fields,a=s.config.fields,u=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(a.amount_per_epoch),cancelable:a.cancelable,cliff:BigInt(a.cliff),creator:a.creator,epochInterval:BigInt(a.epoch_interval),metadata:a.metadata,recipient:a.recipient,timeStart:BigInt(a.time_start),totalEpoch:BigInt(a.total_epoch)},status:{status:u.status,epochCanceled:BigInt(u.epoch_canceled),epochClaimed:BigInt(u.epoch_claimed)}}}},f1=class extends nn{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},h1=1e3,m1=class{constructor(t){this.globals=t,this.coinMetaHelper=new p1(t.suiClient),this.createStreamHelper=new Np(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new f1(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 tn("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,i=(t.totalAmount-n)/t.steps,r={realTotalAmount:i*t.steps+n,cliffAmount:n,amountPerStep:i};return this.validateStreamAmount(r,t.totalAmount),r}calculateTimelineByInterval(t){if(t.steps===0n)throw new tn("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new tn("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(Pe.fromMillis(Number(e*t.steps))),i={timeStart:t.timeStart,timeEnd:n,interval:Pe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(i),i}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),i=await this.getCoinMeta(e);return{...n,coinType:(0,Mr.normalizeStructTag)(n.coinType),coinMeta:i}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(i=>this.getCoinMeta(i.coinType)));return e.map((i,r)=>({...i,coinType:(0,Mr.normalizeStructTag)(i.coinType),coinMeta:n[r]}))}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 tn("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new tn("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<h1)throw new tn("Interval shall be at least 1 second","interval",t.interval)}},p1=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Mr.normalizeStructTag)(t||Mr.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},Du=class extends nn{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}},g1=25;async function am(t,e,n){let i=new qp(e),r=new Lp(t,i,n);return await n1(r)}var qp=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]}},Lp=class extends Rp{constructor(t,e,n){super(new _1(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},_1=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||g1,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&t.push(i)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:i}=this;n=e.filter(r=>i?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}},y1=class ra{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new Du("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new tn("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await am(e.suiClient,n);return i.forEach(r=>{if(!r)throw new kn("stream group object data undefined")}),ra.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await ra.parseGroupStreams(e,n,i);return new ra(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{w1(i,o)||(r=!1)}),r}async refresh(){let e=await am(this.globals.suiClient,this.streams.map(n=>n.streamId));this.streams.forEach((n,i)=>{n.refreshWithData(e[i])})}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,n)=>e+n.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,n)=>e+n.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,n)=>n.nextReleaseAmount===null?e:e+n.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,n)=>e+n.totalAmount,0n),streamed:this.streams.reduce((e,n)=>e+n.streamedAmount,0n),claimed:this.streams.reduce((e,n)=>e+n.claimedAmount,0n),claimable:this.streams.reduce((e,n)=>e+n.claimable,0n),canceled:this.streams.reduce((e,n)=>e+n.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,n,i){let r=i.map((o,s)=>Vu.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new Du("Not same group ID");if(!this.checkStreamGroup(r))throw new Du("Not same stream settings");return r}};function w1(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 cm=class Nu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await um.newIncoming(e);return new Nu(n,e.pageSize)}static async newOutgoing(e){let n=await um.newOutgoing(e);return new Nu(n,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}},um=class Ru{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await lm.newIncomingQuery(e);return new Ru(n)}static async newOutgoing(e){let n=await lm.newOutgoingQuery(e);return new Ru(n)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let n=await this.requester.doNextRequest();if(n===null)throw new kn("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new kn("No more results");return e}},lm=class qu{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new qp(i.flat().map(s=>s.streamId));this.objectIter=new Lp(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=C1(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,gi.normalizeSuiAddress)(s.recipient)===(0,gi.normalizeSuiAddress)(i)),o=dm(r);return new qu(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=S1(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=dm(r);return new qu(e.globals,i,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let n=await k1(this.globals,e[0].streamId,this.objectIter);return this.current++,$p(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await T1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,v1(n,this.query)?n:this.doNextRequest()}throw new kn("Stream group with no stream")}};function dm(t){let e=new Map;return t.forEach(n=>{let i=e.get(n.groupId);i?(i.push(n),e.set(n.groupId,i)):e.set(n.groupId,[n])}),Array.from(e.values()).sort((n,i)=>be.fromISO(i[0].createDate).toMillis()-be.fromISO(n[0].createDate).toMillis())}function $p(t,e){if(e===void 0)return!0;let n=b1(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let i=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return n&&i}return n}function b1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function v1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{$p(i,e)&&(n=!0)}),n}async function k1(t,e,n){let i=await Up(n,e);return Vu.fromObjectData(t,e,i)}async function T1(t,e,n){let i=[];for(;i.length<e.length;){let r=await Up(n,e[i.length]);i.push(r)}return y1.newFromObjectResponse(t,e,i)}async function Up(t,e){if(!await t.hasNext())throw new kn("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new kn("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new kn("stream id not aligned");return n}function C1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),sender:zp(t?.sender)}}function S1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),recipient:zp(t?.recipient)}}function Gu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=Gu(n);return!e||e===i?i:"all"},void 0):A1(t)}function A1(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new tn("Unknown stream filtered status")}}function Kp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeStructTag)(e)):void 0:(0,gi.normalizeStructTag)(t)}function zp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeSuiAddress)(e)):void 0:(0,gi.normalizeSuiAddress)(t)}var x1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},I1=class{constructor(t){this.account=t}async address(){return this.account.address}},O1=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(Ep(t.coinType,Ki.SUI_TYPE_ARG))return{primaryCoin:Mp};if(t.amount<=0)throw new tn("Invalid coin request","coinAmount",t.amount);let e=await s1(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new kn("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},P1=class{globals;helper;constructor(t,e){this.globals=Ap.new(t,e),this.helper=new m1(this.globals)}connectSingleWallet(t){let e=new O1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new x1(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return Vu.new(this.globals,t)}async getIncomingStreams(t,e=10){return cm.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return cm.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,Ki.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new Np(this.globals)}},D1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Vp.default)(this.data))}},Mo=class extends D1{application="mpay";getClient(t,e){let n=new P1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new I1(e)),n}},fm=class extends Mo{constructor(t){super(t),this.data=t}txType=cp.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},hm=class extends Mo{constructor(t){super(t),this.data=t}txType=Gp.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},mm=class extends Mo{constructor(t){super(t),this.data=t}txType=Wp.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},pm=class extends Mo{constructor(t){super(t),this.data=t}txType=Hp.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Zp=class oa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return oa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return oa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,hi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return oa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}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,hi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,hi.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,hi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,hi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,hi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},E1=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"&&Pr(e.target,this.contract.createStreamTarget));if(t.length===0)throw new kn("No create stream transactions");return t.map(e=>new Zp(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Bu(e),r=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),a=t.decodeInputU64(8),u=t.decodeInputU64(9),l=t.decodeInputU64(10),h=t.decodeInputBool(11),w=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:u,amountPerEpoch:l,cancelable:h,coinType:w}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new tn("Stream group not have common info");let e=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 la(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Fp(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ju(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]}},M1=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new la(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"&&Pr(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new E1(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 Zp(t,this.txb)}},gm=class extends Mo{constructor(t){super(t),this.data=t}txType=Xp.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},B1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=Ap.new(e==="sui:mainnet"?"prod":"dev"),r=new M1(i,n).decode(),o;switch(r.type){case"CreateStream":o=new pm(r.info);break;case"SetAutoClaim":o=new gm({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new mm({streamId:r.streamId});break;case"ClaimByProxy":o=new hm({streamId:r.streamId});break;case"Cancel":o=new fm({streamId:r.streamId});break;default:throw new Error(`Unknown transaction type: ${r}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new pm(e);break;case"Claim":n=new mm(e);break;case"ClaimByProxy":n=new hm(e);break;case"SetAutoClaim":n=new gm(e);break;case"Cancel":n=new fm(e);break;default:throw new Error("not implemented")}return n.build({...t})}},j1=class Yp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Jp.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Yp(e)}},F1=class eg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Qp.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new eg(e)}},N1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=ng.TransactionBlock.from(this.data.content);if(!(0,tg.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new ig(e)}},R1=class{application;constructor(){this.application=Er.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case Er.TransactionSubTypes.assets.coin.send:i=j1.fromData(t.intentionData);break;case Er.TransactionSubTypes.assets.object.send:i=F1.fromData(t.intentionData);break;case Er.TransactionSubTypes.others.plain:i=N1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},q1={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"}}},ye=q1,L1=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(`${ye.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ye.pool).find(n=>n.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===`${ye.ProtocolPackage}::incentive_v2::claim_reward`){let n=new _m(e,this.txb),i=n.decodeInputU8(4),r=n.decodeInputU8(5),o=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(i),a=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:a,assetId:i,poolId:o})}}),console.log("decode claims",t),{txType:Dr.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ye.ProtocolPackage));return new _m(t,this.txb)}},_m=class sa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return sa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return sa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,mi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return sa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}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,mi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,mi.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,mi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,mi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,mi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function ym(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function $1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function U1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function wm(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function K1(t,e,n,i,r){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ye.IncentiveV2),t.object(n),t.object(ye.StorageId),t.pure(e),t.pure(i)],typeArguments:r}),t}var z1=class sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new og.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;K1(n,r,o,s,a)}),n}static fromData(e){return new sg(e)}},V1=class cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new ag.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return U1(i,r,n)}static fromData(e){return new cg(e)}};async function lg(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var G1=class dg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new ug.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return ym(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await lg(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return ym(s,a,s.object(l),o)}static fromData(e){return new dg(e)}},W1=class hg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new fg.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return wm(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await lg(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return wm(s,a,s.object(l),o)}static fromData(e){return new hg(e)}},H1=class pg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new mg.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return $1(i,r,n)}static fromData(e){return new pg(e)}},Z1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new L1(e).decode();return{txType:rg.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=G1.fromData(t.intentionData);break;case"EntryBorrow":i=V1.fromData(t.intentionData);break;case"EntryRepay":i=W1.fromData(t.intentionData);break;case"EntryWithdraw":i=H1.fromData(t.intentionData);break;case"ClaimReward":i=z1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},X1="msafe-plain-tx",J1=da.TransactionSubTypes.others.plain,Y1=class{application;constructor(){this.application=X1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:da.TransactionType.Other,txSubType:J1,intentionData:{content:(0,fa.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=gg.TransactionBlock.from((0,fa.fromHEX)(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(r.effects.status.status!=="success")throw new Error(r.effects.status.error);return i}},Q1=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}},Li={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},ek=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(t){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeLiquidityTransaction())return this.decodeCollectFeeLiquidity();if(this.isCollectRewardLTransaction())return this.decodeCollectRewardLiquidity();if(this.isBurnTransaction())return this.decodeBurnLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect`)}isCollectRewardLTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::burn`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),i=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),o=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),a=this.helper.decodeInputBool(7);return{txType:Ui.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:o?-r:r,tickUpper:a?-s:s}}}decodeIncreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),i=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6);return{txType:Ui.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:5,address:t,amountA:i,amountB:r,nft:n}}}decodeDecreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),o=this.helper.decodeInputU64(5);return{txType:Ui.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,decreaseLiquidity:i,nft:n,amountA:r,amountB:o,slippage:3,address:t}}}decodeCollectFeeLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4);return{txType:Ui.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:i,collectAmountB:r,nft:e}}}decodeCollectRewardLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),i=this.collectRewardHelper.map(r=>r.decodeInputU64(5));return{txType:Ui.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:i,nft:e}}}decodeBurnLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:Ui.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new bm(t,this.txb)}get collectRewardHelper(){console.log(this.transactions,"this.transactions");let t=this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${Li.PackageId}::position_manager::collect_reward`);return console.log(t,this.txb,"this.txb"),t.map(e=>new bm(e,this.txb))}},bm=class aa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return aa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return aa.getOwnedObjectId(n)}decodeInputU128(e){let n=this.decodePureArg(e,"u128");return Number(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU32(e){let n=this.decodePureArg(e,"u32");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,pi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return aa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}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,pi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,pi.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,pi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,pi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,pi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},tk=class yg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:u,tickUpper:l,txb:h}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,txb:h})}static fromData(e){return new yg(e)}},nk=class wg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,nft:r,txb:o}=this.data;return n.nft.burn({pool:i,nft:r,txb:o})}static fromData(e){return new wg(e)}},ik=class bg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,txb:u}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,txb:u})}static fromData(e){return new bg(e)}},rk=class vg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,txb:a}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,txb:a})}static fromData(e){return new vg(e)}},ok=class kg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{fee:i,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,amountA:w,amountB:v,txb:T}=this.data;return n.pool.createPool({fee:i,amountA:w,amountB:v,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,txb:T})}static fromData(e){return new kg(e)}},sk=class Tg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,txb:h}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,txb:h})}static fromData(e){return new Tg(e)}},ak=class Cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,txb:l}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,txb:l})}static fromData(e){return new Cg(e)}},ck=class Sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:l,nft:u,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T})}static fromData(e){return new Sg(e)}},uk=class{application="turbos";async deserialize(t){let{transactionBlock:e,account:n}=t,i=new ek(e).decode(n.address);return{txType:_g.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:i}=t,r;switch(t.txSubType){case"CreatePool":r=ok.fromData(t.intentionData);break;case"AddLiquidity":r=tk.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ak.fromData(t.intentionData);break;case"DecreaseLiquidity":r=sk.fromData(t.intentionData);break;case"RemoveLiquidity":r=ck.fromData(t.intentionData);break;case"CollectFee":r=ik.fromData(t.intentionData);break;case"CollectReward":r=rk.fromData(t.intentionData);break;case"Burn":r=nk.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},ha=new Q1([new R1,new Z1,new B1,new Y1,new Bv,new uk]);var Ae=require("@msafe/sui3-utils"),tl=require("@mysten/sui.js/transactions"),ba=require("@mysten/sui.js/utils");var Ag=require("@mysten/sui.js/transactions"),lk=1000n,dk=120n,fk=100n,hk={multiplier:{numerator:dk,denominator:fk}};var ma=class{constructor(e){this.globals=e}async simulate(e,n=hk){let i=this.copyTransactionBlock(e.txb),{suiClient:r}=this.globals,o=await this.getGasPrice(n);i.setGasPrice(o);let s=await r.devInspectTransactionBlock({transactionBlock:i,sender:e.sender}),{gasUsed:a}=s.effects,u=this.toGasBudget(a,o),l=s.effects.status.status==="success",h;return l||(h=s.effects.status.error),{success:l,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:a,gasBudget:u,simulationError:h}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let n=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(n,e)}toGasBudget(e,n){let{computationCost:i,storageCost:r}=e,o=lk*n,s=BigInt(i)+o,a=s+BigInt(r);return a>s?a:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,n){if(this.isFixedValue(n))return n.fixedVal;if(this.isMultiplier(n)){let{multiplier:i}=n;return e*i.numerator/i.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ag.TransactionBlock.from(e.serialize())}};var Wu=require("buffer");function pa(t){return Wu.Buffer.from(t,"utf-8")}function mk(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ga(t){return Uint8Array.from(Wu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ya=require("@mysten/sui.js/verify");var _i=require("@mysten/sui.js/utils");var _a=require("@mysten/sui.js/utils"),Bo=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,_a.normalizeStructTag)(e);if(this._coinMetaReg.has(n))return this._coinMetaReg.get(n);let i=await this.queryCoinMeta(n);return i&&this._coinMetaReg.set(n,i),i}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Hu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,jo=class t{static isCoin(e){return e?(0,_a.normalizeStructTag)(e).match(Hu)!=null:!1}static getCoinType(e){let[,n]=(0,_a.normalizeStructTag)(e).match(Hu)??[];return n||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:n}=e.content?.fields;if(n!==void 0)return BigInt(n)}};var Vn=class{static normalizeSuiAddress(e){return(0,_i.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,_i.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,_i.normalizeSuiAddress)(e)===(0,_i.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,_i.normalizeStructTag)(e)===(0,_i.normalizeStructTag)(n)}static isCoinObjectType(e){return jo.isCoin(e)}};function Zu(t,e){return t.startsWith(e)?t:e+t}var Xu=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ya.verifyTransactionBlock)(e.message,e.signature):(0,ya.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=pa(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return Vn.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=pa(e.messageStr);return this.verifySignature({message:n,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 xg=require("@msafe/sui3-utils"),Ig=require("@mysten/sui.js/cryptography"),Og=require("@mysten/sui.js/multisig");var pk="0x2::sui::SUI";async function Ju(t,e){let n;try{n=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(n.data.length===0||!n.data[0].transaction?.txSignatures)return;let r=n.data[0].transaction?.txSignatures;for(let o=0;o!==r.length;o++){let s=r[o],a=gk(s,e);if(a)return a}}function gk(t,e){let n=(0,Ig.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new Og.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if(Vn.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Vn.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=xg.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return Vn.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function _k(t){let e=!0,n,i=[];for(;e;){let r=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:n});i.push(...r.data),e=r.hasNextPage,n=r.nextCursor}return i}var Pg=25;async function Dg(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Yu=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)}},wa=class{constructor(e){this.requester=e;this.pager=new Yu(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 Eg(t,e,n){let i=new Qu(t,e,n);return await Dg(i)}var Qu=class extends wa{constructor(n,i,r){super(new el(n,i,r));this.provider=n;this.owner=i;this.options=r}},el=class{constructor(e,n,i){this.provider=e;this.owner=n;this.options=i;this.nextCursor=null,this.filter=i?.filter,this.pageSize=i?.pageSize||Pg,this.objectOptions=i?.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 n;if(this.filter){let{filter:i}=this;n=e.data.filter(r=>i?.(r))}else n=e.data;return{data:n.map(i=>i.data).filter(i=>i),hasNext:e.hasNextPage}}};var zi=class t{constructor(e,n){this.globals=e;this.info=n;this.multiSig=new Ae.MultiSigAccount({threshold:n.threshold,ownersWithWeight:n.owners,creationNonce:n.creationNonce}),this.coinHelper=new Bo(this.suiClient),this.simulator=new ma(e)}multiSig;coinHelper;simulator;static async New(e,n){let i=await e.backend.getMSafeAccountInfo(n);if(new t(e,i).address!==n)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 n=>{let i=await this.coinHelper.getCoinMeta(n.coinType),r=n.lockedBalance.number?BigInt(n.totalBalance)-BigInt(n.lockedBalance.number):BigInt(n.totalBalance);return{type:(0,ba.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return Eg(this.suiClient,this.address,n)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let n=e.pending,i=e.reject;return{application:n.application,txType:n.txType,txSubType:n.txSubType,createdAt:n.createdAt,creator:n.creator,digest:n.digest,intention:n.intention,sequenceNumber:n.sequenceNumber,payload:n.payload,votes:n.votes,approvalWeight:this.calculateWeightFromVotes(n.votes),msafeAddress:n.msafeAddress,rejectDigest:i?.digest??"",rejectPayload:i?.payload??"",rejectVotes:i?.votes??[],rejectWeight:this.calculateWeightFromVotes(i?.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 n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,sender:this.address})}async proposeIntention(e){let n=Ae.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),i=await this.wallet.signPersonalMessage({messageStr:n});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:i.signature})}async proposeIntentionAndBuildVote(e){let n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});i.setGasPrice(e.gasPrice),i.setGasBudget(e.gasBudget),i.setSender(this.address);let r=await i.build({client:this.globals.suiClient}),o=await i.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:r});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,ba.toHEX)(r),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async proposeCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async simulateObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async proposeObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async simulatePlainPayloadIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async proposePlainPayloadIntention(e){let n=await this.nextSequenceNumber(),i=tl.TransactionBlock.from(e.payload);if(!i.blockData.sender||!(0,Ae.isSameAddress)(i.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async voteForTransaction(e,n){let i=ga(n),r=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:r.signature})}async proposePendingTransaction(e){let n=new tl.TransactionBlock,i=await n.build({client:this.suiClient}),r=await n.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:r,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let n=e.payload,i=(0,Ae.buildRejectTxb)(this.address,n);return this.simulator.simulate({txb:i,sender:this.address})}async rejectCurrentTx(e){let n=await this.pendingTransaction();if(!n||n.rejectDigest!=="")throw new Error("Already rejected");let i=n.payload,r=(0,Ae.buildRejectTxb)(this.address,i),o=await r.getDigest({client:this.suiClient}),s=await r.build({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:a.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);console.log("\u{1F680} ~ MSafeAccount ~ simulateBuildTransaction ~ intention:",e);let i=await n.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:i,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,n=!1){let i=n?e.rejectVotes:e.votes,r=n?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(i)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(i.map(u=>[u.userAddress,u.signature]));for(let u=0;u<this.info.owners.length;u++){let l=this.info.owners[u],h=s.get(l.address);h&&o.push(h)}let a=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ga(r),signature:a,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(n=>n.userAddress))}calculateWeight(e){let n=0;for(let i=0;i<e.length;i++){let r=this.info.owners.find(o=>(0,Ae.isSameAddress)(o.address,e[i]));r&&(n+=r.weight)}return n}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 Mg=require("@msafe/sui3-utils"),Bg=require("@mysten/sui.js/utils");var va=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let n=this.knownPublicKeys.get(e);if(n)return n;let i=await this._getPublicKey(e);return i&&this.knownPublicKeys.set(e,i),i}async getPublicKeyBatch(e){let n=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];n[o]=this.knownPublicKeys.get(s)}let i=n.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(i.length===0)return n;let r=await this.globals.backend.getPublicKeyBatch(i.map(o=>e[o]));for(let o=0;o<i.length;o++){let s=i[o];n[s]=r[o]}for(let o=0;o<n.length;o++)n[o]===void 0&&(n[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)n[o]&&this.knownPublicKeys.set(e[o],n[o]);return n}addPublicKey(e,n){if(!(0,Mg.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,Bg.normalizeSuiAddress)(e),n)}async _getPublicKey(e){let n=await this.getPublicKeyFromBackend(e);if(n)return n;let i=await this.getPublicKeyFromChain(e);if(i)return i}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Ju(this.globals.suiClient,e)}};var ka=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var $g=require("@mysten/sui.js/client");var No=require("@msafe/sui3-utils"),Fo=ge(require("axios"),1);var Ta=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let n=await this.post("/auth/login",e);return this._token=n.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 n={userAddressList:e};return(await this.get("/user/public-keys",{params:n,headers:this.headers()})).data?.map(r=>r?No.PublicKeySerde.de(r):void 0)}async getMSafeAccountInfo(e){let n={msafeAddress:e},i=await this.get("/msafe",{params:n,headers:this.headers()});return t.toMSafeConfig(i.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let n={status:e.status??No.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},i=await this.get("/msafe/owned",{params:n,headers:this.headers()});return{data:i.data.data.map(t.toMSafeConfig),meta:i.data.meta}}async updateMSafeStatus(e){let n=e;await this.post("/msafe/status",n,{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(n=>({address:n.address,weight:n.weight,publicKey:No.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Fo.default.get(i,n)}catch(r){throw Ca.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Fo.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw Ca.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Zu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=Fo.default.defaults;return n?n instanceof Array?e=n:e=[n]:e=[],[i=>JSON.parse(JSON.stringify(i,(r,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ca=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(Fo.default.isAxiosError(n)&&n?.response?.data&&"message"in n.response.data)return new t(n)}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 jg=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(jg||{}),Sa="https://fullnode.testnet.sui.io",nl="https://fullnode.mainnet.sui.io",il="http://127.0.0.1:3000",rl="http://127.0.0.1:3001",Fg="https://sui-dev.m-safe.link",Ng="http://13.56.226.148:81",Rg="https://sui-preview.m-safe.link",qg="https://sui.m-safe.link",Lg=new Map([["unit",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["local",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["dev",{suiClient:{url:Sa},backend:{url:Fg},syncingURL:Ng,network:"sui:testnet"}],["prev",{suiClient:{url:nl},backend:{url:Rg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:nl},backend:{url:qg},syncingURL:"",network:"sui:mainnet"}]]);function ol(t,e){let n=Lg.get(t);if(!n)throw new Error("Unknown environment");return e?.suiClient?.url&&(n.suiClient.url=e.suiClient.url),e?.backend?.url&&(n.backend.url=e.backend.url),n}var Ro=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,n){let i=ol(e,n),r=new $g.SuiClient(i.suiClient),o=new Ta(i.backend.url);return new t({backend:o,suiClient:r,config:i})}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 Aa=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await Ro.New(e,n);return new t(i)}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 n=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(n),n}async authSign(e){let n=xa.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),i=await e.signPersonalMessage({messageStr:n});return this.backend.authSign({address:await e.address(),message:n,signature:i.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:xa.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new zi(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new zi(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Gi(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new va(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 Wi(this.globals)}get Invitation(){return new $o(this.globals)}get Report(){return new ka(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2053
|
+
`);var To=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=new Set,bu=typeof process=="object"&&process?process:{},Rh=(t,e,n,i)=>{typeof bu.emitWarning=="function"?bu.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},Hs=globalThis.AbortController,Fh=globalThis.AbortSignal;if(typeof Hs>"u"){Fh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},Hs=class{constructor(){e()}signal=new Fh;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let r of this.signal._onabort)r(i);this.signal.onabort?.(i)}}};let t=bu.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Rh("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 Cb=t=>!Nh.has(t),YA=Symbol("type"),ui=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),qh=t=>ui(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ir:null:null,Ir=class extends Array{constructor(e){super(e),this.fill(0)}},vu=class t{heap;length;static#c=!1;static create(e){let n=qh(e);if(!n)return[];t.#c=!0;let i=new t(e,n);return t.#c=!1,i}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zs=class t{#c;#d;#y;#m;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#p;#r;#n;#e;#u;#f;#a;#o;#g;#s;#k;#T;#_;#w;#S;#l;static unsafeExposeInternals(e){return{starts:e.#T,ttls:e.#_,sizes:e.#k,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,i,r,o)=>e.#E(n,i,r,o),moveToTail:n=>e.#I(n),indexes:n=>e.#b(n),rindexes:n=>e.#v(n),isStale:n=>e.#h(n)}}get max(){return this.#c}get maxSize(){return this.#d}get calculatedSize(){return this.#p}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#m}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:u,dispose:l,disposeAfter:h,noDisposeOnSet:w,noUpdateTTL:v,maxSize:T=0,maxEntrySize:I=0,sizeCalculation:x,fetchMethod:P,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:$,ignoreFetchAbort:Z}=e;if(n!==0&&!ui(n))throw new TypeError("max option must be a nonnegative integer");let H=n?qh(n):Array;if(!H)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=T,this.maxEntrySize=I||this.#d,this.sizeCalculation=x,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(P!==void 0&&typeof P!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=P,this.#S=!!P,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new H(n),this.#f=new H(n),this.#a=0,this.#o=0,this.#g=vu.create(n),this.#i=0,this.#p=0,typeof l=="function"&&(this.#y=l),typeof h=="function"?(this.#m=h,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#w=!!this.#y,this.#l=!!this.#m,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!B,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#d!==0&&!ui(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!ui(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#R()}if(this.allowStale=!!u,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=ui(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!ui(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#c===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#d){let te="LRU_CACHE_UNBOUNDED";Cb(te)&&(Nh.add(te),Rh("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",te,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#M(){let e=new Ir(this.#c),n=new Ir(this.#c);this.#_=e,this.#T=n,this.#B=(o,s,a=To.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let u=setTimeout(()=>{this.#h(o)&&this.delete(this.#n[o])},s+1);u.unref&&u.unref()}},this.#A=o=>{n[o]=e[o]!==0?To.now():0},this.#C=(o,s)=>{if(e[s]){let a=e[s],u=n[s];o.ttl=a,o.start=u,o.now=i||r();let l=o.now-u;o.remainingTTL=a-l}};let i=0,r=()=>{let o=To.now();if(this.ttlResolution>0){i=o;let s=setTimeout(()=>i=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],u=n[s];if(a===0||u===0)return 1/0;let l=(i||r())-u;return a-l},this.#h=o=>e[o]!==0&&n[o]!==0&&(i||r())-n[o]>e[o]}#A=()=>{};#C=()=>{};#B=()=>{};#h=()=>!1;#R(){let e=new Ir(this.#c);this.#p=0,this.#k=e,this.#x=n=>{this.#p-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!ui(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!ui(r))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 r},this.#P=(n,i,r)=>{if(e[n]=i,this.#d){let o=this.#d-e[n];for(;this.#p>o;)this.#D(!0)}this.#p+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#p)}}#x=e=>{};#P=(e,n,i)=>{};#j=(e,n,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#F(n)||((e||!this.#h(n))&&(yield n),n===this.#a));)n=this.#f[n]}*#v({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#F(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#F(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#b()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#v()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#b())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,n={}){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&e(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(e,n=this){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}rforEach(e,n=this){for(let i of this.#v()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}purgeStale(){let e=!1;for(let n of this.#v({allowStale:!0}))this.#h(n)&&(this.delete(this.#n[n]),e=!0);return e}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let s={value:o};if(this.#_&&this.#T){s.ttl=this.#_[n];let a=To.now()-this.#T[n];s.start=Math.floor(Date.now()-a)}this.#k&&(s.size=this.#k[n]),e.unshift([i,s])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let r=Date.now()-i.start;i.start=To.now()-r}this.set(n,i.value,i)}}set(e,n,i={}){if(n===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:u}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,h=this.#j(e,n,i.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return u&&(u.set="miss",u.maxEntrySizeExceeded=!0),this.delete(e),this;let w=this.#i===0?void 0:this.#r.get(e);if(w===void 0)w=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[w]=e,this.#e[w]=n,this.#r.set(e,w),this.#u[this.#o]=w,this.#f[w]=this.#o,this.#o=w,this.#i++,this.#P(w,h,u),u&&(u.set="add"),l=!1;else{this.#I(w);let v=this.#e[w];if(n!==v){if(this.#S&&this.#t(v)?v.__abortController.abort(new Error("replaced")):s||(this.#w&&this.#y?.(v,e,"set"),this.#l&&this.#s?.push([v,e,"set"])),this.#x(w),this.#P(w,h,u),this.#e[w]=n,u){u.set="replace";let T=v&&this.#t(v)?v.__staleWhileFetching:v;T!==void 0&&(u.oldValue=T)}}else u&&(u.set="update")}if(r!==0&&!this.#_&&this.#M(),this.#_&&(l||this.#B(w,r,o),u&&this.#C(u,w)),!s&&this.#l&&this.#s){let v=this.#s,T;for(;T=v?.shift();)this.#m?.(...T)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#D(!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,n;for(;n=e?.shift();)this.#m?.(...n)}}}#D(e){let n=this.#a,i=this.#n[n],r=this.#e[n];return this.#S&&this.#t(r)?r.__abortController.abort(new Error("evicted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#x(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#g.push(n)),this.#i===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#u[n],this.#r.delete(i),this.#i--,n}has(e,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#r.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))r&&(r.has="stale",this.#C(r,o));else return i&&this.#A(o),r&&(r.has="hit",this.#C(r,o)),!0}else r&&(r.has="miss");return!1}peek(e,n={}){let{allowStale:i=this.allowStale}=n,r=this.#r.get(e);if(r!==void 0&&(i||!this.#h(r))){let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}}#E(e,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let s=new Hs,{signal:a}=i;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let u={signal:s.signal,options:i,context:r},l=(x,P=!1)=>{let{aborted:O}=s.signal,E=i.ignoreFetchAbort&&x!==void 0;if(i.status&&(O&&!P?(i.status.fetchAborted=!0,i.status.fetchError=s.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),O&&!E&&!P)return w(s.signal.reason);let B=T;return this.#e[n]===T&&(x===void 0?B.__staleWhileFetching?this.#e[n]=B.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,x,u.options))),x},h=x=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=x),w(x)),w=x=>{let{aborted:P}=s.signal,O=P&&i.allowStaleOnFetchAbort,E=O||i.allowStaleOnFetchRejection,B=E||i.noDeleteOnFetchRejection,$=T;if(this.#e[n]===T&&(!B||$.__staleWhileFetching===void 0?this.delete(e):O||(this.#e[n]=$.__staleWhileFetching)),E)return i.status&&$.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),$.__staleWhileFetching;if($.__returned===$)throw x},v=(x,P)=>{let O=this.#O?.(e,o,u);O&&O instanceof Promise&&O.then(E=>x(E),P),s.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(),i.allowStaleOnFetchAbort&&(x=E=>l(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let T=new Promise(v).then(l,h),I=Object.assign(T,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,I,{...u.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=I,I}#t(e){if(!this.#S)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Hs}async fetch(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:u=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:v=this.allowStaleOnFetchRejection,ignoreFetchAbort:T=this.ignoreFetchAbort,allowStaleOnFetchAbort:I=this.allowStaleOnFetchAbort,context:x,forceRefresh:P=!1,status:O,signal:E}=n;if(!this.#S)return O&&(O.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:O});let B={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:u,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:I,ignoreFetchAbort:T,status:O,signal:E},$=this.#r.get(e);if($===void 0){O&&(O.fetch="miss");let Z=this.#E(e,$,B,x);return Z.__returned=Z}else{let Z=this.#e[$];if(this.#t(Z)){let N=i&&Z.__staleWhileFetching!==void 0;return O&&(O.fetch="inflight",N&&(O.returnedStale=!0)),N?Z.__staleWhileFetching:Z.__returned=Z}let H=this.#h($);if(!P&&!H)return O&&(O.fetch="hit"),this.#I($),r&&this.#A($),O&&this.#C(O,$),Z;let te=this.#E(e,$,B,x),V=te.__staleWhileFetching!==void 0&&i;return O&&(O.fetch=H?"stale":"refresh",V&&H&&(O.returnedStale=!0)),V?te.__staleWhileFetching:te.__returned=te}}get(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let u=this.#e[a],l=this.#t(u);return s&&this.#C(s,a),this.#h(a)?(s&&(s.get="stale"),l?(s&&i&&u.__staleWhileFetching!==void 0&&(s.returnedStale=!0),i?u.__staleWhileFetching:void 0):(o||this.delete(e),s&&i&&(s.returnedStale=!0),i?u:void 0)):(s&&(s.get="hit"),l?u.__staleWhileFetching:(this.#I(a),r&&this.#A(a),u))}else s&&(s.get="miss")}#N(e,n){this.#f[n]=e,this.#u[e]=n}#I(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#N(this.#f[e],this.#u[e]),this.#N(this.#o,e),this.#o=e)}delete(e){let n=!1;if(this.#i!==0){let i=this.#r.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.clear();else{this.#x(i);let r=this.#e[i];this.#t(r)?r.__abortController.abort(new Error("deleted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,e,"delete"),this.#l&&this.#s?.push([r,e,"delete"])),this.#r.delete(e),this.#n[i]=void 0,this.#e[i]=void 0,i===this.#o?this.#o=this.#f[i]:i===this.#a?this.#a=this.#u[i]:(this.#u[this.#f[i]]=this.#u[i],this.#f[this.#u[i]]=this.#f[i]),this.#i--,this.#g.push(i)}}if(this.#l&&this.#s?.length){let i=this.#s,r;for(;r=i?.shift();)this.#m?.(...r)}return n}clear(){for(let e of this.#v({allowStale:!0})){let n=this.#e[e];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#n[e];this.#w&&this.#y?.(n,i,"delete"),this.#l&&this.#s?.push([n,i,"delete"])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#_&&this.#T&&(this.#_.fill(0),this.#T.fill(0)),this.#k&&this.#k.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#p=0,this.#i=0,this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#m?.(...n)}}};var ae=ge(ke(),1);var Qs=ge(Lh(),1),Fi=require("@mysten/sui.js/utils"),Ni=require("@mysten/sui.js/transactions");var Co=ge(ke(),1),Hh=require("@mysten/sui.js/transactions"),Wt=ge(ke(),1);var li=ge(ke(),1),ln=ge(ke(),1);var xo=ge(ke(),1);var Zh=require("@mysten/sui.js/utils"),ea=require("@mysten/sui.js/transactions"),ta=require("@mysten/sui.js/utils");var xu=ge(ke(),1),Sb=Object.defineProperty,Ab=(t,e,n)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,On=(t,e,n)=>(Ab(t,typeof e!="symbol"?e+"":e,n),n);var Xs=443636,Js=-443636,Cu="79226673515401279992447579055",Su="4295048016",Ib=14,Ob="59543866431248",Pb="184467440737095516",Db="15793534762490258745",Eb=class{generateMnemonic(t=24){return Bh(jh,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return zh.Ed25519Keypair.deriveKeypair(t,n)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:n=!1,addressIndex:i=0}=t;return`m/44'/784'/${e}'/${n?1:0}'/${i}'`}},Ao=class{constructor(t){this.sdk=t,On(this,"_lru"),On(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new Zs({max:100}));if(r.has(t))return r.get(t);let s=await((i=this._fetching)[t]||(i[t]=e()));return delete this._fetching[t],r.set(t,s,{ttl:n}),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 Mb(t){if("reference"in t)return t.reference;let e=Iu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Gh(t)}function ia(t){var e,n;return"objectId"in t?t.objectId:(n=(e=Mb(t))==null?void 0:e.objectId)!=null?n:Wh(t)}function Pn(t){var e;return"fields"in t?t.fields:(e=Vh(t))==null?void 0:e.fields}function Vh(t){let e="data"in t?Iu(t):t;if(!(!e||!Bb(e)||e.content.dataType!=="moveObject"))return e.content}function Bb(t){return t.content!==void 0}function Iu(t){return t.data}function Gh(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 Wh(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function jb(t){return t.data!==void 0}function Fb(t){var e;let n=jb(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":na(t):n?.type}function na(t){var e;return(e=Vh(t))==null?void 0:e.type}function Nb(t){var e;return(e=Iu(t))==null?void 0:e.owner}var So=async(t,e,n)=>{let r=e.length;if(r>50){let o=[],s=0,a=Math.ceil(r/50);for(s;s<a;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:n}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:n})},Rb=class extends Ao{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 So(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=Pn(i),o=ia(i),s=na(i);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:r.fee,tickSpacing:r.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())}},$h=new ae.default(2).pow(new ae.default(128)),qb=class{priceToSqrtPriceX64(t,e,n){return new ae.default(new F(t).mul(F.pow(10,n-e)).sqrt().mul(F.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new F(t.toString()).mul(F.pow(2,-64)).pow(2).mul(F.pow(10,e-n))}priceToTickIndex(t,e,n){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,n))}sqrtPriceX64ToTickIndex(t){if(t.gt(new ae.default(Cu))||t.lt(new ae.default(Su)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new ae.default(e-64),i=this.signedShiftLeft(n,32,128),r=new ae.default("8000000000000000","hex"),o=0,s=new ae.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ae.default(0))&&o<Ib;){a=a.mul(a);let T=a.shrn(127);a=a.shrn(63+T.toNumber()),s=s.add(r.mul(T)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ae.default(Ob)),w=this.signedShiftRight(h.sub(new ae.default(Pb)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(Db)),64,128).toNumber();return w==v?w:this.tickIndexToSqrtPriceX64(v).lte(t)?v:w}tickIndexToSqrtPriceX64(t){return t>0?new ae.default(this.tickIndexToSqrtPricePositive(t)):new ae.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,n){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,n)}toX64_Decimal(t){return t.mul(F.pow(2,64))}fromX64_Decimal(t){return t.mul(F.pow(2,-64))}scaleDown(t,e){return new F(t).div(F.pow(10,e)).toString()}scaleUp(t,e){return new F(t).mul(F.pow(10,e)).toString()}bitsToNumber(t,e=32){return Qs.default.toNumber(Qs.default.asIntN(e,Qs.default.BigInt(t)))}subUnderflowU128(t,e){return t.add($h).sub(e).mod($h)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new ae.default("79232123823359799118286999567"):e=new ae.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new ae.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new ae.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new ae.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new ae.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new ae.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new ae.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new ae.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new ae.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new ae.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new ae.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new ae.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new ae.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new ae.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new ae.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new ae.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new ae.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new ae.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new ae.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),n;return e&1?n=new ae.default("18445821805675392311"):n=new ae.default("18446744073709551616"),e&2&&(n=this.signedShiftRight(n.mul(new ae.default("18444899583751176498")),64,256)),e&4&&(n=this.signedShiftRight(n.mul(new ae.default("18443055278223354162")),64,256)),e&8&&(n=this.signedShiftRight(n.mul(new ae.default("18439367220385604838")),64,256)),e&16&&(n=this.signedShiftRight(n.mul(new ae.default("18431993317065449817")),64,256)),e&32&&(n=this.signedShiftRight(n.mul(new ae.default("18417254355718160513")),64,256)),e&64&&(n=this.signedShiftRight(n.mul(new ae.default("18387811781193591352")),64,256)),e&128&&(n=this.signedShiftRight(n.mul(new ae.default("18329067761203520168")),64,256)),e&256&&(n=this.signedShiftRight(n.mul(new ae.default("18212142134806087854")),64,256)),e&512&&(n=this.signedShiftRight(n.mul(new ae.default("17980523815641551639")),64,256)),e&1024&&(n=this.signedShiftRight(n.mul(new ae.default("17526086738831147013")),64,256)),e&2048&&(n=this.signedShiftRight(n.mul(new ae.default("16651378430235024244")),64,256)),e&4096&&(n=this.signedShiftRight(n.mul(new ae.default("15030750278693429944")),64,256)),e&8192&&(n=this.signedShiftRight(n.mul(new ae.default("12247334978882834399")),64,256)),e&16384&&(n=this.signedShiftRight(n.mul(new ae.default("8131365268884726200")),64,256)),e&32768&&(n=this.signedShiftRight(n.mul(new ae.default("3584323654723342297")),64,256)),e&65536&&(n=this.signedShiftRight(n.mul(new ae.default("696457651847595233")),64,256)),e&131072&&(n=this.signedShiftRight(n.mul(new ae.default("26294789957452057")),64,256)),e&262144&&(n=this.signedShiftRight(n.mul(new ae.default("37481735321082")),64,256)),n}signedShiftLeft(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}signedShiftRight(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}},Au=(t,e)=>{let n=ia(t);if(Gh(t))throw new Error(`${e}(${n}) had been deleted`);if(Wh(t))throw new Error(`${e}(${n}) is not found`);return!0},Or=60*1e3,Lb=class extends Ao{async getPools(t=!1){let e=await this.contract.getConfig(),n=[],i;do i=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:i?.nextCursor,limit:15}),n.push(...i.data.map(a=>a.objectId));while(i.hasNextPage);if(!n.length)return[];let o=(await So(this.provider,n,{showContent:!0})).map(a=>Pn(a).value.fields.pool_id);if(!o.length)return[];let s=await So(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>Pn(a).unlocked)),s.map(a=>this.parsePool(a))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:n,tickLower:i,tickUpper:r,sqrtPrice:o,slippage:s,coinTypeA:a,coinTypeB:u}=t,l=await this.contract.getConfig(),h=new F(t.amountA),w=new F(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,w)]),I=t.txb||new Ni.TransactionBlock,x=v.length>0?this.coin.convertTradeCoins(I,v,a,h):[this.coin.zero(a,I)],P=T.length>0?this.coin.convertTradeCoins(I,T,u,w):[this.coin.zero(u,I)];return I.moveCall({target:`${l.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[a,u,e.type],arguments:[I.object(l.PoolConfig),I.object(e.objectId),I.pure(o,"u128"),I.object(l.Positions),I.makeMoveVec({objects:x}),I.makeMoveVec({objects:P}),I.pure(Math.abs(i).toFixed(0),"u32"),I.pure(i<0,"bool"),I.pure(Math.abs(r).toFixed(0),"u32"),I.pure(r<0,"bool"),I.pure(h.toFixed(0),"u64"),I.pure(w.toFixed(0),"u64"),I.pure(this.getMinimumAmountBySlippage(h,s),"u64"),I.pure(this.getMinimumAmountBySlippage(w,s),"u64"),I.pure(n,"address"),I.pure(Date.now()+(t.deadline||Or),"u64"),I.object(Fi.SUI_CLOCK_OBJECT_ID),I.object(l.Versioned)]}),I}async addLiquidity(t){let{address:e,tickLower:n,tickUpper:i,slippage:r,pool:o}=t,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(o),[u,l]=a,[h,w]=await Promise.all([this.coin.getMetadata(u),this.coin.getMetadata(l)]);if(!h||!w)throw new Error("Invalid coin type");let v=new F(t.amountA),T=new F(t.amountB),[I,x]=await Promise.all([this.coin.selectTradeCoins(e,u,v),this.coin.selectTradeCoins(e,l,T)]),P=t.txb||new Ni.TransactionBlock,O=I.length>0?this.coin.convertTradeCoins(P,I,u,v):[this.coin.zero(u,P)],E=x.length>0?this.coin.convertTradeCoins(P,x,l,T):[this.coin.zero(l,P)];return P.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:a,arguments:[P.object(o),P.object(s.Positions),P.makeMoveVec({objects:O}),P.makeMoveVec({objects:E}),P.pure(Math.abs(n).toFixed(0),"u32"),P.pure(n<0,"bool"),P.pure(Math.abs(i).toFixed(0),"u32"),P.pure(i<0,"bool"),P.pure(v.toFixed(0),"u64"),P.pure(T.toFixed(0),"u64"),P.pure(this.getMinimumAmountBySlippage(v,r),"u64"),P.pure(this.getMinimumAmountBySlippage(T,r),"u64"),P.pure(e,"address"),P.pure(Date.now()+(t.deadline||Or),"u64"),P.object(Fi.SUI_CLOCK_OBJECT_ID),P.object(s.Versioned)]}),P}async increaseLiquidity(t){let{pool:e,slippage:n,address:i,nft:r}=t,o=await this.contract.getConfig(),s=new F(t.amountA),a=new F(t.amountB),u=await this.getPoolTypeArguments(e),[l,h]=u,[w,v]=await Promise.all([this.coin.selectTradeCoins(i,l,s),this.coin.selectTradeCoins(i,h,a)]),T=t.txb||new Ni.TransactionBlock,I=w.length>0?this.coin.convertTradeCoins(T,w,l,s):[this.coin.zero(l,T)],x=v.length>0?this.coin.convertTradeCoins(T,v,h,a):[this.coin.zero(h,T)];return T.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:u,arguments:[T.object(e),T.object(o.Positions),T.makeMoveVec({objects:I}),T.makeMoveVec({objects:x}),T.object(r),T.pure(s.toFixed(0),"u64"),T.pure(a.toFixed(0),"u64"),T.pure(this.getMinimumAmountBySlippage(s,n),"u64"),T.pure(this.getMinimumAmountBySlippage(a,n),"u64"),T.pure(Date.now()+(t.deadline||Or*3),"u64"),T.object(Fi.SUI_CLOCK_OBJECT_ID),T.object(o.Versioned)]}),T}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new F(t.amountA),s=new F(t.amountB),a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(i),l=t.txb||new Ni.TransactionBlock;return l.moveCall({target:`${a.PackageId}::position_manager::decrease_liquidity`,typeArguments:u,arguments:[l.object(i),l.object(a.Positions),l.object(n),l.pure(new Co.default(r).toString(),"u128"),l.pure(this.getMinimumAmountBySlippage(o,e),"u64"),l.pure(this.getMinimumAmountBySlippage(s,e),"u64"),l.pure(Date.now()+(t.deadline||Or*3),"u64"),l.object(Fi.SUI_CLOCK_OBJECT_ID),l.object(a.Versioned)]}),l}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:n,address:i,collectAmountA:r,collectAmountB:o}=t,s=t.txb||new Ni.TransactionBlock;if(Number(r)===0&&Number(o)===0)return s;let a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return s.moveCall({target:`${a.PackageId}::position_manager::collect`,typeArguments:u,arguments:[s.object(e),s.object(a.Positions),s.object(n),s.pure(r,"u64"),s.pure(o,"u64"),s.pure(i),s.pure(Date.now()+(t.deadline||Or*3),"u64"),s.object(Fi.SUI_CLOCK_OBJECT_ID),s.object(a.Versioned)]}),s}async collectReward(t){let{pool:e,nft:n,rewardAmounts:i,address:r}=t,o=t.txb||new Ni.TransactionBlock,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((l,h)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...a,l.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(n),o.object(l.fields.vault),o.pure(h,"u64"),o.pure(i[h],"u64"),o.pure(r),o.pure(Date.now()+(t.deadline||Or*3),"u64"),o.object(Fi.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new F((t.liquidity||new Co.default(1e8)).toString()),n=new F(t.currentSqrtPrice.toString()),i=new F(t.lowerSqrtPrice.toString()),r=new F(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(i)).div(i.mul(r)),s=new F(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(n)).div(n.mul(r)),s=this.math.fromX64_Decimal(e.mul(n.sub(i)))):(o=new F(0),s=this.math.fromX64_Decimal(e.mul(r.sub(i))));let a=t.ceil!==!1?"ceil":"floor";return[new Co.default(o[a]().toString()),new Co.default(s[a]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var n;let i=((n=t.replace(">","").split("<")[1])==null?void 0:n.split(/,\s*/))||[];if(e!==void 0&&e!==i.length)throw new Error("Invalid pool type");return i}async getFixedLiquidity(t){var e,n;let{coinTypeA:i,coinTypeB:r,amountA:o,amountB:s}=t,[a,u]=await Promise.all([this.coin.getMetadata(i),this.coin.getMetadata(r)]),l=new F(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),h=new F(this.math.scaleDown(s,u.decimals)).mul((n=t.priceB)!=null?n:1);return{liquidityA:l.toString(),liquidityB:h.toString(),liquidity:l.plus(h).toString()}}parsePool(t){let e=Pn(t),n=ia(t),i=Fb(t),r=this.parsePoolType(i,3);return this.getCacheOrSet("pool-type-"+n,async()=>r),{...e,objectId:n,type:i,types:r}}getMinimumAmountBySlippage(t,e){let n=new F(t),i=new F(1).minus(new F(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},$b=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new li.default(n.fee_growth_global_a),a=new li.default(i.fee_growth_inside_a),u=new li.default(i.tokens_owed_a),l=new li.default(n.fee_growth_global_b),h=new li.default(i.fee_growth_inside_b),w=new li.default(i.tokens_owed_b),v=new li.default(i.liquidity),T,I,x,P,O=t.bitsToNumber(n.tick_current_index.fields.bits),E=t.bitsToNumber(i.tick_lower_index.fields.bits),B=t.bitsToNumber(i.tick_upper_index.fields.bits);O<E?(T=t.subUnderflowU128(s,r.feeGrowthOutsideA),I=t.subUnderflowU128(l,r.feeGrowthOutsideB)):(T=r.feeGrowthOutsideA,I=r.feeGrowthOutsideB),O<B?(x=o.feeGrowthOutsideA,P=o.feeGrowthOutsideB):(x=t.subUnderflowU128(s,o.feeGrowthOutsideA),P=t.subUnderflowU128(l,o.feeGrowthOutsideB));let $=t.subUnderflowU128(t.subUnderflowU128(s,T),x),Z=t.subUnderflowU128(t.subUnderflowU128(l,I),P),H=t.subUnderflowU128($,a).mul(v).shrn(64),te=t.subUnderflowU128(Z,h).mul(v).shrn(64);return{feeOwedA:u.add(H).toString(),feeOwedB:w.add(te).toString()}},Uh=new xo.default(0),Kh=new xo.default(1),Ub=new xo.default(2),Kb={mul(t,e,n){let i=t.mul(e);if(this.isOverLimit(i,n))throw new Error(`Mul result higher than u${n}`);return i},mulDiv(t,e,n,i){return this.mulDivRoundUpIf(t,e,n,!1,i)},mulDivRoundUpIf(t,e,n,i,r){if(n.eq(Uh))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt(Uh)?s.add(Kh):s},isOverLimit(t,e){let n=Ub.pow(new xo.default(e)).sub(Kh);return t.gt(n)}},zb=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,w=new ln.default(new F(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),T=(h??new ln.default(Date.now()).div(new ln.default(1e3))).sub(new ln.default(w)),I=[],x=new ln.default(s.liquidity),P=new ln.default(a.liquidity);for(let O=0;O<3;++O){let E=s.reward_infos[O],B={emissionsPerSecondX64:new ln.default(E?E.fields.emissions_per_second:"0"),growthGlobalX64:new ln.default(E?E.fields.growth_global:"0")},$={growthInsideCheckpoint:new ln.default((i=(n=a.reward_infos[O])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new ln.default((o=(r=a.reward_infos[O])==null?void 0:r.fields.amount_owed)!=null?o:"0")},Z=B.growthGlobalX64;if(!x.isZero()){let C=Kb.mulDiv(T,B.emissionsPerSecondX64,x,128);Z=B.growthGlobalX64.add(C)}let H=u.rewardGrowthsOutside[O],te=l.rewardGrowthsOutside[O],U=Z;u.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_lower_index.fields.bits)?t.subUnderflowU128(Z,H):H);let V=new ln.default(0);l.initialized&&(V=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_upper_index.fields.bits)?te:t.subUnderflowU128(Z,te));let N=t.subUnderflowU128(t.subUnderflowU128(Z,U),V),K=$.amountOwed.shln(64);I[O]=K.add(t.subUnderflowU128(N,$.growthInsideCheckpoint).mul(P)).shrn(64).toString()}return I},Vb=class extends Ao{async getOwner(t){let e=await this.getObject(t),n=Nb(e);if(!(!n||typeof n=="string")){if("ObjectOwner"in n)return n.ObjectOwner;if("AddressOwner"in n)return n.AddressOwner}}async getFields(t){let e=await this.getObject(t);return Pn(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return Pn(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"position"),Pn(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=Pn(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new Wt.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Wt.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new Wt.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Wt.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new Wt.default(r))}}async getPositionAPR(t){let{poolId:e,getPrice:n,fees24h:i,tickLower:r,tickUpper:o}=t,s=await this.pool.getPool(e),a=this.math.bitsToNumber(s.tick_current_index.fields.bits),[u,l,h,w]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),n(s.types[0]),n(s.types[1])]);if(!h||!w||r>=o||a<r||a>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:v,minTokenB:T}=this.getRemoveLiquidityQuote(s,r,o),I=new F(this.math.scaleDown(v.toString(),u.decimals)).mul(h),x=new F(this.math.scaleDown(T.toString(),l.decimals)).mul(w),P=I.add(x),O=P.isZero()?new F(0):new F(i).mul(365).div(P).mul(100),E=new F(0);return await Promise.all(s.reward_infos.map(async B=>{let{emissions_per_second:$}=B.fields,Z=this.coin.formatCoinType(B.fields.vault_coin_type),[H,te]=await Promise.all([n(Z),this.coin.getMetadata(Z)]);!$||$==="0"||!H||(E=E.add(new F(new Wt.default($).shrn(64).toString()).div(10**te.decimals).mul(31536e3).mul(H).div(P).mul(100)))})),{fees:O.toString(),rewards:E.toString(),total:O.plus(E).toString()}}getRemoveLiquidityQuote(t,e,n){let i=new Wt.default(0),r=new Wt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),a=this.math.tickIndexToSqrtPriceX64(n);if(o<e){let l=this.getTokenAFromLiquidity(r,s,a);return{minTokenA:this.adjustForSlippage(l),minTokenB:i}}if(o<n){let l=new Wt.default(t.sqrt_price),h=this.getTokenAFromLiquidity(r,l,a),w=this.getTokenBFromLiquidity(r,s,l);return{minTokenA:this.adjustForSlippage(h),minTokenB:this.adjustForSlippage(w)}}let u=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(u)}}adjustForSlippage(t){let e={numerator:new Wt.default(0),denominator:new Wt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,n){let i=t.mul(n.sub(e)).shln(64),r=n.mul(e);return i.div(r)}getTokenBFromLiquidity(t,e,n){return t.mul(n.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:n}=t,i=t.txb||new Hh.TransactionBlock,r=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return i.moveCall({target:`${r.PackageId}::position_manager::burn`,typeArguments:o,arguments:[i.object(r.Positions),i.object(n),i.object(r.Versioned)]}),i}async getPositionLiquidityUSD(t){let{position:e,poolId:n,priceA:i,priceB:r}=t,o=await this.pool.getPool(n),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Wt.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 Wt.default(e.liquidity===void 0?1e8:e.liquidity)}),[a,u]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),l=new F(s[0].toString()).div(10**a.decimals).mul(i||0),h=new F(s[1].toString()).div(10**u.decimals).mul(r||0);return l.plus(h).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:n}=t,[i,r,o]=await Promise.all([this.pool.getPool(n),this.nft.getPositionTick(n,e.tick_lower_index),this.nft.getPositionTick(n,e.tick_upper_index)]),s={...t,pool:i,tickLowerDetail:r,tickUpperDetail:o},[a,u]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:l,...h}=a,{unclaimedRewards:w,...v}=u;return{fees:a.unclaimedFees.toString(),rewards:w.toString(),total:l.plus(w).toString(),fields:{...h,...v}}}async getUnclaimedFees(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,[s,a,u,l]=await Promise.all([this.coin.getMetadata(n.types[0]),this.coin.getMetadata(n.types[1]),i(n.types[0]),i(n.types[1])]),h=$b(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),w=this.math.scaleDown(h.feeOwedA,s.decimals),v=this.math.scaleDown(h.feeOwedB,a.decimals);function T(P,O){return new F(1e6).mul(F.pow(10,O)).lt(P)}T(w,s.decimals)&&(w="0",h.feeOwedA="0"),T(v,a.decimals)&&(v="0",h.feeOwedB="0");let I=u===void 0?new F(0):new F(u).mul(w),x=l===void 0?new F(0):new F(l).mul(v);return{unclaimedFees:I.plus(x),scaledFeeOwedA:w,scaledFeeOwedB:v,...h}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=zb(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),a=[...s],u=n.reward_infos.map(v=>this.coin.formatCoinType(v.fields.vault_coin_type)),l=await Promise.all([...n.reward_infos.map((v,T)=>this.coin.getMetadata(u[T]))]),h=await Promise.all(n.reward_infos.map((v,T)=>i(u[T])));l.forEach((v,T)=>{a[T]=this.math.scaleDown(a[T],v.decimals)});let w=new F(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(w=w.plus(new F(I).mul(a[T])),!1):(w=w.plus(1),!0)}),{unclaimedRewards:w,collectRewards:s,scaledCollectRewards:a}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return Au(e,"nft"),e})}},Gb=class extends Ao{isSUI(t){return(0,Zh.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,n){if(n.eq(0))return[];let i=[],r=[],o=new F(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),i.push(...s.data);while(s.hasNextPage);i.sort((a,u)=>Number(u.balance)-Number(a.balance));for(let a of i)if(r.push(a.coinObjectId),o=o.add(a.balance),o.gte(n))break;return r}convertTradeCoins(t,e,n,i){return this.isSUI(n)?[t.splitCoins(t.gas,[t.pure(i.toNumber())])[0]]:e.map(r=>t.object(r))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let i=t.replace(/^0x/i,"");return i=i.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&i.length<64&&t!=="2::sui:SUI"?"0".repeat(64-i.length):"")+i}},Wb=60*1e3,Ys=100,Hb=class extends Ao{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new F(t.amountA),a=new F(t.amountB),u=await this.contract.getConfig(),l=await Promise.all(t.routes.map(async x=>{let P=await this.pool.getPoolTypeArguments(x.pool),[O,E]=await Promise.all([this.coin.getMetadata(P[0]),this.coin.getMetadata(P[1])]);return{...x,coinA:O,coinB:E,typeArguments:P}})),h=await this.coin.selectTradeCoins(i,e,s),{functionName:w,typeArguments:v}=this.getFunctionNameAndTypeArguments(l.map(({typeArguments:x})=>x),e,n),T=l.map(({nextTickIndex:x,coinA:P,coinB:O,a2b:E})=>{let B=this.math.tickIndexToPrice(x,P.decimals,O.decimals);return this.sqrtPriceWithSlippage(B,o,E,P.decimals,O.decimals)}),I=t.txb||new ea.TransactionBlock;return I.moveCall({target:`${u.PackageId}::swap_router::${w}`,typeArguments:v,arguments:[...l.map(({pool:x})=>I.object(x)),I.makeMoveVec({objects:this.coin.convertTradeCoins(I,h,e,s)}),I.pure((r?s:a).toFixed(0),"u64"),I.pure(this.amountOutWithSlippage(r?a:s,o,r),"u64"),...T.map(x=>I.pure(x,"u128")),I.pure(r,"bool"),I.pure(i,"address"),I.pure(Date.now()+Wb*3,"u64"),I.object(ta.SUI_CLOCK_OBJECT_ID),I.object(u.Versioned)]}),I}async computeSwapResult(t){let{pools:e,amountSpecified:n,amountSpecifiedIsInput:i,address:r,tickStep:o}=t,s=await this.contract.getConfig(),a=e.map(w=>w.pool),u=await So(this.provider,a,{showContent:!0}),l=new ea.TransactionBlock;u.map(async w=>{let v=Pn(w),T=e.find(E=>E.pool===v.id.id),I=this.math.bitsToNumber(v.tick_current_index.fields.bits),x=I-v.tick_spacing*(o||Ys),P=I+v.tick_spacing*(o||Ys);x=x<Js?Js:x,P=P>Xs?Xs:P;let O=this.pool.parsePoolType(na(w));l.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:O,arguments:[l.object(v.id.id),l.pure(T.a2b,"bool"),l.pure(new F(n).toFixed(0),"u128"),l.pure(i,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(T.a2b?x:P).toString(),"u128"),l.object(ta.SUI_CLOCK_OBJECT_ID),l.object(s.Versioned)]})});let h=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:r});if(h.error)throw new Error(h.error);return h.events.map(w=>w.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:n,address:i,tickStep:r}=t,o=await this.contract.getConfig(),s=e.map(h=>h.pool),a=await So(this.provider,Array.from(new Set(s)),{showContent:!0}),u=new ea.TransactionBlock;e.forEach(async h=>{let w=a.find(O=>ia(O)===h.pool),v=Pn(w),T=this.math.bitsToNumber(v.tick_current_index.fields.bits),I=T-v.tick_spacing*(r||Ys),x=T+v.tick_spacing*(r||Ys);I=I<Js?Js:I,x=x>Xs?Xs:x;let P=this.pool.parsePoolType(na(w));u.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:P,arguments:[u.object(v.id.id),u.pure(h.a2b,"bool"),u.pure(new F(h.amountSpecified).toFixed(0),"u128"),u.pure(n,"bool"),u.pure(this.math.tickIndexToSqrtPriceX64(h.a2b?I:x).toString(),"u128"),u.object(ta.SUI_CLOCK_OBJECT_ID),u.object(o.Versioned)]})});let l=await this.provider.devInspectTransactionBlock({transactionBlock:u,sender:i});if(l.error)throw new Error(l.error);return l.events.map(h=>h.parsedJson)}getFunctionNameAndTypeArguments(t,e,n){let i=[],r=["swap"];if(t.length===1)i=t[0],e===i[0]?r.push("a","b"):r.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(r.push("a","b"),i.push(o[0],o[2],o[1])):(r.push("b","a"),i.push(o[1],o[2],o[0])),i.push(s[2],n),n===s[0]?r.push("c","b"):r.push("b","c")}return{functionName:r.join("_"),typeArguments:i}}amountOutWithSlippage(t,e,n){if(n){let r=new F(100).minus(e).div(100);return new F(t).mul(r).toFixed(0)}let i=new F(100).plus(e).div(100);return new F(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new F(t).mul(n?new F(100).minus(e).div(100):new F(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,i,r);return s.lt(new xu.BN(Su))?Su:s.gt(new xu.BN(Cu))?Cu:s.toString()}},Lt=class{constructor(t,e){this.network=t,On(this,"pool"),On(this,"contract"),On(this,"math",new qb),On(this,"account",new Eb),On(this,"coin"),On(this,"nft"),On(this,"trade"),On(this,"provider"),this.provider=e?e instanceof Ri.SuiClient?e:new Ri.SuiClient(e):new Ri.SuiClient({url:t==="mainnet"?(0,Ri.getFullnodeUrl)("mainnet"):(0,Ri.getFullnodeUrl)("testnet")}),this.contract=new Rb(this),this.pool=new Lb(this),this.nft=new Vb(this),this.coin=new Gb(this),this.trade=new Hb(this)}};var Zb=Object.defineProperty,vm=(t,e)=>{for(var n in e)Zb(t,n,{get:e[n],enumerable:!0})},ve=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Cm.default)(this.data))}},Ku={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"},Ht={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Dn=new cr(Ku),Xb=async(t,e,n)=>(console.log("getAddLiquidityTxb suiClient: ",n),console.log("getAddLiquidityTxb txbParams: ",t),Dn.senderAddress=e.address,await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Jb=async(t,e,n)=>(console.log("getIncreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,console.log("getIncreaseLiquidityTxb txbParams: ",t),await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Yb=async(t,e,n)=>(console.log("getRemoveLiquidityTxb txbParams: ",t),console.log("getRemoveLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.closePositionTransactionPayload(t)),Qb=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb txbParams: ",t),console.log("getDecreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.removeLiquidityTransactionPayload(t)),ev=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb txbParams: ",t),console.log("getClaimFeeAndMiningTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Rewarder.collectRewarderTransactionPayload(t)),tv=class Sm extends ve{constructor(e){super(e),this.data=e}txType=Tm.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("AddLiquidityIntention this.data: ",this.data),console.log("AddLiquidityIntention txbParams: ",r);let o=await Xb(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Sm(e)}},nv=class xm extends ve{constructor(e){super(e),this.data=e}txType=Am.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("ClaimFeeAndMiningIntention this.data: ",this.data),console.log("ClaimFeeAndMiningIntention txbParams: ",r);let o=await ev(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new xm(e)}},iv=class Om extends ve{constructor(e){super(e),this.data=e}txType=Im.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("DecreaseLiquidityIntention this.data: ",this.data),console.log("DecreaseLiquidityIntention txbParams: ",r);let o=await Qb(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Om(e)}},xt=new cr(Ku),rv=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.openPositionAddLiquidityStakePaylod(t)),ov=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.addLiquidityFixCoinPayload(t)),sv=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),av=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),cv=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.claimFeeAndClmmReward(t)),uv=async(t,e,n)=>{console.log("getFarmingHarvest account: ",e),console.log("getFarmingHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt);return console.log("getFarmingHarvest txbParams: ",t),await i.Farms.harvestPayload(t)},lv=async(t,e,n)=>{console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt),r=Object.values(t);return console.log("getFarmingBatchHarvest params: ",r),await i.Farms.batchHarvestPayload(r)},dv=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.depositPayload(t)),fv=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.withdrawPayload(t)),hv=class Dm extends ve{constructor(e){super(e),this.data=e}txType=Pm.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingAddLiquidityIntention this.data: ",this.data),console.log("FarmingAddLiquidityIntention txbParams: ",r);let o=await rv(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new Dm(e)}},mv=class Mm extends ve{constructor(e){super(e),this.data=e}txType=Em.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingBatchHarvestIntention this.data: ",this.data),console.log("FarmingBatchHarvestIntention txbParams: ",r);let o=await lv(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Mm(e)}},pv=class jm extends ve{constructor(e){super(e),this.data=e}txType=Bm.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingClaimFeeAndRewardIntention this.data: ",this.data),console.log("FarmingClaimFeeAndRewardIntention txbParams: ",r);let o=await cv(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new jm(e)}},gv=class Nm extends ve{constructor(e){super(e),this.data=e}txType=Fm.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingDecreaseLiquidityIntention this.data: ",this.data),console.log("FarmingDecreaseLiquidityIntention txbParams: ",r);let o=await sv(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Nm(e)}},_v=class qm extends ve{constructor(e){super(e),this.data=e}txType=Rm.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingHarvestIntention this.data: ",this.data),console.log("FarmingHarvestIntention txbParams: ",r);let o=await uv(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new qm(e)}},yv=class $m extends ve{constructor(e){super(e),this.data=e}txType=Lm.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingIncreaseLiquidityIntention this.data: ",this.data),console.log("FarmingIncreaseLiquidityIntention txbParams: ",r);let o=await ov(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new $m(e)}},wv=class Km extends ve{constructor(e){super(e),this.data=e}txType=Um.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingRemoveLiquidityIntention this.data: ",this.data),console.log("FarmingRemoveLiquidityIntention txbParams: ",r);let o=await av(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Km(e)}},bv=class Vm extends ve{constructor(e){super(e),this.data=e}txType=zm.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingStakeIntention this.data: ",this.data),console.log("FarmingStakeIntention txbParams: ",r);let o=await dv(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new Vm(e)}},vv=class Wm extends ve{constructor(e){super(e),this.data=e}txType=Gm.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingUnstakeIntention this.data: ",this.data),console.log("FarmingUnstakeIntention txbParams: ",r);let o=await fv(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new Wm(e)}},kv=class Zm extends ve{constructor(e){super(e),this.data=e}txType=Hm.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("IncreaseLiquidityIntention this.data: ",this.data),console.log("IncreaseLiquidityIntention txbParams: ",r);let o=await Jb(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Zm(e)}},Tv=class Jm extends ve{constructor(e){super(e),this.data=e}txType=Xm.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("RemoveLiquidityIntention this.data: ",this.data),console.log("RemoveLiquidityIntention txbParams: ",r);let o=await Yb(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Jm(e)}},En=new cr(Ku),Cv=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.convertPayload(t)),Sv=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemLockPayload(t)),Av=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemDividendV2Payload(t.venft_id,t.bonus_types,t.xTokenType)),xv=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.cancelRedeemPayload(t)),Iv=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemPayload(t)),Ov=class Qm extends ve{constructor(e){super(e),this.data=e}txType=Ym.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusCancelIntention this.data: ",this.data),console.log("XcetusCancelIntention txbParams: ",r);let o=await xv(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Qm(e)}},Pv=class tp extends ve{constructor(e){super(e),this.data=e}txType=ep.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusClaimingStakeRewardsIntention this.data: ",this.data),console.log("XcetusClaimingStakeRewardsIntention txbParams: ",r);let o=await Av(r,n,i);return console.log("XcetusClaimingStakeRewardsIntention build txb: ",o),o}static fromData(e){return new tp(e)}},Dv=class ip extends ve{constructor(e){super(e),this.data=e}txType=np.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusConvertIntention this.data: ",this.data),console.log("XcetusConvertIntention txbParams: ",r);let o=await Cv(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new ip(e)}},Ev=class op extends ve{constructor(e){super(e),this.data=e}txType=rp.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemIntention this.data: ",this.data),console.log("XcetusRedeemIntention txbParams: ",r);let o=await Iv(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new op(e)}},Mv=class ap extends ve{constructor(e){super(e),this.data=e}txType=sp.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemLockIntention this.data: ",this.data),console.log("XcetusRedeemLockIntention txbParams: ",r);let o=await Sv(r,n,i);return console.log("XcetusRedeemLockIntention build txb: ",o),o}static fromData(e){return new ap(e)}},Bv=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:km.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let i;switch(t.txSubType){case"OpenAndAddLiquidity":i=tv.fromData(t.intentionData);break;case"IncreaseLiquidity":i=kv.fromData(t.intentionData);break;case"DecreaseLiquidity":i=iv.fromData(t.intentionData);break;case"RemoveLiquidity":i=Tv.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=nv.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=hv.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=yv.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=gv.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=wv.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=pv.fromData(t.intentionData);break;case"FarmingHarvest":i=_v.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=mv.fromData(t.intentionData);break;case"FarmingStake":i=bv.fromData(t.intentionData);break;case"FarmingUnstake":i=vv.fromData(t.intentionData);break;case"xCETUSConvert":i=Dv.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=Mv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=Pv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=Ov.fromData(t.intentionData);break;case"xCETUSRedeem":i=Ev.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",i),i.build({suiClient:e,account:n})}},up={};vm(up,{contractId:()=>fp,default:()=>jv,feeObjId:()=>pp,roleObjId:()=>hp,status:()=>dp,transaction:()=>lp,upgradeCapObjId:()=>gp,vaultObjId:()=>mp});var lp="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",dp="success",fp="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",hp="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",mp="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",pp="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",gp="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",jv={transaction:lp,status:dp,contractId:fp,roleObjId:hp,vaultObjId:mp,feeObjId:pp,upgradeCapObjId:gp},_p={};vm(_p,{contractId:()=>bp,default:()=>Fv,feeObjId:()=>Tp,roleObjId:()=>vp,status:()=>wp,transaction:()=>yp,upgradeCapObjId:()=>Cp,vaultObjId:()=>kp});var yp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",wp="success",bp="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",vp="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",kp="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Tp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Cp="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fv={transaction:yp,status:wp,contractId:bp,roleObjId:vp,vaultObjId:kp,feeObjId:Tp,upgradeCapObjId:Cp},Nv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Rv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",qv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Lv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$v="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Uv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Kv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",zv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Xh=up,Jh=_p,Vv=new Map([["dev",{env:"dev",rpc:{url:Nv},backend:{url:$v},contract:Xh}],["stg",{env:"stg",rpc:{url:Rv},backend:{url:Uv},contract:Xh}],["prev",{env:"prev",rpc:{url:qv},backend:{url:Kv},contract:Jh}],["prod",{env:"prod",rpc:{url:Lv},backend:{url:zv},contract:Jh}]]);function Gv(t,e){let n=Vv.get(t);if(!n)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(n.rpc=e.rpc),e&&e.backend&&(n.backend=e.backend),e&&e.contract&&(n.contract=e.contract),n}var nn=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:i,context:r}=n;i?super(`[MPay] ${e}: ${i}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}},Wv=class extends nn{constructor(){super(11,"Backend is not specified")}},Hv=class extends nn{constructor(){super(1,"Wallet not connected")}},Ou=class extends nn{constructor(t,e){super(10,t,{context:e})}},Zv=class $i{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof zn.AxiosError)throw new Ou(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Ou(e.data.code)}throw new Ou(e.status.toString())}async getIncomingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return $i.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{sender:e,...n});return $i.parseResponseData(i)}async getStreamHistory(e){let n=await zn.default.post(`${this.apiURL}/stream-events`,e),i=$i.parseResponseData(n);return i.data.forEach(r=>{let o=r;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}),i}async getAllCoinTypes(e){let n=await zn.default.post(`${this.apiURL}/stream-info`,{address:e});return $i.parseResponseData(n)}async getAllRecipients(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return $i.parseResponseData(i)}async getAllSenders(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return $i.parseResponseData(i)}},Ap=class xp{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Sp.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Zv(e.backend.url))}static new(e,n){let i=Gv(e,n);return new xp(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Wv;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 Hv;return this.signer}async walletAddress(){return this.wallet.address()}},Yh=50n,Pu=10000n,Xv=25n,Qh=100000000n,qi=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},em=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ca=class Ip{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(n,i){if(i in n)return Reflect.get(n,i);let r=s=>new Ip(n.result[s]);if(i===Symbol.iterator)return function*(){let s=0;for(;;)yield r(s),s++};if(typeof i=="symbol")return;let o=parseInt(i,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}},tm=class extends nn{constructor(t,e){super(3,t,{context:e})}},Jv=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 n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="address")throw new tm("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,Op.normalizeSuiAddress)(Mu.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new tm("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Mu.Buffer.from(n).readBigInt64LE()}},tn=class extends nn{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},Pp={groupId:"string",name:"string"},Yv=64;function Qv(t){return Dp(t),zu.bcs.ser(Pp,t).toString("base64")}function Bu(t){let e=zu.bcs.de(Pp,t,"base64");return Dp(e),e}function Dp(t){if(!nm(t.name))throw new tn("Invalid metadata: Name contains unknown character");if(!nm(t.groupId))throw new tn("Invalid metadata: Group ID contains unknown character");if(t.name.length>Yv)throw new tn("Invalid metadata: Name exceed max length 64")}function nm(t){return/^[\x00-\x7F]+$/.test(t)}function Ep(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}function Pr(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}var Mp="txn.gas";function e1(){return yf()}var ju=class Bp{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:Qv({name:e.name,groupId:e1()}),coinType:(0,Po.normalizeStructTag)(e.coinType),recipients:e.recipients.map(n=>({address:n.address,cliffAmount:n.cliffAmount,amountPerEpoch:n.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let n=new Eu.TransactionBlock,i=this.calculateFeesInternal(e),r=this.getCreateStreamCoinRequests(e,i),o=await this.wallet.requestCoins(r),s=await this.addMergeCoins(n,o[0]),a;r.length>1?a=await this.addMergeCoins(n,o[1]):a=s;for(let u=0;u<e.recipients.length;u++){let l=e.recipients[u],h=this.amountForRecipient(l,e.numberEpoch),w=this.getStreamFeeLocal(h),[v]=n.splitCoins(s,[n.pure(h+w,"u64")]),[T]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new ca(v),flatFeeCoin:new ca(T),metadata:e.metadata,recipient:l.address,timeStart:e.startTime,cliff:l.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return n}calculateCreateStreamFees(e){let n=Bp.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Yh,denominator:Pu},claimFeePercent:{numerator:Xv,denominator:Pu},flatFeePerStream:Qh}}async addMergeCoins(e,n){let i;return n.mergedCoins&&n.mergedCoins.length?(e.mergeCoins(e.object(n.primaryCoin),n.mergedCoins.map(r=>e.object(r))),i=e.object(n.primaryCoin)):n.primaryCoin===Mp?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return Ep(i,Po.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Po.SUI_TYPE_ARG,amount:n.flatFeeAmount}]}calculateFeesInternal(e){let n=e.recipients.reduce((i,r)=>{let o=this.amountForRecipient(r,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:i.totalAmount+o,streamFeeAmount:i.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...n}}amountForRecipient(e,n){return BigInt(e.amountPerEpoch)*BigInt(n)+BigInt(e.cliffAmount)}get flatSuiFee(){return Qh}getStreamFeeLocal(e){return e*Yh/Pu}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new Eu.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new Jv(i).getU64()}get wallet(){return this.globals.wallet}},t1="0x0000000000000000000000000000000000000000000000000000000000000006",jp=class{constructor(t,e,n){this.moduleName=t,this.config=e,this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Fu.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof em?i.moveArgs(t):i instanceof qi?i.moveArg(t):i instanceof ca?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(Fu.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof em?r.moveArgs(t):r instanceof qi?r.moveArg(t):r instanceof ca?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new qi(t):t}vaultObject(){return new qi(this.config.vaultObjId)}roleObject(){return new qi(this.config.roleObjId)}feeObject(){return new qi(this.config.feeObjId)}clockObject(){return new qi(t1)}},Fp=class di extends jp{constructor(e,n){super(di.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_flat_fee,arguments:[i,r,n],typeArgs:[]})}setClaimFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:di.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:di.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:di.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},la=class jt extends jp{constructor(e,n){super(jt.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.feeObject(),r=this.vaultObject(),o=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),a=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.create_stream,arguments:[i,r,o,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,a],typeArgs:[n.coinType]})}setAutoClaim(e,n){let i=this.makeObject(n.streamId);return this.addContractCall(e,{method:jt.MethodName.set_auto_claim,arguments:[i,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.cancel_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.claim_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let i=this.makeObject(n.streamId),r=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:jt.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream_by_proxy}`}},Np=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Fp(e,t),this.streamContract=new la(e,t)}feeContract;streamContract;async createStreams(t){let e=ju.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new ju(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new Io.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},kn=class extends nn{constructor(t,e={}){super(0,t,e)}};async function n1(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var i1=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)}},Rp=class{constructor(t){this.requester=t,this.pager=new i1(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]}},r1=class extends nn{constructor(t,e,n){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:n}}),this.coinType=t,this.requestAmount=e,this.gotAmount=n}},o1=25;async function s1(t,e,n,i="0x2::sui::SUI",r=o1){let o=new a1(t,e,i,r),s=BigInt(0),a=[];for(;await o.hasNext()&&s<n;){let u=await o.next();u&&(a.push(u),s+=BigInt(u.balance))}if(s<n)throw new r1(i,n,s);return a}var a1=class extends Rp{constructor(t,e,n,i){super(new c1(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},c1=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new kn("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}}},u1=class extends nn{constructor(){super(7,"Connected wallet is not creator")}},im=class extends nn{constructor(){super(8,"Connected wallet is not recipient")}},rm=class extends nn{constructor(t,e){super(6,t,{context:e})}},l1=class extends nn{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},d1=(1n<<64n)-1n,ua=1e3;function om(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return be.fromMillis(n*ua)}function sm(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return Pe.fromMillis(n*ua)}var Vu=class fi{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new la(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await fi.fetchStreamData(e,n);return new fi(e,n,i)}static fromObjectData(e,n,i){let r=fi.parseRawStreamData(n,i);return new fi(e,n,r)}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 fi.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new kn("Object Id does not align");this.rawData=fi.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 u1;let e=new Oo.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new im;let e=new Oo.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 im;let n=new Oo.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new Oo.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,Eo.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 sm(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Bu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Bu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return om(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return sm(n)}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:om((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===d1?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=be.now().toMillis(),n=this.timeStart.toMillis();if(e<n)return-1n;let i=Math.floor((e-n)/Number(this.rawData.config.epochInterval));return BigInt(i)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(i)}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,n){let i=await e.suiClient.getObject({id:n,options:{showContent:!0,showType:!0}});return fi.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new l1(e):new rm(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new rm("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Eo.parseStructTag)(i.type),o=(0,Eo.normalizeStructTag)(r[0]),s=i.fields,a=s.config.fields,u=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(a.amount_per_epoch),cancelable:a.cancelable,cliff:BigInt(a.cliff),creator:a.creator,epochInterval:BigInt(a.epoch_interval),metadata:a.metadata,recipient:a.recipient,timeStart:BigInt(a.time_start),totalEpoch:BigInt(a.total_epoch)},status:{status:u.status,epochCanceled:BigInt(u.epoch_canceled),epochClaimed:BigInt(u.epoch_claimed)}}}},f1=class extends nn{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},h1=1e3,m1=class{constructor(t){this.globals=t,this.coinMetaHelper=new p1(t.suiClient),this.createStreamHelper=new Np(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new f1(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 tn("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,i=(t.totalAmount-n)/t.steps,r={realTotalAmount:i*t.steps+n,cliffAmount:n,amountPerStep:i};return this.validateStreamAmount(r,t.totalAmount),r}calculateTimelineByInterval(t){if(t.steps===0n)throw new tn("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new tn("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(Pe.fromMillis(Number(e*t.steps))),i={timeStart:t.timeStart,timeEnd:n,interval:Pe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(i),i}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),i=await this.getCoinMeta(e);return{...n,coinType:(0,Mr.normalizeStructTag)(n.coinType),coinMeta:i}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(i=>this.getCoinMeta(i.coinType)));return e.map((i,r)=>({...i,coinType:(0,Mr.normalizeStructTag)(i.coinType),coinMeta:n[r]}))}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 tn("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new tn("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<h1)throw new tn("Interval shall be at least 1 second","interval",t.interval)}},p1=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Mr.normalizeStructTag)(t||Mr.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},Du=class extends nn{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}},g1=25;async function am(t,e,n){let i=new qp(e),r=new Lp(t,i,n);return await n1(r)}var qp=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]}},Lp=class extends Rp{constructor(t,e,n){super(new _1(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},_1=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||g1,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&t.push(i)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:i}=this;n=e.filter(r=>i?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}},y1=class ra{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new Du("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new tn("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await am(e.suiClient,n);return i.forEach(r=>{if(!r)throw new kn("stream group object data undefined")}),ra.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await ra.parseGroupStreams(e,n,i);return new ra(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{w1(i,o)||(r=!1)}),r}async refresh(){let e=await am(this.globals.suiClient,this.streams.map(n=>n.streamId));this.streams.forEach((n,i)=>{n.refreshWithData(e[i])})}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,n)=>e+n.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,n)=>e+n.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,n)=>n.nextReleaseAmount===null?e:e+n.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,n)=>e+n.totalAmount,0n),streamed:this.streams.reduce((e,n)=>e+n.streamedAmount,0n),claimed:this.streams.reduce((e,n)=>e+n.claimedAmount,0n),claimable:this.streams.reduce((e,n)=>e+n.claimable,0n),canceled:this.streams.reduce((e,n)=>e+n.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,n,i){let r=i.map((o,s)=>Vu.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new Du("Not same group ID");if(!this.checkStreamGroup(r))throw new Du("Not same stream settings");return r}};function w1(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 cm=class Nu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await um.newIncoming(e);return new Nu(n,e.pageSize)}static async newOutgoing(e){let n=await um.newOutgoing(e);return new Nu(n,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}},um=class Ru{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await lm.newIncomingQuery(e);return new Ru(n)}static async newOutgoing(e){let n=await lm.newOutgoingQuery(e);return new Ru(n)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let n=await this.requester.doNextRequest();if(n===null)throw new kn("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new kn("No more results");return e}},lm=class qu{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new qp(i.flat().map(s=>s.streamId));this.objectIter=new Lp(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=C1(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,gi.normalizeSuiAddress)(s.recipient)===(0,gi.normalizeSuiAddress)(i)),o=dm(r);return new qu(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=S1(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=dm(r);return new qu(e.globals,i,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let n=await k1(this.globals,e[0].streamId,this.objectIter);return this.current++,$p(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await T1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,v1(n,this.query)?n:this.doNextRequest()}throw new kn("Stream group with no stream")}};function dm(t){let e=new Map;return t.forEach(n=>{let i=e.get(n.groupId);i?(i.push(n),e.set(n.groupId,i)):e.set(n.groupId,[n])}),Array.from(e.values()).sort((n,i)=>be.fromISO(i[0].createDate).toMillis()-be.fromISO(n[0].createDate).toMillis())}function $p(t,e){if(e===void 0)return!0;let n=b1(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let i=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return n&&i}return n}function b1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function v1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{$p(i,e)&&(n=!0)}),n}async function k1(t,e,n){let i=await Up(n,e);return Vu.fromObjectData(t,e,i)}async function T1(t,e,n){let i=[];for(;i.length<e.length;){let r=await Up(n,e[i.length]);i.push(r)}return y1.newFromObjectResponse(t,e,i)}async function Up(t,e){if(!await t.hasNext())throw new kn("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new kn("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new kn("stream id not aligned");return n}function C1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),sender:zp(t?.sender)}}function S1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),recipient:zp(t?.recipient)}}function Gu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=Gu(n);return!e||e===i?i:"all"},void 0):A1(t)}function A1(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new tn("Unknown stream filtered status")}}function Kp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeStructTag)(e)):void 0:(0,gi.normalizeStructTag)(t)}function zp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeSuiAddress)(e)):void 0:(0,gi.normalizeSuiAddress)(t)}var x1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},I1=class{constructor(t){this.account=t}async address(){return this.account.address}},O1=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(Ep(t.coinType,Ki.SUI_TYPE_ARG))return{primaryCoin:Mp};if(t.amount<=0)throw new tn("Invalid coin request","coinAmount",t.amount);let e=await s1(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new kn("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},P1=class{globals;helper;constructor(t,e){this.globals=Ap.new(t,e),this.helper=new m1(this.globals)}connectSingleWallet(t){let e=new O1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new x1(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return Vu.new(this.globals,t)}async getIncomingStreams(t,e=10){return cm.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return cm.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,Ki.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new Np(this.globals)}},D1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Vp.default)(this.data))}},Mo=class extends D1{application="mpay";getClient(t,e){let n=new P1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new I1(e)),n}},fm=class extends Mo{constructor(t){super(t),this.data=t}txType=cp.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},hm=class extends Mo{constructor(t){super(t),this.data=t}txType=Gp.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},mm=class extends Mo{constructor(t){super(t),this.data=t}txType=Wp.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},pm=class extends Mo{constructor(t){super(t),this.data=t}txType=Hp.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Zp=class oa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return oa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return oa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,hi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return oa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}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,hi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,hi.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,hi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,hi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,hi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},E1=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"&&Pr(e.target,this.contract.createStreamTarget));if(t.length===0)throw new kn("No create stream transactions");return t.map(e=>new Zp(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Bu(e),r=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),a=t.decodeInputU64(8),u=t.decodeInputU64(9),l=t.decodeInputU64(10),h=t.decodeInputBool(11),w=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:u,amountPerEpoch:l,cancelable:h,coinType:w}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new tn("Stream group not have common info");let e=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 la(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Fp(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ju(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]}},M1=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new la(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"&&Pr(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new E1(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 Zp(t,this.txb)}},gm=class extends Mo{constructor(t){super(t),this.data=t}txType=Xp.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},B1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=Ap.new(e==="sui:mainnet"?"prod":"dev"),r=new M1(i,n).decode(),o;switch(r.type){case"CreateStream":o=new pm(r.info);break;case"SetAutoClaim":o=new gm({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new mm({streamId:r.streamId});break;case"ClaimByProxy":o=new hm({streamId:r.streamId});break;case"Cancel":o=new fm({streamId:r.streamId});break;default:throw new Error(`Unknown transaction type: ${r}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new pm(e);break;case"Claim":n=new mm(e);break;case"ClaimByProxy":n=new hm(e);break;case"SetAutoClaim":n=new gm(e);break;case"Cancel":n=new fm(e);break;default:throw new Error("not implemented")}return n.build({...t})}},j1=class Yp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Jp.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Yp(e)}},F1=class eg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Qp.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new eg(e)}},N1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=ng.TransactionBlock.from(this.data.content);if(!(0,tg.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new ig(e)}},R1=class{application;constructor(){this.application=Er.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case Er.TransactionSubTypes.assets.coin.send:i=j1.fromData(t.intentionData);break;case Er.TransactionSubTypes.assets.object.send:i=F1.fromData(t.intentionData);break;case Er.TransactionSubTypes.others.plain:i=N1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},q1={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"}}},ye=q1,L1=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(`${ye.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ye.pool).find(n=>n.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===`${ye.ProtocolPackage}::incentive_v2::claim_reward`){let n=new _m(e,this.txb),i=n.decodeInputU8(4),r=n.decodeInputU8(5),o=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(i),a=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:a,assetId:i,poolId:o})}}),console.log("decode claims",t),{txType:Dr.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ye.ProtocolPackage));return new _m(t,this.txb)}},_m=class sa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return sa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return sa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,mi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return sa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}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,mi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,mi.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,mi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,mi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,mi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function ym(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function $1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function U1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function wm(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function K1(t,e,n,i,r){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ye.IncentiveV2),t.object(n),t.object(ye.StorageId),t.pure(e),t.pure(i)],typeArguments:r}),t}var z1=class sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new og.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;K1(n,r,o,s,a)}),n}static fromData(e){return new sg(e)}},V1=class cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new ag.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return U1(i,r,n)}static fromData(e){return new cg(e)}};async function lg(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var G1=class dg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new ug.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return ym(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await lg(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return ym(s,a,s.object(l),o)}static fromData(e){return new dg(e)}},W1=class hg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new fg.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return wm(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await lg(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return wm(s,a,s.object(l),o)}static fromData(e){return new hg(e)}},H1=class pg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new mg.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return $1(i,r,n)}static fromData(e){return new pg(e)}},Z1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new L1(e).decode();return{txType:rg.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=G1.fromData(t.intentionData);break;case"EntryBorrow":i=V1.fromData(t.intentionData);break;case"EntryRepay":i=W1.fromData(t.intentionData);break;case"EntryWithdraw":i=H1.fromData(t.intentionData);break;case"ClaimReward":i=z1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},X1="msafe-plain-tx",J1=da.TransactionSubTypes.others.plain,Y1=class{application;constructor(){this.application=X1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:da.TransactionType.Other,txSubType:J1,intentionData:{content:(0,fa.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=gg.TransactionBlock.from((0,fa.fromHEX)(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(r.effects.status.status!=="success")throw new Error(r.effects.status.error);return i}},Q1=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}},Li={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},ek=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(t){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeLiquidityTransaction())return this.decodeCollectFeeLiquidity();if(this.isCollectRewardLTransaction())return this.decodeCollectRewardLiquidity();if(this.isBurnTransaction())return this.decodeBurnLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect`)}isCollectRewardLTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::burn`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),i=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),o=this.helper.decodeInputBool(5),s=this.helper.decodeInputU32(6),a=this.helper.decodeInputBool(7);return{txType:Ui.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:o?-r:r,tickUpper:a?-s:s}}}decodeIncreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),i=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6);return{txType:Ui.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:5,address:t,amountA:i,amountB:r,nft:n}}}decodeDecreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),o=this.helper.decodeInputU64(5);return{txType:Ui.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,decreaseLiquidity:i,nft:n,amountA:r,amountB:o,slippage:3,address:t}}}decodeCollectFeeLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4);return{txType:Ui.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:i,collectAmountB:r,nft:e}}}decodeCollectRewardLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),i=this.collectRewardHelper.map(r=>r.decodeInputU64(5));return{txType:Ui.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:i,nft:e}}}decodeBurnLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:Ui.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new bm(t,this.txb)}get collectRewardHelper(){console.log(this.transactions,"this.transactions");let t=this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${Li.PackageId}::position_manager::collect_reward`);return console.log(t,this.txb,"this.txb"),t.map(e=>new bm(e,this.txb))}},bm=class aa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return aa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return aa.getOwnedObjectId(n)}decodeInputU128(e){let n=this.decodePureArg(e,"u128");return Number(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU32(e){let n=this.decodePureArg(e,"u32");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,pi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return aa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}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,pi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,pi.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,pi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,pi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,pi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},tk=class yg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:u,tickUpper:l,deadline:h,txb:w}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,deadline:h,txb:w})}static fromData(e){return new yg(e)}},nk=class wg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,nft:r,txb:o}=this.data;return n.nft.burn({pool:i,nft:r,txb:o})}static fromData(e){return new wg(e)}},ik=class bg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,deadline:u,txb:l}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,deadline:u,txb:l})}static fromData(e){return new bg(e)}},rk=class vg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,deadline:a,txb:u}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,deadline:a,txb:u})}static fromData(e){return new vg(e)}},ok=class kg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{fee:i,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,amountA:w,amountB:v,deadline:T,txb:I}=this.data;return n.pool.createPool({fee:i,amountA:w,amountB:v,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,deadline:T,txb:I})}static fromData(e){return new kg(e)}},sk=class Tg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,deadline:h,txb:w}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,deadline:h,txb:w})}static fromData(e){return new Tg(e)}},ak=class Cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,deadline:l,txb:h}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,deadline:l,txb:h})}static fromData(e){return new Cg(e)}},ck=class Sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,collectAmountA:h,collectAmountB:w,rewardAmounts:v,deadline:T,txb:I}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:l,nft:u,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:h,collectAmountB:w,rewardAmounts:v,deadline:T,txb:I})}static fromData(e){return new Sg(e)}},uk=class{application="turbos";async deserialize(t){let{transactionBlock:e,account:n}=t,i=new ek(e).decode(n.address);return{txType:_g.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:i}=t,r;switch(t.txSubType){case"CreatePool":r=ok.fromData(t.intentionData);break;case"AddLiquidity":r=tk.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ak.fromData(t.intentionData);break;case"DecreaseLiquidity":r=sk.fromData(t.intentionData);break;case"RemoveLiquidity":r=ck.fromData(t.intentionData);break;case"CollectFee":r=ik.fromData(t.intentionData);break;case"CollectReward":r=rk.fromData(t.intentionData);break;case"Burn":r=nk.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},ha=new Q1([new R1,new Z1,new B1,new Y1,new Bv,new uk]);var Ae=require("@msafe/sui3-utils"),tl=require("@mysten/sui.js/transactions"),ba=require("@mysten/sui.js/utils");var Ag=require("@mysten/sui.js/transactions"),lk=1000n,dk=120n,fk=100n,hk={multiplier:{numerator:dk,denominator:fk}};var ma=class{constructor(e){this.globals=e}async simulate(e,n=hk){let i=this.copyTransactionBlock(e.txb),{suiClient:r}=this.globals,o=await this.getGasPrice(n);i.setGasPrice(o);let s=await r.devInspectTransactionBlock({transactionBlock:i,sender:e.sender}),{gasUsed:a}=s.effects,u=this.toGasBudget(a,o),l=s.effects.status.status==="success",h;return l||(h=s.effects.status.error),{success:l,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:a,gasBudget:u,simulationError:h}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let n=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(n,e)}toGasBudget(e,n){let{computationCost:i,storageCost:r}=e,o=lk*n,s=BigInt(i)+o,a=s+BigInt(r);return a>s?a:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,n){if(this.isFixedValue(n))return n.fixedVal;if(this.isMultiplier(n)){let{multiplier:i}=n;return e*i.numerator/i.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ag.TransactionBlock.from(e.serialize())}};var Wu=require("buffer");function pa(t){return Wu.Buffer.from(t,"utf-8")}function mk(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ga(t){return Uint8Array.from(Wu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ya=require("@mysten/sui.js/verify");var _i=require("@mysten/sui.js/utils");var _a=require("@mysten/sui.js/utils"),Bo=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,_a.normalizeStructTag)(e);if(this._coinMetaReg.has(n))return this._coinMetaReg.get(n);let i=await this.queryCoinMeta(n);return i&&this._coinMetaReg.set(n,i),i}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Hu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,jo=class t{static isCoin(e){return e?(0,_a.normalizeStructTag)(e).match(Hu)!=null:!1}static getCoinType(e){let[,n]=(0,_a.normalizeStructTag)(e).match(Hu)??[];return n||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:n}=e.content?.fields;if(n!==void 0)return BigInt(n)}};var Vn=class{static normalizeSuiAddress(e){return(0,_i.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,_i.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,_i.normalizeSuiAddress)(e)===(0,_i.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,_i.normalizeStructTag)(e)===(0,_i.normalizeStructTag)(n)}static isCoinObjectType(e){return jo.isCoin(e)}};function Zu(t,e){return t.startsWith(e)?t:e+t}var Xu=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ya.verifyTransactionBlock)(e.message,e.signature):(0,ya.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=pa(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return Vn.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=pa(e.messageStr);return this.verifySignature({message:n,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 xg=require("@msafe/sui3-utils"),Ig=require("@mysten/sui.js/cryptography"),Og=require("@mysten/sui.js/multisig");var pk="0x2::sui::SUI";async function Ju(t,e){let n;try{n=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(n.data.length===0||!n.data[0].transaction?.txSignatures)return;let r=n.data[0].transaction?.txSignatures;for(let o=0;o!==r.length;o++){let s=r[o],a=gk(s,e);if(a)return a}}function gk(t,e){let n=(0,Ig.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new Og.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if(Vn.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Vn.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=xg.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return Vn.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function _k(t){let e=!0,n,i=[];for(;e;){let r=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:n});i.push(...r.data),e=r.hasNextPage,n=r.nextCursor}return i}var Pg=25;async function Dg(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Yu=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)}},wa=class{constructor(e){this.requester=e;this.pager=new Yu(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 Eg(t,e,n){let i=new Qu(t,e,n);return await Dg(i)}var Qu=class extends wa{constructor(n,i,r){super(new el(n,i,r));this.provider=n;this.owner=i;this.options=r}},el=class{constructor(e,n,i){this.provider=e;this.owner=n;this.options=i;this.nextCursor=null,this.filter=i?.filter,this.pageSize=i?.pageSize||Pg,this.objectOptions=i?.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 n;if(this.filter){let{filter:i}=this;n=e.data.filter(r=>i?.(r))}else n=e.data;return{data:n.map(i=>i.data).filter(i=>i),hasNext:e.hasNextPage}}};var zi=class t{constructor(e,n){this.globals=e;this.info=n;this.multiSig=new Ae.MultiSigAccount({threshold:n.threshold,ownersWithWeight:n.owners,creationNonce:n.creationNonce}),this.coinHelper=new Bo(this.suiClient),this.simulator=new ma(e)}multiSig;coinHelper;simulator;static async New(e,n){let i=await e.backend.getMSafeAccountInfo(n);if(new t(e,i).address!==n)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 n=>{let i=await this.coinHelper.getCoinMeta(n.coinType),r=n.lockedBalance.number?BigInt(n.totalBalance)-BigInt(n.lockedBalance.number):BigInt(n.totalBalance);return{type:(0,ba.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return Eg(this.suiClient,this.address,n)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let n=e.pending,i=e.reject;return{application:n.application,txType:n.txType,txSubType:n.txSubType,createdAt:n.createdAt,creator:n.creator,digest:n.digest,intention:n.intention,sequenceNumber:n.sequenceNumber,payload:n.payload,votes:n.votes,approvalWeight:this.calculateWeightFromVotes(n.votes),msafeAddress:n.msafeAddress,rejectDigest:i?.digest??"",rejectPayload:i?.payload??"",rejectVotes:i?.votes??[],rejectWeight:this.calculateWeightFromVotes(i?.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 n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,sender:this.address})}async proposeIntention(e){let n=Ae.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),i=await this.wallet.signPersonalMessage({messageStr:n});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:i.signature})}async proposeIntentionAndBuildVote(e){let n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});i.setGasPrice(e.gasPrice),i.setGasBudget(e.gasBudget),i.setSender(this.address);let r=await i.build({client:this.globals.suiClient}),o=await i.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:r});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,ba.toHEX)(r),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async proposeCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async simulateObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async proposeObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async simulatePlainPayloadIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async proposePlainPayloadIntention(e){let n=await this.nextSequenceNumber(),i=tl.TransactionBlock.from(e.payload);if(!i.blockData.sender||!(0,Ae.isSameAddress)(i.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async voteForTransaction(e,n){let i=ga(n),r=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:r.signature})}async proposePendingTransaction(e){let n=new tl.TransactionBlock,i=await n.build({client:this.suiClient}),r=await n.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:r,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let n=e.payload,i=(0,Ae.buildRejectTxb)(this.address,n);return this.simulator.simulate({txb:i,sender:this.address})}async rejectCurrentTx(e){let n=await this.pendingTransaction();if(!n||n.rejectDigest!=="")throw new Error("Already rejected");let i=n.payload,r=(0,Ae.buildRejectTxb)(this.address,i),o=await r.getDigest({client:this.suiClient}),s=await r.build({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:a.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);console.log("\u{1F680} ~ MSafeAccount ~ simulateBuildTransaction ~ intention:",e);let i=await n.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:i,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,n=!1){let i=n?e.rejectVotes:e.votes,r=n?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(i)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(i.map(u=>[u.userAddress,u.signature]));for(let u=0;u<this.info.owners.length;u++){let l=this.info.owners[u],h=s.get(l.address);h&&o.push(h)}let a=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ga(r),signature:a,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(n=>n.userAddress))}calculateWeight(e){let n=0;for(let i=0;i<e.length;i++){let r=this.info.owners.find(o=>(0,Ae.isSameAddress)(o.address,e[i]));r&&(n+=r.weight)}return n}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 Mg=require("@msafe/sui3-utils"),Bg=require("@mysten/sui.js/utils");var va=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let n=this.knownPublicKeys.get(e);if(n)return n;let i=await this._getPublicKey(e);return i&&this.knownPublicKeys.set(e,i),i}async getPublicKeyBatch(e){let n=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];n[o]=this.knownPublicKeys.get(s)}let i=n.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(i.length===0)return n;let r=await this.globals.backend.getPublicKeyBatch(i.map(o=>e[o]));for(let o=0;o<i.length;o++){let s=i[o];n[s]=r[o]}for(let o=0;o<n.length;o++)n[o]===void 0&&(n[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)n[o]&&this.knownPublicKeys.set(e[o],n[o]);return n}addPublicKey(e,n){if(!(0,Mg.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,Bg.normalizeSuiAddress)(e),n)}async _getPublicKey(e){let n=await this.getPublicKeyFromBackend(e);if(n)return n;let i=await this.getPublicKeyFromChain(e);if(i)return i}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Ju(this.globals.suiClient,e)}};var ka=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var $g=require("@mysten/sui.js/client");var No=require("@msafe/sui3-utils"),Fo=ge(require("axios"),1);var Ta=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let n=await this.post("/auth/login",e);return this._token=n.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 n={userAddressList:e};return(await this.get("/user/public-keys",{params:n,headers:this.headers()})).data?.map(r=>r?No.PublicKeySerde.de(r):void 0)}async getMSafeAccountInfo(e){let n={msafeAddress:e},i=await this.get("/msafe",{params:n,headers:this.headers()});return t.toMSafeConfig(i.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let n={status:e.status??No.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},i=await this.get("/msafe/owned",{params:n,headers:this.headers()});return{data:i.data.data.map(t.toMSafeConfig),meta:i.data.meta}}async updateMSafeStatus(e){let n=e;await this.post("/msafe/status",n,{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(n=>({address:n.address,weight:n.weight,publicKey:No.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Fo.default.get(i,n)}catch(r){throw Ca.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Fo.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw Ca.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Zu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=Fo.default.defaults;return n?n instanceof Array?e=n:e=[n]:e=[],[i=>JSON.parse(JSON.stringify(i,(r,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ca=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(Fo.default.isAxiosError(n)&&n?.response?.data&&"message"in n.response.data)return new t(n)}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 jg=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(jg||{}),Sa="https://fullnode.testnet.sui.io",nl="https://fullnode.mainnet.sui.io",il="http://127.0.0.1:3000",rl="http://127.0.0.1:3001",Fg="https://sui-dev.m-safe.link",Ng="http://13.56.226.148:81",Rg="https://sui-preview.m-safe.link",qg="https://sui.m-safe.link",Lg=new Map([["unit",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["local",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["dev",{suiClient:{url:Sa},backend:{url:Fg},syncingURL:Ng,network:"sui:testnet"}],["prev",{suiClient:{url:nl},backend:{url:Rg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:nl},backend:{url:qg},syncingURL:"",network:"sui:mainnet"}]]);function ol(t,e){let n=Lg.get(t);if(!n)throw new Error("Unknown environment");return e?.suiClient?.url&&(n.suiClient.url=e.suiClient.url),e?.backend?.url&&(n.backend.url=e.backend.url),n}var Ro=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,n){let i=ol(e,n),r=new $g.SuiClient(i.suiClient),o=new Ta(i.backend.url);return new t({backend:o,suiClient:r,config:i})}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 Aa=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await Ro.New(e,n);return new t(i)}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 n=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(n),n}async authSign(e){let n=xa.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),i=await e.signPersonalMessage({messageStr:n});return this.backend.authSign({address:await e.address(),message:n,signature:i.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:xa.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new zi(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new zi(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Gi(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new va(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 Wi(this.globals)}get Invitation(){return new $o(this.globals)}get Report(){return new ka(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2054
2054
|
/*! Bundled license information:
|
|
2055
2055
|
|
|
2056
2056
|
@syntsugar/cc-graph/dist/index.umd.js:
|