@msafe/sui-app-store 0.0.268 → 0.0.269
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Dp=Object.create;var Fn=Object.defineProperty;var Ap=Object.getOwnPropertyDescriptor;var Op=Object.getOwnPropertyNames;var Mp=Object.getPrototypeOf,Pp=Object.prototype.hasOwnProperty;var Rp=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Lr=(a,e)=>{for(var t in e)Fn(a,t,{get:e[t],enumerable:!0})},ec=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Op(e))!Pp.call(a,o)&&o!==t&&Fn(a,o,{get:()=>e[o],enumerable:!(n=Ap(e,o))||n.enumerable});return a};var jt=(a,e,t)=>(t=a!=null?Dp(Mp(a)):{},ec(e||!a||!a.__esModule?Fn(t,"default",{value:a,enumerable:!0}):t,a)),Bp=a=>ec(Fn({},"__esModule",{value:!0}),a);var ep=Rp((tp,Ps)=>{"use strict";(function(a,e){"use strict";function t(y,r){if(!y)throw new Error(r||"Assertion failed")}function n(y,r){y.super_=r;var u=function(){};u.prototype=r.prototype,y.prototype=new u,y.prototype.constructor=y}function o(y,r,u){if(o.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((r==="le"||r==="be")&&(u=r,r=10),this._init(y||0,r||10,u||"be"))}typeof a=="object"?a.exports=o:e.BN=o,o.BN=o,o.wordSize=26;var i;try{typeof window<"u"&&typeof window.Buffer<"u"?i=window.Buffer:i=require("buffer").Buffer}catch{}o.isBN=function(r){return r instanceof o?!0:r!==null&&typeof r=="object"&&r.constructor.wordSize===o.wordSize&&Array.isArray(r.words)},o.max=function(r,u){return r.cmp(u)>0?r:u},o.min=function(r,u){return r.cmp(u)<0?r:u},o.prototype._init=function(r,u,m){if(typeof r=="number")return this._initNumber(r,u,m);if(typeof r=="object")return this._initArray(r,u,m);u==="hex"&&(u=16),t(u===(u|0)&&u>=2&&u<=36),r=r.toString().replace(/\s+/g,"");var p=0;r[0]==="-"&&(p++,this.negative=1),p<r.length&&(u===16?this._parseHex(r,p,m):(this._parseBase(r,u,p),m==="le"&&this._initArray(this.toArray(),u,m)))},o.prototype._initNumber=function(r,u,m){r<0&&(this.negative=1,r=-r),r<67108864?(this.words=[r&67108863],this.length=1):r<4503599627370496?(this.words=[r&67108863,r/67108864&67108863],this.length=2):(t(r<9007199254740992),this.words=[r&67108863,r/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),u,m)},o.prototype._initArray=function(r,u,m){if(t(typeof r.length=="number"),r.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(r.length/3),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h,b,T=0;if(m==="be")for(p=r.length-1,h=0;p>=0;p-=3)b=r[p]|r[p-1]<<8|r[p-2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);else if(m==="le")for(p=0,h=0;p<r.length;p+=3)b=r[p]|r[p+1]<<8|r[p+2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);return this._strip()};function c(y,r){var u=y.charCodeAt(r);if(u>=48&&u<=57)return u-48;if(u>=65&&u<=70)return u-55;if(u>=97&&u<=102)return u-87;t(!1,"Invalid character in "+y)}function l(y,r,u){var m=c(y,u);return u-1>=r&&(m|=c(y,u-1)<<4),m}o.prototype._parseHex=function(r,u,m){this.length=Math.ceil((r.length-u)/6),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h=0,b=0,T;if(m==="be")for(p=r.length-1;p>=u;p-=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8;else{var f=r.length-u;for(p=f%2===0?u+1:u;p<r.length;p+=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8}this._strip()};function d(y,r,u,m){for(var p=0,h=0,b=Math.min(y.length,u),T=r;T<b;T++){var f=y.charCodeAt(T)-48;p*=m,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<m,"Invalid character"),p+=h}return p}o.prototype._parseBase=function(r,u,m){this.words=[0],this.length=1;for(var p=0,h=1;h<=67108863;h*=u)p++;p--,h=h/u|0;for(var b=r.length-m,T=b%p,f=Math.min(b,b-T)+m,s=0,g=m;g<f;g+=p)s=d(r,g,g+p,u),this.imuln(h),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s);if(T!==0){var D=1;for(s=d(r,g,r.length,u),g=0;g<T;g++)D*=u;this.imuln(D),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s)}this._strip()},o.prototype.copy=function(r){r.words=new Array(this.length);for(var u=0;u<this.length;u++)r.words[u]=this.words[u];r.length=this.length,r.negative=this.negative,r.red=this.red};function S(y,r){y.words=r.words,y.length=r.length,y.negative=r.negative,y.red=r.red}if(o.prototype._move=function(r){S(r,this)},o.prototype.clone=function(){var r=new o(null);return this.copy(r),r},o.prototype._expand=function(r){for(;this.length<r;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},o.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{o.prototype.inspect=w}else o.prototype.inspect=w;function w(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],C=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],x=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(r,u){r=r||10,u=u|0||1;var m;if(r===16||r==="hex"){m="";for(var p=0,h=0,b=0;b<this.length;b++){var T=this.words[b],f=((T<<p|h)&16777215).toString(16);h=T>>>24-p&16777215,p+=2,p>=26&&(p-=26,b--),h!==0||b!==this.length-1?m=I[6-f.length]+f+m:m=f+m}for(h!==0&&(m=h.toString(16)+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(r===(r|0)&&r>=2&&r<=36){var s=C[r],g=x[r];m="";var D=this.clone();for(D.negative=0;!D.isZero();){var O=D.modrn(g).toString(r);D=D.idivn(g),D.isZero()?m=O+m:m=I[s-O.length]+O+m}for(this.isZero()&&(m="0"+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}t(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var r=this.words[0];return this.length===2?r+=this.words[1]*67108864:this.length===3&&this.words[2]===1?r+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-r:r},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(r,u){return this.toArrayLike(i,r,u)}),o.prototype.toArray=function(r,u){return this.toArrayLike(Array,r,u)};var v=function(r,u){return r.allocUnsafe?r.allocUnsafe(u):new r(u)};o.prototype.toArrayLike=function(r,u,m){this._strip();var p=this.byteLength(),h=m||Math.max(1,p);t(p<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var b=v(r,h),T=u==="le"?"LE":"BE";return this["_toArrayLike"+T](b,p),b},o.prototype._toArrayLikeLE=function(r,u){for(var m=0,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m++]=T&255,m<r.length&&(r[m++]=T>>8&255),m<r.length&&(r[m++]=T>>16&255),b===6?(m<r.length&&(r[m++]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m<r.length)for(r[m++]=p;m<r.length;)r[m++]=0},o.prototype._toArrayLikeBE=function(r,u){for(var m=r.length-1,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m--]=T&255,m>=0&&(r[m--]=T>>8&255),m>=0&&(r[m--]=T>>16&255),b===6?(m>=0&&(r[m--]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m>=0)for(r[m--]=p;m>=0;)r[m--]=0},Math.clz32?o.prototype._countBits=function(r){return 32-Math.clz32(r)}:o.prototype._countBits=function(r){var u=r,m=0;return u>=4096&&(m+=13,u>>>=13),u>=64&&(m+=7,u>>>=7),u>=8&&(m+=4,u>>>=4),u>=2&&(m+=2,u>>>=2),m+u},o.prototype._zeroBits=function(r){if(r===0)return 26;var u=r,m=0;return u&8191||(m+=13,u>>>=13),u&127||(m+=7,u>>>=7),u&15||(m+=4,u>>>=4),u&3||(m+=2,u>>>=2),u&1||m++,m},o.prototype.bitLength=function(){var r=this.words[this.length-1],u=this._countBits(r);return(this.length-1)*26+u};function R(y){for(var r=new Array(y.bitLength()),u=0;u<r.length;u++){var m=u/26|0,p=u%26;r[u]=y.words[m]>>>p&1}return r}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,u=0;u<this.length;u++){var m=this._zeroBits(this.words[u]);if(r+=m,m!==26)break}return r},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(r){return this.negative!==0?this.abs().inotn(r).iaddn(1):this.clone()},o.prototype.fromTwos=function(r){return this.testn(r-1)?this.notn(r).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return this.negative!==0},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(r){for(;this.length<r.length;)this.words[this.length++]=0;for(var u=0;u<r.length;u++)this.words[u]=this.words[u]|r.words[u];return this._strip()},o.prototype.ior=function(r){return t((this.negative|r.negative)===0),this.iuor(r)},o.prototype.or=function(r){return this.length>r.length?this.clone().ior(r):r.clone().ior(this)},o.prototype.uor=function(r){return this.length>r.length?this.clone().iuor(r):r.clone().iuor(this)},o.prototype.iuand=function(r){var u;this.length>r.length?u=r:u=this;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]&r.words[m];return this.length=u.length,this._strip()},o.prototype.iand=function(r){return t((this.negative|r.negative)===0),this.iuand(r)},o.prototype.and=function(r){return this.length>r.length?this.clone().iand(r):r.clone().iand(this)},o.prototype.uand=function(r){return this.length>r.length?this.clone().iuand(r):r.clone().iuand(this)},o.prototype.iuxor=function(r){var u,m;this.length>r.length?(u=this,m=r):(u=r,m=this);for(var p=0;p<m.length;p++)this.words[p]=u.words[p]^m.words[p];if(this!==u)for(;p<u.length;p++)this.words[p]=u.words[p];return this.length=u.length,this._strip()},o.prototype.ixor=function(r){return t((this.negative|r.negative)===0),this.iuxor(r)},o.prototype.xor=function(r){return this.length>r.length?this.clone().ixor(r):r.clone().ixor(this)},o.prototype.uxor=function(r){return this.length>r.length?this.clone().iuxor(r):r.clone().iuxor(this)},o.prototype.inotn=function(r){t(typeof r=="number"&&r>=0);var u=Math.ceil(r/26)|0,m=r%26;this._expand(u),m>0&&u--;for(var p=0;p<u;p++)this.words[p]=~this.words[p]&67108863;return m>0&&(this.words[p]=~this.words[p]&67108863>>26-m),this._strip()},o.prototype.notn=function(r){return this.clone().inotn(r)},o.prototype.setn=function(r,u){t(typeof r=="number"&&r>=0);var m=r/26|0,p=r%26;return this._expand(m+1),u?this.words[m]=this.words[m]|1<<p:this.words[m]=this.words[m]&~(1<<p),this._strip()},o.prototype.iadd=function(r){var u;if(this.negative!==0&&r.negative===0)return this.negative=0,u=this.isub(r),this.negative^=1,this._normSign();if(this.negative===0&&r.negative!==0)return r.negative=0,u=this.isub(r),r.negative=1,u._normSign();var m,p;this.length>r.length?(m=this,p=r):(m=r,p=this);for(var h=0,b=0;b<p.length;b++)u=(m.words[b]|0)+(p.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;for(;h!==0&&b<m.length;b++)u=(m.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;if(this.length=m.length,h!==0)this.words[this.length]=h,this.length++;else if(m!==this)for(;b<m.length;b++)this.words[b]=m.words[b];return this},o.prototype.add=function(r){var u;return r.negative!==0&&this.negative===0?(r.negative=0,u=this.sub(r),r.negative^=1,u):r.negative===0&&this.negative!==0?(this.negative=0,u=r.sub(this),this.negative=1,u):this.length>r.length?this.clone().iadd(r):r.clone().iadd(this)},o.prototype.isub=function(r){if(r.negative!==0){r.negative=0;var u=this.iadd(r);return r.negative=1,u._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(r),this.negative=1,this._normSign();var m=this.cmp(r);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,h;m>0?(p=this,h=r):(p=r,h=this);for(var b=0,T=0;T<h.length;T++)u=(p.words[T]|0)-(h.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;for(;b!==0&&T<p.length;T++)u=(p.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;if(b===0&&T<p.length&&p!==this)for(;T<p.length;T++)this.words[T]=p.words[T];return this.length=Math.max(this.length,T),p!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(r){return this.clone().isub(r)};function K(y,r,u){u.negative=r.negative^y.negative;var m=y.length+r.length|0;u.length=m,m=m-1|0;var p=y.words[0]|0,h=r.words[0]|0,b=p*h,T=b&67108863,f=b/67108864|0;u.words[0]=T;for(var s=1;s<m;s++){for(var g=f>>>26,D=f&67108863,O=Math.min(s,r.length-1),M=Math.max(0,s-y.length+1);M<=O;M++){var E=s-M|0;p=y.words[E]|0,h=r.words[M]|0,b=p*h+D,g+=b/67108864|0,D=b&67108863}u.words[s]=D|0,f=g|0}return f!==0?u.words[s]=f|0:u.length--,u._strip()}var V=function(r,u,m){var p=r.words,h=u.words,b=m.words,T=0,f,s,g,D=p[0]|0,O=D&8191,M=D>>>13,E=p[1]|0,_=E&8191,j=E>>>13,re=p[2]|0,U=re&8191,q=re>>>13,Ls=p[3]|0,X=Ls&8191,G=Ls>>>13,js=p[4]|0,Q=js&8191,z=js>>>13,Us=p[5]|0,J=Us&8191,Y=Us>>>13,qs=p[6]|0,Z=qs&8191,tt=qs>>>13,Fs=p[7]|0,et=Fs&8191,nt=Fs>>>13,Ks=p[8]|0,ot=Ks&8191,at=Ks>>>13,Vs=p[9]|0,it=Vs&8191,rt=Vs>>>13,$s=h[0]|0,st=$s&8191,ct=$s>>>13,Hs=h[1]|0,lt=Hs&8191,ut=Hs>>>13,Xs=h[2]|0,mt=Xs&8191,pt=Xs>>>13,Gs=h[3]|0,dt=Gs&8191,ft=Gs>>>13,Qs=h[4]|0,ht=Qs&8191,gt=Qs>>>13,zs=h[5]|0,yt=zs&8191,bt=zs>>>13,Js=h[6]|0,St=Js&8191,Tt=Js>>>13,Ys=h[7]|0,wt=Ys&8191,It=Ys>>>13,Zs=h[8]|0,Ct=Zs&8191,kt=Zs>>>13,tc=h[9]|0,xt=tc&8191,vt=tc>>>13;m.negative=r.negative^u.negative,m.length=19,f=Math.imul(O,st),s=Math.imul(O,ct),s=s+Math.imul(M,st)|0,g=Math.imul(M,ct);var Sr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Sr>>>26)|0,Sr&=67108863,f=Math.imul(_,st),s=Math.imul(_,ct),s=s+Math.imul(j,st)|0,g=Math.imul(j,ct),f=f+Math.imul(O,lt)|0,s=s+Math.imul(O,ut)|0,s=s+Math.imul(M,lt)|0,g=g+Math.imul(M,ut)|0;var Tr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Tr>>>26)|0,Tr&=67108863,f=Math.imul(U,st),s=Math.imul(U,ct),s=s+Math.imul(q,st)|0,g=Math.imul(q,ct),f=f+Math.imul(_,lt)|0,s=s+Math.imul(_,ut)|0,s=s+Math.imul(j,lt)|0,g=g+Math.imul(j,ut)|0,f=f+Math.imul(O,mt)|0,s=s+Math.imul(O,pt)|0,s=s+Math.imul(M,mt)|0,g=g+Math.imul(M,pt)|0;var wr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(wr>>>26)|0,wr&=67108863,f=Math.imul(X,st),s=Math.imul(X,ct),s=s+Math.imul(G,st)|0,g=Math.imul(G,ct),f=f+Math.imul(U,lt)|0,s=s+Math.imul(U,ut)|0,s=s+Math.imul(q,lt)|0,g=g+Math.imul(q,ut)|0,f=f+Math.imul(_,mt)|0,s=s+Math.imul(_,pt)|0,s=s+Math.imul(j,mt)|0,g=g+Math.imul(j,pt)|0,f=f+Math.imul(O,dt)|0,s=s+Math.imul(O,ft)|0,s=s+Math.imul(M,dt)|0,g=g+Math.imul(M,ft)|0;var Ir=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ir>>>26)|0,Ir&=67108863,f=Math.imul(Q,st),s=Math.imul(Q,ct),s=s+Math.imul(z,st)|0,g=Math.imul(z,ct),f=f+Math.imul(X,lt)|0,s=s+Math.imul(X,ut)|0,s=s+Math.imul(G,lt)|0,g=g+Math.imul(G,ut)|0,f=f+Math.imul(U,mt)|0,s=s+Math.imul(U,pt)|0,s=s+Math.imul(q,mt)|0,g=g+Math.imul(q,pt)|0,f=f+Math.imul(_,dt)|0,s=s+Math.imul(_,ft)|0,s=s+Math.imul(j,dt)|0,g=g+Math.imul(j,ft)|0,f=f+Math.imul(O,ht)|0,s=s+Math.imul(O,gt)|0,s=s+Math.imul(M,ht)|0,g=g+Math.imul(M,gt)|0;var Cr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,f=Math.imul(J,st),s=Math.imul(J,ct),s=s+Math.imul(Y,st)|0,g=Math.imul(Y,ct),f=f+Math.imul(Q,lt)|0,s=s+Math.imul(Q,ut)|0,s=s+Math.imul(z,lt)|0,g=g+Math.imul(z,ut)|0,f=f+Math.imul(X,mt)|0,s=s+Math.imul(X,pt)|0,s=s+Math.imul(G,mt)|0,g=g+Math.imul(G,pt)|0,f=f+Math.imul(U,dt)|0,s=s+Math.imul(U,ft)|0,s=s+Math.imul(q,dt)|0,g=g+Math.imul(q,ft)|0,f=f+Math.imul(_,ht)|0,s=s+Math.imul(_,gt)|0,s=s+Math.imul(j,ht)|0,g=g+Math.imul(j,gt)|0,f=f+Math.imul(O,yt)|0,s=s+Math.imul(O,bt)|0,s=s+Math.imul(M,yt)|0,g=g+Math.imul(M,bt)|0;var kr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(kr>>>26)|0,kr&=67108863,f=Math.imul(Z,st),s=Math.imul(Z,ct),s=s+Math.imul(tt,st)|0,g=Math.imul(tt,ct),f=f+Math.imul(J,lt)|0,s=s+Math.imul(J,ut)|0,s=s+Math.imul(Y,lt)|0,g=g+Math.imul(Y,ut)|0,f=f+Math.imul(Q,mt)|0,s=s+Math.imul(Q,pt)|0,s=s+Math.imul(z,mt)|0,g=g+Math.imul(z,pt)|0,f=f+Math.imul(X,dt)|0,s=s+Math.imul(X,ft)|0,s=s+Math.imul(G,dt)|0,g=g+Math.imul(G,ft)|0,f=f+Math.imul(U,ht)|0,s=s+Math.imul(U,gt)|0,s=s+Math.imul(q,ht)|0,g=g+Math.imul(q,gt)|0,f=f+Math.imul(_,yt)|0,s=s+Math.imul(_,bt)|0,s=s+Math.imul(j,yt)|0,g=g+Math.imul(j,bt)|0,f=f+Math.imul(O,St)|0,s=s+Math.imul(O,Tt)|0,s=s+Math.imul(M,St)|0,g=g+Math.imul(M,Tt)|0;var xr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(xr>>>26)|0,xr&=67108863,f=Math.imul(et,st),s=Math.imul(et,ct),s=s+Math.imul(nt,st)|0,g=Math.imul(nt,ct),f=f+Math.imul(Z,lt)|0,s=s+Math.imul(Z,ut)|0,s=s+Math.imul(tt,lt)|0,g=g+Math.imul(tt,ut)|0,f=f+Math.imul(J,mt)|0,s=s+Math.imul(J,pt)|0,s=s+Math.imul(Y,mt)|0,g=g+Math.imul(Y,pt)|0,f=f+Math.imul(Q,dt)|0,s=s+Math.imul(Q,ft)|0,s=s+Math.imul(z,dt)|0,g=g+Math.imul(z,ft)|0,f=f+Math.imul(X,ht)|0,s=s+Math.imul(X,gt)|0,s=s+Math.imul(G,ht)|0,g=g+Math.imul(G,gt)|0,f=f+Math.imul(U,yt)|0,s=s+Math.imul(U,bt)|0,s=s+Math.imul(q,yt)|0,g=g+Math.imul(q,bt)|0,f=f+Math.imul(_,St)|0,s=s+Math.imul(_,Tt)|0,s=s+Math.imul(j,St)|0,g=g+Math.imul(j,Tt)|0,f=f+Math.imul(O,wt)|0,s=s+Math.imul(O,It)|0,s=s+Math.imul(M,wt)|0,g=g+Math.imul(M,It)|0;var vr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(vr>>>26)|0,vr&=67108863,f=Math.imul(ot,st),s=Math.imul(ot,ct),s=s+Math.imul(at,st)|0,g=Math.imul(at,ct),f=f+Math.imul(et,lt)|0,s=s+Math.imul(et,ut)|0,s=s+Math.imul(nt,lt)|0,g=g+Math.imul(nt,ut)|0,f=f+Math.imul(Z,mt)|0,s=s+Math.imul(Z,pt)|0,s=s+Math.imul(tt,mt)|0,g=g+Math.imul(tt,pt)|0,f=f+Math.imul(J,dt)|0,s=s+Math.imul(J,ft)|0,s=s+Math.imul(Y,dt)|0,g=g+Math.imul(Y,ft)|0,f=f+Math.imul(Q,ht)|0,s=s+Math.imul(Q,gt)|0,s=s+Math.imul(z,ht)|0,g=g+Math.imul(z,gt)|0,f=f+Math.imul(X,yt)|0,s=s+Math.imul(X,bt)|0,s=s+Math.imul(G,yt)|0,g=g+Math.imul(G,bt)|0,f=f+Math.imul(U,St)|0,s=s+Math.imul(U,Tt)|0,s=s+Math.imul(q,St)|0,g=g+Math.imul(q,Tt)|0,f=f+Math.imul(_,wt)|0,s=s+Math.imul(_,It)|0,s=s+Math.imul(j,wt)|0,g=g+Math.imul(j,It)|0,f=f+Math.imul(O,Ct)|0,s=s+Math.imul(O,kt)|0,s=s+Math.imul(M,Ct)|0,g=g+Math.imul(M,kt)|0;var Dr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Dr>>>26)|0,Dr&=67108863,f=Math.imul(it,st),s=Math.imul(it,ct),s=s+Math.imul(rt,st)|0,g=Math.imul(rt,ct),f=f+Math.imul(ot,lt)|0,s=s+Math.imul(ot,ut)|0,s=s+Math.imul(at,lt)|0,g=g+Math.imul(at,ut)|0,f=f+Math.imul(et,mt)|0,s=s+Math.imul(et,pt)|0,s=s+Math.imul(nt,mt)|0,g=g+Math.imul(nt,pt)|0,f=f+Math.imul(Z,dt)|0,s=s+Math.imul(Z,ft)|0,s=s+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(J,ht)|0,s=s+Math.imul(J,gt)|0,s=s+Math.imul(Y,ht)|0,g=g+Math.imul(Y,gt)|0,f=f+Math.imul(Q,yt)|0,s=s+Math.imul(Q,bt)|0,s=s+Math.imul(z,yt)|0,g=g+Math.imul(z,bt)|0,f=f+Math.imul(X,St)|0,s=s+Math.imul(X,Tt)|0,s=s+Math.imul(G,St)|0,g=g+Math.imul(G,Tt)|0,f=f+Math.imul(U,wt)|0,s=s+Math.imul(U,It)|0,s=s+Math.imul(q,wt)|0,g=g+Math.imul(q,It)|0,f=f+Math.imul(_,Ct)|0,s=s+Math.imul(_,kt)|0,s=s+Math.imul(j,Ct)|0,g=g+Math.imul(j,kt)|0,f=f+Math.imul(O,xt)|0,s=s+Math.imul(O,vt)|0,s=s+Math.imul(M,xt)|0,g=g+Math.imul(M,vt)|0;var Ar=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ar>>>26)|0,Ar&=67108863,f=Math.imul(it,lt),s=Math.imul(it,ut),s=s+Math.imul(rt,lt)|0,g=Math.imul(rt,ut),f=f+Math.imul(ot,mt)|0,s=s+Math.imul(ot,pt)|0,s=s+Math.imul(at,mt)|0,g=g+Math.imul(at,pt)|0,f=f+Math.imul(et,dt)|0,s=s+Math.imul(et,ft)|0,s=s+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,s=s+Math.imul(Z,gt)|0,s=s+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(J,yt)|0,s=s+Math.imul(J,bt)|0,s=s+Math.imul(Y,yt)|0,g=g+Math.imul(Y,bt)|0,f=f+Math.imul(Q,St)|0,s=s+Math.imul(Q,Tt)|0,s=s+Math.imul(z,St)|0,g=g+Math.imul(z,Tt)|0,f=f+Math.imul(X,wt)|0,s=s+Math.imul(X,It)|0,s=s+Math.imul(G,wt)|0,g=g+Math.imul(G,It)|0,f=f+Math.imul(U,Ct)|0,s=s+Math.imul(U,kt)|0,s=s+Math.imul(q,Ct)|0,g=g+Math.imul(q,kt)|0,f=f+Math.imul(_,xt)|0,s=s+Math.imul(_,vt)|0,s=s+Math.imul(j,xt)|0,g=g+Math.imul(j,vt)|0;var Or=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Or>>>26)|0,Or&=67108863,f=Math.imul(it,mt),s=Math.imul(it,pt),s=s+Math.imul(rt,mt)|0,g=Math.imul(rt,pt),f=f+Math.imul(ot,dt)|0,s=s+Math.imul(ot,ft)|0,s=s+Math.imul(at,dt)|0,g=g+Math.imul(at,ft)|0,f=f+Math.imul(et,ht)|0,s=s+Math.imul(et,gt)|0,s=s+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,s=s+Math.imul(Z,bt)|0,s=s+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(J,St)|0,s=s+Math.imul(J,Tt)|0,s=s+Math.imul(Y,St)|0,g=g+Math.imul(Y,Tt)|0,f=f+Math.imul(Q,wt)|0,s=s+Math.imul(Q,It)|0,s=s+Math.imul(z,wt)|0,g=g+Math.imul(z,It)|0,f=f+Math.imul(X,Ct)|0,s=s+Math.imul(X,kt)|0,s=s+Math.imul(G,Ct)|0,g=g+Math.imul(G,kt)|0,f=f+Math.imul(U,xt)|0,s=s+Math.imul(U,vt)|0,s=s+Math.imul(q,xt)|0,g=g+Math.imul(q,vt)|0;var Mr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Mr>>>26)|0,Mr&=67108863,f=Math.imul(it,dt),s=Math.imul(it,ft),s=s+Math.imul(rt,dt)|0,g=Math.imul(rt,ft),f=f+Math.imul(ot,ht)|0,s=s+Math.imul(ot,gt)|0,s=s+Math.imul(at,ht)|0,g=g+Math.imul(at,gt)|0,f=f+Math.imul(et,yt)|0,s=s+Math.imul(et,bt)|0,s=s+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,St)|0,s=s+Math.imul(Z,Tt)|0,s=s+Math.imul(tt,St)|0,g=g+Math.imul(tt,Tt)|0,f=f+Math.imul(J,wt)|0,s=s+Math.imul(J,It)|0,s=s+Math.imul(Y,wt)|0,g=g+Math.imul(Y,It)|0,f=f+Math.imul(Q,Ct)|0,s=s+Math.imul(Q,kt)|0,s=s+Math.imul(z,Ct)|0,g=g+Math.imul(z,kt)|0,f=f+Math.imul(X,xt)|0,s=s+Math.imul(X,vt)|0,s=s+Math.imul(G,xt)|0,g=g+Math.imul(G,vt)|0;var Pr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Pr>>>26)|0,Pr&=67108863,f=Math.imul(it,ht),s=Math.imul(it,gt),s=s+Math.imul(rt,ht)|0,g=Math.imul(rt,gt),f=f+Math.imul(ot,yt)|0,s=s+Math.imul(ot,bt)|0,s=s+Math.imul(at,yt)|0,g=g+Math.imul(at,bt)|0,f=f+Math.imul(et,St)|0,s=s+Math.imul(et,Tt)|0,s=s+Math.imul(nt,St)|0,g=g+Math.imul(nt,Tt)|0,f=f+Math.imul(Z,wt)|0,s=s+Math.imul(Z,It)|0,s=s+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(J,Ct)|0,s=s+Math.imul(J,kt)|0,s=s+Math.imul(Y,Ct)|0,g=g+Math.imul(Y,kt)|0,f=f+Math.imul(Q,xt)|0,s=s+Math.imul(Q,vt)|0,s=s+Math.imul(z,xt)|0,g=g+Math.imul(z,vt)|0;var Rr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Rr>>>26)|0,Rr&=67108863,f=Math.imul(it,yt),s=Math.imul(it,bt),s=s+Math.imul(rt,yt)|0,g=Math.imul(rt,bt),f=f+Math.imul(ot,St)|0,s=s+Math.imul(ot,Tt)|0,s=s+Math.imul(at,St)|0,g=g+Math.imul(at,Tt)|0,f=f+Math.imul(et,wt)|0,s=s+Math.imul(et,It)|0,s=s+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,s=s+Math.imul(Z,kt)|0,s=s+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,kt)|0,f=f+Math.imul(J,xt)|0,s=s+Math.imul(J,vt)|0,s=s+Math.imul(Y,xt)|0,g=g+Math.imul(Y,vt)|0;var Br=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Br>>>26)|0,Br&=67108863,f=Math.imul(it,St),s=Math.imul(it,Tt),s=s+Math.imul(rt,St)|0,g=Math.imul(rt,Tt),f=f+Math.imul(ot,wt)|0,s=s+Math.imul(ot,It)|0,s=s+Math.imul(at,wt)|0,g=g+Math.imul(at,It)|0,f=f+Math.imul(et,Ct)|0,s=s+Math.imul(et,kt)|0,s=s+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,kt)|0,f=f+Math.imul(Z,xt)|0,s=s+Math.imul(Z,vt)|0,s=s+Math.imul(tt,xt)|0,g=g+Math.imul(tt,vt)|0;var Er=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Er>>>26)|0,Er&=67108863,f=Math.imul(it,wt),s=Math.imul(it,It),s=s+Math.imul(rt,wt)|0,g=Math.imul(rt,It),f=f+Math.imul(ot,Ct)|0,s=s+Math.imul(ot,kt)|0,s=s+Math.imul(at,Ct)|0,g=g+Math.imul(at,kt)|0,f=f+Math.imul(et,xt)|0,s=s+Math.imul(et,vt)|0,s=s+Math.imul(nt,xt)|0,g=g+Math.imul(nt,vt)|0;var Nr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Nr>>>26)|0,Nr&=67108863,f=Math.imul(it,Ct),s=Math.imul(it,kt),s=s+Math.imul(rt,Ct)|0,g=Math.imul(rt,kt),f=f+Math.imul(ot,xt)|0,s=s+Math.imul(ot,vt)|0,s=s+Math.imul(at,xt)|0,g=g+Math.imul(at,vt)|0;var Wr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Wr>>>26)|0,Wr&=67108863,f=Math.imul(it,xt),s=Math.imul(it,vt),s=s+Math.imul(rt,xt)|0,g=Math.imul(rt,vt);var _r=(T+f|0)+((s&8191)<<13)|0;return T=(g+(s>>>13)|0)+(_r>>>26)|0,_r&=67108863,b[0]=Sr,b[1]=Tr,b[2]=wr,b[3]=Ir,b[4]=Cr,b[5]=kr,b[6]=xr,b[7]=vr,b[8]=Dr,b[9]=Ar,b[10]=Or,b[11]=Mr,b[12]=Pr,b[13]=Rr,b[14]=Br,b[15]=Er,b[16]=Nr,b[17]=Wr,b[18]=_r,T!==0&&(b[19]=T,m.length++),m};Math.imul||(V=K);function Ht(y,r,u){u.negative=r.negative^y.negative,u.length=y.length+r.length;for(var m=0,p=0,h=0;h<u.length-1;h++){var b=p;p=0;for(var T=m&67108863,f=Math.min(h,r.length-1),s=Math.max(0,h-y.length+1);s<=f;s++){var g=h-s,D=y.words[g]|0,O=r.words[s]|0,M=D*O,E=M&67108863;b=b+(M/67108864|0)|0,E=E+T|0,T=E&67108863,b=b+(E>>>26)|0,p+=b>>>26,b&=67108863}u.words[h]=T,m=b,b=p}return m!==0?u.words[h]=m:u.length--,u._strip()}function Et(y,r,u){return Ht(y,r,u)}o.prototype.mulTo=function(r,u){var m,p=this.length+r.length;return this.length===10&&r.length===10?m=V(this,r,u):p<63?m=K(this,r,u):p<1024?m=Ht(this,r,u):m=Et(this,r,u),m};function Pt(y,r){this.x=y,this.y=r}Pt.prototype.makeRBT=function(r){for(var u=new Array(r),m=o.prototype._countBits(r)-1,p=0;p<r;p++)u[p]=this.revBin(p,m,r);return u},Pt.prototype.revBin=function(r,u,m){if(r===0||r===m-1)return r;for(var p=0,h=0;h<u;h++)p|=(r&1)<<u-h-1,r>>=1;return p},Pt.prototype.permute=function(r,u,m,p,h,b){for(var T=0;T<b;T++)p[T]=u[r[T]],h[T]=m[r[T]]},Pt.prototype.transform=function(r,u,m,p,h,b){this.permute(b,r,u,m,p,h);for(var T=1;T<h;T<<=1)for(var f=T<<1,s=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),D=0;D<h;D+=f)for(var O=s,M=g,E=0;E<T;E++){var _=m[D+E],j=p[D+E],re=m[D+E+T],U=p[D+E+T],q=O*re-M*U;U=O*U+M*re,re=q,m[D+E]=_+re,p[D+E]=j+U,m[D+E+T]=_-re,p[D+E+T]=j-U,E!==f&&(q=s*O-g*M,M=s*M+g*O,O=q)}},Pt.prototype.guessLen13b=function(r,u){var m=Math.max(u,r)|1,p=m&1,h=0;for(m=m/2|0;m;m=m>>>1)h++;return 1<<h+1+p},Pt.prototype.conjugate=function(r,u,m){if(!(m<=1))for(var p=0;p<m/2;p++){var h=r[p];r[p]=r[m-p-1],r[m-p-1]=h,h=u[p],u[p]=-u[m-p-1],u[m-p-1]=-h}},Pt.prototype.normalize13b=function(r,u){for(var m=0,p=0;p<u/2;p++){var h=Math.round(r[2*p+1]/u)*8192+Math.round(r[2*p]/u)+m;r[p]=h&67108863,h<67108864?m=0:m=h/67108864|0}return r},Pt.prototype.convert13b=function(r,u,m,p){for(var h=0,b=0;b<u;b++)h=h+(r[b]|0),m[2*b]=h&8191,h=h>>>13,m[2*b+1]=h&8191,h=h>>>13;for(b=2*u;b<p;++b)m[b]=0;t(h===0),t((h&-8192)===0)},Pt.prototype.stub=function(r){for(var u=new Array(r),m=0;m<r;m++)u[m]=0;return u},Pt.prototype.mulp=function(r,u,m){var p=2*this.guessLen13b(r.length,u.length),h=this.makeRBT(p),b=this.stub(p),T=new Array(p),f=new Array(p),s=new Array(p),g=new Array(p),D=new Array(p),O=new Array(p),M=m.words;M.length=p,this.convert13b(r.words,r.length,T,p),this.convert13b(u.words,u.length,g,p),this.transform(T,b,f,s,p,h),this.transform(g,b,D,O,p,h);for(var E=0;E<p;E++){var _=f[E]*D[E]-s[E]*O[E];s[E]=f[E]*O[E]+s[E]*D[E],f[E]=_}return this.conjugate(f,s,p),this.transform(f,s,M,b,p,h),this.conjugate(M,b,p),this.normalize13b(M,p),m.negative=r.negative^u.negative,m.length=r.length+u.length,m._strip()},o.prototype.mul=function(r){var u=new o(null);return u.words=new Array(this.length+r.length),this.mulTo(r,u)},o.prototype.mulf=function(r){var u=new o(null);return u.words=new Array(this.length+r.length),Et(this,r,u)},o.prototype.imul=function(r){return this.clone().mulTo(r,this)},o.prototype.imuln=function(r){var u=r<0;u&&(r=-r),t(typeof r=="number"),t(r<67108864);for(var m=0,p=0;p<this.length;p++){var h=(this.words[p]|0)*r,b=(h&67108863)+(m&67108863);m>>=26,m+=h/67108864|0,m+=b>>>26,this.words[p]=b&67108863}return m!==0&&(this.words[p]=m,this.length++),u?this.ineg():this},o.prototype.muln=function(r){return this.clone().imuln(r)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(r){var u=R(r);if(u.length===0)return new o(1);for(var m=this,p=0;p<u.length&&u[p]===0;p++,m=m.sqr());if(++p<u.length)for(var h=m.sqr();p<u.length;p++,h=h.sqr())u[p]!==0&&(m=m.mul(h));return m},o.prototype.iushln=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=67108863>>>26-u<<26-u,h;if(u!==0){var b=0;for(h=0;h<this.length;h++){var T=this.words[h]&p,f=(this.words[h]|0)-T<<u;this.words[h]=f|b,b=T>>>26-u}b&&(this.words[h]=b,this.length++)}if(m!==0){for(h=this.length-1;h>=0;h--)this.words[h+m]=this.words[h];for(h=0;h<m;h++)this.words[h]=0;this.length+=m}return this._strip()},o.prototype.ishln=function(r){return t(this.negative===0),this.iushln(r)},o.prototype.iushrn=function(r,u,m){t(typeof r=="number"&&r>=0);var p;u?p=(u-u%26)/26:p=0;var h=r%26,b=Math.min((r-h)/26,this.length),T=67108863^67108863>>>h<<h,f=m;if(p-=b,p=Math.max(0,p),f){for(var s=0;s<b;s++)f.words[s]=this.words[s];f.length=b}if(b!==0)if(this.length>b)for(this.length-=b,s=0;s<this.length;s++)this.words[s]=this.words[s+b];else this.words[0]=0,this.length=1;var g=0;for(s=this.length-1;s>=0&&(g!==0||s>=p);s--){var D=this.words[s]|0;this.words[s]=g<<26-h|D>>>h,g=D&T}return f&&g!==0&&(f.words[f.length++]=g),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(r,u,m){return t(this.negative===0),this.iushrn(r,u,m)},o.prototype.shln=function(r){return this.clone().ishln(r)},o.prototype.ushln=function(r){return this.clone().iushln(r)},o.prototype.shrn=function(r){return this.clone().ishrn(r)},o.prototype.ushrn=function(r){return this.clone().iushrn(r)},o.prototype.testn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return!1;var h=this.words[m];return!!(h&p)},o.prototype.imaskn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(u!==0&&m++,this.length=Math.min(m,this.length),u!==0){var p=67108863^67108863>>>u<<u;this.words[this.length-1]&=p}return this._strip()},o.prototype.maskn=function(r){return this.clone().imaskn(r)},o.prototype.iaddn=function(r){return t(typeof r=="number"),t(r<67108864),r<0?this.isubn(-r):this.negative!==0?this.length===1&&(this.words[0]|0)<=r?(this.words[0]=r-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(r),this.negative=1,this):this._iaddn(r)},o.prototype._iaddn=function(r){this.words[0]+=r;for(var u=0;u<this.length&&this.words[u]>=67108864;u++)this.words[u]-=67108864,u===this.length-1?this.words[u+1]=1:this.words[u+1]++;return this.length=Math.max(this.length,u+1),this},o.prototype.isubn=function(r){if(t(typeof r=="number"),t(r<67108864),r<0)return this.iaddn(-r);if(this.negative!==0)return this.negative=0,this.iaddn(r),this.negative=1,this;if(this.words[0]-=r,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var u=0;u<this.length&&this.words[u]<0;u++)this.words[u]+=67108864,this.words[u+1]-=1;return this._strip()},o.prototype.addn=function(r){return this.clone().iaddn(r)},o.prototype.subn=function(r){return this.clone().isubn(r)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(r,u,m){var p=r.length+m,h;this._expand(p);var b,T=0;for(h=0;h<r.length;h++){b=(this.words[h+m]|0)+T;var f=(r.words[h]|0)*u;b-=f&67108863,T=(b>>26)-(f/67108864|0),this.words[h+m]=b&67108863}for(;h<this.length-m;h++)b=(this.words[h+m]|0)+T,T=b>>26,this.words[h+m]=b&67108863;if(T===0)return this._strip();for(t(T===-1),T=0,h=0;h<this.length;h++)b=-(this.words[h]|0)+T,T=b>>26,this.words[h]=b&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(r,u){var m=this.length-r.length,p=this.clone(),h=r,b=h.words[h.length-1]|0,T=this._countBits(b);m=26-T,m!==0&&(h=h.ushln(m),p.iushln(m),b=h.words[h.length-1]|0);var f=p.length-h.length,s;if(u!=="mod"){s=new o(null),s.length=f+1,s.words=new Array(s.length);for(var g=0;g<s.length;g++)s.words[g]=0}var D=p.clone()._ishlnsubmul(h,1,f);D.negative===0&&(p=D,s&&(s.words[f]=1));for(var O=f-1;O>=0;O--){var M=(p.words[h.length+O]|0)*67108864+(p.words[h.length+O-1]|0);for(M=Math.min(M/b|0,67108863),p._ishlnsubmul(h,M,O);p.negative!==0;)M--,p.negative=0,p._ishlnsubmul(h,1,O),p.isZero()||(p.negative^=1);s&&(s.words[O]=M)}return s&&s._strip(),p._strip(),u!=="div"&&m!==0&&p.iushrn(m),{div:s||null,mod:p}},o.prototype.divmod=function(r,u,m){if(t(!r.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var p,h,b;return this.negative!==0&&r.negative===0?(b=this.neg().divmod(r,u),u!=="mod"&&(p=b.div.neg()),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.iadd(r)),{div:p,mod:h}):this.negative===0&&r.negative!==0?(b=this.divmod(r.neg(),u),u!=="mod"&&(p=b.div.neg()),{div:p,mod:b.mod}):this.negative&r.negative?(b=this.neg().divmod(r.neg(),u),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.isub(r)),{div:b.div,mod:h}):r.length>this.length||this.cmp(r)<0?{div:new o(0),mod:this}:r.length===1?u==="div"?{div:this.divn(r.words[0]),mod:null}:u==="mod"?{div:null,mod:new o(this.modrn(r.words[0]))}:{div:this.divn(r.words[0]),mod:new o(this.modrn(r.words[0]))}:this._wordDiv(r,u)},o.prototype.div=function(r){return this.divmod(r,"div",!1).div},o.prototype.mod=function(r){return this.divmod(r,"mod",!1).mod},o.prototype.umod=function(r){return this.divmod(r,"mod",!0).mod},o.prototype.divRound=function(r){var u=this.divmod(r);if(u.mod.isZero())return u.div;var m=u.div.negative!==0?u.mod.isub(r):u.mod,p=r.ushrn(1),h=r.andln(1),b=m.cmp(p);return b<0||h===1&&b===0?u.div:u.div.negative!==0?u.div.isubn(1):u.div.iaddn(1)},o.prototype.modrn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=(1<<26)%r,p=0,h=this.length-1;h>=0;h--)p=(m*p+(this.words[h]|0))%r;return u?-p:p},o.prototype.modn=function(r){return this.modrn(r)},o.prototype.idivn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=0,p=this.length-1;p>=0;p--){var h=(this.words[p]|0)+m*67108864;this.words[p]=h/r|0,m=h%r}return this._strip(),u?this.ineg():this},o.prototype.divn=function(r){return this.clone().idivn(r)},o.prototype.egcd=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new o(1),h=new o(0),b=new o(0),T=new o(1),f=0;u.isEven()&&m.isEven();)u.iushrn(1),m.iushrn(1),++f;for(var s=m.clone(),g=u.clone();!u.isZero();){for(var D=0,O=1;!(u.words[0]&O)&&D<26;++D,O<<=1);if(D>0)for(u.iushrn(D);D-- >0;)(p.isOdd()||h.isOdd())&&(p.iadd(s),h.isub(g)),p.iushrn(1),h.iushrn(1);for(var M=0,E=1;!(m.words[0]&E)&&M<26;++M,E<<=1);if(M>0)for(m.iushrn(M);M-- >0;)(b.isOdd()||T.isOdd())&&(b.iadd(s),T.isub(g)),b.iushrn(1),T.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(b),h.isub(T)):(m.isub(u),b.isub(p),T.isub(h))}return{a:b,b:T,gcd:m.iushln(f)}},o.prototype._invmp=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new o(1),h=new o(0),b=m.clone();u.cmpn(1)>0&&m.cmpn(1)>0;){for(var T=0,f=1;!(u.words[0]&f)&&T<26;++T,f<<=1);if(T>0)for(u.iushrn(T);T-- >0;)p.isOdd()&&p.iadd(b),p.iushrn(1);for(var s=0,g=1;!(m.words[0]&g)&&s<26;++s,g<<=1);if(s>0)for(m.iushrn(s);s-- >0;)h.isOdd()&&h.iadd(b),h.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(h)):(m.isub(u),h.isub(p))}var D;return u.cmpn(1)===0?D=p:D=h,D.cmpn(0)<0&&D.iadd(r),D},o.prototype.gcd=function(r){if(this.isZero())return r.abs();if(r.isZero())return this.abs();var u=this.clone(),m=r.clone();u.negative=0,m.negative=0;for(var p=0;u.isEven()&&m.isEven();p++)u.iushrn(1),m.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;m.isEven();)m.iushrn(1);var h=u.cmp(m);if(h<0){var b=u;u=m,m=b}else if(h===0||m.cmpn(1)===0)break;u.isub(m)}while(!0);return m.iushln(p)},o.prototype.invm=function(r){return this.egcd(r).a.umod(r)},o.prototype.isEven=function(){return(this.words[0]&1)===0},o.prototype.isOdd=function(){return(this.words[0]&1)===1},o.prototype.andln=function(r){return this.words[0]&r},o.prototype.bincn=function(r){t(typeof r=="number");var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return this._expand(m+1),this.words[m]|=p,this;for(var h=p,b=m;h!==0&&b<this.length;b++){var T=this.words[b]|0;T+=h,h=T>>>26,T&=67108863,this.words[b]=T}return h!==0&&(this.words[b]=h,this.length++),this},o.prototype.isZero=function(){return this.length===1&&this.words[0]===0},o.prototype.cmpn=function(r){var u=r<0;if(this.negative!==0&&!u)return-1;if(this.negative===0&&u)return 1;this._strip();var m;if(this.length>1)m=1;else{u&&(r=-r),t(r<=67108863,"Number is too big");var p=this.words[0]|0;m=p===r?0:p<r?-1:1}return this.negative!==0?-m|0:m},o.prototype.cmp=function(r){if(this.negative!==0&&r.negative===0)return-1;if(this.negative===0&&r.negative!==0)return 1;var u=this.ucmp(r);return this.negative!==0?-u|0:u},o.prototype.ucmp=function(r){if(this.length>r.length)return 1;if(this.length<r.length)return-1;for(var u=0,m=this.length-1;m>=0;m--){var p=this.words[m]|0,h=r.words[m]|0;if(p!==h){p<h?u=-1:p>h&&(u=1);break}}return u},o.prototype.gtn=function(r){return this.cmpn(r)===1},o.prototype.gt=function(r){return this.cmp(r)===1},o.prototype.gten=function(r){return this.cmpn(r)>=0},o.prototype.gte=function(r){return this.cmp(r)>=0},o.prototype.ltn=function(r){return this.cmpn(r)===-1},o.prototype.lt=function(r){return this.cmp(r)===-1},o.prototype.lten=function(r){return this.cmpn(r)<=0},o.prototype.lte=function(r){return this.cmp(r)<=0},o.prototype.eqn=function(r){return this.cmpn(r)===0},o.prototype.eq=function(r){return this.cmp(r)===0},o.red=function(r){return new $(r)},o.prototype.toRed=function(r){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),r.convertTo(this)._forceRed(r)},o.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(r){return this.red=r,this},o.prototype.forceRed=function(r){return t(!this.red,"Already a number in reduction context"),this._forceRed(r)},o.prototype.redAdd=function(r){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,r)},o.prototype.redIAdd=function(r){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,r)},o.prototype.redSub=function(r){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,r)},o.prototype.redISub=function(r){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,r)},o.prototype.redShl=function(r){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,r)},o.prototype.redMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.mul(this,r)},o.prototype.redIMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.imul(this,r)},o.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(r){return t(this.red&&!r.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,r)};var ln={k256:null,p224:null,p192:null,p25519:null};function Lt(y,r){this.name=y,this.p=new o(r,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Lt.prototype._tmp=function(){var r=new o(null);return r.words=new Array(Math.ceil(this.n/13)),r},Lt.prototype.ireduce=function(r){var u=r,m;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),m=u.bitLength();while(m>this.n);var p=m<this.n?-1:u.ucmp(this.p);return p===0?(u.words[0]=0,u.length=1):p>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},Lt.prototype.split=function(r,u){r.iushrn(this.n,0,u)},Lt.prototype.imulK=function(r){return r.imul(this.k)};function qn(){Lt.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(qn,Lt),qn.prototype.split=function(r,u){for(var m=4194303,p=Math.min(r.length,9),h=0;h<p;h++)u.words[h]=r.words[h];if(u.length=p,r.length<=9){r.words[0]=0,r.length=1;return}var b=r.words[9];for(u.words[u.length++]=b&m,h=10;h<r.length;h++){var T=r.words[h]|0;r.words[h-10]=(T&m)<<4|b>>>22,b=T}b>>>=22,r.words[h-10]=b,b===0&&r.length>10?r.length-=10:r.length-=9},qn.prototype.imulK=function(r){r.words[r.length]=0,r.words[r.length+1]=0,r.length+=2;for(var u=0,m=0;m<r.length;m++){var p=r.words[m]|0;u+=p*977,r.words[m]=u&67108863,u=p*64+(u/67108864|0)}return r.words[r.length-1]===0&&(r.length--,r.words[r.length-1]===0&&r.length--),r};function Ws(){Lt.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(Ws,Lt);function _s(){Lt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(_s,Lt);function br(){Lt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(br,Lt),br.prototype.imulK=function(r){for(var u=0,m=0;m<r.length;m++){var p=(r.words[m]|0)*19+u,h=p&67108863;p>>>=26,r.words[m]=h,u=p}return u!==0&&(r.words[r.length++]=u),r},o._prime=function(r){if(ln[r])return ln[r];var u;if(r==="k256")u=new qn;else if(r==="p224")u=new Ws;else if(r==="p192")u=new _s;else if(r==="p25519")u=new br;else throw new Error("Unknown prime "+r);return ln[r]=u,u};function $(y){if(typeof y=="string"){var r=o._prime(y);this.m=r.p,this.prime=r}else t(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}$.prototype._verify1=function(r){t(r.negative===0,"red works only with positives"),t(r.red,"red works only with red numbers")},$.prototype._verify2=function(r,u){t((r.negative|u.negative)===0,"red works only with positives"),t(r.red&&r.red===u.red,"red works only with red numbers")},$.prototype.imod=function(r){return this.prime?this.prime.ireduce(r)._forceRed(this):(S(r,r.umod(this.m)._forceRed(this)),r)},$.prototype.neg=function(r){return r.isZero()?r.clone():this.m.sub(r)._forceRed(this)},$.prototype.add=function(r,u){this._verify2(r,u);var m=r.add(u);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},$.prototype.iadd=function(r,u){this._verify2(r,u);var m=r.iadd(u);return m.cmp(this.m)>=0&&m.isub(this.m),m},$.prototype.sub=function(r,u){this._verify2(r,u);var m=r.sub(u);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},$.prototype.isub=function(r,u){this._verify2(r,u);var m=r.isub(u);return m.cmpn(0)<0&&m.iadd(this.m),m},$.prototype.shl=function(r,u){return this._verify1(r),this.imod(r.ushln(u))},$.prototype.imul=function(r,u){return this._verify2(r,u),this.imod(r.imul(u))},$.prototype.mul=function(r,u){return this._verify2(r,u),this.imod(r.mul(u))},$.prototype.isqr=function(r){return this.imul(r,r.clone())},$.prototype.sqr=function(r){return this.mul(r,r)},$.prototype.sqrt=function(r){if(r.isZero())return r.clone();var u=this.m.andln(3);if(t(u%2===1),u===3){var m=this.m.add(new o(1)).iushrn(2);return this.pow(r,m)}for(var p=this.m.subn(1),h=0;!p.isZero()&&p.andln(1)===0;)h++,p.iushrn(1);t(!p.isZero());var b=new o(1).toRed(this),T=b.redNeg(),f=this.m.subn(1).iushrn(1),s=this.m.bitLength();for(s=new o(2*s*s).toRed(this);this.pow(s,f).cmp(T)!==0;)s.redIAdd(T);for(var g=this.pow(s,p),D=this.pow(r,p.addn(1).iushrn(1)),O=this.pow(r,p),M=h;O.cmp(b)!==0;){for(var E=O,_=0;E.cmp(b)!==0;_++)E=E.redSqr();t(_<M);var j=this.pow(g,new o(1).iushln(M-_-1));D=D.redMul(j),g=j.redSqr(),O=O.redMul(g),M=_}return D},$.prototype.invm=function(r){var u=r._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},$.prototype.pow=function(r,u){if(u.isZero())return new o(1).toRed(this);if(u.cmpn(1)===0)return r.clone();var m=4,p=new Array(1<<m);p[0]=new o(1).toRed(this),p[1]=r;for(var h=2;h<p.length;h++)p[h]=this.mul(p[h-1],r);var b=p[0],T=0,f=0,s=u.bitLength()%26;for(s===0&&(s=26),h=u.length-1;h>=0;h--){for(var g=u.words[h],D=s-1;D>=0;D--){var O=g>>D&1;if(b!==p[0]&&(b=this.sqr(b)),O===0&&T===0){f=0;continue}T<<=1,T|=O,f++,!(f!==m&&(h!==0||D!==0))&&(b=this.mul(b,p[T]),f=0,T=0)}s=26}return b},$.prototype.convertTo=function(r){var u=r.umod(this.m);return u===r?u.clone():u},$.prototype.convertFrom=function(r){var u=r.clone();return u.red=null,u},o.mont=function(r){return new Me(r)};function Me(y){$.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(Me,$),Me.prototype.convertTo=function(r){return this.imod(r.ushln(this.shift))},Me.prototype.convertFrom=function(r){var u=this.imod(r.mul(this.rinv));return u.red=null,u},Me.prototype.imul=function(r,u){if(r.isZero()||u.isZero())return r.words[0]=0,r.length=1,r;var m=r.imul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},Me.prototype.mul=function(r,u){if(r.isZero()||u.isZero())return new o(0)._forceRed(this);var m=r.mul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},Me.prototype.invm=function(r){var u=this.imod(r._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof Ps>"u"||Ps,tp)});var Kd={};Lr(Kd,{appHelpers:()=>Fd});module.exports=Bp(Kd);var cc=require("@msafe/sui3-utils");var ne=require("@alphafi/alphafi-sdk"),Le=require("@msafe/sui3-utils"),zt=require("@mysten/bcs");var Kn=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,n=t.pool_id,o=ne.poolIdPoolNameMap[n];if(console.log("Decoder event data - ",t),console.log("Decoder poolName - ",o),this.isWithdrawAlphaEvent(e))return this.decodeWithdrawAlpha(t);if(this.isWithdrawEvent(t))return this.decodeWithdraw(o);if(this.isDoubleAssetDepositEvent(t,o))return this.decodeDoubleAssetDeposit(o,t);if(this.isSingleAssetDepositEvent(t,o))return this.decodeSingleAssetDeposit(o,t);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(){return this.simResult.events.find(e=>this.isLiquidityChangeEventType(e.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(e){return e.includes("LiquidityChangeEvent")||e.includes("LiquidityChangeNewNewEvent")||e.includes("WithdrawEventV2")}isWithdrawAlphaEvent(e){return e.type.includes("WithdrawEventV2")}isWithdrawEvent(e){return e.event_type===1}isDoubleAssetDepositEvent(e,t){return e.event_type===0&&ne.poolInfo[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&ne.poolInfo[t].assetTypes.length===1}extractXTokensAmount(){let e=this.inputs.find(o=>o.Pure!==void 0);if(!e||!e.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:t}=e.Pure,n;return t.length===12?n=zt.bcs.u64().parse((0,zt.fromBase64)(t)):t.length===24?n=zt.bcs.u128().parse((0,zt.fromBase64)(t)):t.length===44?n=zt.bcs.u256().parse((0,zt.fromBase64)(t)):n=zt.bcs.u64().parse((0,zt.fromBase64)(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:o}=t,i=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,i),{txType:Le.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:i?n:o,isAmountA:i}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:i}=ne.singleAssetPoolCoinMap[e],{expo:c}=ne.coinsList[i];n=Math.floor(Number(n)/10**(9-c)).toString()}return{txType:Le.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:Le.TransactionType.Other,type:"withdraw",intentionData:{poolName:e,xTokensAmount:t}}}decodeWithdrawAlpha(e){let t=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=e;return console.log("Decoder.decodeWithdrawAlpha",t,n),{txType:Le.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:Le.TransactionType.Other,type:"claimReward",intentionData:{}}}};var oc=require("@alphafi/alphafi-sdk");var nc=jt(require("sort-keys-recursive")),k=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,nc.default)(this.data))}};var Vn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t;return await(0,oc.claimRewardTxb)(n.address)}static fromData(t){return new a(t)}};var ac=require("@alphafi/alphafi-sdk");var $n=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i,isAmountA:c}=this.data;return await(0,ac.depositDoubleAssetTxb)(o,n.address,i,c)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};var ic=require("@alphafi/alphafi-sdk");var Hn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i}=this.data;return await(0,ic.depositSingleAssetTxb)(o,n.address,i)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};var rc=require("@alphafi/alphafi-sdk");var Xn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:i}=this.data;return await(0,rc.withdrawTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var sc=require("@alphafi/alphafi-sdk");var Gn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:i}=this.data;return await(0,sc.withdrawAlphaTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var Qn=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:o}=e,i=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",i);let l=new Kn(t,i).decode();return{txType:cc.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=Hn.fromData(e.intentionData);break;case"depositDoubleAsset":n=$n.fromData(e.intentionData);break;case"withdraw":n=Xn.fromData(e.intentionData);break;case"withdrawAlpha":n=Gn.fromData(e.intentionData);break;case"claimReward":n=Vn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};var Bc=require("@msafe/sui3-utils");var Nt=require("@msafe/sui3-utils"),zn=require("@mysten/sui/bcs"),Jn=require("bucket-protocol-sdk");var Yn=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,n){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.package===e&&o.MoveCall.module===t&&o.MoveCall.function===n)}getMoveCallModuleCommands(e,t){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(e=>e.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(e=>e.$kind==="TransferObjects")}isPsmTransaction(){return!!this.getMoveCallCommand("charge_reservoir")||!!this.getMoveCallCommand("discharge_reservoir")}isStrapNewTransaction(){return!!this.getMoveCallModuleCommand("strap","new")}isBorrowTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","high_top_up")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow_with_strap")}isRepayTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","fully_repay")||!!this.getMoveCallModuleCommand("bucket_operations","fully_repay_with_strap")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw_with_strap")}isWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","withdraw")||!!this.getMoveCallModuleCommand("buck","withdraw_with_strap")}isCloseTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","destroy_empty_strap")}isTankDepositTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","deposit")}isTankWithdrawTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","withdraw")}isTankClaimTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","claim")}isSBUCKDepositTransaction(){return!!this.getMoveCallModuleCommand("buck","buck_to_sbuck")}isSBUCKWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","sbuck_to_buck")}isSBUCKStakeTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","claim")}isLockedClaimTransaction(){return!!this.getMoveCallModuleCommand("proof_rule","claim")||!!this.getMoveCallModuleCommand("lst_proof_rule","claim")}isLstUnlockTransaction(){return!!this.getMoveCallModuleCommand("lst_proof_rule","unlock")}decodePsm(){let e,t,n="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),this.getMoveCallCommand("charge_reservoir")?([e]=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments,t=!1):([e]=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments,t=!0),console.log("Decoder.decodePsm",e,n,t),{txType:Nt.TransactionType.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,o=this.getStrapId(),i="0",c=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(c.$kind==="Input"&&(i=this.getPureInputU64(c.Input)),this.getMoveCallCommand("high_top_up")){let l=this.getMoveCallCommand("high_top_up").MoveCall;[e]=l.typeArguments;let d=l.arguments[1];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[3];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow")){let l=this.getMoveCallCommand("high_borrow").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let l=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}return{txType:Nt.TransactionType.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:i,borrowAmount:t,insertionPlace:n,strapId:o}}}decodeRepay(){let e="",t="0",n="0",i,c=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let l=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let l=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}return{txType:Nt.TransactionType.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:i,strapId:c}}}decodeWithdraw(){let e="",t="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let i=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=i.typeArguments;let c=i.arguments[4];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=i.arguments[5];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}else if(this.getMoveCallCommand("withdraw")){let i=this.getMoveCallCommand("withdraw").MoveCall;[e]=i.typeArguments;let c=i.arguments[3];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=i.arguments[4];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}return{txType:Nt.TransactionType.Other,type:"withdraw",intentionData:{collateralType:e,withdrawAmount:t,insertionPlace:n,strapId:o}}}decodeClose(){let e="",t=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([e]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:Nt.TransactionType.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",i=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];i.$kind==="Input"&&(n=this.getPureInputU64(i.Input));let c=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,c),{txType:Nt.TransactionType.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:c}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(e=this.getPureInputU64(d.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let l=0;l<o.length;l++){let d=o[l];n.push("")}else{let l=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let d=0;d<l.length;d++){let w=l[d].MoveCall.arguments[2];if(w.$kind==="Input"){let{objectId:I}=this.inputs[w.Input].UnresolvedObject;n.push(I)}}}let i=this.isSBUCKWithdrawTransaction(),c={stakeProofs:n,amount:e,isStake:t,toBuck:i};return console.log("Decoder.decodeSBUCKUnstake",c),{txType:Nt.TransactionType.Other,type:"sbuck-unstake",intentionData:c}}decodeSBUCKWithdraw(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(e=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:Nt.TransactionType.Other,type:"sbuck-withdraw",intentionData:{amount:e}}}decodeSBUCKClaim(){let e=[],t=this.getMoveCallModuleCommands("fountain_core","claim");for(let n=0;n<t.length;n++){let i=t[n].MoveCall.arguments[2];if(i.$kind==="Input"){let{objectId:c}=this.inputs[i.Input].UnresolvedObject;e.push(c)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:Nt.TransactionType.Other,type:"sbuck-claim",intentionData:{stakeProofs:e}}}decodeTankDeposit(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];n.$kind==="Input"&&(e=this.getPureInputU64(n.Input));let i=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",i,e),{txType:Nt.TransactionType.Other,type:"tank-deposit",intentionData:{coinType:i,amount:e}}}decodeTankWithdraw(){let e=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,t=e.typeArguments[0],n="0",o=e.arguments[5];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),console.log("Decoder.decodeTankWithdraw",t,n),{txType:Nt.TransactionType.Other,type:"tank-withdraw",intentionData:{coinType:t,amount:n}}}decodeTankClaim(){let t=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",t),{txType:Nt.TransactionType.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let i=0;i<n.length;i++)[e]=n[i].MoveCall.typeArguments,t++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let i=0;i<o.length;i++)[e]=o[i].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:Nt.TransactionType.Other,type:"lock-claim",intentionData:{coinType:e,proofCount:t}}}getCoinInput(e){if(this.inputs[e].$kind!=="Object")throw new Error("not Object argument")}getStrapId(){let e;if(this.isStrapNewTransaction()?e="new":this.isLstUnlockTransaction()&&(e="locked"),!e){let t=this.getMoveCallModuleCommand("fountain","unstake");if(t){let n=t.MoveCall.arguments[2];n.$kind==="Input"&&(e=this.inputs[n.Input].UnresolvedObject.objectId)}}return e}getPureInputU64(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return zn.bcs.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return zn.bcs.vector(zn.bcs.Address).fromBase64(t.Pure.bytes)}};var dc=require("@msafe/sui3-utils");var uc=require("@mysten/sui/transactions"),mc=require("bucket-protocol-sdk");var lc=require("bucket-protocol-sdk"),Mt=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new lc.BucketClient(t,e.address)};var pc=async(a,e,t)=>{let{coinType:n,amount:o,buckToCoin:i}=a,c=new uc.Transaction,l=Mt(t,e);return await(0,mc.buildPsmTx)(l,c,n,o,i,e.address),c};var Zn=class a extends k{constructor(t){super(t);this.data=t}txType=dc.TransactionType.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await pc(this.data,n,o)}static fromData(t){return new a(t)}};var bc=require("@msafe/sui3-utils");var un=require("@mysten/sui/transactions"),se=require("bucket-protocol-sdk");var fc=async(a,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:i,insertionPlace:c,strapId:l}=a,d=new un.Transaction,S=Mt(t,e);return await(0,se.buildBorrowTx)(S,d,n,o,i,e.address,c,l),d},hc=async(a,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:i,strapId:c}=a,l=new un.Transaction,d=Mt(t,e);return await(0,se.buildWithdrawTx)(d,l,n,o,e.address,i,c),l},gc=async(a,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:i,isSurplus:c,insertionPlace:l,strapId:d}=a,S=new un.Transaction,w=Mt(t,e);return await(0,se.buildRepayTx)(w,S,n,o,i,e.address,c,l,d),S},yc=async(a,e,t)=>{let{collateralType:n,recipient:o,strapId:i}=a,c=new un.Transaction,l=Mt(t,e);return await(0,se.buildCloseTx)(l,c,n,o,i),c};var to=class a extends k{constructor(t){super(t);this.data=t}txType=bc.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await fc(this.data,n,o)}static fromData(t){return new a(t)}};var Sc=require("@msafe/sui3-utils");var eo=class a extends k{constructor(t){super(t);this.data=t}txType=Sc.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await gc(this.data,n,o)}static fromData(t){return new a(t)}};var Tc=require("@msafe/sui3-utils");var no=class a extends k{constructor(t){super(t);this.data=t}txType=Tc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await hc(this.data,n,o)}static fromData(t){return new a(t)}};var wc=require("@msafe/sui3-utils");var oo=class a extends k{constructor(t){super(t);this.data=t}txType=wc.TransactionType.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await yc(this.data,n,o)}static fromData(t){return new a(t)}};var pn=require("@msafe/sui3-utils");var mn=require("@mysten/sui/transactions"),ce=require("bucket-protocol-sdk");var Ic=async(a,e,t)=>{let{coinType:n,amount:o,isStake:i}=a,c=new mn.Transaction,l=Mt(t,e);return await(0,ce.buildSBUCKDepositTx)(l,c,n,o,e.address,i),c},Cc=async(a,e,t)=>{let{stakeProofs:n,amount:o,isStake:i,toBuck:c}=a,l=new mn.Transaction,d=Mt(t,e);return await(0,ce.buildSBUCKUnstakeTx)(d,l,n,o,e.address,i,c),l},kc=async(a,e,t)=>{let{amount:n}=a,o=new mn.Transaction,i=Mt(t,e);return await(0,ce.buildSBUCKWithdrawTx)(i,o,n,e.address),o},xc=async(a,e,t)=>{let{stakeProofs:n}=a,o=new mn.Transaction,i=Mt(t,e);return await(0,ce.buildSBUCKClaimTx)(i,o,n,e.address),o};var ao=class a extends k{constructor(t){super(t);this.data=t}txType=pn.TransactionType.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await Ic(this.data,n,o)}static fromData(t){return new a(t)}},io=class a extends k{constructor(t){super(t);this.data=t}txType=pn.TransactionType.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await Cc(this.data,n,o)}static fromData(t){return new a(t)}},ro=class a extends k{constructor(t){super(t);this.data=t}txType=pn.TransactionType.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await kc(this.data,n,o)}static fromData(t){return new a(t)}},so=class a extends k{constructor(t){super(t);this.data=t}txType=pn.TransactionType.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await xc(this.data,n,o)}static fromData(t){return new a(t)}};var po=require("@msafe/sui3-utils");var co=require("@mysten/sui/transactions"),je=require("bucket-protocol-sdk");var vc=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new co.Transaction,c=Mt(t,e);return await(0,je.buildTankDepositTx)(c,i,n,o,e.address),i},Dc=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new co.Transaction,c=Mt(t,e);return await(0,je.buildTankWithdrawTx)(c,i,n,o,e.address),i},Ac=async(a,e,t)=>{let{coinType:n}=a,o=new co.Transaction,i=Mt(t,e);return await(0,je.buildTankClaimTx)(i,o,n,e.address),o};var Oc=require("@mysten/sui/transactions"),Mc=require("bucket-protocol-sdk");var Pc=async(a,e,t)=>{let{coinType:n,proofCount:o}=a,i=new Oc.Transaction,c=Mt(t,e);return await(0,Mc.buildLockedClaimTx)(c,i,n,o,e.address),i};var lo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await vc(this.data,n,o)}static fromData(t){return new a(t)}},uo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await Dc(this.data,n,o)}static fromData(t){return new a(t)}},mo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await Ac(this.data,n,o)}static fromData(t){return new a(t)}};var Rc=require("@msafe/sui3-utils");var fo=class a extends k{constructor(t){super(t);this.data=t}txType=Rc.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Pc(this.data,n,o)}static fromData(t){return new a(t)}};var ho=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new Yn(t).decode();return{txType:Bc.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"psm":i=Zn.fromData(e.intentionData);break;case"borrow":i=to.fromData(e.intentionData);break;case"withdraw":i=no.fromData(e.intentionData);break;case"repay":i=eo.fromData(e.intentionData);break;case"close":i=oo.fromData(e.intentionData);break;case"tank-deposit":i=lo.fromData(e.intentionData);break;case"tank-withdraw":i=uo.fromData(e.intentionData);break;case"tank-claim":i=mo.fromData(e.intentionData);break;case"sbuck-deposit":i=ao.fromData(e.intentionData);break;case"sbuck-unstake":i=io.fromData(e.intentionData);break;case"sbuck-withdraw":i=ro.fromData(e.intentionData);break;case"sbuck-claim":i=so.fromData(e.intentionData);break;case"lock-claim":i=fo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Ll=require("@msafe/sui3-utils");var Vc=require("@msafe/sui3-utils");var go=require("@cetusprotocol/aggregator-sdk"),Ec=require("@cetusprotocol/farms-sdk"),Nc=require("@cetusprotocol/sui-clmm-sdk"),Wc=require("@cetusprotocol/vaults-sdk"),_c=require("@cetusprotocol/xcetus-sdk"),Pe=require("@mysten/sui/client"),ae=(a,e)=>{let t=Nc.CetusClmmSDK.createSDK({env:"mainnet",sui_client:new Pe.SuiClient({url:(0,Pe.getFullnodeUrl)("mainnet")})});return t.setSenderAddress(e.address),t},Ut=(a,e)=>{let t=Ec.CetusFarmsSDK.createSDK({env:"mainnet",sui_client:new Pe.SuiClient({url:(0,Pe.getFullnodeUrl)("mainnet")})});return t.setSenderAddress(e.address),t},Np="https://api-sui.cetus.zone/router_v2/find_routes",Lc=(a,e)=>{let t=new Pe.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new go.AggregatorClient({endpoint:Np,signer:e.address,client:t,env:go.Env.Mainnet})},dn=(a,e)=>{let t=Wc.CetusVaultsSDK.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t},Ue=(a,e)=>{let t=_c.CetusXcetusSDK.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t};var jc=async(a,e,t)=>await ae(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Uc=async(a,e,t)=>await ae(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),qc=async(a,e,t)=>await ae(t,e).Position.closePositionPayload(a),Fc=async(a,e,t)=>await ae(t,e).Position.removeLiquidityPayload(a),Kc=async(a,e,t)=>await ae(t,e).Rewarder.collectRewarderPayload(a);var yo=class a extends k{constructor(t){super(t);this.data=t}txType=Vc.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await jc(i,n,o)}static fromData(t){return new a(t)}};var $c=require("@msafe/sui3-utils");var bo=class a extends k{constructor(t){super(t);this.data=t}txType=$c.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Kc(i,n,o)}static fromData(t){return new a(t)}};var Hc=require("@msafe/sui3-utils");var So=class a extends k{constructor(t){super(t);this.data=t}txType=Hc.TransactionType.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Fc(i,n,o)}static fromData(t){return new a(t)}};var nl=require("@msafe/sui3-utils");var Xc=async(a,e,t)=>await Ut(t,e).Farms.openPositionAddLiquidityStakePayload(a),Gc=async(a,e,t)=>await Ut(t,e).Farms.addLiquidityFixCoinPayload(a),Qc=async(a,e,t)=>await Ut(t,e).Farms.removeLiquidityPayload(a),zc=async(a,e,t)=>await Ut(t,e).Farms.removeLiquidityPayload(a),Jc=async(a,e,t)=>await Ut(t,e).Farms.claimFeeAndClmmReward(a),Yc=async(a,e,t)=>await Ut(t,e).Farms.harvestPayload(a),Zc=async(a,e,t)=>{let n=Ut(t,e),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},tl=async(a,e,t)=>await Ut(t,e).Farms.depositPayload(a),el=async(a,e,t)=>await Ut(t,e).Farms.withdrawPayload(a);var To=class a extends k{constructor(t){super(t);this.data=t}txType=nl.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Xc(i,n,o)}static fromData(t){return new a(t)}};var ol=require("@msafe/sui3-utils");var wo=class a extends k{constructor(t){super(t);this.data=t}txType=ol.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Zc(i,n,o)}static fromData(t){return new a(t)}};var al=require("@msafe/sui3-utils");var Io=class a extends k{constructor(t){super(t);this.data=t}txType=al.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Jc(i,n,o)}static fromData(t){return new a(t)}};var il=require("@msafe/sui3-utils");var Co=class a extends k{constructor(t){super(t);this.data=t}txType=il.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Qc(i,n,o)}static fromData(t){return new a(t)}};var rl=require("@msafe/sui3-utils");var ko=class a extends k{constructor(t){super(t);this.data=t}txType=rl.TransactionType.Other;txSubType="FarmingHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Yc(i,n,o)}static fromData(t){return new a(t)}};var sl=require("@msafe/sui3-utils");var xo=class a extends k{constructor(t){super(t);this.data=t}txType=sl.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Gc(i,n,o)}static fromData(t){return new a(t)}};var cl=require("@msafe/sui3-utils");var vo=class a extends k{constructor(t){super(t);this.data=t}txType=cl.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await zc(i,n,o)}static fromData(t){return new a(t)}};var ll=require("@msafe/sui3-utils");var Do=class a extends k{constructor(t){super(t);this.data=t}txType=ll.TransactionType.Other;txSubType="FarmingStake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await tl(i,n,o)}static fromData(t){return new a(t)}};var ul=require("@msafe/sui3-utils");var Ao=class a extends k{constructor(t){super(t);this.data=t}txType=ul.TransactionType.Other;txSubType="FarmingUnstake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await el(i,n,o)}static fromData(t){return new a(t)}};var ml=require("@msafe/sui3-utils");var Oo=class a extends k{constructor(t){super(t);this.data=t}txType=ml.TransactionType.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Uc(i,n,o)}static fromData(t){return new a(t)}};var fl=require("@msafe/sui3-utils");var fn=require("@mysten/sui/transactions"),Mo=jt(require("haedal-vault-sdk"));var Wp=async(a,e,t)=>{let n=dn(t,e),o=new fn.Transaction;return o.setSender(e.address),n.Vest.buildRedeemPayload(a.params,o),o},_p=async(a,e,t)=>{let n=new Mo.default(Mo.vaults_mainnet);n.senderAddress=e.address;let o=new fn.Transaction;return o.setSender(e.address),await n?.Vest.buildRedeemPayload(a.params,o),o},pl=(a,e,t)=>{let n=ae(t,e),o=new fn.Transaction;return n?.Vest.buildRedeemPayload(a.params,o),o},Lp=async(a,e,t)=>{let n=ae(t,e),o=Ut(t,e),i=new fn.Transaction,c=await o.Farms.withdrawReturnPayload(a.withdrawParams,i);return n.Vest.buildRedeemPayload(a.redeemParms.map(l=>({...l,clmm_position_id:c})),i),o.Farms.depositPayload({...a.depositParams,clmm_position_id:c},i),i},dl=async(a,e,t)=>a.type==="clmm"?pl(a,e,t):a.type==="farms"?Lp(a,e,t):a.type==="vaults"?Wp(a,e,t):a.type==="haedalVaults"?_p(a,e,t):pl(a,e,t);var Po=class a extends k{constructor(t){super(t);this.data=t}txType=fl.TransactionType.Other;txSubType="PosVestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await dl(i,n,o)}static fromData(t){return new a(t)}};var hl=require("@msafe/sui3-utils");var Ro=class a extends k{constructor(t){super(t);this.data=t}txType=hl.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await qc(i,n,o)}static fromData(t){return new a(t)}};var Sl=require("@msafe/sui3-utils");var gl=require("@cetusprotocol/aggregator-sdk"),yl=require("@mysten/sui/transactions");var bl=async(a,e,t)=>{let n=Lc(t,e),o=new yl.Transaction;return await n.fastRouterSwap({...a,routers:(0,gl.restituteMsafeFastRouterSwapParams)(a.routers),txb:o}),o};var Bo=class a extends k{constructor(t){super(t);this.data=t}txType=Sl.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await bl(i,n,o)}static fromData(t){return new a(t)}};var Il=require("@msafe/sui3-utils");var jr=require("@mysten/sui/transactions");var Tl=async(a,e,t)=>{let n=dn(t,e),o=new jr.Transaction;return o.setSender(e.address),await n.Vaults.deposit(a,o),o},wl=async(a,e,t)=>{let n=dn(t,e),o=new jr.Transaction;return await n.Vaults.withdraw(a,o),o};var Eo=class a extends k{constructor(t){super(t);this.data=t}txType=Il.TransactionType.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Tl(i,n,o)}static fromData(t){return new a(t)}};var Cl=require("@msafe/sui3-utils");var No=class a extends k{constructor(t){super(t);this.data=t}txType=Cl.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await wl(i,n,o)}static fromData(t){return new a(t)}};var Dl=require("@msafe/sui3-utils");var xl=require("@mysten/sui/transactions"),kl={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},vl=async(a,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:o,periods:i,CLOCK_ADDRESS:c}=a,l=new xl.Transaction;return i.forEach(d=>{l.moveCall({target:`${kl.published_at}::router::redeem`,typeArguments:[kl.cetus_coin_type],arguments:[l.object(n),l.object(o),l.pure(d),l.object(c)]})}),l};var Wo=class a extends k{constructor(t){super(t);this.data=t}txType=Dl.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await vl(i,n,o)}static fromData(t){return new a(t)}};var Bl=require("@msafe/sui3-utils");var Al=async(a,e,t)=>await Ue(t,e).XCetusModule.convertPayload(a),Ol=async(a,e,t)=>await Ue(t,e).XCetusModule.redeemLockPayload(a),Ml=async(a,e,t)=>await Ue(t,e).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),Pl=async(a,e,t)=>await Ue(t,e).XCetusModule.cancelRedeemPayload(a),Rl=async(a,e,t)=>await Ue(t,e).XCetusModule.redeemPayload(a);var _o=class a extends k{constructor(t){super(t);this.data=t}txType=Bl.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Pl(i,n,o)}static fromData(t){return new a(t)}};var El=require("@msafe/sui3-utils");var Lo=class a extends k{constructor(t){super(t);this.data=t}txType=El.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ml(i,n,o)}static fromData(t){return new a(t)}};var Nl=require("@msafe/sui3-utils");var jo=class a extends k{constructor(t){super(t);this.data=t}txType=Nl.TransactionType.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Al(i,n,o)}static fromData(t){return new a(t)}};var Wl=require("@msafe/sui3-utils");var Uo=class a extends k{constructor(t){super(t);this.data=t}txType=Wl.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Rl(i,n,o)}static fromData(t){return new a(t)}};var _l=require("@msafe/sui3-utils");var qo=class a extends k{constructor(t){super(t);this.data=t}txType=_l.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ol(i,n,o)}static fromData(t){return new a(t)}};var Fo=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:Ll.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...t},action:n}}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"OpenAndAddLiquidity":i=yo.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Oo.fromData(e.intentionData);break;case"DecreaseLiquidity":i=So.fromData(e.intentionData);break;case"RemoveLiquidity":i=Ro.fromData(e.intentionData);break;case"ClaimFeeAndMining":i=bo.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":i=To.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":i=xo.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":i=Co.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":i=vo.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":i=Io.fromData(e.intentionData);break;case"FarmingHarvest":i=ko.fromData(e.intentionData);break;case"FarmingBatchHarvest":i=wo.fromData(e.intentionData);break;case"FarmingStake":i=Do.fromData(e.intentionData);break;case"FarmingUnstake":i=Ao.fromData(e.intentionData);break;case"xCETUSConvert":i=jo.fromData(e.intentionData);break;case"xCETUSRedeemLock":i=qo.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":i=Lo.fromData(e.intentionData);break;case"xCETUSCancelRedeem":i=_o.fromData(e.intentionData);break;case"xCETUSRedeem":i=Uo.fromData(e.intentionData);break;case"VestingRedeem":i=Wo.fromData(e.intentionData);break;case"AggregatorSwap":i=Bo.fromData(e.intentionData);break;case"AddVaultsPosition":i=Eo.fromData(e.intentionData);break;case"RemoveVaultsPosition":i=No.fromData(e.intentionData);break;case"PosVestingRedeem":i=Po.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var su=require("@msafe/sui3-utils");var jl=jt(require("sort-keys-recursive")),P=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,jl.default)(this.data))}};var hn=require("@mysten/sui.js/client");var Ur={};Lr(Ur,{contractId:()=>qp,default:()=>Hp,feeObjId:()=>Vp,roleObjId:()=>Fp,status:()=>Up,transaction:()=>jp,upgradeCapObjId:()=>$p,vaultObjId:()=>Kp});var jp="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Up="success",qp="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Fp="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Kp="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Vp="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",$p="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Hp={transaction:jp,status:Up,contractId:qp,roleObjId:Fp,vaultObjId:Kp,feeObjId:Vp,upgradeCapObjId:$p};var qr={};Lr(qr,{contractId:()=>Qp,default:()=>td,feeObjId:()=>Yp,roleObjId:()=>zp,status:()=>Gp,transaction:()=>Xp,upgradeCapObjId:()=>Zp,vaultObjId:()=>Jp});var Xp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Gp="success",Qp="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",zp="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Jp="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Yp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Zp="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",td={transaction:Xp,status:Gp,contractId:Qp,roleObjId:zp,vaultObjId:Jp,feeObjId:Yp,upgradeCapObjId:Zp};var ed=(0,hn.getFullnodeUrl)("testnet"),nd=(0,hn.getFullnodeUrl)("testnet"),od=(0,hn.getFullnodeUrl)("mainnet"),ad=(0,hn.getFullnodeUrl)("mainnet"),id="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",rd="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",sd="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",cd="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Ul=Ur,ql=qr,ld=new Map([["dev",{env:"dev",rpc:{url:ed},backend:{url:id},contract:Ul}],["stg",{env:"stg",rpc:{url:nd},backend:{url:rd},contract:Ul}],["prev",{env:"prev",rpc:{url:od},backend:{url:sd},contract:ql}],["prod",{env:"prod",rpc:{url:ad},backend:{url:cd},contract:ql}]]);function Fl(a,e){let t=ld.get(a);if(!t)throw new Error(`Env not supported: ${a}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var Kl=require("@mysten/sui.js/client");var L=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:o,context:i}=n;o?super(`[MPay] ${t}: ${o}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=i}};var Ko=class extends L{constructor(){super(11,"Backend is not specified")}};var Vo=class extends L{constructor(){super(1,"Wallet not connected")}};var ie=jt(require("axios"));var qe=class extends L{constructor(e,t){super(10,e,{context:t})}};var $o=class a{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof ie.AxiosError)throw new qe(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new qe(e.data.code)}throw new qe(e.status.toString())}async getIncomingStreams(e,t){let n=await ie.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await ie.default.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(n)}async getStreamHistory(e){let t=await ie.default.post(`${this.apiURL}/stream-events`,e),n=a.parseResponseData(t);return n.data.forEach(o=>{let i=o;return i.data.type==="create_stream"?i.data.balance=BigInt(i.data.balance):i.data.type==="cancel_stream"?i.data.withdrawAmount=BigInt(i.data.withdrawAmount):i.data.type==="claim"||i.data.type==="auto_claim"?i.data.claimAmount=BigInt(i.data.claimAmount):i.data.type==="set_auto_claim"&&(i.data.enabled=!!i.data.enabled),i.createdAt=new Date(i.createdAt),i}),n}async getAllCoinTypes(e){let t=await ie.default.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let n=await ie.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(n)}async getAllSenders(e,t){let n=await ie.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(n)}};var Fe=class a{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Kl.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new $o(e.backend.url))}static new(e,t){let n=Fl(e,t);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Ko;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 Vo;return this.signer}async walletAddress(){return this.wallet.address()}};var Be=require("@mysten/sui.js/utils");var wn=require("@mysten/sui.js/transactions");var Hr=require("@mysten/sui.js/transactions"),Tn=require("@mysten/sui.js/utils");var Fr=50n,Ho=10000n,Vl=25n,Kr=100000000n;var Jt=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},gn=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},me=class a{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let o=c=>new a(t.result[c]);if(n===Symbol.iterator)return function*(){let c=0;for(;;)yield o(c),c++};if(typeof n=="symbol")return;let i=parseInt(n,10);if(!(Number.isNaN(i)||i<0))return o(i)}})}moveArg(){return this.result}};var Vr=require("buffer"),$l=require("@mysten/sui.js/utils");var yn=class extends L{constructor(e,t){super(3,e,{context:t})}};var Xo=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let n=this.callResult(e);return this.returnValue(n,t)}getAddress(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="address")throw new yn("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return(0,$l.normalizeSuiAddress)(Vr.Buffer.from(n).toString("hex"))}getU64(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="u64")throw new yn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Vr.Buffer.from(n).readBigInt64LE()}};var $r=require("@mysten/sui.js/bcs");var H=class extends L{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var Xl={groupId:"string",name:"string"},ud=64;function Gl(a){return Ql(a),$r.bcs.ser(Xl,a).toString("base64")}function bn(a){let e=$r.bcs.de(Xl,a,"base64");return Ql(e),e}function Ql(a){if(!Hl(a.name))throw new H("Invalid metadata: Name contains unknown character");if(!Hl(a.groupId))throw new H("Invalid metadata: Group ID contains unknown character");if(a.name.length>ud)throw new H("Invalid metadata: Name exceed max length 64")}function Hl(a){return/^[\x00-\x7F]+$/.test(a)}var Sn=require("@mysten/sui.js/utils");function Go(a,e){return(0,Sn.normalizeStructTag)(a)===(0,Sn.normalizeStructTag)(e)}function pe(a,e){return(0,Sn.normalizeStructTag)(a)===(0,Sn.normalizeStructTag)(e)}var Qo="txn.gas";var zl=require("nanoid");function Jl(){return(0,zl.nanoid)()}var Re=class a{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:Gl({name:e.name,groupId:Jl()}),coinType:(0,Tn.normalizeStructTag)(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new Hr.TransactionBlock,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),i=await this.wallet.requestCoins(o),c=await this.addMergeCoins(t,i[0]),l;o.length>1?l=await this.addMergeCoins(t,i[1]):l=c;for(let d=0;d<e.recipients.length;d++){let S=e.recipients[d],w=this.amountForRecipient(S,e.numberEpoch),I=this.getStreamFeeLocal(w),[C]=t.splitCoins(c,[t.pure(w+I,"u64")]),[x]=t.splitCoins(l,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new me(C),flatFeeCoin:new me(x),metadata:e.metadata,recipient:S.address,timeStart:e.startTime,cliff:S.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:S.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:Fr,denominator:Ho},claimFeePercent:{numerator:Vl,denominator:Ho},flatFeePerStream:Kr}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(o=>e.object(o))),n=e.object(t.primaryCoin)):t.primaryCoin===Qo?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return Go(n,Tn.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:Tn.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,i)=>{let c=this.amountForRecipient(i,e.numberEpoch),l=this.getStreamFeeLocal(c);return{totalAmount:o.totalAmount+c,streamFeeAmount:o.streamFeeAmount+l}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return Kr}getStreamFeeLocal(e){return e*Fr/Ho}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new Hr.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new Xo(n).getU64()}get wallet(){return this.globals.wallet}};var Xr=require("@mysten/sui.js/transactions");var Yl="0x0000000000000000000000000000000000000000000000000000000000000006";var Ke=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(Xr.Transactions.MoveCall({target:n,arguments:t.arguments.map(o=>o instanceof gn?o.moveArgs(e):o instanceof Jt?o.moveArg(e):o instanceof me?o.moveArg():e.pure(o)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,n=[],o=[]){e.add(Xr.Transactions.MoveCall({target:t,arguments:n.map(i=>i instanceof gn?i.moveArgs(e):i instanceof Jt?i.moveArg(e):i instanceof me?i.moveArg():e.pure(i)),typeArguments:o}))}makeObject(e){return typeof e=="string"?new Jt(e):e}vaultObject(){return new Jt(this.config.vaultObjId)}roleObject(){return new Jt(this.config.roleObjId)}feeObject(){return new Jt(this.config.feeObjId)}clockObject(){return new Jt(Yl)}};var Ve=class a extends Ke{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_fee,arguments:[o,i,n],typeArgs:[]})}setStreamingFlatFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,i,n],typeArgs:[]})}setClaimFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_claim_fee,arguments:[o,i,n],typeArgs:[]})}streamingFee(t,n){let o=this.feeObject();return this.addContractCall(t,{method:a.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Yt=class a extends Ke{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.feeObject(),i=this.vaultObject(),c=this.makeObject(n.paymentCoin),l=this.makeObject(n.flatFeeCoin),d=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[o,i,c,l,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,d],typeArgs:[n.coinType]})}setAutoClaim(t,n){let o=this.makeObject(n.streamId);return this.addContractCall(t,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.cancel_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let o=this.makeObject(n.streamId),i=this.vaultObject(),c=this.feeObject(),l=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,i,c,l],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var $e=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new Ve(t,e),this.streamContract=new Yt(t,e)}feeContract;streamContract;async createStreams(e){let t=Re.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new Re(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new wn.TransactionBlock;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new wn.TransactionBlock;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new wn.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new wn.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};var He=require("@mysten/sui.js/utils"),Gr=require("luxon");var zo=class extends L{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var md=1e3,Jo=class{constructor(e){this.globals=e;this.coinMetaHelper=new Qr(e.suiClient),this.createStreamHelper=new $e(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new zo(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},n=e.totalAmount*t.numerator/t.denominator,o=(e.totalAmount-n)/e.steps,c={realTotalAmount:o*e.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(c,e.totalAmount),c}calculateTimelineByInterval(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),n={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(Gr.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:Gr.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await this.globals.suiClient.getBalance({owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:(0,He.normalizeStructTag)(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,i)=>({...o,coinType:(0,He.normalizeStructTag)(o.coinType),coinMeta:n[i]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new H("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new H("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<md)throw new H("Interval shall be at least 1 second","interval",e.interval)}},Qr=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=(0,He.normalizeStructTag)(e||He.SUI_TYPE_ARG);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this.coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};var fe=require("@mysten/sui.js/utils"),ns=require("luxon");var kn=require("@mysten/sui.js/transactions"),xn=require("@mysten/sui.js/utils"),tu=require("luxon");var Yo=class extends L{constructor(){super(7,"Connected wallet is not creator")}};var In=class extends L{constructor(){super(8,"Connected wallet is not recipient")}};var Cn=class extends L{constructor(e,t){super(6,e,{context:t})}};var At=class extends L{constructor(e,t={}){super(0,e,t)}};var Zo=class extends L{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};var ea=require("luxon"),Zl=(1n<<64n)-1n,ta=1e3;function zr(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/ta);return ea.DateTime.fromMillis(t*ta)}function Jr(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/ta);return ea.Duration.fromMillis(t*ta)}var de=class a{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new Yt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await a.fetchStreamData(e,t);return new a(e,t,n)}static fromObjectData(e,t,n){let o=a.parseRawStreamData(t,n);return new a(e,t,o)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new At("Object Id does not align");this.rawData=a.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 Yo;let e=new kn.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new In;let e=new kn.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 In;let t=new kn.TransactionBlock;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new kn.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,xn.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 Jr(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return bn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return bn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return zr(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return Jr(t)}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:zr((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===Zl?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=tu.DateTime.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new Zo(e):new Cn(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new Cn("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=(0,xn.parseStructTag)(n.type),i=(0,xn.normalizeStructTag)(o[0]),c=n.fields,l=c.config.fields,d=c.status.fields;return{coinType:i,autoClaim:c.auto_claim,balance:BigInt(c.balance.fields.balance),config:{amountPerEpoch:BigInt(l.amount_per_epoch),cancelable:l.cancelable,cliff:BigInt(l.cliff),creator:l.creator,epochInterval:BigInt(l.epoch_interval),metadata:l.metadata,recipient:l.recipient,timeStart:BigInt(l.time_start),totalEpoch:BigInt(l.total_epoch)},status:{status:d.status,epochCanceled:BigInt(d.epoch_canceled),epochClaimed:BigInt(d.epoch_claimed)}}}};var Xe=class extends L{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function Zr(a){let e=[];for(;await a.hasNext();){let t=await a.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Yr=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)}},Ge=class{constructor(e){this.requester=e;this.pager=new Yr(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]}};var pd=25;async function es(a,e,t){let n=new vn(e),o=new Dn(a,n,t);return await Zr(o)}var vn=class{constructor(e){this.ids=e;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]}},Dn=class extends Ge{constructor(t,n,o){super(new ts(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}},ts=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||pd,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&e.push(i)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=t.filter(i=>o?.(i))}else n=t;return{data:n,hasNext:await this.stringIter.hasNext()}}};var na=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new Xe("stream size 0");let n=t.map(i=>i.groupId);if(new Set(n).size!==1)throw new H("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await es(e.suiClient,t);return n.forEach(o=>{if(!o)throw new At("stream group object data undefined")}),a.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let o=await a.parseGroupStreams(e,t,n);return new a(e,o)}static checkStreamGroup(e){let t=e.map(i=>i.groupCommonInfo),n=t[0],o=!0;return t.forEach(i=>{dd(n,i)||(o=!1)}),o}async refresh(){let e=await es(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let o=n.map((i,c)=>de.fromObjectData(e,t[c],i)).filter(i=>!!i);if(new Set(o.map(i=>i.groupId)).size!==1)throw new Xe("Not same group ID");if(!this.checkStreamGroup(o))throw new Xe("Not same stream settings");return o}};function dd(a,e){return a.name===e.name&&a.groupId===e.groupId&&a.creator===e.creator&&a.start.toMillis()===e.start.toMillis()&&a.interval.toMillis()===e.interval.toMillis()&&a.steps===e.steps&&a.cancelable===e.cancelable}var An=class a{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await oa.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await oa.newOutgoing(e);return new a(t,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}},oa=class a{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await aa.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await aa.newOutgoingQuery(e);return new a(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new At("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new At("No more results");return e}},aa=class a{constructor(e,t,n,o){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=o;this.current=0;let i=new vn(n.flat().map(c=>c.streamId));this.objectIter=new Dn(e.suiClient,i)}current=0;objectIter;static async newIncomingQuery(e){let t=bd(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,t)).filter(l=>(0,fe.normalizeSuiAddress)(l.recipient)===(0,fe.normalizeSuiAddress)(n)),c=eu(i);return new a(e.globals,n,c,e.query)}static async newOutgoingQuery(e){let t=Sd(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),i=eu(o);return new a(e.globals,n,i,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await gd(this.globals,e[0].streamId,this.objectIter);return this.current++,nu(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await yd(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,hd(t,this.query)?t:this.doNextRequest()}throw new At("Stream group with no stream")}};function eu(a){let e=new Map;return a.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>ns.DateTime.fromISO(n[0].createDate).toMillis()-ns.DateTime.fromISO(t[0].createDate).toMillis())}function nu(a,e){if(e===void 0)return!0;let t=fd(a,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return t&&n}return t}function fd(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function hd(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(n=>{nu(n,e)&&(t=!0)}),t}async function gd(a,e,t){let n=await ou(t,e);return de.fromObjectData(a,e,n)}async function yd(a,e,t){let n=[];for(;n.length<e.length;){let o=await ou(t,e[n.length]);n.push(o)}return na.newFromObjectResponse(a,e,n)}async function ou(a,e){if(!await a.hasNext())throw new At("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new At("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new At("stream id not aligned");return t}function bd(a){return{status:os(a?.status),coinType:au(a?.coinType),sender:iu(a?.sender)}}function Sd(a){return{status:os(a?.status),coinType:au(a?.coinType),recipient:iu(a?.recipient)}}function os(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let n=os(t);return!e||e===n?n:"all"},void 0):Td(a)}function Td(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new H("Unknown stream filtered status")}}function au(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,fe.normalizeStructTag)(e)):void 0:(0,fe.normalizeStructTag)(a)}function iu(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,fe.normalizeSuiAddress)(e)):void 0:(0,fe.normalizeSuiAddress)(a)}var ia=class extends L{constructor(t,n,o){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:n,gotAmount:o}});this.coinType=t;this.requestAmount=n;this.gotAmount=o}};var wd=25;async function ru(a,e,t,n="0x2::sui::SUI",o=wd){let i=new as(a,e,n,o),c=BigInt(0),l=[];for(;await i.hasNext()&&c<t;){let d=await i.next();d&&(l.push(d),c+=BigInt(d.balance))}if(c<t)throw new ia(n,t,c);return l}var as=class extends Ge{constructor(t,n,o,i){super(new is(t,n,o,i));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=i}},is=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new At("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var rs=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},ra=class{constructor(e){this.account=e}async address(){return this.account.address}},ss=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(Go(e.coinType,Be.SUI_TYPE_ARG))return{primaryCoin:Qo};if(e.amount<=0)throw new H("Invalid coin request","coinAmount",e.amount);let t=await ru(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new At("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},sa=class{globals;helper;constructor(e,t){this.globals=Fe.new(e,t),this.helper=new Jo(this.globals)}connectSingleWallet(e){let t=new ss(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new rs(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return de.new(this.globals,e)}async getIncomingStreams(e,t=10){return An.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return An.newOutgoing({globals:this.globals,query:e,pageSize:t})}async getCoinTypesForStreamFilter(){let e=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(e)).map(n=>(0,Be.normalizeStructTag)(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>(0,Be.normalizeSuiAddress)(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>(0,Be.normalizeSuiAddress)(o))}get wallet(){return this.globals.wallet}builder(){return new $e(this.globals)}};var Ft=class extends P{application="mpay";getClient(e,t){let n=new sa(e==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new ra(t)),n}};var On=class extends Ft{constructor(t){super(t);this.data=t}txType=su.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};var cu=require("@msafe/sui3-utils");var Mn=class extends Ft{constructor(t){super(t);this.data=t}txType=cu.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};var lu=require("@msafe/sui3-utils");var Pn=class extends Ft{constructor(t){super(t);this.data=t}txType=lu.TransactionType.Stream;txSubType="Claim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};var uu=require("@msafe/sui3-utils");var Rn=class extends Ft{constructor(t){super(t);this.data=t}txType=uu.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o}=t;return this.getClient(n,o).createStream(this.data)}};var cs=require("@mysten/sui.js/bcs"),he=require("@mysten/sui.js/utils"),Qe=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,he.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return cs.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,he.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,he.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,he.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,he.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return cs.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,he.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var ca=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&pe(t.target,this.contract.createStreamTarget));if(e.length===0)throw new At("No create stream transactions");return e.map(t=>new Qe(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=bn(t),i=e.decodeInputAddress(5),c=e.decodeInputU64(6),l=e.decodeInputU64(7),d=e.decodeInputU64(8),S=e.decodeInputU64(9),w=e.decodeInputU64(10),I=e.decodeInputBool(11),C=e.typeArg(0);return{name:n,groupId:o,recipient:i,timeStart:c,cliff:l,epochInterval:d,totalEpoch:S,amountPerEpoch:w,cancelable:I,coinType:C}}aggregateGroupStreamInfo(e){if(new Set(e.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new H("Stream group not have common info");let n=e.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:n,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Yt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ve(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Re(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var la=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new Yt(e.envConfig.contract,e)}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"&&pe(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new ca(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new Qe(e,this.txb)}};var mu=require("@msafe/sui3-utils");var Bn=class extends Ft{constructor(t){super(t);this.data=t}txType=mu.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var ua=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:n}=e,o=Fe.new(t==="sui:mainnet"?"prod":"dev"),c=new la(o,n).decode(),l;switch(c.type){case"CreateStream":l=new Rn(c.info);break;case"SetAutoClaim":l=new Bn({streamId:c.streamId,enabled:c.enabled});break;case"Claim":l=new Pn({streamId:c.streamId});break;case"ClaimByProxy":l=new Mn({streamId:c.streamId});break;case"Cancel":l=new On({streamId:c.streamId});break;default:throw new Error(`Unknown transaction type: ${c}`)}return{txType:l.txType,txSubType:l.txSubType,intentionData:l.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Rn(t);break;case"Claim":n=new Pn(t);break;case"ClaimByProxy":n=new Mn(t);break;case"SetAutoClaim":n=new Bn(t);break;case"Cancel":n=new On(t);break;default:throw new Error("not implemented")}return n.build({...e})}};var En=require("@msafe/sui3-utils");var pu=require("@msafe/sui3-utils");var ma=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return(0,pu.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var du=require("@msafe/sui3-utils");var pa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return(0,du.buildObjectTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var da=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=En.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case En.TransactionSubTypes.assets.coin.send:o=ma.fromData(e.intentionData);break;case En.TransactionSubTypes.assets.object.send:o=pa.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var xu=require("@msafe/sui3-utils");var fu=!1,Nn={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,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"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",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"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function ls(){if(!fu)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(i=>i.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:o}=a;e&&(Nn.ProtocolPackage=e),t&&(Nn.borrowFee=t),n&&(Nn.borrowFeeAddress=n),o&&(Nn.pool=o),fu=!0}catch(a){console.error(a.message)}}var Xt=Nn;var ge=require("@msafe/sui3-utils"),us=require("@mysten/sui.js/bcs"),ye=require("@mysten/sui.js/utils");var fa=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return!!(this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values(Xt.pool).find(n=>n.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:ge.TransactionType.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:ge.TransactionType.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===t){let o=new ha(n,this.txb),i=o.decodeInputU8(3),c=o.decodeInputU64(5);e.push({assetId:i,amount:c})}}),{txType:ge.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:ge.TransactionType.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Xt.ProtocolPackage));return new ha(e,this.txb)}},ha=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,ye.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return us.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,ye.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ye.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,ye.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ye.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return us.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,ye.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Kt=require("navi-sdk");async function ze(a,e,t,n){return await(0,Kt.depositCoin)(a,e,t,n),a}async function hu(a,e,t,n){let[o]=await(0,Kt.withdrawCoin)(a,e,t);return a.transferObjects([o],a.pure(n)),a}async function gu(a,e,t,n){let[o]=await(0,Kt.borrowCoin)(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function ms(a,e,t,n){return await(0,Kt.repayDebt)(a,e,t,n),a}async function yu(a,e){return await(0,Kt.claimAllRewardsPTB)(a,e)}async function bu(a,e){return await(0,Kt.claimAllRewardsResupplyPTB)(a,e)}var ga=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await yu(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var ya=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await bu(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var Tu=require("@mysten/sui.js/transactions");var Su=require("navi-sdk");function Zt(a){return Object.values(Su.pool).find(e=>String(e.assetId)===String(a))}var ba=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Tu.TransactionBlock;console.log("build",this.data);let c=Zt(n);return await gu(i,c,o,t.account.address)}static fromData(t){return new a(t)}};var wu=require("@mysten/sui.js/transactions");async function Je(a,e,t){let n=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Sa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:c}=this.data,l=new wu.TransactionBlock;console.log("build",this.data);let d=Zt(i);if(i===0){let[C]=l.splitCoins(l.gas,[c]);return await ze(l,d,C,c)}let S=await Je(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let C=1;for(;C<S.data.length;)l.mergeCoins(w,[S.data[C].coinObjectId]),C++}return await ze(l,d,l.object(w),c)}static fromData(t){return new a(t)}};var Iu=require("@mysten/sui.js/transactions");var Ta=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:c}=this.data,l=new Iu.TransactionBlock;console.log("build",this.data);let d=Zt(i);if(i===0){let[I]=l.splitCoins(l.gas,[c]);return ms(l,d,I,c)}let S=await Je(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let I=1;for(;I<S.data.length;)l.mergeCoins(w,[S.data[I].coinObjectId]),I++}return ms(l,d,l.object(w),c)}static fromData(t){return new a(t)}};var Cu=require("@mysten/sui.js/transactions");var wa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Cu.TransactionBlock;console.log("build",this.data);let c=Zt(n);return await hu(i,c,o,t.account.address)}static fromData(t){return new a(t)}};var ku=require("@mysten/sui.js/transactions");var Ia=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:i}=this.data,c=new ku.TransactionBlock;console.log("build",this.data);for(let l=0;l<i.length;l++){let{assetId:d,amount:S}=i[l],w=Zt(d);if(d===0){let[x]=c.splitCoins(c.gas,[S]);await ze(c,w,x,S);continue}let I=await Je(n,o.address,w.type);if(!I.data[0])throw new Error(`Insufficient balance for ${w.name} Token`);let C=I.data[0].coinObjectId;if(I.data.length>=2){let x=1;for(;x<I.data.length;)c.mergeCoins(C,[I.data[x].coinObjectId]),x++}await ze(c,w,c.object(C),S)}return c}static fromData(t){return new a(t)}};var Ca=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await ls();let{transactionBlock:t}=e,o=new fa(t).decode();return{txType:xu.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await ls(),e.txSubType){case"EntryDeposit":o=Sa.fromData(e.intentionData);break;case"EntryBorrow":o=ba.fromData(e.intentionData);break;case"EntryRepay":o=Ta.fromData(e.intentionData);break;case"EntryWithdraw":o=wa.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Ia.fromData(e.intentionData);break;case"ClaimReward":o=ga.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=ya.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Wn=require("@msafe/sui3-utils"),vu=require("@mysten/bcs"),Du=require("@mysten/sui/transactions"),Au=jt(require("sort-keys-recursive")),Ou="msafe-plain-tx",Mu=Wn.TransactionSubTypes.others.plain,ps=class a{constructor(e){this.data=e}application=Ou;txType=Wn.TransactionType.Other;txSubType=Mu;serialize(){return JSON.stringify((0,Au.default)(this.data))}async build(e){return Du.Transaction.from((0,vu.fromHex)(this.data.content))}static fromData(e){return new a(e)}},ka=class{application;supportSDK="@mysten/sui";constructor(){this.application=Ou}async deserialize(e){let{content:t}=e.appContext;return{txType:Wn.TransactionType.Other,txSubType:Mu,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:o}=e;return ps.fromData(e.intentionData).build({suiClient:t,network:n,account:o})}};var hs=require("@mysten/sui/client"),Pu=require("@mysten/sui/transactions"),Da=require("@mysten/sui.js/client"),Ru=require("@mysten/sui.js/transactions");var Ye=require("@open-rpc/client-js");var kd={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},ds=class extends Error{},xa=class extends ds{code;type;constructor(e,t){super(e),this.code=t,this.type=kd[t]??"ServerError"}};function xd(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var vd={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},va=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#i=new Set;#o=new Map;constructor(e,t={}){this.endpoint=e,this.options={...vd,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=xd(this.endpoint))}async makeRequest(e,t){let n=await this.#r();return new Promise((o,i)=>{this.#n+=1,this.#o.set(this.#n,{resolve:o,reject:i,timeout:setTimeout(()=>{this.#o.delete(this.#n),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:o,result:i})=>{if(o)throw new xa(o.message,o.code);return i})}#r(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(o){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:o}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:o,timeout:i}=this.#o.get(n.id);clearTimeout(i),o(n)}else if("params"in n){let{params:o}=n;this.#i.forEach(i=>{i.subscriptionId===o.subscription&&o.subscription===i.subscriptionId&&i.onMessage(o.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#i].map(e=>e.subscribe(this)))}async subscribe(e){let t=new fs(e);return this.#i.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},fs=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var be=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:o}){let i=new Ye.HTTPTransport(o?.url??e,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new Ye.Client(new Ye.RequestManager([i])),this.websocketClient=new va(t??e,n)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var Aa=class a{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new a;for(let n=0;n<e.length;n++){let o=e[n];switch(o.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(o);break;case"@mysten/sui":t.addHelper(o);break;default:throw new Error(`${o.application}: ${o.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new ys(e))}addHelper(e){this.apps.set(e.application,new gs(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},gs=class{constructor(e){this.helper=e}async deserialize(e){let t=new hs.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=new Da.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await e.transactionBlock.build({client:n}),i=Pu.Transaction.from(o);return this.helper.deserialize({...e,suiClient:t,transaction:i})}async build(e){let t=new hs.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});o.setSender(e.account.address);let i=await o.build({client:t});return Ru.TransactionBlock.from(i)}},ys=class{constructor(e){this.helper=e}async deserialize(e){let t=new Da.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new Da.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};var Fu=require("@msafe/sui3-utils"),Ku=require("@mysten/sui/client"),Vu=require("@scallop-io/sui-scallop-sdk");var Ot=require("@msafe/sui3-utils"),Ts=require("@scallop-io/sui-scallop-sdk");var Bu=require("@mysten/sui/utils"),Se=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(n=>`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),veScaObjId:this.address.get("vesca.object"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:n,module:o,name:i}=(0,Bu.parseStructTag)(t);return e?e.package===n&&e.module===o&&e.function===i:!1}isMoveCall(e){return e.$kind==="MoveCall"&&!!e.MoveCall}filterMoveCallCommands(e,t){return this.isMoveCall(e)&&this.matchMoveCallCommand(e.MoveCall,t)}getMoveCallCommands(e){let t=new Set(e),n=e.reduce((i,c,l)=>(i[c]=l,i),{}),o=[];return this.commands.forEach(i=>{this.isMoveCall(i)&&i.MoveCall&&t.has(i.MoveCall.package)&&(o[n[i.MoveCall.package]]=i.MoveCall)}),o}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};var Oa=require("@mysten/sui/bcs"),Te=require("@mysten/sui/utils"),bs=class a{constructor(e,t,n=0){this.moveCall=e;this.transaction=t;let o=[];e?.MoveCall&&t.getData().commands.filter((i,c)=>{if(i.$kind==="MoveCall"){let l=`${i.MoveCall.package}::${i.MoveCall.module}::${i.MoveCall.function}`,d=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return l===d?(o.push(c),!0):!1}return!1}),this.cmdIdx=o[n]}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return(0,Te.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure,o=Oa.bcs[t];return Oa.bcs[t].parse(new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Te.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Te.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,Te.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Te.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e){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 t=e.value.Pure;return Oa.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Te.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},W=bs;var Ss=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(W.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Bt=Ss;var we=require("@mysten/sui/utils"),Eu=async(a,e)=>{let t=await a.scallopSuiKit.client.getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let o=t.data.content.fields.lock_key?.fields.name;if(!o)return!1;let i=a.address.get("borrowIncentive.object");return o===`${i.slice(2)}::incentive_account::IncentiveProgramLockKey`},Ze={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},Vt={unstakeObligation:(a,e,t)=>a.moveCall(`${Ze.id}::user::unstake`,[Ze.incentivePools,Ze.incentiveAccounts,a.object(e),a.object(t),we.SUI_CLOCK_OBJECT_ID],[(0,we.normalizeStructTag)(we.SUI_TYPE_ARG)]),redeem_rewards:(a,e,t,n)=>a.moveCall(`${Ze.id}::user::redeem_rewards`,[Ze.incentivePools,Ze.incentiveAccounts,a.object(e),a.object(t),we.SUI_CLOCK_OBJECT_ID],[(0,we.normalizeStructTag)(n)])};var Nu=(a,e)=>{let t=[];for(let n=0;n<a.length;n+=e)t.push(a.slice(n,n+e));return t};var Ma=class extends Se{decode(){if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMigrateScoinTransaction(){return this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`),t=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`);return e&&t}isUnstakeAndWithdrawTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`),t=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`);return e&&t}isStakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`),t=this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return e&&t}isDepositCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isBorrowWithReferralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isUnstakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return e||t}isOpenObligationTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let e=this.hasMoveCallCommand(`${Ts.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Ts.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new W(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new W(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new W(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new W(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new W(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new W(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new W(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new W(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new W(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new W(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new W(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new W(e,this.transaction)}decodeMigrateScoin(){return{txType:Ot.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let t=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),o=this.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:Ot.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Ot.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLending(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperRedeem.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeDepositCollateral(){let e=this.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),t=this.helperDepositCollateral.getNestedInputParam(3),n=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:e}}}decodeWithdrawCollateral(){let e=this.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),t=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"WithdrawCollateral",intentionData:{amount:t,collateralCoinName:e,obligationKey:o,obligationId:n}}}decodeBorrow(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"Borrow",intentionData:{amount:t,coinName:e,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),i=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeBorrowWithReferral(){let e=this.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),o=this.helperBorrowWithReferral.decodeSharedObjectId(1),i=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:e}}}decodeRepayWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),o=new Bt(n,this.transaction).getAmountInput().reduce((c,l)=>c+l,0),i=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:i,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);t=new Bt(i,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}if(this.helperStake.moveCall&&t===0){let i=this.helperStake.getNestedInputParam(2);t=new Bt(i,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.TransactionType.Other,type:"StakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeUnstakeSpool(){let e=this.helperUnstake.decodeOwnedObjectId(1),t=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.TransactionType.Other,type:"UnstakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeSupplyWithStakeSpool(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Ot.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(o=>{let i=o.decodeOwnedObjectId(1),c=o.decodeInputU64(2);e.push({id:i,coin:c})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);n=new Bt(o,this.transaction).getAmountInput().reduce((i,c)=>i+c,0)}return{txType:Ot.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let i=o.decodeOwnedObjectId(2),c=o.typeArg(0),l=this.utils.parseCoinNameFromType(c);e.push({stakeMarketCoinName:l,stakeAccountId:i})}),this.helperClaimBorrowV2Reward.forEach(o=>{let i=o.decodeSharedObjectId(4),c=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:c,obligationKey:i,rewardCoinName:l})}),this.helperClaimBorrowReward.forEach(o=>{let i=o.decodeSharedObjectId(2),c=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:c,obligationKey:i,rewardCoinName:l})}),{txType:Ot.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};var Pa=require("@msafe/sui3-utils");var Ra=class extends Se{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new W(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new W(e,this.transaction)}decodeCreateReferralLink(){return{txType:Pa.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Pa.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Pa.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};var te=require("@msafe/sui3-utils"),Wu=require("@scallop-io/sui-scallop-sdk");var Ba=class extends Se{async decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMergeVeSca())return this.decodeMergeVesca();if(this.isSplitVeSca())return this.decodeSplitVesca();if(this.isVeScaObligationBindings())return this.decodeVeScaObligationBindings();if(await this.isTransferVeScaKey())return this.decodeTransferVeScaKey()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}isMergeVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::merge`)}isSplitVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::split`)}isVeScaObligationBindings(){let e=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),n=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`)),o=e.length>0&&t.length>0&&e.length===t.length,i=n.length>0;return this.commands.length===e.length+t.length+n.length&&(o||i)}async isTransferVeScaKey(){let e=this.commands.filter(d=>d.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,n=t.filter(d=>d.$kind==="Input").map(({Input:d})=>d);if(n.length!==t.length)return!1;let o=new Set(n),i=this.inputs.filter((d,S)=>d.$kind==="Object"&&o.has(S)).map(d=>d.Object.ImmOrOwnedObject),c=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,l=Nu(i.map(({objectId:d})=>d),50);for(let d=0;d<l.length;d++){let S=l[d];if((await this.scallopClient.scallopSuiKit.queryGetObjects(S,{showType:!0})).some(I=>I.type!==c))return!1}return i.length>0}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new W(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new W(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new W(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new W(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new W(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${Wu.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`));return new W(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new W(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(n=>this.filterMoveCallCommands(n,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new W(t,this.transaction)}getVeScaObligationBindingHelpers(){let e=`${this.coreId.borrowIncentivePkg}::user::unstake_v2`,t=`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`,n=`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`,o=[],i=0,c=0,l=0;return this.commands.forEach(d=>{this.filterMoveCallCommands(d,e)?(o.push({action:"unstake",helper:new W(d,this.transaction,i)}),i++):this.filterMoveCallCommands(d,t)?(o.push({action:"stake",helper:new W(d,this.transaction,c)}),c++):this.filterMoveCallCommands(d,n)&&(o.push({action:"deactivate",helper:new W(d,this.transaction,l)}),l++)}),o}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:te.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new Bt(e,this.transaction).getAmountInput().reduce((v,R)=>v+R,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),i=!!this.helperRedeemSca.moveCall,c=[],l=[],d=[];this.helperOldUnstakeObligation.moveCall&&(c=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(l=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(d=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let S=!1,w=!1,I,C,x=[{condition:c,isOld:!0},{condition:l,isOld:!1},{condition:d,isOld:!1}];for(let v=0;v<x.length;v++)x[v].condition.length>1&&([C,I]=x[v].condition,S=!0,w=x[v].isOld);return{txType:te.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:I,obligationKey:C,veScaKey:o,isHaveRedeem:i,isObligationLocked:S,isOldBorrowIncentive:w}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],i=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(i=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,S,w=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:i,isOld:!1}];for(let I=0;I<w.length;I++)w[I].condition.length>1&&([S,d]=w[I].condition,c=!0,l=w[I].isOld);return{txType:te.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:d,obligationKey:S,veScaKey:t,isObligationLocked:c,isOldBorrowIncentive:l}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new Bt(e,this.transaction).getAmountInput().reduce((x,v)=>x+v,0),o=[],i=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:te.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:c,unlockTime:t,obligationId:w,obligationKey:I,isOldBorrowIncentive:S,isObligationLocked:d}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let n=new Bt(e,this.transaction).getAmountInput().reduce((x,v)=>x+v,0),o=[],i=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:te.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:w,obligationKey:I,veScaKey:c,isObligationLocked:d,isOldBorrowIncentive:S}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:te.TransactionType.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:te.TransactionType.Other,type:"SplitVeSca",intentionData:t}}decodeVeScaObligationBindings(){let e=this.getVeScaObligationBindingHelpers(),t=(o,i)=>{switch(o){case"stake":return{veScaKey:i.decodeOwnedObjectId(9),obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"unstake":return{obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"deactivate":return{veScaKey:i.decodeOwnedObjectId(4),obligationId:i.decodeSharedObjectId(3)};default:throw new Error(`Invalid action ${o}`)}},n=e.map(({action:o,helper:i})=>({action:o,args:t(o,i)}));return{txType:te.TransactionType.Other,type:"VeScaObligationBindings",intentionData:{bindingDatas:n}}}decodeTransferVeScaKey(){let e=this.commands.filter(c=>c.$kind==="TransferObjects"),{objects:t}=e[0].TransferObjects,n=t.filter(c=>c.$kind==="Input").map(({Input:c})=>c);if(n.length!==t.length)return!1;let o=new Set(n),i=this.inputs.filter((c,l)=>c.$kind==="Object"&&o.has(l)).map(c=>c.Object.ImmOrOwnedObject);return{xType:te.TransactionType.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:i}}}};var _u=jt(require("sort-keys-recursive")),A=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,_u.default)(this.data))}isObligationLocked=async(e,t)=>{let n=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),o=!1;return n&&n?.data.content?.dataType==="moveObject"&&"lock_key"in n.data.content.fields&&(o=!!n.data.content.fields.lock_key),o};async buildTxWithRefreshObligation(e,t,n){let o=e.builder.createTxBlock();o.setSender(t.walletAddress);let{obligationId:i,obligationKey:c}=t;return await this.isObligationLocked(e.scallopSuiKit.client,i)?(await o.unstakeObligationQuick(i,c),await n(e,o,t),await o.stakeObligationWithVeScaQuick(i,c,t.veScaKey)):await n(e,o,t),o}};var Ea=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:i,obligationId:c,obligationKey:l}=this.data,d=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:d,obligationId:c,obligationKey:l},async(w,I)=>{let C=await I.borrowQuick(+i,o,c,l);I.transferObjects([C],d)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var Na=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,n){let{obligationId:o,obligationKey:i,veScaKey:c,amount:l,coinName:d}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:n,obligationId:o,obligationKey:i,veScaKey:c},async(w,I)=>{let C=await I.borrowQuick(+l,d,o,i);I.transferObjects([C],n)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new a(t)}};var Wa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:i,obligationKey:c,veScaKey:l,coinName:d,amount:S}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:i,obligationKey:c,veScaKey:l},async(I,C)=>{let x=C.claimReferralTicket(d),v=await C.borrowWithReferralQuick(+S,d,x,i,c);C.burnReferralTicket(x,d),C.transferObjects([v],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};var Lu=require("@mysten/sui/utils");var _a=class a extends A{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let n=e.builder.createTxBlock();n.setSender(t);let o=await e.query.getAllStakeAccounts(t),i=await e.query.getLendings(void 0,t),c=await e.query.getObligations(t),l=Object.values(await e.query.getObligationAccounts(t)??[]),d=(()=>{let C=[...e.constants.whitelist.spool].map(x=>e.utils.parseCoinName(x));return Object.values(i??[]).filter(x=>!!x&&C.includes(x.coinName)).reduce((x,v)=>{let R=e.utils.parseMarketCoinName(v.coinName);return x[R]||(x[R]=0),x[R]+=v.availableClaimCoin,x},{})})(),S={};Object.entries(o).forEach(([C,x])=>{for(let v=0;v<x.length;v++){let R=x[v];if(!d[C])continue;let K=n.claim(R.id,C);S.sui?S.sui.push(K):S.sui=[K]}});let w=(()=>{let C={};return C.sui=Object.values(d).reduce((x,v)=>x+v,0),l.forEach(x=>{Object.values(x.borrowIncentives).forEach(v=>{v&&v.rewards.forEach(R=>{C[R.coinName]||(C[R.coinName]=0),C[R.coinName]?C[R.coinName]+=R.availableClaimCoin:C[R.coinName]=R.availableClaimCoin})})}),C})();if(c.length>0&&l.length>0)for(let C=0;C<l.length;C++){let x=l[C],v=!1,R=c.find(V=>V.id===x.obligationId)?.keyId,K={};if(R){if(Object.values(x.borrowIncentives).forEach(V=>{if(V){let Ht=V.rewards.filter(Et=>{let Pt=Et.coinName;return Et.availableClaimCoin>0&&!K[Pt]});v=Ht.length>0,Ht.forEach(Et=>{let Pt=n.claimBorrowIncentive(x.obligationId,R,Et.coinName);K[Et.coinName]=!0,S[Et.coinName]?S[Et.coinName].push(Pt):S[Et.coinName]=[Pt]})}}),w.sui>0){let V=Vt.redeem_rewards(n,R,x.obligationId,Lu.SUI_TYPE_ARG);S.sui?S.sui.push(V):S.sui=[V]}if(v&&await Eu(e.query,x.obligationId)){n.unstakeObligation(x.obligationId,R);let Ht=await e.query.getBindedVeScaKey(x.obligationId);Ht?n.stakeObligationWithVesca(x.obligationId,R,Ht):n.stakeObligation(x.obligationId,R)}}}let I=(await Promise.all(Object.entries(S).map(async([C,x])=>{let v=x[0];if(x.length>1&&n.mergeCoins(v,x.slice(1)),C==="sui"){n.mergeCoins(n.gas,[v]);return}return await e.builder.utils.mergeSimilarCoins(n,v,e.utils.parseCoinType(C),t),v}))).filter(C=>!!C);return I.length>0&&n.transferObjects(I,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var La=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var ja=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:i,obligationId:c,rewardCoinName:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=Vt.redeem_rewards(S,i,c,n.utils.parseCoinType(l));return S.transferObjects([w],o),await S.unstakeObligationQuick(c,i),d?await S.stakeObligationWithVeScaQuick(c,i,d):await S.stakeObligationQuick(c,i),S.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var Ua=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var qa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var Fa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:c,obligationId:l,obligationKey:d}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:l,obligationKey:d},async(w,I)=>{await I.repayQuick(+c,i,l)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var Ka=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:c,obligationId:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=n.constants.whitelist.borrowing.has(i);return w&&await S.unstakeObligationQuick(l,void 0),await S.repayQuick(+c,i,l),w&&await S.stakeObligationWithVeScaQuick(l,void 0,d),S.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var Va=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var $a=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var Ha=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,n,o){let i=t.builder.createTxBlock();i.setSender(o);let{stakeAccountId:c,amount:l,coinName:d}=this.data,S=[];for(let w=0;w<c.length;w++){let{id:I,coin:C}=c[w],x=t.utils.parseMarketCoinName(d),[v]=await i.unstakeQuick(C,x,I);if(v){let R=i.withdraw(v,d);S.push(R)}}if(l>0){let w=await i.withdrawQuick(l,d);S.push(w)}return S.length>1&&i.mergeCoins(S[0],S.slice(1)),i.transferObjects(S,o),i.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var Xa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new a(t)}};var Ga=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var Qa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();return i.setSender(o),i.bindToReferral(this.data.veScaKey),i.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new a(t)}};var za=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:i}=this.data,c=t.address,l=n.builder.createTxBlock();l.setSender(c);let d=i.map(S=>n.utils.parseCoinNameFromType(S));return await l.claimReferralRevenueQuick(o,d),l.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var Ja=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();i.setSender(o);let c=i.mintEmptyVeSca();return i.transferObjects([c],o),i.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new a(t)}};var ju=require("@scallop-io/sui-scallop-sdk");var Ya=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:i,unlockTime:c,obligationId:l,obligationKey:d,isOldBorrowIncentive:S,isObligationLocked:w}=this.data,I=t.address,C=n.builder.createTxBlock();C.setSender(I);let x=await n.utils.selectCoins(o,ju.SCA_COIN_TYPE,I),[v,R]=C.takeAmountFromCoins(x,o);return C.extendLockPeriod(i,c),C.extendLockAmount(i,v),C.transferObjects([R],I),!l||!d||(w&&(S?Vt.unstakeObligation(C,l,d):C.unstakeObligation(l,d)),C.stakeObligationWithVesca(l,d,i)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var Za=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:i,unlockTime:c,obligationId:l,obligationKey:d,isObligationLocked:S,isOldBorrowIncentive:w}=this.data,I=n.builder.createTxBlock();return I.setSender(o),I.extendLockPeriod(i,c),l&&d&&(S&&(w?Vt.unstakeObligation(I,d,l):I.unstakeObligation(l,d)),I.stakeObligationWithVesca(l,d,i)),I.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var ti=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,sourceVeScaKey:c}=this.data,[l,d]=await Promise.all([n.getBindedObligationId(i),n.getBindedObligationId(c)]);l&&await t.unstakeObligationQuick(l),d&&await t.unstakeObligationQuick(d),o(t,i,c),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i),d&&await t.stakeObligationWithVeScaQuick(d,void 0,c)}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();return i.setSender(o),await this.handleUnsubForKeys(i,n.query,async(c,l,d)=>{c.mergeVeSca(i.object(l),i.object(d))}),i.txBlock}static fromData(t){return new a(t)}};var ei=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:o}=this.data,i=t.address,c=n.builder.createTxBlock();return c.setSender(i),await c.redeemScaQuick(o),c.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};var Uu=require("@scallop-io/sui-scallop-sdk");var ni=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,unlockTime:c,veScaKey:l,isHaveRedeem:d,obligation:S,obligationKey:w,isObligationLocked:I,isOldBorrowIncentive:C}=this.data,x=n.builder.createTxBlock();if(x.setSender(o),d){let V=x.redeemSca(l);x.transferObjects([V],o)}let v=await n.builder.utils.selectCoins(i,Uu.SCA_COIN_TYPE,o),[R,K]=x.takeAmountFromCoins(v,i);return x.transferObjects([K],o),x.renewExpiredVeSca(l,R,c),!S||!w||(I&&(C?Vt.unstakeObligation(x,w,S):x.unstakeObligation(S,w)),x.stakeObligationWithVesca(S,w,l)),x.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};var oi=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,splitAmount:c}=this.data,l=await n.getBindedObligationId(i);l&&await t.unstakeObligationQuick(l),o(t,i,c.toString()),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i)}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();return i.setSender(o),await this.handleUnsubForKeys(i,n.query,(c,l,d)=>{let S=c.splitVeSca(l,d.toString());c.transferObjects([S],o)}),i.txBlock}static fromData(t){return new a(t)}};var qu=require("@scallop-io/sui-scallop-sdk");var ai=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,isObligationLocked:c,isOldBorrowIncentive:l,obligationId:d,obligationKey:S,unlockTime:w,veScaKey:I}=this.data,C=n.builder.createTxBlock();C.setSender(o);let x=await n.utils.selectCoins(i,qu.SCA_COIN_TYPE,o),[v,R]=C.takeAmountFromCoins(x,i),K;return I?C.extendLockAmount(I,v):K=C.lockSca(v,w),d&&S&&(c&&(l?Vt.unstakeObligation(C,S,d):C.unstakeObligation(d,S)),C.stakeObligationWithVesca(d,S,I||K)),I||C.transferObjects([K,R],o),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var ii=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:i,coinName:c,stakeAccountId:l}=this.data,d=n.builder.createTxBlock();d.setSender(o);let S=await d.depositQuick(+i,c),w=n.utils.parseMarketCoinName(c);if(n.constants.whitelist.spool.has(w))return d.txBlock;let I=await n.query.getStakeAccounts(w,o),C=l||(I.length>0?I[0].id:void 0);if(C)await d.stakeQuick(S,w,C);else{let x=d.createStakeAccount(w);await d.stakeQuick(S,w,x),d.transferObjects([x],o)}return d.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var ri=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;handleAction(t,{action:n,args:o}){switch(n){case"deactivate":return t.deactivateBoost(o.obligationId,o.veScaKey);case"stake":return t.stakeObligationWithVesca(o.obligationId,o.obligationKey,o.veScaKey);case"unstake":return t.unstakeObligation(o.obligationId,o.obligationKey);default:throw new Error("Invalid action")}}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();i.setSender(o);let{bindingDatas:c}=this.data;return c.forEach(l=>this.handleAction(i,l)),i.txBlock}static fromData(t){return new a(t)}};var si=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();i.setSender(o);let{veScaKeys:c}=this.data;return i.transferObjects(c.map(l=>i.objectRef(l)),i.pure.address(o)),i.txBlock}static fromData(t){return new a(t)}};var ci=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:o}=this.data,i=t.address,c=n.builder.createTxBlock();return c.setSender(i),await c.redeemScaQuick(o),c.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var li=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let n=new Vu.Scallop({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e,suiClients:[t],fullnodeUrls:[t.transport.rpcClient.requestManager.transports[0]?.uri??(0,Ku.getFullnodeUrl)("mainnet")]});this.scallopClient=await n.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;await this.initScallopClient(o.address,n),console.log("transaction",t);let i=new Ma(t,this.scallopClient),c=new Ra(t,this.scallopClient),l=new Ba(t,this.scallopClient),d=i.decode()||c.decode()||await l.decode();if(!d)throw new Error("Unknown transaction type");return{txType:Fu.TransactionType.Other,txSubType:d.type,intentionData:d.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:i,intentionData:c}=e;await this.initScallopClient(n.address,t);let l;switch(i){case"SupplyLending":l=Va.fromData(c);break;case"WithdrawLending":l=Ga.fromData(c);break;case"Borrow":l=Ea.fromData(c);break;case"Repay":l=Fa.fromData(c);break;case"DepositCollateral":l=La.fromData(c);break;case"WithdrawCollateral":l=Xa.fromData(c);break;case"OpenObligation":l=qa.fromData(c);break;case"UnstakeSpool":l=$a.fromData(c);break;case"ClaimIncentiveReward":l=_a.fromData(c);break;case"BorrowWithBoost":l=Na.fromData(c);break;case"StakeSca":l=ai.fromData(c);break;case"ExtendStakePeriod":l=Za.fromData(c);break;case"ExtendPeriodAndStakeMore":l=Ya.fromData(c);break;case"RenewExpStakePeriod":l=ni.fromData(c);break;case"WithdrawStakedSca":l=ci.fromData(c);break;case"SupplyAndStakeLending":l=ii.fromData(c);break;case"WithdrawAndUnstakeLending":l=Ha.fromData(c);break;case"RedeemSca":l=ei.fromData(c);break;case"MigrateAndClaim":l=ja.fromData(c);break;case"BorrowWithReferral":l=Wa.fromData(c);break;case"CreateReferralLink":l=Ja.fromData(c);break;case"ClaimRevenueReferral":l=za.fromData(c);break;case"BindReferral":l=Qa.fromData(c);break;case"MigrateScoin":l=Ua.fromData(c);break;case"RepayWithBoost":l=Ka.fromData(c);break;case"MergeVeSca":l=ti.fromData(c);break;case"SplitVeSca":l=oi.fromData(c);break;case"VeScaObligationBindings":{l=ri.fromData(c);break}case"TransferVeScaKeys":{l=si.fromData(c);break}default:throw new Error("not implemented")}return l.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};var pm=require("@msafe/sui3-utils");var on=require("@msafe/sui3-utils"),Ce=require("@mysten/sui/utils");var nm=require("@suilend/sui-fe");var em=require("@msafe/sui3-utils"),Ie=require("@suilend/sdk");var Ne=require("@msafe/sui3-utils"),en=require("@mysten/bcs"),tn=require("@mysten/sui/utils"),We=require("@suilend/sui-fe"),Is=jt(require("bignumber.js"));var ui=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},t=(0,tn.normalizeStructTag)(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Ne.TransactionType.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(d=>d.type.includes("lending_market::RedeemEvent"))},n=(0,tn.normalizeStructTag)(t.RedeemEvent.parsedJson.coin_type.name),o=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let i=e.withdraw_ctokens.MoveCall.arguments[4].Input,c=new Is.default((0,en.toHex)((0,en.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),l=c===We.MAX_U64.toString();return console.log("decodeWithdraw - isMax:",l,"inputIndex:",i,"inputValue:",c,"MAX_U64.toString():",We.MAX_U64.toString()),l&&(o=We.MAX_U64.toString()),{txType:Ne.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(d=>d.type.includes("lending_market::BorrowEvent"))},n=(0,tn.normalizeStructTag)(t.BorrowEvent.parsedJson.coin_type.name),o=`${+t.BorrowEvent.parsedJson.liquidity_amount-+t.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,o);let i=e.borrow_request.MoveCall.arguments[4].Input,c=new Is.default((0,en.toHex)((0,en.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),l=c===We.MAX_U64.toString();return console.log("decodeBorrow - isMax:",l,"inputIndex:",i,"inputValue:",c,"MAX_U64.toString():",We.MAX_U64.toString()),l&&(o=We.MAX_U64.toString()),{txType:Ne.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},t=(0,tn.normalizeStructTag)(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Ne.TransactionType.Other,type:"repay",intentionData:{coinType:t,value:n}}}decodeClaim(){let e={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},t={};for(let n=0;n<e.ClaimReward.length;n++){let o=e.ClaimReward[n],i=(0,tn.normalizeStructTag)(o.parsedJson.coin_type.name),c=o.parsedJson.liquidity_amount;t[i]=`${+(t[i]??"0")+ +c}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Ne.TransactionType.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Ne.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var Hu=require("@mysten/sui/transactions");var $u=jt(require("sort-keys-recursive")),Wt=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,$u.default)(this.data))}};var mi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("BorrowIntention.build",n,o,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Hu.Transaction;return await i.borrowAndSendToUser(o.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};var zu=require("@mysten/sui/transactions");var Xu=require("@mysten/sui/utils"),nn=require("@suilend/sdk"),Gu=require("@suilend/sui-fe"),Qu=jt(require("bignumber.js")),Ad=(a,e)=>{let t={[nn.Side.DEPOSIT]:[],[nn.Side.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[nn.Side.DEPOSIT,nn.Side.BORROW].forEach(o=>{let i=o===nn.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,c=e.userRewardManagers.find(l=>l.poolRewardManagerId===i.id);c&&(t[o]=i.poolRewards.map((l,d)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(d),rewardCoinType:(0,Xu.normalizeStructTag)(l.coinType.name),side:o})).filter(l=>!(0,Gu.isSendPoints)(l.rewardCoinType)&&!!c.rewards[Number(l.rewardIndex)]&&new Qu.default(c.rewards[Number(l.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},pi=Ad;var di=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimIntention.build",n,o,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new zu.Transaction;return i.claimRewardsAndSendToUser(o.address,c.id,pi(i,l),d),d}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};var Ju=require("@mysten/sui/transactions");var fi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimAndDepositIntention.build",n,o,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Ju.Transaction;return i.claimRewardsAndDeposit(o.address,c.id,pi(i,l),d),d}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};var Yu=require("@mysten/sui/transactions");var hi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;console.log("DepositIntention.build",n,o,i,c,l);let d=new Yu.Transaction;return await i.depositIntoObligation(o.address,this.data.coinType,this.data.value,d,c?.id),d}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};var Zu=require("@mysten/sui/transactions");var gi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("RepayIntention.build",n,o,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Zu.Transaction;return await i.repayIntoObligation(o.address,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};var tm=require("@mysten/sui/transactions");var yi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("WithdrawIntention.build",n,o,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new tm.Transaction;return await i.withdrawAndSendToUser(o.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var bi=async(a,e)=>{let t=await Ie.SuilendClient.initialize(Ie.LENDING_MARKET_ID,Ie.LENDING_MARKET_TYPE,a),n=await Ie.SuilendClient.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(i=>Ie.SuilendClient.getObligation(i.obligationId,t.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:o}},Si=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await bi(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",i,"utils:",this.utils,"suiClient:",n);let l=new ui(t,i).decode();return{txType:em.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:c}=e;this.utils||(this.utils=await bi(i,c));let l;switch(n){case"deposit":l=hi.fromData(o);break;case"withdraw":l=yi.fromData(o);break;case"borrow":l=mi.fromData(o);break;case"repay":l=gi.fromData(o);break;case"claim":l=di.fromData(o);break;case"claimAndDeposit":l=fi.fromData(o);break;default:throw new Error("not implemented")}let d=window.localStorage.getItem("obligationId"),S=this.utils.obligations?.find(I=>I.id===d)??this.utils.obligations?.[0],w=this.utils.obligationOwnerCaps?.find(I=>I.obligationId===S?.id);return l.build({network:t,suiClient:i,account:c,suilendClient:this.utils.suilendClient,obligationOwnerCap:w,obligation:S})}};var Cs=async(a,e)=>{let t=await bi(a,e),n=await fetch(`${nm.API_URL}/springsui/lst-info`),o=await n.json();if(n?.statusCode===500)throw new Error("Failed to fetch SpringSui LST data");let c=Object.fromEntries(Object.values(o).map(l=>[l.LIQUID_STAKING_INFO.type,l.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:c}};var Ti=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:on.TransactionType.Other,type:"stake",intentionData:{amount:n,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:on.TransactionType.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:on.TransactionType.Other,type:"convert",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:on.TransactionType.Other,type:"convertAndDeposit",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeUnstake(){let e={RedeemEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::RedeemEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:on.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};var am=require("@mysten/sui/transactions"),_n=require("@suilend/springsui-sdk");var om=jt(require("sort-keys-recursive")),$t=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,om.default)(this.data))}};var wi=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertIntention.build",n,o,i,c,l,d);let S=await _n.LstClient.initialize(n,Object.values(c).find(C=>C.type===this.data.inCoinType)),w=await _n.LstClient.initialize(n,Object.values(c).find(C=>C.type===this.data.outCoinType)),I=new am.Transaction;return(0,_n.convertLstsAndSendToUser)(S,w,I,o.address,this.data.amount),I}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};var im=require("@mysten/sui/transactions"),Ci=require("@suilend/sdk"),Ln=require("@suilend/springsui-sdk");var Ii=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertAndDepositIntention.build",n,o,i,c,l,d);let S=await Ln.LstClient.initialize(n,Object.values(c).find(R=>R.type===this.data.inCoinType)),w=await Ln.LstClient.initialize(n,Object.values(c).find(R=>R.type===this.data.outCoinType)),I=new im.Transaction,{obligationOwnerCapId:C,didCreate:x}=(0,Ci.createObligationIfNoneExists)(i,I,l),v=(0,Ln.convertLsts)(S,w,I,o.address,this.data.amount);return i.deposit(v,this.data.outCoinType,C,I),x&&(0,Ci.sendObligationToUser)(C,o.address,I),I}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};var rm=require("@mysten/sui/transactions"),sm=require("@suilend/springsui-sdk");var ki=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeIntention.build",n,o,i,c,l,d);let S=await sm.LstClient.initialize(n,Object.values(c).find(I=>I.type===this.data.outCoinType)),w=new rm.Transaction;return S.mintAmountAndRebalanceAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};var cm=require("@mysten/sui/transactions"),vi=require("@suilend/sdk"),lm=require("@suilend/springsui-sdk");var xi=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeAndDepositIntention.build",n,o,i,c,l,d);let S=await lm.LstClient.initialize(n,Object.values(c).find(v=>v.type===this.data.outCoinType)),w=new cm.Transaction,{obligationOwnerCapId:I,didCreate:C}=(0,vi.createObligationIfNoneExists)(i,w,l),x=S.mintAmountAndRebalance(w,o.address,this.data.amount);return i.deposit(x,this.data.outCoinType,I,w),C&&(0,vi.sendObligationToUser)(I,o.address,w),w}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};var um=require("@mysten/sui/transactions"),mm=require("@suilend/springsui-sdk");var Di=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("UnstakeIntention.build",n,o,i,c,l,d);let S=await mm.LstClient.initialize(n,Object.values(c).find(I=>I.type===this.data.inCoinType)),w=new um.Transaction;return S.redeemAmountAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Ai=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Cs(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",i);let l=new Ti(t,i).decode();return{txType:pm.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:c}=e;this.utils||(this.utils=await Cs(i,c));let l;switch(n){case"stake":l=ki.fromData(o);break;case"stakeAndDeposit":l=xi.fromData(o);break;case"convert":l=wi.fromData(o);break;case"convertAndDeposit":l=Ii.fromData(o);break;case"unstake":l=Di.fromData(o);break;default:throw new Error("not implemented")}return l.build({network:t,suiClient:i,account:c,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};var hm=require("@msafe/sui3-utils");var ks=require("@msafe/sui3-utils");var Oi=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:ks.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:ks.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var dm=require("@alphafi/stsui-sdk");var Mi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new dm.LST(i).mint(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};var fm=require("@alphafi/stsui-sdk");var Pi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new fm.LST(i).redeem(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var Ri=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n}=e,o=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",o);let c=new Oi(t,o).decode();return{txType:hm.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let n;switch(e.txSubType){case"mint":n=Mi.fromData(e.intentionData);break;case"redeem":n=Pi.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};var _m=require("@msafe/sui3-utils"),Lm=require("turbos-clmm-sdk");var _t=require("@msafe/sui3-utils"),xs=require("@mysten/sui.js/bcs"),xe=require("@mysten/sui.js/utils"),gm=require("turbos-clmm-sdk");var Gt={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Qt={PackageId:"0xdee9"};var Rd=(a,e,t,n)=>{if(a===1)switch(n.findIndex(c=>c===e)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${e}`)}switch(t.findIndex(i=>i===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},Bi=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${Gt.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Gt.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(x=>x.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let n=Rd(t,e.target,this.swap1Layer,this.swap2Layer),o=n.map((x,v)=>{let R=this.helper.decodeSharedObjectId(v),K=this.helper.decodeInputU128(4+v+t),V=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new gm.BN(K.toString()));return{pool:R,a2b:x,nextTickIndex:V}}),i=n[0]||t===1?e.typeArguments[0]:e.typeArguments[1],c=t===1?e.typeArguments[4]:n[0]?e.typeArguments[1]:e.typeArguments[0],l=this.helper.decodeInputAddress(6+2*t),d=this.helper.decodeInputU64(7+2*t),S=this.helper.decodeInputBool(5+2*t),w=this.helper.decodeInputU64(2+t),I=this.helper.decodeInputU64(3+t),C=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:o[0].pool,a2b:o[0].a2b,amountSpecified:w}],address:l,amountSpecifiedIsInput:S});return{txType:_t.TransactionType.Other,type:"Swap",intentionData:{routes:o,coinTypeA:i,coinTypeB:c,address:l,amountA:S?w:I,amountB:S?I:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:d}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),c=this.helper.decodeInputBool(5),l=this.helper.decodeInputU32(6),d=this.helper.decodeInputBool(7),S=this.helper.decodeInputU64(13);return{txType:_t.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:n,amountB:o,tickLower:c?-i:i,tickUpper:d?-l:l,deadline:S}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),i=this.helper.decodeInputU64(6),c=this.helper.decodeInputU64(9);return{txType:_t.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:o,amountB:i,nft:n,deadline:c}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(5),l=this.helper.decodeInputU64(6);return{txType:_t.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:c,slippage:10,address:e,deadline:l}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(6);return{txType:_t.TransactionType.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:o,collectAmountB:i,nft:t,deadline:c}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(c=>c.decodeInputU64(5)),i=this.helper.decodeInputU64(7);return{txType:_t.TransactionType.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:o,nft:t,deadline:i}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:_t.TransactionType.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),i=this.decreaseLiquidityHelper.decodeInputU64(4),c=this.decreaseLiquidityHelper.decodeInputU64(5),l=this.decreaseLiquidityHelper.decodeInputU64(6),d=this.collectRewardHelper.map(I=>I.decodeInputU64(5)),S=this.collectFeeHelper.decodeInputU64(3)||0,w=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:_t.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:c,slippage:10,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:d,deadline:l}}}decodePrixClaim(){return{txType:_t.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:_t.TransactionType.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let e=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),t=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:_t.TransactionType.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let e=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),t=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:_t.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new ke(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new ke(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new ke(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new ke(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`);return new ke(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`);return new ke(e,this.txb)}},ke=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,xe.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return xs.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,xe.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,xe.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,xe.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,xe.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return xs.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,xe.normalizeStructTag)(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};var ym=require("turbos-clmm-sdk");var Ei=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new ym.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:c,amountB:l,slippage:d,tickLower:S,tickUpper:w,deadline:I,txb:C}=this.data;return n.pool.addLiquidity({pool:o,slippage:d,address:i,amountA:c,amountB:l,tickLower:S,tickUpper:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};var bm=require("turbos-clmm-sdk");var Ni=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new bm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,nft:i,txb:c}=this.data;return n.nft.burn({pool:o,nft:i,txb:c})}static fromData(t){return new a(t)}};var Sm=require("turbos-clmm-sdk");var Wi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Sm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:c,collectAmountA:l,collectAmountB:d,deadline:S,txb:w}=this.data;return n.pool.collectFee({pool:o,address:i,collectAmountA:l,collectAmountB:d,nft:c,deadline:S,txb:w})}static fromData(t){return new a(t)}};var Tm=require("turbos-clmm-sdk");var _i=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Tm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:c,rewardAmounts:l,deadline:d,txb:S}=this.data;return n.pool.collectReward({pool:o,address:i,rewardAmounts:l,nft:c,deadline:d,txb:S})}static fromData(t){return new a(t)}};var wm=require("turbos-clmm-sdk");var Li=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new wm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{fee:o,address:i,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,amountA:C,amountB:x,deadline:v,txb:R}=this.data;return n.pool.createPool({fee:o,amountA:C,amountB:x,address:i,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,deadline:v,txb:R})}static fromData(t){return new a(t)}};var Im=require("turbos-clmm-sdk");var ji=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Im.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:c,amountB:l,slippage:d,nft:S,decreaseLiquidity:w,deadline:I,txb:C}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:d,address:i,amountA:c,amountB:l,nft:S,decreaseLiquidity:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};var Cm=require("turbos-clmm-sdk");var Ui=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Cm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:c,amountB:l,slippage:d,nft:S,deadline:w,txb:I}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:d,address:i,amountA:c,amountB:l,nft:S,deadline:w,txb:I})}static fromData(t){return new a(t)}};var km=require("@mysten/sui.js/transactions"),xm=require("@mysten/sui.js/utils");var qi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new km.TransactionBlock;return n.moveCall({target:`${Gt.PackageId}::claim::claim`,typeArguments:[Gt.turbosCoinType],arguments:[n.object(Gt.Claim),n.object(xm.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(t){return new a(t)}};var vm=require("@mysten/sui.js/transactions");var Fi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new vm.TransactionBlock;return n.moveCall({target:`${Gt.PackageId}::claim::join`,typeArguments:[Gt.turbosCoinType],arguments:[n.object(Gt.Claim)]}),n}static fromData(t){return new a(t)}};var Dm=require("@mysten/sui.js/transactions"),Am=require("turbos-clmm-sdk");var Ki=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Am.TurbosSdk(t.network.replace("sui:",""),t.suiClient),o=new Dm.TransactionBlock;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(t){return new a(t)}};var Om=require("turbos-clmm-sdk");var Vi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new Om.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{routes:o,coinTypeA:i,coinTypeB:c,address:l,amountA:d,amountB:S,slippage:w,amountSpecifiedIsInput:I,deadline:C,txb:x}=this.data;return n.trade.swap({routes:o,coinTypeA:i,coinTypeB:c,address:l,amountA:d,amountB:S,amountSpecifiedIsInput:I,slippage:w,deadline:C,txb:x})}static fromData(t){return new a(t)}};var Nm=require("turbos-clmm-sdk");var vs=require("@mysten/sui.js/transactions"),Ds=require("@mysten/sui.js/utils");var Mm=require("turbos-clmm-sdk");var jn=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,n){let o=[],i;do i=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:i?.nextCursor}),o.push(...i.data);while(i.hasNextPage);let c=[],l=0;return o.sort((d,S)=>Number(S.balance)-Number(d.balance)).some(d=>l>=n?!0:(l+=Number(d.balance),c.push(d),!1)),c}splitAndMergeCoin(e,t,n){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[c]=n.splitCoins(n.gas,[n.pure(t)]);return[c,void 0]}let o=n.object(e[0].coinObjectId);e.length>1&&n.mergeCoins(o,e.slice(1).map(c=>n.object(c.coinObjectId)));let[i]=n.splitCoins(o,[n.pure(t)]);return[i,o]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${Qt.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?(0,Mm.unstable_getObjectId)(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Qt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var Pm=89,Rm=1e6,Bm=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:c}=a,l=new vs.TransactionBlock,d=new jn(c),S=await d.getCoinsData(i,t,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${t}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),[v,R,K]=l.moveCall({typeArguments:[e,t],target:`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[l.object(String(n)),l.pure(Pm),x,l.pure(o),l.object((0,Ds.normalizeSuiObjectId)("0x6")),w]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([v],l.pure(i)),l.transferObjects([R],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(Rm),l},Em=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:c}=a,l=new vs.TransactionBlock,d=new jn(c),S=await d.getCoinsData(i,e,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${e}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),v=d.zero(t,l),[R,K,V]=l.moveCall({typeArguments:[e,t],target:`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[l.object(String(n)),l.pure(Pm),x,l.pure(o),w,v,l.object((0,Ds.normalizeSuiObjectId)("0x6"))]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([R],l.pure(i)),l.transferObjects([K],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(Rm),l};var $i=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Nm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await Em({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var Wm=require("turbos-clmm-sdk");var Hi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Wm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await Bm({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var Xi=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new Lm.TurbosSdk(e.network.replace("sui:",""),e.suiClient),n=await t.contract.getConfig(),{transactionBlock:o,account:i}=e;console.log(e,"input");let l=await new Bi(o,t,n).decode(i.address);return{txType:_m.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":i=Li.fromData(e.intentionData);break;case"AddLiquidity":i=Ei.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Ui.fromData(e.intentionData);break;case"DecreaseLiquidity":i=ji.fromData(e.intentionData);break;case"RemoveLiquidity":i=Ki.fromData(e.intentionData);break;case"CollectFee":i=Wi.fromData(e.intentionData);break;case"CollectReward":i=_i.fromData(e.intentionData);break;case"Burn":i=Ni.fromData(e.intentionData);break;case"Swap":i=Vi.fromData(e.intentionData);break;case"PrixJoin":i=Fi.fromData(e.intentionData);break;case"PrixClaim":i=qi.fromData(e.intentionData);break;case"SwapExactBaseForQuote":i=$i.fromData(e.intentionData);break;case"SwapExactQuoteForBase":i=Hi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Fm=require("@msafe/sui3-utils");var Gi=require("@msafe/sui3-utils"),As=require("@mysten/sui.js/bcs"),ve=require("@mysten/sui.js/utils");var Bd={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Dt=Bd;var Qi=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:Gi.TransactionType.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Gi.TransactionType.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:Gi.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Dt.packageId));return new Os(e,this.txb)}},Os=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,ve.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return As.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,ve.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ve.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,ve.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ve.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return As.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,ve.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var jm=require("@mysten/sui.js/transactions");var zi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new jm.TransactionBlock,{ticketId:o}=this.data;return n.moveCall({target:`${Dt.packageId}::native_pool::burn_ticket`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new a(t)}};var Um=require("@mysten/sui.js/transactions");var Ji=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Um.TransactionBlock,{amount:o}=this.data,[i]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::stake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),i]}),n}static fromData(t){return new a(t)}};var qm=require("@mysten/sui.js/transactions");var Yi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new qm.TransactionBlock,{amount:o}=this.data,i=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[c,...l]=i.filter(w=>w.coinType.split("::")[0]===Dt.certType.split("::")[0]),d=n.object(c.coinObjectId);l.length&&n.mergeCoins(d,l.map(w=>n.object(w.coinObjectId)));let S=n.splitCoins(n.object(c.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::unstake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),S]}),n}static fromData(t){return new a(t)}};var Zi=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,o=new Qi(t).decode();return{txType:Fm.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case"Stake":o=Ji.fromData(e.intentionData);break;case"UnStake":o=Yi.fromData(e.intentionData);break;case"ClaimTicket":o=zi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Zm=require("@msafe/sui3-utils");var Ms=require("@cetusprotocol/common-sdk"),De=require("@msafe/sui3-utils"),an=require("@mysten/bcs"),rn=require("@mysten/sui/bcs");var tr=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:De.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number((0,Ms.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,Ms.asIntN)(BigInt(this.getU32(this.getInputIndex(e,3)))).toString()),tokenAmount:this.getU64(this.getInputIndex(t,6)),maxAmountTokenA:this.getU64(this.getInputIndex(t,7)),maxAmountTokenB:this.getU64(this.getInputIndex(t,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(t,9))}}}decodeClosePositionTx(){let e=this.getMoveCallCommand("close_position"),t=this.getCollectRewardCallData();return{txType:De.TransactionType.Other,type:"ClosePosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),transferTokensTo:this.getAddress(this.getInputIndex(e,4)),collectRewardTokens:t.map(n=>n.rewardCoinType),collectFeeTokens:this.getTypeArguments(e)}}}decodeProvideLiquidityTx(){let e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:De.TransactionType.Other,type:"ProvideLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),tokenAmount:this.getU64(this.getInputIndex(e,6)),maxAmountTokenA:this.getU64(this.getInputIndex(e,7)),maxAmountTokenB:this.getU64(this.getInputIndex(e,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(e,9))}}}decodeRemoveLiquidityTx(){let e=this.getMoveCallCommand("remove_liquidity");return{txType:De.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),liquidity:this.getU128(this.getInputIndex(e,4)),maxAmountTokenA:this.getU64(this.getInputIndex(e,5)),maxAmountTokenB:this.getU64(this.getInputIndex(e,6)),transferTokensTo:this.getAddress(this.getInputIndex(e,7)),...this.collectTokens()}}}decodeCollectRewardsTx(){let e=this.getCollectRewardCallData();return{txType:De.TransactionType.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:De.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:De.TransactionType.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(n=>n.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(rn.bcs.u32().parse(Uint8Array.from((0,an.fromBase64)(this.inputs[e].Pure.bytes))))}getU64(e){return rn.bcs.u64().parse(Uint8Array.from((0,an.fromBase64)(this.inputs[e].Pure.bytes)))}getU128(e){return rn.bcs.u128().parse(Uint8Array.from((0,an.fromBase64)(this.inputs[e].Pure.bytes)))}getBoolean(e){return rn.bcs.bool().parse(Uint8Array.from((0,an.fromBase64)(this.inputs[e].Pure.bytes)))}getAddress(e){return rn.bcs.Address.parse(Uint8Array.from((0,an.fromBase64)(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};var Hm=require("@msafe/sui3-utils");var ee=require("@firefly-exchange/library-sui");var Vm=require("@firefly-exchange/library-sui"),$m=require("@firefly-exchange/library-sui/dist/src/spot"),Km={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},Oe=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Vm.SuiClient({url:Km.rpc});return new $m.OnChainCalls(t,Km.objects,{address:e.address,isUIWallet:!1})};var Rt=class{static async OpenPosition(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(i,{...e,slippage:0});return await o.openPositionWithFixedAmount(i,e.lowerTick,e.upperTick,c,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(i,e);return await o.provideLiquidityWithFixedAmount(i,e.position,c,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(i,e.position,{liquidityAmount:new ee.BN(e.liquidity),tokenMaxA:new ee.BN(e.maxAmountTokenA),tokenMaxB:new ee.BN(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.closePosition(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectRewards(i,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectFee(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return console.log(e.position),await o.collectFeeAndRewards(i,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...ee.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ee.BN(t.tokenAmount),t.isTokenAFixed,!0,0,new ee.BN(e.current_sqrt_price)),tokenMaxA:new ee.BN(t.maxAmountTokenA),tokenMaxB:new ee.BN(t.maxAmountTokenB)}}};var er=class a extends k{constructor(t){super(t);this.data=t}txType=Hm.TransactionType.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.closePosition(this.data,n,o)}static fromData(t){return new a(t)}};var Xm=require("@msafe/sui3-utils");var nr=class a extends k{constructor(t){super(t);this.data=t}txType=Xm.TransactionType.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectFee(this.data,n,o)}static fromData(t){return new a(t)}};var Gm=require("@msafe/sui3-utils");var or=class a extends k{constructor(t){super(t);this.data=t}txType=Gm.TransactionType.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectRewards(this.data,n,o)}static fromData(t){return new a(t)}};var Qm=require("@msafe/sui3-utils");var ar=class a extends k{constructor(t){super(t);this.data=t}txType=Qm.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new a(t)}};var zm=require("@msafe/sui3-utils");var ir=class a extends k{constructor(t){super(t);this.data=t}txType=zm.TransactionType.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.OpenPosition(this.data,n,o)}static fromData(t){return new a(t)}};var Jm=require("@msafe/sui3-utils");var rr=class a extends k{constructor(t){super(t);this.data=t}txType=Jm.TransactionType.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.provideLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var Ym=require("@msafe/sui3-utils");var sr=class a extends k{constructor(t){super(t);this.data=t}txType=Ym.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.removeLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var cr=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,o=new tr(t).decode();return{txType:Zm.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let i;switch(e.txSubType){case"OpenPosition":i=ir.fromData(e.intentionData);break;case"ProvideLiquidity":i=rr.fromData(e.intentionData);break;case"RemoveLiquidity":i=sr.fromData(e.intentionData);break;case"ClosePosition":i=er.fromData(e.intentionData);break;case"CollectFee":i=nr.fromData(e.intentionData);break;case"CollectRewards":i=or.fromData(e.intentionData);break;case"CollectRewardsAndFee":i=ar.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var vp=require("@msafe/sui3-utils");var lp=require("@mmt-finance/clmm-sdk"),up=require("@mysten/sui/transactions");var _e=require("@mmt-finance/clmm-sdk/dist/utils/math/tickMath"),B=jt(ep());var Nd="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",sn=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Wd=async({suiClient:a,address:e,type:t})=>{let n,o=[],i=0;do{try{let c=await a.getCoins({owner:e,coinType:t,cursor:n,limit:50});o=o.concat(c.data),n=c.nextCursor,(!c.hasNextPage||i===8)&&(n=null)}catch(c){console.log(c),n=null}i++}while(n!==null);return o},_d=(a,e)=>{let t=[],n=BigInt(0);for(let o of e)n<a&&!t.includes(o.objectId)&&(t.push(o.objectId),n+=BigInt(o.balance)),o.balance===BigInt(0)&&!t.includes(o.objectId)&&t.push(o.objectId);if(n>=a)return t;throw new Error("Insufficient balance")},Ld=(a,e,t,n)=>{if(a===Nd){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=_d(t,e);o.length>1&&n.mergeCoins(n.object(o[0]),o.slice(1).map(c=>n.object(c)));let[i]=n.splitCoins(n.object(o[0]),[n.pure.u64(t)]);return i}};async function np(a,e,t,n,o){let i=await Wd({suiClient:a.rpcClient,address:e,type:t});return Ld(sn(t),i.map(l=>({balance:BigInt(l.balance),objectId:l.coinObjectId})),n,o)}function N(a,e,t){let n=a.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function jd(a){let e;return a&1?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),a&2&&(e=N(e.mul(new B.default("79236085330515764027303304731")),96,256)),a&4&&(e=N(e.mul(new B.default("79244008939048815603706035061")),96,256)),a&8&&(e=N(e.mul(new B.default("79259858533276714757314932305")),96,256)),a&16&&(e=N(e.mul(new B.default("79291567232598584799939703904")),96,256)),a&32&&(e=N(e.mul(new B.default("79355022692464371645785046466")),96,256)),a&64&&(e=N(e.mul(new B.default("79482085999252804386437311141")),96,256)),a&128&&(e=N(e.mul(new B.default("79736823300114093921829183326")),96,256)),a&256&&(e=N(e.mul(new B.default("80248749790819932309965073892")),96,256)),a&512&&(e=N(e.mul(new B.default("81282483887344747381513967011")),96,256)),a&1024&&(e=N(e.mul(new B.default("83390072131320151908154831281")),96,256)),a&2048&&(e=N(e.mul(new B.default("87770609709833776024991924138")),96,256)),a&4096&&(e=N(e.mul(new B.default("97234110755111693312479820773")),96,256)),a&8192&&(e=N(e.mul(new B.default("119332217159966728226237229890")),96,256)),a&16384&&(e=N(e.mul(new B.default("179736315981702064433883588727")),96,256)),a&32768&&(e=N(e.mul(new B.default("407748233172238350107850275304")),96,256)),a&65536&&(e=N(e.mul(new B.default("2098478828474011932436660412517")),96,256)),a&131072&&(e=N(e.mul(new B.default("55581415166113811149459800483533")),96,256)),a&262144&&(e=N(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),N(e,32,256)}function Ud(a){let e=Math.abs(a),t;return e&1?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),e&2&&(t=N(t.mul(new B.default("18444899583751176498")),64,256)),e&4&&(t=N(t.mul(new B.default("18443055278223354162")),64,256)),e&8&&(t=N(t.mul(new B.default("18439367220385604838")),64,256)),e&16&&(t=N(t.mul(new B.default("18431993317065449817")),64,256)),e&32&&(t=N(t.mul(new B.default("18417254355718160513")),64,256)),e&64&&(t=N(t.mul(new B.default("18387811781193591352")),64,256)),e&128&&(t=N(t.mul(new B.default("18329067761203520168")),64,256)),e&256&&(t=N(t.mul(new B.default("18212142134806087854")),64,256)),e&512&&(t=N(t.mul(new B.default("17980523815641551639")),64,256)),e&1024&&(t=N(t.mul(new B.default("17526086738831147013")),64,256)),e&2048&&(t=N(t.mul(new B.default("16651378430235024244")),64,256)),e&4096&&(t=N(t.mul(new B.default("15030750278693429944")),64,256)),e&8192&&(t=N(t.mul(new B.default("12247334978882834399")),64,256)),e&16384&&(t=N(t.mul(new B.default("8131365268884726200")),64,256)),e&32768&&(t=N(t.mul(new B.default("3584323654723342297")),64,256)),e&65536&&(t=N(t.mul(new B.default("696457651847595233")),64,256)),e&131072&&(t=N(t.mul(new B.default("26294789957452057")),64,256)),e&262144&&(t=N(t.mul(new B.default("37481735321082")),64,256)),t}var op=(a,e,t)=>{let n=(0,_e.convertI32ToSigned)(t?a+a%(e??1):a-a%(e??1));return n>0?new B.default(jd(n)):new B.default(Ud(n))};function ip(a,e){if(!/^(\d+)(\.\d+)?$/.test(a))return BigInt(0);let[t,n=""]=a.split("."),o=(n+"0".repeat(e)).slice(0,e),c=(t+o).replace(/^0+/,"")||"0";return BigInt(c)}async function Un({address:a,coinType:e,coinAmount:t,coinDecimals:n,tx:o,mmt:i}){let c=ip(t,n),l;return Number(t)?l=await np(i,a,sn(e),c,o):[l]=o.moveCall({target:"0x2::coin::zero",typeArguments:[e],arguments:[]}),l}function rp({mmt:a,tx:e,poolModel:t,selectedLowTick:n,selectedHighTick:o}){let i=op((0,_e.convertI32ToSigned)(n),t.tickSpacing),c=op((0,_e.convertI32ToSigned)(o),t.tickSpacing);return a.Position.openPosition(e,t,i.toString(),c.toString())}var qd=(a,e)=>a*BigInt(100-e)/BigInt(100);function ap(a,e,t){let n=ip(a,e);return Number(a)===0?BigInt(0):qd(n,t)}async function Rs({poolId:a,currentSqrtPrice:e,tokenX:t,tokenY:n,slippagePercentage:o,isTokenX:i,suiClient:c}){let d=(await c.getObject({id:a,options:{showContent:!0}}))?.data?.content?.fields?.sqrt_price??e,S=_e.TickMath.sqrtPriceX64ToPrice(new B.default(d?.toString()),t.decimals,n.decimals),w=i?(100-o)/100:(100+o)/100,I=_e.TickMath.priceToSqrtPriceX64(S.mul(w),t.decimals,n.decimals);return BigInt(I.toString())}var sp=async(a,e,t,n,o,i,c,l,d,S)=>{let w=await Un({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:n,coinDecimals:i.tokenX.decimals,tx:e}),I=await Un({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:o,coinDecimals:i.tokenY.decimals,tx:e}),C={objectId:c,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing},x=rp({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),v=ap(n,i.tokenX.decimals,S),R=ap(o,i.tokenY.decimals,S);a.Pool.addLiquidity(e,C,x,w,I,v,R,t),e.transferObjects([x],e.pure.address(t))},cp=async(a,e,t,n,o,i,c,l,d,S,w)=>{try{let I=await Un({mmt:a,address:n,coinType:i?c.tokenX.coinType:c.tokenY.coinType,coinAmount:o,coinDecimals:i?c.tokenX.decimals:c.tokenY.decimals,tx:e}),C={objectId:c.objectId,tokenXType:c.tokenX.coinType,tokenYType:c.tokenY.coinType,tickSpacing:c.tickSpacing},x=rp({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),v=await Rs({suiClient:t,poolId:c.poolId,currentSqrtPrice:c.currentSqrtPrice,tokenX:c.tokenX,tokenY:c.tokenY,slippagePercentage:S,isTokenX:i});await a.Pool.addLiquiditySingleSidedV2({txb:e,pool:C,position:C.objectId,inputCoin:I,isXtoY:i,limitSqrtPrice:v,slippagePercentage:w,transferToAddress:n}),e.transferObjects([x],e.pure.address(n))}catch(I){console.error(I)}};var lr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=lp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amountA:i,amountB:c,pool:l,selectedLowTick:d,selectedHighTick:S,slippage:w}=n,I=new up.Transaction;return await sp(t,I,o,i,c,l,l.objectId,d,S,w),I}static fromData(t){return new a(t)}};var mp=require("@mmt-finance/clmm-sdk"),pp=require("@mysten/sui/transactions");var ur=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=mp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amount:i,isTokenX:c,pool:l,selectedLowTick:d,selectedHighTick:S,swapSlippage:w,addLiquiditySlippage:I}=n,C=new pp.Transaction;return await cp(t,C,t.rpcClient,o,i,c,l,d,S,w,I),C}static fromData(t){return new a(t)}};var dp=require("@mmt-finance/clmm-sdk"),fp=require("@mysten/sui/transactions");var cn=(a,e,t,n,o)=>{let i={objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType};n?.rewarders&&n?.rewarders.length>0&&a.Pool.collectAllRewards(o,i,n.rewarders.map(c=>({coin_type:c.coinType,flow_rate:c.flowRate,reward_amount:c.rewardAmount,rewards_allocated:c.rewardsAllocated,hasEnded:c.hasEnded})),t.objectId,e),a.Pool.collectFee(o,{objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,isStable:n.isStable,tickSpacing:n.tickSpacing},t.objectId,e)};var mr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=dp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,positions:i,pools:c}=n,l=new fp.Transaction;for(let d of i){let S=c.find(w=>w.poolId===d.poolId);S&&cn(t,o,d,S,l)}return l}static fromData(t){return new a(t)}};var hp=require("@mmt-finance/clmm-sdk"),gp=require("@mysten/sui/transactions");var pr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=hp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,position:i,pool:c}=n,l=new gp.Transaction;return cn(t,o,i,c,l),l}static fromData(t){return new a(t)}};var yp=require("@mmt-finance/clmm-sdk"),bp=require("@mysten/sui/transactions"),Sp=jt(require("bignumber.js"));var dr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=yp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{pool:o,position:i,address:c,withdrawPercentage:l}=n,d=new bp.Transaction,S=o.tokenX.coinType,w=o.tokenY.coinType,I={objectId:o.objectId,tokenXType:S,tokenYType:w},C=BigInt(l===100?i.liquidity:new Sp.default(i.liquidity).multipliedBy(l/100).toFixed(0));return t.Pool.removeLiquidity(d,I,i.objectId,C,BigInt(0),BigInt(0),c),cn(t,c,i,o,d),l===100&&t.Position.closePosition(d,i.objectId),d}static fromData(t){return new a(t)}};var Es=require("@mysten/sui/transactions"),Ns=require("@suilend/springsui-sdk"),Bs={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},Tp=async(a,e,t)=>{let n=await Ns.LstClient.initialize(a,Bs),o=new Es.Transaction,[i]=o.splitCoins(o.gas,[BigInt(t)]),c=n.mint(o,i);return o.transferObjects([c],e),o},wp=async(a,e,t)=>{let n=await Ns.LstClient.initialize(a,Bs),o=await a.getCoins({owner:e,coinType:Bs.type,limit:1e3});if(o.data.length===0)throw new Error("No lst coins found");let i=new Es.Transaction,c=o.data[0];o.data.length>1&&i.mergeCoins(c.coinObjectId,o.data.slice(1).map(S=>S.coinObjectId));let[l]=i.splitCoins(c.coinObjectId,[BigInt(t)]),d=n.redeem(i,l);return i.transferObjects([d],e),i};var fr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return await Tp(t.suiClient,o,i)}static fromData(t){return new a(t)}};var kp=require("@mmt-finance/clmm-sdk"),xp=require("@mysten/sui/transactions");var Ip=require("@mmt-finance/clmm-sdk/dist/utils/poolUtils");var Cp=async(a,e,t,n,o,i,c)=>{let l=await Un({mmt:a,tx:i,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals}),d=i.moveCall({target:"0x2::coin::value",typeArguments:[t.coinType],arguments:[l]}),S=t.coinType;for(let w=0;w<e.length;w+=1){let{poolId:I,tokenX:C,tokenY:x,isStable:v}=e[w],{id:R,isReverse:K}=Ip.mappedMmtV3Pool[I]||{id:I,isReverse:!1},V=sn(C.coinType)===sn(S);V=K?!V:V;let Ht=K?x.coinType:C.coinType,Et=K?C.coinType:x.coinType,Pt=await Rs({poolId:R,tokenX:C,tokenY:x,slippagePercentage:c,isTokenX:V,suiClient:a.rpcClient}),ln=a.Pool.swap(i,{objectId:R,tokenXType:Ht,tokenYType:Et,isStable:v},d,l,V,void 0,Pt,!1);i.transferObjects([l],i.pure.address(o)),l=ln,S=V?Et:Ht,d=i.moveCall({target:"0x2::coin::value",typeArguments:[S],arguments:[l]})}i.transferObjects([l],i.pure.address(o))};var hr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=kp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{route:o,tokenIn:i,amountIn:c,address:l,slippage:d}=n,S=new xp.Transaction;return await Cp(t,o,i,c,l,S,d),S}static fromData(t){return new a(t)}};var gr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return await wp(t.suiClient,o,i)}static fromData(t){return new a(t)}};var yr=class{application="mmt-dex";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:vp.TransactionType.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=hr.fromData(e.intentionData);break;case"AddLiquidity":t=lr.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=ur.fromData(e.intentionData);break;case"ClaimRewards":t=pr.fromData(e.intentionData);break;case"ClaimAllRewards":t=mr.fromData(e.intentionData);break;case"RemoveLiquidity":t=dr.fromData(e.intentionData);break;case"StakeXSui":t=fr.fromData(e.intentionData);break;case"UnstakeXSui":t=gr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build({suiClient:e.suiClient})}};var Fd=Aa.fromHelpers([new da,new Ca,new ua,new ka,new Fo,new Xi,new yr,new li,new Zi,new ho,new Si,new Ai,new Qn,new cr,new Ri]);
|
|
1
|
+
"use strict";var Np=Object.create;var Fn=Object.defineProperty;var Wp=Object.getOwnPropertyDescriptor;var _p=Object.getOwnPropertyNames;var Lp=Object.getPrototypeOf,jp=Object.prototype.hasOwnProperty;var Up=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Fr=(a,e)=>{for(var t in e)Fn(a,t,{get:e[t],enumerable:!0})},ac=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _p(e))!jp.call(a,o)&&o!==t&&Fn(a,o,{get:()=>e[o],enumerable:!(n=Wp(e,o))||n.enumerable});return a};var jt=(a,e,t)=>(t=a!=null?Np(Lp(a)):{},ac(e||!a||!a.__esModule?Fn(t,"default",{value:a,enumerable:!0}):t,a)),qp=a=>ac(Fn({},"__esModule",{value:!0}),a);var ap=Up((op,Ns)=>{"use strict";(function(a,e){"use strict";function t(y,r){if(!y)throw new Error(r||"Assertion failed")}function n(y,r){y.super_=r;var u=function(){};u.prototype=r.prototype,y.prototype=new u,y.prototype.constructor=y}function o(y,r,u){if(o.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((r==="le"||r==="be")&&(u=r,r=10),this._init(y||0,r||10,u||"be"))}typeof a=="object"?a.exports=o:e.BN=o,o.BN=o,o.wordSize=26;var i;try{typeof window<"u"&&typeof window.Buffer<"u"?i=window.Buffer:i=require("buffer").Buffer}catch{}o.isBN=function(r){return r instanceof o?!0:r!==null&&typeof r=="object"&&r.constructor.wordSize===o.wordSize&&Array.isArray(r.words)},o.max=function(r,u){return r.cmp(u)>0?r:u},o.min=function(r,u){return r.cmp(u)<0?r:u},o.prototype._init=function(r,u,m){if(typeof r=="number")return this._initNumber(r,u,m);if(typeof r=="object")return this._initArray(r,u,m);u==="hex"&&(u=16),t(u===(u|0)&&u>=2&&u<=36),r=r.toString().replace(/\s+/g,"");var p=0;r[0]==="-"&&(p++,this.negative=1),p<r.length&&(u===16?this._parseHex(r,p,m):(this._parseBase(r,u,p),m==="le"&&this._initArray(this.toArray(),u,m)))},o.prototype._initNumber=function(r,u,m){r<0&&(this.negative=1,r=-r),r<67108864?(this.words=[r&67108863],this.length=1):r<4503599627370496?(this.words=[r&67108863,r/67108864&67108863],this.length=2):(t(r<9007199254740992),this.words=[r&67108863,r/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),u,m)},o.prototype._initArray=function(r,u,m){if(t(typeof r.length=="number"),r.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(r.length/3),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h,b,T=0;if(m==="be")for(p=r.length-1,h=0;p>=0;p-=3)b=r[p]|r[p-1]<<8|r[p-2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);else if(m==="le")for(p=0,h=0;p<r.length;p+=3)b=r[p]|r[p+1]<<8|r[p+2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);return this._strip()};function s(y,r){var u=y.charCodeAt(r);if(u>=48&&u<=57)return u-48;if(u>=65&&u<=70)return u-55;if(u>=97&&u<=102)return u-87;t(!1,"Invalid character in "+y)}function l(y,r,u){var m=s(y,u);return u-1>=r&&(m|=s(y,u-1)<<4),m}o.prototype._parseHex=function(r,u,m){this.length=Math.ceil((r.length-u)/6),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h=0,b=0,T;if(m==="be")for(p=r.length-1;p>=u;p-=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8;else{var f=r.length-u;for(p=f%2===0?u+1:u;p<r.length;p+=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8}this._strip()};function d(y,r,u,m){for(var p=0,h=0,b=Math.min(y.length,u),T=r;T<b;T++){var f=y.charCodeAt(T)-48;p*=m,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<m,"Invalid character"),p+=h}return p}o.prototype._parseBase=function(r,u,m){this.words=[0],this.length=1;for(var p=0,h=1;h<=67108863;h*=u)p++;p--,h=h/u|0;for(var b=r.length-m,T=b%p,f=Math.min(b,b-T)+m,c=0,g=m;g<f;g+=p)c=d(r,g,g+p,u),this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(T!==0){var v=1;for(c=d(r,g,r.length,u),g=0;g<T;g++)v*=u;this.imuln(v),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this._strip()},o.prototype.copy=function(r){r.words=new Array(this.length);for(var u=0;u<this.length;u++)r.words[u]=this.words[u];r.length=this.length,r.negative=this.negative,r.red=this.red};function S(y,r){y.words=r.words,y.length=r.length,y.negative=r.negative,y.red=r.red}if(o.prototype._move=function(r){S(r,this)},o.prototype.clone=function(){var r=new o(null);return this.copy(r),r},o.prototype._expand=function(r){for(;this.length<r;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},o.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{o.prototype.inspect=w}else o.prototype.inspect=w;function w(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],C=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],x=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(r,u){r=r||10,u=u|0||1;var m;if(r===16||r==="hex"){m="";for(var p=0,h=0,b=0;b<this.length;b++){var T=this.words[b],f=((T<<p|h)&16777215).toString(16);h=T>>>24-p&16777215,p+=2,p>=26&&(p-=26,b--),h!==0||b!==this.length-1?m=I[6-f.length]+f+m:m=f+m}for(h!==0&&(m=h.toString(16)+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(r===(r|0)&&r>=2&&r<=36){var c=C[r],g=x[r];m="";var v=this.clone();for(v.negative=0;!v.isZero();){var O=v.modrn(g).toString(r);v=v.idivn(g),v.isZero()?m=O+m:m=I[c-O.length]+O+m}for(this.isZero()&&(m="0"+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}t(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var r=this.words[0];return this.length===2?r+=this.words[1]*67108864:this.length===3&&this.words[2]===1?r+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-r:r},o.prototype.toJSON=function(){return this.toString(16,2)},i&&(o.prototype.toBuffer=function(r,u){return this.toArrayLike(i,r,u)}),o.prototype.toArray=function(r,u){return this.toArrayLike(Array,r,u)};var D=function(r,u){return r.allocUnsafe?r.allocUnsafe(u):new r(u)};o.prototype.toArrayLike=function(r,u,m){this._strip();var p=this.byteLength(),h=m||Math.max(1,p);t(p<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var b=D(r,h),T=u==="le"?"LE":"BE";return this["_toArrayLike"+T](b,p),b},o.prototype._toArrayLikeLE=function(r,u){for(var m=0,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m++]=T&255,m<r.length&&(r[m++]=T>>8&255),m<r.length&&(r[m++]=T>>16&255),b===6?(m<r.length&&(r[m++]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m<r.length)for(r[m++]=p;m<r.length;)r[m++]=0},o.prototype._toArrayLikeBE=function(r,u){for(var m=r.length-1,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m--]=T&255,m>=0&&(r[m--]=T>>8&255),m>=0&&(r[m--]=T>>16&255),b===6?(m>=0&&(r[m--]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m>=0)for(r[m--]=p;m>=0;)r[m--]=0},Math.clz32?o.prototype._countBits=function(r){return 32-Math.clz32(r)}:o.prototype._countBits=function(r){var u=r,m=0;return u>=4096&&(m+=13,u>>>=13),u>=64&&(m+=7,u>>>=7),u>=8&&(m+=4,u>>>=4),u>=2&&(m+=2,u>>>=2),m+u},o.prototype._zeroBits=function(r){if(r===0)return 26;var u=r,m=0;return u&8191||(m+=13,u>>>=13),u&127||(m+=7,u>>>=7),u&15||(m+=4,u>>>=4),u&3||(m+=2,u>>>=2),u&1||m++,m},o.prototype.bitLength=function(){var r=this.words[this.length-1],u=this._countBits(r);return(this.length-1)*26+u};function R(y){for(var r=new Array(y.bitLength()),u=0;u<r.length;u++){var m=u/26|0,p=u%26;r[u]=y.words[m]>>>p&1}return r}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,u=0;u<this.length;u++){var m=this._zeroBits(this.words[u]);if(r+=m,m!==26)break}return r},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(r){return this.negative!==0?this.abs().inotn(r).iaddn(1):this.clone()},o.prototype.fromTwos=function(r){return this.testn(r-1)?this.notn(r).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return this.negative!==0},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(r){for(;this.length<r.length;)this.words[this.length++]=0;for(var u=0;u<r.length;u++)this.words[u]=this.words[u]|r.words[u];return this._strip()},o.prototype.ior=function(r){return t((this.negative|r.negative)===0),this.iuor(r)},o.prototype.or=function(r){return this.length>r.length?this.clone().ior(r):r.clone().ior(this)},o.prototype.uor=function(r){return this.length>r.length?this.clone().iuor(r):r.clone().iuor(this)},o.prototype.iuand=function(r){var u;this.length>r.length?u=r:u=this;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]&r.words[m];return this.length=u.length,this._strip()},o.prototype.iand=function(r){return t((this.negative|r.negative)===0),this.iuand(r)},o.prototype.and=function(r){return this.length>r.length?this.clone().iand(r):r.clone().iand(this)},o.prototype.uand=function(r){return this.length>r.length?this.clone().iuand(r):r.clone().iuand(this)},o.prototype.iuxor=function(r){var u,m;this.length>r.length?(u=this,m=r):(u=r,m=this);for(var p=0;p<m.length;p++)this.words[p]=u.words[p]^m.words[p];if(this!==u)for(;p<u.length;p++)this.words[p]=u.words[p];return this.length=u.length,this._strip()},o.prototype.ixor=function(r){return t((this.negative|r.negative)===0),this.iuxor(r)},o.prototype.xor=function(r){return this.length>r.length?this.clone().ixor(r):r.clone().ixor(this)},o.prototype.uxor=function(r){return this.length>r.length?this.clone().iuxor(r):r.clone().iuxor(this)},o.prototype.inotn=function(r){t(typeof r=="number"&&r>=0);var u=Math.ceil(r/26)|0,m=r%26;this._expand(u),m>0&&u--;for(var p=0;p<u;p++)this.words[p]=~this.words[p]&67108863;return m>0&&(this.words[p]=~this.words[p]&67108863>>26-m),this._strip()},o.prototype.notn=function(r){return this.clone().inotn(r)},o.prototype.setn=function(r,u){t(typeof r=="number"&&r>=0);var m=r/26|0,p=r%26;return this._expand(m+1),u?this.words[m]=this.words[m]|1<<p:this.words[m]=this.words[m]&~(1<<p),this._strip()},o.prototype.iadd=function(r){var u;if(this.negative!==0&&r.negative===0)return this.negative=0,u=this.isub(r),this.negative^=1,this._normSign();if(this.negative===0&&r.negative!==0)return r.negative=0,u=this.isub(r),r.negative=1,u._normSign();var m,p;this.length>r.length?(m=this,p=r):(m=r,p=this);for(var h=0,b=0;b<p.length;b++)u=(m.words[b]|0)+(p.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;for(;h!==0&&b<m.length;b++)u=(m.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;if(this.length=m.length,h!==0)this.words[this.length]=h,this.length++;else if(m!==this)for(;b<m.length;b++)this.words[b]=m.words[b];return this},o.prototype.add=function(r){var u;return r.negative!==0&&this.negative===0?(r.negative=0,u=this.sub(r),r.negative^=1,u):r.negative===0&&this.negative!==0?(this.negative=0,u=r.sub(this),this.negative=1,u):this.length>r.length?this.clone().iadd(r):r.clone().iadd(this)},o.prototype.isub=function(r){if(r.negative!==0){r.negative=0;var u=this.iadd(r);return r.negative=1,u._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(r),this.negative=1,this._normSign();var m=this.cmp(r);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,h;m>0?(p=this,h=r):(p=r,h=this);for(var b=0,T=0;T<h.length;T++)u=(p.words[T]|0)-(h.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;for(;b!==0&&T<p.length;T++)u=(p.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;if(b===0&&T<p.length&&p!==this)for(;T<p.length;T++)this.words[T]=p.words[T];return this.length=Math.max(this.length,T),p!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(r){return this.clone().isub(r)};function K(y,r,u){u.negative=r.negative^y.negative;var m=y.length+r.length|0;u.length=m,m=m-1|0;var p=y.words[0]|0,h=r.words[0]|0,b=p*h,T=b&67108863,f=b/67108864|0;u.words[0]=T;for(var c=1;c<m;c++){for(var g=f>>>26,v=f&67108863,O=Math.min(c,r.length-1),M=Math.max(0,c-y.length+1);M<=O;M++){var E=c-M|0;p=y.words[E]|0,h=r.words[M]|0,b=p*h+v,g+=b/67108864|0,v=b&67108863}u.words[c]=v|0,f=g|0}return f!==0?u.words[c]=f|0:u.length--,u._strip()}var V=function(r,u,m){var p=r.words,h=u.words,b=m.words,T=0,f,c,g,v=p[0]|0,O=v&8191,M=v>>>13,E=p[1]|0,_=E&8191,j=E>>>13,re=p[2]|0,U=re&8191,q=re>>>13,qs=p[3]|0,X=qs&8191,G=qs>>>13,Fs=p[4]|0,Q=Fs&8191,z=Fs>>>13,Ks=p[5]|0,J=Ks&8191,Y=Ks>>>13,Vs=p[6]|0,Z=Vs&8191,tt=Vs>>>13,$s=p[7]|0,et=$s&8191,nt=$s>>>13,Hs=p[8]|0,ot=Hs&8191,at=Hs>>>13,Xs=p[9]|0,it=Xs&8191,rt=Xs>>>13,Gs=h[0]|0,st=Gs&8191,ct=Gs>>>13,Qs=h[1]|0,lt=Qs&8191,ut=Qs>>>13,zs=h[2]|0,mt=zs&8191,pt=zs>>>13,Js=h[3]|0,dt=Js&8191,ft=Js>>>13,Ys=h[4]|0,ht=Ys&8191,gt=Ys>>>13,Zs=h[5]|0,yt=Zs&8191,bt=Zs>>>13,tc=h[6]|0,St=tc&8191,Tt=tc>>>13,ec=h[7]|0,wt=ec&8191,It=ec>>>13,nc=h[8]|0,Ct=nc&8191,kt=nc>>>13,oc=h[9]|0,xt=oc&8191,Dt=oc>>>13;m.negative=r.negative^u.negative,m.length=19,f=Math.imul(O,st),c=Math.imul(O,ct),c=c+Math.imul(M,st)|0,g=Math.imul(M,ct);var Cr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,f=Math.imul(_,st),c=Math.imul(_,ct),c=c+Math.imul(j,st)|0,g=Math.imul(j,ct),f=f+Math.imul(O,lt)|0,c=c+Math.imul(O,ut)|0,c=c+Math.imul(M,lt)|0,g=g+Math.imul(M,ut)|0;var kr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(kr>>>26)|0,kr&=67108863,f=Math.imul(U,st),c=Math.imul(U,ct),c=c+Math.imul(q,st)|0,g=Math.imul(q,ct),f=f+Math.imul(_,lt)|0,c=c+Math.imul(_,ut)|0,c=c+Math.imul(j,lt)|0,g=g+Math.imul(j,ut)|0,f=f+Math.imul(O,mt)|0,c=c+Math.imul(O,pt)|0,c=c+Math.imul(M,mt)|0,g=g+Math.imul(M,pt)|0;var xr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(xr>>>26)|0,xr&=67108863,f=Math.imul(X,st),c=Math.imul(X,ct),c=c+Math.imul(G,st)|0,g=Math.imul(G,ct),f=f+Math.imul(U,lt)|0,c=c+Math.imul(U,ut)|0,c=c+Math.imul(q,lt)|0,g=g+Math.imul(q,ut)|0,f=f+Math.imul(_,mt)|0,c=c+Math.imul(_,pt)|0,c=c+Math.imul(j,mt)|0,g=g+Math.imul(j,pt)|0,f=f+Math.imul(O,dt)|0,c=c+Math.imul(O,ft)|0,c=c+Math.imul(M,dt)|0,g=g+Math.imul(M,ft)|0;var Dr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Dr>>>26)|0,Dr&=67108863,f=Math.imul(Q,st),c=Math.imul(Q,ct),c=c+Math.imul(z,st)|0,g=Math.imul(z,ct),f=f+Math.imul(X,lt)|0,c=c+Math.imul(X,ut)|0,c=c+Math.imul(G,lt)|0,g=g+Math.imul(G,ut)|0,f=f+Math.imul(U,mt)|0,c=c+Math.imul(U,pt)|0,c=c+Math.imul(q,mt)|0,g=g+Math.imul(q,pt)|0,f=f+Math.imul(_,dt)|0,c=c+Math.imul(_,ft)|0,c=c+Math.imul(j,dt)|0,g=g+Math.imul(j,ft)|0,f=f+Math.imul(O,ht)|0,c=c+Math.imul(O,gt)|0,c=c+Math.imul(M,ht)|0,g=g+Math.imul(M,gt)|0;var vr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(vr>>>26)|0,vr&=67108863,f=Math.imul(J,st),c=Math.imul(J,ct),c=c+Math.imul(Y,st)|0,g=Math.imul(Y,ct),f=f+Math.imul(Q,lt)|0,c=c+Math.imul(Q,ut)|0,c=c+Math.imul(z,lt)|0,g=g+Math.imul(z,ut)|0,f=f+Math.imul(X,mt)|0,c=c+Math.imul(X,pt)|0,c=c+Math.imul(G,mt)|0,g=g+Math.imul(G,pt)|0,f=f+Math.imul(U,dt)|0,c=c+Math.imul(U,ft)|0,c=c+Math.imul(q,dt)|0,g=g+Math.imul(q,ft)|0,f=f+Math.imul(_,ht)|0,c=c+Math.imul(_,gt)|0,c=c+Math.imul(j,ht)|0,g=g+Math.imul(j,gt)|0,f=f+Math.imul(O,yt)|0,c=c+Math.imul(O,bt)|0,c=c+Math.imul(M,yt)|0,g=g+Math.imul(M,bt)|0;var Ar=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Ar>>>26)|0,Ar&=67108863,f=Math.imul(Z,st),c=Math.imul(Z,ct),c=c+Math.imul(tt,st)|0,g=Math.imul(tt,ct),f=f+Math.imul(J,lt)|0,c=c+Math.imul(J,ut)|0,c=c+Math.imul(Y,lt)|0,g=g+Math.imul(Y,ut)|0,f=f+Math.imul(Q,mt)|0,c=c+Math.imul(Q,pt)|0,c=c+Math.imul(z,mt)|0,g=g+Math.imul(z,pt)|0,f=f+Math.imul(X,dt)|0,c=c+Math.imul(X,ft)|0,c=c+Math.imul(G,dt)|0,g=g+Math.imul(G,ft)|0,f=f+Math.imul(U,ht)|0,c=c+Math.imul(U,gt)|0,c=c+Math.imul(q,ht)|0,g=g+Math.imul(q,gt)|0,f=f+Math.imul(_,yt)|0,c=c+Math.imul(_,bt)|0,c=c+Math.imul(j,yt)|0,g=g+Math.imul(j,bt)|0,f=f+Math.imul(O,St)|0,c=c+Math.imul(O,Tt)|0,c=c+Math.imul(M,St)|0,g=g+Math.imul(M,Tt)|0;var Or=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Or>>>26)|0,Or&=67108863,f=Math.imul(et,st),c=Math.imul(et,ct),c=c+Math.imul(nt,st)|0,g=Math.imul(nt,ct),f=f+Math.imul(Z,lt)|0,c=c+Math.imul(Z,ut)|0,c=c+Math.imul(tt,lt)|0,g=g+Math.imul(tt,ut)|0,f=f+Math.imul(J,mt)|0,c=c+Math.imul(J,pt)|0,c=c+Math.imul(Y,mt)|0,g=g+Math.imul(Y,pt)|0,f=f+Math.imul(Q,dt)|0,c=c+Math.imul(Q,ft)|0,c=c+Math.imul(z,dt)|0,g=g+Math.imul(z,ft)|0,f=f+Math.imul(X,ht)|0,c=c+Math.imul(X,gt)|0,c=c+Math.imul(G,ht)|0,g=g+Math.imul(G,gt)|0,f=f+Math.imul(U,yt)|0,c=c+Math.imul(U,bt)|0,c=c+Math.imul(q,yt)|0,g=g+Math.imul(q,bt)|0,f=f+Math.imul(_,St)|0,c=c+Math.imul(_,Tt)|0,c=c+Math.imul(j,St)|0,g=g+Math.imul(j,Tt)|0,f=f+Math.imul(O,wt)|0,c=c+Math.imul(O,It)|0,c=c+Math.imul(M,wt)|0,g=g+Math.imul(M,It)|0;var Mr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Mr>>>26)|0,Mr&=67108863,f=Math.imul(ot,st),c=Math.imul(ot,ct),c=c+Math.imul(at,st)|0,g=Math.imul(at,ct),f=f+Math.imul(et,lt)|0,c=c+Math.imul(et,ut)|0,c=c+Math.imul(nt,lt)|0,g=g+Math.imul(nt,ut)|0,f=f+Math.imul(Z,mt)|0,c=c+Math.imul(Z,pt)|0,c=c+Math.imul(tt,mt)|0,g=g+Math.imul(tt,pt)|0,f=f+Math.imul(J,dt)|0,c=c+Math.imul(J,ft)|0,c=c+Math.imul(Y,dt)|0,g=g+Math.imul(Y,ft)|0,f=f+Math.imul(Q,ht)|0,c=c+Math.imul(Q,gt)|0,c=c+Math.imul(z,ht)|0,g=g+Math.imul(z,gt)|0,f=f+Math.imul(X,yt)|0,c=c+Math.imul(X,bt)|0,c=c+Math.imul(G,yt)|0,g=g+Math.imul(G,bt)|0,f=f+Math.imul(U,St)|0,c=c+Math.imul(U,Tt)|0,c=c+Math.imul(q,St)|0,g=g+Math.imul(q,Tt)|0,f=f+Math.imul(_,wt)|0,c=c+Math.imul(_,It)|0,c=c+Math.imul(j,wt)|0,g=g+Math.imul(j,It)|0,f=f+Math.imul(O,Ct)|0,c=c+Math.imul(O,kt)|0,c=c+Math.imul(M,Ct)|0,g=g+Math.imul(M,kt)|0;var Pr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Pr>>>26)|0,Pr&=67108863,f=Math.imul(it,st),c=Math.imul(it,ct),c=c+Math.imul(rt,st)|0,g=Math.imul(rt,ct),f=f+Math.imul(ot,lt)|0,c=c+Math.imul(ot,ut)|0,c=c+Math.imul(at,lt)|0,g=g+Math.imul(at,ut)|0,f=f+Math.imul(et,mt)|0,c=c+Math.imul(et,pt)|0,c=c+Math.imul(nt,mt)|0,g=g+Math.imul(nt,pt)|0,f=f+Math.imul(Z,dt)|0,c=c+Math.imul(Z,ft)|0,c=c+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(J,ht)|0,c=c+Math.imul(J,gt)|0,c=c+Math.imul(Y,ht)|0,g=g+Math.imul(Y,gt)|0,f=f+Math.imul(Q,yt)|0,c=c+Math.imul(Q,bt)|0,c=c+Math.imul(z,yt)|0,g=g+Math.imul(z,bt)|0,f=f+Math.imul(X,St)|0,c=c+Math.imul(X,Tt)|0,c=c+Math.imul(G,St)|0,g=g+Math.imul(G,Tt)|0,f=f+Math.imul(U,wt)|0,c=c+Math.imul(U,It)|0,c=c+Math.imul(q,wt)|0,g=g+Math.imul(q,It)|0,f=f+Math.imul(_,Ct)|0,c=c+Math.imul(_,kt)|0,c=c+Math.imul(j,Ct)|0,g=g+Math.imul(j,kt)|0,f=f+Math.imul(O,xt)|0,c=c+Math.imul(O,Dt)|0,c=c+Math.imul(M,xt)|0,g=g+Math.imul(M,Dt)|0;var Rr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Rr>>>26)|0,Rr&=67108863,f=Math.imul(it,lt),c=Math.imul(it,ut),c=c+Math.imul(rt,lt)|0,g=Math.imul(rt,ut),f=f+Math.imul(ot,mt)|0,c=c+Math.imul(ot,pt)|0,c=c+Math.imul(at,mt)|0,g=g+Math.imul(at,pt)|0,f=f+Math.imul(et,dt)|0,c=c+Math.imul(et,ft)|0,c=c+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,c=c+Math.imul(Z,gt)|0,c=c+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(J,yt)|0,c=c+Math.imul(J,bt)|0,c=c+Math.imul(Y,yt)|0,g=g+Math.imul(Y,bt)|0,f=f+Math.imul(Q,St)|0,c=c+Math.imul(Q,Tt)|0,c=c+Math.imul(z,St)|0,g=g+Math.imul(z,Tt)|0,f=f+Math.imul(X,wt)|0,c=c+Math.imul(X,It)|0,c=c+Math.imul(G,wt)|0,g=g+Math.imul(G,It)|0,f=f+Math.imul(U,Ct)|0,c=c+Math.imul(U,kt)|0,c=c+Math.imul(q,Ct)|0,g=g+Math.imul(q,kt)|0,f=f+Math.imul(_,xt)|0,c=c+Math.imul(_,Dt)|0,c=c+Math.imul(j,xt)|0,g=g+Math.imul(j,Dt)|0;var Br=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Br>>>26)|0,Br&=67108863,f=Math.imul(it,mt),c=Math.imul(it,pt),c=c+Math.imul(rt,mt)|0,g=Math.imul(rt,pt),f=f+Math.imul(ot,dt)|0,c=c+Math.imul(ot,ft)|0,c=c+Math.imul(at,dt)|0,g=g+Math.imul(at,ft)|0,f=f+Math.imul(et,ht)|0,c=c+Math.imul(et,gt)|0,c=c+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,c=c+Math.imul(Z,bt)|0,c=c+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(J,St)|0,c=c+Math.imul(J,Tt)|0,c=c+Math.imul(Y,St)|0,g=g+Math.imul(Y,Tt)|0,f=f+Math.imul(Q,wt)|0,c=c+Math.imul(Q,It)|0,c=c+Math.imul(z,wt)|0,g=g+Math.imul(z,It)|0,f=f+Math.imul(X,Ct)|0,c=c+Math.imul(X,kt)|0,c=c+Math.imul(G,Ct)|0,g=g+Math.imul(G,kt)|0,f=f+Math.imul(U,xt)|0,c=c+Math.imul(U,Dt)|0,c=c+Math.imul(q,xt)|0,g=g+Math.imul(q,Dt)|0;var Er=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Er>>>26)|0,Er&=67108863,f=Math.imul(it,dt),c=Math.imul(it,ft),c=c+Math.imul(rt,dt)|0,g=Math.imul(rt,ft),f=f+Math.imul(ot,ht)|0,c=c+Math.imul(ot,gt)|0,c=c+Math.imul(at,ht)|0,g=g+Math.imul(at,gt)|0,f=f+Math.imul(et,yt)|0,c=c+Math.imul(et,bt)|0,c=c+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,St)|0,c=c+Math.imul(Z,Tt)|0,c=c+Math.imul(tt,St)|0,g=g+Math.imul(tt,Tt)|0,f=f+Math.imul(J,wt)|0,c=c+Math.imul(J,It)|0,c=c+Math.imul(Y,wt)|0,g=g+Math.imul(Y,It)|0,f=f+Math.imul(Q,Ct)|0,c=c+Math.imul(Q,kt)|0,c=c+Math.imul(z,Ct)|0,g=g+Math.imul(z,kt)|0,f=f+Math.imul(X,xt)|0,c=c+Math.imul(X,Dt)|0,c=c+Math.imul(G,xt)|0,g=g+Math.imul(G,Dt)|0;var Nr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Nr>>>26)|0,Nr&=67108863,f=Math.imul(it,ht),c=Math.imul(it,gt),c=c+Math.imul(rt,ht)|0,g=Math.imul(rt,gt),f=f+Math.imul(ot,yt)|0,c=c+Math.imul(ot,bt)|0,c=c+Math.imul(at,yt)|0,g=g+Math.imul(at,bt)|0,f=f+Math.imul(et,St)|0,c=c+Math.imul(et,Tt)|0,c=c+Math.imul(nt,St)|0,g=g+Math.imul(nt,Tt)|0,f=f+Math.imul(Z,wt)|0,c=c+Math.imul(Z,It)|0,c=c+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(J,Ct)|0,c=c+Math.imul(J,kt)|0,c=c+Math.imul(Y,Ct)|0,g=g+Math.imul(Y,kt)|0,f=f+Math.imul(Q,xt)|0,c=c+Math.imul(Q,Dt)|0,c=c+Math.imul(z,xt)|0,g=g+Math.imul(z,Dt)|0;var Wr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Wr>>>26)|0,Wr&=67108863,f=Math.imul(it,yt),c=Math.imul(it,bt),c=c+Math.imul(rt,yt)|0,g=Math.imul(rt,bt),f=f+Math.imul(ot,St)|0,c=c+Math.imul(ot,Tt)|0,c=c+Math.imul(at,St)|0,g=g+Math.imul(at,Tt)|0,f=f+Math.imul(et,wt)|0,c=c+Math.imul(et,It)|0,c=c+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,c=c+Math.imul(Z,kt)|0,c=c+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,kt)|0,f=f+Math.imul(J,xt)|0,c=c+Math.imul(J,Dt)|0,c=c+Math.imul(Y,xt)|0,g=g+Math.imul(Y,Dt)|0;var _r=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(_r>>>26)|0,_r&=67108863,f=Math.imul(it,St),c=Math.imul(it,Tt),c=c+Math.imul(rt,St)|0,g=Math.imul(rt,Tt),f=f+Math.imul(ot,wt)|0,c=c+Math.imul(ot,It)|0,c=c+Math.imul(at,wt)|0,g=g+Math.imul(at,It)|0,f=f+Math.imul(et,Ct)|0,c=c+Math.imul(et,kt)|0,c=c+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,kt)|0,f=f+Math.imul(Z,xt)|0,c=c+Math.imul(Z,Dt)|0,c=c+Math.imul(tt,xt)|0,g=g+Math.imul(tt,Dt)|0;var Lr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Lr>>>26)|0,Lr&=67108863,f=Math.imul(it,wt),c=Math.imul(it,It),c=c+Math.imul(rt,wt)|0,g=Math.imul(rt,It),f=f+Math.imul(ot,Ct)|0,c=c+Math.imul(ot,kt)|0,c=c+Math.imul(at,Ct)|0,g=g+Math.imul(at,kt)|0,f=f+Math.imul(et,xt)|0,c=c+Math.imul(et,Dt)|0,c=c+Math.imul(nt,xt)|0,g=g+Math.imul(nt,Dt)|0;var jr=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(jr>>>26)|0,jr&=67108863,f=Math.imul(it,Ct),c=Math.imul(it,kt),c=c+Math.imul(rt,Ct)|0,g=Math.imul(rt,kt),f=f+Math.imul(ot,xt)|0,c=c+Math.imul(ot,Dt)|0,c=c+Math.imul(at,xt)|0,g=g+Math.imul(at,Dt)|0;var Ur=(T+f|0)+((c&8191)<<13)|0;T=(g+(c>>>13)|0)+(Ur>>>26)|0,Ur&=67108863,f=Math.imul(it,xt),c=Math.imul(it,Dt),c=c+Math.imul(rt,xt)|0,g=Math.imul(rt,Dt);var qr=(T+f|0)+((c&8191)<<13)|0;return T=(g+(c>>>13)|0)+(qr>>>26)|0,qr&=67108863,b[0]=Cr,b[1]=kr,b[2]=xr,b[3]=Dr,b[4]=vr,b[5]=Ar,b[6]=Or,b[7]=Mr,b[8]=Pr,b[9]=Rr,b[10]=Br,b[11]=Er,b[12]=Nr,b[13]=Wr,b[14]=_r,b[15]=Lr,b[16]=jr,b[17]=Ur,b[18]=qr,T!==0&&(b[19]=T,m.length++),m};Math.imul||(V=K);function Ht(y,r,u){u.negative=r.negative^y.negative,u.length=y.length+r.length;for(var m=0,p=0,h=0;h<u.length-1;h++){var b=p;p=0;for(var T=m&67108863,f=Math.min(h,r.length-1),c=Math.max(0,h-y.length+1);c<=f;c++){var g=h-c,v=y.words[g]|0,O=r.words[c]|0,M=v*O,E=M&67108863;b=b+(M/67108864|0)|0,E=E+T|0,T=E&67108863,b=b+(E>>>26)|0,p+=b>>>26,b&=67108863}u.words[h]=T,m=b,b=p}return m!==0?u.words[h]=m:u.length--,u._strip()}function Et(y,r,u){return Ht(y,r,u)}o.prototype.mulTo=function(r,u){var m,p=this.length+r.length;return this.length===10&&r.length===10?m=V(this,r,u):p<63?m=K(this,r,u):p<1024?m=Ht(this,r,u):m=Et(this,r,u),m};function Pt(y,r){this.x=y,this.y=r}Pt.prototype.makeRBT=function(r){for(var u=new Array(r),m=o.prototype._countBits(r)-1,p=0;p<r;p++)u[p]=this.revBin(p,m,r);return u},Pt.prototype.revBin=function(r,u,m){if(r===0||r===m-1)return r;for(var p=0,h=0;h<u;h++)p|=(r&1)<<u-h-1,r>>=1;return p},Pt.prototype.permute=function(r,u,m,p,h,b){for(var T=0;T<b;T++)p[T]=u[r[T]],h[T]=m[r[T]]},Pt.prototype.transform=function(r,u,m,p,h,b){this.permute(b,r,u,m,p,h);for(var T=1;T<h;T<<=1)for(var f=T<<1,c=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),v=0;v<h;v+=f)for(var O=c,M=g,E=0;E<T;E++){var _=m[v+E],j=p[v+E],re=m[v+E+T],U=p[v+E+T],q=O*re-M*U;U=O*U+M*re,re=q,m[v+E]=_+re,p[v+E]=j+U,m[v+E+T]=_-re,p[v+E+T]=j-U,E!==f&&(q=c*O-g*M,M=c*M+g*O,O=q)}},Pt.prototype.guessLen13b=function(r,u){var m=Math.max(u,r)|1,p=m&1,h=0;for(m=m/2|0;m;m=m>>>1)h++;return 1<<h+1+p},Pt.prototype.conjugate=function(r,u,m){if(!(m<=1))for(var p=0;p<m/2;p++){var h=r[p];r[p]=r[m-p-1],r[m-p-1]=h,h=u[p],u[p]=-u[m-p-1],u[m-p-1]=-h}},Pt.prototype.normalize13b=function(r,u){for(var m=0,p=0;p<u/2;p++){var h=Math.round(r[2*p+1]/u)*8192+Math.round(r[2*p]/u)+m;r[p]=h&67108863,h<67108864?m=0:m=h/67108864|0}return r},Pt.prototype.convert13b=function(r,u,m,p){for(var h=0,b=0;b<u;b++)h=h+(r[b]|0),m[2*b]=h&8191,h=h>>>13,m[2*b+1]=h&8191,h=h>>>13;for(b=2*u;b<p;++b)m[b]=0;t(h===0),t((h&-8192)===0)},Pt.prototype.stub=function(r){for(var u=new Array(r),m=0;m<r;m++)u[m]=0;return u},Pt.prototype.mulp=function(r,u,m){var p=2*this.guessLen13b(r.length,u.length),h=this.makeRBT(p),b=this.stub(p),T=new Array(p),f=new Array(p),c=new Array(p),g=new Array(p),v=new Array(p),O=new Array(p),M=m.words;M.length=p,this.convert13b(r.words,r.length,T,p),this.convert13b(u.words,u.length,g,p),this.transform(T,b,f,c,p,h),this.transform(g,b,v,O,p,h);for(var E=0;E<p;E++){var _=f[E]*v[E]-c[E]*O[E];c[E]=f[E]*O[E]+c[E]*v[E],f[E]=_}return this.conjugate(f,c,p),this.transform(f,c,M,b,p,h),this.conjugate(M,b,p),this.normalize13b(M,p),m.negative=r.negative^u.negative,m.length=r.length+u.length,m._strip()},o.prototype.mul=function(r){var u=new o(null);return u.words=new Array(this.length+r.length),this.mulTo(r,u)},o.prototype.mulf=function(r){var u=new o(null);return u.words=new Array(this.length+r.length),Et(this,r,u)},o.prototype.imul=function(r){return this.clone().mulTo(r,this)},o.prototype.imuln=function(r){var u=r<0;u&&(r=-r),t(typeof r=="number"),t(r<67108864);for(var m=0,p=0;p<this.length;p++){var h=(this.words[p]|0)*r,b=(h&67108863)+(m&67108863);m>>=26,m+=h/67108864|0,m+=b>>>26,this.words[p]=b&67108863}return m!==0&&(this.words[p]=m,this.length++),u?this.ineg():this},o.prototype.muln=function(r){return this.clone().imuln(r)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(r){var u=R(r);if(u.length===0)return new o(1);for(var m=this,p=0;p<u.length&&u[p]===0;p++,m=m.sqr());if(++p<u.length)for(var h=m.sqr();p<u.length;p++,h=h.sqr())u[p]!==0&&(m=m.mul(h));return m},o.prototype.iushln=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=67108863>>>26-u<<26-u,h;if(u!==0){var b=0;for(h=0;h<this.length;h++){var T=this.words[h]&p,f=(this.words[h]|0)-T<<u;this.words[h]=f|b,b=T>>>26-u}b&&(this.words[h]=b,this.length++)}if(m!==0){for(h=this.length-1;h>=0;h--)this.words[h+m]=this.words[h];for(h=0;h<m;h++)this.words[h]=0;this.length+=m}return this._strip()},o.prototype.ishln=function(r){return t(this.negative===0),this.iushln(r)},o.prototype.iushrn=function(r,u,m){t(typeof r=="number"&&r>=0);var p;u?p=(u-u%26)/26:p=0;var h=r%26,b=Math.min((r-h)/26,this.length),T=67108863^67108863>>>h<<h,f=m;if(p-=b,p=Math.max(0,p),f){for(var c=0;c<b;c++)f.words[c]=this.words[c];f.length=b}if(b!==0)if(this.length>b)for(this.length-=b,c=0;c<this.length;c++)this.words[c]=this.words[c+b];else this.words[0]=0,this.length=1;var g=0;for(c=this.length-1;c>=0&&(g!==0||c>=p);c--){var v=this.words[c]|0;this.words[c]=g<<26-h|v>>>h,g=v&T}return f&&g!==0&&(f.words[f.length++]=g),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(r,u,m){return t(this.negative===0),this.iushrn(r,u,m)},o.prototype.shln=function(r){return this.clone().ishln(r)},o.prototype.ushln=function(r){return this.clone().iushln(r)},o.prototype.shrn=function(r){return this.clone().ishrn(r)},o.prototype.ushrn=function(r){return this.clone().iushrn(r)},o.prototype.testn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return!1;var h=this.words[m];return!!(h&p)},o.prototype.imaskn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(u!==0&&m++,this.length=Math.min(m,this.length),u!==0){var p=67108863^67108863>>>u<<u;this.words[this.length-1]&=p}return this._strip()},o.prototype.maskn=function(r){return this.clone().imaskn(r)},o.prototype.iaddn=function(r){return t(typeof r=="number"),t(r<67108864),r<0?this.isubn(-r):this.negative!==0?this.length===1&&(this.words[0]|0)<=r?(this.words[0]=r-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(r),this.negative=1,this):this._iaddn(r)},o.prototype._iaddn=function(r){this.words[0]+=r;for(var u=0;u<this.length&&this.words[u]>=67108864;u++)this.words[u]-=67108864,u===this.length-1?this.words[u+1]=1:this.words[u+1]++;return this.length=Math.max(this.length,u+1),this},o.prototype.isubn=function(r){if(t(typeof r=="number"),t(r<67108864),r<0)return this.iaddn(-r);if(this.negative!==0)return this.negative=0,this.iaddn(r),this.negative=1,this;if(this.words[0]-=r,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var u=0;u<this.length&&this.words[u]<0;u++)this.words[u]+=67108864,this.words[u+1]-=1;return this._strip()},o.prototype.addn=function(r){return this.clone().iaddn(r)},o.prototype.subn=function(r){return this.clone().isubn(r)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(r,u,m){var p=r.length+m,h;this._expand(p);var b,T=0;for(h=0;h<r.length;h++){b=(this.words[h+m]|0)+T;var f=(r.words[h]|0)*u;b-=f&67108863,T=(b>>26)-(f/67108864|0),this.words[h+m]=b&67108863}for(;h<this.length-m;h++)b=(this.words[h+m]|0)+T,T=b>>26,this.words[h+m]=b&67108863;if(T===0)return this._strip();for(t(T===-1),T=0,h=0;h<this.length;h++)b=-(this.words[h]|0)+T,T=b>>26,this.words[h]=b&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(r,u){var m=this.length-r.length,p=this.clone(),h=r,b=h.words[h.length-1]|0,T=this._countBits(b);m=26-T,m!==0&&(h=h.ushln(m),p.iushln(m),b=h.words[h.length-1]|0);var f=p.length-h.length,c;if(u!=="mod"){c=new o(null),c.length=f+1,c.words=new Array(c.length);for(var g=0;g<c.length;g++)c.words[g]=0}var v=p.clone()._ishlnsubmul(h,1,f);v.negative===0&&(p=v,c&&(c.words[f]=1));for(var O=f-1;O>=0;O--){var M=(p.words[h.length+O]|0)*67108864+(p.words[h.length+O-1]|0);for(M=Math.min(M/b|0,67108863),p._ishlnsubmul(h,M,O);p.negative!==0;)M--,p.negative=0,p._ishlnsubmul(h,1,O),p.isZero()||(p.negative^=1);c&&(c.words[O]=M)}return c&&c._strip(),p._strip(),u!=="div"&&m!==0&&p.iushrn(m),{div:c||null,mod:p}},o.prototype.divmod=function(r,u,m){if(t(!r.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var p,h,b;return this.negative!==0&&r.negative===0?(b=this.neg().divmod(r,u),u!=="mod"&&(p=b.div.neg()),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.iadd(r)),{div:p,mod:h}):this.negative===0&&r.negative!==0?(b=this.divmod(r.neg(),u),u!=="mod"&&(p=b.div.neg()),{div:p,mod:b.mod}):this.negative&r.negative?(b=this.neg().divmod(r.neg(),u),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.isub(r)),{div:b.div,mod:h}):r.length>this.length||this.cmp(r)<0?{div:new o(0),mod:this}:r.length===1?u==="div"?{div:this.divn(r.words[0]),mod:null}:u==="mod"?{div:null,mod:new o(this.modrn(r.words[0]))}:{div:this.divn(r.words[0]),mod:new o(this.modrn(r.words[0]))}:this._wordDiv(r,u)},o.prototype.div=function(r){return this.divmod(r,"div",!1).div},o.prototype.mod=function(r){return this.divmod(r,"mod",!1).mod},o.prototype.umod=function(r){return this.divmod(r,"mod",!0).mod},o.prototype.divRound=function(r){var u=this.divmod(r);if(u.mod.isZero())return u.div;var m=u.div.negative!==0?u.mod.isub(r):u.mod,p=r.ushrn(1),h=r.andln(1),b=m.cmp(p);return b<0||h===1&&b===0?u.div:u.div.negative!==0?u.div.isubn(1):u.div.iaddn(1)},o.prototype.modrn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=(1<<26)%r,p=0,h=this.length-1;h>=0;h--)p=(m*p+(this.words[h]|0))%r;return u?-p:p},o.prototype.modn=function(r){return this.modrn(r)},o.prototype.idivn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=0,p=this.length-1;p>=0;p--){var h=(this.words[p]|0)+m*67108864;this.words[p]=h/r|0,m=h%r}return this._strip(),u?this.ineg():this},o.prototype.divn=function(r){return this.clone().idivn(r)},o.prototype.egcd=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new o(1),h=new o(0),b=new o(0),T=new o(1),f=0;u.isEven()&&m.isEven();)u.iushrn(1),m.iushrn(1),++f;for(var c=m.clone(),g=u.clone();!u.isZero();){for(var v=0,O=1;!(u.words[0]&O)&&v<26;++v,O<<=1);if(v>0)for(u.iushrn(v);v-- >0;)(p.isOdd()||h.isOdd())&&(p.iadd(c),h.isub(g)),p.iushrn(1),h.iushrn(1);for(var M=0,E=1;!(m.words[0]&E)&&M<26;++M,E<<=1);if(M>0)for(m.iushrn(M);M-- >0;)(b.isOdd()||T.isOdd())&&(b.iadd(c),T.isub(g)),b.iushrn(1),T.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(b),h.isub(T)):(m.isub(u),b.isub(p),T.isub(h))}return{a:b,b:T,gcd:m.iushln(f)}},o.prototype._invmp=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new o(1),h=new o(0),b=m.clone();u.cmpn(1)>0&&m.cmpn(1)>0;){for(var T=0,f=1;!(u.words[0]&f)&&T<26;++T,f<<=1);if(T>0)for(u.iushrn(T);T-- >0;)p.isOdd()&&p.iadd(b),p.iushrn(1);for(var c=0,g=1;!(m.words[0]&g)&&c<26;++c,g<<=1);if(c>0)for(m.iushrn(c);c-- >0;)h.isOdd()&&h.iadd(b),h.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(h)):(m.isub(u),h.isub(p))}var v;return u.cmpn(1)===0?v=p:v=h,v.cmpn(0)<0&&v.iadd(r),v},o.prototype.gcd=function(r){if(this.isZero())return r.abs();if(r.isZero())return this.abs();var u=this.clone(),m=r.clone();u.negative=0,m.negative=0;for(var p=0;u.isEven()&&m.isEven();p++)u.iushrn(1),m.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;m.isEven();)m.iushrn(1);var h=u.cmp(m);if(h<0){var b=u;u=m,m=b}else if(h===0||m.cmpn(1)===0)break;u.isub(m)}while(!0);return m.iushln(p)},o.prototype.invm=function(r){return this.egcd(r).a.umod(r)},o.prototype.isEven=function(){return(this.words[0]&1)===0},o.prototype.isOdd=function(){return(this.words[0]&1)===1},o.prototype.andln=function(r){return this.words[0]&r},o.prototype.bincn=function(r){t(typeof r=="number");var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return this._expand(m+1),this.words[m]|=p,this;for(var h=p,b=m;h!==0&&b<this.length;b++){var T=this.words[b]|0;T+=h,h=T>>>26,T&=67108863,this.words[b]=T}return h!==0&&(this.words[b]=h,this.length++),this},o.prototype.isZero=function(){return this.length===1&&this.words[0]===0},o.prototype.cmpn=function(r){var u=r<0;if(this.negative!==0&&!u)return-1;if(this.negative===0&&u)return 1;this._strip();var m;if(this.length>1)m=1;else{u&&(r=-r),t(r<=67108863,"Number is too big");var p=this.words[0]|0;m=p===r?0:p<r?-1:1}return this.negative!==0?-m|0:m},o.prototype.cmp=function(r){if(this.negative!==0&&r.negative===0)return-1;if(this.negative===0&&r.negative!==0)return 1;var u=this.ucmp(r);return this.negative!==0?-u|0:u},o.prototype.ucmp=function(r){if(this.length>r.length)return 1;if(this.length<r.length)return-1;for(var u=0,m=this.length-1;m>=0;m--){var p=this.words[m]|0,h=r.words[m]|0;if(p!==h){p<h?u=-1:p>h&&(u=1);break}}return u},o.prototype.gtn=function(r){return this.cmpn(r)===1},o.prototype.gt=function(r){return this.cmp(r)===1},o.prototype.gten=function(r){return this.cmpn(r)>=0},o.prototype.gte=function(r){return this.cmp(r)>=0},o.prototype.ltn=function(r){return this.cmpn(r)===-1},o.prototype.lt=function(r){return this.cmp(r)===-1},o.prototype.lten=function(r){return this.cmpn(r)<=0},o.prototype.lte=function(r){return this.cmp(r)<=0},o.prototype.eqn=function(r){return this.cmpn(r)===0},o.prototype.eq=function(r){return this.cmp(r)===0},o.red=function(r){return new $(r)},o.prototype.toRed=function(r){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),r.convertTo(this)._forceRed(r)},o.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(r){return this.red=r,this},o.prototype.forceRed=function(r){return t(!this.red,"Already a number in reduction context"),this._forceRed(r)},o.prototype.redAdd=function(r){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,r)},o.prototype.redIAdd=function(r){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,r)},o.prototype.redSub=function(r){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,r)},o.prototype.redISub=function(r){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,r)},o.prototype.redShl=function(r){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,r)},o.prototype.redMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.mul(this,r)},o.prototype.redIMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.imul(this,r)},o.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(r){return t(this.red&&!r.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,r)};var un={k256:null,p224:null,p192:null,p25519:null};function Lt(y,r){this.name=y,this.p=new o(r,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Lt.prototype._tmp=function(){var r=new o(null);return r.words=new Array(Math.ceil(this.n/13)),r},Lt.prototype.ireduce=function(r){var u=r,m;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),m=u.bitLength();while(m>this.n);var p=m<this.n?-1:u.ucmp(this.p);return p===0?(u.words[0]=0,u.length=1):p>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},Lt.prototype.split=function(r,u){r.iushrn(this.n,0,u)},Lt.prototype.imulK=function(r){return r.imul(this.k)};function qn(){Lt.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(qn,Lt),qn.prototype.split=function(r,u){for(var m=4194303,p=Math.min(r.length,9),h=0;h<p;h++)u.words[h]=r.words[h];if(u.length=p,r.length<=9){r.words[0]=0,r.length=1;return}var b=r.words[9];for(u.words[u.length++]=b&m,h=10;h<r.length;h++){var T=r.words[h]|0;r.words[h-10]=(T&m)<<4|b>>>22,b=T}b>>>=22,r.words[h-10]=b,b===0&&r.length>10?r.length-=10:r.length-=9},qn.prototype.imulK=function(r){r.words[r.length]=0,r.words[r.length+1]=0,r.length+=2;for(var u=0,m=0;m<r.length;m++){var p=r.words[m]|0;u+=p*977,r.words[m]=u&67108863,u=p*64+(u/67108864|0)}return r.words[r.length-1]===0&&(r.length--,r.words[r.length-1]===0&&r.length--),r};function js(){Lt.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(js,Lt);function Us(){Lt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(Us,Lt);function Ir(){Lt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(Ir,Lt),Ir.prototype.imulK=function(r){for(var u=0,m=0;m<r.length;m++){var p=(r.words[m]|0)*19+u,h=p&67108863;p>>>=26,r.words[m]=h,u=p}return u!==0&&(r.words[r.length++]=u),r},o._prime=function(r){if(un[r])return un[r];var u;if(r==="k256")u=new qn;else if(r==="p224")u=new js;else if(r==="p192")u=new Us;else if(r==="p25519")u=new Ir;else throw new Error("Unknown prime "+r);return un[r]=u,u};function $(y){if(typeof y=="string"){var r=o._prime(y);this.m=r.p,this.prime=r}else t(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}$.prototype._verify1=function(r){t(r.negative===0,"red works only with positives"),t(r.red,"red works only with red numbers")},$.prototype._verify2=function(r,u){t((r.negative|u.negative)===0,"red works only with positives"),t(r.red&&r.red===u.red,"red works only with red numbers")},$.prototype.imod=function(r){return this.prime?this.prime.ireduce(r)._forceRed(this):(S(r,r.umod(this.m)._forceRed(this)),r)},$.prototype.neg=function(r){return r.isZero()?r.clone():this.m.sub(r)._forceRed(this)},$.prototype.add=function(r,u){this._verify2(r,u);var m=r.add(u);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},$.prototype.iadd=function(r,u){this._verify2(r,u);var m=r.iadd(u);return m.cmp(this.m)>=0&&m.isub(this.m),m},$.prototype.sub=function(r,u){this._verify2(r,u);var m=r.sub(u);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},$.prototype.isub=function(r,u){this._verify2(r,u);var m=r.isub(u);return m.cmpn(0)<0&&m.iadd(this.m),m},$.prototype.shl=function(r,u){return this._verify1(r),this.imod(r.ushln(u))},$.prototype.imul=function(r,u){return this._verify2(r,u),this.imod(r.imul(u))},$.prototype.mul=function(r,u){return this._verify2(r,u),this.imod(r.mul(u))},$.prototype.isqr=function(r){return this.imul(r,r.clone())},$.prototype.sqr=function(r){return this.mul(r,r)},$.prototype.sqrt=function(r){if(r.isZero())return r.clone();var u=this.m.andln(3);if(t(u%2===1),u===3){var m=this.m.add(new o(1)).iushrn(2);return this.pow(r,m)}for(var p=this.m.subn(1),h=0;!p.isZero()&&p.andln(1)===0;)h++,p.iushrn(1);t(!p.isZero());var b=new o(1).toRed(this),T=b.redNeg(),f=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new o(2*c*c).toRed(this);this.pow(c,f).cmp(T)!==0;)c.redIAdd(T);for(var g=this.pow(c,p),v=this.pow(r,p.addn(1).iushrn(1)),O=this.pow(r,p),M=h;O.cmp(b)!==0;){for(var E=O,_=0;E.cmp(b)!==0;_++)E=E.redSqr();t(_<M);var j=this.pow(g,new o(1).iushln(M-_-1));v=v.redMul(j),g=j.redSqr(),O=O.redMul(g),M=_}return v},$.prototype.invm=function(r){var u=r._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},$.prototype.pow=function(r,u){if(u.isZero())return new o(1).toRed(this);if(u.cmpn(1)===0)return r.clone();var m=4,p=new Array(1<<m);p[0]=new o(1).toRed(this),p[1]=r;for(var h=2;h<p.length;h++)p[h]=this.mul(p[h-1],r);var b=p[0],T=0,f=0,c=u.bitLength()%26;for(c===0&&(c=26),h=u.length-1;h>=0;h--){for(var g=u.words[h],v=c-1;v>=0;v--){var O=g>>v&1;if(b!==p[0]&&(b=this.sqr(b)),O===0&&T===0){f=0;continue}T<<=1,T|=O,f++,!(f!==m&&(h!==0||v!==0))&&(b=this.mul(b,p[T]),f=0,T=0)}c=26}return b},$.prototype.convertTo=function(r){var u=r.umod(this.m);return u===r?u.clone():u},$.prototype.convertFrom=function(r){var u=r.clone();return u.red=null,u},o.mont=function(r){return new Pe(r)};function Pe(y){$.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(Pe,$),Pe.prototype.convertTo=function(r){return this.imod(r.ushln(this.shift))},Pe.prototype.convertFrom=function(r){var u=this.imod(r.mul(this.rinv));return u.red=null,u},Pe.prototype.imul=function(r,u){if(r.isZero()||u.isZero())return r.words[0]=0,r.length=1,r;var m=r.imul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},Pe.prototype.mul=function(r,u){if(r.isZero()||u.isZero())return new o(0)._forceRed(this);var m=r.mul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},Pe.prototype.invm=function(r){var u=this.imod(r._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof Ns>"u"||Ns,op)});var Jd={};Fr(Jd,{appHelpers:()=>zd});module.exports=qp(Jd);var mc=require("@msafe/sui3-utils");var ne=require("@alphafi/alphafi-sdk"),je=require("@msafe/sui3-utils"),zt=require("@mysten/bcs");var Kn=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,n=t.pool_id,o=ne.poolIdPoolNameMap[n];if(console.log("Decoder event data - ",t),console.log("Decoder poolName - ",o),this.isWithdrawAlphaEvent(e))return this.decodeWithdrawAlpha(t);if(this.isWithdrawEvent(t))return this.decodeWithdraw(o);if(this.isDoubleAssetDepositEvent(t,o))return this.decodeDoubleAssetDeposit(o,t);if(this.isSingleAssetDepositEvent(t,o))return this.decodeSingleAssetDeposit(o,t);throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(){return this.simResult.events.find(e=>this.isLiquidityChangeEventType(e.type))}isClaimRewardTransaction(){return!!this.getMoveCallCommand("get_user_rewards_all")}isLiquidityChangeEventType(e){return e.includes("LiquidityChangeEvent")||e.includes("LiquidityChangeNewNewEvent")||e.includes("WithdrawEventV2")}isWithdrawAlphaEvent(e){return e.type.includes("WithdrawEventV2")}isWithdrawEvent(e){return e.event_type===1}isDoubleAssetDepositEvent(e,t){return e.event_type===0&&ne.poolInfo[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&ne.poolInfo[t].assetTypes.length===1}extractXTokensAmount(){let e=this.inputs.find(o=>o.Pure!==void 0);if(!e||!e.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:t}=e.Pure,n;return t.length===12?n=zt.bcs.u64().parse((0,zt.fromBase64)(t)):t.length===24?n=zt.bcs.u128().parse((0,zt.fromBase64)(t)):t.length===44?n=zt.bcs.u256().parse((0,zt.fromBase64)(t)):n=zt.bcs.u64().parse((0,zt.fromBase64)(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:o}=t,i=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,i),{txType:je.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:i?n:o,isAmountA:i}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:i}=ne.singleAssetPoolCoinMap[e],{expo:s}=ne.coinsList[i];n=Math.floor(Number(n)/10**(9-s)).toString()}return{txType:je.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:je.TransactionType.Other,type:"withdraw",intentionData:{poolName:e,xTokensAmount:t}}}decodeWithdrawAlpha(e){let t=this.extractXTokensAmount(),{amount_withdrawn_from_locked:n}=e;return console.log("Decoder.decodeWithdrawAlpha",t,n),{txType:je.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:je.TransactionType.Other,type:"claimReward",intentionData:{}}}};var rc=require("@alphafi/alphafi-sdk");var ic=jt(require("sort-keys-recursive")),k=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,ic.default)(this.data))}};var Vn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t;return await(0,rc.claimRewardTxb)(n.address)}static fromData(t){return new a(t)}};var sc=require("@alphafi/alphafi-sdk");var $n=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i,isAmountA:s}=this.data;return await(0,sc.depositDoubleAssetTxb)(o,n.address,i,s)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};var cc=require("@alphafi/alphafi-sdk");var Hn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i}=this.data;return await(0,cc.depositSingleAssetTxb)(o,n.address,i)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};var lc=require("@alphafi/alphafi-sdk");var Xn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:i}=this.data;return await(0,lc.withdrawTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var uc=require("@alphafi/alphafi-sdk");var Gn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:i}=this.data;return await(0,uc.withdrawAlphaTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var Qn=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:o}=e,i=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",i);let l=new Kn(t,i).decode();return{txType:mc.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=Hn.fromData(e.intentionData);break;case"depositDoubleAsset":n=$n.fromData(e.intentionData);break;case"withdraw":n=Xn.fromData(e.intentionData);break;case"withdrawAlpha":n=Gn.fromData(e.intentionData);break;case"claimReward":n=Vn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};var Wc=require("@msafe/sui3-utils");var Nt=require("@msafe/sui3-utils"),zn=require("@mysten/sui/bcs"),Jn=require("bucket-protocol-sdk");var Yn=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,n){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.package===e&&o.MoveCall.module===t&&o.MoveCall.function===n)}getMoveCallModuleCommands(e,t){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(e=>e.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(e=>e.$kind==="TransferObjects")}isPsmTransaction(){return!!this.getMoveCallCommand("charge_reservoir")||!!this.getMoveCallCommand("discharge_reservoir")}isStrapNewTransaction(){return!!this.getMoveCallModuleCommand("strap","new")}isBorrowTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","high_top_up")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow_with_strap")}isRepayTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","fully_repay")||!!this.getMoveCallModuleCommand("bucket_operations","fully_repay_with_strap")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw_with_strap")}isWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","withdraw")||!!this.getMoveCallModuleCommand("buck","withdraw_with_strap")}isCloseTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","destroy_empty_strap")}isTankDepositTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","deposit")}isTankWithdrawTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","withdraw")}isTankClaimTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","claim")}isSBUCKDepositTransaction(){return!!this.getMoveCallModuleCommand("buck","buck_to_sbuck")}isSBUCKWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","sbuck_to_buck")}isSBUCKStakeTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(Jn.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","claim")}isLockedClaimTransaction(){return!!this.getMoveCallModuleCommand("proof_rule","claim")||!!this.getMoveCallModuleCommand("lst_proof_rule","claim")}isLstUnlockTransaction(){return!!this.getMoveCallModuleCommand("lst_proof_rule","unlock")}decodePsm(){let e,t,n="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),this.getMoveCallCommand("charge_reservoir")?([e]=this.getMoveCallCommand("charge_reservoir").MoveCall.typeArguments,t=!1):([e]=this.getMoveCallCommand("discharge_reservoir").MoveCall.typeArguments,t=!0),console.log("Decoder.decodePsm",e,n,t),{txType:Nt.TransactionType.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,o=this.getStrapId(),i="0",s=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(s.$kind==="Input"&&(i=this.getPureInputU64(s.Input)),this.getMoveCallCommand("high_top_up")){let l=this.getMoveCallCommand("high_top_up").MoveCall;[e]=l.typeArguments;let d=l.arguments[1];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[3];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow")){let l=this.getMoveCallCommand("high_borrow").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let l=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}return{txType:Nt.TransactionType.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:i,borrowAmount:t,insertionPlace:n,strapId:o}}}decodeRepay(){let e="",t="0",n="0",i,s=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let l=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let l=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}return{txType:Nt.TransactionType.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:i,strapId:s}}}decodeWithdraw(){let e="",t="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let i=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=i.typeArguments;let s=i.arguments[4];s.$kind==="Input"&&(t=this.getPureInputU64(s.Input));let l=i.arguments[5];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}else if(this.getMoveCallCommand("withdraw")){let i=this.getMoveCallCommand("withdraw").MoveCall;[e]=i.typeArguments;let s=i.arguments[3];s.$kind==="Input"&&(t=this.getPureInputU64(s.Input));let l=i.arguments[4];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}return{txType:Nt.TransactionType.Other,type:"withdraw",intentionData:{collateralType:e,withdrawAmount:t,insertionPlace:n,strapId:o}}}decodeClose(){let e="",t=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([e]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:Nt.TransactionType.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",i=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];i.$kind==="Input"&&(n=this.getPureInputU64(i.Input));let s=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,s),{txType:Nt.TransactionType.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:s}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(e=this.getPureInputU64(d.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let l=0;l<o.length;l++){let d=o[l];n.push("")}else{let l=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let d=0;d<l.length;d++){let w=l[d].MoveCall.arguments[2];if(w.$kind==="Input"){let{objectId:I}=this.inputs[w.Input].UnresolvedObject;n.push(I)}}}let i=this.isSBUCKWithdrawTransaction(),s={stakeProofs:n,amount:e,isStake:t,toBuck:i};return console.log("Decoder.decodeSBUCKUnstake",s),{txType:Nt.TransactionType.Other,type:"sbuck-unstake",intentionData:s}}decodeSBUCKWithdraw(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(e=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:Nt.TransactionType.Other,type:"sbuck-withdraw",intentionData:{amount:e}}}decodeSBUCKClaim(){let e=[],t=this.getMoveCallModuleCommands("fountain_core","claim");for(let n=0;n<t.length;n++){let i=t[n].MoveCall.arguments[2];if(i.$kind==="Input"){let{objectId:s}=this.inputs[i.Input].UnresolvedObject;e.push(s)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:Nt.TransactionType.Other,type:"sbuck-claim",intentionData:{stakeProofs:e}}}decodeTankDeposit(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];n.$kind==="Input"&&(e=this.getPureInputU64(n.Input));let i=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",i,e),{txType:Nt.TransactionType.Other,type:"tank-deposit",intentionData:{coinType:i,amount:e}}}decodeTankWithdraw(){let e=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,t=e.typeArguments[0],n="0",o=e.arguments[5];return o.$kind==="Input"&&(n=this.getPureInputU64(o.Input)),console.log("Decoder.decodeTankWithdraw",t,n),{txType:Nt.TransactionType.Other,type:"tank-withdraw",intentionData:{coinType:t,amount:n}}}decodeTankClaim(){let t=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",t),{txType:Nt.TransactionType.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let i=0;i<n.length;i++)[e]=n[i].MoveCall.typeArguments,t++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let i=0;i<o.length;i++)[e]=o[i].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:Nt.TransactionType.Other,type:"lock-claim",intentionData:{coinType:e,proofCount:t}}}getCoinInput(e){if(this.inputs[e].$kind!=="Object")throw new Error("not Object argument")}getStrapId(){let e;if(this.isStrapNewTransaction()?e="new":this.isLstUnlockTransaction()&&(e="locked"),!e){let t=this.getMoveCallModuleCommand("fountain","unstake");if(t){let n=t.MoveCall.arguments[2];n.$kind==="Input"&&(e=this.inputs[n.Input].UnresolvedObject.objectId)}}return e}getPureInputU64(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return zn.bcs.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return zn.bcs.vector(zn.bcs.Address).fromBase64(t.Pure.bytes)}};var gc=require("@msafe/sui3-utils");var dc=require("@mysten/sui/transactions"),fc=require("bucket-protocol-sdk");var pc=require("bucket-protocol-sdk"),Mt=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new pc.BucketClient(t,e.address)};var hc=async(a,e,t)=>{let{coinType:n,amount:o,buckToCoin:i}=a,s=new dc.Transaction,l=Mt(t,e);return await(0,fc.buildPsmTx)(l,s,n,o,i,e.address),s};var Zn=class a extends k{constructor(t){super(t);this.data=t}txType=gc.TransactionType.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await hc(this.data,n,o)}static fromData(t){return new a(t)}};var wc=require("@msafe/sui3-utils");var mn=require("@mysten/sui/transactions"),se=require("bucket-protocol-sdk");var yc=async(a,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:i,insertionPlace:s,strapId:l}=a,d=new mn.Transaction,S=Mt(t,e);return await(0,se.buildBorrowTx)(S,d,n,o,i,e.address,s,l),d},bc=async(a,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:i,strapId:s}=a,l=new mn.Transaction,d=Mt(t,e);return await(0,se.buildWithdrawTx)(d,l,n,o,e.address,i,s),l},Sc=async(a,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:i,isSurplus:s,insertionPlace:l,strapId:d}=a,S=new mn.Transaction,w=Mt(t,e);return await(0,se.buildRepayTx)(w,S,n,o,i,e.address,s,l,d),S},Tc=async(a,e,t)=>{let{collateralType:n,recipient:o,strapId:i}=a,s=new mn.Transaction,l=Mt(t,e);return await(0,se.buildCloseTx)(l,s,n,o,i),s};var to=class a extends k{constructor(t){super(t);this.data=t}txType=wc.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await yc(this.data,n,o)}static fromData(t){return new a(t)}};var Ic=require("@msafe/sui3-utils");var eo=class a extends k{constructor(t){super(t);this.data=t}txType=Ic.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await Sc(this.data,n,o)}static fromData(t){return new a(t)}};var Cc=require("@msafe/sui3-utils");var no=class a extends k{constructor(t){super(t);this.data=t}txType=Cc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await bc(this.data,n,o)}static fromData(t){return new a(t)}};var kc=require("@msafe/sui3-utils");var oo=class a extends k{constructor(t){super(t);this.data=t}txType=kc.TransactionType.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await Tc(this.data,n,o)}static fromData(t){return new a(t)}};var dn=require("@msafe/sui3-utils");var pn=require("@mysten/sui/transactions"),ce=require("bucket-protocol-sdk");var xc=async(a,e,t)=>{let{coinType:n,amount:o,isStake:i}=a,s=new pn.Transaction,l=Mt(t,e);return await(0,ce.buildSBUCKDepositTx)(l,s,n,o,e.address,i),s},Dc=async(a,e,t)=>{let{stakeProofs:n,amount:o,isStake:i,toBuck:s}=a,l=new pn.Transaction,d=Mt(t,e);return await(0,ce.buildSBUCKUnstakeTx)(d,l,n,o,e.address,i,s),l},vc=async(a,e,t)=>{let{amount:n}=a,o=new pn.Transaction,i=Mt(t,e);return await(0,ce.buildSBUCKWithdrawTx)(i,o,n,e.address),o},Ac=async(a,e,t)=>{let{stakeProofs:n}=a,o=new pn.Transaction,i=Mt(t,e);return await(0,ce.buildSBUCKClaimTx)(i,o,n,e.address),o};var ao=class a extends k{constructor(t){super(t);this.data=t}txType=dn.TransactionType.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await xc(this.data,n,o)}static fromData(t){return new a(t)}},io=class a extends k{constructor(t){super(t);this.data=t}txType=dn.TransactionType.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await Dc(this.data,n,o)}static fromData(t){return new a(t)}},ro=class a extends k{constructor(t){super(t);this.data=t}txType=dn.TransactionType.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await vc(this.data,n,o)}static fromData(t){return new a(t)}},so=class a extends k{constructor(t){super(t);this.data=t}txType=dn.TransactionType.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await Ac(this.data,n,o)}static fromData(t){return new a(t)}};var po=require("@msafe/sui3-utils");var co=require("@mysten/sui/transactions"),Ue=require("bucket-protocol-sdk");var Oc=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new co.Transaction,s=Mt(t,e);return await(0,Ue.buildTankDepositTx)(s,i,n,o,e.address),i},Mc=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new co.Transaction,s=Mt(t,e);return await(0,Ue.buildTankWithdrawTx)(s,i,n,o,e.address),i},Pc=async(a,e,t)=>{let{coinType:n}=a,o=new co.Transaction,i=Mt(t,e);return await(0,Ue.buildTankClaimTx)(i,o,n,e.address),o};var Rc=require("@mysten/sui/transactions"),Bc=require("bucket-protocol-sdk");var Ec=async(a,e,t)=>{let{coinType:n,proofCount:o}=a,i=new Rc.Transaction,s=Mt(t,e);return await(0,Bc.buildLockedClaimTx)(s,i,n,o,e.address),i};var lo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await Oc(this.data,n,o)}static fromData(t){return new a(t)}},uo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await Mc(this.data,n,o)}static fromData(t){return new a(t)}},mo=class a extends k{constructor(t){super(t);this.data=t}txType=po.TransactionType.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await Pc(this.data,n,o)}static fromData(t){return new a(t)}};var Nc=require("@msafe/sui3-utils");var fo=class a extends k{constructor(t){super(t);this.data=t}txType=Nc.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Ec(this.data,n,o)}static fromData(t){return new a(t)}};var ho=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new Yn(t).decode();return{txType:Wc.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"psm":i=Zn.fromData(e.intentionData);break;case"borrow":i=to.fromData(e.intentionData);break;case"withdraw":i=no.fromData(e.intentionData);break;case"repay":i=eo.fromData(e.intentionData);break;case"close":i=oo.fromData(e.intentionData);break;case"tank-deposit":i=lo.fromData(e.intentionData);break;case"tank-withdraw":i=uo.fromData(e.intentionData);break;case"tank-claim":i=mo.fromData(e.intentionData);break;case"sbuck-deposit":i=ao.fromData(e.intentionData);break;case"sbuck-unstake":i=io.fromData(e.intentionData);break;case"sbuck-withdraw":i=ro.fromData(e.intentionData);break;case"sbuck-claim":i=so.fromData(e.intentionData);break;case"lock-claim":i=fo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var ql=require("@msafe/sui3-utils");var Xc=require("@msafe/sui3-utils");var go=require("@cetusprotocol/aggregator-sdk"),_c=require("@cetusprotocol/farms-sdk"),Lc=require("@cetusprotocol/sui-clmm-sdk"),jc=require("@cetusprotocol/vaults-sdk"),Uc=require("@cetusprotocol/xcetus-sdk"),Re=require("@mysten/sui/client"),ae=(a,e)=>{let t=Lc.CetusClmmSDK.createSDK({env:"mainnet",sui_client:new Re.SuiClient({url:(0,Re.getFullnodeUrl)("mainnet")})});return t.setSenderAddress(e.address),t},Ut=(a,e)=>{let t=_c.CetusFarmsSDK.createSDK({env:"mainnet",sui_client:new Re.SuiClient({url:(0,Re.getFullnodeUrl)("mainnet")})});return t.setSenderAddress(e.address),t},Kp="https://api-sui.cetus.zone/router_v2/find_routes",qc=(a,e)=>{let t=new Re.SuiClient({url:"https://fullnode.mainnet.sui.io/"});return new go.AggregatorClient({endpoint:Kp,signer:e.address,client:t,env:go.Env.Mainnet})},fn=(a,e)=>{let t=jc.CetusVaultsSDK.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t},qe=(a,e)=>{let t=Uc.CetusXcetusSDK.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t};var Fc=async(a,e,t)=>await ae(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Kc=async(a,e,t)=>await ae(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Vc=async(a,e,t)=>await ae(t,e).Position.closePositionPayload(a),$c=async(a,e,t)=>await ae(t,e).Position.removeLiquidityPayload(a),Hc=async(a,e,t)=>await ae(t,e).Rewarder.collectRewarderPayload(a);var yo=class a extends k{constructor(t){super(t);this.data=t}txType=Xc.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Fc(i,n,o)}static fromData(t){return new a(t)}};var Gc=require("@msafe/sui3-utils");var bo=class a extends k{constructor(t){super(t);this.data=t}txType=Gc.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Hc(i,n,o)}static fromData(t){return new a(t)}};var Qc=require("@msafe/sui3-utils");var So=class a extends k{constructor(t){super(t);this.data=t}txType=Qc.TransactionType.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await $c(i,n,o)}static fromData(t){return new a(t)}};var il=require("@msafe/sui3-utils");var zc=async(a,e,t)=>await Ut(t,e).Farms.openPositionAddLiquidityStakePayload(a),Jc=async(a,e,t)=>await Ut(t,e).Farms.addLiquidityFixCoinPayload(a),Yc=async(a,e,t)=>await Ut(t,e).Farms.removeLiquidityPayload(a),Zc=async(a,e,t)=>await Ut(t,e).Farms.removeLiquidityPayload(a),tl=async(a,e,t)=>await Ut(t,e).Farms.claimFeeAndClmmReward(a),el=async(a,e,t)=>await Ut(t,e).Farms.harvestPayload(a),nl=async(a,e,t)=>{let n=Ut(t,e),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},ol=async(a,e,t)=>await Ut(t,e).Farms.depositPayload(a),al=async(a,e,t)=>await Ut(t,e).Farms.withdrawPayload(a);var To=class a extends k{constructor(t){super(t);this.data=t}txType=il.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await zc(i,n,o)}static fromData(t){return new a(t)}};var rl=require("@msafe/sui3-utils");var wo=class a extends k{constructor(t){super(t);this.data=t}txType=rl.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await nl(i,n,o)}static fromData(t){return new a(t)}};var sl=require("@msafe/sui3-utils");var Io=class a extends k{constructor(t){super(t);this.data=t}txType=sl.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await tl(i,n,o)}static fromData(t){return new a(t)}};var cl=require("@msafe/sui3-utils");var Co=class a extends k{constructor(t){super(t);this.data=t}txType=cl.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Yc(i,n,o)}static fromData(t){return new a(t)}};var ll=require("@msafe/sui3-utils");var ko=class a extends k{constructor(t){super(t);this.data=t}txType=ll.TransactionType.Other;txSubType="FarmingHarvest";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await el(i,n,o)}static fromData(t){return new a(t)}};var ul=require("@msafe/sui3-utils");var xo=class a extends k{constructor(t){super(t);this.data=t}txType=ul.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Jc(i,n,o)}static fromData(t){return new a(t)}};var ml=require("@msafe/sui3-utils");var Do=class a extends k{constructor(t){super(t);this.data=t}txType=ml.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Zc(i,n,o)}static fromData(t){return new a(t)}};var pl=require("@msafe/sui3-utils");var vo=class a extends k{constructor(t){super(t);this.data=t}txType=pl.TransactionType.Other;txSubType="FarmingStake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await ol(i,n,o)}static fromData(t){return new a(t)}};var dl=require("@msafe/sui3-utils");var Ao=class a extends k{constructor(t){super(t);this.data=t}txType=dl.TransactionType.Other;txSubType="FarmingUnstake";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await al(i,n,o)}static fromData(t){return new a(t)}};var fl=require("@msafe/sui3-utils");var Oo=class a extends k{constructor(t){super(t);this.data=t}txType=fl.TransactionType.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Kc(i,n,o)}static fromData(t){return new a(t)}};var yl=require("@msafe/sui3-utils");var hn=require("@mysten/sui/transactions"),Mo=jt(require("haedal-vault-sdk"));var Vp=async(a,e,t)=>{let n=fn(t,e),o=new hn.Transaction;return o.setSender(e.address),n.Vest.buildRedeemPayload(a.params,o),o},$p=async(a,e,t)=>{let n=new Mo.default(Mo.vaults_mainnet);n.senderAddress=e.address;let o=new hn.Transaction;return o.setSender(e.address),await n?.Vest.buildRedeemPayload(a.params,o),o},hl=(a,e,t)=>{let n=ae(t,e),o=new hn.Transaction;return n?.Vest.buildRedeemPayload(a.params,o),o},Hp=async(a,e,t)=>{let n=ae(t,e),o=Ut(t,e),i=new hn.Transaction,s=await o.Farms.withdrawReturnPayload(a.withdrawParams,i);return n.Vest.buildRedeemPayload(a.redeemParms.map(l=>({...l,clmm_position_id:s})),i),o.Farms.depositPayload({...a.depositParams,clmm_position_id:s},i),i},gl=async(a,e,t)=>a.type==="clmm"?hl(a,e,t):a.type==="farms"?Hp(a,e,t):a.type==="vaults"?Vp(a,e,t):a.type==="haedalVaults"?$p(a,e,t):hl(a,e,t);var Po=class a extends k{constructor(t){super(t);this.data=t}txType=yl.TransactionType.Other;txSubType="PosVestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await gl(i,n,o)}static fromData(t){return new a(t)}};var bl=require("@msafe/sui3-utils");var Ro=class a extends k{constructor(t){super(t);this.data=t}txType=bl.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Vc(i,n,o)}static fromData(t){return new a(t)}};var Il=require("@msafe/sui3-utils");var Sl=require("@cetusprotocol/aggregator-sdk"),Tl=require("@mysten/sui/transactions");var wl=async(a,e,t)=>{let n=qc(t,e),o=new Tl.Transaction;return await n.fastRouterSwap({...a,routers:(0,Sl.restituteMsafeFastRouterSwapParams)(a.routers),txb:o}),o};var Bo=class a extends k{constructor(t){super(t);this.data=t}txType=Il.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await wl(i,n,o)}static fromData(t){return new a(t)}};var xl=require("@msafe/sui3-utils");var Kr=require("@mysten/sui/transactions");var Cl=async(a,e,t)=>{let n=fn(t,e),o=new Kr.Transaction;return o.setSender(e.address),await n.Vaults.deposit(a,o),o},kl=async(a,e,t)=>{let n=fn(t,e),o=new Kr.Transaction;return await n.Vaults.withdraw(a,o),o};var Eo=class a extends k{constructor(t){super(t);this.data=t}txType=xl.TransactionType.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Cl(i,n,o)}static fromData(t){return new a(t)}};var Dl=require("@msafe/sui3-utils");var No=class a extends k{constructor(t){super(t);this.data=t}txType=Dl.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await kl(i,n,o)}static fromData(t){return new a(t)}};var Ml=require("@msafe/sui3-utils");var Al=require("@mysten/sui/transactions"),vl={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Ol=async(a,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:o,periods:i,CLOCK_ADDRESS:s}=a,l=new Al.Transaction;return i.forEach(d=>{l.moveCall({target:`${vl.published_at}::router::redeem`,typeArguments:[vl.cetus_coin_type],arguments:[l.object(n),l.object(o),l.pure(d),l.object(s)]})}),l};var Wo=class a extends k{constructor(t){super(t);this.data=t}txType=Ml.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ol(i,n,o)}static fromData(t){return new a(t)}};var Wl=require("@msafe/sui3-utils");var Pl=async(a,e,t)=>await qe(t,e).XCetusModule.convertPayload(a),Rl=async(a,e,t)=>await qe(t,e).XCetusModule.redeemLockPayload(a),Bl=async(a,e,t)=>await qe(t,e).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),El=async(a,e,t)=>await qe(t,e).XCetusModule.cancelRedeemPayload(a),Nl=async(a,e,t)=>await qe(t,e).XCetusModule.redeemPayload(a);var _o=class a extends k{constructor(t){super(t);this.data=t}txType=Wl.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await El(i,n,o)}static fromData(t){return new a(t)}};var _l=require("@msafe/sui3-utils");var Lo=class a extends k{constructor(t){super(t);this.data=t}txType=_l.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Bl(i,n,o)}static fromData(t){return new a(t)}};var Ll=require("@msafe/sui3-utils");var jo=class a extends k{constructor(t){super(t);this.data=t}txType=Ll.TransactionType.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Pl(i,n,o)}static fromData(t){return new a(t)}};var jl=require("@msafe/sui3-utils");var Uo=class a extends k{constructor(t){super(t);this.data=t}txType=jl.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Nl(i,n,o)}static fromData(t){return new a(t)}};var Ul=require("@msafe/sui3-utils");var qo=class a extends k{constructor(t){super(t);this.data=t}txType=Ul.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Rl(i,n,o)}static fromData(t){return new a(t)}};var Fo=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:ql.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...t},action:n}}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(e.txSubType){case"OpenAndAddLiquidity":i=yo.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Oo.fromData(e.intentionData);break;case"DecreaseLiquidity":i=So.fromData(e.intentionData);break;case"RemoveLiquidity":i=Ro.fromData(e.intentionData);break;case"ClaimFeeAndMining":i=bo.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":i=To.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":i=xo.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":i=Co.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":i=Do.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":i=Io.fromData(e.intentionData);break;case"FarmingHarvest":i=ko.fromData(e.intentionData);break;case"FarmingBatchHarvest":i=wo.fromData(e.intentionData);break;case"FarmingStake":i=vo.fromData(e.intentionData);break;case"FarmingUnstake":i=Ao.fromData(e.intentionData);break;case"xCETUSConvert":i=jo.fromData(e.intentionData);break;case"xCETUSRedeemLock":i=qo.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":i=Lo.fromData(e.intentionData);break;case"xCETUSCancelRedeem":i=_o.fromData(e.intentionData);break;case"xCETUSRedeem":i=Uo.fromData(e.intentionData);break;case"VestingRedeem":i=Wo.fromData(e.intentionData);break;case"AggregatorSwap":i=Bo.fromData(e.intentionData);break;case"AddVaultsPosition":i=Eo.fromData(e.intentionData);break;case"RemoveVaultsPosition":i=No.fromData(e.intentionData);break;case"PosVestingRedeem":i=Po.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var uu=require("@msafe/sui3-utils");var Fl=jt(require("sort-keys-recursive")),P=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,Fl.default)(this.data))}};var gn=require("@mysten/sui.js/client");var Vr={};Fr(Vr,{contractId:()=>Qp,default:()=>td,feeObjId:()=>Yp,roleObjId:()=>zp,status:()=>Gp,transaction:()=>Xp,upgradeCapObjId:()=>Zp,vaultObjId:()=>Jp});var Xp="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Gp="success",Qp="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",zp="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Jp="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Yp="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Zp="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",td={transaction:Xp,status:Gp,contractId:Qp,roleObjId:zp,vaultObjId:Jp,feeObjId:Yp,upgradeCapObjId:Zp};var $r={};Fr($r,{contractId:()=>od,default:()=>cd,feeObjId:()=>rd,roleObjId:()=>ad,status:()=>nd,transaction:()=>ed,upgradeCapObjId:()=>sd,vaultObjId:()=>id});var ed="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",nd="success",od="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",ad="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",id="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",rd="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",sd="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",cd={transaction:ed,status:nd,contractId:od,roleObjId:ad,vaultObjId:id,feeObjId:rd,upgradeCapObjId:sd};var ld=(0,gn.getFullnodeUrl)("testnet"),ud=(0,gn.getFullnodeUrl)("testnet"),md=(0,gn.getFullnodeUrl)("mainnet"),pd=(0,gn.getFullnodeUrl)("mainnet"),dd="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",fd="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",hd="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",gd="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Kl=Vr,Vl=$r,yd=new Map([["dev",{env:"dev",rpc:{url:ld},backend:{url:dd},contract:Kl}],["stg",{env:"stg",rpc:{url:ud},backend:{url:fd},contract:Kl}],["prev",{env:"prev",rpc:{url:md},backend:{url:hd},contract:Vl}],["prod",{env:"prod",rpc:{url:pd},backend:{url:gd},contract:Vl}]]);function $l(a,e){let t=yd.get(a);if(!t)throw new Error(`Env not supported: ${a}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var Hl=require("@mysten/sui.js/client");var L=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:o,context:i}=n;o?super(`[MPay] ${t}: ${o}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=i}};var Ko=class extends L{constructor(){super(11,"Backend is not specified")}};var Vo=class extends L{constructor(){super(1,"Wallet not connected")}};var ie=jt(require("axios"));var Fe=class extends L{constructor(e,t){super(10,e,{context:t})}};var $o=class a{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof ie.AxiosError)throw new Fe(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Fe(e.data.code)}throw new Fe(e.status.toString())}async getIncomingStreams(e,t){let n=await ie.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await ie.default.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(n)}async getStreamHistory(e){let t=await ie.default.post(`${this.apiURL}/stream-events`,e),n=a.parseResponseData(t);return n.data.forEach(o=>{let i=o;return i.data.type==="create_stream"?i.data.balance=BigInt(i.data.balance):i.data.type==="cancel_stream"?i.data.withdrawAmount=BigInt(i.data.withdrawAmount):i.data.type==="claim"||i.data.type==="auto_claim"?i.data.claimAmount=BigInt(i.data.claimAmount):i.data.type==="set_auto_claim"&&(i.data.enabled=!!i.data.enabled),i.createdAt=new Date(i.createdAt),i}),n}async getAllCoinTypes(e){let t=await ie.default.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let n=await ie.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(n)}async getAllSenders(e,t){let n=await ie.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(n)}};var Ke=class a{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Hl.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new $o(e.backend.url))}static new(e,t){let n=$l(e,t);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Ko;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 Vo;return this.signer}async walletAddress(){return this.wallet.address()}};var Ee=require("@mysten/sui.js/utils");var In=require("@mysten/sui.js/transactions");var zr=require("@mysten/sui.js/transactions"),wn=require("@mysten/sui.js/utils");var Hr=50n,Ho=10000n,Xl=25n,Xr=100000000n;var Jt=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},yn=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},me=class a{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let o=s=>new a(t.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield o(s),s++};if(typeof n=="symbol")return;let i=parseInt(n,10);if(!(Number.isNaN(i)||i<0))return o(i)}})}moveArg(){return this.result}};var Gr=require("buffer"),Gl=require("@mysten/sui.js/utils");var bn=class extends L{constructor(e,t){super(3,e,{context:t})}};var Xo=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let n=this.callResult(e);return this.returnValue(n,t)}getAddress(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="address")throw new bn("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return(0,Gl.normalizeSuiAddress)(Gr.Buffer.from(n).toString("hex"))}getU64(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="u64")throw new bn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Gr.Buffer.from(n).readBigInt64LE()}};var Qr=require("@mysten/sui.js/bcs");var H=class extends L{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var zl={groupId:"string",name:"string"},bd=64;function Jl(a){return Yl(a),Qr.bcs.ser(zl,a).toString("base64")}function Sn(a){let e=Qr.bcs.de(zl,a,"base64");return Yl(e),e}function Yl(a){if(!Ql(a.name))throw new H("Invalid metadata: Name contains unknown character");if(!Ql(a.groupId))throw new H("Invalid metadata: Group ID contains unknown character");if(a.name.length>bd)throw new H("Invalid metadata: Name exceed max length 64")}function Ql(a){return/^[\x00-\x7F]+$/.test(a)}var Tn=require("@mysten/sui.js/utils");function Go(a,e){return(0,Tn.normalizeStructTag)(a)===(0,Tn.normalizeStructTag)(e)}function pe(a,e){return(0,Tn.normalizeStructTag)(a)===(0,Tn.normalizeStructTag)(e)}var Qo="txn.gas";var Zl=require("nanoid");function tu(){return(0,Zl.nanoid)()}var Be=class a{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:Jl({name:e.name,groupId:tu()}),coinType:(0,wn.normalizeStructTag)(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new zr.TransactionBlock,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),i=await this.wallet.requestCoins(o),s=await this.addMergeCoins(t,i[0]),l;o.length>1?l=await this.addMergeCoins(t,i[1]):l=s;for(let d=0;d<e.recipients.length;d++){let S=e.recipients[d],w=this.amountForRecipient(S,e.numberEpoch),I=this.getStreamFeeLocal(w),[C]=t.splitCoins(s,[t.pure(w+I,"u64")]),[x]=t.splitCoins(l,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new me(C),flatFeeCoin:new me(x),metadata:e.metadata,recipient:S.address,timeStart:e.startTime,cliff:S.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:S.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:Hr,denominator:Ho},claimFeePercent:{numerator:Xl,denominator:Ho},flatFeePerStream:Xr}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(o=>e.object(o))),n=e.object(t.primaryCoin)):t.primaryCoin===Qo?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return Go(n,wn.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:wn.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,i)=>{let s=this.amountForRecipient(i,e.numberEpoch),l=this.getStreamFeeLocal(s);return{totalAmount:o.totalAmount+s,streamFeeAmount:o.streamFeeAmount+l}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return Xr}getStreamFeeLocal(e){return e*Hr/Ho}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new zr.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new Xo(n).getU64()}get wallet(){return this.globals.wallet}};var Jr=require("@mysten/sui.js/transactions");var eu="0x0000000000000000000000000000000000000000000000000000000000000006";var Ve=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(Jr.Transactions.MoveCall({target:n,arguments:t.arguments.map(o=>o instanceof yn?o.moveArgs(e):o instanceof Jt?o.moveArg(e):o instanceof me?o.moveArg():e.pure(o)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,n=[],o=[]){e.add(Jr.Transactions.MoveCall({target:t,arguments:n.map(i=>i instanceof yn?i.moveArgs(e):i instanceof Jt?i.moveArg(e):i instanceof me?i.moveArg():e.pure(i)),typeArguments:o}))}makeObject(e){return typeof e=="string"?new Jt(e):e}vaultObject(){return new Jt(this.config.vaultObjId)}roleObject(){return new Jt(this.config.roleObjId)}feeObject(){return new Jt(this.config.feeObjId)}clockObject(){return new Jt(eu)}};var $e=class a extends Ve{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_fee,arguments:[o,i,n],typeArgs:[]})}setStreamingFlatFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,i,n],typeArgs:[]})}setClaimFee(t,n){let o=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_claim_fee,arguments:[o,i,n],typeArgs:[]})}streamingFee(t,n){let o=this.feeObject();return this.addContractCall(t,{method:a.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Yt=class a extends Ve{constructor(t,n){super(a.ModuleName,t,n);this.config=t;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(t,n){let o=this.feeObject(),i=this.vaultObject(),s=this.makeObject(n.paymentCoin),l=this.makeObject(n.flatFeeCoin),d=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[o,i,s,l,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,d],typeArgs:[n.coinType]})}setAutoClaim(t,n){let o=this.makeObject(n.streamId);return this.addContractCall(t,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.cancel_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStream(t,n){let o=this.makeObject(n.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream,arguments:[o,i],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let o=this.makeObject(n.streamId),i=this.vaultObject(),s=this.feeObject(),l=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,i,s,l],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var He=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new $e(t,e),this.streamContract=new Yt(t,e)}feeContract;streamContract;async createStreams(e){let t=Be.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new Be(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new In.TransactionBlock;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new In.TransactionBlock;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new In.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new In.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};var Xe=require("@mysten/sui.js/utils"),Yr=require("luxon");var zo=class extends L{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var Sd=1e3,Jo=class{constructor(e){this.globals=e;this.coinMetaHelper=new Zr(e.suiClient),this.createStreamHelper=new He(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new zo(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},n=e.totalAmount*t.numerator/t.denominator,o=(e.totalAmount-n)/e.steps,s={realTotalAmount:o*e.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(s,e.totalAmount),s}calculateTimelineByInterval(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),n={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(Yr.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:Yr.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await this.globals.suiClient.getBalance({owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:(0,Xe.normalizeStructTag)(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,i)=>({...o,coinType:(0,Xe.normalizeStructTag)(o.coinType),coinMeta:n[i]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new H("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new H("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<Sd)throw new H("Interval shall be at least 1 second","interval",e.interval)}},Zr=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=(0,Xe.normalizeStructTag)(e||Xe.SUI_TYPE_ARG);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this.coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};var fe=require("@mysten/sui.js/utils"),rs=require("luxon");var xn=require("@mysten/sui.js/transactions"),Dn=require("@mysten/sui.js/utils"),ou=require("luxon");var Yo=class extends L{constructor(){super(7,"Connected wallet is not creator")}};var Cn=class extends L{constructor(){super(8,"Connected wallet is not recipient")}};var kn=class extends L{constructor(e,t){super(6,e,{context:t})}};var At=class extends L{constructor(e,t={}){super(0,e,t)}};var Zo=class extends L{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};var ea=require("luxon"),nu=(1n<<64n)-1n,ta=1e3;function ts(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/ta);return ea.DateTime.fromMillis(t*ta)}function es(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/ta);return ea.Duration.fromMillis(t*ta)}var de=class a{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new Yt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await a.fetchStreamData(e,t);return new a(e,t,n)}static fromObjectData(e,t,n){let o=a.parseRawStreamData(t,n);return new a(e,t,o)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new At("Object Id does not align");this.rawData=a.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 Yo;let e=new xn.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Cn;let e=new xn.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 Cn;let t=new xn.TransactionBlock;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new xn.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,Dn.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 es(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Sn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Sn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ts(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return es(t)}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:ts((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===nu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=ou.DateTime.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new Zo(e):new kn(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new kn("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=(0,Dn.parseStructTag)(n.type),i=(0,Dn.normalizeStructTag)(o[0]),s=n.fields,l=s.config.fields,d=s.status.fields;return{coinType:i,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(l.amount_per_epoch),cancelable:l.cancelable,cliff:BigInt(l.cliff),creator:l.creator,epochInterval:BigInt(l.epoch_interval),metadata:l.metadata,recipient:l.recipient,timeStart:BigInt(l.time_start),totalEpoch:BigInt(l.total_epoch)},status:{status:d.status,epochCanceled:BigInt(d.epoch_canceled),epochClaimed:BigInt(d.epoch_claimed)}}}};var Ge=class extends L{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function os(a){let e=[];for(;await a.hasNext();){let t=await a.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var ns=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)}},Qe=class{constructor(e){this.requester=e;this.pager=new ns(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]}};var Td=25;async function is(a,e,t){let n=new vn(e),o=new An(a,n,t);return await os(o)}var vn=class{constructor(e){this.ids=e;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]}},An=class extends Qe{constructor(t,n,o){super(new as(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}},as=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||Td,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&e.push(i)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=t.filter(i=>o?.(i))}else n=t;return{data:n,hasNext:await this.stringIter.hasNext()}}};var na=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new Ge("stream size 0");let n=t.map(i=>i.groupId);if(new Set(n).size!==1)throw new H("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await is(e.suiClient,t);return n.forEach(o=>{if(!o)throw new At("stream group object data undefined")}),a.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let o=await a.parseGroupStreams(e,t,n);return new a(e,o)}static checkStreamGroup(e){let t=e.map(i=>i.groupCommonInfo),n=t[0],o=!0;return t.forEach(i=>{wd(n,i)||(o=!1)}),o}async refresh(){let e=await is(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let o=n.map((i,s)=>de.fromObjectData(e,t[s],i)).filter(i=>!!i);if(new Set(o.map(i=>i.groupId)).size!==1)throw new Ge("Not same group ID");if(!this.checkStreamGroup(o))throw new Ge("Not same stream settings");return o}};function wd(a,e){return a.name===e.name&&a.groupId===e.groupId&&a.creator===e.creator&&a.start.toMillis()===e.start.toMillis()&&a.interval.toMillis()===e.interval.toMillis()&&a.steps===e.steps&&a.cancelable===e.cancelable}var On=class a{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await oa.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await oa.newOutgoing(e);return new a(t,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}},oa=class a{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await aa.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await aa.newOutgoingQuery(e);return new a(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new At("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new At("No more results");return e}},aa=class a{constructor(e,t,n,o){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=o;this.current=0;let i=new vn(n.flat().map(s=>s.streamId));this.objectIter=new An(e.suiClient,i)}current=0;objectIter;static async newIncomingQuery(e){let t=Dd(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,t)).filter(l=>(0,fe.normalizeSuiAddress)(l.recipient)===(0,fe.normalizeSuiAddress)(n)),s=au(i);return new a(e.globals,n,s,e.query)}static async newOutgoingQuery(e){let t=vd(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),i=au(o);return new a(e.globals,n,i,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await kd(this.globals,e[0].streamId,this.objectIter);return this.current++,iu(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await xd(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Cd(t,this.query)?t:this.doNextRequest()}throw new At("Stream group with no stream")}};function au(a){let e=new Map;return a.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>rs.DateTime.fromISO(n[0].createDate).toMillis()-rs.DateTime.fromISO(t[0].createDate).toMillis())}function iu(a,e){if(e===void 0)return!0;let t=Id(a,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return t&&n}return t}function Id(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function Cd(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(n=>{iu(n,e)&&(t=!0)}),t}async function kd(a,e,t){let n=await ru(t,e);return de.fromObjectData(a,e,n)}async function xd(a,e,t){let n=[];for(;n.length<e.length;){let o=await ru(t,e[n.length]);n.push(o)}return na.newFromObjectResponse(a,e,n)}async function ru(a,e){if(!await a.hasNext())throw new At("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new At("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new At("stream id not aligned");return t}function Dd(a){return{status:ss(a?.status),coinType:su(a?.coinType),sender:cu(a?.sender)}}function vd(a){return{status:ss(a?.status),coinType:su(a?.coinType),recipient:cu(a?.recipient)}}function ss(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let n=ss(t);return!e||e===n?n:"all"},void 0):Ad(a)}function Ad(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new H("Unknown stream filtered status")}}function su(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,fe.normalizeStructTag)(e)):void 0:(0,fe.normalizeStructTag)(a)}function cu(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,fe.normalizeSuiAddress)(e)):void 0:(0,fe.normalizeSuiAddress)(a)}var ia=class extends L{constructor(t,n,o){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:n,gotAmount:o}});this.coinType=t;this.requestAmount=n;this.gotAmount=o}};var Od=25;async function lu(a,e,t,n="0x2::sui::SUI",o=Od){let i=new cs(a,e,n,o),s=BigInt(0),l=[];for(;await i.hasNext()&&s<t;){let d=await i.next();d&&(l.push(d),s+=BigInt(d.balance))}if(s<t)throw new ia(n,t,s);return l}var cs=class extends Qe{constructor(t,n,o,i){super(new ls(t,n,o,i));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=i}},ls=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new At("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var us=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},ra=class{constructor(e){this.account=e}async address(){return this.account.address}},ms=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(Go(e.coinType,Ee.SUI_TYPE_ARG))return{primaryCoin:Qo};if(e.amount<=0)throw new H("Invalid coin request","coinAmount",e.amount);let t=await lu(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new At("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},sa=class{globals;helper;constructor(e,t){this.globals=Ke.new(e,t),this.helper=new Jo(this.globals)}connectSingleWallet(e){let t=new ms(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new us(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return de.new(this.globals,e)}async getIncomingStreams(e,t=10){return On.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return On.newOutgoing({globals:this.globals,query:e,pageSize:t})}async getCoinTypesForStreamFilter(){let e=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(e)).map(n=>(0,Ee.normalizeStructTag)(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>(0,Ee.normalizeSuiAddress)(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>(0,Ee.normalizeSuiAddress)(o))}get wallet(){return this.globals.wallet}builder(){return new He(this.globals)}};var Ft=class extends P{application="mpay";getClient(e,t){let n=new sa(e==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new ra(t)),n}};var Mn=class extends Ft{constructor(t){super(t);this.data=t}txType=uu.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};var mu=require("@msafe/sui3-utils");var Pn=class extends Ft{constructor(t){super(t);this.data=t}txType=mu.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};var pu=require("@msafe/sui3-utils");var Rn=class extends Ft{constructor(t){super(t);this.data=t}txType=pu.TransactionType.Stream;txSubType="Claim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};var du=require("@msafe/sui3-utils");var Bn=class extends Ft{constructor(t){super(t);this.data=t}txType=du.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o}=t;return this.getClient(n,o).createStream(this.data)}};var ps=require("@mysten/sui.js/bcs"),he=require("@mysten/sui.js/utils"),ze=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,he.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return ps.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,he.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,he.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,he.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,he.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return ps.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,he.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var ca=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&pe(t.target,this.contract.createStreamTarget));if(e.length===0)throw new At("No create stream transactions");return e.map(t=>new ze(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=Sn(t),i=e.decodeInputAddress(5),s=e.decodeInputU64(6),l=e.decodeInputU64(7),d=e.decodeInputU64(8),S=e.decodeInputU64(9),w=e.decodeInputU64(10),I=e.decodeInputBool(11),C=e.typeArg(0);return{name:n,groupId:o,recipient:i,timeStart:s,cliff:l,epochInterval:d,totalEpoch:S,amountPerEpoch:w,cancelable:I,coinType:C}}aggregateGroupStreamInfo(e){if(new Set(e.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new H("Stream group not have common info");let n=e.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:n,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Yt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new $e(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Be(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var la=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new Yt(e.envConfig.contract,e)}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"&&pe(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&pe(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new ca(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new ze(e,this.txb)}};var fu=require("@msafe/sui3-utils");var En=class extends Ft{constructor(t){super(t);this.data=t}txType=fu.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var ua=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:n}=e,o=Ke.new(t==="sui:mainnet"?"prod":"dev"),s=new la(o,n).decode(),l;switch(s.type){case"CreateStream":l=new Bn(s.info);break;case"SetAutoClaim":l=new En({streamId:s.streamId,enabled:s.enabled});break;case"Claim":l=new Rn({streamId:s.streamId});break;case"ClaimByProxy":l=new Pn({streamId:s.streamId});break;case"Cancel":l=new Mn({streamId:s.streamId});break;default:throw new Error(`Unknown transaction type: ${s}`)}return{txType:l.txType,txSubType:l.txSubType,intentionData:l.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Bn(t);break;case"Claim":n=new Rn(t);break;case"ClaimByProxy":n=new Pn(t);break;case"SetAutoClaim":n=new En(t);break;case"Cancel":n=new Mn(t);break;default:throw new Error("not implemented")}return n.build({...e})}};var Nn=require("@msafe/sui3-utils");var hu=require("@msafe/sui3-utils");var ma=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return(0,hu.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var gu=require("@msafe/sui3-utils");var pa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return(0,gu.buildObjectTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var da=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=Nn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case Nn.TransactionSubTypes.assets.coin.send:o=ma.fromData(e.intentionData);break;case Nn.TransactionSubTypes.assets.object.send:o=pa.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Au=require("@msafe/sui3-utils");var yu=!1,Wn={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,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"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",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"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function ds(){if(!yu)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(i=>i.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:o}=a;e&&(Wn.ProtocolPackage=e),t&&(Wn.borrowFee=t),n&&(Wn.borrowFeeAddress=n),o&&(Wn.pool=o),yu=!0}catch(a){console.error(a.message)}}var Xt=Wn;var ge=require("@msafe/sui3-utils"),fs=require("@mysten/sui.js/bcs"),ye=require("@mysten/sui.js/utils");var fa=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return!!(this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${Xt.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values(Xt.pool).find(n=>n.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:ge.TransactionType.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:ge.TransactionType.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${Xt.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===t){let o=new ha(n,this.txb),i=o.decodeInputU8(3),s=o.decodeInputU64(5);e.push({assetId:i,amount:s})}}),{txType:ge.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:ge.TransactionType.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ge.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Xt.ProtocolPackage));return new ha(e,this.txb)}},ha=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,ye.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return fs.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,ye.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ye.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,ye.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ye.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return fs.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,ye.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Kt=require("navi-sdk");async function Je(a,e,t,n){return await(0,Kt.depositCoin)(a,e,t,n),a}async function bu(a,e,t,n){let[o]=await(0,Kt.withdrawCoin)(a,e,t);return a.transferObjects([o],a.pure(n)),a}async function Su(a,e,t,n){let[o]=await(0,Kt.borrowCoin)(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function hs(a,e,t,n){return await(0,Kt.repayDebt)(a,e,t,n),a}async function Tu(a,e){return await(0,Kt.claimAllRewardsPTB)(a,e)}async function wu(a,e){return await(0,Kt.claimAllRewardsResupplyPTB)(a,e)}var ga=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await Tu(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var ya=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await wu(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var Cu=require("@mysten/sui.js/transactions");var Iu=require("navi-sdk");function Zt(a){return Object.values(Iu.pool).find(e=>String(e.assetId)===String(a))}var ba=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Cu.TransactionBlock;console.log("build",this.data);let s=Zt(n);return await Su(i,s,o,t.account.address)}static fromData(t){return new a(t)}};var ku=require("@mysten/sui.js/transactions");async function Ye(a,e,t){let n=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Sa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:s}=this.data,l=new ku.TransactionBlock;console.log("build",this.data);let d=Zt(i);if(i===0){let[C]=l.splitCoins(l.gas,[s]);return await Je(l,d,C,s)}let S=await Ye(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let C=1;for(;C<S.data.length;)l.mergeCoins(w,[S.data[C].coinObjectId]),C++}return await Je(l,d,l.object(w),s)}static fromData(t){return new a(t)}};var xu=require("@mysten/sui.js/transactions");var Ta=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:s}=this.data,l=new xu.TransactionBlock;console.log("build",this.data);let d=Zt(i);if(i===0){let[I]=l.splitCoins(l.gas,[s]);return hs(l,d,I,s)}let S=await Ye(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let I=1;for(;I<S.data.length;)l.mergeCoins(w,[S.data[I].coinObjectId]),I++}return hs(l,d,l.object(w),s)}static fromData(t){return new a(t)}};var Du=require("@mysten/sui.js/transactions");var wa=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new Du.TransactionBlock;console.log("build",this.data);let s=Zt(n);return await bu(i,s,o,t.account.address)}static fromData(t){return new a(t)}};var vu=require("@mysten/sui.js/transactions");var Ia=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:i}=this.data,s=new vu.TransactionBlock;console.log("build",this.data);for(let l=0;l<i.length;l++){let{assetId:d,amount:S}=i[l],w=Zt(d);if(d===0){let[x]=s.splitCoins(s.gas,[S]);await Je(s,w,x,S);continue}let I=await Ye(n,o.address,w.type);if(!I.data[0])throw new Error(`Insufficient balance for ${w.name} Token`);let C=I.data[0].coinObjectId;if(I.data.length>=2){let x=1;for(;x<I.data.length;)s.mergeCoins(C,[I.data[x].coinObjectId]),x++}await Je(s,w,s.object(C),S)}return s}static fromData(t){return new a(t)}};var Ca=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await ds();let{transactionBlock:t}=e,o=new fa(t).decode();return{txType:Au.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await ds(),e.txSubType){case"EntryDeposit":o=Sa.fromData(e.intentionData);break;case"EntryBorrow":o=ba.fromData(e.intentionData);break;case"EntryRepay":o=Ta.fromData(e.intentionData);break;case"EntryWithdraw":o=wa.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Ia.fromData(e.intentionData);break;case"ClaimReward":o=ga.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=ya.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var _n=require("@msafe/sui3-utils"),Ou=require("@mysten/bcs"),Mu=require("@mysten/sui/transactions"),Pu=jt(require("sort-keys-recursive")),Ru="msafe-plain-tx",Bu=_n.TransactionSubTypes.others.plain,gs=class a{constructor(e){this.data=e}application=Ru;txType=_n.TransactionType.Other;txSubType=Bu;serialize(){return JSON.stringify((0,Pu.default)(this.data))}async build(e){return Mu.Transaction.from((0,Ou.fromHex)(this.data.content))}static fromData(e){return new a(e)}},ka=class{application;supportSDK="@mysten/sui";constructor(){this.application=Ru}async deserialize(e){let{content:t}=e.appContext;return{txType:_n.TransactionType.Other,txSubType:Bu,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:o}=e;return gs.fromData(e.intentionData).build({suiClient:t,network:n,account:o})}};var Ss=require("@mysten/sui/client"),Eu=require("@mysten/sui/transactions"),va=require("@mysten/sui.js/client"),Nu=require("@mysten/sui.js/transactions");var Ze=require("@open-rpc/client-js");var Rd={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},ys=class extends Error{},xa=class extends ys{code;type;constructor(e,t){super(e),this.code=t,this.type=Rd[t]??"ServerError"}};function Bd(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var Ed={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Da=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#i=new Set;#o=new Map;constructor(e,t={}){this.endpoint=e,this.options={...Ed,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=Bd(this.endpoint))}async makeRequest(e,t){let n=await this.#r();return new Promise((o,i)=>{this.#n+=1,this.#o.set(this.#n,{resolve:o,reject:i,timeout:setTimeout(()=>{this.#o.delete(this.#n),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:o,result:i})=>{if(o)throw new xa(o.message,o.code);return i})}#r(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(o){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:o}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:o,timeout:i}=this.#o.get(n.id);clearTimeout(i),o(n)}else if("params"in n){let{params:o}=n;this.#i.forEach(i=>{i.subscriptionId===o.subscription&&o.subscription===i.subscriptionId&&i.onMessage(o.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#i].map(e=>e.subscribe(this)))}async subscribe(e){let t=new bs(e);return this.#i.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},bs=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var be=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:o}){let i=new Ze.HTTPTransport(o?.url??e,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new Ze.Client(new Ze.RequestManager([i])),this.websocketClient=new Da(t??e,n)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var Aa=class a{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new a;for(let n=0;n<e.length;n++){let o=e[n];switch(o.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(o);break;case"@mysten/sui":t.addHelper(o);break;default:throw new Error(`${o.application}: ${o.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new ws(e))}addHelper(e){this.apps.set(e.application,new Ts(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},Ts=class{constructor(e){this.helper=e}async deserialize(e){let t=new Ss.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=new va.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await e.transactionBlock.build({client:n}),i=Eu.Transaction.from(o);return this.helper.deserialize({...e,suiClient:t,transaction:i})}async build(e){let t=new Ss.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});o.setSender(e.account.address);let i=await o.build({client:t});return Nu.TransactionBlock.from(i)}},ws=class{constructor(e){this.helper=e}async deserialize(e){let t=new va.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new va.SuiClient({transport:new be({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};var $u=require("@msafe/sui3-utils"),Hu=require("@mysten/sui/client"),Xu=require("@scallop-io/sui-scallop-sdk");var Ot=require("@msafe/sui3-utils"),ks=require("@scallop-io/sui-scallop-sdk");var Wu=require("@mysten/sui/utils"),Se=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(n=>`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),veScaObjId:this.address.get("vesca.object"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:n,module:o,name:i}=(0,Wu.parseStructTag)(t);return e?e.package===n&&e.module===o&&e.function===i:!1}isMoveCall(e){return e.$kind==="MoveCall"&&!!e.MoveCall}filterMoveCallCommands(e,t){return this.isMoveCall(e)&&this.matchMoveCallCommand(e.MoveCall,t)}getMoveCallCommands(e){let t=new Set(e),n=e.reduce((i,s,l)=>(i[s]=l,i),{}),o=[];return this.commands.forEach(i=>{this.isMoveCall(i)&&i.MoveCall&&t.has(i.MoveCall.package)&&(o[n[i.MoveCall.package]]=i.MoveCall)}),o}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};var Oa=require("@mysten/sui/bcs"),Te=require("@mysten/sui/utils"),Is=class a{constructor(e,t,n=0){this.moveCall=e;this.transaction=t;let o=[];e?.MoveCall&&t.getData().commands.filter((i,s)=>{if(i.$kind==="MoveCall"){let l=`${i.MoveCall.package}::${i.MoveCall.module}::${i.MoveCall.function}`,d=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return l===d?(o.push(s),!0):!1}return!1}),this.cmdIdx=o[n]}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return(0,Te.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure,o=Oa.bcs[t];return Oa.bcs[t].parse(new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Te.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Te.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,Te.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Te.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e){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 t=e.value.Pure;return Oa.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Te.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},W=Is;var Cs=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(W.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Bt=Cs;var we=require("@mysten/sui/utils"),_u=async(a,e)=>{let t=await a.scallopSuiKit.client.getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let o=t.data.content.fields.lock_key?.fields.name;if(!o)return!1;let i=a.address.get("borrowIncentive.object");return o===`${i.slice(2)}::incentive_account::IncentiveProgramLockKey`},tn={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},Vt={unstakeObligation:(a,e,t)=>a.moveCall(`${tn.id}::user::unstake`,[tn.incentivePools,tn.incentiveAccounts,a.object(e),a.object(t),we.SUI_CLOCK_OBJECT_ID],[(0,we.normalizeStructTag)(we.SUI_TYPE_ARG)]),redeem_rewards:(a,e,t,n)=>a.moveCall(`${tn.id}::user::redeem_rewards`,[tn.incentivePools,tn.incentiveAccounts,a.object(e),a.object(t),we.SUI_CLOCK_OBJECT_ID],[(0,we.normalizeStructTag)(n)])};var Lu=(a,e)=>{let t=[];for(let n=0;n<a.length;n+=e)t.push(a.slice(n,n+e));return t};var Ma=class extends Se{decode(){if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMigrateScoinTransaction(){return this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`),t=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`);return e&&t}isUnstakeAndWithdrawTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`),t=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`);return e&&t}isStakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`),t=this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return e&&t}isDepositCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isBorrowWithReferralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isUnstakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return e||t}isOpenObligationTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let e=this.hasMoveCallCommand(`${ks.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${ks.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new W(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new W(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new W(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new W(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new W(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new W(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new W(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new W(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new W(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new W(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new W(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new W(e,this.transaction)}decodeMigrateScoin(){return{txType:Ot.TransactionType.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let t=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),n=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),o=this.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:Ot.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Ot.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"SupplyLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLending(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperRedeem.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),n=new Bt(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Ot.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeDepositCollateral(){let e=this.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),t=this.helperDepositCollateral.getNestedInputParam(3),n=new Bt(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"DepositCollateral",intentionData:{amount:n,obligationId:o,collateralCoinName:e}}}decodeWithdrawCollateral(){let e=this.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),t=this.helperWithdrawCollateral.decodeInputU64(5),n=this.helperWithdrawCollateral.decodeSharedObjectId(1),o=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"WithdrawCollateral",intentionData:{amount:t,collateralCoinName:e,obligationKey:o,obligationId:n}}}decodeBorrow(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),o=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"Borrow",intentionData:{amount:t,coinName:e,obligationKey:o,obligationId:n}}}decodeBorrowWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),i=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeBorrowWithReferral(){let e=this.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let n=this.helperBorrowWithReferral.decodeInputU64(6),o=this.helperBorrowWithReferral.decodeSharedObjectId(1),i=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Ot.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:i,obligationId:o,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new Bt(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"Repay",intentionData:{amount:n,obligationId:o,coinName:e}}}decodeRepayWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),n=this.helperRepay.getNestedInputParam(3),o=new Bt(n,this.transaction).getAmountInput().reduce((s,l)=>s+l,0),i=this.helperRepay.decodeSharedObjectId(1);return{txType:Ot.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:i,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);t=new Bt(i,this.transaction).getAmountInput().reduce((s,l)=>s+l,0)}if(this.helperStake.moveCall&&t===0){let i=this.helperStake.getNestedInputParam(2);t=new Bt(i,this.transaction).getAmountInput().reduce((s,l)=>s+l,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.TransactionType.Other,type:"StakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeUnstakeSpool(){let e=this.helperUnstake.decodeOwnedObjectId(1),t=this.helperUnstake.decodeInputU64(2),n=this.helperUnstake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Ot.TransactionType.Other,type:"UnstakeSpool",intentionData:{amount:t,marketCoinName:o,stakeAccountId:e}}}decodeSupplyWithStakeSpool(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Bt(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Ot.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(o=>{let i=o.decodeOwnedObjectId(1),s=o.decodeInputU64(2);e.push({id:i,coin:s})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);n=new Bt(o,this.transaction).getAmountInput().reduce((i,s)=>i+s,0)}return{txType:Ot.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let i=o.decodeOwnedObjectId(2),s=o.typeArg(0),l=this.utils.parseCoinNameFromType(s);e.push({stakeMarketCoinName:l,stakeAccountId:i})}),this.helperClaimBorrowV2Reward.forEach(o=>{let i=o.decodeSharedObjectId(4),s=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:s,obligationKey:i,rewardCoinName:l})}),this.helperClaimBorrowReward.forEach(o=>{let i=o.decodeSharedObjectId(2),s=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:s,obligationKey:i,rewardCoinName:l})}),{txType:Ot.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};var Pa=require("@msafe/sui3-utils");var Ra=class extends Se{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new W(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new W(e,this.transaction)}decodeCreateReferralLink(){return{txType:Pa.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Pa.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Pa.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};var te=require("@msafe/sui3-utils"),ju=require("@scallop-io/sui-scallop-sdk");var Ba=class extends Se{async decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMergeVeSca())return this.decodeMergeVesca();if(this.isSplitVeSca())return this.decodeSplitVesca();if(this.isVeScaObligationBindings())return this.decodeVeScaObligationBindings();if(await this.isTransferVeScaKey())return this.decodeTransferVeScaKey()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}isMergeVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::merge`)}isSplitVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::split`)}isVeScaObligationBindings(){let e=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),n=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`)),o=e.length>0&&t.length>0&&e.length===t.length,i=n.length>0;return this.commands.length===e.length+t.length+n.length&&(o||i)}async isTransferVeScaKey(){let e=this.commands.filter(d=>d.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,n=t.filter(d=>d.$kind==="Input").map(({Input:d})=>d);if(n.length!==t.length)return!1;let o=new Set(n),i=this.inputs.filter((d,S)=>d.$kind==="Object"&&o.has(S)).map(d=>d.Object.ImmOrOwnedObject),s=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,l=Lu(i.map(({objectId:d})=>d),50);for(let d=0;d<l.length;d++){let S=l[d];if((await this.scallopClient.scallopSuiKit.queryGetObjects(S,{showType:!0})).some(I=>I.type!==s))return!1}return i.length>0}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new W(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new W(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new W(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new W(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new W(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${ju.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`));return new W(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new W(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(n=>this.filterMoveCallCommands(n,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new W(t,this.transaction)}getVeScaObligationBindingHelpers(){let e=`${this.coreId.borrowIncentivePkg}::user::unstake_v2`,t=`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`,n=`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`,o=[],i=0,s=0,l=0;return this.commands.forEach(d=>{this.filterMoveCallCommands(d,e)?(o.push({action:"unstake",helper:new W(d,this.transaction,i)}),i++):this.filterMoveCallCommands(d,t)?(o.push({action:"stake",helper:new W(d,this.transaction,s)}),s++):this.filterMoveCallCommands(d,n)&&(o.push({action:"deactivate",helper:new W(d,this.transaction,l)}),l++)}),o}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:te.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new Bt(e,this.transaction).getAmountInput().reduce((D,R)=>D+R,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),i=!!this.helperRedeemSca.moveCall,s=[],l=[],d=[];this.helperOldUnstakeObligation.moveCall&&(s=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(l=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(d=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let S=!1,w=!1,I,C,x=[{condition:s,isOld:!0},{condition:l,isOld:!1},{condition:d,isOld:!1}];for(let D=0;D<x.length;D++)x[D].condition.length>1&&([C,I]=x[D].condition,S=!0,w=x[D].isOld);return{txType:te.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:I,obligationKey:C,veScaKey:o,isHaveRedeem:i,isObligationLocked:S,isOldBorrowIncentive:w}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],i=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(o=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(i=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let s=!1,l=!1,d,S,w=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:i,isOld:!1}];for(let I=0;I<w.length;I++)w[I].condition.length>1&&([S,d]=w[I].condition,s=!0,l=w[I].isOld);return{txType:te.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:d,obligationKey:S,veScaKey:t,isObligationLocked:s,isOldBorrowIncentive:l}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new Bt(e,this.transaction).getAmountInput().reduce((x,D)=>x+D,0),o=[],i=[],s,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(s=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:te.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:s,unlockTime:t,obligationId:w,obligationKey:I,isOldBorrowIncentive:S,isObligationLocked:d}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let n=new Bt(e,this.transaction).getAmountInput().reduce((x,D)=>x+D,0),o=[],i=[],s,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(s=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:te.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:w,obligationKey:I,veScaKey:s,isObligationLocked:d,isOldBorrowIncentive:S}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:te.TransactionType.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:te.TransactionType.Other,type:"SplitVeSca",intentionData:t}}decodeVeScaObligationBindings(){let e=this.getVeScaObligationBindingHelpers(),t=(o,i)=>{switch(o){case"stake":return{veScaKey:i.decodeOwnedObjectId(9),obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"unstake":return{obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"deactivate":return{veScaKey:i.decodeOwnedObjectId(4),obligationId:i.decodeSharedObjectId(3)};default:throw new Error(`Invalid action ${o}`)}},n=e.map(({action:o,helper:i})=>({action:o,args:t(o,i)}));return{txType:te.TransactionType.Other,type:"VeScaObligationBindings",intentionData:{bindingDatas:n}}}decodeTransferVeScaKey(){let e=this.commands.filter(s=>s.$kind==="TransferObjects"),{objects:t}=e[0].TransferObjects,n=t.filter(s=>s.$kind==="Input").map(({Input:s})=>s);if(n.length!==t.length)return!1;let o=new Set(n),i=this.inputs.filter((s,l)=>s.$kind==="Object"&&o.has(l)).map(s=>s.Object.ImmOrOwnedObject);return{xType:te.TransactionType.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:i}}}};var Uu=jt(require("sort-keys-recursive")),A=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Uu.default)(this.data))}isObligationLocked=async(e,t)=>{let n=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),o=!1;return n&&n?.data.content?.dataType==="moveObject"&&"lock_key"in n.data.content.fields&&(o=!!n.data.content.fields.lock_key),o};async buildTxWithRefreshObligation(e,t,n){let o=e.builder.createTxBlock();o.setSender(t.walletAddress);let{obligationId:i,obligationKey:s}=t;return await this.isObligationLocked(e.scallopSuiKit.client,i)?(await o.unstakeObligationQuick(i,s),await n(e,o,t),await o.stakeObligationWithVeScaQuick(i,s,t.veScaKey)):await n(e,o,t),o}};var Ea=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:i,obligationId:s,obligationKey:l}=this.data,d=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:d,obligationId:s,obligationKey:l},async(w,I)=>{let C=await I.borrowQuick(+i,o,s,l);I.transferObjects([C],d)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var Na=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,n){let{obligationId:o,obligationKey:i,veScaKey:s,amount:l,coinName:d}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:n,obligationId:o,obligationKey:i,veScaKey:s},async(w,I)=>{let C=await I.borrowQuick(+l,d,o,i);I.transferObjects([C],n)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new a(t)}};var Wa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:i,obligationKey:s,veScaKey:l,coinName:d,amount:S}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:i,obligationKey:s,veScaKey:l},async(I,C)=>{let x=C.claimReferralTicket(d),D=await C.borrowWithReferralQuick(+S,d,x,i,s);C.burnReferralTicket(x,d),C.transferObjects([D],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};var qu=require("@mysten/sui/utils");var _a=class a extends A{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let n=e.builder.createTxBlock();n.setSender(t);let o=await e.query.getAllStakeAccounts(t),i=await e.query.getLendings(void 0,t),s=await e.query.getObligations(t),l=Object.values(await e.query.getObligationAccounts(t)??[]),d=(()=>{let C=[...e.constants.whitelist.spool].map(x=>e.utils.parseCoinName(x));return Object.values(i??[]).filter(x=>!!x&&C.includes(x.coinName)).reduce((x,D)=>{let R=e.utils.parseMarketCoinName(D.coinName);return x[R]||(x[R]=0),x[R]+=D.availableClaimCoin,x},{})})(),S={};Object.entries(o).forEach(([C,x])=>{for(let D=0;D<x.length;D++){let R=x[D];if(!d[C])continue;let K=n.claim(R.id,C);S.sui?S.sui.push(K):S.sui=[K]}});let w=(()=>{let C={};return C.sui=Object.values(d).reduce((x,D)=>x+D,0),l.forEach(x=>{Object.values(x.borrowIncentives).forEach(D=>{D&&D.rewards.forEach(R=>{C[R.coinName]||(C[R.coinName]=0),C[R.coinName]?C[R.coinName]+=R.availableClaimCoin:C[R.coinName]=R.availableClaimCoin})})}),C})();if(s.length>0&&l.length>0)for(let C=0;C<l.length;C++){let x=l[C],D=!1,R=s.find(V=>V.id===x.obligationId)?.keyId,K={};if(R){if(Object.values(x.borrowIncentives).forEach(V=>{if(V){let Ht=V.rewards.filter(Et=>{let Pt=Et.coinName;return Et.availableClaimCoin>0&&!K[Pt]});D=Ht.length>0,Ht.forEach(Et=>{let Pt=n.claimBorrowIncentive(x.obligationId,R,Et.coinName);K[Et.coinName]=!0,S[Et.coinName]?S[Et.coinName].push(Pt):S[Et.coinName]=[Pt]})}}),w.sui>0){let V=Vt.redeem_rewards(n,R,x.obligationId,qu.SUI_TYPE_ARG);S.sui?S.sui.push(V):S.sui=[V]}if(D&&await _u(e.query,x.obligationId)){n.unstakeObligation(x.obligationId,R);let Ht=await e.query.getBindedVeScaKey(x.obligationId);Ht?n.stakeObligationWithVesca(x.obligationId,R,Ht):n.stakeObligation(x.obligationId,R)}}}let I=(await Promise.all(Object.entries(S).map(async([C,x])=>{let D=x[0];if(x.length>1&&n.mergeCoins(D,x.slice(1)),C==="sui"){n.mergeCoins(n.gas,[D]);return}return await e.builder.utils.mergeSimilarCoins(n,D,e.utils.parseCoinType(C),t),D}))).filter(C=>!!C);return I.length>0&&n.transferObjects(I,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var La=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var ja=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:i,obligationId:s,rewardCoinName:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=Vt.redeem_rewards(S,i,s,n.utils.parseCoinType(l));return S.transferObjects([w],o),await S.unstakeObligationQuick(s,i),d?await S.stakeObligationWithVeScaQuick(s,i,d):await S.stakeObligationQuick(s,i),S.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var Ua=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var qa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var Fa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:s,obligationId:l,obligationKey:d}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:l,obligationKey:d},async(w,I)=>{await I.repayQuick(+s,i,l)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var Ka=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:s,obligationId:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=n.constants.whitelist.borrowing.has(i);return w&&await S.unstakeObligationQuick(l,void 0),await S.repayQuick(+s,i,l),w&&await S.stakeObligationWithVeScaQuick(l,void 0,d),S.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var Va=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var $a=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var Ha=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,n,o){let i=t.builder.createTxBlock();i.setSender(o);let{stakeAccountId:s,amount:l,coinName:d}=this.data,S=[];for(let w=0;w<s.length;w++){let{id:I,coin:C}=s[w],x=t.utils.parseMarketCoinName(d),[D]=await i.unstakeQuick(C,x,I);if(D){let R=i.withdraw(D,d);S.push(R)}}if(l>0){let w=await i.withdrawQuick(l,d);S.push(w)}return S.length>1&&i.mergeCoins(S[0],S.slice(1)),i.transferObjects(S,o),i.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var Xa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new a(t)}};var Ga=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var Qa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();return i.setSender(o),i.bindToReferral(this.data.veScaKey),i.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new a(t)}};var za=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:i}=this.data,s=t.address,l=n.builder.createTxBlock();l.setSender(s);let d=i.map(S=>n.utils.parseCoinNameFromType(S));return await l.claimReferralRevenueQuick(o,d),l.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var Ja=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let o=t.address,i=n.builder.createTxBlock();i.setSender(o);let s=i.mintEmptyVeSca();return i.transferObjects([s],o),i.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new a(t)}};var Fu=require("@scallop-io/sui-scallop-sdk");var Ya=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:i,unlockTime:s,obligationId:l,obligationKey:d,isOldBorrowIncentive:S,isObligationLocked:w}=this.data,I=t.address,C=n.builder.createTxBlock();C.setSender(I);let x=await n.utils.selectCoins(o,Fu.SCA_COIN_TYPE,I),[D,R]=C.takeAmountFromCoins(x,o);return C.extendLockPeriod(i,s),C.extendLockAmount(i,D),C.transferObjects([R],I),!l||!d||(w&&(S?Vt.unstakeObligation(C,l,d):C.unstakeObligation(l,d)),C.stakeObligationWithVesca(l,d,i)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var Za=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:i,unlockTime:s,obligationId:l,obligationKey:d,isObligationLocked:S,isOldBorrowIncentive:w}=this.data,I=n.builder.createTxBlock();return I.setSender(o),I.extendLockPeriod(i,s),l&&d&&(S&&(w?Vt.unstakeObligation(I,d,l):I.unstakeObligation(l,d)),I.stakeObligationWithVesca(l,d,i)),I.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var ti=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,sourceVeScaKey:s}=this.data,[l,d]=await Promise.all([n.getBindedObligationId(i),n.getBindedObligationId(s)]);l&&await t.unstakeObligationQuick(l),d&&await t.unstakeObligationQuick(d),o(t,i,s),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i),d&&await t.stakeObligationWithVeScaQuick(d,void 0,s)}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();return i.setSender(o),await this.handleUnsubForKeys(i,n.query,async(s,l,d)=>{s.mergeVeSca(i.object(l),i.object(d))}),i.txBlock}static fromData(t){return new a(t)}};var ei=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:o}=this.data,i=t.address,s=n.builder.createTxBlock();return s.setSender(i),await s.redeemScaQuick(o),s.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};var Ku=require("@scallop-io/sui-scallop-sdk");var ni=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,unlockTime:s,veScaKey:l,isHaveRedeem:d,obligation:S,obligationKey:w,isObligationLocked:I,isOldBorrowIncentive:C}=this.data,x=n.builder.createTxBlock();if(x.setSender(o),d){let V=x.redeemSca(l);x.transferObjects([V],o)}let D=await n.builder.utils.selectCoins(i,Ku.SCA_COIN_TYPE,o),[R,K]=x.takeAmountFromCoins(D,i);return x.transferObjects([K],o),x.renewExpiredVeSca(l,R,s),!S||!w||(I&&(C?Vt.unstakeObligation(x,w,S):x.unstakeObligation(S,w)),x.stakeObligationWithVesca(S,w,l)),x.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};var oi=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,splitAmount:s}=this.data,l=await n.getBindedObligationId(i);l&&await t.unstakeObligationQuick(l),o(t,i,s.toString()),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i)}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();return i.setSender(o),await this.handleUnsubForKeys(i,n.query,(s,l,d)=>{let S=s.splitVeSca(l,d.toString());s.transferObjects([S],o)}),i.txBlock}static fromData(t){return new a(t)}};var Vu=require("@scallop-io/sui-scallop-sdk");var ai=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,isObligationLocked:s,isOldBorrowIncentive:l,obligationId:d,obligationKey:S,unlockTime:w,veScaKey:I}=this.data,C=n.builder.createTxBlock();C.setSender(o);let x=await n.utils.selectCoins(i,Vu.SCA_COIN_TYPE,o),[D,R]=C.takeAmountFromCoins(x,i),K;return I?C.extendLockAmount(I,D):K=C.lockSca(D,w),d&&S&&(s&&(l?Vt.unstakeObligation(C,S,d):C.unstakeObligation(d,S)),C.stakeObligationWithVesca(d,S,I||K)),I||C.transferObjects([K,R],o),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var ii=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:i,coinName:s,stakeAccountId:l}=this.data,d=n.builder.createTxBlock();d.setSender(o);let S=await d.depositQuick(+i,s),w=n.utils.parseMarketCoinName(s);if(n.constants.whitelist.spool.has(w))return d.txBlock;let I=await n.query.getStakeAccounts(w,o),C=l||(I.length>0?I[0].id:void 0);if(C)await d.stakeQuick(S,w,C);else{let x=d.createStakeAccount(w);await d.stakeQuick(S,w,x),d.transferObjects([x],o)}return d.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var ri=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;handleAction(t,{action:n,args:o}){switch(n){case"deactivate":return t.deactivateBoost(o.obligationId,o.veScaKey);case"stake":return t.stakeObligationWithVesca(o.obligationId,o.obligationKey,o.veScaKey);case"unstake":return t.unstakeObligation(o.obligationId,o.obligationKey);default:throw new Error("Invalid action")}}async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();i.setSender(o);let{bindingDatas:s}=this.data;return s.forEach(l=>this.handleAction(i,l)),i.txBlock}static fromData(t){return new a(t)}};var si=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{scallopClient:n,account:{address:o}}=t,i=n.builder.createTxBlock();i.setSender(o);let{veScaKeys:s}=this.data;return i.transferObjects(s.map(l=>i.objectRef(l)),i.pure.address(o)),i.txBlock}static fromData(t){return new a(t)}};var ci=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:o}=this.data,i=t.address,s=n.builder.createTxBlock();return s.setSender(i),await s.redeemScaQuick(o),s.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var li=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let n=new Xu.Scallop({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e,suiClients:[t],fullnodeUrls:[t.transport.rpcClient.requestManager.transports[0]?.uri??(0,Hu.getFullnodeUrl)("mainnet")]});this.scallopClient=await n.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;await this.initScallopClient(o.address,n),console.log("transaction",t);let i=new Ma(t,this.scallopClient),s=new Ra(t,this.scallopClient),l=new Ba(t,this.scallopClient),d=i.decode()||s.decode()||await l.decode();if(!d)throw new Error("Unknown transaction type");return{txType:$u.TransactionType.Other,txSubType:d.type,intentionData:d.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:i,intentionData:s}=e;await this.initScallopClient(n.address,t);let l;switch(i){case"SupplyLending":l=Va.fromData(s);break;case"WithdrawLending":l=Ga.fromData(s);break;case"Borrow":l=Ea.fromData(s);break;case"Repay":l=Fa.fromData(s);break;case"DepositCollateral":l=La.fromData(s);break;case"WithdrawCollateral":l=Xa.fromData(s);break;case"OpenObligation":l=qa.fromData(s);break;case"UnstakeSpool":l=$a.fromData(s);break;case"ClaimIncentiveReward":l=_a.fromData(s);break;case"BorrowWithBoost":l=Na.fromData(s);break;case"StakeSca":l=ai.fromData(s);break;case"ExtendStakePeriod":l=Za.fromData(s);break;case"ExtendPeriodAndStakeMore":l=Ya.fromData(s);break;case"RenewExpStakePeriod":l=ni.fromData(s);break;case"WithdrawStakedSca":l=ci.fromData(s);break;case"SupplyAndStakeLending":l=ii.fromData(s);break;case"WithdrawAndUnstakeLending":l=Ha.fromData(s);break;case"RedeemSca":l=ei.fromData(s);break;case"MigrateAndClaim":l=ja.fromData(s);break;case"BorrowWithReferral":l=Wa.fromData(s);break;case"CreateReferralLink":l=Ja.fromData(s);break;case"ClaimRevenueReferral":l=za.fromData(s);break;case"BindReferral":l=Qa.fromData(s);break;case"MigrateScoin":l=Ua.fromData(s);break;case"RepayWithBoost":l=Ka.fromData(s);break;case"MergeVeSca":l=ti.fromData(s);break;case"SplitVeSca":l=oi.fromData(s);break;case"VeScaObligationBindings":{l=ri.fromData(s);break}case"TransferVeScaKeys":{l=si.fromData(s);break}default:throw new Error("not implemented")}return l.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};var hm=require("@msafe/sui3-utils");var an=require("@msafe/sui3-utils"),Ce=require("@mysten/sui/utils");var im=require("@suilend/sui-fe");var am=require("@msafe/sui3-utils"),Ie=require("@suilend/sdk");var We=require("@msafe/sui3-utils"),nn=require("@mysten/bcs"),en=require("@mysten/sui/utils"),_e=require("@suilend/sui-fe"),Ds=jt(require("bignumber.js"));var ui=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},t=(0,en.normalizeStructTag)(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:We.TransactionType.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(d=>d.type.includes("lending_market::RedeemEvent"))},n=(0,en.normalizeStructTag)(t.RedeemEvent.parsedJson.coin_type.name),o=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let i=e.withdraw_ctokens.MoveCall.arguments[4].Input,s=new Ds.default((0,nn.toHex)((0,nn.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),l=s===_e.MAX_U64.toString();return console.log("decodeWithdraw - isMax:",l,"inputIndex:",i,"inputValue:",s,"MAX_U64.toString():",_e.MAX_U64.toString()),l&&(o=_e.MAX_U64.toString()),{txType:We.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(d=>d.type.includes("lending_market::BorrowEvent"))},n=(0,en.normalizeStructTag)(t.BorrowEvent.parsedJson.coin_type.name),o=`${+t.BorrowEvent.parsedJson.liquidity_amount-+t.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",n,o);let i=e.borrow_request.MoveCall.arguments[4].Input,s=new Ds.default((0,nn.toHex)((0,nn.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),l=s===_e.MAX_U64.toString();return console.log("decodeBorrow - isMax:",l,"inputIndex:",i,"inputValue:",s,"MAX_U64.toString():",_e.MAX_U64.toString()),l&&(o=_e.MAX_U64.toString()),{txType:We.TransactionType.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},t=(0,en.normalizeStructTag)(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:We.TransactionType.Other,type:"repay",intentionData:{coinType:t,value:n}}}decodeClaim(){let e={ClaimReward:this.simResult.events.filter(n=>n.type.includes("lending_market::ClaimReward"))},t={};for(let n=0;n<e.ClaimReward.length;n++){let o=e.ClaimReward[n],i=(0,en.normalizeStructTag)(o.parsedJson.coin_type.name),s=o.parsedJson.liquidity_amount;t[i]=`${+(t[i]??"0")+ +s}`}return console.log("Decoder.decodeClaimRewards",t),{txType:We.TransactionType.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:We.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var Qu=require("@mysten/sui/transactions");var Gu=jt(require("sort-keys-recursive")),Wt=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,Gu.default)(this.data))}};var mi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;if(console.log("BorrowIntention.build",n,o,i,s,l),!s||!l)throw new Error("Obligation not found");let d=new Qu.Transaction;return await i.borrowAndSendToUser(o.address,s.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};var Zu=require("@mysten/sui/transactions");var zu=require("@mysten/sui/utils"),on=require("@suilend/sdk"),Ju=require("@suilend/sui-fe"),Yu=jt(require("bignumber.js")),Wd=(a,e)=>{let t={[on.Side.DEPOSIT]:[],[on.Side.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[on.Side.DEPOSIT,on.Side.BORROW].forEach(o=>{let i=o===on.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,s=e.userRewardManagers.find(l=>l.poolRewardManagerId===i.id);s&&(t[o]=i.poolRewards.map((l,d)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(d),rewardCoinType:(0,zu.normalizeStructTag)(l.coinType.name),side:o})).filter(l=>!(0,Ju.isSendPoints)(l.rewardCoinType)&&!!s.rewards[Number(l.rewardIndex)]&&new Yu.default(s.rewards[Number(l.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},pi=Wd;var di=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;if(console.log("ClaimIntention.build",n,o,i,s,l),!s||!l)throw new Error("Obligation not found");let d=new Zu.Transaction;return i.claimRewardsAndSendToUser(o.address,s.id,pi(i,l),d),d}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};var tm=require("@mysten/sui/transactions");var fi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;if(console.log("ClaimAndDepositIntention.build",n,o,i,s,l),!s||!l)throw new Error("Obligation not found");let d=new tm.Transaction;return i.claimRewardsAndDeposit(o.address,s.id,pi(i,l),d),d}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};var em=require("@mysten/sui/transactions");var hi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;console.log("DepositIntention.build",n,o,i,s,l);let d=new em.Transaction;return await i.depositIntoObligation(o.address,this.data.coinType,this.data.value,d,s?.id),d}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};var nm=require("@mysten/sui/transactions");var gi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;if(console.log("RepayIntention.build",n,o,i,s,l),!s||!l)throw new Error("Obligation not found");let d=new nm.Transaction;return await i.repayIntoObligation(o.address,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};var om=require("@mysten/sui/transactions");var yi=class a extends Wt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:l}=t;if(console.log("WithdrawIntention.build",n,o,i,s,l),!s||!l)throw new Error("Obligation not found");let d=new om.Transaction;return await i.withdrawAndSendToUser(o.address,s.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var bi=async(a,e)=>{let t=await Ie.SuilendClient.initialize(Ie.LENDING_MARKET_ID,Ie.LENDING_MARKET_TYPE,a),n=await Ie.SuilendClient.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(i=>Ie.SuilendClient.getObligation(i.obligationId,t.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:o}},Si=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await bi(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",i,"utils:",this.utils,"suiClient:",n);let l=new ui(t,i).decode();return{txType:am.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:s}=e;this.utils||(this.utils=await bi(i,s));let l;switch(n){case"deposit":l=hi.fromData(o);break;case"withdraw":l=yi.fromData(o);break;case"borrow":l=mi.fromData(o);break;case"repay":l=gi.fromData(o);break;case"claim":l=di.fromData(o);break;case"claimAndDeposit":l=fi.fromData(o);break;default:throw new Error("not implemented")}let d=window.localStorage.getItem("obligationId"),S=this.utils.obligations?.find(I=>I.id===d)??this.utils.obligations?.[0],w=this.utils.obligationOwnerCaps?.find(I=>I.obligationId===S?.id);return l.build({network:t,suiClient:i,account:s,suilendClient:this.utils.suilendClient,obligationOwnerCap:w,obligation:S})}};var vs=async(a,e)=>{let t=await bi(a,e),n=await fetch(`${im.API_URL}/springsui/lst-info`),o=await n.json();if(n?.statusCode===500)throw new Error("Failed to fetch SpringSui LST data");let s=Object.fromEntries(Object.values(o).map(l=>[l.LIQUID_STAKING_INFO.type,l.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:s}};var Ti=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:an.TransactionType.Other,type:"stake",intentionData:{amount:n,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:an.TransactionType.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:an.TransactionType.Other,type:"convert",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Ce.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:an.TransactionType.Other,type:"convertAndDeposit",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeUnstake(){let e={RedeemEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::RedeemEvent"))},t=(0,Ce.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:an.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};var sm=require("@mysten/sui/transactions"),Ln=require("@suilend/springsui-sdk");var rm=jt(require("sort-keys-recursive")),$t=class{constructor(e){this.data=e}serialize(){return JSON.stringify((0,rm.default)(this.data))}};var wi=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertIntention.build",n,o,i,s,l,d);let S=await Ln.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.inCoinType)),w=await Ln.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.outCoinType)),I=new sm.Transaction;return(0,Ln.convertLstsAndSendToUser)(S,w,I,o.address,this.data.amount),I}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};var cm=require("@mysten/sui/transactions"),Ci=require("@suilend/sdk"),jn=require("@suilend/springsui-sdk");var Ii=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertAndDepositIntention.build",n,o,i,s,l,d);let S=await jn.LstClient.initialize(n,Object.values(s).find(R=>R.type===this.data.inCoinType)),w=await jn.LstClient.initialize(n,Object.values(s).find(R=>R.type===this.data.outCoinType)),I=new cm.Transaction,{obligationOwnerCapId:C,didCreate:x}=(0,Ci.createObligationIfNoneExists)(i,I,l),D=(0,jn.convertLsts)(S,w,I,o.address,this.data.amount);return i.deposit(D,this.data.outCoinType,C,I),x&&(0,Ci.sendObligationToUser)(C,o.address,I),I}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};var lm=require("@mysten/sui/transactions"),um=require("@suilend/springsui-sdk");var ki=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:l,obligation:d}=t;console.log("StakeIntention.build",n,o,i,s,l,d);let S=await um.LstClient.initialize(n,Object.values(s).find(I=>I.type===this.data.outCoinType)),w=new lm.Transaction;return S.mintAmountAndRebalanceAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};var mm=require("@mysten/sui/transactions"),Di=require("@suilend/sdk"),pm=require("@suilend/springsui-sdk");var xi=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:l,obligation:d}=t;console.log("StakeAndDepositIntention.build",n,o,i,s,l,d);let S=await pm.LstClient.initialize(n,Object.values(s).find(D=>D.type===this.data.outCoinType)),w=new mm.Transaction,{obligationOwnerCapId:I,didCreate:C}=(0,Di.createObligationIfNoneExists)(i,w,l),x=S.mintAmountAndRebalance(w,o.address,this.data.amount);return i.deposit(x,this.data.outCoinType,I,w),C&&(0,Di.sendObligationToUser)(I,o.address,w),w}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};var dm=require("@mysten/sui/transactions"),fm=require("@suilend/springsui-sdk");var vi=class a extends $t{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:l,obligation:d}=t;console.log("UnstakeIntention.build",n,o,i,s,l,d);let S=await fm.LstClient.initialize(n,Object.values(s).find(I=>I.type===this.data.inCoinType)),w=new dm.Transaction;return S.redeemAmountAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Ai=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await vs(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",i);let l=new Ti(t,i).decode();return{txType:hm.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:s}=e;this.utils||(this.utils=await vs(i,s));let l;switch(n){case"stake":l=ki.fromData(o);break;case"stakeAndDeposit":l=xi.fromData(o);break;case"convert":l=wi.fromData(o);break;case"convertAndDeposit":l=Ii.fromData(o);break;case"unstake":l=vi.fromData(o);break;default:throw new Error("not implemented")}return l.build({network:t,suiClient:i,account:s,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};var bm=require("@msafe/sui3-utils");var As=require("@msafe/sui3-utils");var Oi=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:As.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:As.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var gm=require("@alphafi/stsui-sdk");var Mi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new gm.LST(i).mint(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};var ym=require("@alphafi/stsui-sdk");var Pi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new ym.LST(i).redeem(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var Ri=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n}=e,o=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",o);let s=new Oi(t,o).decode();return{txType:bm.TransactionType.Other,txSubType:s.type,intentionData:s.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let n;switch(e.txSubType){case"mint":n=Mi.fromData(e.intentionData);break;case"redeem":n=Pi.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};var Um=require("@msafe/sui3-utils"),qm=require("turbos-clmm-sdk");var _t=require("@msafe/sui3-utils"),Os=require("@mysten/sui.js/bcs"),xe=require("@mysten/sui.js/utils"),Sm=require("turbos-clmm-sdk");var Gt={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Qt={PackageId:"0xdee9"};var Ud=(a,e,t,n)=>{if(a===1)switch(n.findIndex(s=>s===e)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${e}`)}switch(t.findIndex(i=>i===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},Bi=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${Gt.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Gt.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(x=>x.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let n=Ud(t,e.target,this.swap1Layer,this.swap2Layer),o=n.map((x,D)=>{let R=this.helper.decodeSharedObjectId(D),K=this.helper.decodeInputU128(4+D+t),V=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Sm.BN(K.toString()));return{pool:R,a2b:x,nextTickIndex:V}}),i=n[0]||t===1?e.typeArguments[0]:e.typeArguments[1],s=t===1?e.typeArguments[4]:n[0]?e.typeArguments[1]:e.typeArguments[0],l=this.helper.decodeInputAddress(6+2*t),d=this.helper.decodeInputU64(7+2*t),S=this.helper.decodeInputBool(5+2*t),w=this.helper.decodeInputU64(2+t),I=this.helper.decodeInputU64(3+t),C=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:o[0].pool,a2b:o[0].a2b,amountSpecified:w}],address:l,amountSpecifiedIsInput:S});return{txType:_t.TransactionType.Other,type:"Swap",intentionData:{routes:o,coinTypeA:i,coinTypeB:s,address:l,amountA:S?w:I,amountB:S?I:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:d}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),s=this.helper.decodeInputBool(5),l=this.helper.decodeInputU32(6),d=this.helper.decodeInputBool(7),S=this.helper.decodeInputU64(13);return{txType:_t.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:n,amountB:o,tickLower:s?-i:i,tickUpper:d?-l:l,deadline:S}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),i=this.helper.decodeInputU64(6),s=this.helper.decodeInputU64(9);return{txType:_t.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:o,amountB:i,nft:n,deadline:s}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),s=this.helper.decodeInputU64(5),l=this.helper.decodeInputU64(6);return{txType:_t.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:s,slippage:10,address:e,deadline:l}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),s=this.helper.decodeInputU64(6);return{txType:_t.TransactionType.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:o,collectAmountB:i,nft:t,deadline:s}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(s=>s.decodeInputU64(5)),i=this.helper.decodeInputU64(7);return{txType:_t.TransactionType.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:o,nft:t,deadline:i}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:_t.TransactionType.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),i=this.decreaseLiquidityHelper.decodeInputU64(4),s=this.decreaseLiquidityHelper.decodeInputU64(5),l=this.decreaseLiquidityHelper.decodeInputU64(6),d=this.collectRewardHelper.map(I=>I.decodeInputU64(5)),S=this.collectFeeHelper.decodeInputU64(3)||0,w=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:_t.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:s,slippage:10,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:d,deadline:l}}}decodePrixClaim(){return{txType:_t.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:_t.TransactionType.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let e=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),t=this.swapExactBaseForQuoteHelper.decodeInputU64(3),n=this.swapExactBaseForQuoteHelper.shortTypeArg(0),o=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:_t.TransactionType.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}decodeSwapExactQuoteForBase(){let e=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),t=this.swapExactQuoteForBaseHelper.decodeInputU64(3),n=this.swapExactQuoteForBaseHelper.shortTypeArg(0),o=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:_t.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new ke(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new ke(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new ke(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new ke(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`);return new ke(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`);return new ke(e,this.txb)}},ke=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,xe.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Os.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,xe.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,xe.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,xe.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,xe.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Os.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,xe.normalizeStructTag)(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};var Tm=require("turbos-clmm-sdk");var Ei=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Tm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:l,slippage:d,tickLower:S,tickUpper:w,deadline:I,txb:C}=this.data;return n.pool.addLiquidity({pool:o,slippage:d,address:i,amountA:s,amountB:l,tickLower:S,tickUpper:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};var wm=require("turbos-clmm-sdk");var Ni=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new wm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,nft:i,txb:s}=this.data;return n.nft.burn({pool:o,nft:i,txb:s})}static fromData(t){return new a(t)}};var Im=require("turbos-clmm-sdk");var Wi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Im.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:s,collectAmountA:l,collectAmountB:d,deadline:S,txb:w}=this.data;return n.pool.collectFee({pool:o,address:i,collectAmountA:l,collectAmountB:d,nft:s,deadline:S,txb:w})}static fromData(t){return new a(t)}};var Cm=require("turbos-clmm-sdk");var _i=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Cm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:s,rewardAmounts:l,deadline:d,txb:S}=this.data;return n.pool.collectReward({pool:o,address:i,rewardAmounts:l,nft:s,deadline:d,txb:S})}static fromData(t){return new a(t)}};var km=require("turbos-clmm-sdk");var Li=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new km.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{fee:o,address:i,tickLower:s,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,amountA:C,amountB:x,deadline:D,txb:R}=this.data;return n.pool.createPool({fee:o,amountA:C,amountB:x,address:i,tickLower:s,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,deadline:D,txb:R})}static fromData(t){return new a(t)}};var xm=require("turbos-clmm-sdk");var ji=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new xm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:l,slippage:d,nft:S,decreaseLiquidity:w,deadline:I,txb:C}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:d,address:i,amountA:s,amountB:l,nft:S,decreaseLiquidity:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};var Dm=require("turbos-clmm-sdk");var Ui=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Dm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:l,slippage:d,nft:S,deadline:w,txb:I}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:d,address:i,amountA:s,amountB:l,nft:S,deadline:w,txb:I})}static fromData(t){return new a(t)}};var vm=require("@mysten/sui.js/transactions"),Am=require("@mysten/sui.js/utils");var qi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new vm.TransactionBlock;return n.moveCall({target:`${Gt.PackageId}::claim::claim`,typeArguments:[Gt.turbosCoinType],arguments:[n.object(Gt.Claim),n.object(Am.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(t){return new a(t)}};var Om=require("@mysten/sui.js/transactions");var Fi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Om.TransactionBlock;return n.moveCall({target:`${Gt.PackageId}::claim::join`,typeArguments:[Gt.turbosCoinType],arguments:[n.object(Gt.Claim)]}),n}static fromData(t){return new a(t)}};var Mm=require("@mysten/sui.js/transactions"),Pm=require("turbos-clmm-sdk");var Ki=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Pm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),o=new Mm.TransactionBlock;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(t){return new a(t)}};var Rm=require("turbos-clmm-sdk");var Vi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new Rm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{routes:o,coinTypeA:i,coinTypeB:s,address:l,amountA:d,amountB:S,slippage:w,amountSpecifiedIsInput:I,deadline:C,txb:x}=this.data;return n.trade.swap({routes:o,coinTypeA:i,coinTypeB:s,address:l,amountA:d,amountB:S,amountSpecifiedIsInput:I,slippage:w,deadline:C,txb:x})}static fromData(t){return new a(t)}};var Lm=require("turbos-clmm-sdk");var Ms=require("@mysten/sui.js/transactions"),Ps=require("@mysten/sui.js/utils");var Bm=require("turbos-clmm-sdk");var Un=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,n){let o=[],i;do i=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:i?.nextCursor}),o.push(...i.data);while(i.hasNextPage);let s=[],l=0;return o.sort((d,S)=>Number(S.balance)-Number(d.balance)).some(d=>l>=n?!0:(l+=Number(d.balance),s.push(d),!1)),s}splitAndMergeCoin(e,t,n){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[s]=n.splitCoins(n.gas,[n.pure(t)]);return[s,void 0]}let o=n.object(e[0].coinObjectId);e.length>1&&n.mergeCoins(o,e.slice(1).map(s=>n.object(s.coinObjectId)));let[i]=n.splitCoins(o,[n.pure(t)]);return[i,o]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${Qt.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?(0,Bm.unstable_getObjectId)(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Qt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var Em=89,Nm=1e6,Wm=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:s}=a,l=new Ms.TransactionBlock,d=new Un(s),S=await d.getCoinsData(i,t,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${t}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),[D,R,K]=l.moveCall({typeArguments:[e,t],target:`${Qt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[l.object(String(n)),l.pure(Em),x,l.pure(o),l.object((0,Ps.normalizeSuiObjectId)("0x6")),w]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([D],l.pure(i)),l.transferObjects([R],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(Nm),l},_m=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:s}=a,l=new Ms.TransactionBlock,d=new Un(s),S=await d.getCoinsData(i,e,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${e}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),D=d.zero(t,l),[R,K,V]=l.moveCall({typeArguments:[e,t],target:`${Qt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[l.object(String(n)),l.pure(Em),x,l.pure(o),w,D,l.object((0,Ps.normalizeSuiObjectId)("0x6"))]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([R],l.pure(i)),l.transferObjects([K],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(Nm),l};var $i=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Lm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await _m({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var jm=require("turbos-clmm-sdk");var Hi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new jm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await Wm({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var Xi=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new qm.TurbosSdk(e.network.replace("sui:",""),e.suiClient),n=await t.contract.getConfig(),{transactionBlock:o,account:i}=e;console.log(e,"input");let l=await new Bi(o,t,n).decode(i.address);return{txType:Um.TransactionType.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,i;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":i=Li.fromData(e.intentionData);break;case"AddLiquidity":i=Ei.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Ui.fromData(e.intentionData);break;case"DecreaseLiquidity":i=ji.fromData(e.intentionData);break;case"RemoveLiquidity":i=Ki.fromData(e.intentionData);break;case"CollectFee":i=Wi.fromData(e.intentionData);break;case"CollectReward":i=_i.fromData(e.intentionData);break;case"Burn":i=Ni.fromData(e.intentionData);break;case"Swap":i=Vi.fromData(e.intentionData);break;case"PrixJoin":i=Fi.fromData(e.intentionData);break;case"PrixClaim":i=qi.fromData(e.intentionData);break;case"SwapExactBaseForQuote":i=$i.fromData(e.intentionData);break;case"SwapExactQuoteForBase":i=Hi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var $m=require("@msafe/sui3-utils");var Gi=require("@msafe/sui3-utils"),Rs=require("@mysten/sui.js/bcs"),De=require("@mysten/sui.js/utils");var qd={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},vt=qd;var Qi=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${vt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${vt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${vt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:Gi.TransactionType.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Gi.TransactionType.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:Gi.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(vt.packageId));return new Bs(e,this.txb)}},Bs=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,De.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Rs.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,De.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,De.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,De.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,De.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Rs.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,De.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Fm=require("@mysten/sui.js/transactions");var zi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Fm.TransactionBlock,{ticketId:o}=this.data;return n.moveCall({target:`${vt.packageId}::native_pool::burn_ticket`,arguments:[n.object(vt.poolObjectId),n.object(vt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new a(t)}};var Km=require("@mysten/sui.js/transactions");var Ji=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Km.TransactionBlock,{amount:o}=this.data,[i]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${vt.packageId}::native_pool::stake`,arguments:[n.object(vt.poolObjectId),n.object(vt.metadataObjectId),n.object(vt.systemStateObjectId),i]}),n}static fromData(t){return new a(t)}};var Vm=require("@mysten/sui.js/transactions");var Yi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Vm.TransactionBlock,{amount:o}=this.data,i=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[s,...l]=i.filter(w=>w.coinType.split("::")[0]===vt.certType.split("::")[0]),d=n.object(s.coinObjectId);l.length&&n.mergeCoins(d,l.map(w=>n.object(w.coinObjectId)));let S=n.splitCoins(n.object(s.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${vt.packageId}::native_pool::unstake`,arguments:[n.object(vt.poolObjectId),n.object(vt.metadataObjectId),n.object(vt.systemStateObjectId),S]}),n}static fromData(t){return new a(t)}};var Zi=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,o=new Qi(t).decode();return{txType:$m.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case"Stake":o=Ji.fromData(e.intentionData);break;case"UnStake":o=Yi.fromData(e.intentionData);break;case"ClaimTicket":o=zi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var np=require("@msafe/sui3-utils");var Es=require("@cetusprotocol/common-sdk"),ve=require("@msafe/sui3-utils"),rn=require("@mysten/bcs"),sn=require("@mysten/sui/bcs");var tr=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ve.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number((0,Es.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,Es.asIntN)(BigInt(this.getU32(this.getInputIndex(e,3)))).toString()),tokenAmount:this.getU64(this.getInputIndex(t,6)),maxAmountTokenA:this.getU64(this.getInputIndex(t,7)),maxAmountTokenB:this.getU64(this.getInputIndex(t,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(t,9))}}}decodeClosePositionTx(){let e=this.getMoveCallCommand("close_position"),t=this.getCollectRewardCallData();return{txType:ve.TransactionType.Other,type:"ClosePosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),transferTokensTo:this.getAddress(this.getInputIndex(e,4)),collectRewardTokens:t.map(n=>n.rewardCoinType),collectFeeTokens:this.getTypeArguments(e)}}}decodeProvideLiquidityTx(){let e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ve.TransactionType.Other,type:"ProvideLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),tokenAmount:this.getU64(this.getInputIndex(e,6)),maxAmountTokenA:this.getU64(this.getInputIndex(e,7)),maxAmountTokenB:this.getU64(this.getInputIndex(e,8)),isTokenAFixed:this.getBoolean(this.getInputIndex(e,9))}}}decodeRemoveLiquidityTx(){let e=this.getMoveCallCommand("remove_liquidity");return{txType:ve.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),liquidity:this.getU128(this.getInputIndex(e,4)),maxAmountTokenA:this.getU64(this.getInputIndex(e,5)),maxAmountTokenB:this.getU64(this.getInputIndex(e,6)),transferTokensTo:this.getAddress(this.getInputIndex(e,7)),...this.collectTokens()}}}decodeCollectRewardsTx(){let e=this.getCollectRewardCallData();return{txType:ve.TransactionType.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:ve.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:ve.TransactionType.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(n=>n.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(sn.bcs.u32().parse(Uint8Array.from((0,rn.fromBase64)(this.inputs[e].Pure.bytes))))}getU64(e){return sn.bcs.u64().parse(Uint8Array.from((0,rn.fromBase64)(this.inputs[e].Pure.bytes)))}getU128(e){return sn.bcs.u128().parse(Uint8Array.from((0,rn.fromBase64)(this.inputs[e].Pure.bytes)))}getBoolean(e){return sn.bcs.bool().parse(Uint8Array.from((0,rn.fromBase64)(this.inputs[e].Pure.bytes)))}getAddress(e){return sn.bcs.Address.parse(Uint8Array.from((0,rn.fromBase64)(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};var Qm=require("@msafe/sui3-utils");var ee=require("@firefly-exchange/library-sui");var Xm=require("@firefly-exchange/library-sui"),Gm=require("@firefly-exchange/library-sui/dist/src/spot"),Hm={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},Oe=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Xm.SuiClient({url:Hm.rpc});return new Gm.OnChainCalls(t,Hm.objects,{address:e.address,isUIWallet:!1})};var Rt=class{static async OpenPosition(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool),s=this.prototype.buildLiqInput(i,{...e,slippage:0});return await o.openPositionWithFixedAmount(i,e.lowerTick,e.upperTick,s,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool),s=this.prototype.buildLiqInput(i,e);return await o.provideLiquidityWithFixedAmount(i,e.position,s,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(i,e.position,{liquidityAmount:new ee.BN(e.liquidity),tokenMaxA:new ee.BN(e.maxAmountTokenA),tokenMaxB:new ee.BN(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.closePosition(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectRewards(i,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return await o.collectFee(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let o=Oe(n,t),i=await o.queryChain.getPool(e.pool);return console.log(e.position),await o.collectFeeAndRewards(i,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...ee.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ee.BN(t.tokenAmount),t.isTokenAFixed,!0,0,new ee.BN(e.current_sqrt_price)),tokenMaxA:new ee.BN(t.maxAmountTokenA),tokenMaxB:new ee.BN(t.maxAmountTokenB)}}};var er=class a extends k{constructor(t){super(t);this.data=t}txType=Qm.TransactionType.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.closePosition(this.data,n,o)}static fromData(t){return new a(t)}};var zm=require("@msafe/sui3-utils");var nr=class a extends k{constructor(t){super(t);this.data=t}txType=zm.TransactionType.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectFee(this.data,n,o)}static fromData(t){return new a(t)}};var Jm=require("@msafe/sui3-utils");var or=class a extends k{constructor(t){super(t);this.data=t}txType=Jm.TransactionType.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectRewards(this.data,n,o)}static fromData(t){return new a(t)}};var Ym=require("@msafe/sui3-utils");var ar=class a extends k{constructor(t){super(t);this.data=t}txType=Ym.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new a(t)}};var Zm=require("@msafe/sui3-utils");var ir=class a extends k{constructor(t){super(t);this.data=t}txType=Zm.TransactionType.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.OpenPosition(this.data,n,o)}static fromData(t){return new a(t)}};var tp=require("@msafe/sui3-utils");var rr=class a extends k{constructor(t){super(t);this.data=t}txType=tp.TransactionType.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.provideLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var ep=require("@msafe/sui3-utils");var sr=class a extends k{constructor(t){super(t);this.data=t}txType=ep.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Rt.removeLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var cr=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,o=new tr(t).decode();return{txType:np.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let i;switch(e.txSubType){case"OpenPosition":i=ir.fromData(e.intentionData);break;case"ProvideLiquidity":i=rr.fromData(e.intentionData);break;case"RemoveLiquidity":i=sr.fromData(e.intentionData);break;case"ClosePosition":i=er.fromData(e.intentionData);break;case"CollectFee":i=nr.fromData(e.intentionData);break;case"CollectRewards":i=or.fromData(e.intentionData);break;case"CollectRewardsAndFee":i=ar.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Ep=require("@msafe/sui3-utils");var dp=require("@mmt-finance/clmm-sdk"),fp=require("@mysten/sui/transactions");var Le=require("@mmt-finance/clmm-sdk/dist/utils/math/tickMath"),B=jt(ap());var Kd="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",cn=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Vd=async({suiClient:a,address:e,type:t})=>{let n,o=[],i=0;do{try{let s=await a.getCoins({owner:e,coinType:t,cursor:n,limit:50});o=o.concat(s.data),n=s.nextCursor,(!s.hasNextPage||i===8)&&(n=null)}catch(s){console.log(s),n=null}i++}while(n!==null);return o},$d=(a,e)=>{let t=[],n=BigInt(0);for(let o of e)n<a&&!t.includes(o.objectId)&&(t.push(o.objectId),n+=BigInt(o.balance)),o.balance===BigInt(0)&&!t.includes(o.objectId)&&t.push(o.objectId);if(n>=a)return t;throw new Error("Insufficient balance")},Hd=(a,e,t,n)=>{if(a===Kd){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=$d(t,e);o.length>1&&n.mergeCoins(n.object(o[0]),o.slice(1).map(s=>n.object(s)));let[i]=n.splitCoins(n.object(o[0]),[n.pure.u64(t)]);return i}};async function ip(a,e,t,n,o){let i=await Vd({suiClient:a.rpcClient,address:e,type:t});return Hd(cn(t),i.map(l=>({balance:BigInt(l.balance),objectId:l.coinObjectId})),n,o)}function N(a,e,t){let n=a.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function Xd(a){let e;return a&1?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),a&2&&(e=N(e.mul(new B.default("79236085330515764027303304731")),96,256)),a&4&&(e=N(e.mul(new B.default("79244008939048815603706035061")),96,256)),a&8&&(e=N(e.mul(new B.default("79259858533276714757314932305")),96,256)),a&16&&(e=N(e.mul(new B.default("79291567232598584799939703904")),96,256)),a&32&&(e=N(e.mul(new B.default("79355022692464371645785046466")),96,256)),a&64&&(e=N(e.mul(new B.default("79482085999252804386437311141")),96,256)),a&128&&(e=N(e.mul(new B.default("79736823300114093921829183326")),96,256)),a&256&&(e=N(e.mul(new B.default("80248749790819932309965073892")),96,256)),a&512&&(e=N(e.mul(new B.default("81282483887344747381513967011")),96,256)),a&1024&&(e=N(e.mul(new B.default("83390072131320151908154831281")),96,256)),a&2048&&(e=N(e.mul(new B.default("87770609709833776024991924138")),96,256)),a&4096&&(e=N(e.mul(new B.default("97234110755111693312479820773")),96,256)),a&8192&&(e=N(e.mul(new B.default("119332217159966728226237229890")),96,256)),a&16384&&(e=N(e.mul(new B.default("179736315981702064433883588727")),96,256)),a&32768&&(e=N(e.mul(new B.default("407748233172238350107850275304")),96,256)),a&65536&&(e=N(e.mul(new B.default("2098478828474011932436660412517")),96,256)),a&131072&&(e=N(e.mul(new B.default("55581415166113811149459800483533")),96,256)),a&262144&&(e=N(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),N(e,32,256)}function Gd(a){let e=Math.abs(a),t;return e&1?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),e&2&&(t=N(t.mul(new B.default("18444899583751176498")),64,256)),e&4&&(t=N(t.mul(new B.default("18443055278223354162")),64,256)),e&8&&(t=N(t.mul(new B.default("18439367220385604838")),64,256)),e&16&&(t=N(t.mul(new B.default("18431993317065449817")),64,256)),e&32&&(t=N(t.mul(new B.default("18417254355718160513")),64,256)),e&64&&(t=N(t.mul(new B.default("18387811781193591352")),64,256)),e&128&&(t=N(t.mul(new B.default("18329067761203520168")),64,256)),e&256&&(t=N(t.mul(new B.default("18212142134806087854")),64,256)),e&512&&(t=N(t.mul(new B.default("17980523815641551639")),64,256)),e&1024&&(t=N(t.mul(new B.default("17526086738831147013")),64,256)),e&2048&&(t=N(t.mul(new B.default("16651378430235024244")),64,256)),e&4096&&(t=N(t.mul(new B.default("15030750278693429944")),64,256)),e&8192&&(t=N(t.mul(new B.default("12247334978882834399")),64,256)),e&16384&&(t=N(t.mul(new B.default("8131365268884726200")),64,256)),e&32768&&(t=N(t.mul(new B.default("3584323654723342297")),64,256)),e&65536&&(t=N(t.mul(new B.default("696457651847595233")),64,256)),e&131072&&(t=N(t.mul(new B.default("26294789957452057")),64,256)),e&262144&&(t=N(t.mul(new B.default("37481735321082")),64,256)),t}var rp=(a,e,t)=>{let n=(0,Le.convertI32ToSigned)(t?a+a%(e??1):a-a%(e??1));return n>0?new B.default(Xd(n)):new B.default(Gd(n))};function sp(a,e){if(!/^(\d+)(\.\d+)?$/.test(a))return BigInt(0);let[t,n=""]=a.split("."),o=(n+"0".repeat(e)).slice(0,e),s=(t+o).replace(/^0+/,"")||"0";return BigInt(s)}async function Me({address:a,coinType:e,coinAmount:t,coinDecimals:n,tx:o,mmt:i}){let s=sp(t,n),l;return Number(t)?l=await ip(i,a,cn(e),s,o):[l]=o.moveCall({target:"0x2::coin::zero",typeArguments:[e],arguments:[]}),l}function cp({mmt:a,tx:e,poolModel:t,selectedLowTick:n,selectedHighTick:o}){let i=rp((0,Le.convertI32ToSigned)(n),t.tickSpacing),s=rp((0,Le.convertI32ToSigned)(o),t.tickSpacing);return a.Position.openPosition(e,t,i.toString(),s.toString())}var Qd=(a,e)=>a*BigInt(100-e)/BigInt(100);function lr(a,e,t){let n=sp(a,e);return Number(a)===0?BigInt(0):Qd(n,t)}async function ur({poolId:a,currentSqrtPrice:e,tokenX:t,tokenY:n,slippagePercentage:o,isTokenX:i,suiClient:s}){let d=(await s.getObject({id:a,options:{showContent:!0}}))?.data?.content?.fields?.sqrt_price??e,S=Le.TickMath.sqrtPriceX64ToPrice(new B.default(d?.toString()),t.decimals,n.decimals),w=i?(100-o)/100:(100+o)/100,I=Le.TickMath.priceToSqrtPriceX64(S.mul(w),t.decimals,n.decimals);return BigInt(I.toString())}var lp=async(a,e,t,n,o,i,s,l,d,S)=>{let w=await Me({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:n,coinDecimals:i.tokenX.decimals,tx:e}),I=await Me({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:o,coinDecimals:i.tokenY.decimals,tx:e}),C={objectId:s,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing},x=cp({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),D=lr(n,i.tokenX.decimals,S),R=lr(o,i.tokenY.decimals,S);a.Pool.addLiquidity(e,C,x,w,I,D,R,t),e.transferObjects([x],e.pure.address(t))},up=async(a,e,t,n,o,i,s,l,d,S,w)=>{try{let I=await Me({mmt:a,address:n,coinType:i?s.tokenX.coinType:s.tokenY.coinType,coinAmount:o,coinDecimals:i?s.tokenX.decimals:s.tokenY.decimals,tx:e}),C={objectId:s.poolId,tokenXType:s.tokenX.coinType,tokenYType:s.tokenY.coinType,tickSpacing:s.tickSpacing},x=cp({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),D=await ur({suiClient:t,poolId:s.poolId,currentSqrtPrice:s.currentSqrtPrice,tokenX:s.tokenX,tokenY:s.tokenY,slippagePercentage:S,isTokenX:i});await a.Pool.addLiquiditySingleSidedV2({txb:e,pool:C,position:C.objectId,inputCoin:I,isXtoY:i,limitSqrtPrice:D,slippagePercentage:w,transferToAddress:n}),e.transferObjects([x],e.pure.address(n))}catch(I){console.error(I)}},mp=async(a,e,t,n,o,i,s,l)=>{let d=await Me({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:n,coinDecimals:i.tokenX.decimals,tx:e}),S=await Me({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:o,coinDecimals:i.tokenY.decimals,tx:e}),w={objectId:i.poolId,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing},I=lr(n,i.tokenX.decimals,l),C=lr(o,i.tokenY.decimals,l);a.Pool.addLiquidity(e,w,s,d,S,I,C,t)},pp=async(a,e,t,n,o,i,s,l,d,S)=>{try{let w=await Me({mmt:a,address:n,coinType:i?s.tokenX.coinType:s.tokenY.coinType,coinAmount:o,coinDecimals:i?s.tokenX.decimals:s.tokenY.decimals,tx:e}),I={objectId:s.poolId,tokenXType:s.tokenX.coinType,tokenYType:s.tokenY.coinType,tickSpacing:s.tickSpacing},C=await ur({suiClient:t,poolId:s.poolId,currentSqrtPrice:s.currentSqrtPrice,tokenX:s.tokenX,tokenY:s.tokenY,slippagePercentage:d,isTokenX:i});await a.Pool.addLiquiditySingleSidedV2({txb:e,pool:I,position:l,inputCoin:w,isXtoY:i,limitSqrtPrice:C,slippagePercentage:S,transferToAddress:n})}catch(w){throw console.error(w),w}};var mr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=dp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amountA:i,amountB:s,pool:l,selectedLowTick:d,selectedHighTick:S,slippage:w}=n,I=new fp.Transaction;return await lp(t,I,o,i,s,l,l.poolId,d,S,w),I}static fromData(t){return new a(t)}};var hp=require("@mmt-finance/clmm-sdk"),gp=require("@mysten/sui/transactions");var pr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=hp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amount:i,isTokenX:s,pool:l,selectedLowTick:d,selectedHighTick:S,swapSlippage:w,addLiquiditySlippage:I}=n,C=new gp.Transaction;return await up(t,C,t.rpcClient,o,i,s,l,d,S,w,I),C}static fromData(t){return new a(t)}};var yp=require("@mmt-finance/clmm-sdk"),bp=require("@mysten/sui/transactions");var ln=(a,e,t,n,o)=>{let i={objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType};n?.rewarders&&n?.rewarders.length>0&&a.Pool.collectAllRewards(o,i,n.rewarders.map(s=>({coin_type:s.coinType,flow_rate:s.flowRate,reward_amount:s.rewardAmount,rewards_allocated:s.rewardsAllocated,hasEnded:s.hasEnded})),t.objectId,e),a.Pool.collectFee(o,{objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,isStable:n.isStable,tickSpacing:n.tickSpacing},t.objectId,e)};var dr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=yp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,positions:i,pools:s}=n,l=new bp.Transaction;for(let d of i){let S=s.find(w=>w.poolId===d.poolId);S&&ln(t,o,d,S,l)}return l}static fromData(t){return new a(t)}};var Sp=require("@mmt-finance/clmm-sdk"),Tp=require("@mysten/sui/transactions");var fr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Sp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,position:i,pool:s}=n,l=new Tp.Transaction;return ln(t,o,i,s,l),l}static fromData(t){return new a(t)}};var wp=require("@mmt-finance/clmm-sdk"),Ip=require("@mysten/sui/transactions"),Cp=jt(require("bignumber.js"));var hr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=wp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{pool:o,position:i,address:s,withdrawPercentage:l}=n,d=new Ip.Transaction,S=o.tokenX.coinType,w=o.tokenY.coinType,I={objectId:o.objectId,tokenXType:S,tokenYType:w},C=BigInt(l===100?i.liquidity:new Cp.default(i.liquidity).multipliedBy(l/100).toFixed(0));return t.Pool.removeLiquidity(d,I,i.objectId,C,BigInt(0),BigInt(0),s),ln(t,s,i,o,d),l===100&&t.Position.closePosition(d,i.objectId),d}static fromData(t){return new a(t)}};var _s=require("@mysten/sui/transactions"),Ls=require("@suilend/springsui-sdk"),Ws={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},kp=async(a,e,t)=>{let n=await Ls.LstClient.initialize(a,Ws),o=new _s.Transaction,[i]=o.splitCoins(o.gas,[BigInt(t)]),s=n.mint(o,i);return o.transferObjects([s],e),o},xp=async(a,e,t)=>{let n=await Ls.LstClient.initialize(a,Ws),o=await a.getCoins({owner:e,coinType:Ws.type,limit:1e3});if(o.data.length===0)throw new Error("No lst coins found");let i=new _s.Transaction,s=o.data[0];o.data.length>1&&i.mergeCoins(s.coinObjectId,o.data.slice(1).map(S=>S.coinObjectId));let[l]=i.splitCoins(s.coinObjectId,[BigInt(t)]),d=n.redeem(i,l);return i.transferObjects([d],e),i};var gr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return await kp(t.suiClient,o,i)}static fromData(t){return new a(t)}};var Ap=require("@mmt-finance/clmm-sdk"),Op=require("@mysten/sui/transactions");var Dp=require("@mmt-finance/clmm-sdk/dist/utils/poolUtils");var vp=async(a,e,t,n,o,i,s)=>{let l=await Me({mmt:a,tx:i,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals}),d=i.moveCall({target:"0x2::coin::value",typeArguments:[t.coinType],arguments:[l]}),S=t.coinType;for(let w=0;w<e.length;w+=1){let{poolId:I,tokenX:C,tokenY:x,isStable:D}=e[w],{id:R,isReverse:K}=Dp.mappedMmtV3Pool[I]||{id:I,isReverse:!1},V=cn(C.coinType)===cn(S);V=K?!V:V;let Ht=K?x.coinType:C.coinType,Et=K?C.coinType:x.coinType,Pt=await ur({poolId:R,tokenX:C,tokenY:x,slippagePercentage:s,isTokenX:V,suiClient:a.rpcClient}),un=a.Pool.swap(i,{objectId:R,tokenXType:Ht,tokenYType:Et,isStable:D},d,l,V,void 0,Pt,!1);i.transferObjects([l],i.pure.address(o)),l=un,S=V?Et:Ht,d=i.moveCall({target:"0x2::coin::value",typeArguments:[S],arguments:[l]})}i.transferObjects([l],i.pure.address(o))};var yr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Ap.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{route:o,tokenIn:i,amountIn:s,address:l,slippage:d}=n,S=new Op.Transaction;return await vp(t,o,i,s,l,S,d),S}static fromData(t){return new a(t)}};var br=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return await xp(t.suiClient,o,i)}static fromData(t){return new a(t)}};var Mp=require("@mmt-finance/clmm-sdk"),Pp=require("@mysten/sui/transactions");var Sr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Mp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amountA:i,amountB:s,pool:l,positionObjectId:d,slippage:S}=n,w=new Pp.Transaction;return await mp(t,w,o,i,s,l,d,S),w}static fromData(t){return new a(t)}};var Rp=require("@mmt-finance/clmm-sdk"),Bp=require("@mysten/sui/transactions");var Tr=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Rp.MmtSDK.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amount:i,isTokenX:s,pool:l,positionObjectId:d,swapSlippage:S,addLiquiditySlippage:w}=n,I=new Bp.Transaction;return await pp(t,I,t.rpcClient,o,i,s,l,d,S,w),I}static fromData(t){return new a(t)}};var wr=class{application="mmt-dex";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:Ep.TransactionType.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=yr.fromData(e.intentionData);break;case"AddLiquidity":t=mr.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=pr.fromData(e.intentionData);break;case"ClaimRewards":t=fr.fromData(e.intentionData);break;case"ClaimAllRewards":t=dr.fromData(e.intentionData);break;case"RemoveLiquidity":t=hr.fromData(e.intentionData);break;case"StakeXSui":t=gr.fromData(e.intentionData);break;case"UnstakeXSui":t=br.fromData(e.intentionData);break;case"ManageLiquidity":t=Sr.fromData(e.intentionData);break;case"ManageLiquiditySingleSide":t=Tr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build({suiClient:e.suiClient})}};var zd=Aa.fromHelpers([new da,new Ca,new ua,new ka,new Fo,new Xi,new wr,new li,new Zi,new ho,new Si,new Ai,new Qn,new cr,new Ri]);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|