@msafe/sui-app-store 0.0.353 → 0.0.355

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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var _d=Object.create;var no=Object.defineProperty;var Ld=Object.getOwnPropertyDescriptor;var jd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,qd=Object.prototype.hasOwnProperty;var Fd=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),ys=(a,e)=>{for(var t in e)no(a,t,{get:e[t],enumerable:!0})},Oc=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jd(e))!qd.call(a,o)&&o!==t&&no(a,o,{get:()=>e[o],enumerable:!(n=Ld(e,o))||n.enumerable});return a};var Pt=(a,e,t)=>(t=a!=null?_d(Ud(a)):{},Oc(e||!a||!a.__esModule?no(t,"default",{value:a,enumerable:!0}):t,a)),Kd=a=>Oc(no({},"__esModule",{value:!0}),a);var zm=Fd((Xm,lc)=>{"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,p){if(typeof r=="number")return this._initNumber(r,u,p);if(typeof r=="object")return this._initArray(r,u,p);u==="hex"&&(u=16),t(u===(u|0)&&u>=2&&u<=36),r=r.toString().replace(/\s+/g,"");var d=0;r[0]==="-"&&(d++,this.negative=1),d<r.length&&(u===16?this._parseHex(r,d,p):(this._parseBase(r,u,d),p==="le"&&this._initArray(this.toArray(),u,p)))},o.prototype._initNumber=function(r,u,p){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),p==="le"&&this._initArray(this.toArray(),u,p)},o.prototype._initArray=function(r,u,p){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 d=0;d<this.length;d++)this.words[d]=0;var h,T,I=0;if(p==="be")for(d=r.length-1,h=0;d>=0;d-=3)T=r[d]|r[d-1]<<8|r[d-2]<<16,this.words[h]|=T<<I&67108863,this.words[h+1]=T>>>26-I&67108863,I+=24,I>=26&&(I-=26,h++);else if(p==="le")for(d=0,h=0;d<r.length;d+=3)T=r[d]|r[d+1]<<8|r[d+2]<<16,this.words[h]|=T<<I&67108863,this.words[h+1]=T>>>26-I&67108863,I+=24,I>=26&&(I-=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 c(y,r,u){var p=s(y,u);return u-1>=r&&(p|=s(y,u-1)<<4),p}o.prototype._parseHex=function(r,u,p){this.length=Math.ceil((r.length-u)/6),this.words=new Array(this.length);for(var d=0;d<this.length;d++)this.words[d]=0;var h=0,T=0,I;if(p==="be")for(d=r.length-1;d>=u;d-=2)I=c(r,u,d)<<h,this.words[T]|=I&67108863,h>=18?(h-=18,T+=1,this.words[T]|=I>>>26):h+=8;else{var f=r.length-u;for(d=f%2===0?u+1:u;d<r.length;d+=2)I=c(r,u,d)<<h,this.words[T]|=I&67108863,h>=18?(h-=18,T+=1,this.words[T]|=I>>>26):h+=8}this._strip()};function m(y,r,u,p){for(var d=0,h=0,T=Math.min(y.length,u),I=r;I<T;I++){var f=y.charCodeAt(I)-48;d*=p,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<p,"Invalid character"),d+=h}return d}o.prototype._parseBase=function(r,u,p){this.words=[0],this.length=1;for(var d=0,h=1;h<=67108863;h*=u)d++;d--,h=h/u|0;for(var T=r.length-p,I=T%d,f=Math.min(T,T-I)+p,l=0,g=p;g<f;g+=d)l=m(r,g,g+d,u),this.imuln(h),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(I!==0){var v=1;for(l=m(r,g,r.length,u),g=0;g<I;g++)v*=u;this.imuln(v),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}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 b(y,r){y.words=r.words,y.length=r.length,y.negative=r.negative,y.red=r.red}if(o.prototype._move=function(r){b(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")]=S}catch{o.prototype.inspect=S}else o.prototype.inspect=S;function S(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var w=["","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],k=[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 p;if(r===16||r==="hex"){p="";for(var d=0,h=0,T=0;T<this.length;T++){var I=this.words[T],f=((I<<d|h)&16777215).toString(16);h=I>>>24-d&16777215,d+=2,d>=26&&(d-=26,T--),h!==0||T!==this.length-1?p=w[6-f.length]+f+p:p=f+p}for(h!==0&&(p=h.toString(16)+p);p.length%u!==0;)p="0"+p;return this.negative!==0&&(p="-"+p),p}if(r===(r|0)&&r>=2&&r<=36){var l=C[r],g=k[r];p="";var v=this.clone();for(v.negative=0;!v.isZero();){var O=v.modrn(g).toString(r);v=v.idivn(g),v.isZero()?p=O+p:p=w[l-O.length]+O+p}for(this.isZero()&&(p="0"+p);p.length%u!==0;)p="0"+p;return this.negative!==0&&(p="-"+p),p}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,p){this._strip();var d=this.byteLength(),h=p||Math.max(1,d);t(d<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var T=D(r,h),I=u==="le"?"LE":"BE";return this["_toArrayLike"+I](T,d),T},o.prototype._toArrayLikeLE=function(r,u){for(var p=0,d=0,h=0,T=0;h<this.length;h++){var I=this.words[h]<<T|d;r[p++]=I&255,p<r.length&&(r[p++]=I>>8&255),p<r.length&&(r[p++]=I>>16&255),T===6?(p<r.length&&(r[p++]=I>>24&255),d=0,T=0):(d=I>>>24,T+=2)}if(p<r.length)for(r[p++]=d;p<r.length;)r[p++]=0},o.prototype._toArrayLikeBE=function(r,u){for(var p=r.length-1,d=0,h=0,T=0;h<this.length;h++){var I=this.words[h]<<T|d;r[p--]=I&255,p>=0&&(r[p--]=I>>8&255),p>=0&&(r[p--]=I>>16&255),T===6?(p>=0&&(r[p--]=I>>24&255),d=0,T=0):(d=I>>>24,T+=2)}if(p>=0)for(r[p--]=d;p>=0;)r[p--]=0},Math.clz32?o.prototype._countBits=function(r){return 32-Math.clz32(r)}:o.prototype._countBits=function(r){var u=r,p=0;return u>=4096&&(p+=13,u>>>=13),u>=64&&(p+=7,u>>>=7),u>=8&&(p+=4,u>>>=4),u>=2&&(p+=2,u>>>=2),p+u},o.prototype._zeroBits=function(r){if(r===0)return 26;var u=r,p=0;return(u&8191)===0&&(p+=13,u>>>=13),(u&127)===0&&(p+=7,u>>>=7),(u&15)===0&&(p+=4,u>>>=4),(u&3)===0&&(p+=2,u>>>=2),(u&1)===0&&p++,p},o.prototype.bitLength=function(){var r=this.words[this.length-1],u=this._countBits(r);return(this.length-1)*26+u};function M(y){for(var r=new Array(y.bitLength()),u=0;u<r.length;u++){var p=u/26|0,d=u%26;r[u]=y.words[p]>>>d&1}return r}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,u=0;u<this.length;u++){var p=this._zeroBits(this.words[u]);if(r+=p,p!==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 p=0;p<u.length;p++)this.words[p]=this.words[p]&r.words[p];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,p;this.length>r.length?(u=this,p=r):(u=r,p=this);for(var d=0;d<p.length;d++)this.words[d]=u.words[d]^p.words[d];if(this!==u)for(;d<u.length;d++)this.words[d]=u.words[d];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,p=r%26;this._expand(u),p>0&&u--;for(var d=0;d<u;d++)this.words[d]=~this.words[d]&67108863;return p>0&&(this.words[d]=~this.words[d]&67108863>>26-p),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 p=r/26|0,d=r%26;return this._expand(p+1),u?this.words[p]=this.words[p]|1<<d:this.words[p]=this.words[p]&~(1<<d),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 p,d;this.length>r.length?(p=this,d=r):(p=r,d=this);for(var h=0,T=0;T<d.length;T++)u=(p.words[T]|0)+(d.words[T]|0)+h,this.words[T]=u&67108863,h=u>>>26;for(;h!==0&&T<p.length;T++)u=(p.words[T]|0)+h,this.words[T]=u&67108863,h=u>>>26;if(this.length=p.length,h!==0)this.words[this.length]=h,this.length++;else if(p!==this)for(;T<p.length;T++)this.words[T]=p.words[T];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 p=this.cmp(r);if(p===0)return this.negative=0,this.length=1,this.words[0]=0,this;var d,h;p>0?(d=this,h=r):(d=r,h=this);for(var T=0,I=0;I<h.length;I++)u=(d.words[I]|0)-(h.words[I]|0)+T,T=u>>26,this.words[I]=u&67108863;for(;T!==0&&I<d.length;I++)u=(d.words[I]|0)+T,T=u>>26,this.words[I]=u&67108863;if(T===0&&I<d.length&&d!==this)for(;I<d.length;I++)this.words[I]=d.words[I];return this.length=Math.max(this.length,I),d!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(r){return this.clone().isub(r)};function q(y,r,u){u.negative=r.negative^y.negative;var p=y.length+r.length|0;u.length=p,p=p-1|0;var d=y.words[0]|0,h=r.words[0]|0,T=d*h,I=T&67108863,f=T/67108864|0;u.words[0]=I;for(var l=1;l<p;l++){for(var g=f>>>26,v=f&67108863,O=Math.min(l,r.length-1),P=Math.max(0,l-y.length+1);P<=O;P++){var B=l-P|0;d=y.words[B]|0,h=r.words[P]|0,T=d*h+v,g+=T/67108864|0,v=T&67108863}u.words[l]=v|0,f=g|0}return f!==0?u.words[l]=f|0:u.length--,u._strip()}var U=function(r,u,p){var d=r.words,h=u.words,T=p.words,I=0,f,l,g,v=d[0]|0,O=v&8191,P=v>>>13,B=d[1]|0,L=B&8191,F=B>>>13,be=d[2]|0,K=be&8191,H=be>>>13,dc=d[3]|0,Y=dc&8191,J=dc>>>13,fc=d[4]|0,Z=fc&8191,tt=fc>>>13,hc=d[5]|0,et=hc&8191,nt=hc>>>13,gc=d[6]|0,ot=gc&8191,at=gc>>>13,yc=d[7]|0,it=yc&8191,rt=yc>>>13,bc=d[8]|0,st=bc&8191,ct=bc>>>13,Tc=d[9]|0,lt=Tc&8191,ut=Tc>>>13,Sc=h[0]|0,pt=Sc&8191,mt=Sc>>>13,wc=h[1]|0,dt=wc&8191,ft=wc>>>13,Ic=h[2]|0,ht=Ic&8191,gt=Ic>>>13,Cc=h[3]|0,yt=Cc&8191,bt=Cc>>>13,xc=h[4]|0,Tt=xc&8191,St=xc>>>13,kc=h[5]|0,wt=kc&8191,It=kc>>>13,Dc=h[6]|0,Ct=Dc&8191,xt=Dc>>>13,vc=h[7]|0,kt=vc&8191,Dt=vc>>>13,Ac=h[8]|0,vt=Ac&8191,At=Ac>>>13,Mc=h[9]|0,Mt=Mc&8191,Ot=Mc>>>13;p.negative=r.negative^u.negative,p.length=19,f=Math.imul(O,pt),l=Math.imul(O,mt),l=l+Math.imul(P,pt)|0,g=Math.imul(P,mt);var Jr=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Jr>>>26)|0,Jr&=67108863,f=Math.imul(L,pt),l=Math.imul(L,mt),l=l+Math.imul(F,pt)|0,g=Math.imul(F,mt),f=f+Math.imul(O,dt)|0,l=l+Math.imul(O,ft)|0,l=l+Math.imul(P,dt)|0,g=g+Math.imul(P,ft)|0;var Zr=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,f=Math.imul(K,pt),l=Math.imul(K,mt),l=l+Math.imul(H,pt)|0,g=Math.imul(H,mt),f=f+Math.imul(L,dt)|0,l=l+Math.imul(L,ft)|0,l=l+Math.imul(F,dt)|0,g=g+Math.imul(F,ft)|0,f=f+Math.imul(O,ht)|0,l=l+Math.imul(O,gt)|0,l=l+Math.imul(P,ht)|0,g=g+Math.imul(P,gt)|0;var ts=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ts>>>26)|0,ts&=67108863,f=Math.imul(Y,pt),l=Math.imul(Y,mt),l=l+Math.imul(J,pt)|0,g=Math.imul(J,mt),f=f+Math.imul(K,dt)|0,l=l+Math.imul(K,ft)|0,l=l+Math.imul(H,dt)|0,g=g+Math.imul(H,ft)|0,f=f+Math.imul(L,ht)|0,l=l+Math.imul(L,gt)|0,l=l+Math.imul(F,ht)|0,g=g+Math.imul(F,gt)|0,f=f+Math.imul(O,yt)|0,l=l+Math.imul(O,bt)|0,l=l+Math.imul(P,yt)|0,g=g+Math.imul(P,bt)|0;var es=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(es>>>26)|0,es&=67108863,f=Math.imul(Z,pt),l=Math.imul(Z,mt),l=l+Math.imul(tt,pt)|0,g=Math.imul(tt,mt),f=f+Math.imul(Y,dt)|0,l=l+Math.imul(Y,ft)|0,l=l+Math.imul(J,dt)|0,g=g+Math.imul(J,ft)|0,f=f+Math.imul(K,ht)|0,l=l+Math.imul(K,gt)|0,l=l+Math.imul(H,ht)|0,g=g+Math.imul(H,gt)|0,f=f+Math.imul(L,yt)|0,l=l+Math.imul(L,bt)|0,l=l+Math.imul(F,yt)|0,g=g+Math.imul(F,bt)|0,f=f+Math.imul(O,Tt)|0,l=l+Math.imul(O,St)|0,l=l+Math.imul(P,Tt)|0,g=g+Math.imul(P,St)|0;var ns=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ns>>>26)|0,ns&=67108863,f=Math.imul(et,pt),l=Math.imul(et,mt),l=l+Math.imul(nt,pt)|0,g=Math.imul(nt,mt),f=f+Math.imul(Z,dt)|0,l=l+Math.imul(Z,ft)|0,l=l+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(Y,ht)|0,l=l+Math.imul(Y,gt)|0,l=l+Math.imul(J,ht)|0,g=g+Math.imul(J,gt)|0,f=f+Math.imul(K,yt)|0,l=l+Math.imul(K,bt)|0,l=l+Math.imul(H,yt)|0,g=g+Math.imul(H,bt)|0,f=f+Math.imul(L,Tt)|0,l=l+Math.imul(L,St)|0,l=l+Math.imul(F,Tt)|0,g=g+Math.imul(F,St)|0,f=f+Math.imul(O,wt)|0,l=l+Math.imul(O,It)|0,l=l+Math.imul(P,wt)|0,g=g+Math.imul(P,It)|0;var os=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(os>>>26)|0,os&=67108863,f=Math.imul(ot,pt),l=Math.imul(ot,mt),l=l+Math.imul(at,pt)|0,g=Math.imul(at,mt),f=f+Math.imul(et,dt)|0,l=l+Math.imul(et,ft)|0,l=l+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,l=l+Math.imul(Z,gt)|0,l=l+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(Y,yt)|0,l=l+Math.imul(Y,bt)|0,l=l+Math.imul(J,yt)|0,g=g+Math.imul(J,bt)|0,f=f+Math.imul(K,Tt)|0,l=l+Math.imul(K,St)|0,l=l+Math.imul(H,Tt)|0,g=g+Math.imul(H,St)|0,f=f+Math.imul(L,wt)|0,l=l+Math.imul(L,It)|0,l=l+Math.imul(F,wt)|0,g=g+Math.imul(F,It)|0,f=f+Math.imul(O,Ct)|0,l=l+Math.imul(O,xt)|0,l=l+Math.imul(P,Ct)|0,g=g+Math.imul(P,xt)|0;var as=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(as>>>26)|0,as&=67108863,f=Math.imul(it,pt),l=Math.imul(it,mt),l=l+Math.imul(rt,pt)|0,g=Math.imul(rt,mt),f=f+Math.imul(ot,dt)|0,l=l+Math.imul(ot,ft)|0,l=l+Math.imul(at,dt)|0,g=g+Math.imul(at,ft)|0,f=f+Math.imul(et,ht)|0,l=l+Math.imul(et,gt)|0,l=l+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,l=l+Math.imul(Z,bt)|0,l=l+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(Y,Tt)|0,l=l+Math.imul(Y,St)|0,l=l+Math.imul(J,Tt)|0,g=g+Math.imul(J,St)|0,f=f+Math.imul(K,wt)|0,l=l+Math.imul(K,It)|0,l=l+Math.imul(H,wt)|0,g=g+Math.imul(H,It)|0,f=f+Math.imul(L,Ct)|0,l=l+Math.imul(L,xt)|0,l=l+Math.imul(F,Ct)|0,g=g+Math.imul(F,xt)|0,f=f+Math.imul(O,kt)|0,l=l+Math.imul(O,Dt)|0,l=l+Math.imul(P,kt)|0,g=g+Math.imul(P,Dt)|0;var is=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(is>>>26)|0,is&=67108863,f=Math.imul(st,pt),l=Math.imul(st,mt),l=l+Math.imul(ct,pt)|0,g=Math.imul(ct,mt),f=f+Math.imul(it,dt)|0,l=l+Math.imul(it,ft)|0,l=l+Math.imul(rt,dt)|0,g=g+Math.imul(rt,ft)|0,f=f+Math.imul(ot,ht)|0,l=l+Math.imul(ot,gt)|0,l=l+Math.imul(at,ht)|0,g=g+Math.imul(at,gt)|0,f=f+Math.imul(et,yt)|0,l=l+Math.imul(et,bt)|0,l=l+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,Tt)|0,l=l+Math.imul(Z,St)|0,l=l+Math.imul(tt,Tt)|0,g=g+Math.imul(tt,St)|0,f=f+Math.imul(Y,wt)|0,l=l+Math.imul(Y,It)|0,l=l+Math.imul(J,wt)|0,g=g+Math.imul(J,It)|0,f=f+Math.imul(K,Ct)|0,l=l+Math.imul(K,xt)|0,l=l+Math.imul(H,Ct)|0,g=g+Math.imul(H,xt)|0,f=f+Math.imul(L,kt)|0,l=l+Math.imul(L,Dt)|0,l=l+Math.imul(F,kt)|0,g=g+Math.imul(F,Dt)|0,f=f+Math.imul(O,vt)|0,l=l+Math.imul(O,At)|0,l=l+Math.imul(P,vt)|0,g=g+Math.imul(P,At)|0;var rs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(rs>>>26)|0,rs&=67108863,f=Math.imul(lt,pt),l=Math.imul(lt,mt),l=l+Math.imul(ut,pt)|0,g=Math.imul(ut,mt),f=f+Math.imul(st,dt)|0,l=l+Math.imul(st,ft)|0,l=l+Math.imul(ct,dt)|0,g=g+Math.imul(ct,ft)|0,f=f+Math.imul(it,ht)|0,l=l+Math.imul(it,gt)|0,l=l+Math.imul(rt,ht)|0,g=g+Math.imul(rt,gt)|0,f=f+Math.imul(ot,yt)|0,l=l+Math.imul(ot,bt)|0,l=l+Math.imul(at,yt)|0,g=g+Math.imul(at,bt)|0,f=f+Math.imul(et,Tt)|0,l=l+Math.imul(et,St)|0,l=l+Math.imul(nt,Tt)|0,g=g+Math.imul(nt,St)|0,f=f+Math.imul(Z,wt)|0,l=l+Math.imul(Z,It)|0,l=l+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(Y,Ct)|0,l=l+Math.imul(Y,xt)|0,l=l+Math.imul(J,Ct)|0,g=g+Math.imul(J,xt)|0,f=f+Math.imul(K,kt)|0,l=l+Math.imul(K,Dt)|0,l=l+Math.imul(H,kt)|0,g=g+Math.imul(H,Dt)|0,f=f+Math.imul(L,vt)|0,l=l+Math.imul(L,At)|0,l=l+Math.imul(F,vt)|0,g=g+Math.imul(F,At)|0,f=f+Math.imul(O,Mt)|0,l=l+Math.imul(O,Ot)|0,l=l+Math.imul(P,Mt)|0,g=g+Math.imul(P,Ot)|0;var ss=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ss>>>26)|0,ss&=67108863,f=Math.imul(lt,dt),l=Math.imul(lt,ft),l=l+Math.imul(ut,dt)|0,g=Math.imul(ut,ft),f=f+Math.imul(st,ht)|0,l=l+Math.imul(st,gt)|0,l=l+Math.imul(ct,ht)|0,g=g+Math.imul(ct,gt)|0,f=f+Math.imul(it,yt)|0,l=l+Math.imul(it,bt)|0,l=l+Math.imul(rt,yt)|0,g=g+Math.imul(rt,bt)|0,f=f+Math.imul(ot,Tt)|0,l=l+Math.imul(ot,St)|0,l=l+Math.imul(at,Tt)|0,g=g+Math.imul(at,St)|0,f=f+Math.imul(et,wt)|0,l=l+Math.imul(et,It)|0,l=l+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,l=l+Math.imul(Z,xt)|0,l=l+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,xt)|0,f=f+Math.imul(Y,kt)|0,l=l+Math.imul(Y,Dt)|0,l=l+Math.imul(J,kt)|0,g=g+Math.imul(J,Dt)|0,f=f+Math.imul(K,vt)|0,l=l+Math.imul(K,At)|0,l=l+Math.imul(H,vt)|0,g=g+Math.imul(H,At)|0,f=f+Math.imul(L,Mt)|0,l=l+Math.imul(L,Ot)|0,l=l+Math.imul(F,Mt)|0,g=g+Math.imul(F,Ot)|0;var cs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(cs>>>26)|0,cs&=67108863,f=Math.imul(lt,ht),l=Math.imul(lt,gt),l=l+Math.imul(ut,ht)|0,g=Math.imul(ut,gt),f=f+Math.imul(st,yt)|0,l=l+Math.imul(st,bt)|0,l=l+Math.imul(ct,yt)|0,g=g+Math.imul(ct,bt)|0,f=f+Math.imul(it,Tt)|0,l=l+Math.imul(it,St)|0,l=l+Math.imul(rt,Tt)|0,g=g+Math.imul(rt,St)|0,f=f+Math.imul(ot,wt)|0,l=l+Math.imul(ot,It)|0,l=l+Math.imul(at,wt)|0,g=g+Math.imul(at,It)|0,f=f+Math.imul(et,Ct)|0,l=l+Math.imul(et,xt)|0,l=l+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,xt)|0,f=f+Math.imul(Z,kt)|0,l=l+Math.imul(Z,Dt)|0,l=l+Math.imul(tt,kt)|0,g=g+Math.imul(tt,Dt)|0,f=f+Math.imul(Y,vt)|0,l=l+Math.imul(Y,At)|0,l=l+Math.imul(J,vt)|0,g=g+Math.imul(J,At)|0,f=f+Math.imul(K,Mt)|0,l=l+Math.imul(K,Ot)|0,l=l+Math.imul(H,Mt)|0,g=g+Math.imul(H,Ot)|0;var ls=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ls>>>26)|0,ls&=67108863,f=Math.imul(lt,yt),l=Math.imul(lt,bt),l=l+Math.imul(ut,yt)|0,g=Math.imul(ut,bt),f=f+Math.imul(st,Tt)|0,l=l+Math.imul(st,St)|0,l=l+Math.imul(ct,Tt)|0,g=g+Math.imul(ct,St)|0,f=f+Math.imul(it,wt)|0,l=l+Math.imul(it,It)|0,l=l+Math.imul(rt,wt)|0,g=g+Math.imul(rt,It)|0,f=f+Math.imul(ot,Ct)|0,l=l+Math.imul(ot,xt)|0,l=l+Math.imul(at,Ct)|0,g=g+Math.imul(at,xt)|0,f=f+Math.imul(et,kt)|0,l=l+Math.imul(et,Dt)|0,l=l+Math.imul(nt,kt)|0,g=g+Math.imul(nt,Dt)|0,f=f+Math.imul(Z,vt)|0,l=l+Math.imul(Z,At)|0,l=l+Math.imul(tt,vt)|0,g=g+Math.imul(tt,At)|0,f=f+Math.imul(Y,Mt)|0,l=l+Math.imul(Y,Ot)|0,l=l+Math.imul(J,Mt)|0,g=g+Math.imul(J,Ot)|0;var us=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(us>>>26)|0,us&=67108863,f=Math.imul(lt,Tt),l=Math.imul(lt,St),l=l+Math.imul(ut,Tt)|0,g=Math.imul(ut,St),f=f+Math.imul(st,wt)|0,l=l+Math.imul(st,It)|0,l=l+Math.imul(ct,wt)|0,g=g+Math.imul(ct,It)|0,f=f+Math.imul(it,Ct)|0,l=l+Math.imul(it,xt)|0,l=l+Math.imul(rt,Ct)|0,g=g+Math.imul(rt,xt)|0,f=f+Math.imul(ot,kt)|0,l=l+Math.imul(ot,Dt)|0,l=l+Math.imul(at,kt)|0,g=g+Math.imul(at,Dt)|0,f=f+Math.imul(et,vt)|0,l=l+Math.imul(et,At)|0,l=l+Math.imul(nt,vt)|0,g=g+Math.imul(nt,At)|0,f=f+Math.imul(Z,Mt)|0,l=l+Math.imul(Z,Ot)|0,l=l+Math.imul(tt,Mt)|0,g=g+Math.imul(tt,Ot)|0;var ps=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ps>>>26)|0,ps&=67108863,f=Math.imul(lt,wt),l=Math.imul(lt,It),l=l+Math.imul(ut,wt)|0,g=Math.imul(ut,It),f=f+Math.imul(st,Ct)|0,l=l+Math.imul(st,xt)|0,l=l+Math.imul(ct,Ct)|0,g=g+Math.imul(ct,xt)|0,f=f+Math.imul(it,kt)|0,l=l+Math.imul(it,Dt)|0,l=l+Math.imul(rt,kt)|0,g=g+Math.imul(rt,Dt)|0,f=f+Math.imul(ot,vt)|0,l=l+Math.imul(ot,At)|0,l=l+Math.imul(at,vt)|0,g=g+Math.imul(at,At)|0,f=f+Math.imul(et,Mt)|0,l=l+Math.imul(et,Ot)|0,l=l+Math.imul(nt,Mt)|0,g=g+Math.imul(nt,Ot)|0;var ms=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ms>>>26)|0,ms&=67108863,f=Math.imul(lt,Ct),l=Math.imul(lt,xt),l=l+Math.imul(ut,Ct)|0,g=Math.imul(ut,xt),f=f+Math.imul(st,kt)|0,l=l+Math.imul(st,Dt)|0,l=l+Math.imul(ct,kt)|0,g=g+Math.imul(ct,Dt)|0,f=f+Math.imul(it,vt)|0,l=l+Math.imul(it,At)|0,l=l+Math.imul(rt,vt)|0,g=g+Math.imul(rt,At)|0,f=f+Math.imul(ot,Mt)|0,l=l+Math.imul(ot,Ot)|0,l=l+Math.imul(at,Mt)|0,g=g+Math.imul(at,Ot)|0;var ds=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ds>>>26)|0,ds&=67108863,f=Math.imul(lt,kt),l=Math.imul(lt,Dt),l=l+Math.imul(ut,kt)|0,g=Math.imul(ut,Dt),f=f+Math.imul(st,vt)|0,l=l+Math.imul(st,At)|0,l=l+Math.imul(ct,vt)|0,g=g+Math.imul(ct,At)|0,f=f+Math.imul(it,Mt)|0,l=l+Math.imul(it,Ot)|0,l=l+Math.imul(rt,Mt)|0,g=g+Math.imul(rt,Ot)|0;var fs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(fs>>>26)|0,fs&=67108863,f=Math.imul(lt,vt),l=Math.imul(lt,At),l=l+Math.imul(ut,vt)|0,g=Math.imul(ut,At),f=f+Math.imul(st,Mt)|0,l=l+Math.imul(st,Ot)|0,l=l+Math.imul(ct,Mt)|0,g=g+Math.imul(ct,Ot)|0;var hs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(hs>>>26)|0,hs&=67108863,f=Math.imul(lt,Mt),l=Math.imul(lt,Ot),l=l+Math.imul(ut,Mt)|0,g=Math.imul(ut,Ot);var gs=(I+f|0)+((l&8191)<<13)|0;return I=(g+(l>>>13)|0)+(gs>>>26)|0,gs&=67108863,T[0]=Jr,T[1]=Zr,T[2]=ts,T[3]=es,T[4]=ns,T[5]=os,T[6]=as,T[7]=is,T[8]=rs,T[9]=ss,T[10]=cs,T[11]=ls,T[12]=us,T[13]=ps,T[14]=ms,T[15]=ds,T[16]=fs,T[17]=hs,T[18]=gs,I!==0&&(T[19]=I,p.length++),p};Math.imul||(U=q);function G(y,r,u){u.negative=r.negative^y.negative,u.length=y.length+r.length;for(var p=0,d=0,h=0;h<u.length-1;h++){var T=d;d=0;for(var I=p&67108863,f=Math.min(h,r.length-1),l=Math.max(0,h-y.length+1);l<=f;l++){var g=h-l,v=y.words[g]|0,O=r.words[l]|0,P=v*O,B=P&67108863;T=T+(P/67108864|0)|0,B=B+I|0,I=B&67108863,T=T+(B>>>26)|0,d+=T>>>26,T&=67108863}u.words[h]=I,p=T,T=d}return p!==0?u.words[h]=p:u.length--,u._strip()}function $(y,r,u){return G(y,r,u)}o.prototype.mulTo=function(r,u){var p,d=this.length+r.length;return this.length===10&&r.length===10?p=U(this,r,u):d<63?p=q(this,r,u):d<1024?p=G(this,r,u):p=$(this,r,u),p};function E(y,r){this.x=y,this.y=r}E.prototype.makeRBT=function(r){for(var u=new Array(r),p=o.prototype._countBits(r)-1,d=0;d<r;d++)u[d]=this.revBin(d,p,r);return u},E.prototype.revBin=function(r,u,p){if(r===0||r===p-1)return r;for(var d=0,h=0;h<u;h++)d|=(r&1)<<u-h-1,r>>=1;return d},E.prototype.permute=function(r,u,p,d,h,T){for(var I=0;I<T;I++)d[I]=u[r[I]],h[I]=p[r[I]]},E.prototype.transform=function(r,u,p,d,h,T){this.permute(T,r,u,p,d,h);for(var I=1;I<h;I<<=1)for(var f=I<<1,l=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),v=0;v<h;v+=f)for(var O=l,P=g,B=0;B<I;B++){var L=p[v+B],F=d[v+B],be=p[v+B+I],K=d[v+B+I],H=O*be-P*K;K=O*K+P*be,be=H,p[v+B]=L+be,d[v+B]=F+K,p[v+B+I]=L-be,d[v+B+I]=F-K,B!==f&&(H=l*O-g*P,P=l*P+g*O,O=H)}},E.prototype.guessLen13b=function(r,u){var p=Math.max(u,r)|1,d=p&1,h=0;for(p=p/2|0;p;p=p>>>1)h++;return 1<<h+1+d},E.prototype.conjugate=function(r,u,p){if(!(p<=1))for(var d=0;d<p/2;d++){var h=r[d];r[d]=r[p-d-1],r[p-d-1]=h,h=u[d],u[d]=-u[p-d-1],u[p-d-1]=-h}},E.prototype.normalize13b=function(r,u){for(var p=0,d=0;d<u/2;d++){var h=Math.round(r[2*d+1]/u)*8192+Math.round(r[2*d]/u)+p;r[d]=h&67108863,h<67108864?p=0:p=h/67108864|0}return r},E.prototype.convert13b=function(r,u,p,d){for(var h=0,T=0;T<u;T++)h=h+(r[T]|0),p[2*T]=h&8191,h=h>>>13,p[2*T+1]=h&8191,h=h>>>13;for(T=2*u;T<d;++T)p[T]=0;t(h===0),t((h&-8192)===0)},E.prototype.stub=function(r){for(var u=new Array(r),p=0;p<r;p++)u[p]=0;return u},E.prototype.mulp=function(r,u,p){var d=2*this.guessLen13b(r.length,u.length),h=this.makeRBT(d),T=this.stub(d),I=new Array(d),f=new Array(d),l=new Array(d),g=new Array(d),v=new Array(d),O=new Array(d),P=p.words;P.length=d,this.convert13b(r.words,r.length,I,d),this.convert13b(u.words,u.length,g,d),this.transform(I,T,f,l,d,h),this.transform(g,T,v,O,d,h);for(var B=0;B<d;B++){var L=f[B]*v[B]-l[B]*O[B];l[B]=f[B]*O[B]+l[B]*v[B],f[B]=L}return this.conjugate(f,l,d),this.transform(f,l,P,T,d,h),this.conjugate(P,T,d),this.normalize13b(P,d),p.negative=r.negative^u.negative,p.length=r.length+u.length,p._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),$(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 p=0,d=0;d<this.length;d++){var h=(this.words[d]|0)*r,T=(h&67108863)+(p&67108863);p>>=26,p+=h/67108864|0,p+=T>>>26,this.words[d]=T&67108863}return p!==0&&(this.words[d]=p,this.length++),this.length=r===0?1: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=M(r);if(u.length===0)return new o(1);for(var p=this,d=0;d<u.length&&u[d]===0;d++,p=p.sqr());if(++d<u.length)for(var h=p.sqr();d<u.length;d++,h=h.sqr())u[d]!==0&&(p=p.mul(h));return p},o.prototype.iushln=function(r){t(typeof r=="number"&&r>=0);var u=r%26,p=(r-u)/26,d=67108863>>>26-u<<26-u,h;if(u!==0){var T=0;for(h=0;h<this.length;h++){var I=this.words[h]&d,f=(this.words[h]|0)-I<<u;this.words[h]=f|T,T=I>>>26-u}T&&(this.words[h]=T,this.length++)}if(p!==0){for(h=this.length-1;h>=0;h--)this.words[h+p]=this.words[h];for(h=0;h<p;h++)this.words[h]=0;this.length+=p}return this._strip()},o.prototype.ishln=function(r){return t(this.negative===0),this.iushln(r)},o.prototype.iushrn=function(r,u,p){t(typeof r=="number"&&r>=0);var d;u?d=(u-u%26)/26:d=0;var h=r%26,T=Math.min((r-h)/26,this.length),I=67108863^67108863>>>h<<h,f=p;if(d-=T,d=Math.max(0,d),f){for(var l=0;l<T;l++)f.words[l]=this.words[l];f.length=T}if(T!==0)if(this.length>T)for(this.length-=T,l=0;l<this.length;l++)this.words[l]=this.words[l+T];else this.words[0]=0,this.length=1;var g=0;for(l=this.length-1;l>=0&&(g!==0||l>=d);l--){var v=this.words[l]|0;this.words[l]=g<<26-h|v>>>h,g=v&I}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,p){return t(this.negative===0),this.iushrn(r,u,p)},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,p=(r-u)/26,d=1<<u;if(this.length<=p)return!1;var h=this.words[p];return!!(h&d)},o.prototype.imaskn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,p=(r-u)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=p)return this;if(u!==0&&p++,this.length=Math.min(p,this.length),u!==0){var d=67108863^67108863>>>u<<u;this.words[this.length-1]&=d}return this.length===0&&(this.words[0]=0,this.length=1),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,p){var d=r.length+p,h;this._expand(d);var T,I=0;for(h=0;h<r.length;h++){T=(this.words[h+p]|0)+I;var f=(r.words[h]|0)*u;T-=f&67108863,I=(T>>26)-(f/67108864|0),this.words[h+p]=T&67108863}for(;h<this.length-p;h++)T=(this.words[h+p]|0)+I,I=T>>26,this.words[h+p]=T&67108863;if(I===0)return this._strip();for(t(I===-1),I=0,h=0;h<this.length;h++)T=-(this.words[h]|0)+I,I=T>>26,this.words[h]=T&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(r,u){var p=this.length-r.length,d=this.clone(),h=r,T=h.words[h.length-1]|0,I=this._countBits(T);p=26-I,p!==0&&(h=h.ushln(p),d.iushln(p),T=h.words[h.length-1]|0);var f=d.length-h.length,l;if(u!=="mod"){l=new o(null),l.length=f+1,l.words=new Array(l.length);for(var g=0;g<l.length;g++)l.words[g]=0}var v=d.clone()._ishlnsubmul(h,1,f);v.negative===0&&(d=v,l&&(l.words[f]=1));for(var O=f-1;O>=0;O--){var P=(d.words[h.length+O]|0)*67108864+(d.words[h.length+O-1]|0);for(P=Math.min(P/T|0,67108863),d._ishlnsubmul(h,P,O);d.negative!==0;)P--,d.negative=0,d._ishlnsubmul(h,1,O),d.isZero()||(d.negative^=1);l&&(l.words[O]=P)}return l&&l._strip(),d._strip(),u!=="div"&&p!==0&&d.iushrn(p),{div:l||null,mod:d}},o.prototype.divmod=function(r,u,p){if(t(!r.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var d,h,T;return this.negative!==0&&r.negative===0?(T=this.neg().divmod(r,u),u!=="mod"&&(d=T.div.neg()),u!=="div"&&(h=T.mod.neg(),p&&h.negative!==0&&h.iadd(r)),{div:d,mod:h}):this.negative===0&&r.negative!==0?(T=this.divmod(r.neg(),u),u!=="mod"&&(d=T.div.neg()),{div:d,mod:T.mod}):(this.negative&r.negative)!==0?(T=this.neg().divmod(r.neg(),u),u!=="div"&&(h=T.mod.neg(),p&&h.negative!==0&&h.isub(r)),{div:T.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 p=u.div.negative!==0?u.mod.isub(r):u.mod,d=r.ushrn(1),h=r.andln(1),T=p.cmp(d);return T<0||h===1&&T===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 p=(1<<26)%r,d=0,h=this.length-1;h>=0;h--)d=(p*d+(this.words[h]|0))%r;return u?-d:d},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 p=0,d=this.length-1;d>=0;d--){var h=(this.words[d]|0)+p*67108864;this.words[d]=h/r|0,p=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,p=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var d=new o(1),h=new o(0),T=new o(0),I=new o(1),f=0;u.isEven()&&p.isEven();)u.iushrn(1),p.iushrn(1),++f;for(var l=p.clone(),g=u.clone();!u.isZero();){for(var v=0,O=1;(u.words[0]&O)===0&&v<26;++v,O<<=1);if(v>0)for(u.iushrn(v);v-- >0;)(d.isOdd()||h.isOdd())&&(d.iadd(l),h.isub(g)),d.iushrn(1),h.iushrn(1);for(var P=0,B=1;(p.words[0]&B)===0&&P<26;++P,B<<=1);if(P>0)for(p.iushrn(P);P-- >0;)(T.isOdd()||I.isOdd())&&(T.iadd(l),I.isub(g)),T.iushrn(1),I.iushrn(1);u.cmp(p)>=0?(u.isub(p),d.isub(T),h.isub(I)):(p.isub(u),T.isub(d),I.isub(h))}return{a:T,b:I,gcd:p.iushln(f)}},o.prototype._invmp=function(r){t(r.negative===0),t(!r.isZero());var u=this,p=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var d=new o(1),h=new o(0),T=p.clone();u.cmpn(1)>0&&p.cmpn(1)>0;){for(var I=0,f=1;(u.words[0]&f)===0&&I<26;++I,f<<=1);if(I>0)for(u.iushrn(I);I-- >0;)d.isOdd()&&d.iadd(T),d.iushrn(1);for(var l=0,g=1;(p.words[0]&g)===0&&l<26;++l,g<<=1);if(l>0)for(p.iushrn(l);l-- >0;)h.isOdd()&&h.iadd(T),h.iushrn(1);u.cmp(p)>=0?(u.isub(p),d.isub(h)):(p.isub(u),h.isub(d))}var v;return u.cmpn(1)===0?v=d: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(),p=r.clone();u.negative=0,p.negative=0;for(var d=0;u.isEven()&&p.isEven();d++)u.iushrn(1),p.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;p.isEven();)p.iushrn(1);var h=u.cmp(p);if(h<0){var T=u;u=p,p=T}else if(h===0||p.cmpn(1)===0)break;u.isub(p)}while(!0);return p.iushln(d)},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,p=(r-u)/26,d=1<<u;if(this.length<=p)return this._expand(p+1),this.words[p]|=d,this;for(var h=d,T=p;h!==0&&T<this.length;T++){var I=this.words[T]|0;I+=h,h=I>>>26,I&=67108863,this.words[T]=I}return h!==0&&(this.words[T]=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 p;if(this.length>1)p=1;else{u&&(r=-r),t(r<=67108863,"Number is too big");var d=this.words[0]|0;p=d===r?0:d<r?-1:1}return this.negative!==0?-p|0:p},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,p=this.length-1;p>=0;p--){var d=this.words[p]|0,h=r.words[p]|0;if(d!==h){d<h?u=-1:d>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 X(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 ye={k256:null,p224:null,p192:null,p25519:null};function _t(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()}_t.prototype._tmp=function(){var r=new o(null);return r.words=new Array(Math.ceil(this.n/13)),r},_t.prototype.ireduce=function(r){var u=r,p;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),p=u.bitLength();while(p>this.n);var d=p<this.n?-1:u.ucmp(this.p);return d===0?(u.words[0]=0,u.length=1):d>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},_t.prototype.split=function(r,u){r.iushrn(this.n,0,u)},_t.prototype.imulK=function(r){return r.imul(this.k)};function le(){_t.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(le,_t),le.prototype.split=function(r,u){for(var p=4194303,d=Math.min(r.length,9),h=0;h<d;h++)u.words[h]=r.words[h];if(u.length=d,r.length<=9){r.words[0]=0,r.length=1;return}var T=r.words[9];for(u.words[u.length++]=T&p,h=10;h<r.length;h++){var I=r.words[h]|0;r.words[h-10]=(I&p)<<4|T>>>22,T=I}T>>>=22,r.words[h-10]=T,T===0&&r.length>10?r.length-=10:r.length-=9},le.prototype.imulK=function(r){r.words[r.length]=0,r.words[r.length+1]=0,r.length+=2;for(var u=0,p=0;p<r.length;p++){var d=r.words[p]|0;u+=d*977,r.words[p]=u&67108863,u=d*64+(u/67108864|0)}return r.words[r.length-1]===0&&(r.length--,r.words[r.length-1]===0&&r.length--),r};function eo(){_t.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(eo,_t);function kn(){_t.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(kn,_t);function ze(){_t.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(ze,_t),ze.prototype.imulK=function(r){for(var u=0,p=0;p<r.length;p++){var d=(r.words[p]|0)*19+u,h=d&67108863;d>>>=26,r.words[p]=h,u=d}return u!==0&&(r.words[r.length++]=u),r},o._prime=function(r){if(ye[r])return ye[r];var u;if(r==="k256")u=new le;else if(r==="p224")u=new eo;else if(r==="p192")u=new kn;else if(r==="p25519")u=new ze;else throw new Error("Unknown prime "+r);return ye[r]=u,u};function X(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}X.prototype._verify1=function(r){t(r.negative===0,"red works only with positives"),t(r.red,"red works only with red numbers")},X.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")},X.prototype.imod=function(r){return this.prime?this.prime.ireduce(r)._forceRed(this):(b(r,r.umod(this.m)._forceRed(this)),r)},X.prototype.neg=function(r){return r.isZero()?r.clone():this.m.sub(r)._forceRed(this)},X.prototype.add=function(r,u){this._verify2(r,u);var p=r.add(u);return p.cmp(this.m)>=0&&p.isub(this.m),p._forceRed(this)},X.prototype.iadd=function(r,u){this._verify2(r,u);var p=r.iadd(u);return p.cmp(this.m)>=0&&p.isub(this.m),p},X.prototype.sub=function(r,u){this._verify2(r,u);var p=r.sub(u);return p.cmpn(0)<0&&p.iadd(this.m),p._forceRed(this)},X.prototype.isub=function(r,u){this._verify2(r,u);var p=r.isub(u);return p.cmpn(0)<0&&p.iadd(this.m),p},X.prototype.shl=function(r,u){return this._verify1(r),this.imod(r.ushln(u))},X.prototype.imul=function(r,u){return this._verify2(r,u),this.imod(r.imul(u))},X.prototype.mul=function(r,u){return this._verify2(r,u),this.imod(r.mul(u))},X.prototype.isqr=function(r){return this.imul(r,r.clone())},X.prototype.sqr=function(r){return this.mul(r,r)},X.prototype.sqrt=function(r){if(r.isZero())return r.clone();var u=this.m.andln(3);if(t(u%2===1),u===3){var p=this.m.add(new o(1)).iushrn(2);return this.pow(r,p)}for(var d=this.m.subn(1),h=0;!d.isZero()&&d.andln(1)===0;)h++,d.iushrn(1);t(!d.isZero());var T=new o(1).toRed(this),I=T.redNeg(),f=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);this.pow(l,f).cmp(I)!==0;)l.redIAdd(I);for(var g=this.pow(l,d),v=this.pow(r,d.addn(1).iushrn(1)),O=this.pow(r,d),P=h;O.cmp(T)!==0;){for(var B=O,L=0;B.cmp(T)!==0;L++)B=B.redSqr();t(L<P);var F=this.pow(g,new o(1).iushln(P-L-1));v=v.redMul(F),g=F.redSqr(),O=O.redMul(g),P=L}return v},X.prototype.invm=function(r){var u=r._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},X.prototype.pow=function(r,u){if(u.isZero())return new o(1).toRed(this);if(u.cmpn(1)===0)return r.clone();var p=4,d=new Array(1<<p);d[0]=new o(1).toRed(this),d[1]=r;for(var h=2;h<d.length;h++)d[h]=this.mul(d[h-1],r);var T=d[0],I=0,f=0,l=u.bitLength()%26;for(l===0&&(l=26),h=u.length-1;h>=0;h--){for(var g=u.words[h],v=l-1;v>=0;v--){var O=g>>v&1;if(T!==d[0]&&(T=this.sqr(T)),O===0&&I===0){f=0;continue}I<<=1,I|=O,f++,!(f!==p&&(h!==0||v!==0))&&(T=this.mul(T,d[I]),f=0,I=0)}l=26}return T},X.prototype.convertTo=function(r){var u=r.umod(this.m);return u===r?u.clone():u},X.prototype.convertFrom=function(r){var u=r.clone();return u.red=null,u},o.mont=function(r){return new We(r)};function We(y){X.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(We,X),We.prototype.convertTo=function(r){return this.imod(r.ushln(this.shift))},We.prototype.convertFrom=function(r){var u=this.imod(r.mul(this.rinv));return u.red=null,u},We.prototype.imul=function(r,u){if(r.isZero()||u.isZero())return r.words[0]=0,r.length=1,r;var p=r.imul(u),d=p.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=p.isub(d).iushrn(this.shift),T=h;return h.cmp(this.m)>=0?T=h.isub(this.m):h.cmpn(0)<0&&(T=h.iadd(this.m)),T._forceRed(this)},We.prototype.mul=function(r,u){if(r.isZero()||u.isZero())return new o(0)._forceRed(this);var p=r.mul(u),d=p.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=p.isub(d).iushrn(this.shift),T=h;return h.cmp(this.m)>=0?T=h.isub(this.m):h.cmpn(0)<0&&(T=h.iadd(this.m)),T._forceRed(this)},We.prototype.invm=function(r){var u=this.imod(r._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof lc>"u"||lc,Xm)});var sh={};ys(sh,{appHelpers:()=>rh});module.exports=Kd(sh);var _c=require("@msafe/sui3-utils");var ue=require("@alphafi/alphafi-sdk"),Qe=require("@msafe/sui3-utils"),te=require("@mysten/bcs");var oo=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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=ue.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&&ue.poolInfo[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&ue.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=te.bcs.u64().parse((0,te.fromBase64)(t)):t.length===24?n=te.bcs.u128().parse((0,te.fromBase64)(t)):t.length===44?n=te.bcs.u256().parse((0,te.fromBase64)(t)):n=te.bcs.u64().parse((0,te.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:Qe.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}=ue.singleAssetPoolCoinMap[e],{expo:s}=ue.coinsList[i];n=Math.floor(Number(n)/10**(9-s)).toString()}return{txType:Qe.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:Qe.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:Qe.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:Qe.TransactionType.Other,type:"claimReward",intentionData:{}}}};var Rc=require("@alphafi/alphafi-sdk");var Pc=Pt(require("sort-keys-recursive")),x=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Pc.default)(this.data))}};var ao=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t;return await(0,Rc.claimRewardTxb)(n.address)}static fromData(t){return new a(t)}};var Bc=require("@alphafi/alphafi-sdk");var io=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i,isAmountA:s}=this.data;return await(0,Bc.depositDoubleAssetTxb)(o,n.address,i,s)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};var Ec=require("@alphafi/alphafi-sdk");var ro=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:i}=this.data;return await(0,Ec.depositSingleAssetTxb)(o,n.address,i)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};var Nc=require("@alphafi/alphafi-sdk");var so=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:i}=this.data;return await(0,Nc.withdrawTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var Wc=require("@alphafi/alphafi-sdk");var co=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:i}=this.data;return await(0,Wc.withdrawAlphaTxb)(i,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var lo=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 c=new oo(t,i).decode();return{txType:_c.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=ro.fromData(e.intentionData);break;case"depositDoubleAsset":n=io.fromData(e.intentionData);break;case"withdraw":n=so.fromData(e.intentionData);break;case"withdrawAlpha":n=co.fromData(e.intentionData);break;case"claimReward":n=ao.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};var cl=require("@msafe/sui3-utils");var Ft=require("@msafe/sui3-utils"),uo=require("@mysten/sui/bcs"),po=require("bucket-protocol-sdk");var mo=class{constructor(e){this.transaction=e}transaction;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(po.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(po.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(po.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:Ft.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 c=this.getMoveCallCommand("high_top_up").MoveCall;[e]=c.typeArguments;let m=c.arguments[1];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[3];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow")){let c=this.getMoveCallCommand("high_borrow").MoveCall;[e]=c.typeArguments;let m=c.arguments[4];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[5];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let c=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=c.typeArguments;let m=c.arguments[5];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[6];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}return{txType:Ft.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 c=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=c.typeArguments;let m=c.arguments[4];m.$kind==="Input"&&(n=this.getPureInputU64(m.Input));let b=c.arguments[5];if(b.$kind==="Input"){let w=this.getPureAddresses(b.Input);w.length===1&&([i]=w)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let c=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=c.typeArguments;let m=c.arguments[5];m.$kind==="Input"&&(n=this.getPureInputU64(m.Input));let b=c.arguments[6];if(b.$kind==="Input"){let w=this.getPureAddresses(b.Input);w.length===1&&([i]=w)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}return{txType:Ft.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 c=i.arguments[5];if(c.$kind==="Input"){let m=this.getPureAddresses(c.Input);m.length===1&&([n]=m)}}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 c=i.arguments[4];if(c.$kind==="Input"){let m=this.getPureAddresses(c.Input);m.length===1&&([n]=m)}}return{txType:Ft.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:Ft.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:Ft.TransactionType.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:s}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let m=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];m.$kind==="Input"&&(e=this.getPureInputU64(m.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let c=0;c<o.length;c++){let m=o[c];n.push("")}else{let c=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let m=0;m<c.length;m++){let S=c[m].MoveCall.arguments[2];if(S.$kind==="Input"){let{objectId:w}=this.inputs[S.Input].UnresolvedObject;n.push(w)}}}let i=this.isSBUCKWithdrawTransaction(),s={stakeProofs:n,amount:e,isStake:t,toBuck:i};return console.log("Decoder.decodeSBUCKUnstake",s),{txType:Ft.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:Ft.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:Ft.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:Ft.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:Ft.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:Ft.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:Ft.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 uo.bcs.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return uo.bcs.vector(uo.bcs.Address).fromBase64(t.Pure.bytes)}};var Fc=require("@msafe/sui3-utils");var jc=require("@mysten/sui/transactions"),Uc=require("bucket-protocol-sdk");var Lc=require("bucket-protocol-sdk"),Lt=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new Lc.BucketClient(t,e.address)};var qc=async(a,e,t)=>{let{coinType:n,amount:o,buckToCoin:i}=a,s=new jc.Transaction,c=Lt(t,e);return await(0,Uc.buildPsmTx)(c,s,n,o,i,e.address),s};var ho=class a extends x{constructor(t){super(t);this.data=t}data;txType=Fc.TransactionType.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await qc(this.data,n,o)}static fromData(t){return new a(t)}};var Hc=require("@msafe/sui3-utils");var Dn=require("@mysten/sui/transactions"),Te=require("bucket-protocol-sdk");var Kc=async(a,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:i,insertionPlace:s,strapId:c}=a,m=new Dn.Transaction,b=Lt(t,e);return await(0,Te.buildBorrowTx)(b,m,n,o,i,e.address,s,c),m},Gc=async(a,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:i,strapId:s}=a,c=new Dn.Transaction,m=Lt(t,e);return await(0,Te.buildWithdrawTx)(m,c,n,o,e.address,i,s),c},Vc=async(a,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:i,isSurplus:s,insertionPlace:c,strapId:m}=a,b=new Dn.Transaction,S=Lt(t,e);return await(0,Te.buildRepayTx)(S,b,n,o,i,e.address,s,c,m),b},$c=async(a,e,t)=>{let{collateralType:n,recipient:o,strapId:i}=a,s=new Dn.Transaction,c=Lt(t,e);return await(0,Te.buildCloseTx)(c,s,n,o,i),s};var go=class a extends x{constructor(t){super(t);this.data=t}data;txType=Hc.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await Kc(this.data,n,o)}static fromData(t){return new a(t)}};var Xc=require("@msafe/sui3-utils");var yo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Xc.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await Vc(this.data,n,o)}static fromData(t){return new a(t)}};var zc=require("@msafe/sui3-utils");var bo=class a extends x{constructor(t){super(t);this.data=t}data;txType=zc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await Gc(this.data,n,o)}static fromData(t){return new a(t)}};var Qc=require("@msafe/sui3-utils");var To=class a extends x{constructor(t){super(t);this.data=t}data;txType=Qc.TransactionType.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await $c(this.data,n,o)}static fromData(t){return new a(t)}};var An=require("@msafe/sui3-utils");var vn=require("@mysten/sui/transactions"),Se=require("bucket-protocol-sdk");var Yc=async(a,e,t)=>{let{coinType:n,amount:o,isStake:i}=a,s=new vn.Transaction,c=Lt(t,e);return await(0,Se.buildSBUCKDepositTx)(c,s,n,o,e.address,i),s},Jc=async(a,e,t)=>{let{stakeProofs:n,amount:o,isStake:i,toBuck:s}=a,c=new vn.Transaction,m=Lt(t,e);return await(0,Se.buildSBUCKUnstakeTx)(m,c,n,o,e.address,i,s),c},Zc=async(a,e,t)=>{let{amount:n}=a,o=new vn.Transaction,i=Lt(t,e);return await(0,Se.buildSBUCKWithdrawTx)(i,o,n,e.address),o},tl=async(a,e,t)=>{let{stakeProofs:n}=a,o=new vn.Transaction,i=Lt(t,e);return await(0,Se.buildSBUCKClaimTx)(i,o,n,e.address),o};var So=class a extends x{constructor(t){super(t);this.data=t}data;txType=An.TransactionType.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await Yc(this.data,n,o)}static fromData(t){return new a(t)}},wo=class a extends x{constructor(t){super(t);this.data=t}data;txType=An.TransactionType.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await Jc(this.data,n,o)}static fromData(t){return new a(t)}},Io=class a extends x{constructor(t){super(t);this.data=t}data;txType=An.TransactionType.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await Zc(this.data,n,o)}static fromData(t){return new a(t)}},Co=class a extends x{constructor(t){super(t);this.data=t}data;txType=An.TransactionType.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await tl(this.data,n,o)}static fromData(t){return new a(t)}};var Ao=require("@msafe/sui3-utils");var xo=require("@mysten/sui/transactions"),Ye=require("bucket-protocol-sdk");var el=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new xo.Transaction,s=Lt(t,e);return await(0,Ye.buildTankDepositTx)(s,i,n,o,e.address),i},nl=async(a,e,t)=>{let{coinType:n,amount:o}=a,i=new xo.Transaction,s=Lt(t,e);return await(0,Ye.buildTankWithdrawTx)(s,i,n,o,e.address),i},ol=async(a,e,t)=>{let{coinType:n}=a,o=new xo.Transaction,i=Lt(t,e);return await(0,Ye.buildTankClaimTx)(i,o,n,e.address),o};var al=require("@mysten/sui/transactions"),il=require("bucket-protocol-sdk");var rl=async(a,e,t)=>{let{coinType:n,proofCount:o}=a,i=new al.Transaction,s=Lt(t,e);return await(0,il.buildLockedClaimTx)(s,i,n,o,e.address),i};var ko=class a extends x{constructor(t){super(t);this.data=t}data;txType=Ao.TransactionType.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await el(this.data,n,o)}static fromData(t){return new a(t)}},Do=class a extends x{constructor(t){super(t);this.data=t}data;txType=Ao.TransactionType.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await nl(this.data,n,o)}static fromData(t){return new a(t)}},vo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Ao.TransactionType.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await ol(this.data,n,o)}static fromData(t){return new a(t)}};var sl=require("@msafe/sui3-utils");var Mo=class a extends x{constructor(t){super(t);this.data=t}data;txType=sl.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await rl(this.data,n,o)}static fromData(t){return new a(t)}};var Oo=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new mo(t).decode();return{txType:cl.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=ho.fromData(e.intentionData);break;case"borrow":i=go.fromData(e.intentionData);break;case"withdraw":i=bo.fromData(e.intentionData);break;case"repay":i=yo.fromData(e.intentionData);break;case"close":i=To.fromData(e.intentionData);break;case"tank-deposit":i=ko.fromData(e.intentionData);break;case"tank-withdraw":i=Do.fromData(e.intentionData);break;case"tank-claim":i=vo.fromData(e.intentionData);break;case"sbuck-deposit":i=So.fromData(e.intentionData);break;case"sbuck-unstake":i=wo.fromData(e.intentionData);break;case"sbuck-withdraw":i=Io.fromData(e.intentionData);break;case"sbuck-claim":i=Co.fromData(e.intentionData);break;case"lock-claim":i=Mo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var du=require("@msafe/sui3-utils");var Tl=require("@msafe/sui3-utils");var bs=require("@mysten/sui/grpc"),pl=require("@mysten/sui/transactions");var ll=require("@mysten/sui/grpc"),ul=require("@mysten/sui/transactions"),Vd={"sui:mainnet":"mainnet","sui:testnet":"testnet","sui:devnet":"devnet","sui:localnet":"localnet"};function Po(a){return Vd[a]}function jt(a){switch(a){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${a}`)}}function $d(a){return Object.assign(a,{async getCoins(e){let t=await a.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinType:n.type,coinObjectId:n.objectId,version:n.version,digest:n.digest,balance:n.balance,previousTransaction:"0x0"})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}},async devInspectTransactionBlock(e){let t=typeof e.transactionBlock=="object"&&e.transactionBlock!==null&&"setSenderIfNotSet"in e.transactionBlock?e.transactionBlock:ul.Transaction.from(e.transactionBlock);t.setSenderIfNotSet(e.sender);let n=await a.simulateTransaction({transaction:t,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}}),o=n.$kind==="Transaction"?n.Transaction:n.FailedTransaction,i=o.effects?.status?.success??!1;return{error:i?null:o.effects?.status?.error?.message??"Simulation failed",effects:{status:{status:i?"success":"failure",error:o.effects?.status?.error?.message}},events:(o.events??[]).map(s=>({type:s.eventType,parsedJson:s.json,packageId:s.packageId,transactionModule:s.module,sender:s.sender,bcs:"",id:{txDigest:"",eventSeq:"0"}})),results:n.commandResults?.map(s=>({returnValues:s.returnValues.map(c=>[Array.from(c.bcs),"u64"])}))}}})}function Mn(a,e){let t=Po(a),n=new ll.SuiGrpcClient({network:t,baseUrl:e??jt(t)});return $d(n)}var Je=class extends bs.SuiGrpcClient{constructor(e){let t=e.baseUrl??e.url??jt(e.network);super({network:e.network,baseUrl:t})}async getCoins(e){let t=await this.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinType:n.type,coinObjectId:n.objectId,version:n.version,digest:n.digest,balance:n.balance,previousTransaction:"0x0"})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}}async devInspectTransactionBlock(e){let t=typeof e.transactionBlock=="object"&&e.transactionBlock!==null&&"setSenderIfNotSet"in e.transactionBlock?e.transactionBlock:pl.Transaction.from(e.transactionBlock);t.setSenderIfNotSet(e.sender);let n=await this.simulateTransaction({transaction:t,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}}),o=n.$kind==="Transaction"?n.Transaction:n.FailedTransaction,i=o.effects?.status?.success??!1;return{error:i?null:o.effects?.status?.error?.message??"Simulation failed",effects:{status:{status:i?"success":"failure",error:o.effects?.status?.error?.message}},events:(o.events??[]).map(s=>({type:s.eventType,parsedJson:s.json,packageId:s.packageId,transactionModule:s.module,sender:s.sender,bcs:"",id:{txDigest:"",eventSeq:"0"}})),results:n.commandResults?.map(s=>({returnValues:s.returnValues.map(c=>[Array.from(c.bcs),"u64"])}))}}};var ee=async(a,e)=>{let{CetusClmmSDK:t}=await import("@cetusprotocol/sui-clmm-sdk"),n=t.createSDK({env:"mainnet",full_rpc_url:jt("mainnet")});return n.setSenderAddress(e.address),n},Vt=async(a,e)=>{let{CetusFarmsSDK:t}=await import("@cetusprotocol/farms-sdk"),n=t.createSDK({env:"mainnet",full_rpc_url:jt("mainnet")});return n.setSenderAddress(e.address),n},Hd="https://api-sui.cetus.zone/router_v2/find_routes",ml=async(a,e)=>{let{AggregatorClient:t,Env:n}=await import("@cetusprotocol/aggregator-sdk"),o=new Je({baseUrl:jt("mainnet"),network:"mainnet"});return new t({endpoint:Hd,signer:e.address,client:o,env:n.Mainnet})},On=async(a,e)=>{let{CetusVaultsSDK:t}=await import("@cetusprotocol/vaults-sdk"),n=t.createSDK({env:"mainnet",full_rpc_url:jt("mainnet")});return n.setSenderAddress(e.address),n},Ze=async(a,e)=>{let{CetusXcetusSDK:t}=await import("@cetusprotocol/xcetus-sdk"),n=t.createSDK({env:"mainnet",full_rpc_url:jt("mainnet")});return n.setSenderAddress(e.address),n};var dl=async(a,e,t)=>await(await ee(t,e)).Pool.createPoolPayload(a),fl=async(a,e,t)=>await(await ee(t,e)).Position.createAddLiquidityFixTokenPayload(a?.parameter),hl=async(a,e,t)=>await(await ee(t,e)).Position.createAddLiquidityFixTokenPayload(a?.parameter),gl=async(a,e,t)=>await(await ee(t,e)).Position.closePositionPayload(a),yl=async(a,e,t)=>await(await ee(t,e)).Position.removeLiquidityPayload(a),bl=async(a,e,t)=>await(await ee(t,e)).Rewarder.collectRewarderPayload(a);var Ro=class a extends x{constructor(t){super(t);this.data=t}data;txType=Tl.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await fl(i,n,o)}static fromData(t){return new a(t)}};var Sl=require("@msafe/sui3-utils");var Bo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Sl.TransactionType.Other;txSubType="ClaimFeeAndMining";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 wl=require("@msafe/sui3-utils");var Eo=class a extends x{constructor(t){super(t);this.data=t}data;txType=wl.TransactionType.Other;txSubType="CreatePool";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 Il=require("@msafe/sui3-utils");var No=class a extends x{constructor(t){super(t);this.data=t}data;txType=Il.TransactionType.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await yl(i,n,o)}static fromData(t){return new a(t)}};var Rl=require("@msafe/sui3-utils");var Cl=async(a,e,t)=>await(await Vt(t,e)).Farms.openPositionAddLiquidityStakePayload(a),xl=async(a,e,t)=>await(await Vt(t,e)).Farms.addLiquidityFixCoinPayload(a),kl=async(a,e,t)=>await(await Vt(t,e)).Farms.removeLiquidityPayload(a);var Dl=async(a,e,t)=>await(await Vt(t,e)).Farms.removeLiquidityPayload(a),vl=async(a,e,t)=>await(await Vt(t,e)).Farms.claimFeeAndClmmReward(a),Al=async(a,e,t)=>await(await Vt(t,e)).Farms.harvestPayload(a),Ml=async(a,e,t)=>{let n=await Vt(t,e),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},Ol=async(a,e,t)=>await(await Vt(t,e)).Farms.depositPayload(a),Pl=async(a,e,t)=>await(await Vt(t,e)).Farms.withdrawPayload(a);var Wo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Rl.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";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 Bl=require("@msafe/sui3-utils");var _o=class a extends x{constructor(t){super(t);this.data=t}data;txType=Bl.TransactionType.Other;txSubType="FarmingBatchHarvest";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 El=require("@msafe/sui3-utils");var Lo=class a extends x{constructor(t){super(t);this.data=t}data;txType=El.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";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 Nl=require("@msafe/sui3-utils");var jo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Nl.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";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 Wl=require("@msafe/sui3-utils");var Uo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Wl.TransactionType.Other;txSubType="FarmingHarvest";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 _l=require("@msafe/sui3-utils");var qo=class a extends x{constructor(t){super(t);this.data=t}data;txType=_l.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await xl(i,n,o)}static fromData(t){return new a(t)}};var Ll=require("@msafe/sui3-utils");var Fo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Ll.TransactionType.Other;txSubType="FarmingRemoveLiquidity";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 jl=require("@msafe/sui3-utils");var Ko=class a extends x{constructor(t){super(t);this.data=t}data;txType=jl.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 Ul=require("@msafe/sui3-utils");var Go=class a extends x{constructor(t){super(t);this.data=t}data;txType=Ul.TransactionType.Other;txSubType="FarmingUnstake";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 ql=require("@msafe/sui3-utils");var Vo=class a extends x{constructor(t){super(t);this.data=t}data;txType=ql.TransactionType.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await hl(i,n,o)}static fromData(t){return new a(t)}};var Gl=require("@msafe/sui3-utils");var $o=async()=>{let{Transaction:a}=await import("@mysten/sui/transactions");return new a},Xd=async(a,e,t)=>{let n=await On(t,e),o=await $o();return o.setSender(e.address),n.Vest.buildRedeemPayload(a.params,o),o},zd=async(a,e)=>{let{default:t,vaults_mainnet:n}=await import("haedal-vault-sdk"),o=new t(n);o.senderAddress=e.address;let i=await $o();return i.setSender(e.address),await o?.Vest.buildRedeemPayload(a.params,i),i},Fl=async(a,e,t)=>{let n=await ee(t,e),o=await $o();return n?.Vest.buildRedeemPayload(a.params,o),o},Qd=async(a,e,t)=>{let n=await ee(t,e),o=await Vt(t,e),i=await $o(),s=await o.Farms.withdrawReturnPayload(a.withdrawParams,i);return n.Vest.buildRedeemPayload(a.redeemParms.map(c=>({...c,clmm_position_id:s})),i),o.Farms.depositPayload({...a.depositParams,clmm_position_id:s},i),i},Kl=async(a,e,t)=>a.type==="clmm"?Fl(a,e,t):a.type==="farms"?Qd(a,e,t):a.type==="vaults"?Xd(a,e,t):a.type==="haedalVaults"?zd(a,e):Fl(a,e,t);var Ho=class a extends x{constructor(t){super(t);this.data=t}data;txType=Gl.TransactionType.Other;txSubType="PosVestingRedeem";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 Vl=require("@msafe/sui3-utils");var Xo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Vl.TransactionType.Other;txSubType="RemoveLiquidity";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 Xl=require("@msafe/sui3-utils");var $l=require("@mysten/sui/transactions");var Hl=async(a,e,t)=>{let{restituteMsafeFastRouterSwapParams:n}=await import("@cetusprotocol/aggregator-sdk"),o=await ml(t,e),i=new $l.Transaction;return await o.fastRouterSwap({...a,router:n(a.router),txb:i}),i};var zo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Xl.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Hl(i,n,o)}static fromData(t){return new a(t)}};var Yl=require("@msafe/sui3-utils");var Ts=require("@mysten/sui/transactions");var zl=async(a,e,t)=>{let n=await On(t,e),o=new Ts.Transaction;return o.setSender(e.address),await n.Vaults.deposit(a,o),o},Ql=async(a,e,t)=>{let n=await On(t,e),o=new Ts.Transaction;return await n.Vaults.withdraw(a,o),o};var Qo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Yl.TransactionType.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await zl(i,n,o)}static fromData(t){return new a(t)}};var Jl=require("@msafe/sui3-utils");var Yo=class a extends x{constructor(t){super(t);this.data=t}data;txType=Jl.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await Ql(i,n,o)}static fromData(t){return new a(t)}};var nu=require("@msafe/sui3-utils");var tu=require("@mysten/sui/transactions"),Zl={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},eu=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,c=new tu.Transaction;return i.forEach(m=>{c.moveCall({target:`${Zl.published_at}::router::redeem`,typeArguments:[Zl.cetus_coin_type],arguments:[c.object(n),c.object(o),c.pure(m),c.object(s)]})}),c};var Jo=class a extends x{constructor(t){super(t);this.data=t}data;txType=nu.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await eu(i,n,o)}static fromData(t){return new a(t)}};var cu=require("@msafe/sui3-utils");var ou=async(a,e,t)=>await(await Ze(t,e)).XCetusModule.convertPayload(a),au=async(a,e,t)=>await(await Ze(t,e)).XCetusModule.redeemLockPayload(a),iu=async(a,e,t)=>await(await Ze(t,e)).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),ru=async(a,e,t)=>await(await Ze(t,e)).XCetusModule.cancelRedeemPayload(a),su=async(a,e,t)=>await(await Ze(t,e)).XCetusModule.redeemPayload(a);var Zo=class a extends x{constructor(t){super(t);this.data=t}data;txType=cu.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await ru(i,n,o)}static fromData(t){return new a(t)}};var lu=require("@msafe/sui3-utils");var ta=class a extends x{constructor(t){super(t);this.data=t}data;txType=lu.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await iu(i,n,o)}static fromData(t){return new a(t)}};var uu=require("@msafe/sui3-utils");var ea=class a extends x{constructor(t){super(t);this.data=t}data;txType=uu.TransactionType.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await ou(i,n,o)}static fromData(t){return new a(t)}};var pu=require("@msafe/sui3-utils");var na=class a extends x{constructor(t){super(t);this.data=t}data;txType=pu.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await su(i,n,o)}static fromData(t){return new a(t)}};var mu=require("@msafe/sui3-utils");var oa=class a extends x{constructor(t){super(t);this.data=t}data;txType=mu.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:o}=t,{txbParams:i}=this.data;return await au(i,n,o)}static fromData(t){return new a(t)}};var aa=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:du.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=Ro.fromData(e.intentionData);break;case"IncreaseLiquidity":i=Vo.fromData(e.intentionData);break;case"DecreaseLiquidity":i=No.fromData(e.intentionData);break;case"RemoveLiquidity":i=Xo.fromData(e.intentionData);break;case"ClaimFeeAndMining":i=Bo.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":i=Wo.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":i=qo.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":i=jo.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":i=Fo.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":i=Lo.fromData(e.intentionData);break;case"FarmingHarvest":i=Uo.fromData(e.intentionData);break;case"FarmingBatchHarvest":i=_o.fromData(e.intentionData);break;case"FarmingStake":i=Ko.fromData(e.intentionData);break;case"FarmingUnstake":i=Go.fromData(e.intentionData);break;case"xCETUSConvert":i=ea.fromData(e.intentionData);break;case"xCETUSRedeemLock":i=oa.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":i=ta.fromData(e.intentionData);break;case"xCETUSCancelRedeem":i=Zo.fromData(e.intentionData);break;case"xCETUSRedeem":i=na.fromData(e.intentionData);break;case"VestingRedeem":i=Jo.fromData(e.intentionData);break;case"AggregatorSwap":i=zo.fromData(e.intentionData);break;case"AddVaultsPosition":i=Qo.fromData(e.intentionData);break;case"RemoveVaultsPosition":i=Yo.fromData(e.intentionData);break;case"PosVestingRedeem":i=Ho.fromData(e.intentionData);break;case"CreatePool":i=Eo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Xu=require("@msafe/sui3-utils");var fu=Pt(require("sort-keys-recursive")),N=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,fu.default)(this.data))}};var Ss={};ys(Ss,{contractId:()=>Zd,default:()=>af,feeObjId:()=>nf,roleObjId:()=>tf,status:()=>Jd,transaction:()=>Yd,upgradeCapObjId:()=>of,vaultObjId:()=>ef});var Yd="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Jd="success",Zd="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",tf="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",ef="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",nf="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",of="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",af={transaction:Yd,status:Jd,contractId:Zd,roleObjId:tf,vaultObjId:ef,feeObjId:nf,upgradeCapObjId:of};var ws={};ys(ws,{contractId:()=>cf,default:()=>df,feeObjId:()=>pf,roleObjId:()=>lf,status:()=>sf,transaction:()=>rf,upgradeCapObjId:()=>mf,vaultObjId:()=>uf});var rf="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",sf="success",cf="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",lf="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",uf="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",pf="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",mf="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",df={transaction:rf,status:sf,contractId:cf,roleObjId:lf,vaultObjId:uf,feeObjId:pf,upgradeCapObjId:mf};var ff=jt("testnet"),hf=jt("testnet"),gf=jt("mainnet"),yf=jt("mainnet"),bf="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Tf="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Sf="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",wf="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",hu=Ss,gu=ws,If=new Map([["dev",{env:"dev",rpc:{url:ff},backend:{url:bf},contract:hu}],["stg",{env:"stg",rpc:{url:hf},backend:{url:Tf},contract:hu}],["prev",{env:"prev",rpc:{url:gf},backend:{url:Sf},contract:gu}],["prod",{env:"prod",rpc:{url:yf},backend:{url:wf},contract:gu}]]);function yu(a,e){let t=If.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 j=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 ia=class extends j{constructor(){super(11,"Backend is not specified")}};var ra=class extends j{constructor(){super(1,"Wallet not connected")}};var me=Pt(require("axios"));var tn=class extends j{constructor(e,t){super(10,e,{context:t})}};var sa=class a{constructor(e){this.apiURL=e}apiURL;static parseResponseData(e){if(e instanceof me.AxiosError)throw new tn(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new tn(e.data.code)}throw new tn(e.status.toString())}async getIncomingStreams(e,t){let n=await me.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await me.default.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(n)}async getStreamHistory(e){let t=await me.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 me.default.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let n=await me.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(n)}async getAllSenders(e,t){let n=await me.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(n)}};var Cf={dev:"sui:testnet",stg:"sui:testnet",prev:"sui:mainnet",prod:"sui:mainnet"},en=class a{signer;suiClient;envConfig;_backend;constructor(e,t){this.envConfig=e,this.suiClient=t??Mn(Cf[e.env],e.rpc.url),e.backend&&(this._backend=new sa(e.backend.url))}static new(e,t){let n=yu(e,t);return new a(n,t?.suiGrpcClient)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new ia;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 ra;return this.signer}async walletAddress(){return this.wallet.address()}};var je=require("@mysten/sui/utils");var Nn=require("@mysten/sui/transactions");var xs=require("@mysten/sui/transactions"),En=require("@mysten/sui/utils");var Is=50n,ca=10000n,Tu=25n,Cs=100000000n;var de=class{constructor(e){this.object=e}object;moveArg(e){return e.object(this.object)}},la=class{constructor(e){this.objects=e}objects;moveArgs(e){return e.makeMoveVec({elements:this.objects.map(t=>e.object(t))})}},_e=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)}})}result;moveArg(){return this.result}};function Su(a,e){if(typeof e=="bigint"||typeof e=="number")return a.pure.u64(e);if(typeof e=="boolean")return a.pure.bool(e);if(typeof e=="string")return/^0x[0-9a-fA-F]+$/.test(e)?a.pure.address(e):a.pure.string(e);throw new Error(`Unsupported pure argument type: ${typeof e}`)}var Ru=require("@mysten/bcs");var Pn=class extends j{constructor(e,t){super(3,e,{context:t})}};var Cu=require("@mysten/bcs");var ne=class extends j{constructor(e,t){super(6,e,{context:t})}};function ua(a){if(a==null)throw new ne("Missing move object field");if(typeof a=="object"&&"fields"in a){let e=a.fields;if(e&&typeof e=="object")return e}if(typeof a=="object")return a;throw new ne("Unexpected move object field shape",{value:String(a)})}function wu(a){return a.fields&&typeof a.fields=="object"&&!("balance"in a)&&!("config"in a)&&!("status"in a)?a.fields:a}function Iu(a,e="balance"){if(a==null)throw new ne(`Stream object missing ${e} field`);if(typeof a=="string"||typeof a=="number"||typeof a=="bigint")return BigInt(a);let t=ua(a),n=t.balance??t.value;if(n==null)throw new ne(`Stream object ${e} field has unexpected shape`,{value:JSON.stringify(a)});return BigInt(String(n))}async function xu(a,e){let t=await a.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinObjectId:n.objectId,balance:n.balance,coinType:n.type})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}}function xf(a){return a.core?.getObject?a.core.getObject.bind(a.core):a.getObject.bind(a)}function ku(a){return a.json&&typeof a.json=="object"?wu(a.json):null}async function Du(a,e){try{let t=xf(a),{object:n}=await t({objectId:e,include:{json:!0,type:!0}}),o=ku(n);return o?{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}:{error:{code:"notExists"}}}catch{return{error:{code:"notExists"}}}}async function vu(a,e){if(e.length===0)return[];let{objects:t}=await a.getObjects({objectIds:e,include:{json:!0,type:!0}});return t.map(n=>{if(!("objectId"in n))return{error:{code:String(n.code??"unknown")}};let o=ku(n);if(o)return{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}})}async function Au(a,e){let{balance:t}=await a.getBalance({owner:e.owner,coinType:e.coinType??void 0});return{coinType:t.coinType,totalBalance:t.balance}}async function Mu(a,e){return(await a.listBalances({owner:e})).balances.map(n=>({coinType:n.coinType,totalBalance:n.balance}))}async function Ou(a,e){let{coinMetadata:t}=await a.getCoinMetadata({coinType:e});return t}async function pa(a,e){e.transaction.setSenderIfNotSet(e.sender);let t=await a.simulateTransaction({transaction:e.transaction,include:{effects:!0,commandResults:!0}}),n=t.$kind==="Transaction"?t.Transaction:t.FailedTransaction;return{effects:n.effects?{status:{status:n.effects.status.success?"success":"failure",error:n.effects.status.error?.message}}:void 0,commandResults:t.commandResults,results:t.commandResults?.map(o=>({returnValues:o.returnValues.map(i=>[Array.from(i.bcs),"u64"])}))}}function Pu(a,e=0,t=0){let n=a.commandResults?.[e]?.returnValues?.[t];if(!n)throw new Error("Missing command result");return BigInt(Cu.bcs.u64().parse(n.bcs))}var ma=class{constructor(e){this.results=e}results;getU64(e=0,t=0){try{return Pu(this.results,e,t)}catch{let[n,o]=this.getLegacyValue(e,t);if(o!=="u64")throw new Pn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Ru.bcs.u64().parse(Uint8Array.from(n))}}getLegacyValue(e=0,t=0){let o=this.results.results?.[e]?.returnValues;if(!o?.[t])throw new Pn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:"missing"}});return o[t]}};var da=require("@mysten/bcs");var z=class extends j{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var Eu=da.bcs.struct("StreamMetadata",{groupId:da.bcs.string(),name:da.bcs.string()}),kf=64;function Nu(a){return Wu(a),Eu.serialize(a).toBase64()}function Rn(a){let e=Eu.fromBase64(a);return Wu(e),e}function Wu(a){if(!Bu(a.name))throw new z("Invalid metadata: Name contains unknown character");if(!Bu(a.groupId))throw new z("Invalid metadata: Group ID contains unknown character");if(a.name.length>kf)throw new z("Invalid metadata: Name exceed max length 64")}function Bu(a){return/^[\x00-\x7F]+$/.test(a)}var Bn=require("@mysten/sui/utils");function fa(a,e){return(0,Bn.normalizeStructTag)(a)===(0,Bn.normalizeStructTag)(e)}function Ce(a,e){return(0,Bn.normalizeStructTag)(a)===(0,Bn.normalizeStructTag)(e)}function xe(a){if(a.$kind!=="MoveCall"||!a.MoveCall)return null;let{package:e,module:t,function:n}=a.MoveCall;return`${e}::${t}::${n}`}var ha="txn.gas";var _u=require("nanoid");function Lu(){return(0,_u.nanoid)()}var Le=class a{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}globals;feeContract;streamContract;static convertCreateStreamInfoToInternal(e){return{metadata:Nu({name:e.name,groupId:Lu()}),coinType:(0,En.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 xs.Transaction,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),i=await this.wallet.requestCoins(o),s=await this.addMergeCoins(t,i[0]),c;o.length>1?c=await this.addMergeCoins(t,i[1]):c=s;for(let m=0;m<e.recipients.length;m++){let b=e.recipients[m],S=this.amountForRecipient(b,e.numberEpoch),w=this.getStreamFeeLocal(S),[C]=t.splitCoins(s,[t.pure.u64(S+w)]),[k]=t.splitCoins(c,[t.pure.u64(this.flatSuiFee)]);this.streamContract.createStream(t,{paymentCoin:new _e(C),flatFeeCoin:new _e(k),metadata:e.metadata,recipient:b.address,timeStart:e.startTime,cliff:b.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:b.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:Is,denominator:ca},claimFeePercent:{numerator:Tu,denominator:ca},flatFeePerStream:Cs}}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===ha?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return fa(n,En.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:En.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,i)=>{let s=this.amountForRecipient(i,e.numberEpoch),c=this.getStreamFeeLocal(s);return{totalAmount:o.totalAmount+s,streamFeeAmount:o.streamFeeAmount+c}},{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 Cs}getStreamFeeLocal(e){return e*Is/ca}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new xs.Transaction,e),n=await pa(this.globals.suiClient,{sender:await this.globals.walletAddress(),transaction:t});return new ma(n).getU64()}get wallet(){return this.globals.wallet}};var ju="0x0000000000000000000000000000000000000000000000000000000000000006";var nn=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}moduleName;config;globals;addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.moveCall({target:n,arguments:t.arguments.map(o=>o instanceof la?o.moveArgs(e):o instanceof de?o.moveArg(e):o instanceof _e?o.moveArg():Su(e,o)),typeArguments:t.typeArgs}),e}makeObject(e){return typeof e=="string"?new de(e):e}vaultObject(){return new de(this.config.vaultObjId)}roleObject(){return new de(this.config.roleObjId)}feeObject(){return new de(this.config.feeObjId)}clockObject(){return new de(ju)}};var on=class a extends nn{constructor(t,n){super(a.ModuleName,t,n);this.config=t;this.globals=n}config;globals;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 oe=class a extends nn{constructor(t,n){super(a.ModuleName,t,n);this.config=t;this.globals=n}config;globals;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),c=this.makeObject(n.flatFeeCoin),m=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[o,i,s,c,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,m],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(),c=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,i,s,c],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 an=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new on(t,e),this.streamContract=new oe(t,e)}globals;feeContract;streamContract;async createStreams(e){let t=Le.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new Le(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new Nn.Transaction;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new Nn.Transaction;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new Nn.Transaction;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new Nn.Transaction;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};var rn=require("@mysten/sui/utils"),ks=require("luxon");var ga=class extends j{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var Df=1e3,ya=class{constructor(e){this.globals=e;this.coinMetaHelper=new Ds(e.suiClient),this.createStreamHelper=new an(e).createStreamHelper()}globals;coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new ga(e.effects?.status.status,e.effects?.status.error);return Object.entries(e.objectTypes??{}).filter(([,t])=>t.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(([t])=>t)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new z("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 z("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 z("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(ks.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:ks.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await Au(this.globals.suiClient,{owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:(0,rn.normalizeStructTag)(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await Mu(this.globals.suiClient,e),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,i)=>({...o,coinType:(0,rn.normalizeStructTag)(o.coinType),coinMeta:n[i]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return pa(this.globals.suiClient,{transaction:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new z("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new z("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<Df)throw new z("Interval shall be at least 1 second","interval",e.interval)}},Ds=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}suiClient;coinMetaReg;async getCoinMeta(e){let t=(0,rn.normalizeStructTag)(e||rn.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??void 0}async queryCoinMeta(e){return Ou(this.suiClient,e)}};var De=require("@mysten/sui/utils"),Bs=require("luxon");var _n=require("@mysten/sui/transactions"),Ln=require("@mysten/sui/utils"),qu=require("luxon");var ba=class extends j{constructor(){super(7,"Connected wallet is not creator")}};var Wn=class extends j{constructor(){super(8,"Connected wallet is not recipient")}};var Et=class extends j{constructor(e,t={}){super(0,e,t)}};var Ta=class extends j{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};var wa=require("luxon"),Uu=(1n<<64n)-1n,Sa=1e3;function vs(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/Sa);return wa.DateTime.fromMillis(t*Sa)}function As(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/Sa);return wa.Duration.fromMillis(t*Sa)}var ke=class a{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new oe(e.envConfig.contract,e)}globals;streamId;rawData;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 Et("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 ba;let e=new _n.Transaction;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Wn;let e=new _n.Transaction;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Wn;let t=new _n.Transaction;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new _n.Transaction;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,Ln.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 As(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Rn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Rn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return vs(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return As(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:vs((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===Uu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=qu.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 Du(e.suiClient,t);return a.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new Ta(e):new ne(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data?.content;if(!n||n.dataType!=="moveObject")throw new ne("Unexpected object type",{gotType:n?.dataType});let{typeParams:o}=(0,Ln.parseStructTag)(n.type),i=(0,Ln.normalizeStructTag)(o[0]),s=n.fields,c=ua(s.config),m=ua(s.status);return{coinType:i,autoClaim:s.auto_claim,balance:Iu(s.balance),config:{amountPerEpoch:BigInt(String(c.amount_per_epoch)),cancelable:c.cancelable,cliff:BigInt(String(c.cliff)),creator:String(c.creator),epochInterval:BigInt(String(c.epoch_interval)),metadata:String(c.metadata),recipient:String(c.recipient),timeStart:BigInt(String(c.time_start)),totalEpoch:BigInt(String(c.total_epoch))},status:{status:m.status,epochCanceled:BigInt(String(m.epoch_canceled)),epochClaimed:BigInt(String(m.epoch_claimed))}}}};var sn=class extends j{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 Ms=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}requester;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)}},cn=class{constructor(e){this.requester=e;this.pager=new Ms(e),this.curData=[],this.cursor=0}requester;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 vf=25;async function Rs(a,e,t){let n=new jn(e),o=new Un(a,n,t);return await Os(o)}var jn=class{constructor(e){this.ids=e;this.cursor=-1}ids;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]}},Un=class extends cn{constructor(t,n,o){super(new Ps(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}suiClient;idIter;options},Ps=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||vf,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}suiClient;stringIter;options;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 vu(this.suiClient,e),n;if(this.filter){let{filter:o}=this;n=t.filter(i=>!!i&&o(i))}else n=t.filter(o=>!!o);return{data:n,hasNext:await this.stringIter.hasNext()}}};var Ia=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new sn("stream size 0");let n=t.map(i=>i.groupId);if(new Set(n).size!==1)throw new z("Stream does not have same group ID")}globals;streams;type="StreamGroup";static async new(e,t){let n=await Rs(e.suiClient,t);return n.forEach(o=>{if(!o)throw new Et("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=>{Af(n,i)||(o=!1)}),o}async refresh(){let e=await Rs(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)=>ke.fromObjectData(e,t[s],i)).filter(i=>!!i);if(new Set(o.map(i=>i.groupId)).size!==1)throw new sn("Not same group ID");if(!this.checkStreamGroup(o))throw new sn("Not same stream settings");return o}};function Af(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 qn=class a{constructor(e,t){this.it=e;this.pageSize=t}it;pageSize;static async newIncoming(e){let t=await Ca.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await Ca.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}},Ca=class a{constructor(e){this.requester=e}requester;cachedNext;static async newIncoming(e){let t=await xa.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await xa.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 Et("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Et("No more results");return e}},xa=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 jn(n.flat().map(s=>s.streamId));this.objectIter=new Un(e.suiClient,i)}globals;recipient;groupRefs;query;current=0;objectIter;static async newIncomingQuery(e){let t=Bf(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,t)).filter(c=>(0,De.normalizeSuiAddress)(c.recipient)===(0,De.normalizeSuiAddress)(n)),s=Fu(i);return new a(e.globals,n,s,e.query)}static async newOutgoingQuery(e){let t=Ef(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),i=Fu(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 Pf(this.globals,e[0].streamId,this.objectIter);return this.current++,Ku(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await Rf(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Of(t,this.query)?t:this.doNextRequest()}throw new Et("Stream group with no stream")}};function Fu(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)=>Bs.DateTime.fromISO(n[0].createDate).toMillis()-Bs.DateTime.fromISO(t[0].createDate).toMillis())}function Ku(a,e){if(e===void 0)return!0;let t=Mf(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 Mf(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function Of(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(n=>{Ku(n,e)&&(t=!0)}),t}async function Pf(a,e,t){let n=await Gu(t,e);return ke.fromObjectData(a,e,n)}async function Rf(a,e,t){let n=[];for(;n.length<e.length;){let o=await Gu(t,e[n.length]);n.push(o)}return Ia.newFromObjectResponse(a,e,n)}async function Gu(a,e){if(!await a.hasNext())throw new Et("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new Et("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new Et("stream id not aligned");return t}function Bf(a){return{status:Es(a?.status),coinType:Vu(a?.coinType),sender:$u(a?.sender)}}function Ef(a){return{status:Es(a?.status),coinType:Vu(a?.coinType),recipient:$u(a?.recipient)}}function Es(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let n=Es(t);return!e||e===n?n:"all"},void 0):Nf(a)}function Nf(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new z("Unknown stream filtered status")}}function Vu(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,De.normalizeStructTag)(e)):void 0:(0,De.normalizeStructTag)(a)}function $u(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>(0,De.normalizeSuiAddress)(e)):void 0:(0,De.normalizeSuiAddress)(a)}var ka=class extends j{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}coinType;requestAmount;gotAmount};var Wf=25;async function Hu(a,e,t,n="0x2::sui::SUI",o=Wf){let i=new Ns(a,e,n,o),s=BigInt(0),c=[];for(;await i.hasNext()&&s<t;){let m=await i.next();m&&(c.push(m),s+=BigInt(m.balance))}if(s<t)throw new ka(n,t,s);return c}var Ns=class extends cn{constructor(t,n,o,i){super(new Ws(t,n,o,i));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=i}suiClient;owner;coinType;reqPageSize},Ws=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new Et("Invalid reqPageSize")}suiClient;owner;coinType;reqPageSize;nextCursor;async doNextRequest(){let e=await xu(this.suiClient,{owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var _s=class{constructor(e){this.msafe=e}msafe;get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Da=class{constructor(e){this.account=e}account;async address(){return this.account.address}},Ls=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}singleWallet;suiClient;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(fa(e.coinType,je.SUI_TYPE_ARG))return{primaryCoin:ha};if(e.amount<=0)throw new z("Invalid coin request","coinAmount",e.amount);let t=await Hu(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new Et("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},va=class{globals;helper;constructor(e,t){this.globals=en.new(e,t),this.helper=new ya(this.globals)}connectSingleWallet(e){let t=new Ls(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new _s(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ke.new(this.globals,e)}async getIncomingStreams(e,t=10){return qn.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return qn.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,je.normalizeStructTag)(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>(0,je.normalizeSuiAddress)(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>(0,je.normalizeSuiAddress)(o))}get wallet(){return this.globals.wallet}builder(){return new an(this.globals)}};var Ht=class extends N{application="mpay";getClient(e,t,n){let o=new va(e==="sui:mainnet"?"prod":"dev",{suiGrpcClient:n});return o.connectSingleWallet(new Da(t)),o}};var Fn=class extends Ht{constructor(t){super(t);this.data=t}data;txType=Xu.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:n,account:o,suiGrpcClient:i}=t;return(await this.getClient(n,o,i).getStream(this.data.streamId)).cancel()}};var zu=require("@msafe/sui3-utils");var Kn=class extends Ht{constructor(t){super(t);this.data=t}data;txType=zu.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o,suiGrpcClient:i}=t;return(await this.getClient(n,o,i).getStream(this.data.streamId)).claimByProxy()}};var Qu=require("@msafe/sui3-utils");var Gn=class extends Ht{constructor(t){super(t);this.data=t}data;txType=Qu.TransactionType.Stream;txSubType="Claim";async build(t){let{network:n,account:o,suiGrpcClient:i}=t;return(await this.getClient(n,o,i).getStream(this.data.streamId)).claim()}};var Yu=require("@msafe/sui3-utils");var Vn=class extends Ht{constructor(t){super(t);this.data=t}data;txType=Yu.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o,suiGrpcClient:i}=t;return this.getClient(n,o,i).createStream(this.data)}};var Ju=require("@mysten/bcs"),qe=require("@mysten/sui/bcs"),ln=require("@mysten/sui/utils");function $n(a){if(!a.Pure)throw new Error("not pure argument");return(0,Ju.fromBase64)(a.Pure.bytes)}var un=class a{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get moveCallData(){if(this.moveCall.$kind!=="MoveCall")throw new Error("not move call command");return this.moveCall.MoveCall}get inputs(){return this.txb.getData().inputs}getInputIndex(e){let t=this.moveCallData.arguments[e];if(t.$kind!=="Input")throw new Error("not input type");return t.Input}getInputParam(e){return this.inputs[this.getInputIndex(e)]}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.getInputParam(e);return BigInt(qe.bcs.U64.parse($n(t)))}decodeInputAddress(e){let t=this.getInputParam(e);return(0,ln.normalizeSuiAddress)(qe.bcs.Address.parse($n(t)))}decodeInputString(e){let t=this.getInputParam(e);return qe.bcs.String.parse($n(t))}decodeInputBool(e){let t=this.getInputParam(e);return qe.bcs.Bool.parse($n(t))}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}static getPureInputValue(e,t){return a.getPureInput(e,t)}static getOwnedObjectId(e){let t=e.Object?.ImmOrOwnedObject?.objectId??e.Object?.Receiving?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not object argument: ${JSON.stringify(e)}`);return(0,ln.normalizeSuiAddress)(t)}static getSharedObjectId(e){let t=e.Object?.SharedObject?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not shared object argument: ${JSON.stringify(e)}`);return(0,ln.normalizeSuiAddress)(t)}static getPureInput(e,t){return(0,qe.pureBcsSchemaFromTypeName)(t).parse($n(e))}typeArg(e){return(0,ln.normalizeStructTag)(this.moveCallData.typeArguments[e])}txArg(e){return this.moveCallData.arguments[e]}};var Aa=class{constructor(e,t){this.globals=e;this.txb=t}globals;txb;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.commands.filter(t=>t.$kind==="MoveCall"&&Ce(xe(t),this.contract.createStreamTarget));if(e.length===0)throw new Et("No create stream transactions");return e.map(t=>new un(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=Rn(t),i=e.decodeInputAddress(5),s=e.decodeInputU64(6),c=e.decodeInputU64(7),m=e.decodeInputU64(8),b=e.decodeInputU64(9),S=e.decodeInputU64(10),w=e.decodeInputBool(11),C=e.typeArg(0);return{name:n,groupId:o,recipient:i,timeStart:s,cliff:c,epochInterval:m,totalEpoch:b,amountPerEpoch:S,cancelable:w,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 z("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}}get commands(){return this.txb.getData().commands}get contract(){return new oe(this.globals.envConfig.contract,this.globals)}get feeContract(){return new on(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Le(this.globals,this.feeContract,this.contract)}};var Ma=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new oe(e.envConfig.contract,e)}globals;txb;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 commands(){return this.txb.getData().commands}isCreateStreamTransaction(){return this.commands.findIndex(t=>t.$kind==="MoveCall"&&Ce(xe(t),this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Aa(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.commands[0];if(e.$kind!=="MoveCall")throw new Error("MoveCall not found");return new un(e,this.txb)}};var Zu=require("@msafe/sui3-utils");var Hn=class extends Ht{constructor(t){super(t);this.data=t}data;txType=Zu.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o,suiGrpcClient:i}=t;return(await this.getClient(n,o,i).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Oa=class{application="mpay";supportSDK="@mysten/sui-v2";async deserialize(e){let{network:t,transaction:n,suiGrpcClient:o}=e,i=en.new(t==="sui:mainnet"?"prod":"dev",{suiGrpcClient:o}),c=new Ma(i,n).decode(),m;switch(c.type){case"CreateStream":m=new Vn(c.info);break;case"SetAutoClaim":m=new Hn({streamId:c.streamId,enabled:c.enabled});break;case"Claim":m=new Gn({streamId:c.streamId});break;case"ClaimByProxy":m=new Kn({streamId:c.streamId});break;case"Cancel":m=new Fn({streamId:c.streamId});break;default:throw new Error(`Unknown transaction type: ${c}`)}return{txType:m.txType,txSubType:m.txSubType,intentionData:m.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Vn(t);break;case"Claim":n=new Gn(t);break;case"ClaimByProxy":n=new Kn(t);break;case"SetAutoClaim":n=new Hn(t);break;case"Cancel":n=new Fn(t);break;default:throw new Error("not implemented")}return n.build({...e})}};var Xn=require("@msafe/sui3-utils");var tp=require("@msafe/sui3-utils");var Pa=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiGrpcClient:n,account:o}=t;return(0,tp.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var ep=require("@msafe/sui3-utils");var Ra=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiGrpcClient:n,account:o}=t;return(0,ep.buildObjectTransferTxb)(n,this.data,o.address)}static fromData(t){return new a(t)}};var Ba=class{application="msafe-core";supportSDK="@mysten/sui-v2";constructor(){this.application=Xn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{account:t,network:n,suiGrpcClient:o}=e,i;switch(e.txSubType){case Xn.TransactionSubTypes.assets.coin.send:i=Pa.fromData(e.intentionData);break;case Xn.TransactionSubTypes.assets.object.send:i=Ra.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiGrpcClient:o,account:t,network:n})}};var Fs=require("@msafe/sui3-utils");var np=!1,zn={ProtocolPackage:"0x1e4a13a0494d5facdbe8473e74127b838c2d446ecec0ce262e2eddafa77259cb",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 js(){if(!np)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&&(zn.ProtocolPackage=e),t&&(zn.borrowFee=t),n&&(zn.borrowFeeAddress=n),o&&(zn.pool=o),np=!0}catch(a){console.error(a.message)}}var ae=zn;var ve=require("@msafe/sui3-utils"),Xt=require("@mysten/bcs"),pn=require("@mysten/sui/utils");function Ea(a){if(a.$kind!=="MoveCall")return null;let{package:e,module:t,function:n}=a.MoveCall;return`${e}::${t}::${n}`}var Na=class{constructor(e){this.txb=e}txb;decode(){if(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 commands(){return this.txb.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>Ea(t)===e)}isClaimRewardTransaction(){return this.commands.some(e=>e.$kind==="MoveCall"&&e.MoveCall.function.includes("claim_reward"))}isEntryBorrowTransaction(){return!!this.getMoveCallCommand(`${ae.ProtocolPackage}::incentive_v3::entry_borrow_v2`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallCommand(`${ae.ProtocolPackage}::incentive_v3::borrow_v2`)}isEntryMultiDepositTransaction(){let e=`${ae.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.commands.filter(o=>Ea(o)===e);return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.function.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${ae.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.commands.filter(o=>Ea(o)===e);return!!(this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.function.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallCommand(`${ae.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallCommand(`${ae.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallCommand(`${ae.ProtocolPackage}::incentive_v3::withdraw_v2`)}decodeEntryClaimAndDeposit(){return{txType:ve.TransactionType.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return{txType:ve.TransactionType.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${ae.ProtocolPackage}::incentive_v3::entry_deposit`;return this.commands.forEach(n=>{if(Ea(n)===t){let o=new Wa(n,this.txb),i=o.decodeInputU8(3),s=o.decodeInputU64(5);e.push({assetId:i,amount:s})}}),{txType:ve.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:ve.TransactionType.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.package===ae.ProtocolPackage);if(!e)throw new Error("MoveCall not found");return new Wa(e,this.txb)}},Wa=class a{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get moveCallData(){if(this.moveCall.$kind!=="MoveCall")throw new Error("not move call command");return this.moveCall.MoveCall}get inputs(){return this.txb.getData().inputs}getInputIndex(e){let t=this.moveCallData.arguments[e];if(t.$kind!=="Input")throw new Error("not input type");return t.Input}getInputParam(e){return this.inputs[this.getInputIndex(e)]}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.getInputParam(e);return Number(Xt.bcs.u64().parse(Uint8Array.from((0,Xt.fromBase64)(t.Pure.bytes))))}decodeInputU8(e){let t=this.getInputParam(e);return Number(Xt.bcs.u8().parse(Uint8Array.from((0,Xt.fromBase64)(t.Pure.bytes))))}decodeInputAddress(e){let t=this.getInputParam(e);return(0,pn.normalizeSuiAddress)(Xt.bcs.Address.parse(Uint8Array.from((0,Xt.fromBase64)(t.Pure.bytes))))}decodeInputString(e){let t=this.getInputParam(e);return Xt.bcs.string().parse(Uint8Array.from((0,Xt.fromBase64)(t.Pure.bytes)))}decodeInputBool(e){let t=this.getInputParam(e);return Xt.bcs.bool().parse(Uint8Array.from((0,Xt.fromBase64)(t.Pure.bytes)))}static getOwnedObjectId(e){let t=e.Object?.ImmOrOwnedObject?.objectId??e.Object?.Receiving?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not object argument: ${JSON.stringify(e)}`);return(0,pn.normalizeSuiAddress)(t)}static getSharedObjectId(e){let t=e.Object?.SharedObject?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not shared object argument: ${JSON.stringify(e)}`);return(0,pn.normalizeSuiAddress)(t)}typeArg(e){return(0,pn.normalizeStructTag)(this.moveCallData.typeArguments[e])}txArg(e){return this.moveCallData.arguments[e]}};var Us=require("@mysten/sui/transactions"),Kt=require("@naviprotocol/lending");async function mn(a,e,t,n){return await(0,Kt.depositCoinPTB)(a,e,t,{amount:n}),a}async function op(a,e,t,n){let[o]=await(0,Kt.withdrawCoinPTB)(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function ap(a,e,t,n){let[o]=await(0,Kt.borrowCoinPTB)(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function qs(a,e,t,n){return await(0,Kt.repayCoinPTB)(a,e,t,{amount:n}),a}async function ip(a,e){let t=new Us.Transaction,n=await(0,Kt.getUserAvailableLendingRewards)(e,{client:a});return await(0,Kt.claimLendingRewardsPTB)(t,n),t}async function rp(a,e){let t=new Us.Transaction,n=await(0,Kt.getUserAvailableLendingRewards)(e,{client:a});return await(0,Kt.claimLendingRewardsPTB)(t,n,{customCoinReceive:{type:"depositNAVI",depositNAVI:{fallbackReceiveAddress:e}}}),t}var _a=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await ip(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var La=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await rp(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var cp=require("@mysten/sui/transactions");var sp=require("@naviprotocol/lending");async function ie(a){return(0,sp.getPool)(a)}var ja=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new cp.Transaction;console.log("build",this.data);let s=await ie(n);return await ap(i,s,o,t.account.address)}static fromData(t){return new a(t)}};var lp=require("@mysten/sui/transactions");async function dn(a,e,t){let n=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Ua=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:s}=this.data,c=new lp.Transaction;console.log("build",this.data);let m=await ie(i);if(i===0){let[C]=c.splitCoins(c.gas,[s]);return await mn(c,m,C,s)}let b=await dn(n,o.address,m.suiCoinType);if(!b.data[0])throw new Error(`Insufficient balance for ${m.suiCoinType} Token`);let S=b.data[0].coinObjectId;if(b.data.length>=2){let C=1;for(;C<b.data.length;)c.mergeCoins(S,[b.data[C].coinObjectId]),C++}return await mn(c,m,c.object(S),s)}static fromData(t){return new a(t)}};var up=require("@mysten/sui/transactions");var qa=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:i,amount:s}=this.data,c=new up.Transaction;console.log("build",this.data);let m=await ie(i);if(i===0){let[w]=c.splitCoins(c.gas,[s]);return qs(c,m,w,s)}let b=await dn(n,o.address,m.suiCoinType);if(!b.data[0])throw new Error(`Insufficient balance for ${m.suiCoinType} Token`);let S=b.data[0].coinObjectId;if(b.data.length>=2){let w=1;for(;w<b.data.length;)c.mergeCoins(S,[b.data[w].coinObjectId]),w++}return qs(c,m,c.object(S),s)}static fromData(t){return new a(t)}};var pp=require("@mysten/sui/transactions");var Fa=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,i=new pp.Transaction;console.log("build",this.data);let s=await ie(n);return await op(i,s,o,t.account.address)}static fromData(t){return new a(t)}};var mp=require("@mysten/sui/transactions");var Ka=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:i}=this.data,s=new mp.Transaction;console.log("build",this.data);for(let c=0;c<i.length;c++){let{assetId:m,amount:b}=i[c],S=await ie(m);if(m===0){let[k]=s.splitCoins(s.gas,[b]);await mn(s,S,k,b);continue}let w=await dn(n,o.address,S.suiCoinType);if(!w.data[0])throw new Error(`Insufficient balance for ${S.suiCoinType} Token`);let C=w.data[0].coinObjectId;if(w.data.length>=2){let k=1;for(;k<w.data.length;)s.mergeCoins(C,[w.data[k].coinObjectId]),k++}await mn(s,S,s.object(C),b)}return s}static fromData(t){return new a(t)}};var dp=require("@mysten/sui/transactions");var Ga=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return console.log("build",this.data),dp.Transaction.from(this.data.content)}static fromData(t){return new a(t)}};var Va=class{application="navi";supportSDK="@mysten/sui";async deserialize(e){if(await js(),e.appContext?.content)return{txType:Fs.TransactionType.Other,txSubType:"PlainTransaction",intentionData:{content:e.appContext.content,scene:e.appContext.scene||"unknown"}};let{transaction:t}=e,o=new Na(t).decode();return{txType:Fs.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await js(),e.txSubType){case"EntryDeposit":o=Ua.fromData(e.intentionData);break;case"EntryBorrow":o=ja.fromData(e.intentionData);break;case"EntryRepay":o=qa.fromData(e.intentionData);break;case"EntryWithdraw":o=Fa.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Ka.fromData(e.intentionData);break;case"ClaimReward":o=_a.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=La.fromData(e.intentionData);break;case"PlainTransaction":o=Ga.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Qn=require("@msafe/sui3-utils"),fp=require("@mysten/bcs"),hp=require("@mysten/sui/transactions"),gp=Pt(require("sort-keys-recursive")),yp="msafe-plain-tx",bp=Qn.TransactionSubTypes.others.plain,Ks=class a{constructor(e){this.data=e}data;application=yp;txType=Qn.TransactionType.Other;txSubType=bp;serialize(){return JSON.stringify((0,gp.default)(this.data))}async build(e){return hp.Transaction.from((0,fp.fromHex)(this.data.content))}static fromData(e){return new a(e)}},$a=class{application;supportSDK="@mysten/sui";constructor(){this.application=yp}async deserialize(e){let{content:t}=e.appContext;return{txType:Qn.TransactionType.Other,txSubType:bp,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:o}=e;return Ks.fromData(e.intentionData).build({suiClient:t,network:n,account:o})}};var Fe=require("@mysten/sui/transactions"),Sp=require("@mysten/sui.js/client");var fn=require("@open-rpc/client-js");var Lf={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},Gs=class extends Error{},Ha=class extends Gs{code;type;constructor(e,t){super(e),this.code=t,this.type=Lf[t]??"ServerError"}};function jf(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var Uf={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Xa=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={...Uf,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=jf(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 Ha(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 Vs(e);return this.#i.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},Vs=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 za=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:o}){let i=new fn.HTTPTransport(o?.url??e,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new fn.Client(new fn.RequestManager([i])),this.websocketClient=new Xa(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()}};function Tp(a,e){return new Je({network:Po(a),baseUrl:e})}var wp="0x2::sui::SUI",Qs=1e8;function $s(a){return new Sp.SuiClient({transport:new za({url:a,rpc:{url:a}})})}async function Ip(a,e){if((0,Fe.isTransaction)(a))return a;let t=$s(e),n=await a.build({client:t});return Fe.Transaction.from(n)}var Qa=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;case"@mysten/sui-v2":t.addGrpcHelper(o);break;default:{let i=o;throw new Error(`${i.application}: ${i.supportSDK} SDK not supported`)}}}return t}addLegacyHelper(e){this.setApp(e.application,new zs(e))}addHelper(e){this.setApp(e.application,new Hs(e))}addGrpcHelper(e){this.setApp(e.application,new Xs(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}setApp(e,t){this.apps.set(e,t)}},Hs=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=Tp(e.network,e.clientUrl),n=await Ip(e.transactionBlock,e.clientUrl);return this.helper.deserialize({...e,suiClient:t,transaction:n})}async build(e){let t=Tp(e.network,e.clientUrl),{balance:n}=await t.getBalance({owner:e.account.address,coinType:wp});if(Number(n.balance)<Qs)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 Fe.Transaction.from(i)}},Xs=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=Mn(e.network,e.clientUrl),n=await Ip(e.transactionBlock,e.clientUrl);return this.helper.deserialize({...e,suiGrpcClient:t,transaction:n})}async build(e){let t=Mn(e.network,e.clientUrl),{balance:n}=await t.core.getBalance({owner:e.account.address,coinType:wp});if(Number(n.balance)<Qs)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiGrpcClient:t});o.setSender(e.account.address);let i=await o.build({client:t});return Fe.Transaction.from(i)}},zs=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=$s(e.clientUrl);return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=$s(e.clientUrl),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<Qs)throw new Error("Insufficient gas fee");let i=await(await this.helper.build({...e,suiClient:t})).build({client:t});return Fe.Transaction.from(i)}};var Rp=require("@msafe/sui3-utils"),Bp=require("@scallop-io/sui-scallop-sdk");var Nt=require("@msafe/sui3-utils"),Zs=require("@scallop-io/sui-scallop-sdk");var Cp=require("@mysten/sui/utils"),Ae=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}`))}transaction;scallopClient;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,Cp.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,c)=>(i[s]=c,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 Ya=require("@mysten/sui/bcs"),Me=require("@mysten/sui/utils"),Ys=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 c=`${i.MoveCall.package}::${i.MoveCall.module}::${i.MoveCall.function}`,m=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return c===m?(o.push(s),!0):!1}return!1}),this.cmdIdx=o[n]}moveCall;transaction;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,Me.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"&&t.kind!=="Result")throw new Error("not nested or result 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=Ya.bcs[t];return Ya.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,Me.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Me.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,Me.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Me.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 Ya.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Me.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},_=Ys;var Js=class{constructor(e,t){this.splitCoin=e;this.txb=t}splitCoin;txb;getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(_.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Ut=Js;var Oe=require("@mysten/sui/utils"),xp=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`},hn={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},zt={unstakeObligation:(a,e,t)=>a.moveCall(`${hn.id}::user::unstake`,[hn.incentivePools,hn.incentiveAccounts,a.object(e),a.object(t),Oe.SUI_CLOCK_OBJECT_ID],[(0,Oe.normalizeStructTag)(Oe.SUI_TYPE_ARG)]),redeem_rewards:(a,e,t,n)=>a.moveCall(`${hn.id}::user::redeem_rewards`,[hn.incentivePools,hn.incentiveAccounts,a.object(e),a.object(t),Oe.SUI_CLOCK_OBJECT_ID],[(0,Oe.normalizeStructTag)(n)])};var kp=(a,e)=>{let t=[];for(let n=0;n<a.length;n+=e)t.push(a.slice(n,n+e));return t};var Ja=class extends Ae{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(`${Zs.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 _(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new _(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 _(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Zs.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`)).map(t=>new _(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new _(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new _(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new _(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new _(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 _(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new _(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new _(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new _(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new _(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new _(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new _(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new _(e,this.transaction)}decodeMigrateScoin(){return{txType:Nt.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:Nt.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Nt.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Ut(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Nt.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 Ut(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Nt.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperBurnScoin.getNestedInputParam(1),n=new Ut(t,this.transaction).getAmountInput().reduce((o,i)=>o+i,0);return{txType:Nt.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 Ut(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Nt.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:Nt.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:Nt.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:Nt.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:Nt.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 Ut(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Nt.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 Ut(n,this.transaction).getAmountInput().reduce((s,c)=>s+c,0),i=this.helperRepay.decodeSharedObjectId(1);return{txType:Nt.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 Ut(i,this.transaction).getAmountInput().reduce((s,c)=>s+c,0)}if(this.helperStake.moveCall&&t===0){let i=this.helperStake.getNestedInputParam(2);t=new Ut(i,this.transaction).getAmountInput().reduce((s,c)=>s+c,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Nt.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:Nt.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 Ut(t,this.transaction).getAmountInput().reduce((i,s)=>i+s,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Nt.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 Ut(o,this.transaction).getAmountInput().reduce((i,s)=>i+s,0)}return{txType:Nt.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),c=this.utils.parseCoinNameFromType(s);e.push({stakeMarketCoinName:c,stakeAccountId:i})}),this.helperClaimBorrowV2Reward.forEach(o=>{let i=o.decodeSharedObjectId(4),s=o.decodeOwnedObjectId(3),c=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:s,obligationKey:i,rewardCoinName:c})}),this.helperClaimBorrowReward.forEach(o=>{let i=o.decodeSharedObjectId(2),s=o.decodeOwnedObjectId(3),c=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:s,obligationKey:i,rewardCoinName:c})}),{txType:Nt.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};var Za=require("@msafe/sui3-utils");var ti=class extends Ae{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 _(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 _(e,this.transaction)}decodeCreateReferralLink(){return{txType:Za.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Za.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Za.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};var re=require("@msafe/sui3-utils"),Dp=require("@scallop-io/sui-scallop-sdk");var ei=class extends Ae{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(c=>this.filterMoveCallCommands(c,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(c=>this.filterMoveCallCommands(c,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),n=this.commands.filter(c=>this.filterMoveCallCommands(c,`${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(m=>m.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,n=t.filter(m=>m.$kind==="Input").map(({Input:m})=>m);if(n.length!==t.length)return!1;let o=new Set(n),i=this.inputs.filter((m,b)=>m.$kind==="Object"&&o.has(b)).map(m=>m.Object.ImmOrOwnedObject),s=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,c=kp(i.map(({objectId:m})=>m),50);for(let m=0;m<c.length;m++){let b=c[m];if((await this.scallopClient.scallopSuiKit.queryGetObjects(b,{showType:!0})).some(w=>w.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 _(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 _(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new _(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new _(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 _(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${Dp.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`));return new _(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new _(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 _(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(n=>this.filterMoveCallCommands(n,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new _(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,c=0;return this.commands.forEach(m=>{this.filterMoveCallCommands(m,e)?(o.push({action:"unstake",helper:new _(m,this.transaction,i)}),i++):this.filterMoveCallCommands(m,t)?(o.push({action:"stake",helper:new _(m,this.transaction,s)}),s++):this.filterMoveCallCommands(m,n)&&(o.push({action:"deactivate",helper:new _(m,this.transaction,c)}),c++)}),o}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:re.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new Ut(e,this.transaction).getAmountInput().reduce((D,M)=>D+M,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),i=!!this.helperRedeemSca.moveCall,s=[],c=[],m=[];this.helperOldUnstakeObligation.moveCall&&(s=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(c=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(m=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let b=!1,S=!1,w,C,k=[{condition:s,isOld:!0},{condition:c,isOld:!1},{condition:m,isOld:!1}];for(let D=0;D<k.length;D++)k[D].condition.length>1&&([C,w]=k[D].condition,b=!0,S=k[D].isOld);return{txType:re.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:w,obligationKey:C,veScaKey:o,isHaveRedeem:i,isObligationLocked:b,isOldBorrowIncentive:S}}}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,c=!1,m,b,S=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:i,isOld:!1}];for(let w=0;w<S.length;w++)S[w].condition.length>1&&([b,m]=S[w].condition,s=!0,c=S[w].isOld);return{txType:re.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:m,obligationKey:b,veScaKey:t,isObligationLocked:s,isOldBorrowIncentive:c}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new Ut(e,this.transaction).getAmountInput().reduce((k,D)=>k+D,0),o=[],i=[],s,c=[];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&&(c=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let m=!1,b=!1,S,w,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:c,isOld:!1}];for(let k=0;k<C.length;k++)C[k].condition.length>1&&([w,S]=C[k].condition,m=!0,b=C[k].isOld);return{txType:re.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:s,unlockTime:t,obligationId:S,obligationKey:w,isOldBorrowIncentive:b,isObligationLocked:m}}}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 Ut(e,this.transaction).getAmountInput().reduce((k,D)=>k+D,0),o=[],i=[],s,c=[];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&&(c=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let m=!1,b=!1,S,w,C=[{condition:o,isOld:!0},{condition:i,isOld:!1},{condition:c,isOld:!1}];for(let k=0;k<C.length;k++)C[k].condition.length>1&&([w,S]=C[k].condition,m=!0,b=C[k].isOld);return{txType:re.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:S,obligationKey:w,veScaKey:s,isObligationLocked:m,isOldBorrowIncentive:b}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:re.TransactionType.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:re.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:re.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,c)=>s.$kind==="Object"&&o.has(c)).map(s=>s.Object.ImmOrOwnedObject);return{xType:re.TransactionType.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:i}}}};var vp=Pt(require("sort-keys-recursive")),A=class{constructor(e){this.data=e}data;get application(){return"msafe-core"}serialize(){return JSON.stringify((0,vp.default)(this.data))}isObligationLocked=async(e,t)=>{let{object:n}=await e.getObject({objectId:typeof t=="string"?t:t.objectId,include:{json:!0}}),o=n?.json?.fields??n?.json;return!!(o&&"lock_key"in o&&o.lock_key)};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 ni=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:i,obligationId:s,obligationKey:c}=this.data,m=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:m,obligationId:s,obligationKey:c},async(S,w)=>{let C=await w.borrowQuick(+i,o,s,c);w.transferObjects([C],m)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var oi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrowWithBoost(t,n){let{obligationId:o,obligationKey:i,veScaKey:s,amount:c,coinName:m}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:n,obligationId:o,obligationKey:i,veScaKey:s},async(S,w)=>{let C=await w.borrowQuick(+c,m,o,i);w.transferObjects([C],n)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new a(t)}};var ai=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:i,obligationKey:s,veScaKey:c,coinName:m,amount:b}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:i,obligationKey:s,veScaKey:c},async(w,C)=>{let k=C.claimReferralTicket(m),D=await C.borrowWithReferralQuick(+b,m,k,i,s);C.burnReferralTicket(k,m),C.transferObjects([D],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};var Ap=require("@mysten/sui/utils");var ii=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),c=Object.values(await e.query.getObligationAccounts(t)??[]),m=(()=>{let C=[...e.constants.whitelist.spool].map(k=>e.utils.parseCoinName(k));return Object.values(i??[]).filter(k=>!!k&&C.includes(k.coinName)).reduce((k,D)=>{let M=e.utils.parseMarketCoinName(D.coinName);return k[M]||(k[M]=0),k[M]+=D.availableClaimCoin,k},{})})(),b={};Object.entries(o).forEach(([C,k])=>{for(let D=0;D<k.length;D++){let M=k[D];if(!m[C])continue;let q=n.claim(M.id,C);b.sui?b.sui.push(q):b.sui=[q]}});let S=(()=>{let C={};return C.sui=Object.values(m).reduce((k,D)=>k+D,0),c.forEach(k=>{Object.values(k.borrowIncentives).forEach(D=>{D&&D.rewards.forEach(M=>{C[M.coinName]||(C[M.coinName]=0),C[M.coinName]?C[M.coinName]+=M.availableClaimCoin:C[M.coinName]=M.availableClaimCoin})})}),C})();if(s.length>0&&c.length>0)for(let C=0;C<c.length;C++){let k=c[C],D=!1,M=s.find(U=>U.id===k.obligationId)?.keyId,q={};if(M){if(Object.values(k.borrowIncentives).forEach(U=>{if(U){let G=U.rewards.filter($=>{let E=$.coinName;return $.availableClaimCoin>0&&!q[E]});D=G.length>0,G.forEach($=>{let E=n.claimBorrowIncentive(k.obligationId,M,$.coinName);q[$.coinName]=!0,b[$.coinName]?b[$.coinName].push(E):b[$.coinName]=[E]})}}),S.sui>0){let U=zt.redeem_rewards(n,M,k.obligationId,Ap.SUI_TYPE_ARG);b.sui?b.sui.push(U):b.sui=[U]}if(D&&await xp(e.query,k.obligationId)){n.unstakeObligation(k.obligationId,M);let G=await e.query.getBindedVeScaKey(k.obligationId);G?n.stakeObligationWithVesca(k.obligationId,M,G):n.stakeObligation(k.obligationId,M)}}}let w=(await Promise.all(Object.entries(b).map(async([C,k])=>{let D=k[0];if(k.length>1&&n.mergeCoins(D,k.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 w.length>0&&n.transferObjects(w,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var ri=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var si=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:i,obligationId:s,rewardCoinName:c,veScaKey:m}=this.data,b=n.builder.createTxBlock();b.setSender(o);let S=zt.redeem_rewards(b,i,s,n.utils.parseCoinType(c));return b.transferObjects([S],o),await b.unstakeObligationQuick(s,i),m?await b.stakeObligationWithVeScaQuick(s,i,m):await b.stakeObligationQuick(s,i),b.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var ci=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var li=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var ui=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:s,obligationId:c,obligationKey:m}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:c,obligationKey:m},async(S,w)=>{await w.repayQuick(+s,i,c)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var pi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:i,amount:s,obligationId:c,veScaKey:m}=this.data,b=n.builder.createTxBlock();b.setSender(o);let S=n.constants.whitelist.borrowing.has(i);return S&&await b.unstakeObligationQuick(c,void 0),await b.repayQuick(+s,i,c),S&&await b.stakeObligationWithVeScaQuick(c,void 0,m),b.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var mi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var di=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var fi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async unstakeAndWithdraw(t,n,o){let i=t.builder.createTxBlock();i.setSender(o);let{stakeAccountId:s,amount:c,coinName:m}=this.data,b=[];for(let S=0;S<s.length;S++){let{id:w,coin:C}=s[S],k=t.utils.parseMarketCoinName(m),[D]=await i.unstakeQuick(C,k,w,!1);if(D){let M=i.withdraw(D,m);b.push(M)}}if(c>0){let S=await i.withdrawQuick(c,m);b.push(S)}return b.length>1&&i.mergeCoins(b[0],b.slice(1)),i.transferObjects(b,o),i.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var hi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await 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 gi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var yi=class a extends A{constructor(t){super(t);this.data=t}data;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 bi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:i}=this.data,s=t.address,c=n.builder.createTxBlock();c.setSender(s);let m=i.map(b=>n.utils.parseCoinNameFromType(b));return await c.claimReferralRevenueQuick(o,m),c.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var Ti=class a extends A{constructor(t){super(t);this.data=t}data;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 Mp=require("@scallop-io/sui-scallop-sdk");var Si=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:i,unlockTime:s,obligationId:c,obligationKey:m,isOldBorrowIncentive:b,isObligationLocked:S}=this.data,w=t.address,C=n.builder.createTxBlock();C.setSender(w);let k=await n.utils.selectCoins(o,Mp.SCA_COIN_TYPE,w),[D,M]=C.takeAmountFromCoins(k,o);return C.extendLockPeriod(i,s),C.extendLockAmount(i,D),C.transferObjects([M],w),!c||!m||(S&&(b?zt.unstakeObligation(C,c,m):C.unstakeObligation(c,m)),C.stakeObligationWithVesca(c,m,i)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var wi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:i,unlockTime:s,obligationId:c,obligationKey:m,isObligationLocked:b,isOldBorrowIncentive:S}=this.data,w=n.builder.createTxBlock();return w.setSender(o),w.extendLockPeriod(i,s),c&&m&&(b&&(S?zt.unstakeObligation(w,m,c):w.unstakeObligation(c,m)),w.stakeObligationWithVesca(c,m,i)),w.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var Ii=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,sourceVeScaKey:s}=this.data,[c,m]=await Promise.all([n.getBindedObligationId(i),n.getBindedObligationId(s)]);c&&await t.unstakeObligationQuick(c),m&&await t.unstakeObligationQuick(m),o(t,i,s),c&&await t.stakeObligationWithVeScaQuick(c,void 0,i),m&&await t.stakeObligationWithVeScaQuick(m,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,c,m)=>{s.mergeVeSca(i.object(c),i.object(m))}),i.txBlock}static fromData(t){return new a(t)}};var Ci=class a extends A{constructor(t){super(t);this.data=t}data;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({veScaKey:o}),s.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};var Op=require("@scallop-io/sui-scallop-sdk");var xi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,unlockTime:s,veScaKey:c,isHaveRedeem:m,obligation:b,obligationKey:S,isObligationLocked:w,isOldBorrowIncentive:C}=this.data,k=n.builder.createTxBlock();if(k.setSender(o),m){let U=k.redeemSca(c);k.transferObjects([U],o)}let D=await n.builder.utils.selectCoins(i,Op.SCA_COIN_TYPE,o),[M,q]=k.takeAmountFromCoins(D,i);return k.transferObjects([q],o),k.renewExpiredVeSca(c,M,s),!b||!S||(w&&(C?zt.unstakeObligation(k,S,b):k.unstakeObligation(b,S)),k.stakeObligationWithVesca(b,S,c)),k.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};var ki=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:i,splitAmount:s}=this.data,c=await n.getBindedObligationId(i);c&&await t.unstakeObligationQuick(c),o(t,i,s.toString()),c&&await t.stakeObligationWithVeScaQuick(c,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,c,m)=>{let b=s.splitVeSca(c,m.toString());s.transferObjects([b],o)}),i.txBlock}static fromData(t){return new a(t)}};var Pp=require("@scallop-io/sui-scallop-sdk");var Di=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:i,isObligationLocked:s,isOldBorrowIncentive:c,obligationId:m,obligationKey:b,unlockTime:S,veScaKey:w}=this.data,C=n.builder.createTxBlock();C.setSender(o);let k=await n.utils.selectCoins(i,Pp.SCA_COIN_TYPE,o),[D,M]=C.takeAmountFromCoins(k,i),q;return w?C.extendLockAmount(w,D):q=C.lockSca(D,S),m&&b&&(s&&(c?zt.unstakeObligation(C,b,m):C.unstakeObligation(m,b)),C.stakeObligationWithVesca(m,b,w||q)),w||C.transferObjects([q,M],o),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var vi=class a extends A{constructor(t){super(t);this.data=t}data;txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:i,coinName:s,stakeAccountId:c}=this.data,m=n.builder.createTxBlock();m.setSender(o);let b=await m.depositQuick(+i,s),S=n.utils.parseMarketCoinName(s);if(n.constants.whitelist.spool.has(S))return m.txBlock;let w=await n.query.getStakeAccounts(S,o),C=c||(w.length>0?w[0].id:void 0);if(C)await m.stakeQuick(b,S,C);else{let k=m.createStakeAccount(S);await m.stakeQuick(b,S,k),m.transferObjects([k],o)}return m.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var Ai=class a extends A{constructor(t){super(t);this.data=t}data;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(c=>this.handleAction(i,c)),i.txBlock}static fromData(t){return new a(t)}};var Mi=class a extends A{constructor(t){super(t);this.data=t}data;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(c=>i.objectRef(c)),i.pure.address(o)),i.txBlock}static fromData(t){return new a(t)}};var Oi=class a extends A{constructor(t){super(t);this.data=t}data;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({veScaKey:o}),s.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var Pi=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let n=new Bp.Scallop({addressId:"695fcdc084f790c04eb068dc",walletAddress:e,suiClients:[t],fullnodeUrls:[jt("mainnet")]});this.scallopClient=await n.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;await this.initScallopClient(o.address,n);let i=new Ja(t,this.scallopClient),s=new ti(t,this.scallopClient),c=new ei(t,this.scallopClient),m=i.decode()||s.decode()||await c.decode();if(!m)throw new Error("Unknown transaction type");return{txType:Rp.TransactionType.Other,txSubType:m.type,intentionData:m.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:i,intentionData:s}=e;await this.initScallopClient(n.address,t);let c;switch(i){case"SupplyLending":c=mi.fromData(s);break;case"WithdrawLending":c=gi.fromData(s);break;case"Borrow":c=ni.fromData(s);break;case"Repay":c=ui.fromData(s);break;case"DepositCollateral":c=ri.fromData(s);break;case"WithdrawCollateral":c=hi.fromData(s);break;case"OpenObligation":c=li.fromData(s);break;case"UnstakeSpool":c=di.fromData(s);break;case"ClaimIncentiveReward":c=ii.fromData(s);break;case"BorrowWithBoost":c=oi.fromData(s);break;case"StakeSca":c=Di.fromData(s);break;case"ExtendStakePeriod":c=wi.fromData(s);break;case"ExtendPeriodAndStakeMore":c=Si.fromData(s);break;case"RenewExpStakePeriod":c=xi.fromData(s);break;case"WithdrawStakedSca":c=Oi.fromData(s);break;case"SupplyAndStakeLending":c=vi.fromData(s);break;case"WithdrawAndUnstakeLending":c=fi.fromData(s);break;case"RedeemSca":c=Ci.fromData(s);break;case"MigrateAndClaim":c=si.fromData(s);break;case"BorrowWithReferral":c=ai.fromData(s);break;case"CreateReferralLink":c=Ti.fromData(s);break;case"ClaimRevenueReferral":c=bi.fromData(s);break;case"BindReferral":c=yi.fromData(s);break;case"MigrateScoin":c=ci.fromData(s);break;case"RepayWithBoost":c=pi.fromData(s);break;case"MergeVeSca":c=Ii.fromData(s);break;case"SplitVeSca":c=ki.fromData(s);break;case"VeScaObligationBindings":{c=Ai.fromData(s);break}case"TransferVeScaKeys":{c=Mi.fromData(s);break}default:throw new Error("not implemented")}return c.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};var em=require("@msafe/sui3-utils");var Sn=require("@msafe/sui3-utils"),Re=require("@mysten/sui/utils");var Vp=require("@suilend/sui-fe");var Gp=require("@msafe/sui3-utils"),Pe=require("@suilend/sdk");var Ke=require("@msafe/sui3-utils"),bn=require("@mysten/bcs"),yn=require("@mysten/sui/utils"),Ge=require("@suilend/sui-fe"),ec=Pt(require("bignumber.js"));var Ri=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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,yn.normalizeStructTag)(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Ke.TransactionType.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(m=>m.type.includes("lending_market::RedeemEvent"))},n=(0,yn.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 ec.default((0,bn.toHex)((0,bn.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),c=s===Ge.MAX_U64.toString();return console.log("decodeWithdraw - isMax:",c,"inputIndex:",i,"inputValue:",s,"MAX_U64.toString():",Ge.MAX_U64.toString()),c&&(o=Ge.MAX_U64.toString()),{txType:Ke.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(m=>m.type.includes("lending_market::BorrowEvent"))},n=(0,yn.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 ec.default((0,bn.toHex)((0,bn.fromBase64)(this.inputs[i].Pure.bytes)),16).toString(),c=s===Ge.MAX_U64.toString();return console.log("decodeBorrow - isMax:",c,"inputIndex:",i,"inputValue:",s,"MAX_U64.toString():",Ge.MAX_U64.toString()),c&&(o=Ge.MAX_U64.toString()),{txType:Ke.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,yn.normalizeStructTag)(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Ke.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,yn.normalizeStructTag)(o.parsedJson.coin_type.name),s=o.parsedJson.liquidity_amount;t[i]=`${+(t[i]??"0")+ +s}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Ke.TransactionType.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Ke.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var Np=require("@mysten/sui/transactions");var Ep=Pt(require("sort-keys-recursive")),Gt=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Ep.default)(this.data))}};var Bi=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;if(console.log("BorrowIntention.build",n,o,i,s,c),!s||!c)throw new Error("Obligation not found");let m=new Np.Transaction;return await i.borrowAndSendToUser(o.address,s.id,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};var jp=require("@mysten/sui/transactions");var Wp=require("@mysten/sui/utils"),Tn=require("@suilend/sdk"),_p=require("@suilend/sui-fe"),Lp=Pt(require("bignumber.js")),Ff=(a,e)=>{let t={[Tn.Side.DEPOSIT]:[],[Tn.Side.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[Tn.Side.DEPOSIT,Tn.Side.BORROW].forEach(o=>{let i=o===Tn.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,s=e.userRewardManagers.find(c=>c.poolRewardManagerId===i.id);s&&(t[o]=i.poolRewards.map((c,m)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(m),rewardCoinType:(0,Wp.normalizeStructTag)(c.coinType.name),side:o})).filter(c=>!(0,_p.isSendPoints)(c.rewardCoinType)&&!!s.rewards[Number(c.rewardIndex)]&&new Lp.default(s.rewards[Number(c.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},Ei=Ff;var Ni=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;if(console.log("ClaimIntention.build",n,o,i,s,c),!s||!c)throw new Error("Obligation not found");let m=new jp.Transaction;return i.claimRewardsAndSendToUser(o.address,s.id,Ei(i,c),m),m}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};var Up=require("@mysten/sui/transactions");var Wi=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;if(console.log("ClaimAndDepositIntention.build",n,o,i,s,c),!s||!c)throw new Error("Obligation not found");let m=new Up.Transaction;return i.claimRewardsAndDeposit(o.address,s.id,Ei(i,c),m),m}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};var qp=require("@mysten/sui/transactions");var _i=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;console.log("DepositIntention.build",n,o,i,s,c);let m=new qp.Transaction;return await i.depositIntoObligation(o.address,this.data.coinType,this.data.value,m,s?.id),m}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};var Fp=require("@mysten/sui/transactions");var Li=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;if(console.log("RepayIntention.build",n,o,i,s,c),!s||!c)throw new Error("Obligation not found");let m=new Fp.Transaction;return await i.repayIntoObligation(o.address,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};var Kp=require("@mysten/sui/transactions");var ji=class a extends Gt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,obligationOwnerCap:s,obligation:c}=t;if(console.log("WithdrawIntention.build",n,o,i,s,c),!s||!c)throw new Error("Obligation not found");let m=new Kp.Transaction;return await i.withdrawAndSendToUser(o.address,s.id,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var Ui=async(a,e)=>{let t=await Pe.SuilendClient.initialize(Pe.LENDING_MARKET_ID,Pe.LENDING_MARKET_TYPE,a),n=await Pe.SuilendClient.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(i=>Pe.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}},qi=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Ui(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",i,"utils:",this.utils,"suiClient:",n);let c=new Ri(t,i).decode();return{txType:Gp.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:s}=e;this.utils||(this.utils=await Ui(i,s));let c;switch(n){case"deposit":c=_i.fromData(o);break;case"withdraw":c=ji.fromData(o);break;case"borrow":c=Bi.fromData(o);break;case"repay":c=Li.fromData(o);break;case"claim":c=Ni.fromData(o);break;case"claimAndDeposit":c=Wi.fromData(o);break;default:throw new Error("not implemented")}let m=window.localStorage.getItem("obligationId"),b=this.utils.obligations?.find(w=>w.id===m)??this.utils.obligations?.[0],S=this.utils.obligationOwnerCaps?.find(w=>w.obligationId===b?.id);return c.build({network:t,suiClient:i,account:s,suilendClient:this.utils.suilendClient,obligationOwnerCap:S,obligation:b})}};var nc=async(a,e)=>{let t=await Ui(a,e),n=await fetch(`${Vp.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(c=>[c.LIQUID_STAKING_INFO.type,c.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:s}};var Fi=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:Sn.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,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:Sn.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,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:Sn.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,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:Sn.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,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:Sn.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};var Hp=require("@mysten/sui/transactions"),Yn=require("@suilend/springsui-sdk");var $p=Pt(require("sort-keys-recursive")),Qt=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,$p.default)(this.data))}};var Ki=class a extends Qt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("ConvertIntention.build",n,o,i,s,c,m);let b=await Yn.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.inCoinType)),S=await Yn.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.outCoinType)),w=new Hp.Transaction;return(0,Yn.convertLstsAndRebalanceAndSendToUser)(b,S,w,o.address,this.data.amount),w}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};var Xp=require("@mysten/sui/transactions"),Vi=require("@suilend/sdk"),Jn=require("@suilend/springsui-sdk");var Gi=class a extends Qt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("ConvertAndDepositIntention.build",n,o,i,s,c,m);let b=await Jn.LstClient.initialize(n,Object.values(s).find(M=>M.type===this.data.inCoinType)),S=await Jn.LstClient.initialize(n,Object.values(s).find(M=>M.type===this.data.outCoinType)),w=new Xp.Transaction,{obligationOwnerCapId:C,didCreate:k}=(0,Vi.createObligationIfNoneExists)(i,w,c),D=(0,Jn.convertLstsAndRebalance)(b,S,w,o.address,this.data.amount);return i.deposit(D,this.data.outCoinType,C,w),k&&(0,Vi.sendObligationToUser)(C,o.address,w),w}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};var zp=require("@mysten/sui/transactions"),Qp=require("@suilend/springsui-sdk");var $i=class a extends Qt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("StakeIntention.build",n,o,i,s,c,m);let b=await Qp.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.outCoinType)),S=new zp.Transaction;return b.mintAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};var Yp=require("@mysten/sui/transactions"),Xi=require("@suilend/sdk"),Jp=require("@suilend/springsui-sdk");var Hi=class a extends Qt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("StakeAndDepositIntention.build",n,o,i,s,c,m);let b=await Jp.LstClient.initialize(n,Object.values(s).find(D=>D.type===this.data.outCoinType)),S=new Yp.Transaction,{obligationOwnerCapId:w,didCreate:C}=(0,Xi.createObligationIfNoneExists)(i,S,c),k=b.mintAmountAndRebalance(S,o.address,this.data.amount);return i.deposit(k,this.data.outCoinType,w,S),C&&(0,Xi.sendObligationToUser)(w,o.address,S),S}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};var Zp=require("@mysten/sui/transactions"),tm=require("@suilend/springsui-sdk");var zi=class a extends Qt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:i,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("UnstakeIntention.build",n,o,i,s,c,m);let b=await tm.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.inCoinType)),S=new Zp.Transaction;return b.redeemAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Qi=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await nc(n,o));let i=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",i);let c=new Fi(t,i).decode();return{txType:em.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:i,account:s}=e;this.utils||(this.utils=await nc(i,s));let c;switch(n){case"stake":c=$i.fromData(o);break;case"stakeAndDeposit":c=Hi.fromData(o);break;case"convert":c=Ki.fromData(o);break;case"convertAndDeposit":c=Gi.fromData(o);break;case"unstake":c=zi.fromData(o);break;default:throw new Error("not implemented")}return c.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 am=require("@msafe/sui3-utils");var oc=require("@msafe/sui3-utils");var Yi=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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:oc.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:oc.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var nm=require("@alphafi/stsui-sdk");var Ji=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},c=await new nm.LST(i).mint(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};var om=require("@alphafi/stsui-sdk");var Zi=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},c=await new om.LST(i).redeem(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var tr=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 Yi(t,o).decode();return{txType:am.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=Ji.fromData(e.intentionData);break;case"redeem":n=Zi.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};var Am=require("@msafe/sui3-utils"),Mm=require("turbos-clmm-sdk");var qt=require("@msafe/sui3-utils"),Ve=require("@mysten/bcs"),$e=require("@mysten/sui/bcs"),im=require("turbos-clmm-sdk");var Jt={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Zt={PackageId:"0xdee9"};var $f=(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}`)}},er=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}txb;turbosSdk;config;get transactions(){return this.txb.getData().commands}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.isRemoveLiquidityWithReturnTransaction())return this.decodeRemoveLiquidityWithReturn(e);if(this.isDecreaseLiquidityWithReturnTransaction())return this.decodeDecreaseLiquidityWithReturn(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.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===e:!1)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.$kind==="MoveCall"?`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`===t:!1))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>{if(t.$kind==="MoveCall"){let n=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;return!!e.includes(n)}return!1})}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`)}isDecreaseLiquidityWithReturnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity_with_return_`)}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(`${Jt.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Jt.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isRemoveLiquidityWithReturnTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity_with_return_`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(k=>k.$kind==="MoveCall"),t=0,n=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;console.log(n,"moveCallTarget"),this.swap2Layer.includes(n)&&(t=1);let o=$f(t,n,this.swap1Layer,this.swap2Layer),i=o.map((k,D)=>{let M=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(D)),q=this.helper.decodeInputU128(this.helper.getInputsIndex(4+D+t)),U=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new im.BN(q.toString()));return{pool:M,a2b:k,nextTickIndex:U}}),s=o[0]||t===1?e.MoveCall.typeArguments[0]:e.MoveCall.typeArguments[1],c=t===1?e.MoveCall.typeArguments[4]:o[0]?e.MoveCall.typeArguments[1]:e.MoveCall.typeArguments[0],m=this.helper.decodeInputAddress(this.helper.getInputsIndex(6+2*t)),b=this.helper.decodeInputU64(this.helper.getInputsIndex(7+2*t)),S=this.helper.decodeInputBool(this.helper.getInputsIndex(5+2*t)),w=this.helper.decodeInputU64(this.helper.getInputsIndex(2+t)),C=this.helper.decodeInputU64(this.helper.getInputsIndex(3+t));return{txType:qt.TransactionType.Other,type:"Swap",intentionData:{routes:i,coinTypeA:s,coinTypeB:c,address:m,amountA:S?w:C,amountB:S?C:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:b}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeInputAddress(this.helper.getInputsIndex(12)),n=this.helper.decodeInputU64(this.helper.getInputsIndex(8)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(9)),i=this.helper.decodeInputU32(this.helper.getInputsIndex(4)),s=this.helper.decodeInputBool(this.helper.getInputsIndex(5)),c=this.helper.decodeInputU32(this.helper.getInputsIndex(6)),m=this.helper.decodeInputBool(this.helper.getInputsIndex(7)),b=this.helper.decodeInputU64(this.helper.getInputsIndex(13));return{txType:qt.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:30,address:t,amountA:n,amountB:o,tickLower:s?-i:i,tickUpper:m?-c:c,deadline:b}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),n=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(4)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(5)),i=this.helper.decodeInputU64(this.helper.getInputsIndex(6)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(9));return{txType:qt.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:30,address:e,amountA:o,amountB:i,nft:n,deadline:s}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),n=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(3)),i=this.helper.decodeInputU64(this.helper.getInputsIndex(4)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(5)),c=this.helper.decodeInputU64(this.helper.getInputsIndex(6));return{txType:qt.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:s,slippage:10,address:e,deadline:c}}}decodeDecreaseLiquidityWithReturn(e){console.log(this.helper,"decodeDecreaseLiquidityWithReturn this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeOwnedObjectId(2),o=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),s=this.helper.decodeInputU64(5),c=this.helper.decodeInputU64(6);return{txType:qt.TransactionType.Other,type:"DecreaseLiquidityWithReturn",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:s,slippage:10,address:e,deadline:c}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),n=this.helper.decodeInputAddress(this.helper.getInputsIndex(5)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(3)),i=this.helper.decodeInputU64(this.helper.getInputsIndex(4)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(6));return{txType:qt.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(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),n=this.helper.decodeInputAddress(this.helper.getInputsIndex(6)),o=[0,0,0];this.collectRewardHelper.forEach(s=>{let c=s.decodeInputU64(s.getInputsIndex(4)),m=s.decodeInputU64(s.getInputsIndex(5));o[c]=m});let i=this.helper.decodeInputU64(7);return{txType:qt.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(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2));return{txType:qt.TransactionType.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=30,n=this.decreaseLiquidityHelper.decodeSharedObjectId(this.decreaseLiquidityHelper.getInputsIndex(0)),o=this.decreaseLiquidityHelper.decodeOwnedObjectId(this.decreaseLiquidityHelper.getInputsIndex(2)),i=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(3)),s=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(4)),c=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(5)),m=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(6)),b=[0,0,0];this.collectRewardHelper.forEach(C=>{let k=C.decodeInputU64(C.getInputsIndex(4)),D=C.decodeInputU64(C.getInputsIndex(5));b[k]=D});let S=this.collectFeeHelper.decodeInputU64(this.collectFeeHelper.getInputsIndex(3))||0,w=this.collectFeeHelper.decodeInputU64(this.collectFeeHelper.getInputsIndex(4))||0;return{txType:qt.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:n,decreaseLiquidity:i,nft:o,amountA:(s/(100-t)*100).toFixed(0),amountB:(c/(100-t)*100).toFixed(0),slippage:t,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:b,deadline:m}}}decodeRemoveLiquidityWithReturn(e){console.log(this.helper,"decodeRemoveLiquidityWithReturn this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeOwnedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),i=this.decreaseLiquidityHelper.decodeInputU64(4),s=this.decreaseLiquidityHelper.decodeInputU64(5),c=this.decreaseLiquidityHelper.decodeInputU64(6),m=this.collectRewardHelper.map(w=>w.decodeInputU64(5)),b=this.collectFeeHelper.decodeInputU64(3)||0,S=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:qt.TransactionType.Other,type:"removeLiquidityWithReturn",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:i,amountB:s,slippage:10,address:e,collectAmountA:b,collectAmountB:S,rewardAmounts:m,deadline:c}}}decodePrixClaim(){return{txType:qt.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:qt.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:qt.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:qt.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>{if(t.$kind==="MoveCall"){let n=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;return n!=="0x2::coin::zero"&&n!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero"}return!1});return new Be(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::collect_reward`:!1).map(t=>new Be(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::collect`:!1);return new Be(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::decrease_liquidity`:!1);return new Be(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`:!1);return new Be(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`:!1);return new Be(e,this.txb)}},Be=class{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get inputs(){return this.txb.getData().inputs}getInputsIndex(e){return this.moveCall.MoveCall.arguments[e].Input}decodeSharedObjectId(e){return this.inputs[e].Object?.SharedObject?.objectId||this.inputs[e].UnresolvedObject.objectId}decodeOwnedObjectId(e){return this.inputs[e].Object?.ImmOrOwnedObject?.objectId||this.inputs[e].UnresolvedObject.objectId}decodeInputU128(e){return Number($e.bcs.u128().parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU64(e){return Number($e.bcs.u64().parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU32(e){return Number($e.bcs.u32().parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU8(e){return Number($e.bcs.u8().parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputAddress(e){return $e.bcs.Address.parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes)))}decodeInputBool(e){return $e.bcs.bool().parse(Uint8Array.from((0,Ve.fromBase64)(this.inputs[e].Pure.bytes)))}shortTypeArg(e){return this.moveCall.MoveCall.typeArguments[e]}txArg(e){return this.moveCall.MoveCall.arguments[e]}};var rm=require("turbos-clmm-sdk");var nr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new rm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:c,slippage:m,tickLower:b,tickUpper:S,deadline:w,txb:C}=this.data;return n.pool.addLiquidity({pool:o,slippage:m,address:i,amountA:s,amountB:c,tickLower:b,tickUpper:S,deadline:w,txb:C})}static fromData(t){return new a(t)}};var sm=require("turbos-clmm-sdk");var or=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new sm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,nft:i,txb:s}=this.data;return n.position.burn({pool:o,nft:i,txb:s})}static fromData(t){return new a(t)}};var cm=require("turbos-clmm-sdk");var ar=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new cm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:s,collectAmountA:c,collectAmountB:m,deadline:b,txb:S}=this.data;return n.pool.collectFee({pool:o,address:i,collectAmountA:c,collectAmountB:m,nft:s,deadline:b,txb:S})}static fromData(t){return new a(t)}};var lm=require("turbos-clmm-sdk");var ir=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new lm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,nft:s,rewardAmounts:c,deadline:m,txb:b}=this.data;return n.pool.collectReward({pool:o,address:i,rewardAmounts:c,nft:s,deadline:m,txb:b})}static fromData(t){return new a(t)}};var um=require("turbos-clmm-sdk");var rr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new um.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{fee:o,address:i,tickLower:s,tickUpper:c,sqrtPrice:m,slippage:b,coinTypeA:S,coinTypeB:w,amountA:C,amountB:k,deadline:D,txb:M}=this.data;return n.pool.createPool({fee:o,amountA:C,amountB:k,address:i,tickLower:s,tickUpper:c,sqrtPrice:m,slippage:b,coinTypeA:S,coinTypeB:w,deadline:D,txb:M})}static fromData(t){return new a(t)}};var pm=require("turbos-clmm-sdk");var sr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new pm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:c,slippage:m,nft:b,decreaseLiquidity:S,deadline:w,txb:C}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:m,address:i,amountA:s,amountB:c,nft:b,decreaseLiquidity:S,deadline:w,txb:C})}static fromData(t){return new a(t)}};var mm=require("turbos-clmm-sdk");var cr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new mm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:c,slippage:m,nft:b,decreaseLiquidity:S,deadline:w}=this.data,{txb:C,coinA:k,coinB:D}=await n.pool.decreaseLiquidityWithReturn({pool:o,slippage:m,address:i,amountA:s,amountB:c,nft:b,decreaseLiquidity:S,deadline:w});return C.transferObjects([k,D],this.data.address),C}static fromData(t){return new a(t)}};var dm=require("turbos-clmm-sdk");var lr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new dm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{pool:o,address:i,amountA:s,amountB:c,slippage:m,nft:b,deadline:S,txb:w}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:m,address:i,amountA:s,amountB:c,nft:b,deadline:S,txb:w})}static fromData(t){return new a(t)}};var fm=require("@mysten/sui/transactions"),hm=require("@mysten/sui/utils");var ur=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new fm.Transaction;return n.moveCall({target:`${Jt.PackageId}::claim::claim`,typeArguments:[Jt.turbosCoinType],arguments:[n.object(Jt.Claim),n.object(hm.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(t){return new a(t)}};var gm=require("@mysten/sui/transactions");var pr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new gm.Transaction;return n.moveCall({target:`${Jt.PackageId}::claim::join`,typeArguments:[Jt.turbosCoinType],arguments:[n.object(Jt.Claim)]}),n}static fromData(t){return new a(t)}};var ym=require("@mysten/sui/transactions"),bm=require("turbos-clmm-sdk");var mr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new bm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),o=new ym.Transaction;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.position.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(t){return new a(t)}};var Tm=require("turbos-clmm-sdk");var dr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Tm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{txb:o,coinA:i,coinB:s}=await n.pool.removeLiquidityWithReturn({...this.data});return o.transferObjects([i,s],this.data.address),o}static fromData(t){return new a(t)}};var Sm=require("turbos-clmm-sdk");var fr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new Sm.TurbosSdk(t.network.replace("sui:",""),t.suiClient),{routes:o,coinTypeA:i,coinTypeB:s,address:c,amountA:m,amountB:b,slippage:S,amountSpecifiedIsInput:w,deadline:C,txb:k}=this.data;return n.trade.swap({routes:o,coinTypeA:i,coinTypeB:s,address:c,amountA:m,amountB:b,amountSpecifiedIsInput:w,slippage:S,deadline:C,txb:k})}static fromData(t){return new a(t)}};var Dm=require("turbos-clmm-sdk");var ac=require("@mysten/sui/transactions"),ic=require("@mysten/sui/utils");var wm=require("turbos-clmm-sdk");var Zn=class{constructor(e){this.turbosSdk=e}turbosSdk;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=[],c=0;return o.sort((m,b)=>Number(b.balance)-Number(m.balance)).some(m=>c>=n?!0:(c+=Number(m.balance),s.push(m),!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.u64(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.u64(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:`${Zt.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?(0,wm.unstable_getObjectId)(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Zt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var Im=89,Cm=1e6,xm=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:s}=a,c=new ac.Transaction,m=new Zn(s),b=await m.getCoinsData(i,t,o),[S,w]=m.splitAndMergeCoin(b,o,c);if(!S)throw new Error(`Not enough balance: ${t}`);let C=await m.IsAccountCap(i),k=C?c.object(C):m.createAccount(c),[D,M,q]=c.moveCall({typeArguments:[e,t],target:`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[c.object(String(n)),c.pure.u64(Im),k,c.pure.u64(o),c.object((0,ic.normalizeSuiObjectId)("0x6")),S]});return w&&c.transferObjects([w],c.pure.address(i)),c.transferObjects([D],c.pure.address(i)),c.transferObjects([M],c.pure.address(i)),C||c.transferObjects([k],c.pure.address(i)),c.setSenderIfNotSet(i),c.setGasBudget(Cm),c},km=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:i,turbosSdk:s}=a,c=new ac.Transaction,m=new Zn(s),b=await m.getCoinsData(i,e,o),[S,w]=m.splitAndMergeCoin(b,o,c);if(!S)throw new Error(`Not enough balance: ${e}`);let C=await m.IsAccountCap(i),k=C?c.object(C):m.createAccount(c),D=m.zero(t,c),[M,q,U]=c.moveCall({typeArguments:[e,t],target:`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[c.object(String(n)),c.pure.u64(Im),k,c.pure.u64(o),S,D,c.object((0,ic.normalizeSuiObjectId)("0x6"))]});return w&&c.transferObjects([w],c.pure.address(i)),c.transferObjects([M],c.pure.address(i)),c.transferObjects([q],c.pure.address(i)),C||c.transferObjects([k],c.pure.address(i)),c.setSenderIfNotSet(i),c.setGasBudget(Cm),c};var hr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Dm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await km({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var vm=require("turbos-clmm-sdk");var gr=class a extends x{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new vm.TurbosSdk(t.network.replace("sui:",""),t.suiClient);return await xm({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var yr=class{application="turbos";supportSDK="@mysten/sui";async deserialize(e){console.log(e,"input");let t=new Mm.TurbosSdk(e.network.replace("sui:","")),n=await t.contract.getConfig(),{transaction:o,account:i}=e,c=await new er(o,t,n).decode(i.address);return{txType:Am.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.intentionData,"intentionData");let i;switch(e.txSubType){case"CreatePool":i=rr.fromData(e.intentionData);break;case"AddLiquidity":i=nr.fromData(e.intentionData);break;case"IncreaseLiquidity":i=lr.fromData(e.intentionData);break;case"DecreaseLiquidity":i=sr.fromData(e.intentionData);break;case"DecreaseLiquidityWithReturn":i=cr.fromData(e.intentionData);break;case"RemoveLiquidity":i=mr.fromData(e.intentionData);break;case"removeLiquidityWithReturn":i=dr.fromData(e.intentionData);break;case"CollectFee":i=ar.fromData(e.intentionData);break;case"CollectReward":i=ir.fromData(e.intentionData);break;case"Burn":i=or.fromData(e.intentionData);break;case"Swap":i=fr.fromData(e.intentionData);break;case"PrixJoin":i=pr.fromData(e.intentionData);break;case"PrixClaim":i=ur.fromData(e.intentionData);break;case"SwapExactBaseForQuote":i=hr.fromData(e.intentionData);break;case"SwapExactQuoteForBase":i=gr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Em=require("@msafe/sui3-utils");var br=require("@msafe/sui3-utils"),rc=require("@mysten/sui.js/bcs"),Ee=require("@mysten/sui.js/utils");var Hf={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Rt=Hf;var Tr=class{constructor(e){this.txb=e}txb;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(`${Rt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${Rt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${Rt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:br.TransactionType.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:br.TransactionType.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:br.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Rt.packageId));return new sc(e,this.txb)}},sc=class a{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;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,Ee.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 rc.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,Ee.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Ee.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,Ee.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Ee.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 rc.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,Ee.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Pm=require("@mysten/sui.js/transactions");var Om=Pt(require("sort-keys-recursive")),Ne=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Om.default)(this.data))}};var Sr=class a extends Ne{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){console.log(t);let n=new Pm.TransactionBlock,{ticketId:o}=this.data;return n.moveCall({target:`${Rt.packageId}::native_pool::burn_ticket`,arguments:[n.object(Rt.poolObjectId),n.object(Rt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new a(t)}};var Rm=require("@mysten/sui.js/transactions");var wr=class a extends Ne{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){console.log(t);let n=new Rm.TransactionBlock,{amount:o}=this.data,[i]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${Rt.packageId}::native_pool::stake`,arguments:[n.object(Rt.poolObjectId),n.object(Rt.metadataObjectId),n.object(Rt.systemStateObjectId),i]}),n}static fromData(t){return new a(t)}};var Bm=require("@mysten/sui.js/transactions");var Ir=class a extends Ne{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){console.log(t);let n=new Bm.TransactionBlock,{amount:o}=this.data,i=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[s,...c]=i.filter(S=>S.coinType.split("::")[0]===Rt.certType.split("::")[0]),m=n.object(s.coinObjectId);c.length&&n.mergeCoins(m,c.map(S=>n.object(S.coinObjectId)));let b=n.splitCoins(n.object(s.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${Rt.packageId}::native_pool::unstake`,arguments:[n.object(Rt.poolObjectId),n.object(Rt.metadataObjectId),n.object(Rt.systemStateObjectId),b]}),n}static fromData(t){return new a(t)}};var Cr=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,o=new Tr(t).decode();return{txType:Em.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case"Stake":o=wr.fromData(e.intentionData);break;case"UnStake":o=Ir.fromData(e.intentionData);break;case"ClaimTicket":o=Sr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Hm=require("@msafe/sui3-utils");var cc=require("@cetusprotocol/common-sdk"),fe=require("@msafe/sui3-utils"),wn=require("@mysten/bcs"),In=require("@mysten/sui/bcs");var xr=class{constructor(e,t){this.transaction=e;this.appContext=t}transaction;appContext;async 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();if(this.isAggregator7KSwapTx())return this.decodeAggregator7KSwapTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:fe.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number((0,cc.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,cc.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:fe.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:fe.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:fe.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:fe.TransactionType.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:fe.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:fe.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}async decodeAggregator7KSwapTx(){let{appContext:e}=this;return console.log("appContext",e),{txType:fe.TransactionType.Other,type:"Aggregator7KSwap",intentionData:{tokenIn:e.txParams.tokenIn,tokenOut:e.txParams.tokenOut,amountIn:String(e.txParams.amountIn),maxSlippage:String(e.txParams.maxSlippage)}}}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")}isAggregator7KSwapTx(){return!!this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function.toLowerCase().includes("settle"))}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(In.bcs.u32().parse(Uint8Array.from((0,wn.fromBase64)(this.inputs[e].Pure.bytes))))}getU64(e){return In.bcs.u64().parse(Uint8Array.from((0,wn.fromBase64)(this.inputs[e].Pure.bytes)))}getU128(e){return In.bcs.u128().parse(Uint8Array.from((0,wn.fromBase64)(this.inputs[e].Pure.bytes)))}getBoolean(e){return In.bcs.bool().parse(Uint8Array.from((0,wn.fromBase64)(this.inputs[e].Pure.bytes)))}getAddress(e){return In.bcs.Address.parse(Uint8Array.from((0,wn.fromBase64)(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};var jm=require("@msafe/sui3-utils");var kr=require("@bluefin-exchange/bluefin7k-aggregator-sdk"),se=require("@firefly-exchange/library-sui"),Lm=require("turbos-clmm-sdk");var Wm=require("@firefly-exchange/library-sui"),_m=require("@firefly-exchange/library-sui/spot"),Nm={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},ge=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Wm.SuiClient({url:Nm.rpc});return new _m.OnChainCalls(t,Nm.objects,{address:e.address,isUIWallet:!1})};var Wt=class{static async OpenPosition(e,t,n){let o=ge(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=ge(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=ge(n,t),i=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(i,e.position,{liquidityAmount:new se.BN(e.liquidity),tokenMaxA:new se.BN(e.maxAmountTokenA),tokenMaxB:new se.BN(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=ge(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=ge(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=ge(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=ge(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})}static async aggregator7KSwap(e,t,n){let o=ge(n,t),i=await(0,kr.getQuote)({tokenIn:e.tokenIn.address,tokenOut:e.tokenOut.address,amountIn:new Lm.Decimal(e.amountIn).mul(10**e.tokenIn.decimals).toString()}),s=await(0,kr.buildTx)({quoteResponse:i,accountAddress:t.address,slippage:e.maxSlippage,commission:{partner:"0x956d6ea2da156a037952964badc51f997cc5581c86a0e05f74049e6effab9347",commissionBps:0}});return s.tx.setSender(t.address),s.tx}buildLiqInput(e,t){return{...se.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new se.BN(t.tokenAmount),t.isTokenAFixed,!0,0,new se.BN(e.current_sqrt_price)),tokenMaxA:new se.BN(t.maxAmountTokenA),tokenMaxB:new se.BN(t.maxAmountTokenB)}}};var Dr=class a extends x{constructor(t){super(t);this.data=t}data;txType=jm.TransactionType.Other;txSubType="Aggregator7KSwap";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.aggregator7KSwap(this.data,n,o)}static fromData(t){return new a(t)}};var Um=require("@msafe/sui3-utils");var vr=class a extends x{constructor(t){super(t);this.data=t}data;txType=Um.TransactionType.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.closePosition(this.data,n,o)}static fromData(t){return new a(t)}};var qm=require("@msafe/sui3-utils");var Ar=class a extends x{constructor(t){super(t);this.data=t}data;txType=qm.TransactionType.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.collectFee(this.data,n,o)}static fromData(t){return new a(t)}};var Fm=require("@msafe/sui3-utils");var Mr=class a extends x{constructor(t){super(t);this.data=t}data;txType=Fm.TransactionType.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.collectRewards(this.data,n,o)}static fromData(t){return new a(t)}};var Km=require("@msafe/sui3-utils");var Or=class a extends x{constructor(t){super(t);this.data=t}data;txType=Km.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new a(t)}};var Gm=require("@msafe/sui3-utils");var Pr=class a extends x{constructor(t){super(t);this.data=t}data;txType=Gm.TransactionType.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.OpenPosition(this.data,n,o)}static fromData(t){return new a(t)}};var Vm=require("@msafe/sui3-utils");var Rr=class a extends x{constructor(t){super(t);this.data=t}data;txType=Vm.TransactionType.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.provideLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var $m=require("@msafe/sui3-utils");var Br=class a extends x{constructor(t){super(t);this.data=t}data;txType=$m.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Wt.removeLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var Er=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t,appContext:n}=e,i=await new xr(t,n).decode();return{txType:Hm.TransactionType.Other,txSubType:i.type,intentionData:{appContext:e.appContext,...i.intentionData}}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let i;switch(e.txSubType){case"OpenPosition":i=Pr.fromData(e.intentionData);break;case"ProvideLiquidity":i=Rr.fromData(e.intentionData);break;case"RemoveLiquidity":i=Br.fromData(e.intentionData);break;case"ClosePosition":i=vr.fromData(e.intentionData);break;case"CollectFee":i=Ar.fromData(e.intentionData);break;case"CollectRewards":i=Mr.fromData(e.intentionData);break;case"CollectRewardsAndFee":i=Or.fromData(e.intentionData);break;case"Aggregator7KSwap":i=Dr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:n,network:o})}};var Wd=require("@msafe/sui3-utils");var pd=require("@mysten/sui/transactions");var Cn=require("@mmt-finance/clmm-sui-sdk"),Zm=Pt(require("bignumber.js")),R=Pt(zm());var zf="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Q=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Qf=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},Yf=(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")},Jf=(a,e,t,n)=>{if(a===zf){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=Yf(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 Qm(a,e,t,n,o){let i=await Qf({suiClient:a.rpcClient,address:e,type:t});return Jf(Q(t),i.map(c=>({balance:BigInt(c.balance),objectId:c.coinObjectId})),n,o)}var He=(a,e,t,n,o)=>{let i={poolId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,tickSpacing:n.tickSpacing,isStable:n.isStable};n?.rewarders&&n?.rewarders.length>0&&a.Pool.collectAllRewards({txb:o,pool:i,rewarders:n.rewarders.map(s=>({coin_type:s.coinType,flow_rate:s.flowRate,reward_amount:s.rewardAmount,rewards_allocated:s.rewardsAllocated,hasEnded:s.hasEnded})),positionId:t.objectId,transferToAddress:e}),a.Pool.collectFee({txb:o,pool:i,positionId:t.objectId,transferToAddress:e})};async function Ym({sdk:a,address:e,positionId:t,pool:n,txb:o,targetCoinType:i,slippage:s}){let c={poolId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,tickSpacing:n.tickSpacing,isStable:n.isStable},m=n.rewarders.map(S=>S.coinType),b=await a.Pool.getAllPools();return m.length>0&&(console.log("claimRewardsAsTargetCoin input",{pool:c,positionId:t,rewarderCoinTypes:m,targetCoinType:i,slippage:s,toAddress:e}),await a.Pool.claimRewardsAs({txb:o,pool:c,positionId:t,rewarderCoinTypes:m,targetCoinType:i,slippage:s,toAddress:e,pools:b})),await a.Pool.claimFeeAs({txb:o,pool:c,positionId:t,targetCoinType:i,slippage:s,toAddress:e,pools:b}),o}function W(a,e,t){let n=a.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function Zf(a){let e;return(a&1)!==0?e=new R.default("79232123823359799118286999567"):e=new R.default("79228162514264337593543950336"),(a&2)!==0&&(e=W(e.mul(new R.default("79236085330515764027303304731")),96,256)),(a&4)!==0&&(e=W(e.mul(new R.default("79244008939048815603706035061")),96,256)),(a&8)!==0&&(e=W(e.mul(new R.default("79259858533276714757314932305")),96,256)),(a&16)!==0&&(e=W(e.mul(new R.default("79291567232598584799939703904")),96,256)),(a&32)!==0&&(e=W(e.mul(new R.default("79355022692464371645785046466")),96,256)),(a&64)!==0&&(e=W(e.mul(new R.default("79482085999252804386437311141")),96,256)),(a&128)!==0&&(e=W(e.mul(new R.default("79736823300114093921829183326")),96,256)),(a&256)!==0&&(e=W(e.mul(new R.default("80248749790819932309965073892")),96,256)),(a&512)!==0&&(e=W(e.mul(new R.default("81282483887344747381513967011")),96,256)),(a&1024)!==0&&(e=W(e.mul(new R.default("83390072131320151908154831281")),96,256)),(a&2048)!==0&&(e=W(e.mul(new R.default("87770609709833776024991924138")),96,256)),(a&4096)!==0&&(e=W(e.mul(new R.default("97234110755111693312479820773")),96,256)),(a&8192)!==0&&(e=W(e.mul(new R.default("119332217159966728226237229890")),96,256)),(a&16384)!==0&&(e=W(e.mul(new R.default("179736315981702064433883588727")),96,256)),(a&32768)!==0&&(e=W(e.mul(new R.default("407748233172238350107850275304")),96,256)),(a&65536)!==0&&(e=W(e.mul(new R.default("2098478828474011932436660412517")),96,256)),(a&131072)!==0&&(e=W(e.mul(new R.default("55581415166113811149459800483533")),96,256)),(a&262144)!==0&&(e=W(e.mul(new R.default("38992368544603139932233054999993551")),96,256)),W(e,32,256)}function th(a){let e=Math.abs(a),t;return(e&1)!==0?t=new R.default("18445821805675392311"):t=new R.default("18446744073709551616"),(e&2)!==0&&(t=W(t.mul(new R.default("18444899583751176498")),64,256)),(e&4)!==0&&(t=W(t.mul(new R.default("18443055278223354162")),64,256)),(e&8)!==0&&(t=W(t.mul(new R.default("18439367220385604838")),64,256)),(e&16)!==0&&(t=W(t.mul(new R.default("18431993317065449817")),64,256)),(e&32)!==0&&(t=W(t.mul(new R.default("18417254355718160513")),64,256)),(e&64)!==0&&(t=W(t.mul(new R.default("18387811781193591352")),64,256)),(e&128)!==0&&(t=W(t.mul(new R.default("18329067761203520168")),64,256)),(e&256)!==0&&(t=W(t.mul(new R.default("18212142134806087854")),64,256)),(e&512)!==0&&(t=W(t.mul(new R.default("17980523815641551639")),64,256)),(e&1024)!==0&&(t=W(t.mul(new R.default("17526086738831147013")),64,256)),(e&2048)!==0&&(t=W(t.mul(new R.default("16651378430235024244")),64,256)),(e&4096)!==0&&(t=W(t.mul(new R.default("15030750278693429944")),64,256)),(e&8192)!==0&&(t=W(t.mul(new R.default("12247334978882834399")),64,256)),(e&16384)!==0&&(t=W(t.mul(new R.default("8131365268884726200")),64,256)),(e&32768)!==0&&(t=W(t.mul(new R.default("3584323654723342297")),64,256)),(e&65536)!==0&&(t=W(t.mul(new R.default("696457651847595233")),64,256)),(e&131072)!==0&&(t=W(t.mul(new R.default("26294789957452057")),64,256)),(e&262144)!==0&&(t=W(t.mul(new R.default("37481735321082")),64,256)),t}var Jm=(a,e,t)=>{let n=Cn.TickMath.convertI32ToSigned(t?a+a%(e??1):a-a%(e??1));return n>0?new R.default(Zf(n)):new R.default(th(n))};function td(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 ce({address:a,coinType:e,coinAmount:t,coinDecimals:n,tx:o,mmt:i}){let s=td(t,n),c;return Number(t)?c=await Qm(i,a,Q(e),s,o):[c]=o.moveCall({target:"0x2::coin::zero",typeArguments:[e],arguments:[]}),c}function ed({mmt:a,tx:e,poolModel:t,selectedLowTick:n,selectedHighTick:o}){let i=Jm(Cn.TickMath.convertI32ToSigned(n),t.tickSpacing),s=Jm(Cn.TickMath.convertI32ToSigned(o),t.tickSpacing);return a.Position.openPosition({txb:e,pool:t,lowerTickSqrtPrice:i.toString(),upperTickSqrtPrice:s.toString()})}var eh=(a,e)=>{let n=1e4-Math.floor(e*100);return a*BigInt(n)/BigInt(1e4)};function Nr(a,e,t){let n=td(a,e);return Number(a)===0?BigInt(0):eh(n,t)}async function Xe({poolId:a,currentSqrtPrice:e,tokenX:t,tokenY:n,slippagePercentage:o,isTokenX:i,suiClient:s}){let{object:c}=await s.getObject({objectId:a,include:{json:!0}}),m=c?.json?.sqrt_price??e,b=Cn.TickMath.sqrtPriceX64ToPrice(new R.default(m?.toString()),t.decimals,n.decimals),S=i?(100-o)/100:(100+o)/100,w=Cn.TickMath.priceToSqrtPriceX64(b.mul(S),t.decimals,n.decimals);return BigInt(w.toString())}var nd=async(a,e,t,n,o,i,s,c,m,b)=>{let S=await ce({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:n,coinDecimals:i.tokenX.decimals,tx:e}),w=await ce({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:o,coinDecimals:i.tokenY.decimals,tx:e}),C={poolId:s,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing,isStable:i.isStable},k=ed({mmt:a,tx:e,poolModel:C,selectedLowTick:c,selectedHighTick:m}),D=Nr(n,i.tokenX.decimals,b),M=Nr(o,i.tokenY.decimals,b);await a.Pool.addLiquidity({txb:e,pool:C,position:k,coinX:S,coinY:w,minAmountX:D,minAmountY:M,transferToAddress:t,useMvr:!0}),e.transferObjects([k],e.pure.address(t))},od=async(a,e,t,n,o,i,s,c,m,b,S)=>{try{let w=await ce({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={poolId:s.poolId,tokenXType:Q(s.tokenX.coinType),tokenYType:Q(s.tokenY.coinType),tickSpacing:s.tickSpacing,isStable:s.isStable},k=ed({mmt:a,tx:e,poolModel:C,selectedLowTick:c,selectedHighTick:m}),D=await Xe({suiClient:t,poolId:s.poolId,currentSqrtPrice:s.currentSqrtPrice,tokenX:s.tokenX,tokenY:s.tokenY,slippagePercentage:b,isTokenX:i});await a.Pool.zapInLiquidity({txb:e,pool:C,position:k,inputCoin:w,isXtoY:i,limitSqrtPrice:D,slippagePercentage:S,transferToAddress:n,useMvr:!0}),e.transferObjects([k],e.pure.address(n))}catch(w){console.error(w)}},ad=async(a,e,t,n,o,i,s,c)=>{let m=await ce({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:n,coinDecimals:i.tokenX.decimals,tx:e}),b=await ce({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:o,coinDecimals:i.tokenY.decimals,tx:e}),S={poolId:i.poolId,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing,isStable:i.isStable},w=Nr(n,i.tokenX.decimals,c),C=Nr(o,i.tokenY.decimals,c);await a.Pool.addLiquidity({txb:e,pool:S,position:s,coinX:m,coinY:b,minAmountX:w,minAmountY:C,transferToAddress:t})},id=async(a,e,t,n,o,i,s,c,m)=>{try{let b=await ce({mmt:a,address:t,coinType:o?i.tokenX.coinType:i.tokenY.coinType,coinAmount:n,coinDecimals:o?i.tokenX.decimals:i.tokenY.decimals,tx:e}),S={poolId:i.poolId,tokenXType:i.tokenX.coinType,tokenYType:i.tokenY.coinType,tickSpacing:i.tickSpacing,isStable:i.isStable},w=await Xe({suiClient:a.rpcClient,poolId:i.poolId,currentSqrtPrice:i.currentSqrtPrice,tokenX:i.tokenX,tokenY:i.tokenY,slippagePercentage:c,isTokenX:o});await a.Pool.zapInLiquidity({txb:e,pool:S,position:s,inputCoin:b,isXtoY:o,limitSqrtPrice:w,slippagePercentage:m,transferToAddress:t})}catch(b){throw console.error(b),b}},rd=(a,e)=>BigInt(e===100?a:new Zm.default(a).multipliedBy(e/100).toFixed(0)),sd=async(a,e,t,n,o,i)=>{let s=rd(t.liquidity,o),c=n.tokenX.coinType,m=n.tokenY.coinType,b={poolId:n.poolId,tokenXType:c,tokenYType:m,tickSpacing:n.tickSpacing,isStable:n.isStable};await a.Pool.removeLiquidity({txb:i,pool:b,positionId:t.objectId,liquidity:s,minAmountX:BigInt(0),minAmountY:BigInt(0),transferToAddress:e}),He(a,e,t,n,i),o===100&&a.Position.closePosition({txb:i,positionId:t.objectId})},cd=async({sdk:a,address:e,position:t,pool:n,withdrawPercentage:o,txb:i,targetCoinType:s,slippage:c})=>{let m=rd(t.liquidity,o),b=Q(n.tokenX.coinType),S=Q(n.tokenY.coinType),w=Q(s)===S,C={poolId:n.poolId,tokenXType:b,tokenYType:S,tickSpacing:n.tickSpacing,isStable:n.isStable},k=a.Pool.removeLiquidity({txb:i,pool:C,positionId:t.objectId,liquidity:m,minAmountX:BigInt(0),minAmountY:BigInt(0)}),D=k?.removeLpCoinA,M=k?.removeLpCoinB;if(!D||!M)throw new Error("Remove liquidity Failed: empty remove result");let q=await Xe({suiClient:a.rpcClient,poolId:n.poolId,currentSqrtPrice:n.currentSqrtPrice,tokenX:n.tokenX,tokenY:n.tokenY,isTokenX:w,slippagePercentage:c}),U=w?D:M,G=i.moveCall({target:"0x2::coin::value",arguments:[U],typeArguments:[w?b:S]});i.transferObjects([w?M:D],e),a.Pool.swap({txb:i,transferToAddress:e,pool:C,limitSqrtPrice:q,amount:G,inputCoin:U,isXtoY:w}),He(a,e,t,n,i),o===100&&a.Position.closePosition({txb:i,positionId:t.objectId})};var ld=require("@mmt-finance/clmm-sui-sdk"),ud=require("@mmt-finance/ve-sdk-v1");function Bt(a){return new ld.MmtSDK({network:"mainnet",client:a})}function Yt(a){return new ud.VeMMT(a,"mainnet")}var Wr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{address:i,amountA:s,amountB:c,pool:m,selectedLowTick:b,selectedHighTick:S,slippage:w}=o,C=new pd.Transaction;return await nd(n,C,i,s,c,m,m.poolId,b,S,w),C}static fromData(t){return new a(t)}};var md=require("@mysten/sui/transactions");var _r=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{address:i,amount:s,isTokenX:c,pool:m,selectedLowTick:b,selectedHighTick:S,swapSlippage:w,addLiquiditySlippage:C}=o,k=new md.Transaction;return await od(n,k,t.suiGrpcClient,i,s,c,m,b,S,w,C),k}static fromData(t){return new a(t)}};var Td=require("@mysten/sui/transactions");var xn="0x35169bc93e1fddfcf3a82a9eae726d349689ed59e4b065369af8789fe59f8608::mmt::MMT";var to=async a=>{let e=await a.getSyncEpochInfo();if(!e)throw new Error("Failed to sync epoch");return e},dd=async(a,e,t,n,o,i,s,c)=>{let m=Number(n);if(!n||Number.isNaN(m)||m<=0)throw new Error(`Bond Failed: Invalid amount: ${n}. Amount must be greater than 0`);if(!i&&!s)throw new Error("Bond Failed: Failed to calculate unbond date");if(typeof s!="number"&&!i)throw new Error("Bond Failed: Invalid unbond date");let b=await ce({mmt:a,tx:c,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals});if(!b)throw new Error(`Bond Failed: Failed to get coin object for ${t.coinType}, amount: ${n}`);let S=await to(e);await e.syncOrAdvanceEpoch(c,S.currentEpoch,S.syncedEpoch);let w=c.getData().commands.length;i?await e.createMaxBond(c,b,o):await e.createBond(c,b,BigInt(s),o);let k=c.getData().commands.length;if(k===0)throw new Error(`Bond Failed: Transaction has no commands. enableAutoMaxBond: ${i}, unbondAt: ${s}, amount: ${n}`);if(k===w)throw new Error(`Bond Failed: No new commands were added by bond operation. Commands before: ${w}, after: ${k}`)},fd=async(a,e,t,n,o,i,s,c)=>{let m=await to(a);if(await a.syncOrAdvanceEpoch(c,m.currentEpoch,m.syncedEpoch),await a.claimReward(c,t,e),o)i||await a.setNormal(c,t);else if(i)await a.setMaxBond(c,t);else{if(typeof s!="number")throw new Error("Extend Failed: Failed to calculate unbond date");if(s<n)throw new Error("Extend Failed: New duration cannot be less than current duration");await a.extend(c,t,s)}},hd=async(a,e,t,n,o)=>{let i=await to(a);await a.syncOrAdvanceEpoch(o,i.currentEpoch,i.syncedEpoch),await a.claimReward(o,t,e),await n.reduce(async(s,c)=>{await s,await a.claimReward(o,c,e),await a.merge(o,t,c)},Promise.resolve())},gd=async(a,e,t,n)=>{let o=await to(a);await a.syncOrAdvanceEpoch(n,o.currentEpoch,o.syncedEpoch),await a.claimReward(n,t,e),await a.unbond(n,t,e)},yd=async(a,e,t,n)=>{if(t.length>0&&t.some(o=>o.userRewardAmount>0)){let o=await to(a);await a.syncOrAdvanceEpoch(n,o.currentEpoch,o.syncedEpoch),await t.reduce(async(i,s)=>{await i,s.userRewardAmount>0&&await a.claimReward(n,s.veId,e)},Promise.resolve())}},bd=async(a,e,t,n,o,i,s,c,m)=>{let b=Q(i),S=[];for(let G of n)if(G.userRewardAmount>0){let $=await e.buildClaimRewardCoin(o,G.veId);S.push($)}let w=[];for(let G of S)Array.isArray(G)?w.push(...G):w.push(G);if(w.length===0)return;if(i===Q(xn)){o.transferObjects(w,o.pure.address(t));return}let C=c?.[i]?.[xn];if(!C||C.length===0)throw new Error(`No swap route found from ${xn} to ${i}`);let[k,...D]=w;D.length>0&&o.mergeCoins(k,D);let M=k,q=o.moveCall({target:"0x2::coin::value",arguments:[M],typeArguments:[xn]}),U=Q(xn);for(let G=0;G<C.length;G++){let $=C[G],E=m.find(X=>X.poolId===$);if(!E)throw new Error(`Pool ${$} not found`);let _t=Q(E.tokenXType||E.tokenX?.coinType||"")===U,le={poolId:E.poolId,tokenXType:E.tokenXType||E.tokenX?.coinType||"",tokenYType:E.tokenYType||E.tokenY?.coinType||"",tickSpacing:E.tickSpacing,isStable:E.isStable},eo=await Xe({suiClient:a.rpcClient,poolId:E.poolId,currentSqrtPrice:E.currentSqrtPrice,tokenX:E.tokenX,tokenY:E.tokenY,slippagePercentage:s,isTokenX:_t}),{outputCoin:kn,leftoverCoin:ze}=a.Pool.swap({txb:o,pool:le,amount:q,inputCoin:M,isXtoY:_t,limitSqrtPrice:eo})||{};if(!kn||!ze)throw new Error(`Swap Failed: empty swap result for pool ${$}`);if(o.transferObjects([ze],o.pure.address(t)),M=kn,U=_t?Q(E.tokenYType||E.tokenY?.coinType||""):Q(E.tokenXType||E.tokenX?.coinType||""),U===i){o.transferObjects([M],o.pure.address(t));return}q=o.moveCall({target:"0x2::coin::value",arguments:[M],typeArguments:[U]})}o.transferObjects([M],o.pure.address(t))};var Lr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),o=Yt(t.suiGrpcClient),{params:i}=this.data,{address:s,positions:c,pools:m,veMMTs:b}=i,S=new Td.Transaction;for(let w of c){let C=m.find(k=>k.poolId===w.poolId);C&&He(n,s,w,C,S)}return await yd(o,s,b,S),S}static fromData(t){return new a(t)}};var Sd=require("@mysten/sui/transactions");var jr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),o=Yt(t.suiGrpcClient),{params:i}=this.data,{claimVeMMTParams:s}=i,{address:c,veMMTs:m,targetCoinType:b,slippage:S,claimRoutes:w,pools:C}=s,k=new Sd.Transaction;return await Promise.all(i.claimParams.map(D=>Ym({...D,sdk:n,txb:k}))),await bd(n,o,c,m,k,b,S,w,C),k}static fromData(t){return new a(t)}};var wd=require("@mysten/sui/transactions");var Ur=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{address:i,position:s,pool:c}=o,m=new wd.Transaction;return He(n,i,s,c,m),m}static fromData(t){return new a(t)}};var Id=require("@mysten/sui/transactions");var qr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{address:i,amountA:s,amountB:c,pool:m,positionObjectId:b,slippage:S}=o,w=new Id.Transaction;return await ad(n,w,i,s,c,m,b,S),w}static fromData(t){return new a(t)}};var Cd=require("@mysten/sui/transactions");var Fr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{address:i,amount:s,isTokenX:c,pool:m,positionObjectId:b,swapSlippage:S,addLiquiditySlippage:w}=o,C=new Cd.Transaction;return await id(n,C,i,s,c,m,b,S,w),C}static fromData(t){return new a(t)}};var xd=require("@mysten/sui/transactions");var Kr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),{params:o}=this.data,{pool:i,position:s,address:c,withdrawPercentage:m,zapOutOn:b,targetCoinType:S,slippage:w}=o,C=new xd.Transaction;return b?await cd({sdk:n,address:c,position:s,pool:i,withdrawPercentage:m,txb:C,targetCoinType:S,slippage:w}):await sd(n,c,s,i,m,C),C}static fromData(t){return new a(t)}};var pc=require("@mysten/sui/transactions"),mc=require("@suilend/springsui-sdk"),uc={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},kd=async(a,e,t)=>{let n=await mc.LstClient.initialize(a,a,uc),o=new pc.Transaction,[i]=o.splitCoins(o.gas,[BigInt(t)]),s=n.mint(o,i);return o.transferObjects([s],e),o},Dd=async(a,e,t)=>{let n=await mc.LstClient.initialize(a,a,uc),o=await a.getCoins({owner:e,coinType:uc.type,limit:1e3});if(o.data.length===0)throw new Error("No lst coins found");let i=new pc.Transaction,s=o.data[0];o.data.length>1&&i.mergeCoins(s.coinObjectId,o.data.slice(1).map(b=>b.coinObjectId));let[c]=i.splitCoins(s.coinObjectId,[BigInt(t)]),m=n.redeem(i,c);return i.transferObjects([m],e),i};var Gr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return kd(t.suiGrpcClient,o,i)}static fromData(t){return new a(t)}};var Pd=require("@mysten/sui/transactions");var Ad=require("@mmt-finance/clmm-sui-sdk");function vd(a){return Array.isArray(a)&&(a.length===0||typeof a[0]=="string")}function nh(a){return typeof a=="object"&&a!==null&&"coinType"in a&&"decimals"in a}function oh(a,e){if(!/^\d+$/.test(a))return a;if(e<=0)return a.replace(/^0+/,"")||"0";let t=BigInt(a),n=10n**BigInt(e),o=t/n,i=t%n;if(i===0n)return o.toString();let s=i.toString().padStart(e,"0").replace(/0+$/,"");return`${o}.${s}`}function ah(a){return{poolSource:"mmt-v3",poolId:a.poolId,tokenXType:a.tokenXType,tokenYType:a.tokenYType,tickSpacing:a.tickSpacing,lpFeesPercent:a.lpFeesPercent,feeRate:Number(a.lpFeesPercent)||0,protocolFeesPercent:a.protocolFeesPercent,isStable:a.isStable,currentSqrtPrice:a.currentSqrtPrice,currentTickIndex:a.currentTickIndex,liquidity:a.liquidity,liquidityHM:a.liquidityHM,tokenXReserve:a.tokenXReserve,tokenYReserve:a.tokenYReserve,tvl:a.tvl,apy:a.apy,volume24h:a.volume24h,fees24h:a.fees24h,timestamp:a.timestamp,rewarders:(a.rewarders||[]).map(e=>({coinType:e.coin_type,flowRate:e.flow_rate,hasEnded:e.hasEnded,rewardAmount:e.reward_amount,rewardsAllocated:e.rewards_allocated})),tokenX:a.tokenX,tokenY:a.tokenY,aprBreakdown:{total:a.aprBreakdown?.total??a.apy??"0",fee:a.aprBreakdown?.fee??"0",rewards:(a.aprBreakdown?.rewards||[]).map(e=>({coinType:e.coinType,apr:e.rewarderApr?.toString?.()??String(e.rewarderApr??"0"),amountPerDay:Number(e.amountPerDay??0)}))}}}function ih(a,e){let t=Q(e);for(let n of a){if(Q(n.tokenX?.coinType||"")===t)return n.tokenX;if(Q(n.tokenY?.coinType||"")===t)return n.tokenY}}async function Md(a,e){if(e.mode==="aggregator")throw new Error("Swap Failed: aggregator mode is not supported in MSafe rebuild path yet");let t=e.address,n=e.slippage??e.slippagePct;if(typeof n!="number")throw new Error("Swap Failed: missing slippage");if(!vd(e.route)&&nh(e.tokenIn))return{route:e.route,tokenIn:e.tokenIn,amountIn:e.amountIn,address:t,slippage:n};if(!vd(e.route))throw new Error("Swap Failed: route must be NormalizedPool[] or poolId string[]");if(typeof e.tokenIn!="string")throw new Error("Swap Failed: tokenIn must be a coinType string when route is poolId[]");if(e.route.length===0)throw new Error("Swap Failed: empty route");let i=(await Promise.all(e.route.map(m=>a.Pool.getPool(m)))).map(ah),s=ih(i,e.tokenIn);if(!s){let m=await a.Pool.getToken(e.tokenIn);s={coinType:m.coinType,tokenName:m.name,ticker:m.ticker,iconUrl:m.iconUrl,decimals:m.decimals,price:m.price,description:m.description,isVerified:m.isVerified}}let c=oh(e.amountIn,s.decimals);return{route:i,tokenIn:s,amountIn:c,address:t,slippage:n}}var Od=async(a,e,t,n,o,i,s)=>{let c=await ce({mmt:a,tx:i,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals}),m=i.moveCall({target:"0x2::coin::value",typeArguments:[t.coinType],arguments:[c]}),b=t.coinType;for(let S=0;S<e.length;S+=1){let w=e[S],{poolId:C,tokenX:k,tokenY:D,isStable:M,currentSqrtPrice:q}=w;if(!k?.coinType||!D?.coinType)throw new Error(`Swap Failed: route[${S}] is missing tokenX/tokenY after resolve. poolId=${w.poolId}`);let{id:U,isReverse:G}=Ad.Utils.mappedMmtV3Pool[C]||{id:C,isReverse:!1},$=Q(k.coinType)===Q(b);$=G?!$:$;let E=G?D:k,ye=G?k:D,_t=await Xe({poolId:U,tokenX:E,tokenY:ye,slippagePercentage:s,isTokenX:$,suiClient:a.rpcClient,currentSqrtPrice:q}),le=a.Pool.swap({txb:i,pool:{poolId:U,tokenXType:E.coinType,tokenYType:ye.coinType,tickSpacing:w.tickSpacing,isStable:M},amount:m,inputCoin:c,isXtoY:$,limitSqrtPrice:_t});if(!le?.outputCoin)throw new Error("Swap Failed: empty swap result");i.transferObjects([c],i.pure.address(o)),c=le.outputCoin,b=$?ye.coinType:E.coinType,m=i.moveCall({target:"0x2::coin::value",typeArguments:[b],arguments:[c]})}i.transferObjects([c],i.pure.address(o))};var Vr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),o=await Md(n,this.data.params),i=new Pd.Transaction;return await Od(n,o.route,o.tokenIn,o.amountIn,o.address,i,o.slippage),i}static fromData(t){return new a(t)}};var $r=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:i}=n;return Dd(t.suiGrpcClient,o,i)}static fromData(t){return new a(t)}};var Rd=require("@mysten/sui/transactions");var Hr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Bt(t.suiGrpcClient),o=Yt(t.suiGrpcClient),{params:i}=this.data,{token:s,amount:c,address:m,enableAutoMaxBond:b,unbondAt:S}=i,w=new Rd.Transaction;return await dd(n,o,s,c,m,b,S,w),w}static fromData(t){return new a(t)}};var Bd=require("@mysten/sui/transactions");var Xr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Yt(t.suiGrpcClient),{params:o}=this.data,{address:i,veId:s,currentUnbondAt:c,isCurrentlyMaxBond:m,enableAutoMaxBond:b,unbondAt:S}=o,w=new Bd.Transaction;return await fd(n,i,s,c,m,b,S,w),w}static fromData(t){return new a(t)}};var Ed=require("@mysten/sui/transactions");var zr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Yt(t.suiGrpcClient),{params:o}=this.data,{address:i,veId:s,selectedVeMMTIds:c}=o,m=new Ed.Transaction;return await hd(n,i,s,c,m),m}static fromData(t){return new a(t)}};var Nd=require("@mysten/sui/transactions");var Qr=class a extends N{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Yt(t.suiGrpcClient),{params:o}=this.data,{address:i,veId:s}=o,c=new Nd.Transaction;return await gd(n,i,s,c),c}static fromData(t){return new a(t)}};var Yr=class{application="mmt-dex";supportSDK="@mysten/sui-v2";async deserialize(e){let{appContext:t}=e;return{txType:Wd.TransactionType.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=Vr.fromData(e.intentionData);break;case"AddLiquidity":t=Wr.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=_r.fromData(e.intentionData);break;case"ClaimRewards":t=Ur.fromData(e.intentionData);break;case"ClaimAllRewards":t=Lr.fromData(e.intentionData);break;case"ClaimRewardsAs":t=jr.fromData(e.intentionData);break;case"RemoveLiquidity":t=Kr.fromData(e.intentionData);break;case"StakeXSui":t=Gr.fromData(e.intentionData);break;case"UnstakeXSui":t=$r.fromData(e.intentionData);break;case"ManageLiquidity":t=qr.fromData(e.intentionData);break;case"ManageLiquiditySingleSide":t=Fr.fromData(e.intentionData);break;case"Bond":t=Hr.fromData(e.intentionData);break;case"Extend":t=Xr.fromData(e.intentionData);break;case"Merge":t=zr.fromData(e.intentionData);break;case"Unbond":t=Qr.fromData(e.intentionData);break;default:throw new Error(`not implemented ${e.txSubType}`)}return t.build({suiGrpcClient:e.suiGrpcClient,account:e.account,network:e.network})}};var rh=Qa.fromHelpers([new Ba,new Va,new Oa,new $a,new aa,new yr,new Yr,new Pi,new Cr,new Oo,new qi,new Qi,new lo,new Er,new tr]);
1
+ "use strict";var Cd=Object.create;var Jn=Object.defineProperty;var xd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var Dd=Object.getPrototypeOf,vd=Object.prototype.hasOwnProperty;var Ad=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),us=(r,e)=>{for(var t in e)Jn(r,t,{get:e[t],enumerable:!0})},Sc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kd(e))!vd.call(r,o)&&o!==t&&Jn(r,o,{get:()=>e[o],enumerable:!(n=xd(e,o))||n.enumerable});return r};var _t=(r,e,t)=>(t=r!=null?Cd(Dd(r)):{},Sc(e||!r||!r.__esModule?Jn(t,"default",{value:r,enumerable:!0}):t,r)),Md=r=>Sc(Jn({},"__esModule",{value:!0}),r);var Em=Ad((Nm,Zs)=>{"use strict";(function(r,e){"use strict";function t(y,i){if(!y)throw new Error(i||"Assertion failed")}function n(y,i){y.super_=i;var p=function(){};p.prototype=i.prototype,y.prototype=new p,y.prototype.constructor=y}function o(y,i,p){if(o.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((i==="le"||i==="be")&&(p=i,i=10),this._init(y||0,i||10,p||"be"))}typeof r=="object"?r.exports=o:e.BN=o,o.BN=o,o.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=require("buffer").Buffer}catch{}o.isBN=function(i){return i instanceof o?!0:i!==null&&typeof i=="object"&&i.constructor.wordSize===o.wordSize&&Array.isArray(i.words)},o.max=function(i,p){return i.cmp(p)>0?i:p},o.min=function(i,p){return i.cmp(p)<0?i:p},o.prototype._init=function(i,p,u){if(typeof i=="number")return this._initNumber(i,p,u);if(typeof i=="object")return this._initArray(i,p,u);p==="hex"&&(p=16),t(p===(p|0)&&p>=2&&p<=36),i=i.toString().replace(/\s+/g,"");var d=0;i[0]==="-"&&(d++,this.negative=1),d<i.length&&(p===16?this._parseHex(i,d,u):(this._parseBase(i,p,d),u==="le"&&this._initArray(this.toArray(),p,u)))},o.prototype._initNumber=function(i,p,u){i<0&&(this.negative=1,i=-i),i<67108864?(this.words=[i&67108863],this.length=1):i<4503599627370496?(this.words=[i&67108863,i/67108864&67108863],this.length=2):(t(i<9007199254740992),this.words=[i&67108863,i/67108864&67108863,1],this.length=3),u==="le"&&this._initArray(this.toArray(),p,u)},o.prototype._initArray=function(i,p,u){if(t(typeof i.length=="number"),i.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(i.length/3),this.words=new Array(this.length);for(var d=0;d<this.length;d++)this.words[d]=0;var h,T,I=0;if(u==="be")for(d=i.length-1,h=0;d>=0;d-=3)T=i[d]|i[d-1]<<8|i[d-2]<<16,this.words[h]|=T<<I&67108863,this.words[h+1]=T>>>26-I&67108863,I+=24,I>=26&&(I-=26,h++);else if(u==="le")for(d=0,h=0;d<i.length;d+=3)T=i[d]|i[d+1]<<8|i[d+2]<<16,this.words[h]|=T<<I&67108863,this.words[h+1]=T>>>26-I&67108863,I+=24,I>=26&&(I-=26,h++);return this._strip()};function s(y,i){var p=y.charCodeAt(i);if(p>=48&&p<=57)return p-48;if(p>=65&&p<=70)return p-55;if(p>=97&&p<=102)return p-87;t(!1,"Invalid character in "+y)}function c(y,i,p){var u=s(y,p);return p-1>=i&&(u|=s(y,p-1)<<4),u}o.prototype._parseHex=function(i,p,u){this.length=Math.ceil((i.length-p)/6),this.words=new Array(this.length);for(var d=0;d<this.length;d++)this.words[d]=0;var h=0,T=0,I;if(u==="be")for(d=i.length-1;d>=p;d-=2)I=c(i,p,d)<<h,this.words[T]|=I&67108863,h>=18?(h-=18,T+=1,this.words[T]|=I>>>26):h+=8;else{var f=i.length-p;for(d=f%2===0?p+1:p;d<i.length;d+=2)I=c(i,p,d)<<h,this.words[T]|=I&67108863,h>=18?(h-=18,T+=1,this.words[T]|=I>>>26):h+=8}this._strip()};function m(y,i,p,u){for(var d=0,h=0,T=Math.min(y.length,p),I=i;I<T;I++){var f=y.charCodeAt(I)-48;d*=u,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<u,"Invalid character"),d+=h}return d}o.prototype._parseBase=function(i,p,u){this.words=[0],this.length=1;for(var d=0,h=1;h<=67108863;h*=p)d++;d--,h=h/p|0;for(var T=i.length-u,I=T%d,f=Math.min(T,T-I)+u,l=0,g=u;g<f;g+=d)l=m(i,g,g+d,p),this.imuln(h),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(I!==0){var A=1;for(l=m(i,g,i.length,p),g=0;g<I;g++)A*=p;this.imuln(A),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},o.prototype.copy=function(i){i.words=new Array(this.length);for(var p=0;p<this.length;p++)i.words[p]=this.words[p];i.length=this.length,i.negative=this.negative,i.red=this.red};function b(y,i){y.words=i.words,y.length=i.length,y.negative=i.negative,y.red=i.red}if(o.prototype._move=function(i){b(i,this)},o.prototype.clone=function(){var i=new o(null);return this.copy(i),i},o.prototype._expand=function(i){for(;this.length<i;)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")]=S}catch{o.prototype.inspect=S}else o.prototype.inspect=S;function S(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var w=["","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(i,p){i=i||10,p=p|0||1;var u;if(i===16||i==="hex"){u="";for(var d=0,h=0,T=0;T<this.length;T++){var I=this.words[T],f=((I<<d|h)&16777215).toString(16);h=I>>>24-d&16777215,d+=2,d>=26&&(d-=26,T--),h!==0||T!==this.length-1?u=w[6-f.length]+f+u:u=f+u}for(h!==0&&(u=h.toString(16)+u);u.length%p!==0;)u="0"+u;return this.negative!==0&&(u="-"+u),u}if(i===(i|0)&&i>=2&&i<=36){var l=C[i],g=x[i];u="";var A=this.clone();for(A.negative=0;!A.isZero();){var P=A.modrn(g).toString(i);A=A.idivn(g),A.isZero()?u=P+u:u=w[l-P.length]+P+u}for(this.isZero()&&(u="0"+u);u.length%p!==0;)u="0"+u;return this.negative!==0&&(u="-"+u),u}t(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var i=this.words[0];return this.length===2?i+=this.words[1]*67108864:this.length===3&&this.words[2]===1?i+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-i:i},o.prototype.toJSON=function(){return this.toString(16,2)},a&&(o.prototype.toBuffer=function(i,p){return this.toArrayLike(a,i,p)}),o.prototype.toArray=function(i,p){return this.toArrayLike(Array,i,p)};var D=function(i,p){return i.allocUnsafe?i.allocUnsafe(p):new i(p)};o.prototype.toArrayLike=function(i,p,u){this._strip();var d=this.byteLength(),h=u||Math.max(1,d);t(d<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var T=D(i,h),I=p==="le"?"LE":"BE";return this["_toArrayLike"+I](T,d),T},o.prototype._toArrayLikeLE=function(i,p){for(var u=0,d=0,h=0,T=0;h<this.length;h++){var I=this.words[h]<<T|d;i[u++]=I&255,u<i.length&&(i[u++]=I>>8&255),u<i.length&&(i[u++]=I>>16&255),T===6?(u<i.length&&(i[u++]=I>>24&255),d=0,T=0):(d=I>>>24,T+=2)}if(u<i.length)for(i[u++]=d;u<i.length;)i[u++]=0},o.prototype._toArrayLikeBE=function(i,p){for(var u=i.length-1,d=0,h=0,T=0;h<this.length;h++){var I=this.words[h]<<T|d;i[u--]=I&255,u>=0&&(i[u--]=I>>8&255),u>=0&&(i[u--]=I>>16&255),T===6?(u>=0&&(i[u--]=I>>24&255),d=0,T=0):(d=I>>>24,T+=2)}if(u>=0)for(i[u--]=d;u>=0;)i[u--]=0},Math.clz32?o.prototype._countBits=function(i){return 32-Math.clz32(i)}:o.prototype._countBits=function(i){var p=i,u=0;return p>=4096&&(u+=13,p>>>=13),p>=64&&(u+=7,p>>>=7),p>=8&&(u+=4,p>>>=4),p>=2&&(u+=2,p>>>=2),u+p},o.prototype._zeroBits=function(i){if(i===0)return 26;var p=i,u=0;return(p&8191)===0&&(u+=13,p>>>=13),(p&127)===0&&(u+=7,p>>>=7),(p&15)===0&&(u+=4,p>>>=4),(p&3)===0&&(u+=2,p>>>=2),(p&1)===0&&u++,u},o.prototype.bitLength=function(){var i=this.words[this.length-1],p=this._countBits(i);return(this.length-1)*26+p};function O(y){for(var i=new Array(y.bitLength()),p=0;p<i.length;p++){var u=p/26|0,d=p%26;i[p]=y.words[u]>>>d&1}return i}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var i=0,p=0;p<this.length;p++){var u=this._zeroBits(this.words[p]);if(i+=u,u!==26)break}return i},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(i){return this.negative!==0?this.abs().inotn(i).iaddn(1):this.clone()},o.prototype.fromTwos=function(i){return this.testn(i-1)?this.notn(i).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(i){for(;this.length<i.length;)this.words[this.length++]=0;for(var p=0;p<i.length;p++)this.words[p]=this.words[p]|i.words[p];return this._strip()},o.prototype.ior=function(i){return t((this.negative|i.negative)===0),this.iuor(i)},o.prototype.or=function(i){return this.length>i.length?this.clone().ior(i):i.clone().ior(this)},o.prototype.uor=function(i){return this.length>i.length?this.clone().iuor(i):i.clone().iuor(this)},o.prototype.iuand=function(i){var p;this.length>i.length?p=i:p=this;for(var u=0;u<p.length;u++)this.words[u]=this.words[u]&i.words[u];return this.length=p.length,this._strip()},o.prototype.iand=function(i){return t((this.negative|i.negative)===0),this.iuand(i)},o.prototype.and=function(i){return this.length>i.length?this.clone().iand(i):i.clone().iand(this)},o.prototype.uand=function(i){return this.length>i.length?this.clone().iuand(i):i.clone().iuand(this)},o.prototype.iuxor=function(i){var p,u;this.length>i.length?(p=this,u=i):(p=i,u=this);for(var d=0;d<u.length;d++)this.words[d]=p.words[d]^u.words[d];if(this!==p)for(;d<p.length;d++)this.words[d]=p.words[d];return this.length=p.length,this._strip()},o.prototype.ixor=function(i){return t((this.negative|i.negative)===0),this.iuxor(i)},o.prototype.xor=function(i){return this.length>i.length?this.clone().ixor(i):i.clone().ixor(this)},o.prototype.uxor=function(i){return this.length>i.length?this.clone().iuxor(i):i.clone().iuxor(this)},o.prototype.inotn=function(i){t(typeof i=="number"&&i>=0);var p=Math.ceil(i/26)|0,u=i%26;this._expand(p),u>0&&p--;for(var d=0;d<p;d++)this.words[d]=~this.words[d]&67108863;return u>0&&(this.words[d]=~this.words[d]&67108863>>26-u),this._strip()},o.prototype.notn=function(i){return this.clone().inotn(i)},o.prototype.setn=function(i,p){t(typeof i=="number"&&i>=0);var u=i/26|0,d=i%26;return this._expand(u+1),p?this.words[u]=this.words[u]|1<<d:this.words[u]=this.words[u]&~(1<<d),this._strip()},o.prototype.iadd=function(i){var p;if(this.negative!==0&&i.negative===0)return this.negative=0,p=this.isub(i),this.negative^=1,this._normSign();if(this.negative===0&&i.negative!==0)return i.negative=0,p=this.isub(i),i.negative=1,p._normSign();var u,d;this.length>i.length?(u=this,d=i):(u=i,d=this);for(var h=0,T=0;T<d.length;T++)p=(u.words[T]|0)+(d.words[T]|0)+h,this.words[T]=p&67108863,h=p>>>26;for(;h!==0&&T<u.length;T++)p=(u.words[T]|0)+h,this.words[T]=p&67108863,h=p>>>26;if(this.length=u.length,h!==0)this.words[this.length]=h,this.length++;else if(u!==this)for(;T<u.length;T++)this.words[T]=u.words[T];return this},o.prototype.add=function(i){var p;return i.negative!==0&&this.negative===0?(i.negative=0,p=this.sub(i),i.negative^=1,p):i.negative===0&&this.negative!==0?(this.negative=0,p=i.sub(this),this.negative=1,p):this.length>i.length?this.clone().iadd(i):i.clone().iadd(this)},o.prototype.isub=function(i){if(i.negative!==0){i.negative=0;var p=this.iadd(i);return i.negative=1,p._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(i),this.negative=1,this._normSign();var u=this.cmp(i);if(u===0)return this.negative=0,this.length=1,this.words[0]=0,this;var d,h;u>0?(d=this,h=i):(d=i,h=this);for(var T=0,I=0;I<h.length;I++)p=(d.words[I]|0)-(h.words[I]|0)+T,T=p>>26,this.words[I]=p&67108863;for(;T!==0&&I<d.length;I++)p=(d.words[I]|0)+T,T=p>>26,this.words[I]=p&67108863;if(T===0&&I<d.length&&d!==this)for(;I<d.length;I++)this.words[I]=d.words[I];return this.length=Math.max(this.length,I),d!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(i){return this.clone().isub(i)};function G(y,i,p){p.negative=i.negative^y.negative;var u=y.length+i.length|0;p.length=u,u=u-1|0;var d=y.words[0]|0,h=i.words[0]|0,T=d*h,I=T&67108863,f=T/67108864|0;p.words[0]=I;for(var l=1;l<u;l++){for(var g=f>>>26,A=f&67108863,P=Math.min(l,i.length-1),R=Math.max(0,l-y.length+1);R<=P;R++){var N=l-R|0;d=y.words[N]|0,h=i.words[R]|0,T=d*h+A,g+=T/67108864|0,A=T&67108863}p.words[l]=A|0,f=g|0}return f!==0?p.words[l]=f|0:p.length--,p._strip()}var U=function(i,p,u){var d=i.words,h=p.words,T=u.words,I=0,f,l,g,A=d[0]|0,P=A&8191,R=A>>>13,N=d[1]|0,L=N&8191,q=N>>>13,be=d[2]|0,F=be&8191,H=be>>>13,oc=d[3]|0,Y=oc&8191,J=oc>>>13,rc=d[4]|0,Z=rc&8191,tt=rc>>>13,ac=d[5]|0,et=ac&8191,nt=ac>>>13,ic=d[6]|0,ot=ic&8191,rt=ic>>>13,sc=d[7]|0,at=sc&8191,it=sc>>>13,cc=d[8]|0,st=cc&8191,ct=cc>>>13,lc=d[9]|0,lt=lc&8191,pt=lc>>>13,pc=h[0]|0,ut=pc&8191,mt=pc>>>13,uc=h[1]|0,dt=uc&8191,ft=uc>>>13,mc=h[2]|0,ht=mc&8191,gt=mc>>>13,dc=h[3]|0,yt=dc&8191,bt=dc>>>13,fc=h[4]|0,Tt=fc&8191,St=fc>>>13,hc=h[5]|0,wt=hc&8191,It=hc>>>13,gc=h[6]|0,Ct=gc&8191,xt=gc>>>13,yc=h[7]|0,kt=yc&8191,Dt=yc>>>13,bc=h[8]|0,vt=bc&8191,At=bc>>>13,Tc=h[9]|0,Mt=Tc&8191,Ot=Tc>>>13;u.negative=i.negative^p.negative,u.length=19,f=Math.imul(P,ut),l=Math.imul(P,mt),l=l+Math.imul(R,ut)|0,g=Math.imul(R,mt);var Vi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Vi>>>26)|0,Vi&=67108863,f=Math.imul(L,ut),l=Math.imul(L,mt),l=l+Math.imul(q,ut)|0,g=Math.imul(q,mt),f=f+Math.imul(P,dt)|0,l=l+Math.imul(P,ft)|0,l=l+Math.imul(R,dt)|0,g=g+Math.imul(R,ft)|0;var Hi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Hi>>>26)|0,Hi&=67108863,f=Math.imul(F,ut),l=Math.imul(F,mt),l=l+Math.imul(H,ut)|0,g=Math.imul(H,mt),f=f+Math.imul(L,dt)|0,l=l+Math.imul(L,ft)|0,l=l+Math.imul(q,dt)|0,g=g+Math.imul(q,ft)|0,f=f+Math.imul(P,ht)|0,l=l+Math.imul(P,gt)|0,l=l+Math.imul(R,ht)|0,g=g+Math.imul(R,gt)|0;var Xi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Xi>>>26)|0,Xi&=67108863,f=Math.imul(Y,ut),l=Math.imul(Y,mt),l=l+Math.imul(J,ut)|0,g=Math.imul(J,mt),f=f+Math.imul(F,dt)|0,l=l+Math.imul(F,ft)|0,l=l+Math.imul(H,dt)|0,g=g+Math.imul(H,ft)|0,f=f+Math.imul(L,ht)|0,l=l+Math.imul(L,gt)|0,l=l+Math.imul(q,ht)|0,g=g+Math.imul(q,gt)|0,f=f+Math.imul(P,yt)|0,l=l+Math.imul(P,bt)|0,l=l+Math.imul(R,yt)|0,g=g+Math.imul(R,bt)|0;var zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(zi>>>26)|0,zi&=67108863,f=Math.imul(Z,ut),l=Math.imul(Z,mt),l=l+Math.imul(tt,ut)|0,g=Math.imul(tt,mt),f=f+Math.imul(Y,dt)|0,l=l+Math.imul(Y,ft)|0,l=l+Math.imul(J,dt)|0,g=g+Math.imul(J,ft)|0,f=f+Math.imul(F,ht)|0,l=l+Math.imul(F,gt)|0,l=l+Math.imul(H,ht)|0,g=g+Math.imul(H,gt)|0,f=f+Math.imul(L,yt)|0,l=l+Math.imul(L,bt)|0,l=l+Math.imul(q,yt)|0,g=g+Math.imul(q,bt)|0,f=f+Math.imul(P,Tt)|0,l=l+Math.imul(P,St)|0,l=l+Math.imul(R,Tt)|0,g=g+Math.imul(R,St)|0;var Qi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Qi>>>26)|0,Qi&=67108863,f=Math.imul(et,ut),l=Math.imul(et,mt),l=l+Math.imul(nt,ut)|0,g=Math.imul(nt,mt),f=f+Math.imul(Z,dt)|0,l=l+Math.imul(Z,ft)|0,l=l+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(Y,ht)|0,l=l+Math.imul(Y,gt)|0,l=l+Math.imul(J,ht)|0,g=g+Math.imul(J,gt)|0,f=f+Math.imul(F,yt)|0,l=l+Math.imul(F,bt)|0,l=l+Math.imul(H,yt)|0,g=g+Math.imul(H,bt)|0,f=f+Math.imul(L,Tt)|0,l=l+Math.imul(L,St)|0,l=l+Math.imul(q,Tt)|0,g=g+Math.imul(q,St)|0,f=f+Math.imul(P,wt)|0,l=l+Math.imul(P,It)|0,l=l+Math.imul(R,wt)|0,g=g+Math.imul(R,It)|0;var Yi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Yi>>>26)|0,Yi&=67108863,f=Math.imul(ot,ut),l=Math.imul(ot,mt),l=l+Math.imul(rt,ut)|0,g=Math.imul(rt,mt),f=f+Math.imul(et,dt)|0,l=l+Math.imul(et,ft)|0,l=l+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,l=l+Math.imul(Z,gt)|0,l=l+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(Y,yt)|0,l=l+Math.imul(Y,bt)|0,l=l+Math.imul(J,yt)|0,g=g+Math.imul(J,bt)|0,f=f+Math.imul(F,Tt)|0,l=l+Math.imul(F,St)|0,l=l+Math.imul(H,Tt)|0,g=g+Math.imul(H,St)|0,f=f+Math.imul(L,wt)|0,l=l+Math.imul(L,It)|0,l=l+Math.imul(q,wt)|0,g=g+Math.imul(q,It)|0,f=f+Math.imul(P,Ct)|0,l=l+Math.imul(P,xt)|0,l=l+Math.imul(R,Ct)|0,g=g+Math.imul(R,xt)|0;var Ji=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Ji>>>26)|0,Ji&=67108863,f=Math.imul(at,ut),l=Math.imul(at,mt),l=l+Math.imul(it,ut)|0,g=Math.imul(it,mt),f=f+Math.imul(ot,dt)|0,l=l+Math.imul(ot,ft)|0,l=l+Math.imul(rt,dt)|0,g=g+Math.imul(rt,ft)|0,f=f+Math.imul(et,ht)|0,l=l+Math.imul(et,gt)|0,l=l+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,l=l+Math.imul(Z,bt)|0,l=l+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(Y,Tt)|0,l=l+Math.imul(Y,St)|0,l=l+Math.imul(J,Tt)|0,g=g+Math.imul(J,St)|0,f=f+Math.imul(F,wt)|0,l=l+Math.imul(F,It)|0,l=l+Math.imul(H,wt)|0,g=g+Math.imul(H,It)|0,f=f+Math.imul(L,Ct)|0,l=l+Math.imul(L,xt)|0,l=l+Math.imul(q,Ct)|0,g=g+Math.imul(q,xt)|0,f=f+Math.imul(P,kt)|0,l=l+Math.imul(P,Dt)|0,l=l+Math.imul(R,kt)|0,g=g+Math.imul(R,Dt)|0;var Zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Zi>>>26)|0,Zi&=67108863,f=Math.imul(st,ut),l=Math.imul(st,mt),l=l+Math.imul(ct,ut)|0,g=Math.imul(ct,mt),f=f+Math.imul(at,dt)|0,l=l+Math.imul(at,ft)|0,l=l+Math.imul(it,dt)|0,g=g+Math.imul(it,ft)|0,f=f+Math.imul(ot,ht)|0,l=l+Math.imul(ot,gt)|0,l=l+Math.imul(rt,ht)|0,g=g+Math.imul(rt,gt)|0,f=f+Math.imul(et,yt)|0,l=l+Math.imul(et,bt)|0,l=l+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,Tt)|0,l=l+Math.imul(Z,St)|0,l=l+Math.imul(tt,Tt)|0,g=g+Math.imul(tt,St)|0,f=f+Math.imul(Y,wt)|0,l=l+Math.imul(Y,It)|0,l=l+Math.imul(J,wt)|0,g=g+Math.imul(J,It)|0,f=f+Math.imul(F,Ct)|0,l=l+Math.imul(F,xt)|0,l=l+Math.imul(H,Ct)|0,g=g+Math.imul(H,xt)|0,f=f+Math.imul(L,kt)|0,l=l+Math.imul(L,Dt)|0,l=l+Math.imul(q,kt)|0,g=g+Math.imul(q,Dt)|0,f=f+Math.imul(P,vt)|0,l=l+Math.imul(P,At)|0,l=l+Math.imul(R,vt)|0,g=g+Math.imul(R,At)|0;var ts=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ts>>>26)|0,ts&=67108863,f=Math.imul(lt,ut),l=Math.imul(lt,mt),l=l+Math.imul(pt,ut)|0,g=Math.imul(pt,mt),f=f+Math.imul(st,dt)|0,l=l+Math.imul(st,ft)|0,l=l+Math.imul(ct,dt)|0,g=g+Math.imul(ct,ft)|0,f=f+Math.imul(at,ht)|0,l=l+Math.imul(at,gt)|0,l=l+Math.imul(it,ht)|0,g=g+Math.imul(it,gt)|0,f=f+Math.imul(ot,yt)|0,l=l+Math.imul(ot,bt)|0,l=l+Math.imul(rt,yt)|0,g=g+Math.imul(rt,bt)|0,f=f+Math.imul(et,Tt)|0,l=l+Math.imul(et,St)|0,l=l+Math.imul(nt,Tt)|0,g=g+Math.imul(nt,St)|0,f=f+Math.imul(Z,wt)|0,l=l+Math.imul(Z,It)|0,l=l+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(Y,Ct)|0,l=l+Math.imul(Y,xt)|0,l=l+Math.imul(J,Ct)|0,g=g+Math.imul(J,xt)|0,f=f+Math.imul(F,kt)|0,l=l+Math.imul(F,Dt)|0,l=l+Math.imul(H,kt)|0,g=g+Math.imul(H,Dt)|0,f=f+Math.imul(L,vt)|0,l=l+Math.imul(L,At)|0,l=l+Math.imul(q,vt)|0,g=g+Math.imul(q,At)|0,f=f+Math.imul(P,Mt)|0,l=l+Math.imul(P,Ot)|0,l=l+Math.imul(R,Mt)|0,g=g+Math.imul(R,Ot)|0;var es=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(es>>>26)|0,es&=67108863,f=Math.imul(lt,dt),l=Math.imul(lt,ft),l=l+Math.imul(pt,dt)|0,g=Math.imul(pt,ft),f=f+Math.imul(st,ht)|0,l=l+Math.imul(st,gt)|0,l=l+Math.imul(ct,ht)|0,g=g+Math.imul(ct,gt)|0,f=f+Math.imul(at,yt)|0,l=l+Math.imul(at,bt)|0,l=l+Math.imul(it,yt)|0,g=g+Math.imul(it,bt)|0,f=f+Math.imul(ot,Tt)|0,l=l+Math.imul(ot,St)|0,l=l+Math.imul(rt,Tt)|0,g=g+Math.imul(rt,St)|0,f=f+Math.imul(et,wt)|0,l=l+Math.imul(et,It)|0,l=l+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,l=l+Math.imul(Z,xt)|0,l=l+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,xt)|0,f=f+Math.imul(Y,kt)|0,l=l+Math.imul(Y,Dt)|0,l=l+Math.imul(J,kt)|0,g=g+Math.imul(J,Dt)|0,f=f+Math.imul(F,vt)|0,l=l+Math.imul(F,At)|0,l=l+Math.imul(H,vt)|0,g=g+Math.imul(H,At)|0,f=f+Math.imul(L,Mt)|0,l=l+Math.imul(L,Ot)|0,l=l+Math.imul(q,Mt)|0,g=g+Math.imul(q,Ot)|0;var ns=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ns>>>26)|0,ns&=67108863,f=Math.imul(lt,ht),l=Math.imul(lt,gt),l=l+Math.imul(pt,ht)|0,g=Math.imul(pt,gt),f=f+Math.imul(st,yt)|0,l=l+Math.imul(st,bt)|0,l=l+Math.imul(ct,yt)|0,g=g+Math.imul(ct,bt)|0,f=f+Math.imul(at,Tt)|0,l=l+Math.imul(at,St)|0,l=l+Math.imul(it,Tt)|0,g=g+Math.imul(it,St)|0,f=f+Math.imul(ot,wt)|0,l=l+Math.imul(ot,It)|0,l=l+Math.imul(rt,wt)|0,g=g+Math.imul(rt,It)|0,f=f+Math.imul(et,Ct)|0,l=l+Math.imul(et,xt)|0,l=l+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,xt)|0,f=f+Math.imul(Z,kt)|0,l=l+Math.imul(Z,Dt)|0,l=l+Math.imul(tt,kt)|0,g=g+Math.imul(tt,Dt)|0,f=f+Math.imul(Y,vt)|0,l=l+Math.imul(Y,At)|0,l=l+Math.imul(J,vt)|0,g=g+Math.imul(J,At)|0,f=f+Math.imul(F,Mt)|0,l=l+Math.imul(F,Ot)|0,l=l+Math.imul(H,Mt)|0,g=g+Math.imul(H,Ot)|0;var os=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(os>>>26)|0,os&=67108863,f=Math.imul(lt,yt),l=Math.imul(lt,bt),l=l+Math.imul(pt,yt)|0,g=Math.imul(pt,bt),f=f+Math.imul(st,Tt)|0,l=l+Math.imul(st,St)|0,l=l+Math.imul(ct,Tt)|0,g=g+Math.imul(ct,St)|0,f=f+Math.imul(at,wt)|0,l=l+Math.imul(at,It)|0,l=l+Math.imul(it,wt)|0,g=g+Math.imul(it,It)|0,f=f+Math.imul(ot,Ct)|0,l=l+Math.imul(ot,xt)|0,l=l+Math.imul(rt,Ct)|0,g=g+Math.imul(rt,xt)|0,f=f+Math.imul(et,kt)|0,l=l+Math.imul(et,Dt)|0,l=l+Math.imul(nt,kt)|0,g=g+Math.imul(nt,Dt)|0,f=f+Math.imul(Z,vt)|0,l=l+Math.imul(Z,At)|0,l=l+Math.imul(tt,vt)|0,g=g+Math.imul(tt,At)|0,f=f+Math.imul(Y,Mt)|0,l=l+Math.imul(Y,Ot)|0,l=l+Math.imul(J,Mt)|0,g=g+Math.imul(J,Ot)|0;var rs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(rs>>>26)|0,rs&=67108863,f=Math.imul(lt,Tt),l=Math.imul(lt,St),l=l+Math.imul(pt,Tt)|0,g=Math.imul(pt,St),f=f+Math.imul(st,wt)|0,l=l+Math.imul(st,It)|0,l=l+Math.imul(ct,wt)|0,g=g+Math.imul(ct,It)|0,f=f+Math.imul(at,Ct)|0,l=l+Math.imul(at,xt)|0,l=l+Math.imul(it,Ct)|0,g=g+Math.imul(it,xt)|0,f=f+Math.imul(ot,kt)|0,l=l+Math.imul(ot,Dt)|0,l=l+Math.imul(rt,kt)|0,g=g+Math.imul(rt,Dt)|0,f=f+Math.imul(et,vt)|0,l=l+Math.imul(et,At)|0,l=l+Math.imul(nt,vt)|0,g=g+Math.imul(nt,At)|0,f=f+Math.imul(Z,Mt)|0,l=l+Math.imul(Z,Ot)|0,l=l+Math.imul(tt,Mt)|0,g=g+Math.imul(tt,Ot)|0;var as=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(as>>>26)|0,as&=67108863,f=Math.imul(lt,wt),l=Math.imul(lt,It),l=l+Math.imul(pt,wt)|0,g=Math.imul(pt,It),f=f+Math.imul(st,Ct)|0,l=l+Math.imul(st,xt)|0,l=l+Math.imul(ct,Ct)|0,g=g+Math.imul(ct,xt)|0,f=f+Math.imul(at,kt)|0,l=l+Math.imul(at,Dt)|0,l=l+Math.imul(it,kt)|0,g=g+Math.imul(it,Dt)|0,f=f+Math.imul(ot,vt)|0,l=l+Math.imul(ot,At)|0,l=l+Math.imul(rt,vt)|0,g=g+Math.imul(rt,At)|0,f=f+Math.imul(et,Mt)|0,l=l+Math.imul(et,Ot)|0,l=l+Math.imul(nt,Mt)|0,g=g+Math.imul(nt,Ot)|0;var is=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(is>>>26)|0,is&=67108863,f=Math.imul(lt,Ct),l=Math.imul(lt,xt),l=l+Math.imul(pt,Ct)|0,g=Math.imul(pt,xt),f=f+Math.imul(st,kt)|0,l=l+Math.imul(st,Dt)|0,l=l+Math.imul(ct,kt)|0,g=g+Math.imul(ct,Dt)|0,f=f+Math.imul(at,vt)|0,l=l+Math.imul(at,At)|0,l=l+Math.imul(it,vt)|0,g=g+Math.imul(it,At)|0,f=f+Math.imul(ot,Mt)|0,l=l+Math.imul(ot,Ot)|0,l=l+Math.imul(rt,Mt)|0,g=g+Math.imul(rt,Ot)|0;var ss=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ss>>>26)|0,ss&=67108863,f=Math.imul(lt,kt),l=Math.imul(lt,Dt),l=l+Math.imul(pt,kt)|0,g=Math.imul(pt,Dt),f=f+Math.imul(st,vt)|0,l=l+Math.imul(st,At)|0,l=l+Math.imul(ct,vt)|0,g=g+Math.imul(ct,At)|0,f=f+Math.imul(at,Mt)|0,l=l+Math.imul(at,Ot)|0,l=l+Math.imul(it,Mt)|0,g=g+Math.imul(it,Ot)|0;var cs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(cs>>>26)|0,cs&=67108863,f=Math.imul(lt,vt),l=Math.imul(lt,At),l=l+Math.imul(pt,vt)|0,g=Math.imul(pt,At),f=f+Math.imul(st,Mt)|0,l=l+Math.imul(st,Ot)|0,l=l+Math.imul(ct,Mt)|0,g=g+Math.imul(ct,Ot)|0;var ls=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ls>>>26)|0,ls&=67108863,f=Math.imul(lt,Mt),l=Math.imul(lt,Ot),l=l+Math.imul(pt,Mt)|0,g=Math.imul(pt,Ot);var ps=(I+f|0)+((l&8191)<<13)|0;return I=(g+(l>>>13)|0)+(ps>>>26)|0,ps&=67108863,T[0]=Vi,T[1]=Hi,T[2]=Xi,T[3]=zi,T[4]=Qi,T[5]=Yi,T[6]=Ji,T[7]=Zi,T[8]=ts,T[9]=es,T[10]=ns,T[11]=os,T[12]=rs,T[13]=as,T[14]=is,T[15]=ss,T[16]=cs,T[17]=ls,T[18]=ps,I!==0&&(T[19]=I,u.length++),u};Math.imul||(U=G);function K(y,i,p){p.negative=i.negative^y.negative,p.length=y.length+i.length;for(var u=0,d=0,h=0;h<p.length-1;h++){var T=d;d=0;for(var I=u&67108863,f=Math.min(h,i.length-1),l=Math.max(0,h-y.length+1);l<=f;l++){var g=h-l,A=y.words[g]|0,P=i.words[l]|0,R=A*P,N=R&67108863;T=T+(R/67108864|0)|0,N=N+I|0,I=N&67108863,T=T+(N>>>26)|0,d+=T>>>26,T&=67108863}p.words[h]=I,u=T,T=d}return u!==0?p.words[h]=u:p.length--,p._strip()}function V(y,i,p){return K(y,i,p)}o.prototype.mulTo=function(i,p){var u,d=this.length+i.length;return this.length===10&&i.length===10?u=U(this,i,p):d<63?u=G(this,i,p):d<1024?u=K(this,i,p):u=V(this,i,p),u};function E(y,i){this.x=y,this.y=i}E.prototype.makeRBT=function(i){for(var p=new Array(i),u=o.prototype._countBits(i)-1,d=0;d<i;d++)p[d]=this.revBin(d,u,i);return p},E.prototype.revBin=function(i,p,u){if(i===0||i===u-1)return i;for(var d=0,h=0;h<p;h++)d|=(i&1)<<p-h-1,i>>=1;return d},E.prototype.permute=function(i,p,u,d,h,T){for(var I=0;I<T;I++)d[I]=p[i[I]],h[I]=u[i[I]]},E.prototype.transform=function(i,p,u,d,h,T){this.permute(T,i,p,u,d,h);for(var I=1;I<h;I<<=1)for(var f=I<<1,l=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),A=0;A<h;A+=f)for(var P=l,R=g,N=0;N<I;N++){var L=u[A+N],q=d[A+N],be=u[A+N+I],F=d[A+N+I],H=P*be-R*F;F=P*F+R*be,be=H,u[A+N]=L+be,d[A+N]=q+F,u[A+N+I]=L-be,d[A+N+I]=q-F,N!==f&&(H=l*P-g*R,R=l*R+g*P,P=H)}},E.prototype.guessLen13b=function(i,p){var u=Math.max(p,i)|1,d=u&1,h=0;for(u=u/2|0;u;u=u>>>1)h++;return 1<<h+1+d},E.prototype.conjugate=function(i,p,u){if(!(u<=1))for(var d=0;d<u/2;d++){var h=i[d];i[d]=i[u-d-1],i[u-d-1]=h,h=p[d],p[d]=-p[u-d-1],p[u-d-1]=-h}},E.prototype.normalize13b=function(i,p){for(var u=0,d=0;d<p/2;d++){var h=Math.round(i[2*d+1]/p)*8192+Math.round(i[2*d]/p)+u;i[d]=h&67108863,h<67108864?u=0:u=h/67108864|0}return i},E.prototype.convert13b=function(i,p,u,d){for(var h=0,T=0;T<p;T++)h=h+(i[T]|0),u[2*T]=h&8191,h=h>>>13,u[2*T+1]=h&8191,h=h>>>13;for(T=2*p;T<d;++T)u[T]=0;t(h===0),t((h&-8192)===0)},E.prototype.stub=function(i){for(var p=new Array(i),u=0;u<i;u++)p[u]=0;return p},E.prototype.mulp=function(i,p,u){var d=2*this.guessLen13b(i.length,p.length),h=this.makeRBT(d),T=this.stub(d),I=new Array(d),f=new Array(d),l=new Array(d),g=new Array(d),A=new Array(d),P=new Array(d),R=u.words;R.length=d,this.convert13b(i.words,i.length,I,d),this.convert13b(p.words,p.length,g,d),this.transform(I,T,f,l,d,h),this.transform(g,T,A,P,d,h);for(var N=0;N<d;N++){var L=f[N]*A[N]-l[N]*P[N];l[N]=f[N]*P[N]+l[N]*A[N],f[N]=L}return this.conjugate(f,l,d),this.transform(f,l,R,T,d,h),this.conjugate(R,T,d),this.normalize13b(R,d),u.negative=i.negative^p.negative,u.length=i.length+p.length,u._strip()},o.prototype.mul=function(i){var p=new o(null);return p.words=new Array(this.length+i.length),this.mulTo(i,p)},o.prototype.mulf=function(i){var p=new o(null);return p.words=new Array(this.length+i.length),V(this,i,p)},o.prototype.imul=function(i){return this.clone().mulTo(i,this)},o.prototype.imuln=function(i){var p=i<0;p&&(i=-i),t(typeof i=="number"),t(i<67108864);for(var u=0,d=0;d<this.length;d++){var h=(this.words[d]|0)*i,T=(h&67108863)+(u&67108863);u>>=26,u+=h/67108864|0,u+=T>>>26,this.words[d]=T&67108863}return u!==0&&(this.words[d]=u,this.length++),this.length=i===0?1:this.length,p?this.ineg():this},o.prototype.muln=function(i){return this.clone().imuln(i)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(i){var p=O(i);if(p.length===0)return new o(1);for(var u=this,d=0;d<p.length&&p[d]===0;d++,u=u.sqr());if(++d<p.length)for(var h=u.sqr();d<p.length;d++,h=h.sqr())p[d]!==0&&(u=u.mul(h));return u},o.prototype.iushln=function(i){t(typeof i=="number"&&i>=0);var p=i%26,u=(i-p)/26,d=67108863>>>26-p<<26-p,h;if(p!==0){var T=0;for(h=0;h<this.length;h++){var I=this.words[h]&d,f=(this.words[h]|0)-I<<p;this.words[h]=f|T,T=I>>>26-p}T&&(this.words[h]=T,this.length++)}if(u!==0){for(h=this.length-1;h>=0;h--)this.words[h+u]=this.words[h];for(h=0;h<u;h++)this.words[h]=0;this.length+=u}return this._strip()},o.prototype.ishln=function(i){return t(this.negative===0),this.iushln(i)},o.prototype.iushrn=function(i,p,u){t(typeof i=="number"&&i>=0);var d;p?d=(p-p%26)/26:d=0;var h=i%26,T=Math.min((i-h)/26,this.length),I=67108863^67108863>>>h<<h,f=u;if(d-=T,d=Math.max(0,d),f){for(var l=0;l<T;l++)f.words[l]=this.words[l];f.length=T}if(T!==0)if(this.length>T)for(this.length-=T,l=0;l<this.length;l++)this.words[l]=this.words[l+T];else this.words[0]=0,this.length=1;var g=0;for(l=this.length-1;l>=0&&(g!==0||l>=d);l--){var A=this.words[l]|0;this.words[l]=g<<26-h|A>>>h,g=A&I}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(i,p,u){return t(this.negative===0),this.iushrn(i,p,u)},o.prototype.shln=function(i){return this.clone().ishln(i)},o.prototype.ushln=function(i){return this.clone().iushln(i)},o.prototype.shrn=function(i){return this.clone().ishrn(i)},o.prototype.ushrn=function(i){return this.clone().iushrn(i)},o.prototype.testn=function(i){t(typeof i=="number"&&i>=0);var p=i%26,u=(i-p)/26,d=1<<p;if(this.length<=u)return!1;var h=this.words[u];return!!(h&d)},o.prototype.imaskn=function(i){t(typeof i=="number"&&i>=0);var p=i%26,u=(i-p)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=u)return this;if(p!==0&&u++,this.length=Math.min(u,this.length),p!==0){var d=67108863^67108863>>>p<<p;this.words[this.length-1]&=d}return this.length===0&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.maskn=function(i){return this.clone().imaskn(i)},o.prototype.iaddn=function(i){return t(typeof i=="number"),t(i<67108864),i<0?this.isubn(-i):this.negative!==0?this.length===1&&(this.words[0]|0)<=i?(this.words[0]=i-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(i),this.negative=1,this):this._iaddn(i)},o.prototype._iaddn=function(i){this.words[0]+=i;for(var p=0;p<this.length&&this.words[p]>=67108864;p++)this.words[p]-=67108864,p===this.length-1?this.words[p+1]=1:this.words[p+1]++;return this.length=Math.max(this.length,p+1),this},o.prototype.isubn=function(i){if(t(typeof i=="number"),t(i<67108864),i<0)return this.iaddn(-i);if(this.negative!==0)return this.negative=0,this.iaddn(i),this.negative=1,this;if(this.words[0]-=i,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var p=0;p<this.length&&this.words[p]<0;p++)this.words[p]+=67108864,this.words[p+1]-=1;return this._strip()},o.prototype.addn=function(i){return this.clone().iaddn(i)},o.prototype.subn=function(i){return this.clone().isubn(i)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(i,p,u){var d=i.length+u,h;this._expand(d);var T,I=0;for(h=0;h<i.length;h++){T=(this.words[h+u]|0)+I;var f=(i.words[h]|0)*p;T-=f&67108863,I=(T>>26)-(f/67108864|0),this.words[h+u]=T&67108863}for(;h<this.length-u;h++)T=(this.words[h+u]|0)+I,I=T>>26,this.words[h+u]=T&67108863;if(I===0)return this._strip();for(t(I===-1),I=0,h=0;h<this.length;h++)T=-(this.words[h]|0)+I,I=T>>26,this.words[h]=T&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(i,p){var u=this.length-i.length,d=this.clone(),h=i,T=h.words[h.length-1]|0,I=this._countBits(T);u=26-I,u!==0&&(h=h.ushln(u),d.iushln(u),T=h.words[h.length-1]|0);var f=d.length-h.length,l;if(p!=="mod"){l=new o(null),l.length=f+1,l.words=new Array(l.length);for(var g=0;g<l.length;g++)l.words[g]=0}var A=d.clone()._ishlnsubmul(h,1,f);A.negative===0&&(d=A,l&&(l.words[f]=1));for(var P=f-1;P>=0;P--){var R=(d.words[h.length+P]|0)*67108864+(d.words[h.length+P-1]|0);for(R=Math.min(R/T|0,67108863),d._ishlnsubmul(h,R,P);d.negative!==0;)R--,d.negative=0,d._ishlnsubmul(h,1,P),d.isZero()||(d.negative^=1);l&&(l.words[P]=R)}return l&&l._strip(),d._strip(),p!=="div"&&u!==0&&d.iushrn(u),{div:l||null,mod:d}},o.prototype.divmod=function(i,p,u){if(t(!i.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var d,h,T;return this.negative!==0&&i.negative===0?(T=this.neg().divmod(i,p),p!=="mod"&&(d=T.div.neg()),p!=="div"&&(h=T.mod.neg(),u&&h.negative!==0&&h.iadd(i)),{div:d,mod:h}):this.negative===0&&i.negative!==0?(T=this.divmod(i.neg(),p),p!=="mod"&&(d=T.div.neg()),{div:d,mod:T.mod}):(this.negative&i.negative)!==0?(T=this.neg().divmod(i.neg(),p),p!=="div"&&(h=T.mod.neg(),u&&h.negative!==0&&h.isub(i)),{div:T.div,mod:h}):i.length>this.length||this.cmp(i)<0?{div:new o(0),mod:this}:i.length===1?p==="div"?{div:this.divn(i.words[0]),mod:null}:p==="mod"?{div:null,mod:new o(this.modrn(i.words[0]))}:{div:this.divn(i.words[0]),mod:new o(this.modrn(i.words[0]))}:this._wordDiv(i,p)},o.prototype.div=function(i){return this.divmod(i,"div",!1).div},o.prototype.mod=function(i){return this.divmod(i,"mod",!1).mod},o.prototype.umod=function(i){return this.divmod(i,"mod",!0).mod},o.prototype.divRound=function(i){var p=this.divmod(i);if(p.mod.isZero())return p.div;var u=p.div.negative!==0?p.mod.isub(i):p.mod,d=i.ushrn(1),h=i.andln(1),T=u.cmp(d);return T<0||h===1&&T===0?p.div:p.div.negative!==0?p.div.isubn(1):p.div.iaddn(1)},o.prototype.modrn=function(i){var p=i<0;p&&(i=-i),t(i<=67108863);for(var u=(1<<26)%i,d=0,h=this.length-1;h>=0;h--)d=(u*d+(this.words[h]|0))%i;return p?-d:d},o.prototype.modn=function(i){return this.modrn(i)},o.prototype.idivn=function(i){var p=i<0;p&&(i=-i),t(i<=67108863);for(var u=0,d=this.length-1;d>=0;d--){var h=(this.words[d]|0)+u*67108864;this.words[d]=h/i|0,u=h%i}return this._strip(),p?this.ineg():this},o.prototype.divn=function(i){return this.clone().idivn(i)},o.prototype.egcd=function(i){t(i.negative===0),t(!i.isZero());var p=this,u=i.clone();p.negative!==0?p=p.umod(i):p=p.clone();for(var d=new o(1),h=new o(0),T=new o(0),I=new o(1),f=0;p.isEven()&&u.isEven();)p.iushrn(1),u.iushrn(1),++f;for(var l=u.clone(),g=p.clone();!p.isZero();){for(var A=0,P=1;(p.words[0]&P)===0&&A<26;++A,P<<=1);if(A>0)for(p.iushrn(A);A-- >0;)(d.isOdd()||h.isOdd())&&(d.iadd(l),h.isub(g)),d.iushrn(1),h.iushrn(1);for(var R=0,N=1;(u.words[0]&N)===0&&R<26;++R,N<<=1);if(R>0)for(u.iushrn(R);R-- >0;)(T.isOdd()||I.isOdd())&&(T.iadd(l),I.isub(g)),T.iushrn(1),I.iushrn(1);p.cmp(u)>=0?(p.isub(u),d.isub(T),h.isub(I)):(u.isub(p),T.isub(d),I.isub(h))}return{a:T,b:I,gcd:u.iushln(f)}},o.prototype._invmp=function(i){t(i.negative===0),t(!i.isZero());var p=this,u=i.clone();p.negative!==0?p=p.umod(i):p=p.clone();for(var d=new o(1),h=new o(0),T=u.clone();p.cmpn(1)>0&&u.cmpn(1)>0;){for(var I=0,f=1;(p.words[0]&f)===0&&I<26;++I,f<<=1);if(I>0)for(p.iushrn(I);I-- >0;)d.isOdd()&&d.iadd(T),d.iushrn(1);for(var l=0,g=1;(u.words[0]&g)===0&&l<26;++l,g<<=1);if(l>0)for(u.iushrn(l);l-- >0;)h.isOdd()&&h.iadd(T),h.iushrn(1);p.cmp(u)>=0?(p.isub(u),d.isub(h)):(u.isub(p),h.isub(d))}var A;return p.cmpn(1)===0?A=d:A=h,A.cmpn(0)<0&&A.iadd(i),A},o.prototype.gcd=function(i){if(this.isZero())return i.abs();if(i.isZero())return this.abs();var p=this.clone(),u=i.clone();p.negative=0,u.negative=0;for(var d=0;p.isEven()&&u.isEven();d++)p.iushrn(1),u.iushrn(1);do{for(;p.isEven();)p.iushrn(1);for(;u.isEven();)u.iushrn(1);var h=p.cmp(u);if(h<0){var T=p;p=u,u=T}else if(h===0||u.cmpn(1)===0)break;p.isub(u)}while(!0);return u.iushln(d)},o.prototype.invm=function(i){return this.egcd(i).a.umod(i)},o.prototype.isEven=function(){return(this.words[0]&1)===0},o.prototype.isOdd=function(){return(this.words[0]&1)===1},o.prototype.andln=function(i){return this.words[0]&i},o.prototype.bincn=function(i){t(typeof i=="number");var p=i%26,u=(i-p)/26,d=1<<p;if(this.length<=u)return this._expand(u+1),this.words[u]|=d,this;for(var h=d,T=u;h!==0&&T<this.length;T++){var I=this.words[T]|0;I+=h,h=I>>>26,I&=67108863,this.words[T]=I}return h!==0&&(this.words[T]=h,this.length++),this},o.prototype.isZero=function(){return this.length===1&&this.words[0]===0},o.prototype.cmpn=function(i){var p=i<0;if(this.negative!==0&&!p)return-1;if(this.negative===0&&p)return 1;this._strip();var u;if(this.length>1)u=1;else{p&&(i=-i),t(i<=67108863,"Number is too big");var d=this.words[0]|0;u=d===i?0:d<i?-1:1}return this.negative!==0?-u|0:u},o.prototype.cmp=function(i){if(this.negative!==0&&i.negative===0)return-1;if(this.negative===0&&i.negative!==0)return 1;var p=this.ucmp(i);return this.negative!==0?-p|0:p},o.prototype.ucmp=function(i){if(this.length>i.length)return 1;if(this.length<i.length)return-1;for(var p=0,u=this.length-1;u>=0;u--){var d=this.words[u]|0,h=i.words[u]|0;if(d!==h){d<h?p=-1:d>h&&(p=1);break}}return p},o.prototype.gtn=function(i){return this.cmpn(i)===1},o.prototype.gt=function(i){return this.cmp(i)===1},o.prototype.gten=function(i){return this.cmpn(i)>=0},o.prototype.gte=function(i){return this.cmp(i)>=0},o.prototype.ltn=function(i){return this.cmpn(i)===-1},o.prototype.lt=function(i){return this.cmp(i)===-1},o.prototype.lten=function(i){return this.cmpn(i)<=0},o.prototype.lte=function(i){return this.cmp(i)<=0},o.prototype.eqn=function(i){return this.cmpn(i)===0},o.prototype.eq=function(i){return this.cmp(i)===0},o.red=function(i){return new X(i)},o.prototype.toRed=function(i){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),i.convertTo(this)._forceRed(i)},o.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(i){return this.red=i,this},o.prototype.forceRed=function(i){return t(!this.red,"Already a number in reduction context"),this._forceRed(i)},o.prototype.redAdd=function(i){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,i)},o.prototype.redIAdd=function(i){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,i)},o.prototype.redSub=function(i){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,i)},o.prototype.redISub=function(i){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,i)},o.prototype.redShl=function(i){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,i)},o.prototype.redMul=function(i){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,i),this.red.mul(this,i)},o.prototype.redIMul=function(i){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,i),this.red.imul(this,i)},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(i){return t(this.red&&!i.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,i)};var ye={k256:null,p224:null,p192:null,p25519:null};function Wt(y,i){this.name=y,this.p=new o(i,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Wt.prototype._tmp=function(){var i=new o(null);return i.words=new Array(Math.ceil(this.n/13)),i},Wt.prototype.ireduce=function(i){var p=i,u;do this.split(p,this.tmp),p=this.imulK(p),p=p.iadd(this.tmp),u=p.bitLength();while(u>this.n);var d=u<this.n?-1:p.ucmp(this.p);return d===0?(p.words[0]=0,p.length=1):d>0?p.isub(this.p):p.strip!==void 0?p.strip():p._strip(),p},Wt.prototype.split=function(i,p){i.iushrn(this.n,0,p)},Wt.prototype.imulK=function(i){return i.imul(this.k)};function le(){Wt.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(le,Wt),le.prototype.split=function(i,p){for(var u=4194303,d=Math.min(i.length,9),h=0;h<d;h++)p.words[h]=i.words[h];if(p.length=d,i.length<=9){i.words[0]=0,i.length=1;return}var T=i.words[9];for(p.words[p.length++]=T&u,h=10;h<i.length;h++){var I=i.words[h]|0;i.words[h-10]=(I&u)<<4|T>>>22,T=I}T>>>=22,i.words[h-10]=T,T===0&&i.length>10?i.length-=10:i.length-=9},le.prototype.imulK=function(i){i.words[i.length]=0,i.words[i.length+1]=0,i.length+=2;for(var p=0,u=0;u<i.length;u++){var d=i.words[u]|0;p+=d*977,i.words[u]=p&67108863,p=d*64+(p/67108864|0)}return i.words[i.length-1]===0&&(i.length--,i.words[i.length-1]===0&&i.length--),i};function Yn(){Wt.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(Yn,Wt);function wn(){Wt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(wn,Wt);function He(){Wt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(He,Wt),He.prototype.imulK=function(i){for(var p=0,u=0;u<i.length;u++){var d=(i.words[u]|0)*19+p,h=d&67108863;d>>>=26,i.words[u]=h,p=d}return p!==0&&(i.words[i.length++]=p),i},o._prime=function(i){if(ye[i])return ye[i];var p;if(i==="k256")p=new le;else if(i==="p224")p=new Yn;else if(i==="p192")p=new wn;else if(i==="p25519")p=new He;else throw new Error("Unknown prime "+i);return ye[i]=p,p};function X(y){if(typeof y=="string"){var i=o._prime(y);this.m=i.p,this.prime=i}else t(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}X.prototype._verify1=function(i){t(i.negative===0,"red works only with positives"),t(i.red,"red works only with red numbers")},X.prototype._verify2=function(i,p){t((i.negative|p.negative)===0,"red works only with positives"),t(i.red&&i.red===p.red,"red works only with red numbers")},X.prototype.imod=function(i){return this.prime?this.prime.ireduce(i)._forceRed(this):(b(i,i.umod(this.m)._forceRed(this)),i)},X.prototype.neg=function(i){return i.isZero()?i.clone():this.m.sub(i)._forceRed(this)},X.prototype.add=function(i,p){this._verify2(i,p);var u=i.add(p);return u.cmp(this.m)>=0&&u.isub(this.m),u._forceRed(this)},X.prototype.iadd=function(i,p){this._verify2(i,p);var u=i.iadd(p);return u.cmp(this.m)>=0&&u.isub(this.m),u},X.prototype.sub=function(i,p){this._verify2(i,p);var u=i.sub(p);return u.cmpn(0)<0&&u.iadd(this.m),u._forceRed(this)},X.prototype.isub=function(i,p){this._verify2(i,p);var u=i.isub(p);return u.cmpn(0)<0&&u.iadd(this.m),u},X.prototype.shl=function(i,p){return this._verify1(i),this.imod(i.ushln(p))},X.prototype.imul=function(i,p){return this._verify2(i,p),this.imod(i.imul(p))},X.prototype.mul=function(i,p){return this._verify2(i,p),this.imod(i.mul(p))},X.prototype.isqr=function(i){return this.imul(i,i.clone())},X.prototype.sqr=function(i){return this.mul(i,i)},X.prototype.sqrt=function(i){if(i.isZero())return i.clone();var p=this.m.andln(3);if(t(p%2===1),p===3){var u=this.m.add(new o(1)).iushrn(2);return this.pow(i,u)}for(var d=this.m.subn(1),h=0;!d.isZero()&&d.andln(1)===0;)h++,d.iushrn(1);t(!d.isZero());var T=new o(1).toRed(this),I=T.redNeg(),f=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);this.pow(l,f).cmp(I)!==0;)l.redIAdd(I);for(var g=this.pow(l,d),A=this.pow(i,d.addn(1).iushrn(1)),P=this.pow(i,d),R=h;P.cmp(T)!==0;){for(var N=P,L=0;N.cmp(T)!==0;L++)N=N.redSqr();t(L<R);var q=this.pow(g,new o(1).iushln(R-L-1));A=A.redMul(q),g=q.redSqr(),P=P.redMul(g),R=L}return A},X.prototype.invm=function(i){var p=i._invmp(this.m);return p.negative!==0?(p.negative=0,this.imod(p).redNeg()):this.imod(p)},X.prototype.pow=function(i,p){if(p.isZero())return new o(1).toRed(this);if(p.cmpn(1)===0)return i.clone();var u=4,d=new Array(1<<u);d[0]=new o(1).toRed(this),d[1]=i;for(var h=2;h<d.length;h++)d[h]=this.mul(d[h-1],i);var T=d[0],I=0,f=0,l=p.bitLength()%26;for(l===0&&(l=26),h=p.length-1;h>=0;h--){for(var g=p.words[h],A=l-1;A>=0;A--){var P=g>>A&1;if(T!==d[0]&&(T=this.sqr(T)),P===0&&I===0){f=0;continue}I<<=1,I|=P,f++,!(f!==u&&(h!==0||A!==0))&&(T=this.mul(T,d[I]),f=0,I=0)}l=26}return T},X.prototype.convertTo=function(i){var p=i.umod(this.m);return p===i?p.clone():p},X.prototype.convertFrom=function(i){var p=i.clone();return p.red=null,p},o.mont=function(i){return new Ne(i)};function Ne(y){X.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(Ne,X),Ne.prototype.convertTo=function(i){return this.imod(i.ushln(this.shift))},Ne.prototype.convertFrom=function(i){var p=this.imod(i.mul(this.rinv));return p.red=null,p},Ne.prototype.imul=function(i,p){if(i.isZero()||p.isZero())return i.words[0]=0,i.length=1,i;var u=i.imul(p),d=u.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=u.isub(d).iushrn(this.shift),T=h;return h.cmp(this.m)>=0?T=h.isub(this.m):h.cmpn(0)<0&&(T=h.iadd(this.m)),T._forceRed(this)},Ne.prototype.mul=function(i,p){if(i.isZero()||p.isZero())return new o(0)._forceRed(this);var u=i.mul(p),d=u.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=u.isub(d).iushrn(this.shift),T=h;return h.cmp(this.m)>=0?T=h.isub(this.m):h.cmpn(0)<0&&(T=h.iadd(this.m)),T._forceRed(this)},Ne.prototype.invm=function(i){var p=this.imod(i._invmp(this.m).mul(this.r2));return p._forceRed(this)}})(typeof Zs>"u"||Zs,Nm)});var Hf={};us(Hf,{appHelpers:()=>Vf});module.exports=Md(Hf);var vc=require("@msafe/sui3-utils");var pe=require("@alphafi/alphafi-sdk"),Xe=require("@msafe/sui3-utils"),te=require("@mysten/bcs");var Zn=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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=pe.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&&pe.poolInfo[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&pe.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=te.bcs.u64().parse((0,te.fromBase64)(t)):t.length===24?n=te.bcs.u128().parse((0,te.fromBase64)(t)):t.length===44?n=te.bcs.u256().parse((0,te.fromBase64)(t)):n=te.bcs.u64().parse((0,te.fromBase64)(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:o}=t,a=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,a),{txType:Xe.TransactionType.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:a?n:o,isAmountA:a}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:a}=pe.singleAssetPoolCoinMap[e],{expo:s}=pe.coinsList[a];n=Math.floor(Number(n)/10**(9-s)).toString()}return{txType:Xe.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:Xe.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:Xe.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:Xe.TransactionType.Other,type:"claimReward",intentionData:{}}}};var Ic=require("@alphafi/alphafi-sdk");var wc=_t(require("sort-keys-recursive")),v=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,wc.default)(this.data))}};var to=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t;return await(0,Ic.claimRewardTxb)(n.address)}static fromData(t){return new r(t)}};var Cc=require("@alphafi/alphafi-sdk");var eo=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:a,isAmountA:s}=this.data;return await(0,Cc.depositDoubleAssetTxb)(o,n.address,a,s)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new r(t)}};var xc=require("@alphafi/alphafi-sdk");var no=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:a}=this.data;return await(0,xc.depositSingleAssetTxb)(o,n.address,a)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new r(t)}};var kc=require("@alphafi/alphafi-sdk");var oo=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:a}=this.data;return await(0,kc.withdrawTxb)(a,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new r(t)}};var Dc=require("@alphafi/alphafi-sdk");var ro=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:a}=this.data;return await(0,Dc.withdrawAlphaTxb)(a,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new r(t)}};var ao=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:o}=e,a=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",a);let c=new Zn(t,a).decode();return{txType:vc.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=no.fromData(e.intentionData);break;case"depositDoubleAsset":n=eo.fromData(e.intentionData);break;case"withdraw":n=oo.fromData(e.intentionData);break;case"withdrawAlpha":n=ro.fromData(e.intentionData);break;case"claimReward":n=to.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};var Jc=require("@msafe/sui3-utils");var Gt=require("@msafe/sui3-utils"),io=require("@mysten/sui/bcs"),so=require("bucket-protocol-sdk");var co=class{constructor(e){this.transaction=e}transaction;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(so.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(so.SBUCK_FOUNTAIN_PACKAGE_ID,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(so.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:Gt.TransactionType.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,o=this.getStrapId(),a="0",s=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(s.$kind==="Input"&&(a=this.getPureInputU64(s.Input)),this.getMoveCallCommand("high_top_up")){let c=this.getMoveCallCommand("high_top_up").MoveCall;[e]=c.typeArguments;let m=c.arguments[1];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[3];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow")){let c=this.getMoveCallCommand("high_borrow").MoveCall;[e]=c.typeArguments;let m=c.arguments[4];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[5];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let c=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=c.typeArguments;let m=c.arguments[5];m.$kind==="Input"&&(t=this.getPureInputU64(m.Input));let b=c.arguments[6];if(b.$kind==="Input"){let S=this.getPureAddresses(b.Input);S.length===1&&([n]=S)}}return{txType:Gt.TransactionType.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:a,borrowAmount:t,insertionPlace:n,strapId:o}}}decodeRepay(){let e="",t="0",n="0",a,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 c=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=c.typeArguments;let m=c.arguments[4];m.$kind==="Input"&&(n=this.getPureInputU64(m.Input));let b=c.arguments[5];if(b.$kind==="Input"){let w=this.getPureAddresses(b.Input);w.length===1&&([a]=w)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let c=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=c.typeArguments;let m=c.arguments[5];m.$kind==="Input"&&(n=this.getPureInputU64(m.Input));let b=c.arguments[6];if(b.$kind==="Input"){let w=this.getPureAddresses(b.Input);w.length===1&&([a]=w)}let S=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];S.$kind==="Input"&&(t=this.getPureInputU64(S.Input))}return{txType:Gt.TransactionType.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:a,strapId:s}}}decodeWithdraw(){let e="",t="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let a=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=a.typeArguments;let s=a.arguments[4];s.$kind==="Input"&&(t=this.getPureInputU64(s.Input));let c=a.arguments[5];if(c.$kind==="Input"){let m=this.getPureAddresses(c.Input);m.length===1&&([n]=m)}}else if(this.getMoveCallCommand("withdraw")){let a=this.getMoveCallCommand("withdraw").MoveCall;[e]=a.typeArguments;let s=a.arguments[3];s.$kind==="Input"&&(t=this.getPureInputU64(s.Input));let c=a.arguments[4];if(c.$kind==="Input"){let m=this.getPureAddresses(c.Input);m.length===1&&([n]=m)}}return{txType:Gt.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:Gt.TransactionType.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",a=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];a.$kind==="Input"&&(n=this.getPureInputU64(a.Input));let s=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,s),{txType:Gt.TransactionType.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:s}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let m=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];m.$kind==="Input"&&(e=this.getPureInputU64(m.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let c=0;c<o.length;c++){let m=o[c];n.push("")}else{let c=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let m=0;m<c.length;m++){let S=c[m].MoveCall.arguments[2];if(S.$kind==="Input"){let{objectId:w}=this.inputs[S.Input].UnresolvedObject;n.push(w)}}}let a=this.isSBUCKWithdrawTransaction(),s={stakeProofs:n,amount:e,isStake:t,toBuck:a};return console.log("Decoder.decodeSBUCKUnstake",s),{txType:Gt.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:Gt.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 a=t[n].MoveCall.arguments[2];if(a.$kind==="Input"){let{objectId:s}=this.inputs[a.Input].UnresolvedObject;e.push(s)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:Gt.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 a=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",a,e),{txType:Gt.TransactionType.Other,type:"tank-deposit",intentionData:{coinType:a,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:Gt.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:Gt.TransactionType.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let a=0;a<n.length;a++)[e]=n[a].MoveCall.typeArguments,t++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let a=0;a<o.length;a++)[e]=o[a].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:Gt.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 io.bcs.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return io.bcs.vector(io.bcs.Address).fromBase64(t.Pure.bytes)}};var Rc=require("@msafe/sui3-utils");var Mc=require("@mysten/sui/transactions"),Oc=require("bucket-protocol-sdk");var Ac=require("bucket-protocol-sdk"),Lt=(r,e)=>{let t=r==="sui:mainnet"?"mainnet":"testnet";return new Ac.BucketClient(t,e.address)};var Pc=async(r,e,t)=>{let{coinType:n,amount:o,buckToCoin:a}=r,s=new Mc.Transaction,c=Lt(t,e);return await(0,Oc.buildPsmTx)(c,s,n,o,a,e.address),s};var po=class r extends v{constructor(t){super(t);this.data=t}data;txType=Rc.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 r(t)}};var _c=require("@msafe/sui3-utils");var In=require("@mysten/sui/transactions"),Te=require("bucket-protocol-sdk");var Bc=async(r,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:a,insertionPlace:s,strapId:c}=r,m=new In.Transaction,b=Lt(t,e);return await(0,Te.buildBorrowTx)(b,m,n,o,a,e.address,s,c),m},Nc=async(r,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:a,strapId:s}=r,c=new In.Transaction,m=Lt(t,e);return await(0,Te.buildWithdrawTx)(m,c,n,o,e.address,a,s),c},Ec=async(r,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:a,isSurplus:s,insertionPlace:c,strapId:m}=r,b=new In.Transaction,S=Lt(t,e);return await(0,Te.buildRepayTx)(S,b,n,o,a,e.address,s,c,m),b},Wc=async(r,e,t)=>{let{collateralType:n,recipient:o,strapId:a}=r,s=new In.Transaction,c=Lt(t,e);return await(0,Te.buildCloseTx)(c,s,n,o,a),s};var uo=class r extends v{constructor(t){super(t);this.data=t}data;txType=_c.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await Bc(this.data,n,o)}static fromData(t){return new r(t)}};var Lc=require("@msafe/sui3-utils");var mo=class r extends v{constructor(t){super(t);this.data=t}data;txType=Lc.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await Ec(this.data,n,o)}static fromData(t){return new r(t)}};var jc=require("@msafe/sui3-utils");var fo=class r extends v{constructor(t){super(t);this.data=t}data;txType=jc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await Nc(this.data,n,o)}static fromData(t){return new r(t)}};var Uc=require("@msafe/sui3-utils");var ho=class r extends v{constructor(t){super(t);this.data=t}data;txType=Uc.TransactionType.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await Wc(this.data,n,o)}static fromData(t){return new r(t)}};var xn=require("@msafe/sui3-utils");var Cn=require("@mysten/sui/transactions"),Se=require("bucket-protocol-sdk");var Gc=async(r,e,t)=>{let{coinType:n,amount:o,isStake:a}=r,s=new Cn.Transaction,c=Lt(t,e);return await(0,Se.buildSBUCKDepositTx)(c,s,n,o,e.address,a),s},qc=async(r,e,t)=>{let{stakeProofs:n,amount:o,isStake:a,toBuck:s}=r,c=new Cn.Transaction,m=Lt(t,e);return await(0,Se.buildSBUCKUnstakeTx)(m,c,n,o,e.address,a,s),c},Fc=async(r,e,t)=>{let{amount:n}=r,o=new Cn.Transaction,a=Lt(t,e);return await(0,Se.buildSBUCKWithdrawTx)(a,o,n,e.address),o},Kc=async(r,e,t)=>{let{stakeProofs:n}=r,o=new Cn.Transaction,a=Lt(t,e);return await(0,Se.buildSBUCKClaimTx)(a,o,n,e.address),o};var go=class r extends v{constructor(t){super(t);this.data=t}data;txType=xn.TransactionType.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await Gc(this.data,n,o)}static fromData(t){return new r(t)}},yo=class r extends v{constructor(t){super(t);this.data=t}data;txType=xn.TransactionType.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await qc(this.data,n,o)}static fromData(t){return new r(t)}},bo=class r extends v{constructor(t){super(t);this.data=t}data;txType=xn.TransactionType.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await Fc(this.data,n,o)}static fromData(t){return new r(t)}},To=class r extends v{constructor(t){super(t);this.data=t}data;txType=xn.TransactionType.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await Kc(this.data,n,o)}static fromData(t){return new r(t)}};var xo=require("@msafe/sui3-utils");var So=require("@mysten/sui/transactions"),ze=require("bucket-protocol-sdk");var $c=async(r,e,t)=>{let{coinType:n,amount:o}=r,a=new So.Transaction,s=Lt(t,e);return await(0,ze.buildTankDepositTx)(s,a,n,o,e.address),a},Vc=async(r,e,t)=>{let{coinType:n,amount:o}=r,a=new So.Transaction,s=Lt(t,e);return await(0,ze.buildTankWithdrawTx)(s,a,n,o,e.address),a},Hc=async(r,e,t)=>{let{coinType:n}=r,o=new So.Transaction,a=Lt(t,e);return await(0,ze.buildTankClaimTx)(a,o,n,e.address),o};var Xc=require("@mysten/sui/transactions"),zc=require("bucket-protocol-sdk");var Qc=async(r,e,t)=>{let{coinType:n,proofCount:o}=r,a=new Xc.Transaction,s=Lt(t,e);return await(0,zc.buildLockedClaimTx)(s,a,n,o,e.address),a};var wo=class r extends v{constructor(t){super(t);this.data=t}data;txType=xo.TransactionType.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await $c(this.data,n,o)}static fromData(t){return new r(t)}},Io=class r extends v{constructor(t){super(t);this.data=t}data;txType=xo.TransactionType.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await Vc(this.data,n,o)}static fromData(t){return new r(t)}},Co=class r extends v{constructor(t){super(t);this.data=t}data;txType=xo.TransactionType.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await Hc(this.data,n,o)}static fromData(t){return new r(t)}};var Yc=require("@msafe/sui3-utils");var ko=class r extends v{constructor(t){super(t);this.data=t}data;txType=Yc.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Qc(this.data,n,o)}static fromData(t){return new r(t)}};var Do=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new co(t).decode();return{txType:Jc.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,a;switch(e.txSubType){case"psm":a=po.fromData(e.intentionData);break;case"borrow":a=uo.fromData(e.intentionData);break;case"withdraw":a=fo.fromData(e.intentionData);break;case"repay":a=mo.fromData(e.intentionData);break;case"close":a=ho.fromData(e.intentionData);break;case"tank-deposit":a=wo.fromData(e.intentionData);break;case"tank-withdraw":a=Io.fromData(e.intentionData);break;case"tank-claim":a=Co.fromData(e.intentionData);break;case"sbuck-deposit":a=go.fromData(e.intentionData);break;case"sbuck-unstake":a=yo.fromData(e.intentionData);break;case"sbuck-withdraw":a=bo.fromData(e.intentionData);break;case"sbuck-claim":a=To.fromData(e.intentionData);break;case"lock-claim":a=ko.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:t,account:n,network:o})}};var ep=require("@msafe/sui3-utils");var sl=require("@msafe/sui3-utils");var Zc=_t(require("sort-keys-recursive")),k=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Zc.default)(this.data))}};var ee=async(r,e,t)=>{let{CetusClmmSDK:n}=await import("@cetusprotocol/sui-clmm-sdk"),o=n.createSDK({env:"mainnet",sui_grpc_client:t});return o.setSenderAddress(e.address),o},Kt=async(r,e,t)=>{let{CetusFarmsSDK:n}=await import("@cetusprotocol/farms-sdk"),o=n.createSDK({env:"mainnet",sui_grpc_client:t});return o.setSenderAddress(e.address),o},Pd="https://api-sui.cetus.zone/router_v2/find_routes",tl=async(r,e,t)=>{let{AggregatorClient:n,Env:o}=await import("@cetusprotocol/aggregator-sdk");return new n({endpoint:Pd,signer:e.address,client:t,env:o.Mainnet})},kn=async(r,e,t)=>{let{CetusVaultsSDK:n}=await import("@cetusprotocol/vaults-sdk"),o=n.createSDK({env:"mainnet",sui_grpc_client:t});return o.setSenderAddress(e.address),o},Qe=async(r,e,t)=>{let{CetusXcetusSDK:n}=await import("@cetusprotocol/xcetus-sdk"),o=n.createSDK({env:"mainnet",sui_grpc_client:t});return o.setSenderAddress(e.address),o};var el=async(r,e,t,n)=>await(await ee(t,e,n)).Pool.createPoolPayload(r),nl=async(r,e,t,n)=>await(await ee(t,e,n)).Position.createAddLiquidityFixTokenPayload(r?.parameter),ol=async(r,e,t,n)=>await(await ee(t,e,n)).Position.createAddLiquidityFixTokenPayload(r?.parameter),rl=async(r,e,t,n)=>await(await ee(t,e,n)).Position.closePositionPayload(r),al=async(r,e,t,n)=>await(await ee(t,e,n)).Position.removeLiquidityPayload(r),il=async(r,e,t,n)=>await(await ee(t,e,n)).Rewarder.collectRewarderPayload(r);var vo=class r extends k{constructor(t){super(t);this.data=t}data;txType=sl.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await nl(s,o,a,n)}static fromData(t){return new r(t)}};var cl=require("@msafe/sui3-utils");var Ao=class r extends k{constructor(t){super(t);this.data=t}data;txType=cl.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await il(s,o,a,n)}static fromData(t){return new r(t)}};var ll=require("@msafe/sui3-utils");var Mo=class r extends k{constructor(t){super(t);this.data=t}data;txType=ll.TransactionType.Other;txSubType="CreatePool";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await el(s,o,a,n)}static fromData(t){return new r(t)}};var pl=require("@msafe/sui3-utils");var Oo=class r extends k{constructor(t){super(t);this.data=t}data;txType=pl.TransactionType.Other;txSubType="DecreaseLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await al(s,o,a,n)}static fromData(t){return new r(t)}};var Sl=require("@msafe/sui3-utils");var ul=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.openPositionAddLiquidityStakePayload(r),ml=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.addLiquidityFixCoinPayload(r),dl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r);var fl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r),hl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.claimFeeAndClmmReward(r),gl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.harvestPayload(r),yl=async(r,e,t,n)=>{let o=await Kt(t,e,n),a=Object.values(r);return await o.Farms.batchHarvestPayload(a)},bl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.depositPayload(r),Tl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.withdrawPayload(r);var Po=class r extends k{constructor(t){super(t);this.data=t}data;txType=Sl.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await ul(s,o,a,n)}static fromData(t){return new r(t)}};var wl=require("@msafe/sui3-utils");var Ro=class r extends k{constructor(t){super(t);this.data=t}data;txType=wl.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await yl(s,o,a,n)}static fromData(t){return new r(t)}};var Il=require("@msafe/sui3-utils");var Bo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Il.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await hl(s,o,a,n)}static fromData(t){return new r(t)}};var Cl=require("@msafe/sui3-utils");var No=class r extends k{constructor(t){super(t);this.data=t}data;txType=Cl.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await dl(s,o,a,n)}static fromData(t){return new r(t)}};var xl=require("@msafe/sui3-utils");var Eo=class r extends k{constructor(t){super(t);this.data=t}data;txType=xl.TransactionType.Other;txSubType="FarmingHarvest";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await gl(s,o,a,n)}static fromData(t){return new r(t)}};var kl=require("@msafe/sui3-utils");var Wo=class r extends k{constructor(t){super(t);this.data=t}data;txType=kl.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await ml(s,o,a,n)}static fromData(t){return new r(t)}};var Dl=require("@msafe/sui3-utils");var _o=class r extends k{constructor(t){super(t);this.data=t}data;txType=Dl.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await fl(s,o,a,n)}static fromData(t){return new r(t)}};var vl=require("@msafe/sui3-utils");var Lo=class r extends k{constructor(t){super(t);this.data=t}data;txType=vl.TransactionType.Other;txSubType="FarmingStake";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await bl(s,o,a,n)}static fromData(t){return new r(t)}};var Al=require("@msafe/sui3-utils");var jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Al.TransactionType.Other;txSubType="FarmingUnstake";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Tl(s,o,a,n)}static fromData(t){return new r(t)}};var Ml=require("@msafe/sui3-utils");var Uo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ml.TransactionType.Other;txSubType="IncreaseLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await ol(s,o,a,n)}static fromData(t){return new r(t)}};var Rl=require("@msafe/sui3-utils");var Go=async()=>{let{Transaction:r}=await import("@mysten/sui/transactions");return new r},Rd=async(r,e,t,n)=>{let o=await kn(t,e,n),a=await Go();return a.setSender(e.address),o.Vest.buildRedeemPayload(r.params,a),a},Bd=async(r,e)=>{let{default:t,vaults_mainnet:n}=await import("haedal-vault-sdk"),o=new t(n);o.senderAddress=e.address;let a=await Go();return a.setSender(e.address),await o?.Vest.buildRedeemPayload(r.params,a),a},Ol=async(r,e,t,n)=>{let o=await ee(t,e,n),a=await Go();return o?.Vest.buildRedeemPayload(r.params,a),a},Nd=async(r,e,t,n)=>{let o=await ee(t,e,n),a=await Kt(t,e,n),s=await Go(),c=await a.Farms.withdrawReturnPayload(r.withdrawParams,s);return o.Vest.buildRedeemPayload(r.redeemParms.map(m=>({...m,clmm_position_id:c})),s),a.Farms.depositPayload({...r.depositParams,clmm_position_id:c},s),s},Pl=async(r,e,t,n)=>r.type==="clmm"?Ol(r,e,t,n):r.type==="farms"?Nd(r,e,t,n):r.type==="vaults"?Rd(r,e,t,n):r.type==="haedalVaults"?Bd(r,e):Ol(r,e,t,n);var qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Rl.TransactionType.Other;txSubType="PosVestingRedeem";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Pl(s,o,a,n)}static fromData(t){return new r(t)}};var Bl=require("@msafe/sui3-utils");var Fo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Bl.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await rl(s,o,a,n)}static fromData(t){return new r(t)}};var Wl=require("@msafe/sui3-utils");var Nl=require("@mysten/sui/transactions");var El=async(r,e,t,n)=>{let{restituteMsafeFastRouterSwapParams:o}=await import("@cetusprotocol/aggregator-sdk"),a=await tl(t,e,n),s=new Nl.Transaction;return await a.fastRouterSwap({...r,router:o(r.router),txb:s}),s};var Ko=class r extends k{constructor(t){super(t);this.data=t}data;txType=Wl.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await El(s,o,a,n)}static fromData(t){return new r(t)}};var jl=require("@msafe/sui3-utils");var ms=require("@mysten/sui/transactions");var _l=async(r,e,t,n)=>{let o=await kn(t,e,n),a=new ms.Transaction;return a.setSender(e.address),await o.Vaults.deposit(r,a),a},Ll=async(r,e,t,n)=>{let o=await kn(t,e,n),a=new ms.Transaction;return await o.Vaults.withdraw(r,a),a};var $o=class r extends k{constructor(t){super(t);this.data=t}data;txType=jl.TransactionType.Other;txSubType="AddVaultsPosition";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await _l(s,o,a,n)}static fromData(t){return new r(t)}};var Ul=require("@msafe/sui3-utils");var Vo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ul.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Ll(s,o,a,n)}static fromData(t){return new r(t)}};var Kl=require("@msafe/sui3-utils");var ql=require("@mysten/sui/transactions"),Gl={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Fl=async(r,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",r),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:o,periods:a,CLOCK_ADDRESS:s}=r,c=new ql.Transaction;return a.forEach(m=>{c.moveCall({target:`${Gl.published_at}::router::redeem`,typeArguments:[Gl.cetus_coin_type],arguments:[c.object(n),c.object(o),c.pure(m),c.object(s)]})}),c};var Ho=class r extends k{constructor(t){super(t);this.data=t}data;txType=Kl.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:a}=this.data;return await Fl(a,n,o)}static fromData(t){return new r(t)}};var Ql=require("@msafe/sui3-utils");var $l=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.convertPayload(r),Vl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.redeemLockPayload(r),Hl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.redeemDividendV3Payload(r.veNftId,r.rewardList),Xl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.cancelRedeemPayload(r),zl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.redeemPayload(r);var Xo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ql.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Xl(s,o,a,n)}static fromData(t){return new r(t)}};var Yl=require("@msafe/sui3-utils");var zo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Yl.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Hl(s,o,a,n)}static fromData(t){return new r(t)}};var Jl=require("@msafe/sui3-utils");var Qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Jl.TransactionType.Other;txSubType="xCETUSConvert";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await $l(s,o,a,n)}static fromData(t){return new r(t)}};var Zl=require("@msafe/sui3-utils");var Yo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Zl.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await zl(s,o,a,n)}static fromData(t){return new r(t)}};var tp=require("@msafe/sui3-utils");var Jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=tp.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Vl(s,o,a,n)}static fromData(t){return new r(t)}};var Zo=class{application="cetus";supportSDK="@mysten/sui-v2";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{appContext:t}=e;return{txType:ep.TransactionType.Other,txSubType:t.action,intentionData:t}}async build(e){let{suiGrpcClient:t,account:n,network:o}=e,a;switch(e.txSubType){case"OpenAndAddLiquidity":a=vo.fromData(e.intentionData);break;case"IncreaseLiquidity":a=Uo.fromData(e.intentionData);break;case"DecreaseLiquidity":a=Oo.fromData(e.intentionData);break;case"RemoveLiquidity":a=Fo.fromData(e.intentionData);break;case"ClaimFeeAndMining":a=Ao.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":a=Po.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":a=Wo.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":a=No.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":a=_o.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":a=Bo.fromData(e.intentionData);break;case"FarmingHarvest":a=Eo.fromData(e.intentionData);break;case"FarmingBatchHarvest":a=Ro.fromData(e.intentionData);break;case"FarmingStake":a=Lo.fromData(e.intentionData);break;case"FarmingUnstake":a=jo.fromData(e.intentionData);break;case"xCETUSConvert":a=Qo.fromData(e.intentionData);break;case"xCETUSRedeemLock":a=Jo.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":a=zo.fromData(e.intentionData);break;case"xCETUSCancelRedeem":a=Xo.fromData(e.intentionData);break;case"xCETUSRedeem":a=Yo.fromData(e.intentionData);break;case"VestingRedeem":a=Ho.fromData(e.intentionData);break;case"AggregatorSwap":a=Ko.fromData(e.intentionData);break;case"AddVaultsPosition":a=$o.fromData(e.intentionData);break;case"RemoveVaultsPosition":a=Vo.fromData(e.intentionData);break;case"PosVestingRedeem":a=qo.fromData(e.intentionData);break;case"CreatePool":a=Mo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiGrpcClient:t,account:n,network:o})}};var Lp=require("@msafe/sui3-utils");var ds=require("@mysten/sui/grpc"),rp=require("@mysten/sui/transactions");var np=require("@mysten/sui/grpc"),op=require("@mysten/sui/transactions"),Ed={"sui:mainnet":"mainnet","sui:testnet":"testnet","sui:devnet":"devnet","sui:localnet":"localnet"};function tr(r){return Ed[r]}function Yt(r){switch(r){case"mainnet":return"https://fullnode.mainnet.sui.io:443";case"testnet":return"https://fullnode.testnet.sui.io:443";case"devnet":return"https://fullnode.devnet.sui.io:443";case"localnet":return"http://127.0.0.1:9000";default:throw new Error(`Unknown network: ${r}`)}}function Wd(r){return Object.assign(r,{async getCoins(e){let t=await r.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinType:n.type,coinObjectId:n.objectId,version:n.version,digest:n.digest,balance:n.balance,previousTransaction:"0x0"})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}},async devInspectTransactionBlock(e){let t=typeof e.transactionBlock=="object"&&e.transactionBlock!==null&&"setSenderIfNotSet"in e.transactionBlock?e.transactionBlock:op.Transaction.from(e.transactionBlock);t.setSenderIfNotSet(e.sender);let n=await r.simulateTransaction({transaction:t,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}}),o=n.$kind==="Transaction"?n.Transaction:n.FailedTransaction,a=o.effects?.status?.success??!1;return{error:a?null:o.effects?.status?.error?.message??"Simulation failed",effects:{status:{status:a?"success":"failure",error:o.effects?.status?.error?.message}},events:(o.events??[]).map(s=>({type:s.eventType,parsedJson:s.json,packageId:s.packageId,transactionModule:s.module,sender:s.sender,bcs:"",id:{txDigest:"",eventSeq:"0"}})),results:n.commandResults?.map(s=>({returnValues:s.returnValues.map(c=>[Array.from(c.bcs),"u64"])}))}}})}function Dn(r,e){let t=tr(r),n=new np.SuiGrpcClient({network:t,baseUrl:e??Yt(t)});return Wd(n)}function _d(r){return r?r.includes("testnet")?"testnet":r.includes("devnet")?"devnet":r.includes("127.0.0.1")||r.includes("localhost")?"localnet":"mainnet":"mainnet"}var er=class extends ds.SuiGrpcClient{constructor(e){let t=e.baseUrl??e.url??Yt(e.network??"mainnet");super({network:e.network??_d(t),baseUrl:t})}async getCoins(e){let t=await this.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinType:n.type,coinObjectId:n.objectId,version:n.version,digest:n.digest,balance:n.balance,previousTransaction:"0x0"})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}}async getOwnedObjects(e){let t=e.filter&&"StructType"in e.filter?e.filter.StructType:void 0,n=await this.listOwnedObjects({owner:e.owner,type:t,cursor:e.cursor??void 0,limit:e.limit??void 0,include:{content:!!e.options?.showContent,json:!!e.options?.showContent,type:!0}});return{data:n.objects.map(o=>({data:{objectId:o.objectId,version:o.version,digest:o.digest,type:o.type,owner:o.owner,content:o.json?{dataType:"moveObject",type:o.type,fields:o.json,hasPublicTransfer:!1}:o.content?{dataType:"moveObject",type:o.type,fields:o.content,hasPublicTransfer:!1}:void 0}})),hasNextPage:n.hasNextPage,nextCursor:n.cursor}}async devInspectTransactionBlock(e){let t=typeof e.transactionBlock=="object"&&e.transactionBlock!==null&&"setSenderIfNotSet"in e.transactionBlock?e.transactionBlock:rp.Transaction.from(e.transactionBlock);t.setSenderIfNotSet(e.sender);let n=await this.simulateTransaction({transaction:t,checksEnabled:!1,include:{effects:!0,events:!0,commandResults:!0}}),o=n.$kind==="Transaction"?n.Transaction:n.FailedTransaction,a=o.effects?.status?.success??!1;return{error:a?null:o.effects?.status?.error?.message??"Simulation failed",effects:{status:{status:a?"success":"failure",error:o.effects?.status?.error?.message}},events:(o.events??[]).map(s=>({type:s.eventType,parsedJson:s.json,packageId:s.packageId,transactionModule:s.module,sender:s.sender,bcs:"",id:{txDigest:"",eventSeq:"0"}})),results:n.commandResults?.map(s=>({returnValues:s.returnValues.map(c=>[Array.from(c.bcs),"u64"])}))}}};var fs={};us(fs,{contractId:()=>Ud,default:()=>$d,feeObjId:()=>Fd,roleObjId:()=>Gd,status:()=>jd,transaction:()=>Ld,upgradeCapObjId:()=>Kd,vaultObjId:()=>qd});var Ld="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",jd="success",Ud="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Gd="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",qd="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Fd="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Kd="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",$d={transaction:Ld,status:jd,contractId:Ud,roleObjId:Gd,vaultObjId:qd,feeObjId:Fd,upgradeCapObjId:Kd};var hs={};us(hs,{contractId:()=>Xd,default:()=>Zd,feeObjId:()=>Yd,roleObjId:()=>zd,status:()=>Hd,transaction:()=>Vd,upgradeCapObjId:()=>Jd,vaultObjId:()=>Qd});var Vd="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Hd="success",Xd="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",zd="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Qd="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Yd="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Jd="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Zd={transaction:Vd,status:Hd,contractId:Xd,roleObjId:zd,vaultObjId:Qd,feeObjId:Yd,upgradeCapObjId:Jd};var tf=Yt("testnet"),ef=Yt("testnet"),nf=Yt("mainnet"),of=Yt("mainnet"),rf="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",af="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",sf="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",cf="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",ap=fs,ip=hs,lf=new Map([["dev",{env:"dev",rpc:{url:tf},backend:{url:rf},contract:ap}],["stg",{env:"stg",rpc:{url:ef},backend:{url:af},contract:ap}],["prev",{env:"prev",rpc:{url:nf},backend:{url:sf},contract:ip}],["prod",{env:"prod",rpc:{url:of},backend:{url:cf},contract:ip}]]);function sp(r,e){let t=lf.get(r);if(!t)throw new Error(`Env not supported: ${r}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var j=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:o,context:a}=n;o?super(`[MPay] ${t}: ${o}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=a}};var nr=class extends j{constructor(){super(11,"Backend is not specified")}};var or=class extends j{constructor(){super(1,"Wallet not connected")}};var me=_t(require("axios"));var Ye=class extends j{constructor(e,t){super(10,e,{context:t})}};var rr=class r{constructor(e){this.apiURL=e}apiURL;static parseResponseData(e){if(e instanceof me.AxiosError)throw new Ye(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Ye(e.data.code)}throw new Ye(e.status.toString())}async getIncomingStreams(e,t){let n=await me.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return r.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await me.default.post(`${this.apiURL}/stream`,{sender:e,...t});return r.parseResponseData(n)}async getStreamHistory(e){let t=await me.default.post(`${this.apiURL}/stream-events`,e),n=r.parseResponseData(t);return n.data.forEach(o=>{let a=o;return a.data.type==="create_stream"?a.data.balance=BigInt(a.data.balance):a.data.type==="cancel_stream"?a.data.withdrawAmount=BigInt(a.data.withdrawAmount):a.data.type==="claim"||a.data.type==="auto_claim"?a.data.claimAmount=BigInt(a.data.claimAmount):a.data.type==="set_auto_claim"&&(a.data.enabled=!!a.data.enabled),a.createdAt=new Date(a.createdAt),a}),n}async getAllCoinTypes(e){let t=await me.default.post(`${this.apiURL}/stream-info`,{address:e});return r.parseResponseData(t)}async getAllRecipients(e,t){let n=await me.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return r.parseResponseData(n)}async getAllSenders(e,t){let n=await me.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return r.parseResponseData(n)}};var pf={dev:"sui:testnet",stg:"sui:testnet",prev:"sui:mainnet",prod:"sui:mainnet"},Je=class r{signer;suiClient;envConfig;_backend;constructor(e,t){this.envConfig=e,this.suiClient=t??Dn(pf[e.env],e.rpc.url),e.backend&&(this._backend=new rr(e.backend.url))}static new(e,t){let n=sp(e,t);return new r(n,t?.suiGrpcClient)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new nr;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 or;return this.signer}async walletAddress(){return this.wallet.address()}};var _e=require("@mysten/sui/utils");var Pn=require("@mysten/sui/transactions");var bs=require("@mysten/sui/transactions"),On=require("@mysten/sui/utils");var gs=50n,ar=10000n,lp=25n,ys=100000000n;var de=class{constructor(e){this.object=e}object;moveArg(e){return e.object(this.object)}},ir=class{constructor(e){this.objects=e}objects;moveArgs(e){return e.makeMoveVec({elements:this.objects.map(t=>e.object(t))})}},Ee=class r{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 r(t.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield o(s),s++};if(typeof n=="symbol")return;let a=parseInt(n,10);if(!(Number.isNaN(a)||a<0))return o(a)}})}result;moveArg(){return this.result}};function pp(r,e){if(typeof e=="bigint"||typeof e=="number")return r.pure.u64(e);if(typeof e=="boolean")return r.pure.bool(e);if(typeof e=="string")return/^0x[0-9a-fA-F]+$/.test(e)?r.pure.address(e):r.pure.string(e);throw new Error(`Unsupported pure argument type: ${typeof e}`)}var Ip=require("@mysten/bcs");var vn=class extends j{constructor(e,t){super(3,e,{context:t})}};var dp=require("@mysten/bcs");var ne=class extends j{constructor(e,t){super(6,e,{context:t})}};function sr(r){if(r==null)throw new ne("Missing move object field");if(typeof r=="object"&&"fields"in r){let e=r.fields;if(e&&typeof e=="object")return e}if(typeof r=="object")return r;throw new ne("Unexpected move object field shape",{value:String(r)})}function up(r){return r.fields&&typeof r.fields=="object"&&!("balance"in r)&&!("config"in r)&&!("status"in r)?r.fields:r}function mp(r,e="balance"){if(r==null)throw new ne(`Stream object missing ${e} field`);if(typeof r=="string"||typeof r=="number"||typeof r=="bigint")return BigInt(r);let t=sr(r),n=t.balance??t.value;if(n==null)throw new ne(`Stream object ${e} field has unexpected shape`,{value:JSON.stringify(r)});return BigInt(String(n))}async function fp(r,e){let t=await r.listCoins({owner:e.owner,coinType:e.coinType,cursor:e.cursor??void 0,limit:e.limit});return{data:t.objects.map(n=>({coinObjectId:n.objectId,balance:n.balance,coinType:n.type})),hasNextPage:t.hasNextPage,nextCursor:t.cursor}}function uf(r){return r.core?.getObject?r.core.getObject.bind(r.core):r.getObject.bind(r)}function hp(r){return r.json&&typeof r.json=="object"?up(r.json):null}async function gp(r,e){try{let t=uf(r),{object:n}=await t({objectId:e,include:{json:!0,type:!0}}),o=hp(n);return o?{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}:{error:{code:"notExists"}}}catch{return{error:{code:"notExists"}}}}async function yp(r,e){if(e.length===0)return[];let{objects:t}=await r.getObjects({objectIds:e,include:{json:!0,type:!0}});return t.map(n=>{if(!("objectId"in n))return{error:{code:String(n.code??"unknown")}};let o=hp(n);if(o)return{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}})}async function bp(r,e){let{balance:t}=await r.getBalance({owner:e.owner,coinType:e.coinType??void 0});return{coinType:t.coinType,totalBalance:t.balance}}async function Tp(r,e){return(await r.listBalances({owner:e})).balances.map(n=>({coinType:n.coinType,totalBalance:n.balance}))}async function Sp(r,e){let{coinMetadata:t}=await r.getCoinMetadata({coinType:e});return t}async function cr(r,e){e.transaction.setSenderIfNotSet(e.sender);let t=await r.simulateTransaction({transaction:e.transaction,include:{effects:!0,commandResults:!0}}),n=t.$kind==="Transaction"?t.Transaction:t.FailedTransaction;return{effects:n.effects?{status:{status:n.effects.status.success?"success":"failure",error:n.effects.status.error?.message}}:void 0,commandResults:t.commandResults,results:t.commandResults?.map(o=>({returnValues:o.returnValues.map(a=>[Array.from(a.bcs),"u64"])}))}}function wp(r,e=0,t=0){let n=r.commandResults?.[e]?.returnValues?.[t];if(!n)throw new Error("Missing command result");return BigInt(dp.bcs.u64().parse(n.bcs))}var lr=class{constructor(e){this.results=e}results;getU64(e=0,t=0){try{return wp(this.results,e,t)}catch{let[n,o]=this.getLegacyValue(e,t);if(o!=="u64")throw new vn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Ip.bcs.u64().parse(Uint8Array.from(n))}}getLegacyValue(e=0,t=0){let o=this.results.results?.[e]?.returnValues;if(!o?.[t])throw new vn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:"missing"}});return o[t]}};var pr=require("@mysten/bcs");var z=class extends j{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var xp=pr.bcs.struct("StreamMetadata",{groupId:pr.bcs.string(),name:pr.bcs.string()}),mf=64;function kp(r){return Dp(r),xp.serialize(r).toBase64()}function An(r){let e=xp.fromBase64(r);return Dp(e),e}function Dp(r){if(!Cp(r.name))throw new z("Invalid metadata: Name contains unknown character");if(!Cp(r.groupId))throw new z("Invalid metadata: Group ID contains unknown character");if(r.name.length>mf)throw new z("Invalid metadata: Name exceed max length 64")}function Cp(r){return/^[\x00-\x7F]+$/.test(r)}var Mn=require("@mysten/sui/utils");function ur(r,e){return(0,Mn.normalizeStructTag)(r)===(0,Mn.normalizeStructTag)(e)}function Ce(r,e){return(0,Mn.normalizeStructTag)(r)===(0,Mn.normalizeStructTag)(e)}function xe(r){if(r.$kind!=="MoveCall"||!r.MoveCall)return null;let{package:e,module:t,function:n}=r.MoveCall;return`${e}::${t}::${n}`}var mr="txn.gas";var vp=require("nanoid");function Ap(){return(0,vp.nanoid)()}var We=class r{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}globals;feeContract;streamContract;static convertCreateStreamInfoToInternal(e){return{metadata:kp({name:e.name,groupId:Ap()}),coinType:(0,On.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 bs.Transaction,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),a=await this.wallet.requestCoins(o),s=await this.addMergeCoins(t,a[0]),c;o.length>1?c=await this.addMergeCoins(t,a[1]):c=s;for(let m=0;m<e.recipients.length;m++){let b=e.recipients[m],S=this.amountForRecipient(b,e.numberEpoch),w=this.getStreamFeeLocal(S),[C]=t.splitCoins(s,[t.pure.u64(S+w)]),[x]=t.splitCoins(c,[t.pure.u64(this.flatSuiFee)]);this.streamContract.createStream(t,{paymentCoin:new Ee(C),flatFeeCoin:new Ee(x),metadata:e.metadata,recipient:b.address,timeStart:e.startTime,cliff:b.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:b.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=r.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:gs,denominator:ar},claimFeePercent:{numerator:lp,denominator:ar},flatFeePerStream:ys}}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===mr?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return ur(n,On.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:On.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,a)=>{let s=this.amountForRecipient(a,e.numberEpoch),c=this.getStreamFeeLocal(s);return{totalAmount:o.totalAmount+s,streamFeeAmount:o.streamFeeAmount+c}},{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 ys}getStreamFeeLocal(e){return e*gs/ar}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new bs.Transaction,e),n=await cr(this.globals.suiClient,{sender:await this.globals.walletAddress(),transaction:t});return new lr(n).getU64()}get wallet(){return this.globals.wallet}};var Mp="0x0000000000000000000000000000000000000000000000000000000000000006";var Ze=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}moduleName;config;globals;addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.moveCall({target:n,arguments:t.arguments.map(o=>o instanceof ir?o.moveArgs(e):o instanceof de?o.moveArg(e):o instanceof Ee?o.moveArg():pp(e,o)),typeArguments:t.typeArgs}),e}makeObject(e){return typeof e=="string"?new de(e):e}vaultObject(){return new de(this.config.vaultObjId)}roleObject(){return new de(this.config.roleObjId)}feeObject(){return new de(this.config.feeObjId)}clockObject(){return new de(Mp)}};var tn=class r extends Ze{constructor(t,n){super(r.ModuleName,t,n);this.config=t;this.globals=n}config;globals;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(),a=this.feeObject();return this.addContractCall(t,{method:r.MethodName.set_streaming_fee,arguments:[o,a,n],typeArgs:[]})}setStreamingFlatFee(t,n){let o=this.roleObject(),a=this.feeObject();return this.addContractCall(t,{method:r.MethodName.set_streaming_flat_fee,arguments:[o,a,n],typeArgs:[]})}setClaimFee(t,n){let o=this.roleObject(),a=this.feeObject();return this.addContractCall(t,{method:r.MethodName.set_claim_fee,arguments:[o,a,n],typeArgs:[]})}streamingFee(t,n){let o=this.feeObject();return this.addContractCall(t,{method:r.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:r.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:r.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var oe=class r extends Ze{constructor(t,n){super(r.ModuleName,t,n);this.config=t;this.globals=n}config;globals;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(),a=this.vaultObject(),s=this.makeObject(n.paymentCoin),c=this.makeObject(n.flatFeeCoin),m=this.clockObject();return this.addContractCall(t,{method:r.MethodName.create_stream,arguments:[o,a,s,c,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,m],typeArgs:[n.coinType]})}setAutoClaim(t,n){let o=this.makeObject(n.streamId);return this.addContractCall(t,{method:r.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let o=this.makeObject(n.streamId),a=this.clockObject();return this.addContractCall(t,{method:r.MethodName.cancel_stream,arguments:[o,a],typeArgs:[n.coinType]})}claimStream(t,n){let o=this.makeObject(n.streamId),a=this.clockObject();return this.addContractCall(t,{method:r.MethodName.claim_stream,arguments:[o,a],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let o=this.makeObject(n.streamId),a=this.vaultObject(),s=this.feeObject(),c=this.clockObject();return this.addContractCall(t,{method:r.MethodName.claim_stream_by_proxy,arguments:[o,a,s,c],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${r.ModuleName}::${r.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${r.ModuleName}::${r.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${r.ModuleName}::${r.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${r.ModuleName}::${r.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${r.ModuleName}::${r.MethodName.claim_stream_by_proxy}`}};var en=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new tn(t,e),this.streamContract=new oe(t,e)}globals;feeContract;streamContract;async createStreams(e){let t=We.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new We(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new Pn.Transaction;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new Pn.Transaction;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new Pn.Transaction;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new Pn.Transaction;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};var nn=require("@mysten/sui/utils"),Ts=require("luxon");var dr=class extends j{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var df=1e3,fr=class{constructor(e){this.globals=e;this.coinMetaHelper=new Ss(e.suiClient),this.createStreamHelper=new en(e).createStreamHelper()}globals;coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new dr(e.effects?.status.status,e.effects?.status.error);return Object.entries(e.objectTypes??{}).filter(([,t])=>t.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(([t])=>t)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new z("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 z("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 z("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(Ts.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:Ts.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await bp(this.globals.suiClient,{owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:(0,nn.normalizeStructTag)(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await Tp(this.globals.suiClient,e),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,a)=>({...o,coinType:(0,nn.normalizeStructTag)(o.coinType),coinMeta:n[a]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return cr(this.globals.suiClient,{transaction:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new z("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new z("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<df)throw new z("Interval shall be at least 1 second","interval",e.interval)}},Ss=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}suiClient;coinMetaReg;async getCoinMeta(e){let t=(0,nn.normalizeStructTag)(e||nn.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??void 0}async queryCoinMeta(e){return Sp(this.suiClient,e)}};var De=require("@mysten/sui/utils"),vs=require("luxon");var Bn=require("@mysten/sui/transactions"),Nn=require("@mysten/sui/utils"),Pp=require("luxon");var hr=class extends j{constructor(){super(7,"Connected wallet is not creator")}};var Rn=class extends j{constructor(){super(8,"Connected wallet is not recipient")}};var Bt=class extends j{constructor(e,t={}){super(0,e,t)}};var gr=class extends j{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};var br=require("luxon"),Op=(1n<<64n)-1n,yr=1e3;function ws(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/yr);return br.DateTime.fromMillis(t*yr)}function Is(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/yr);return br.Duration.fromMillis(t*yr)}var ke=class r{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new oe(e.envConfig.contract,e)}globals;streamId;rawData;streamContract;type="Stream";static async new(e,t){let n=await r.fetchStreamData(e,t);return new r(e,t,n)}static fromObjectData(e,t,n){let o=r.parseRawStreamData(t,n);return new r(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 r.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Bt("Object Id does not align");this.rawData=r.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 hr;let e=new Bn.Transaction;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Rn;let e=new Bn.Transaction;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Rn;let t=new Bn.Transaction;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new Bn.Transaction;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,Nn.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 Is(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return An(e).groupId}get name(){let{metadata:e}=this.rawData.config;return An(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ws(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return Is(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:ws((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===Op?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=Pp.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 gp(e.suiClient,t);return r.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new gr(e):new ne(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data?.content;if(!n||n.dataType!=="moveObject")throw new ne("Unexpected object type",{gotType:n?.dataType});let{typeParams:o}=(0,Nn.parseStructTag)(n.type),a=(0,Nn.normalizeStructTag)(o[0]),s=n.fields,c=sr(s.config),m=sr(s.status);return{coinType:a,autoClaim:s.auto_claim,balance:mp(s.balance),config:{amountPerEpoch:BigInt(String(c.amount_per_epoch)),cancelable:c.cancelable,cliff:BigInt(String(c.cliff)),creator:String(c.creator),epochInterval:BigInt(String(c.epoch_interval)),metadata:String(c.metadata),recipient:String(c.recipient),timeStart:BigInt(String(c.time_start)),totalEpoch:BigInt(String(c.total_epoch))},status:{status:m.status,epochCanceled:BigInt(String(m.epoch_canceled)),epochClaimed:BigInt(String(m.epoch_claimed))}}}};var on=class extends j{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function xs(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Cs=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}requester;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)}},rn=class{constructor(e){this.requester=e;this.pager=new Cs(e),this.curData=[],this.cursor=0}requester;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 ff=25;async function Ds(r,e,t){let n=new En(e),o=new Wn(r,n,t);return await xs(o)}var En=class{constructor(e){this.ids=e;this.cursor=-1}ids;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]}},Wn=class extends rn{constructor(t,n,o){super(new ks(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}suiClient;idIter;options},ks=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||ff,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}suiClient;stringIter;options;filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let a=await this.stringIter.next();a&&e.push(a)}let t=await yp(this.suiClient,e),n;if(this.filter){let{filter:o}=this;n=t.filter(a=>!!a&&o(a))}else n=t.filter(o=>!!o);return{data:n,hasNext:await this.stringIter.hasNext()}}};var Tr=class r{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new on("stream size 0");let n=t.map(a=>a.groupId);if(new Set(n).size!==1)throw new z("Stream does not have same group ID")}globals;streams;type="StreamGroup";static async new(e,t){let n=await Ds(e.suiClient,t);return n.forEach(o=>{if(!o)throw new Bt("stream group object data undefined")}),r.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let o=await r.parseGroupStreams(e,t,n);return new r(e,o)}static checkStreamGroup(e){let t=e.map(a=>a.groupCommonInfo),n=t[0],o=!0;return t.forEach(a=>{hf(n,a)||(o=!1)}),o}async refresh(){let e=await Ds(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((a,s)=>ke.fromObjectData(e,t[s],a)).filter(a=>!!a);if(new Set(o.map(a=>a.groupId)).size!==1)throw new on("Not same group ID");if(!this.checkStreamGroup(o))throw new on("Not same stream settings");return o}};function hf(r,e){return r.name===e.name&&r.groupId===e.groupId&&r.creator===e.creator&&r.start.toMillis()===e.start.toMillis()&&r.interval.toMillis()===e.interval.toMillis()&&r.steps===e.steps&&r.cancelable===e.cancelable}var _n=class r{constructor(e,t){this.it=e;this.pageSize=t}it;pageSize;static async newIncoming(e){let t=await Sr.newIncoming(e);return new r(t,e.pageSize)}static async newOutgoing(e){let t=await Sr.newOutgoing(e);return new r(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}},Sr=class r{constructor(e){this.requester=e}requester;cachedNext;static async newIncoming(e){let t=await wr.newIncomingQuery(e);return new r(t)}static async newOutgoing(e){let t=await wr.newOutgoingQuery(e);return new r(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 Bt("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Bt("No more results");return e}},wr=class r{constructor(e,t,n,o){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=o;this.current=0;let a=new En(n.flat().map(s=>s.streamId));this.objectIter=new Wn(e.suiClient,a)}globals;recipient;groupRefs;query;current=0;objectIter;static async newIncomingQuery(e){let t=Sf(e.query),n=await e.globals.walletAddress(),a=(await e.globals.backend.getIncomingStreams(n,t)).filter(c=>(0,De.normalizeSuiAddress)(c.recipient)===(0,De.normalizeSuiAddress)(n)),s=Rp(a);return new r(e.globals,n,s,e.query)}static async newOutgoingQuery(e){let t=wf(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),a=Rp(o);return new r(e.globals,n,a,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 bf(this.globals,e[0].streamId,this.objectIter);return this.current++,Bp(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await Tf(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,yf(t,this.query)?t:this.doNextRequest()}throw new Bt("Stream group with no stream")}};function Rp(r){let e=new Map;return r.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)=>vs.DateTime.fromISO(n[0].createDate).toMillis()-vs.DateTime.fromISO(t[0].createDate).toMillis())}function Bp(r,e){if(e===void 0)return!0;let t=gf(r,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?r.progress.claimable!==0n:r.progress.claimable===0n;return t&&n}return t}function gf(r,e){return e===void 0?!0:Array.isArray(e)?e.includes(r.progress.status):r.progress.status===e}function yf(r,e){if(!e)return!0;let t=!1;return r.streams.forEach(n=>{Bp(n,e)&&(t=!0)}),t}async function bf(r,e,t){let n=await Np(t,e);return ke.fromObjectData(r,e,n)}async function Tf(r,e,t){let n=[];for(;n.length<e.length;){let o=await Np(t,e[n.length]);n.push(o)}return Tr.newFromObjectResponse(r,e,n)}async function Np(r,e){if(!await r.hasNext())throw new Bt("object iterator has been consumed");let t=await r.next();if(!t||t.error||t.data===void 0||t.data===null)throw new Bt("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new Bt("stream id not aligned");return t}function Sf(r){return{status:As(r?.status),coinType:Ep(r?.coinType),sender:Wp(r?.sender)}}function wf(r){return{status:As(r?.status),coinType:Ep(r?.coinType),recipient:Wp(r?.recipient)}}function As(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=As(t);return!e||e===n?n:"all"},void 0):If(r)}function If(r){switch(r){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new z("Unknown stream filtered status")}}function Ep(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,De.normalizeStructTag)(e)):void 0:(0,De.normalizeStructTag)(r)}function Wp(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,De.normalizeSuiAddress)(e)):void 0:(0,De.normalizeSuiAddress)(r)}var Ir=class extends j{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}coinType;requestAmount;gotAmount};var Cf=25;async function _p(r,e,t,n="0x2::sui::SUI",o=Cf){let a=new Ms(r,e,n,o),s=BigInt(0),c=[];for(;await a.hasNext()&&s<t;){let m=await a.next();m&&(c.push(m),s+=BigInt(m.balance))}if(s<t)throw new Ir(n,t,s);return c}var Ms=class extends rn{constructor(t,n,o,a){super(new Os(t,n,o,a));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=a}suiClient;owner;coinType;reqPageSize},Os=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new Bt("Invalid reqPageSize")}suiClient;owner;coinType;reqPageSize;nextCursor;async doNextRequest(){let e=await fp(this.suiClient,{owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var Ps=class{constructor(e){this.msafe=e}msafe;get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Cr=class{constructor(e){this.account=e}account;async address(){return this.account.address}},Rs=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}singleWallet;suiClient;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(ur(e.coinType,_e.SUI_TYPE_ARG))return{primaryCoin:mr};if(e.amount<=0)throw new z("Invalid coin request","coinAmount",e.amount);let t=await _p(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new Bt("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},xr=class{globals;helper;constructor(e,t){this.globals=Je.new(e,t),this.helper=new fr(this.globals)}connectSingleWallet(e){let t=new Rs(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new Ps(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ke.new(this.globals,e)}async getIncomingStreams(e,t=10){return _n.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return _n.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,_e.normalizeStructTag)(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>(0,_e.normalizeSuiAddress)(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>(0,_e.normalizeSuiAddress)(o))}get wallet(){return this.globals.wallet}builder(){return new en(this.globals)}};var Vt=class extends k{application="mpay";getClient(e,t,n){let o=new xr(e==="sui:mainnet"?"prod":"dev",{suiGrpcClient:n});return o.connectSingleWallet(new Cr(t)),o}};var Ln=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Lp.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:n,account:o,suiGrpcClient:a}=t;return(await this.getClient(n,o,a).getStream(this.data.streamId)).cancel()}};var jp=require("@msafe/sui3-utils");var jn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=jp.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o,suiGrpcClient:a}=t;return(await this.getClient(n,o,a).getStream(this.data.streamId)).claimByProxy()}};var Up=require("@msafe/sui3-utils");var Un=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Up.TransactionType.Stream;txSubType="Claim";async build(t){let{network:n,account:o,suiGrpcClient:a}=t;return(await this.getClient(n,o,a).getStream(this.data.streamId)).claim()}};var Gp=require("@msafe/sui3-utils");var Gn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Gp.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o,suiGrpcClient:a}=t;return this.getClient(n,o,a).createStream(this.data)}};var qp=require("@mysten/bcs"),je=require("@mysten/sui/bcs"),an=require("@mysten/sui/utils");function qn(r){if(!r.Pure)throw new Error("not pure argument");return(0,qp.fromBase64)(r.Pure.bytes)}var sn=class r{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get moveCallData(){if(this.moveCall.$kind!=="MoveCall")throw new Error("not move call command");return this.moveCall.MoveCall}get inputs(){return this.txb.getData().inputs}getInputIndex(e){let t=this.moveCallData.arguments[e];if(t.$kind!=="Input")throw new Error("not input type");return t.Input}getInputParam(e){return this.inputs[this.getInputIndex(e)]}decodeSharedObjectId(e){let t=this.getInputParam(e);return r.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return r.getOwnedObjectId(t)}decodeInputU64(e){let t=this.getInputParam(e);return BigInt(je.bcs.U64.parse(qn(t)))}decodeInputAddress(e){let t=this.getInputParam(e);return(0,an.normalizeSuiAddress)(je.bcs.Address.parse(qn(t)))}decodeInputString(e){let t=this.getInputParam(e);return je.bcs.String.parse(qn(t))}decodeInputBool(e){let t=this.getInputParam(e);return je.bcs.Bool.parse(qn(t))}decodePureArg(e,t){let n=this.getInputParam(e);return r.getPureInputValue(n,t)}static getPureInputValue(e,t){return r.getPureInput(e,t)}static getOwnedObjectId(e){let t=e.Object?.ImmOrOwnedObject?.objectId??e.Object?.Receiving?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not object argument: ${JSON.stringify(e)}`);return(0,an.normalizeSuiAddress)(t)}static getSharedObjectId(e){let t=e.Object?.SharedObject?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not shared object argument: ${JSON.stringify(e)}`);return(0,an.normalizeSuiAddress)(t)}static getPureInput(e,t){return(0,je.pureBcsSchemaFromTypeName)(t).parse(qn(e))}typeArg(e){return(0,an.normalizeStructTag)(this.moveCallData.typeArguments[e])}txArg(e){return this.moveCallData.arguments[e]}};var kr=class{constructor(e,t){this.globals=e;this.txb=t}globals;txb;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.commands.filter(t=>t.$kind==="MoveCall"&&Ce(xe(t),this.contract.createStreamTarget));if(e.length===0)throw new Bt("No create stream transactions");return e.map(t=>new sn(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=An(t),a=e.decodeInputAddress(5),s=e.decodeInputU64(6),c=e.decodeInputU64(7),m=e.decodeInputU64(8),b=e.decodeInputU64(9),S=e.decodeInputU64(10),w=e.decodeInputBool(11),C=e.typeArg(0);return{name:n,groupId:o,recipient:a,timeStart:s,cliff:c,epochInterval:m,totalEpoch:b,amountPerEpoch:S,cancelable:w,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 z("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}}get commands(){return this.txb.getData().commands}get contract(){return new oe(this.globals.envConfig.contract,this.globals)}get feeContract(){return new tn(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new We(this.globals,this.feeContract,this.contract)}};var Dr=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new oe(e.envConfig.contract,e)}globals;txb;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 commands(){return this.txb.getData().commands}isCreateStreamTransaction(){return this.commands.findIndex(t=>t.$kind==="MoveCall"&&Ce(xe(t),this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.commands.length===1&&this.commands[0].$kind==="MoveCall"&&Ce(xe(this.commands[0]),this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new kr(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.commands[0];if(e.$kind!=="MoveCall")throw new Error("MoveCall not found");return new sn(e,this.txb)}};var Fp=require("@msafe/sui3-utils");var Fn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Fp.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o,suiGrpcClient:a}=t;return(await this.getClient(n,o,a).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var vr=class{application="mpay";supportSDK="@mysten/sui-v2";async deserialize(e){let{network:t,transaction:n,suiGrpcClient:o}=e,a=Je.new(t==="sui:mainnet"?"prod":"dev",{suiGrpcClient:o}),c=new Dr(a,n).decode(),m;switch(c.type){case"CreateStream":m=new Gn(c.info);break;case"SetAutoClaim":m=new Fn({streamId:c.streamId,enabled:c.enabled});break;case"Claim":m=new Un({streamId:c.streamId});break;case"ClaimByProxy":m=new jn({streamId:c.streamId});break;case"Cancel":m=new Ln({streamId:c.streamId});break;default:throw new Error(`Unknown transaction type: ${c}`)}return{txType:m.txType,txSubType:m.txSubType,intentionData:m.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Gn(t);break;case"Claim":n=new Un(t);break;case"ClaimByProxy":n=new jn(t);break;case"SetAutoClaim":n=new Fn(t);break;case"Cancel":n=new Ln(t);break;default:throw new Error("not implemented")}return n.build({...e})}};var Kn=require("@msafe/sui3-utils");var Kp=require("@msafe/sui3-utils");var Ar=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiGrpcClient:n,account:o}=t;return(0,Kp.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new r(t)}};var $p=require("@msafe/sui3-utils");var Mr=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiGrpcClient:n,account:o}=t;return(0,$p.buildObjectTransferTxb)(n,this.data,o.address)}static fromData(t){return new r(t)}};var Or=class{application="msafe-core";supportSDK="@mysten/sui-v2";constructor(){this.application=Kn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{account:t,network:n,suiGrpcClient:o}=e,a;switch(e.txSubType){case Kn.TransactionSubTypes.assets.coin.send:a=Ar.fromData(e.intentionData);break;case Kn.TransactionSubTypes.assets.object.send:a=Mr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiGrpcClient:o,account:t,network:n})}};var Ws=require("@msafe/sui3-utils");var Vp=!1,$n={ProtocolPackage:"0x512f28261c1a293f49416d8885b8d5d32bde6dd68a99a0be36fe42b248e6833a",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 Bs(){if(!Vp)try{let r=await fetch("https://open-api.naviprotocol.io/api/msafe").then(a=>a.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:o}=r;e&&($n.ProtocolPackage=e),t&&($n.borrowFee=t),n&&($n.borrowFeeAddress=n),o&&($n.pool=o),Vp=!0}catch(r){console.error(r.message)}}var re=$n;var ve=require("@msafe/sui3-utils"),Ht=require("@mysten/bcs"),cn=require("@mysten/sui/utils");function Pr(r){if(r.$kind!=="MoveCall")return null;let{package:e,module:t,function:n}=r.MoveCall;return`${e}::${t}::${n}`}var Rr=class{constructor(e){this.txb=e}txb;decode(){if(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 commands(){return this.txb.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>Pr(t)===e)}isClaimRewardTransaction(){return this.commands.some(e=>e.$kind==="MoveCall"&&e.MoveCall.function.includes("claim_reward"))}isEntryBorrowTransaction(){return!!this.getMoveCallCommand(`${re.ProtocolPackage}::incentive_v3::entry_borrow_v2`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallCommand(`${re.ProtocolPackage}::incentive_v3::borrow_v2`)}isEntryMultiDepositTransaction(){let e=`${re.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.commands.filter(o=>Pr(o)===e);return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.function.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${re.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.commands.filter(o=>Pr(o)===e);return!!(this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.function.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallCommand(`${re.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallCommand(`${re.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallCommand(`${re.ProtocolPackage}::incentive_v3::withdraw_v2`)}decodeEntryClaimAndDeposit(){return{txType:ve.TransactionType.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return{txType:ve.TransactionType.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${re.ProtocolPackage}::incentive_v3::entry_deposit`;return this.commands.forEach(n=>{if(Pr(n)===t){let o=new Br(n,this.txb),a=o.decodeInputU8(3),s=o.decodeInputU64(5);e.push({assetId:a,amount:s})}}),{txType:ve.TransactionType.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:ve.TransactionType.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:ve.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.package===re.ProtocolPackage);if(!e)throw new Error("MoveCall not found");return new Br(e,this.txb)}},Br=class r{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get moveCallData(){if(this.moveCall.$kind!=="MoveCall")throw new Error("not move call command");return this.moveCall.MoveCall}get inputs(){return this.txb.getData().inputs}getInputIndex(e){let t=this.moveCallData.arguments[e];if(t.$kind!=="Input")throw new Error("not input type");return t.Input}getInputParam(e){return this.inputs[this.getInputIndex(e)]}decodeSharedObjectId(e){let t=this.getInputParam(e);return r.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return r.getOwnedObjectId(t)}decodeInputU64(e){let t=this.getInputParam(e);return Number(Ht.bcs.u64().parse(Uint8Array.from((0,Ht.fromBase64)(t.Pure.bytes))))}decodeInputU8(e){let t=this.getInputParam(e);return Number(Ht.bcs.u8().parse(Uint8Array.from((0,Ht.fromBase64)(t.Pure.bytes))))}decodeInputAddress(e){let t=this.getInputParam(e);return(0,cn.normalizeSuiAddress)(Ht.bcs.Address.parse(Uint8Array.from((0,Ht.fromBase64)(t.Pure.bytes))))}decodeInputString(e){let t=this.getInputParam(e);return Ht.bcs.string().parse(Uint8Array.from((0,Ht.fromBase64)(t.Pure.bytes)))}decodeInputBool(e){let t=this.getInputParam(e);return Ht.bcs.bool().parse(Uint8Array.from((0,Ht.fromBase64)(t.Pure.bytes)))}static getOwnedObjectId(e){let t=e.Object?.ImmOrOwnedObject?.objectId??e.Object?.Receiving?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not object argument: ${JSON.stringify(e)}`);return(0,cn.normalizeSuiAddress)(t)}static getSharedObjectId(e){let t=e.Object?.SharedObject?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not shared object argument: ${JSON.stringify(e)}`);return(0,cn.normalizeSuiAddress)(t)}typeArg(e){return(0,cn.normalizeStructTag)(this.moveCallData.typeArguments[e])}txArg(e){return this.moveCallData.arguments[e]}};var Ns=require("@mysten/sui/transactions"),qt=require("@naviprotocol/lending");async function ln(r,e,t,n){return await(0,qt.depositCoinPTB)(r,e,t,{amount:n}),r}async function Hp(r,e,t,n){let[o]=await(0,qt.withdrawCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function Xp(r,e,t,n){let[o]=await(0,qt.borrowCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function Es(r,e,t,n){return await(0,qt.repayCoinPTB)(r,e,t,{amount:n}),r}async function zp(r,e){let t=new Ns.Transaction,n=await(0,qt.getUserAvailableLendingRewards)(e,{client:r});return await(0,qt.claimLendingRewardsPTB)(t,n),t}async function Qp(r,e){let t=new Ns.Transaction,n=await(0,qt.getUserAvailableLendingRewards)(e,{client:r});return await(0,qt.claimLendingRewardsPTB)(t,n,{customCoinReceive:{type:"depositNAVI",depositNAVI:{fallbackReceiveAddress:e}}}),t}var Nr=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await zp(t.suiClient,t.account.address)}static fromData(t){return new r(t)}};var Er=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await Qp(t.suiClient,t.account.address)}static fromData(t){return new r(t)}};var Jp=require("@mysten/sui/transactions");var Yp=require("@naviprotocol/lending");async function ae(r){return(0,Yp.getPool)(r)}var Wr=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,a=new Jp.Transaction;console.log("build",this.data);let s=await ae(n);return await Xp(a,s,o,t.account.address)}static fromData(t){return new r(t)}};var Zp=require("@mysten/sui/transactions");async function pn(r,e,t){let n=await r.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var _r=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:a,amount:s}=this.data,c=new Zp.Transaction;console.log("build",this.data);let m=await ae(a);if(a===0){let[C]=c.splitCoins(c.gas,[s]);return await ln(c,m,C,s)}let b=await pn(n,o.address,m.suiCoinType);if(!b.data[0])throw new Error(`Insufficient balance for ${m.suiCoinType} Token`);let S=b.data[0].coinObjectId;if(b.data.length>=2){let C=1;for(;C<b.data.length;)c.mergeCoins(S,[b.data[C].coinObjectId]),C++}return await ln(c,m,c.object(S),s)}static fromData(t){return new r(t)}};var tu=require("@mysten/sui/transactions");var Lr=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:a,amount:s}=this.data,c=new tu.Transaction;console.log("build",this.data);let m=await ae(a);if(a===0){let[w]=c.splitCoins(c.gas,[s]);return Es(c,m,w,s)}let b=await pn(n,o.address,m.suiCoinType);if(!b.data[0])throw new Error(`Insufficient balance for ${m.suiCoinType} Token`);let S=b.data[0].coinObjectId;if(b.data.length>=2){let w=1;for(;w<b.data.length;)c.mergeCoins(S,[b.data[w].coinObjectId]),w++}return Es(c,m,c.object(S),s)}static fromData(t){return new r(t)}};var eu=require("@mysten/sui/transactions");var jr=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,a=new eu.Transaction;console.log("build",this.data);let s=await ae(n);return await Hp(a,s,o,t.account.address)}static fromData(t){return new r(t)}};var nu=require("@mysten/sui/transactions");var Ur=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:a}=this.data,s=new nu.Transaction;console.log("build",this.data);for(let c=0;c<a.length;c++){let{assetId:m,amount:b}=a[c],S=await ae(m);if(m===0){let[x]=s.splitCoins(s.gas,[b]);await ln(s,S,x,b);continue}let w=await pn(n,o.address,S.suiCoinType);if(!w.data[0])throw new Error(`Insufficient balance for ${S.suiCoinType} Token`);let C=w.data[0].coinObjectId;if(w.data.length>=2){let x=1;for(;x<w.data.length;)s.mergeCoins(C,[w.data[x].coinObjectId]),x++}await ln(s,S,s.object(C),b)}return s}static fromData(t){return new r(t)}};var ou=require("@mysten/sui/transactions");var Gr=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return console.log("build",this.data),ou.Transaction.from(this.data.content)}static fromData(t){return new r(t)}};var qr=class{application="navi";supportSDK="@mysten/sui";async deserialize(e){if(await Bs(),e.appContext?.content)return{txType:Ws.TransactionType.Other,txSubType:"PlainTransaction",intentionData:{content:e.appContext.content,scene:e.appContext.scene||"unknown"}};let{transaction:t}=e,o=new Rr(t).decode();return{txType:Ws.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await Bs(),e.txSubType){case"EntryDeposit":o=_r.fromData(e.intentionData);break;case"EntryBorrow":o=Wr.fromData(e.intentionData);break;case"EntryRepay":o=Lr.fromData(e.intentionData);break;case"EntryWithdraw":o=jr.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Ur.fromData(e.intentionData);break;case"ClaimReward":o=Nr.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=Er.fromData(e.intentionData);break;case"PlainTransaction":o=Gr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};var Vn=require("@msafe/sui3-utils"),ru=require("@mysten/bcs"),au=require("@mysten/sui/transactions");var kf="msafe-plain-tx",iu=Vn.TransactionSubTypes.others.plain,_s=class r extends k{constructor(t){super(t);this.data=t}data;txType=Vn.TransactionType.Other;txSubType=iu;async build(t){return au.Transaction.from((0,ru.fromHex)(this.data.content))}static fromData(t){return new r(t)}},Fr=class{application;supportSDK="@mysten/sui-v2";constructor(){this.application=kf}async deserialize(e){let{content:t}=e.appContext;return{txType:Vn.TransactionType.Other,txSubType:iu,intentionData:{content:t}}}async build(e){let{suiGrpcClient:t,network:n,account:o}=e;return _s.fromData(e.intentionData).build({suiGrpcClient:t,network:n,account:o})}};var Ue=require("@mysten/sui/transactions");function su(r,e){return new er({network:tr(r),baseUrl:e})}var cu="0x2::sui::SUI",lu=1e8;async function pu(r){if((0,Ue.isTransaction)(r))return r;if(typeof r=="string"||r instanceof Uint8Array)return Ue.Transaction.from(r);if(r&&typeof r=="object"&&"build"in r&&typeof r.build=="function"){let e=await r.build({onlyTransactionKind:!0});return Ue.Transaction.from(e)}throw new Error("Unsupported transaction payload for deserialize")}var Kr=class r{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new r;for(let n=0;n<e.length;n++){let o=e[n];switch(o.supportSDK){case"@mysten/sui":t.addHelper(o);break;case"@mysten/sui-v2":t.addGrpcHelper(o);break;default:{let a=o;throw new Error(`${a.application}: ${a.supportSDK} SDK not supported`)}}}return t}addHelper(e){this.setApp(e.application,new Ls(e))}addGrpcHelper(e){this.setApp(e.application,new js(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}setApp(e,t){this.apps.set(e,t)}},Ls=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=su(e.network,e.clientUrl),n=await pu(e.transactionBlock);return this.helper.deserialize({...e,suiClient:t,transaction:n})}async build(e){let t=su(e.network,e.clientUrl),{balance:n}=await t.getBalance({owner:e.account.address,coinType:cu});if(Number(n.balance)<lu)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});o.setSender(e.account.address);let a=await o.build({client:t});return Ue.Transaction.from(a)}},js=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=Dn(e.network,e.clientUrl),n=await pu(e.transactionBlock);return this.helper.deserialize({...e,suiGrpcClient:t,transaction:n})}async build(e){let t=Dn(e.network,e.clientUrl),{balance:n}=await t.core.getBalance({owner:e.account.address,coinType:cu});if(Number(n.balance)<lu)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiGrpcClient:t});o.setSender(e.account.address);let a=await o.build({client:t});return Ue.Transaction.from(a)}};var Su=require("@msafe/sui3-utils"),wu=require("@scallop-io/sui-scallop-sdk");var Nt=require("@msafe/sui3-utils"),Fs=require("@scallop-io/sui-scallop-sdk");var uu=require("@mysten/sui/utils"),Ae=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}`))}transaction;scallopClient;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:a}=(0,uu.parseStructTag)(t);return e?e.package===n&&e.module===o&&e.function===a:!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((a,s,c)=>(a[s]=c,a),{}),o=[];return this.commands.forEach(a=>{this.isMoveCall(a)&&a.MoveCall&&t.has(a.MoveCall.package)&&(o[n[a.MoveCall.package]]=a.MoveCall)}),o}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};var Us=require("@mysten/sui/bcs"),Me=require("@mysten/sui/utils"),Gs=class r{constructor(e,t,n=0){this.moveCall=e;this.transaction=t;let o=[];e?.MoveCall&&t.getData().commands.filter((a,s)=>{if(a.$kind==="MoveCall"){let c=`${a.MoveCall.package}::${a.MoveCall.module}::${a.MoveCall.function}`,m=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return c===m?(o.push(s),!0):!1}return!1}),this.cmdIdx=o[n]}moveCall;transaction;cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return r.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return r.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,Me.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 r.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"&&t.kind!=="Result")throw new Error("not nested or result 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;return Us.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,Me.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Me.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,Me.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Me.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 Us.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Me.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},_=Gs;var qs=class{constructor(e,t){this.splitCoin=e;this.txb=t}splitCoin;txb;getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(_.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},jt=qs;var Oe=require("@mysten/sui/utils"),mu=async(r,e)=>{let t=await r.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 a=r.address.get("borrowIncentive.object");return o===`${a.slice(2)}::incentive_account::IncentiveProgramLockKey`},un={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},Xt={unstakeObligation:(r,e,t)=>r.moveCall(`${un.id}::user::unstake`,[un.incentivePools,un.incentiveAccounts,r.object(e),r.object(t),Oe.SUI_CLOCK_OBJECT_ID],[(0,Oe.normalizeStructTag)(Oe.SUI_TYPE_ARG)]),redeem_rewards:(r,e,t,n)=>r.moveCall(`${un.id}::user::redeem_rewards`,[un.incentivePools,un.incentiveAccounts,r.object(e),r.object(t),Oe.SUI_CLOCK_OBJECT_ID],[(0,Oe.normalizeStructTag)(n)])};var du=(r,e)=>{let t=[];for(let n=0;n<r.length;n+=e)t.push(r.slice(n,n+e));return t};var $r=class extends Ae{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(`${Fs.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 _(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new _(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 _(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Fs.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`)).map(t=>new _(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new _(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new _(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new _(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new _(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 _(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new _(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new _(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new _(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new _(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new _(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new _(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new _(e,this.transaction)}decodeMigrateScoin(){return{txType:Nt.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:Nt.TransactionType.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Nt.TransactionType.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new jt(t,this.transaction).getAmountInput().reduce((o,a)=>o+a,0);return{txType:Nt.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 jt(t,this.transaction).getAmountInput().reduce((o,a)=>o+a,0);return{txType:Nt.TransactionType.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperBurnScoin.getNestedInputParam(1),n=new jt(t,this.transaction).getAmountInput().reduce((o,a)=>o+a,0);return{txType:Nt.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 jt(t,this.transaction).getAmountInput().reduce((a,s)=>a+s,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Nt.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:Nt.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:Nt.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),a=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Nt.TransactionType.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:a,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),a=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Nt.TransactionType.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:a,obligationId:o,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new jt(t,this.transaction).getAmountInput().reduce((a,s)=>a+s,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Nt.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 jt(n,this.transaction).getAmountInput().reduce((s,c)=>s+c,0),a=this.helperRepay.decodeSharedObjectId(1);return{txType:Nt.TransactionType.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:a,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let a=this.helperBurnScoin.getNestedInputParam(1);t=new jt(a,this.transaction).getAmountInput().reduce((s,c)=>s+c,0)}if(this.helperStake.moveCall&&t===0){let a=this.helperStake.getNestedInputParam(2);t=new jt(a,this.transaction).getAmountInput().reduce((s,c)=>s+c,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Nt.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:Nt.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 jt(t,this.transaction).getAmountInput().reduce((a,s)=>a+s,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Nt.TransactionType.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(o=>{let a=o.decodeOwnedObjectId(1),s=o.decodeInputU64(2);e.push({id:a,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 jt(o,this.transaction).getAmountInput().reduce((a,s)=>a+s,0)}return{txType:Nt.TransactionType.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let a=o.decodeOwnedObjectId(2),s=o.typeArg(0),c=this.utils.parseCoinNameFromType(s);e.push({stakeMarketCoinName:c,stakeAccountId:a})}),this.helperClaimBorrowV2Reward.forEach(o=>{let a=o.decodeSharedObjectId(4),s=o.decodeOwnedObjectId(3),c=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:s,obligationKey:a,rewardCoinName:c})}),this.helperClaimBorrowReward.forEach(o=>{let a=o.decodeSharedObjectId(2),s=o.decodeOwnedObjectId(3),c=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:s,obligationKey:a,rewardCoinName:c})}),{txType:Nt.TransactionType.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};var Vr=require("@msafe/sui3-utils");var Hr=class extends Ae{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 _(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 _(e,this.transaction)}decodeCreateReferralLink(){return{txType:Vr.TransactionType.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Vr.TransactionType.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Vr.TransactionType.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};var ie=require("@msafe/sui3-utils"),fu=require("@scallop-io/sui-scallop-sdk");var Xr=class extends Ae{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(c=>this.filterMoveCallCommands(c,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(c=>this.filterMoveCallCommands(c,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),n=this.commands.filter(c=>this.filterMoveCallCommands(c,`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`)),o=e.length>0&&t.length>0&&e.length===t.length,a=n.length>0;return this.commands.length===e.length+t.length+n.length&&(o||a)}async isTransferVeScaKey(){let e=this.commands.filter(m=>m.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,n=t.filter(m=>m.$kind==="Input").map(({Input:m})=>m);if(n.length!==t.length)return!1;let o=new Set(n),a=this.inputs.filter((m,b)=>m.$kind==="Object"&&o.has(b)).map(m=>m.Object.ImmOrOwnedObject),s=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,c=du(a.map(({objectId:m})=>m),50);for(let m=0;m<c.length;m++){let b=c[m];if((await this.scallopClient.scallopSuiKit.queryGetObjects(b,{showType:!0})).some(w=>w.type!==s))return!1}return a.length>0}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new _(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 _(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new _(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new _(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 _(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${fu.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`));return new _(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new _(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 _(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(n=>this.filterMoveCallCommands(n,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new _(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=[],a=0,s=0,c=0;return this.commands.forEach(m=>{this.filterMoveCallCommands(m,e)?(o.push({action:"unstake",helper:new _(m,this.transaction,a)}),a++):this.filterMoveCallCommands(m,t)?(o.push({action:"stake",helper:new _(m,this.transaction,s)}),s++):this.filterMoveCallCommands(m,n)&&(o.push({action:"deactivate",helper:new _(m,this.transaction,c)}),c++)}),o}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:ie.TransactionType.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new jt(e,this.transaction).getAmountInput().reduce((D,O)=>D+O,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),a=!!this.helperRedeemSca.moveCall,s=[],c=[],m=[];this.helperOldUnstakeObligation.moveCall&&(s=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(c=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(m=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let b=!1,S=!1,w,C,x=[{condition:s,isOld:!0},{condition:c,isOld:!1},{condition:m,isOld:!1}];for(let D=0;D<x.length;D++)x[D].condition.length>1&&([C,w]=x[D].condition,b=!0,S=x[D].isOld);return{txType:ie.TransactionType.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:w,obligationKey:C,veScaKey:o,isHaveRedeem:a,isObligationLocked:b,isOldBorrowIncentive:S}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],a=[];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&&(a=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let s=!1,c=!1,m,b,S=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:a,isOld:!1}];for(let w=0;w<S.length;w++)S[w].condition.length>1&&([b,m]=S[w].condition,s=!0,c=S[w].isOld);return{txType:ie.TransactionType.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:m,obligationKey:b,veScaKey:t,isObligationLocked:s,isOldBorrowIncentive:c}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new jt(e,this.transaction).getAmountInput().reduce((x,D)=>x+D,0),o=[],a=[],s,c=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(s=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let m=!1,b=!1,S,w,C=[{condition:o,isOld:!0},{condition:a,isOld:!1},{condition:c,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([w,S]=C[x].condition,m=!0,b=C[x].isOld);return{txType:ie.TransactionType.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:s,unlockTime:t,obligationId:S,obligationKey:w,isOldBorrowIncentive:b,isObligationLocked:m}}}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 jt(e,this.transaction).getAmountInput().reduce((x,D)=>x+D,0),o=[],a=[],s,c=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(a=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(s=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(c=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let m=!1,b=!1,S,w,C=[{condition:o,isOld:!0},{condition:a,isOld:!1},{condition:c,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([w,S]=C[x].condition,m=!0,b=C[x].isOld);return{txType:ie.TransactionType.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:S,obligationKey:w,veScaKey:s,isObligationLocked:m,isOldBorrowIncentive:b}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:ie.TransactionType.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:ie.TransactionType.Other,type:"SplitVeSca",intentionData:t}}decodeVeScaObligationBindings(){let e=this.getVeScaObligationBindingHelpers(),t=(o,a)=>{switch(o){case"stake":return{veScaKey:a.decodeOwnedObjectId(9),obligationId:a.decodeSharedObjectId(4),obligationKey:a.decodeOwnedObjectId(3)};case"unstake":return{obligationId:a.decodeSharedObjectId(4),obligationKey:a.decodeOwnedObjectId(3)};case"deactivate":return{veScaKey:a.decodeOwnedObjectId(4),obligationId:a.decodeSharedObjectId(3)};default:throw new Error(`Invalid action ${o}`)}},n=e.map(({action:o,helper:a})=>({action:o,args:t(o,a)}));return{txType:ie.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),a=this.inputs.filter((s,c)=>s.$kind==="Object"&&o.has(c)).map(s=>s.Object.ImmOrOwnedObject);return{xType:ie.TransactionType.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:a}}}};var hu=_t(require("sort-keys-recursive")),M=class{constructor(e){this.data=e}data;get application(){return"msafe-core"}serialize(){return JSON.stringify((0,hu.default)(this.data))}isObligationLocked=async(e,t)=>{let n=typeof t=="string"?t:t.objectId,{object:o}=await e.getObject({objectId:n,include:{json:!0}});return!!o.json?.lock_key};async buildTxWithRefreshObligation(e,t,n){let o=e.builder.createTxBlock();o.setSender(t.walletAddress);let{obligationId:a,obligationKey:s}=t;return await this.isObligationLocked(e.scallopSuiKit.client,a)?(await o.unstakeObligationQuick(a,s),await n(e,o,t),await o.stakeObligationWithVeScaQuick(a,s,t.veScaKey)):await n(e,o,t),o}};var zr=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:a,obligationId:s,obligationKey:c}=this.data,m=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:m,obligationId:s,obligationKey:c},async(S,w)=>{let C=await w.borrowQuick(+a,o,s,c);w.transferObjects([C],m)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new r(t)}};var Qr=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrowWithBoost(t,n){let{obligationId:o,obligationKey:a,veScaKey:s,amount:c,coinName:m}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:n,obligationId:o,obligationKey:a,veScaKey:s},async(S,w)=>{let C=await w.borrowQuick(+c,m,o,a);w.transferObjects([C],n)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new r(t)}};var Yr=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:a,obligationKey:s,veScaKey:c,coinName:m,amount:b}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:a,obligationKey:s,veScaKey:c},async(w,C)=>{let x=C.claimReferralTicket(m),D=await C.borrowWithReferralQuick(+b,m,x,a,s);C.burnReferralTicket(x,m),C.transferObjects([D],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new r(t)}};var gu=require("@mysten/sui/utils");var Jr=class r extends M{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),a=await e.query.getLendings(void 0,t),s=await e.query.getObligations(t),c=Object.values(await e.query.getObligationAccounts(t)??[]),m=(()=>{let C=[...e.constants.whitelist.spool].map(x=>e.utils.parseCoinName(x));return Object.values(a??[]).filter(x=>!!x&&C.includes(x.coinName)).reduce((x,D)=>{let O=e.utils.parseMarketCoinName(D.coinName);return x[O]||(x[O]=0),x[O]+=D.availableClaimCoin,x},{})})(),b={};Object.entries(o).forEach(([C,x])=>{for(let D=0;D<x.length;D++){let O=x[D];if(!m[C])continue;let G=n.claim(O.id,C);b.sui?b.sui.push(G):b.sui=[G]}});let S=(()=>{let C={};return C.sui=Object.values(m).reduce((x,D)=>x+D,0),c.forEach(x=>{Object.values(x.borrowIncentives).forEach(D=>{D&&D.rewards.forEach(O=>{C[O.coinName]||(C[O.coinName]=0),C[O.coinName]?C[O.coinName]+=O.availableClaimCoin:C[O.coinName]=O.availableClaimCoin})})}),C})();if(s.length>0&&c.length>0)for(let C=0;C<c.length;C++){let x=c[C],D=!1,O=s.find(U=>U.id===x.obligationId)?.keyId,G={};if(O){if(Object.values(x.borrowIncentives).forEach(U=>{if(U){let K=U.rewards.filter(V=>{let E=V.coinName;return V.availableClaimCoin>0&&!G[E]});D=K.length>0,K.forEach(V=>{let E=n.claimBorrowIncentive(x.obligationId,O,V.coinName);G[V.coinName]=!0,b[V.coinName]?b[V.coinName].push(E):b[V.coinName]=[E]})}}),S.sui>0){let U=Xt.redeem_rewards(n,O,x.obligationId,gu.SUI_TYPE_ARG);b.sui?b.sui.push(U):b.sui=[U]}if(D&&await mu(e.query,x.obligationId)){n.unstakeObligation(x.obligationId,O);let K=await e.query.getBindedVeScaKey(x.obligationId);K?n.stakeObligationWithVesca(x.obligationId,O,K):n.stakeObligation(x.obligationId,O)}}}let w=(await Promise.all(Object.entries(b).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 w.length>0&&n.transferObjects(w,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new r(e)}};var Zr=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new r(t)}};var ta=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:a,obligationId:s,rewardCoinName:c,veScaKey:m}=this.data,b=n.builder.createTxBlock();b.setSender(o);let S=Xt.redeem_rewards(b,a,s,n.utils.parseCoinType(c));return b.transferObjects([S],o),await b.unstakeObligationQuick(s,a),m?await b.stakeObligationWithVeScaQuick(s,a,m):await b.stakeObligationQuick(s,a),b.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new r(t)}};var ea=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new r(t)}};var na=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.openObligation(!1)}static fromData(t){return new r(t)}};var oa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:a,amount:s,obligationId:c,obligationKey:m}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:c,obligationKey:m},async(S,w)=>{await w.repayQuick(+s,a,c)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new r(t)}};var ra=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:a,amount:s,obligationId:c,veScaKey:m}=this.data,b=n.builder.createTxBlock();b.setSender(o);let S=n.constants.whitelist.borrowing.has(a);return S&&await b.unstakeObligationQuick(c,void 0),await b.repayQuick(+s,a,c),S&&await b.stakeObligationWithVeScaQuick(c,void 0,m),b.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new r(t)}};var aa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new r(t)}};var ia=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new r(t)}};var sa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async unstakeAndWithdraw(t,n,o){let a=t.builder.createTxBlock();a.setSender(o);let{stakeAccountId:s,amount:c,coinName:m}=this.data,b=[];for(let S=0;S<s.length;S++){let{id:w,coin:C}=s[S],x=t.utils.parseMarketCoinName(m),[D]=await a.unstakeQuick(C,x,w,!1);if(D){let O=a.withdraw(D,m);b.push(O)}}if(c>0){let S=await a.withdrawQuick(c,m);b.push(S)}return b.length>1&&a.mergeCoins(b[0],b.slice(1)),a.transferObjects(b,o),a.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new r(t)}};var ca=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await 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 r(t)}};var la=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){return await t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new r(t)}};var pa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async bindReferral({account:t,scallopClient:n}){let o=t.address,a=n.builder.createTxBlock();return a.setSender(o),a.bindToReferral(this.data.veScaKey),a.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new r(t)}};var ua=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:a}=this.data,s=t.address,c=n.builder.createTxBlock();c.setSender(s);let m=a.map(b=>n.utils.parseCoinNameFromType(b));return await c.claimReferralRevenueQuick(o,m),c.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new r(t)}};var ma=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let o=t.address,a=n.builder.createTxBlock();a.setSender(o);let s=a.mintEmptyVeSca();return a.transferObjects([s],o),a.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new r(t)}};var yu=require("@scallop-io/sui-scallop-sdk");var da=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:a,unlockTime:s,obligationId:c,obligationKey:m,isOldBorrowIncentive:b,isObligationLocked:S}=this.data,w=t.address,C=n.builder.createTxBlock();C.setSender(w);let x=await n.utils.selectCoins(o,yu.SCA_COIN_TYPE,w),[D,O]=C.takeAmountFromCoins(x,o);return C.extendLockPeriod(a,s),C.extendLockAmount(a,D),C.transferObjects([O],w),!c||!m||(S&&(b?Xt.unstakeObligation(C,c,m):C.unstakeObligation(c,m)),C.stakeObligationWithVesca(c,m,a)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new r(t)}};var fa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:a,unlockTime:s,obligationId:c,obligationKey:m,isObligationLocked:b,isOldBorrowIncentive:S}=this.data,w=n.builder.createTxBlock();return w.setSender(o),w.extendLockPeriod(a,s),c&&m&&(b&&(S?Xt.unstakeObligation(w,m,c):w.unstakeObligation(c,m)),w.stakeObligationWithVesca(c,m,a)),w.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new r(t)}};var ha=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:a,sourceVeScaKey:s}=this.data,[c,m]=await Promise.all([n.getBindedObligationId(a),n.getBindedObligationId(s)]);c&&await t.unstakeObligationQuick(c),m&&await t.unstakeObligationQuick(m),o(t,a,s),c&&await t.stakeObligationWithVeScaQuick(c,void 0,a),m&&await t.stakeObligationWithVeScaQuick(m,void 0,s)}async build(t){let{scallopClient:n,account:{address:o}}=t,a=n.builder.createTxBlock();return a.setSender(o),await this.handleUnsubForKeys(a,n.query,async(s,c,m)=>{s.mergeVeSca(a.object(c),a.object(m))}),a.txBlock}static fromData(t){return new r(t)}};var ga=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:o}=this.data,a=t.address,s=n.builder.createTxBlock();return s.setSender(a),await s.redeemScaQuick({veScaKey:o}),s.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new r(t)}};var bu=require("@scallop-io/sui-scallop-sdk");var ya=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:a,unlockTime:s,veScaKey:c,isHaveRedeem:m,obligation:b,obligationKey:S,isObligationLocked:w,isOldBorrowIncentive:C}=this.data,x=n.builder.createTxBlock();if(x.setSender(o),m){let U=x.redeemSca(c);x.transferObjects([U],o)}let D=await n.builder.utils.selectCoins(a,bu.SCA_COIN_TYPE,o),[O,G]=x.takeAmountFromCoins(D,a);return x.transferObjects([G],o),x.renewExpiredVeSca(c,O,s),!b||!S||(w&&(C?Xt.unstakeObligation(x,S,b):x.unstakeObligation(b,S)),x.stakeObligationWithVesca(b,S,c)),x.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new r(t)}};var ba=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:a,splitAmount:s}=this.data,c=await n.getBindedObligationId(a);c&&await t.unstakeObligationQuick(c),o(t,a,s.toString()),c&&await t.stakeObligationWithVeScaQuick(c,void 0,a)}async build(t){let{scallopClient:n,account:{address:o}}=t,a=n.builder.createTxBlock();return a.setSender(o),await this.handleUnsubForKeys(a,n.query,(s,c,m)=>{let b=s.splitVeSca(c,m.toString());s.transferObjects([b],o)}),a.txBlock}static fromData(t){return new r(t)}};var Tu=require("@scallop-io/sui-scallop-sdk");var Ta=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:a,isObligationLocked:s,isOldBorrowIncentive:c,obligationId:m,obligationKey:b,unlockTime:S,veScaKey:w}=this.data,C=n.builder.createTxBlock();C.setSender(o);let x=await n.utils.selectCoins(a,Tu.SCA_COIN_TYPE,o),[D,O]=C.takeAmountFromCoins(x,a),G;return w?C.extendLockAmount(w,D):G=C.lockSca(D,S),m&&b&&(s&&(c?Xt.unstakeObligation(C,b,m):C.unstakeObligation(m,b)),C.stakeObligationWithVesca(m,b,w||G)),w||C.transferObjects([G,O],o),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new r(t)}};var Sa=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:a,coinName:s,stakeAccountId:c}=this.data,m=n.builder.createTxBlock();m.setSender(o);let b=await m.depositQuick(+a,s),S=n.utils.parseMarketCoinName(s);if(n.constants.whitelist.spool.has(S))return m.txBlock;let w=await n.query.getStakeAccounts(S,o),C=c||(w.length>0?w[0].id:void 0);if(C)await m.stakeQuick(b,S,C);else{let x=m.createStakeAccount(S);await m.stakeQuick(b,S,x),m.transferObjects([x],o)}return m.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new r(t)}};var wa=class r extends M{constructor(t){super(t);this.data=t}data;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,a=n.builder.createTxBlock();a.setSender(o);let{bindingDatas:s}=this.data;return s.forEach(c=>this.handleAction(a,c)),a.txBlock}static fromData(t){return new r(t)}};var Ia=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{scallopClient:n,account:{address:o}}=t,a=n.builder.createTxBlock();a.setSender(o);let{veScaKeys:s}=this.data;return a.transferObjects(s.map(c=>a.objectRef(c)),a.pure.address(o)),a.txBlock}static fromData(t){return new r(t)}};var Ca=class r extends M{constructor(t){super(t);this.data=t}data;txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:o}=this.data,a=t.address,s=n.builder.createTxBlock();return s.setSender(a),await s.redeemScaQuick({veScaKey:o}),s.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new r(t)}};var xa=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let n=new wu.Scallop({addressId:"695fcdc084f790c04eb068dc",walletAddress:e,suiClients:[t],fullnodeUrls:[t.transport.rpcClient.requestManager.transports[0]?.uri??Yt("mainnet")]});this.scallopClient=await n.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;await this.initScallopClient(o.address,n);let a=new $r(t,this.scallopClient),s=new Hr(t,this.scallopClient),c=new Xr(t,this.scallopClient),m=a.decode()||s.decode()||await c.decode();if(!m)throw new Error("Unknown transaction type");return{txType:Su.TransactionType.Other,txSubType:m.type,intentionData:m.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:a,intentionData:s}=e;await this.initScallopClient(n.address,t);let c;switch(a){case"SupplyLending":c=aa.fromData(s);break;case"WithdrawLending":c=la.fromData(s);break;case"Borrow":c=zr.fromData(s);break;case"Repay":c=oa.fromData(s);break;case"DepositCollateral":c=Zr.fromData(s);break;case"WithdrawCollateral":c=ca.fromData(s);break;case"OpenObligation":c=na.fromData(s);break;case"UnstakeSpool":c=ia.fromData(s);break;case"ClaimIncentiveReward":c=Jr.fromData(s);break;case"BorrowWithBoost":c=Qr.fromData(s);break;case"StakeSca":c=Ta.fromData(s);break;case"ExtendStakePeriod":c=fa.fromData(s);break;case"ExtendPeriodAndStakeMore":c=da.fromData(s);break;case"RenewExpStakePeriod":c=ya.fromData(s);break;case"WithdrawStakedSca":c=Ca.fromData(s);break;case"SupplyAndStakeLending":c=Sa.fromData(s);break;case"WithdrawAndUnstakeLending":c=sa.fromData(s);break;case"RedeemSca":c=ga.fromData(s);break;case"MigrateAndClaim":c=ta.fromData(s);break;case"BorrowWithReferral":c=Yr.fromData(s);break;case"CreateReferralLink":c=ma.fromData(s);break;case"ClaimRevenueReferral":c=ua.fromData(s);break;case"BindReferral":c=pa.fromData(s);break;case"MigrateScoin":c=ea.fromData(s);break;case"RepayWithBoost":c=ra.fromData(s);break;case"MergeVeSca":c=ha.fromData(s);break;case"SplitVeSca":c=ba.fromData(s);break;case"VeScaObligationBindings":{c=wa.fromData(s);break}case"TransferVeScaKeys":{c=Ia.fromData(s);break}default:throw new Error("not implemented")}return c.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};var Fu=require("@msafe/sui3-utils");var gn=require("@msafe/sui3-utils"),Re=require("@mysten/sui/utils");var Bu=require("@suilend/sui-fe");var Ru=require("@msafe/sui3-utils"),Pe=require("@suilend/sdk");var Ge=require("@msafe/sui3-utils"),fn=require("@mysten/bcs"),dn=require("@mysten/sui/utils"),qe=require("@suilend/sui-fe"),$s=_t(require("bignumber.js"));var ka=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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,dn.normalizeStructTag)(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Ge.TransactionType.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(m=>m.type.includes("lending_market::RedeemEvent"))},n=(0,dn.normalizeStructTag)(t.RedeemEvent.parsedJson.coin_type.name),o=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let a=e.withdraw_ctokens.MoveCall.arguments[4].Input,s=new $s.default((0,fn.toHex)((0,fn.fromBase64)(this.inputs[a].Pure.bytes)),16).toString(),c=s===qe.MAX_U64.toString();return console.log("decodeWithdraw - isMax:",c,"inputIndex:",a,"inputValue:",s,"MAX_U64.toString():",qe.MAX_U64.toString()),c&&(o=qe.MAX_U64.toString()),{txType:Ge.TransactionType.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(m=>m.type.includes("lending_market::BorrowEvent"))},n=(0,dn.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 a=e.borrow_request.MoveCall.arguments[4].Input,s=new $s.default((0,fn.toHex)((0,fn.fromBase64)(this.inputs[a].Pure.bytes)),16).toString(),c=s===qe.MAX_U64.toString();return console.log("decodeBorrow - isMax:",c,"inputIndex:",a,"inputValue:",s,"MAX_U64.toString():",qe.MAX_U64.toString()),c&&(o=qe.MAX_U64.toString()),{txType:Ge.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,dn.normalizeStructTag)(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Ge.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],a=(0,dn.normalizeStructTag)(o.parsedJson.coin_type.name),s=o.parsedJson.liquidity_amount;t[a]=`${+(t[a]??"0")+ +s}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Ge.TransactionType.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Ge.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var Cu=require("@mysten/sui/transactions");var Iu=_t(require("sort-keys-recursive")),Ft=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Iu.default)(this.data))}};var Da=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;if(console.log("BorrowIntention.build",n,o,a,s,c),!s||!c)throw new Error("Obligation not found");let m=new Cu.Transaction;return await a.borrowAndSendToUser(o.address,s.id,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("BorrowIntention.fromData",t),new r(t)}};var vu=require("@mysten/sui/transactions");var xu=require("@mysten/sui/utils"),hn=require("@suilend/sdk"),ku=require("@suilend/sui-fe"),Du=_t(require("bignumber.js")),vf=(r,e)=>{let t={[hn.Side.DEPOSIT]:[],[hn.Side.BORROW]:[]};return r.lendingMarket.reserves.forEach(n=>{[hn.Side.DEPOSIT,hn.Side.BORROW].forEach(o=>{let a=o===hn.Side.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,s=e.userRewardManagers.find(c=>c.poolRewardManagerId===a.id);s&&(t[o]=a.poolRewards.map((c,m)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(m),rewardCoinType:(0,xu.normalizeStructTag)(c.coinType.name),side:o})).filter(c=>!(0,ku.isSendPoints)(c.rewardCoinType)&&!!s.rewards[Number(c.rewardIndex)]&&new Du.default(s.rewards[Number(c.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},va=vf;var Aa=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;if(console.log("ClaimIntention.build",n,o,a,s,c),!s||!c)throw new Error("Obligation not found");let m=new vu.Transaction;return a.claimRewardsAndSendToUser(o.address,s.id,va(a,c),m),m}static fromData(t){return console.log("ClaimIntention.fromData",t),new r(t)}};var Au=require("@mysten/sui/transactions");var Ma=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;if(console.log("ClaimAndDepositIntention.build",n,o,a,s,c),!s||!c)throw new Error("Obligation not found");let m=new Au.Transaction;return a.claimRewardsAndDeposit(o.address,s.id,va(a,c),m),m}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new r(t)}};var Mu=require("@mysten/sui/transactions");var Oa=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;console.log("DepositIntention.build",n,o,a,s,c);let m=new Mu.Transaction;return await a.depositIntoObligation(o.address,this.data.coinType,this.data.value,m,s?.id),m}static fromData(t){return console.log("DepositIntention.fromData",t),new r(t)}};var Ou=require("@mysten/sui/transactions");var Pa=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;if(console.log("RepayIntention.build",n,o,a,s,c),!s||!c)throw new Error("Obligation not found");let m=new Ou.Transaction;return await a.repayIntoObligation(o.address,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("RepayIntention.fromData",t),new r(t)}};var Pu=require("@mysten/sui/transactions");var Ra=class r extends Ft{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,obligationOwnerCap:s,obligation:c}=t;if(console.log("WithdrawIntention.build",n,o,a,s,c),!s||!c)throw new Error("Obligation not found");let m=new Pu.Transaction;return await a.withdrawAndSendToUser(o.address,s.id,c.id,this.data.coinType,this.data.value,m),m}static fromData(t){return console.log("WithdrawIntention.fromData",t),new r(t)}};var Ba=async(r,e)=>{let t=await Pe.SuilendClient.initialize(Pe.LENDING_MARKET_ID,Pe.LENDING_MARKET_TYPE,r),n=await Pe.SuilendClient.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,r),o=await Promise.all(n.map(a=>Pe.SuilendClient.getObligation(a.obligationId,t.lendingMarket.$typeArgs,r)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:o}},Na=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Ba(n,o));let a=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",a,"utils:",this.utils,"suiClient:",n);let c=new ka(t,a).decode();return{txType:Ru.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:a,account:s}=e;this.utils||(this.utils=await Ba(a,s));let c;switch(n){case"deposit":c=Oa.fromData(o);break;case"withdraw":c=Ra.fromData(o);break;case"borrow":c=Da.fromData(o);break;case"repay":c=Pa.fromData(o);break;case"claim":c=Aa.fromData(o);break;case"claimAndDeposit":c=Ma.fromData(o);break;default:throw new Error("not implemented")}let m=window.localStorage.getItem("obligationId"),b=this.utils.obligations?.find(w=>w.id===m)??this.utils.obligations?.[0],S=this.utils.obligationOwnerCaps?.find(w=>w.obligationId===b?.id);return c.build({network:t,suiClient:a,account:s,suilendClient:this.utils.suilendClient,obligationOwnerCap:S,obligation:b})}};var Vs=async(r,e)=>{let t=await Ba(r,e),n=await fetch(`${Bu.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(c=>[c.LIQUID_STAKING_INFO.type,c.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:s}};var Ea=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:gn.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,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:gn.TransactionType.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::MintEvent"))},t=(0,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:gn.TransactionType.Other,type:"convert",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(a=>a.type.includes("liquid_staking::MintEvent"))},t=(0,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=(0,Re.normalizeStructTag)(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:gn.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,Re.normalizeStructTag)(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:gn.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};var Eu=require("@mysten/sui/transactions"),Hn=require("@suilend/springsui-sdk");var Nu=_t(require("sort-keys-recursive")),zt=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Nu.default)(this.data))}};var Wa=class r extends zt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("ConvertIntention.build",n,o,a,s,c,m);let b=await Hn.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.inCoinType)),S=await Hn.LstClient.initialize(n,Object.values(s).find(C=>C.type===this.data.outCoinType)),w=new Eu.Transaction;return(0,Hn.convertLstsAndRebalanceAndSendToUser)(b,S,w,o.address,this.data.amount),w}static fromData(t){return console.log("ConvertIntention.fromData",t),new r(t)}};var Wu=require("@mysten/sui/transactions"),La=require("@suilend/sdk"),Xn=require("@suilend/springsui-sdk");var _a=class r extends zt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("ConvertAndDepositIntention.build",n,o,a,s,c,m);let b=await Xn.LstClient.initialize(n,Object.values(s).find(O=>O.type===this.data.inCoinType)),S=await Xn.LstClient.initialize(n,Object.values(s).find(O=>O.type===this.data.outCoinType)),w=new Wu.Transaction,{obligationOwnerCapId:C,didCreate:x}=(0,La.createObligationIfNoneExists)(a,w,c),D=(0,Xn.convertLstsAndRebalance)(b,S,w,o.address,this.data.amount);return a.deposit(D,this.data.outCoinType,C,w),x&&(0,La.sendObligationToUser)(C,o.address,w),w}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new r(t)}};var _u=require("@mysten/sui/transactions"),Lu=require("@suilend/springsui-sdk");var ja=class r extends zt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("StakeIntention.build",n,o,a,s,c,m);let b=await Lu.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.outCoinType)),S=new _u.Transaction;return b.mintAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("StakeIntention.fromData",t),new r(t)}};var ju=require("@mysten/sui/transactions"),Ga=require("@suilend/sdk"),Uu=require("@suilend/springsui-sdk");var Ua=class r extends zt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("StakeAndDepositIntention.build",n,o,a,s,c,m);let b=await Uu.LstClient.initialize(n,Object.values(s).find(D=>D.type===this.data.outCoinType)),S=new ju.Transaction,{obligationOwnerCapId:w,didCreate:C}=(0,Ga.createObligationIfNoneExists)(a,S,c),x=b.mintAmountAndRebalance(S,o.address,this.data.amount);return a.deposit(x,this.data.outCoinType,w,S),C&&(0,Ga.sendObligationToUser)(w,o.address,S),S}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new r(t)}};var Gu=require("@mysten/sui/transactions"),qu=require("@suilend/springsui-sdk");var qa=class r extends zt{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:a,LIQUID_STAKING_INFO_MAP:s,obligationOwnerCap:c,obligation:m}=t;console.log("UnstakeIntention.build",n,o,a,s,c,m);let b=await qu.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.inCoinType)),S=new Gu.Transaction;return b.redeemAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("UnstakeIntention.fromData",t),new r(t)}};var Fa=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 a=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",a);let c=new Ea(t,a).decode();return{txType:Fu.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:a,account:s}=e;this.utils||(this.utils=await Vs(a,s));let c;switch(n){case"stake":c=ja.fromData(o);break;case"stakeAndDeposit":c=Ua.fromData(o);break;case"convert":c=Wa.fromData(o);break;case"convertAndDeposit":c=_a.fromData(o);break;case"unstake":c=qa.fromData(o);break;default:throw new Error("not implemented")}return c.build({network:t,suiClient:a,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 Vu=require("@msafe/sui3-utils");var Hs=require("@msafe/sui3-utils");var Ka=class{constructor(e,t){this.transaction=e;this.simResult=t}transaction;simResult;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:Hs.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Hs.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var Ku=require("@alphafi/stsui-sdk");var $a=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,a={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},c=await new Ku.LST(a).mint(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("MintIntention.fromData",t),new r(t)}};var $u=require("@alphafi/stsui-sdk");var Va=class r extends v{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,a={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},c=await new $u.LST(a).redeem(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("RedeemIntention.fromData",t),new r(t)}};var Ha=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 Ka(t,o).decode();return{txType:Vu.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=$a.fromData(e.intentionData);break;case"redeem":n=Va.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};var hm=require("@msafe/sui3-utils"),gm=require("turbos-clmm-sdk");var Ut=require("@msafe/sui3-utils"),Fe=require("@mysten/bcs"),Ke=require("@mysten/sui/bcs"),Hu=require("turbos-clmm-sdk");var Jt={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Zt={PackageId:"0xdee9"};var Pf=(r,e,t,n)=>{if(r===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(a=>a===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},Xa=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}txb;turbosSdk;config;get transactions(){return this.txb.getData().commands}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.isRemoveLiquidityWithReturnTransaction())return this.decodeRemoveLiquidityWithReturn(e);if(this.isDecreaseLiquidityWithReturnTransaction())return this.decodeDecreaseLiquidityWithReturn(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.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===e:!1)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.$kind==="MoveCall"?`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`===t:!1))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>{if(t.$kind==="MoveCall"){let n=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;return!!e.includes(n)}return!1})}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`)}isDecreaseLiquidityWithReturnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity_with_return_`)}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(`${Jt.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Jt.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isRemoveLiquidityWithReturnTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity_with_return_`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(x=>x.$kind==="MoveCall"),t=0,n=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;console.log(n,"moveCallTarget"),this.swap2Layer.includes(n)&&(t=1);let o=Pf(t,n,this.swap1Layer,this.swap2Layer),a=o.map((x,D)=>{let O=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(D)),G=this.helper.decodeInputU128(this.helper.getInputsIndex(4+D+t)),U=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Hu.BN(G.toString()));return{pool:O,a2b:x,nextTickIndex:U}}),s=o[0]||t===1?e.MoveCall.typeArguments[0]:e.MoveCall.typeArguments[1],c=t===1?e.MoveCall.typeArguments[4]:o[0]?e.MoveCall.typeArguments[1]:e.MoveCall.typeArguments[0],m=this.helper.decodeInputAddress(this.helper.getInputsIndex(6+2*t)),b=this.helper.decodeInputU64(this.helper.getInputsIndex(7+2*t)),S=this.helper.decodeInputBool(this.helper.getInputsIndex(5+2*t)),w=this.helper.decodeInputU64(this.helper.getInputsIndex(2+t)),C=this.helper.decodeInputU64(this.helper.getInputsIndex(3+t));return{txType:Ut.TransactionType.Other,type:"Swap",intentionData:{routes:a,coinTypeA:s,coinTypeB:c,address:m,amountA:S?w:C,amountB:S?C:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:b}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeInputAddress(this.helper.getInputsIndex(12)),n=this.helper.decodeInputU64(this.helper.getInputsIndex(8)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(9)),a=this.helper.decodeInputU32(this.helper.getInputsIndex(4)),s=this.helper.decodeInputBool(this.helper.getInputsIndex(5)),c=this.helper.decodeInputU32(this.helper.getInputsIndex(6)),m=this.helper.decodeInputBool(this.helper.getInputsIndex(7)),b=this.helper.decodeInputU64(this.helper.getInputsIndex(13));return{txType:Ut.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:30,address:t,amountA:n,amountB:o,tickLower:s?-a:a,tickUpper:m?-c:c,deadline:b}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),n=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(4)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(5)),a=this.helper.decodeInputU64(this.helper.getInputsIndex(6)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(9));return{txType:Ut.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:30,address:e,amountA:o,amountB:a,nft:n,deadline:s}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),n=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(3)),a=this.helper.decodeInputU64(this.helper.getInputsIndex(4)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(5)),c=this.helper.decodeInputU64(this.helper.getInputsIndex(6));return{txType:Ut.TransactionType.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:a,amountB:s,slippage:10,address:e,deadline:c}}}decodeDecreaseLiquidityWithReturn(e){console.log(this.helper,"decodeDecreaseLiquidityWithReturn this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeOwnedObjectId(2),o=this.helper.decodeInputU64(3),a=this.helper.decodeInputU64(4),s=this.helper.decodeInputU64(5),c=this.helper.decodeInputU64(6);return{txType:Ut.TransactionType.Other,type:"DecreaseLiquidityWithReturn",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:a,amountB:s,slippage:10,address:e,deadline:c}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),n=this.helper.decodeInputAddress(this.helper.getInputsIndex(5)),o=this.helper.decodeInputU64(this.helper.getInputsIndex(3)),a=this.helper.decodeInputU64(this.helper.getInputsIndex(4)),s=this.helper.decodeInputU64(this.helper.getInputsIndex(6));return{txType:Ut.TransactionType.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:o,collectAmountB:a,nft:t,deadline:s}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2)),n=this.helper.decodeInputAddress(this.helper.getInputsIndex(6)),o=[0,0,0];this.collectRewardHelper.forEach(s=>{let c=s.decodeInputU64(s.getInputsIndex(4)),m=s.decodeInputU64(s.getInputsIndex(5));o[c]=m});let a=this.helper.decodeInputU64(7);return{txType:Ut.TransactionType.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:o,nft:t,deadline:a}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(this.helper.getInputsIndex(0)),t=this.helper.decodeOwnedObjectId(this.helper.getInputsIndex(2));return{txType:Ut.TransactionType.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=30,n=this.decreaseLiquidityHelper.decodeSharedObjectId(this.decreaseLiquidityHelper.getInputsIndex(0)),o=this.decreaseLiquidityHelper.decodeOwnedObjectId(this.decreaseLiquidityHelper.getInputsIndex(2)),a=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(3)),s=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(4)),c=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(5)),m=this.decreaseLiquidityHelper.decodeInputU64(this.decreaseLiquidityHelper.getInputsIndex(6)),b=[0,0,0];this.collectRewardHelper.forEach(C=>{let x=C.decodeInputU64(C.getInputsIndex(4)),D=C.decodeInputU64(C.getInputsIndex(5));b[x]=D});let S=this.collectFeeHelper.decodeInputU64(this.collectFeeHelper.getInputsIndex(3))||0,w=this.collectFeeHelper.decodeInputU64(this.collectFeeHelper.getInputsIndex(4))||0;return{txType:Ut.TransactionType.Other,type:"RemoveLiquidity",intentionData:{pool:n,decreaseLiquidity:a,nft:o,amountA:(s/(100-t)*100).toFixed(0),amountB:(c/(100-t)*100).toFixed(0),slippage:t,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:b,deadline:m}}}decodeRemoveLiquidityWithReturn(e){console.log(this.helper,"decodeRemoveLiquidityWithReturn this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeOwnedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),a=this.decreaseLiquidityHelper.decodeInputU64(4),s=this.decreaseLiquidityHelper.decodeInputU64(5),c=this.decreaseLiquidityHelper.decodeInputU64(6),m=this.collectRewardHelper.map(w=>w.decodeInputU64(5)),b=this.collectFeeHelper.decodeInputU64(3)||0,S=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:Ut.TransactionType.Other,type:"removeLiquidityWithReturn",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:a,amountB:s,slippage:10,address:e,collectAmountA:b,collectAmountB:S,rewardAmounts:m,deadline:c}}}decodePrixClaim(){return{txType:Ut.TransactionType.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:Ut.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:Ut.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:Ut.TransactionType.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>{if(t.$kind==="MoveCall"){let n=`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`;return n!=="0x2::coin::zero"&&n!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero"}return!1});return new Be(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::collect_reward`:!1).map(t=>new Be(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::collect`:!1);return new Be(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${this.config.PackageId}::position_manager::decrease_liquidity`:!1);return new Be(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`:!1);return new Be(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.$kind==="MoveCall"?`${t.MoveCall.package}::${t.MoveCall.module}::${t.MoveCall.function}`===`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`:!1);return new Be(e,this.txb)}},Be=class{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get inputs(){return this.txb.getData().inputs}getInputsIndex(e){return this.moveCall.MoveCall.arguments[e].Input}decodeSharedObjectId(e){return this.inputs[e].Object?.SharedObject?.objectId||this.inputs[e].UnresolvedObject.objectId}decodeOwnedObjectId(e){return this.inputs[e].Object?.ImmOrOwnedObject?.objectId||this.inputs[e].UnresolvedObject.objectId}decodeInputU128(e){return Number(Ke.bcs.u128().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU64(e){return Number(Ke.bcs.u64().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU32(e){return Number(Ke.bcs.u32().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU8(e){return Number(Ke.bcs.u8().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputAddress(e){return Ke.bcs.Address.parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes)))}decodeInputBool(e){return Ke.bcs.bool().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes)))}shortTypeArg(e){return this.moveCall.MoveCall.typeArguments[e]}txArg(e){return this.moveCall.MoveCall.arguments[e]}};var Xu=require("turbos-clmm-sdk");var za=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Xu.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,amountA:s,amountB:c,slippage:m,tickLower:b,tickUpper:S,deadline:w,txb:C}=this.data;return n.pool.addLiquidity({pool:o,slippage:m,address:a,amountA:s,amountB:c,tickLower:b,tickUpper:S,deadline:w,txb:C})}static fromData(t){return new r(t)}};var zu=require("turbos-clmm-sdk");var Qa=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new zu.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,nft:a,txb:s}=this.data;return n.position.burn({pool:o,nft:a,txb:s})}static fromData(t){return new r(t)}};var Qu=require("turbos-clmm-sdk");var Ya=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Qu.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,nft:s,collectAmountA:c,collectAmountB:m,deadline:b,txb:S}=this.data;return n.pool.collectFee({pool:o,address:a,collectAmountA:c,collectAmountB:m,nft:s,deadline:b,txb:S})}static fromData(t){return new r(t)}};var Yu=require("turbos-clmm-sdk");var Ja=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Yu.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,nft:s,rewardAmounts:c,deadline:m,txb:b}=this.data;return n.pool.collectReward({pool:o,address:a,rewardAmounts:c,nft:s,deadline:m,txb:b})}static fromData(t){return new r(t)}};var Ju=require("turbos-clmm-sdk");var Za=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Ju.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{fee:o,address:a,tickLower:s,tickUpper:c,sqrtPrice:m,slippage:b,coinTypeA:S,coinTypeB:w,amountA:C,amountB:x,deadline:D,txb:O}=this.data;return n.pool.createPool({fee:o,amountA:C,amountB:x,address:a,tickLower:s,tickUpper:c,sqrtPrice:m,slippage:b,coinTypeA:S,coinTypeB:w,deadline:D,txb:O})}static fromData(t){return new r(t)}};var Zu=require("turbos-clmm-sdk");var ti=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Zu.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,amountA:s,amountB:c,slippage:m,nft:b,decreaseLiquidity:S,deadline:w,txb:C}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:m,address:a,amountA:s,amountB:c,nft:b,decreaseLiquidity:S,deadline:w,txb:C})}static fromData(t){return new r(t)}};var tm=require("turbos-clmm-sdk");var ei=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new tm.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,amountA:s,amountB:c,slippage:m,nft:b,decreaseLiquidity:S,deadline:w}=this.data,{txb:C,coinA:x,coinB:D}=await n.pool.decreaseLiquidityWithReturn({pool:o,slippage:m,address:a,amountA:s,amountB:c,nft:b,decreaseLiquidity:S,deadline:w});return C.transferObjects([x,D],this.data.address),C}static fromData(t){return new r(t)}};var em=require("turbos-clmm-sdk");var ni=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new em.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{pool:o,address:a,amountA:s,amountB:c,slippage:m,nft:b,deadline:S,txb:w}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:m,address:a,amountA:s,amountB:c,nft:b,deadline:S,txb:w})}static fromData(t){return new r(t)}};var nm=require("@mysten/sui/transactions"),om=require("@mysten/sui/utils");var oi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new nm.Transaction;return n.moveCall({target:`${Jt.PackageId}::claim::claim`,typeArguments:[Jt.turbosCoinType],arguments:[n.object(Jt.Claim),n.object(om.SUI_CLOCK_OBJECT_ID)]}),n}static fromData(t){return new r(t)}};var rm=require("@mysten/sui/transactions");var ri=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new rm.Transaction;return n.moveCall({target:`${Jt.PackageId}::claim::join`,typeArguments:[Jt.turbosCoinType],arguments:[n.object(Jt.Claim)]}),n}static fromData(t){return new r(t)}};var am=require("@mysten/sui/transactions"),im=require("turbos-clmm-sdk");var ai=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new im.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),o=new am.Transaction;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.position.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(t){return new r(t)}};var sm=require("turbos-clmm-sdk");var ii=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new sm.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{txb:o,coinA:a,coinB:s}=await n.pool.removeLiquidityWithReturn({...this.data});return o.transferObjects([a,s],this.data.address),o}static fromData(t){return new r(t)}};var cm=require("turbos-clmm-sdk");var si=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new cm.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient),{routes:o,coinTypeA:a,coinTypeB:s,address:c,amountA:m,amountB:b,slippage:S,amountSpecifiedIsInput:w,deadline:C,txb:x}=this.data;return n.trade.swap({routes:o,coinTypeA:a,coinTypeB:s,address:c,amountA:m,amountB:b,amountSpecifiedIsInput:w,slippage:S,deadline:C,txb:x})}static fromData(t){return new r(t)}};var dm=require("turbos-clmm-sdk");var Xs=require("@mysten/sui/transactions"),zs=require("@mysten/sui/utils");var zn=class{constructor(e){this.turbosSdk=e}turbosSdk;async getCoinsData(e,t,n){let o=[],a,s=!0;for(;s;){let b=await this.turbosSdk.provider.core.listCoins({owner:e,coinType:t,cursor:a??void 0});o.push(...b.objects.map(S=>({coinObjectId:S.objectId,balance:S.balance,coinType:S.type}))),s=b.hasNextPage,a=b.cursor}let c=[],m=0;return o.sort((b,S)=>Number(S.balance)-Number(b.balance)).some(b=>m>=n?!0:(m+=Number(b.balance),c.push(b),!1)),c}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.u64(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[a]=n.splitCoins(o,[n.pure.u64(t)]);return[a,o]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){return(await this.turbosSdk.provider.core.listOwnedObjects({owner:e,type:`${Zt.PackageId}::custodian_v2::AccountCap`})).objects[0]?.objectId}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Zt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var lm=89,pm=1e6,um=async r=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:a,turbosSdk:s}=r,c=new Xs.Transaction,m=new zn(s),b=await m.getCoinsData(a,t,o),[S,w]=m.splitAndMergeCoin(b,o,c);if(!S)throw new Error(`Not enough balance: ${t}`);let C=await m.IsAccountCap(a),x=C?c.object(C):m.createAccount(c),[D,O,G]=c.moveCall({typeArguments:[e,t],target:`${Zt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[c.object(String(n)),c.pure.u64(lm),x,c.pure.u64(o),c.object((0,zs.normalizeSuiObjectId)("0x6")),S]});return w&&c.transferObjects([w],c.pure.address(a)),c.transferObjects([D],c.pure.address(a)),c.transferObjects([O],c.pure.address(a)),C||c.transferObjects([x],c.pure.address(a)),c.setSenderIfNotSet(a),c.setGasBudget(pm),c},mm=async r=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:a,turbosSdk:s}=r,c=new Xs.Transaction,m=new zn(s),b=await m.getCoinsData(a,e,o),[S,w]=m.splitAndMergeCoin(b,o,c);if(!S)throw new Error(`Not enough balance: ${e}`);let C=await m.IsAccountCap(a),x=C?c.object(C):m.createAccount(c),D=m.zero(t,c),[O,G,U]=c.moveCall({typeArguments:[e,t],target:`${Zt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[c.object(String(n)),c.pure.u64(lm),x,c.pure.u64(o),S,D,c.object((0,zs.normalizeSuiObjectId)("0x6"))]});return w&&c.transferObjects([w],c.pure.address(a)),c.transferObjects([O],c.pure.address(a)),c.transferObjects([G],c.pure.address(a)),C||c.transferObjects([x],c.pure.address(a)),c.setSenderIfNotSet(a),c.setGasBudget(pm),c};var ci=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new dm.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient);return await mm({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new r(t)}};var fm=require("turbos-clmm-sdk");var li=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new fm.TurbosSdk(t.network.replace("sui:",""),t.suiGrpcClient);return await um({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new r(t)}};var pi=class{application="turbos";supportSDK="@mysten/sui-v2";async deserialize(e){console.log(e,"input");let t=new gm.TurbosSdk(e.network.replace("sui:",""),e.suiGrpcClient),n=await t.contract.getConfig(),{transaction:o,account:a}=e,c=await new Xa(o,t,n).decode(a.address);return{txType:hm.TransactionType.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{suiGrpcClient:t,account:n,network:o}=e;console.log(e.intentionData,"intentionData");let a;switch(e.txSubType){case"CreatePool":a=Za.fromData(e.intentionData);break;case"AddLiquidity":a=za.fromData(e.intentionData);break;case"IncreaseLiquidity":a=ni.fromData(e.intentionData);break;case"DecreaseLiquidity":a=ti.fromData(e.intentionData);break;case"DecreaseLiquidityWithReturn":a=ei.fromData(e.intentionData);break;case"RemoveLiquidity":a=ai.fromData(e.intentionData);break;case"removeLiquidityWithReturn":a=ii.fromData(e.intentionData);break;case"CollectFee":a=Ya.fromData(e.intentionData);break;case"CollectReward":a=Ja.fromData(e.intentionData);break;case"Burn":a=Qa.fromData(e.intentionData);break;case"Swap":a=si.fromData(e.intentionData);break;case"PrixJoin":a=ri.fromData(e.intentionData);break;case"PrixClaim":a=oi.fromData(e.intentionData);break;case"SwapExactBaseForQuote":a=ci.fromData(e.intentionData);break;case"SwapExactQuoteForBase":a=li.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiGrpcClient:t,account:n,network:o})}};var Sm=require("@msafe/sui3-utils");var ui=require("@msafe/sui3-utils"),di=require("@mysten/bcs"),Ys=require("@mysten/sui/utils");var Rf={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Pt=Rf;function Nf(r){if(r.$kind!=="MoveCall")return null;let{package:e,module:t,function:n}=r.MoveCall;return`${e}::${t}::${n}`}var mi=class{constructor(e){this.txb=e}txb;decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get commands(){return this.txb.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>Nf(t)===e)}isStakeTransaction(){return!!this.getMoveCallCommand(`${Pt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallCommand(`${Pt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallCommand(`${Pt.packageId}::native_pool::burn_ticket`)}decodeSplitAmount(){let e=this.commands.find(o=>o.$kind==="SplitCoins");if(!e||e.$kind!=="SplitCoins")throw new Error("SplitCoins command not found");let t=e.SplitCoins.amounts[0];if(t.$kind!=="Input")throw new Error("SplitCoins amount is not an Input");let n=this.txb.getData().inputs[t.Input];return Number(di.bcs.u64().parse(Uint8Array.from((0,di.fromBase64)(n.Pure.bytes))))}decodeStake(){return{txType:ui.TransactionType.Other,type:"Stake",intentionData:{amount:this.decodeSplitAmount()}}}decodeUnStake(){return{txType:ui.TransactionType.Other,type:"UnStake",intentionData:{amount:this.decodeSplitAmount()}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return{txType:ui.TransactionType.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.package===Pt.packageId);if(!e)throw new Error("MoveCall not found");return new Qs(e,this.txb)}},Qs=class r{constructor(e,t){this.moveCall=e;this.txb=t}moveCall;txb;get moveCallData(){if(this.moveCall.$kind!=="MoveCall")throw new Error("not move call command");return this.moveCall.MoveCall}get inputs(){return this.txb.getData().inputs}getInputIndex(e){let t=this.moveCallData.arguments[e];if(t.$kind!=="Input")throw new Error("not input type");return t.Input}getInputParam(e){return this.inputs[this.getInputIndex(e)]}decodeOwnedObjectId(e){let t=this.getInputParam(e);return r.getOwnedObjectId(t)}static getOwnedObjectId(e){let t=e.Object?.ImmOrOwnedObject?.objectId??e.Object?.Receiving?.objectId??e.UnresolvedObject?.objectId;if(!t)throw new Error(`not object argument: ${JSON.stringify(e)}`);return(0,Ys.normalizeSuiAddress)(t)}};var ym=require("@mysten/sui/transactions");var fi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new ym.Transaction,{ticketId:o}=this.data;return n.moveCall({target:`${Pt.packageId}::native_pool::burn_ticket`,arguments:[n.object(Pt.poolObjectId),n.object(Pt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new r(t)}};var bm=require("@mysten/sui/transactions");var hi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new bm.Transaction,{amount:o}=this.data,[a]=n.splitCoins(n.gas,[o]);return n.moveCall({target:`${Pt.packageId}::native_pool::stake`,arguments:[n.object(Pt.poolObjectId),n.object(Pt.metadataObjectId),n.object(Pt.systemStateObjectId),a]}),n}static fromData(t){return new r(t)}};var Tm=require("@mysten/sui/transactions");var gi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=new Tm.Transaction,{amount:o}=this.data,a=await t.suiGrpcClient.listCoins({owner:t.account.address,coinType:Pt.certType,limit:100});if(a.objects.length===0)throw new Error("No cert coins found");let[s,...c]=a.objects,m=n.object(s.objectId);c.length&&n.mergeCoins(m,c.map(S=>n.object(S.objectId)));let[b]=n.splitCoins(n.object(s.objectId),[o]);return n.moveCall({target:`${Pt.packageId}::native_pool::unstake`,arguments:[n.object(Pt.poolObjectId),n.object(Pt.metadataObjectId),n.object(Pt.systemStateObjectId),b]}),n}static fromData(t){return new r(t)}};var yi=class{application="volo";supportSDK="@mysten/sui-v2";async deserialize(e){let n=new mi(e.transaction).decode();return{txType:Sm.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(e){let{suiGrpcClient:t,account:n,network:o}=e,a;switch(e.txSubType){case"Stake":a=hi.fromData(e.intentionData);break;case"UnStake":a=gi.fromData(e.intentionData);break;case"ClaimTicket":a=fi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiGrpcClient:t,account:n,network:o})}};var Bm=require("@msafe/sui3-utils");var Js=require("@cetusprotocol/common-sdk"),fe=require("@msafe/sui3-utils"),yn=require("@mysten/bcs"),bn=require("@mysten/sui/bcs");var bi=class{constructor(e,t){this.transaction=e;this.appContext=t}transaction;appContext;async 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();if(this.isAggregator7KSwapTx())return this.decodeAggregator7KSwapTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:fe.TransactionType.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number((0,Js.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,Js.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:fe.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:fe.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:fe.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:fe.TransactionType.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:fe.TransactionType.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:fe.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}async decodeAggregator7KSwapTx(){let{appContext:e}=this;return console.log("appContext",e),{txType:fe.TransactionType.Other,type:"Aggregator7KSwap",intentionData:{tokenIn:e.txParams.tokenIn,tokenOut:e.txParams.tokenOut,amountIn:String(e.txParams.amountIn),maxSlippage:String(e.txParams.maxSlippage)}}}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")}isAggregator7KSwapTx(){return!!this.commands.find(e=>e.$kind==="MoveCall"&&e.MoveCall.function.toLowerCase().includes("settle"))}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(bn.bcs.u32().parse(Uint8Array.from((0,yn.fromBase64)(this.inputs[e].Pure.bytes))))}getU64(e){return bn.bcs.u64().parse(Uint8Array.from((0,yn.fromBase64)(this.inputs[e].Pure.bytes)))}getU128(e){return bn.bcs.u128().parse(Uint8Array.from((0,yn.fromBase64)(this.inputs[e].Pure.bytes)))}getBoolean(e){return bn.bcs.bool().parse(Uint8Array.from((0,yn.fromBase64)(this.inputs[e].Pure.bytes)))}getAddress(e){return bn.bcs.Address.parse(Uint8Array.from((0,yn.fromBase64)(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};var km=require("@msafe/sui3-utils");var Ti=require("@bluefin-exchange/bluefin7k-aggregator-sdk"),se=require("@firefly-exchange/library-sui"),xm=require("turbos-clmm-sdk");var Im=require("@firefly-exchange/library-sui"),Cm=require("@firefly-exchange/library-sui/spot"),wm={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},ge=(r,e)=>{if(r!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new Im.SuiClient({url:wm.rpc});return new Cm.OnChainCalls(t,wm.objects,{address:e.address,isUIWallet:!1})};var Et=class{static async OpenPosition(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool),s=this.prototype.buildLiqInput(a,{...e,slippage:0});return await o.openPositionWithFixedAmount(a,e.lowerTick,e.upperTick,s,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool),s=this.prototype.buildLiqInput(a,e);return await o.provideLiquidityWithFixedAmount(a,e.position,s,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(a,e.position,{liquidityAmount:new se.BN(e.liquidity),tokenMaxA:new se.BN(e.maxAmountTokenA),tokenMaxB:new se.BN(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool);return await o.closePosition(a,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool);return await o.collectRewards(a,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool);return await o.collectFee(a,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let o=ge(n,t),a=await o.queryChain.getPool(e.pool);return console.log(e.position),await o.collectFeeAndRewards(a,e.position,{returnTx:!0,sender:t.address})}static async aggregator7KSwap(e,t,n){let o=ge(n,t),a=await(0,Ti.getQuote)({tokenIn:e.tokenIn.address,tokenOut:e.tokenOut.address,amountIn:new xm.Decimal(e.amountIn).mul(10**e.tokenIn.decimals).toString()}),s=await(0,Ti.buildTx)({quoteResponse:a,accountAddress:t.address,slippage:e.maxSlippage,commission:{partner:"0x956d6ea2da156a037952964badc51f997cc5581c86a0e05f74049e6effab9347",commissionBps:0}});return s.tx.setSender(t.address),s.tx}buildLiqInput(e,t){return{...se.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new se.BN(t.tokenAmount),t.isTokenAFixed,!0,0,new se.BN(e.current_sqrt_price)),tokenMaxA:new se.BN(t.maxAmountTokenA),tokenMaxB:new se.BN(t.maxAmountTokenB)}}};var Si=class r extends v{constructor(t){super(t);this.data=t}data;txType=km.TransactionType.Other;txSubType="Aggregator7KSwap";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.aggregator7KSwap(this.data,n,o)}static fromData(t){return new r(t)}};var Dm=require("@msafe/sui3-utils");var wi=class r extends v{constructor(t){super(t);this.data=t}data;txType=Dm.TransactionType.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.closePosition(this.data,n,o)}static fromData(t){return new r(t)}};var vm=require("@msafe/sui3-utils");var Ii=class r extends v{constructor(t){super(t);this.data=t}data;txType=vm.TransactionType.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.collectFee(this.data,n,o)}static fromData(t){return new r(t)}};var Am=require("@msafe/sui3-utils");var Ci=class r extends v{constructor(t){super(t);this.data=t}data;txType=Am.TransactionType.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.collectRewards(this.data,n,o)}static fromData(t){return new r(t)}};var Mm=require("@msafe/sui3-utils");var xi=class r extends v{constructor(t){super(t);this.data=t}data;txType=Mm.TransactionType.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new r(t)}};var Om=require("@msafe/sui3-utils");var ki=class r extends v{constructor(t){super(t);this.data=t}data;txType=Om.TransactionType.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.OpenPosition(this.data,n,o)}static fromData(t){return new r(t)}};var Pm=require("@msafe/sui3-utils");var Di=class r extends v{constructor(t){super(t);this.data=t}data;txType=Pm.TransactionType.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.provideLiquidity(this.data,n,o)}static fromData(t){return new r(t)}};var Rm=require("@msafe/sui3-utils");var vi=class r extends v{constructor(t){super(t);this.data=t}data;txType=Rm.TransactionType.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Et.removeLiquidity(this.data,n,o)}static fromData(t){return new r(t)}};var Ai=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t,appContext:n}=e,a=await new bi(t,n).decode();return{txType:Bm.TransactionType.Other,txSubType:a.type,intentionData:{appContext:e.appContext,...a.intentionData}}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let a;switch(e.txSubType){case"OpenPosition":a=ki.fromData(e.intentionData);break;case"ProvideLiquidity":a=Di.fromData(e.intentionData);break;case"RemoveLiquidity":a=vi.fromData(e.intentionData);break;case"ClosePosition":a=wi.fromData(e.intentionData);break;case"CollectFee":a=Ii.fromData(e.intentionData);break;case"CollectRewards":a=Ci.fromData(e.intentionData);break;case"CollectRewardsAndFee":a=xi.fromData(e.intentionData);break;case"Aggregator7KSwap":a=Si.fromData(e.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:t,account:n,network:o})}};var Id=require("@msafe/sui3-utils");var Ym=require("@mysten/sui/transactions");var Tn=require("@mmt-finance/clmm-sui-sdk"),jm=_t(require("bignumber.js")),B=_t(Em());var Ef="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Q=r=>r!=="0x2::sui::SUI"?r:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Wf=async({suiClient:r,address:e,type:t})=>{let n,o=[],a=0;do{try{let s=await r.listCoins({owner:e,coinType:t,cursor:n??void 0,limit:50});o=o.concat(s.objects.map(c=>({coinType:c.type,coinObjectId:c.objectId,version:c.version,digest:c.digest,balance:c.balance,previousTransaction:"0x0"}))),n=s.cursor,(!s.hasNextPage||a===8)&&(n=null)}catch(s){console.log(s),n=null}a++}while(n!==null);return o},_f=(r,e)=>{let t=[],n=BigInt(0);for(let o of e)n<r&&!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>=r)return t;throw new Error("Insufficient balance")},Lf=(r,e,t,n)=>{if(r===Ef){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=_f(t,e);o.length>1&&n.mergeCoins(n.object(o[0]),o.slice(1).map(s=>n.object(s)));let[a]=n.splitCoins(n.object(o[0]),[n.pure.u64(t)]);return a}};async function Wm(r,e,t,n,o){let a=await Wf({suiClient:r.rpcClient,address:e,type:t});return Lf(Q(t),a.map(c=>({balance:BigInt(c.balance),objectId:c.coinObjectId})),n,o)}var $e=(r,e,t,n,o)=>{let a={poolId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,tickSpacing:n.tickSpacing,isStable:n.isStable};n?.rewarders&&n?.rewarders.length>0&&r.Pool.collectAllRewards({txb:o,pool:a,rewarders:n.rewarders.map(s=>({coin_type:s.coinType,flow_rate:s.flowRate,reward_amount:s.rewardAmount,rewards_allocated:s.rewardsAllocated,hasEnded:s.hasEnded})),positionId:t.objectId,transferToAddress:e}),r.Pool.collectFee({txb:o,pool:a,positionId:t.objectId,transferToAddress:e})};async function _m({sdk:r,address:e,positionId:t,pool:n,txb:o,targetCoinType:a,slippage:s}){let c={poolId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,tickSpacing:n.tickSpacing,isStable:n.isStable},m=n.rewarders.map(S=>S.coinType),b=await r.Pool.getAllPools();return m.length>0&&(console.log("claimRewardsAsTargetCoin input",{pool:c,positionId:t,rewarderCoinTypes:m,targetCoinType:a,slippage:s,toAddress:e}),await r.Pool.claimRewardsAs({txb:o,pool:c,positionId:t,rewarderCoinTypes:m,targetCoinType:a,slippage:s,toAddress:e,pools:b})),await r.Pool.claimFeeAs({txb:o,pool:c,positionId:t,targetCoinType:a,slippage:s,toAddress:e,pools:b}),o}function W(r,e,t){let n=r.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function jf(r){let e;return(r&1)!==0?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),(r&2)!==0&&(e=W(e.mul(new B.default("79236085330515764027303304731")),96,256)),(r&4)!==0&&(e=W(e.mul(new B.default("79244008939048815603706035061")),96,256)),(r&8)!==0&&(e=W(e.mul(new B.default("79259858533276714757314932305")),96,256)),(r&16)!==0&&(e=W(e.mul(new B.default("79291567232598584799939703904")),96,256)),(r&32)!==0&&(e=W(e.mul(new B.default("79355022692464371645785046466")),96,256)),(r&64)!==0&&(e=W(e.mul(new B.default("79482085999252804386437311141")),96,256)),(r&128)!==0&&(e=W(e.mul(new B.default("79736823300114093921829183326")),96,256)),(r&256)!==0&&(e=W(e.mul(new B.default("80248749790819932309965073892")),96,256)),(r&512)!==0&&(e=W(e.mul(new B.default("81282483887344747381513967011")),96,256)),(r&1024)!==0&&(e=W(e.mul(new B.default("83390072131320151908154831281")),96,256)),(r&2048)!==0&&(e=W(e.mul(new B.default("87770609709833776024991924138")),96,256)),(r&4096)!==0&&(e=W(e.mul(new B.default("97234110755111693312479820773")),96,256)),(r&8192)!==0&&(e=W(e.mul(new B.default("119332217159966728226237229890")),96,256)),(r&16384)!==0&&(e=W(e.mul(new B.default("179736315981702064433883588727")),96,256)),(r&32768)!==0&&(e=W(e.mul(new B.default("407748233172238350107850275304")),96,256)),(r&65536)!==0&&(e=W(e.mul(new B.default("2098478828474011932436660412517")),96,256)),(r&131072)!==0&&(e=W(e.mul(new B.default("55581415166113811149459800483533")),96,256)),(r&262144)!==0&&(e=W(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),W(e,32,256)}function Uf(r){let e=Math.abs(r),t;return(e&1)!==0?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),(e&2)!==0&&(t=W(t.mul(new B.default("18444899583751176498")),64,256)),(e&4)!==0&&(t=W(t.mul(new B.default("18443055278223354162")),64,256)),(e&8)!==0&&(t=W(t.mul(new B.default("18439367220385604838")),64,256)),(e&16)!==0&&(t=W(t.mul(new B.default("18431993317065449817")),64,256)),(e&32)!==0&&(t=W(t.mul(new B.default("18417254355718160513")),64,256)),(e&64)!==0&&(t=W(t.mul(new B.default("18387811781193591352")),64,256)),(e&128)!==0&&(t=W(t.mul(new B.default("18329067761203520168")),64,256)),(e&256)!==0&&(t=W(t.mul(new B.default("18212142134806087854")),64,256)),(e&512)!==0&&(t=W(t.mul(new B.default("17980523815641551639")),64,256)),(e&1024)!==0&&(t=W(t.mul(new B.default("17526086738831147013")),64,256)),(e&2048)!==0&&(t=W(t.mul(new B.default("16651378430235024244")),64,256)),(e&4096)!==0&&(t=W(t.mul(new B.default("15030750278693429944")),64,256)),(e&8192)!==0&&(t=W(t.mul(new B.default("12247334978882834399")),64,256)),(e&16384)!==0&&(t=W(t.mul(new B.default("8131365268884726200")),64,256)),(e&32768)!==0&&(t=W(t.mul(new B.default("3584323654723342297")),64,256)),(e&65536)!==0&&(t=W(t.mul(new B.default("696457651847595233")),64,256)),(e&131072)!==0&&(t=W(t.mul(new B.default("26294789957452057")),64,256)),(e&262144)!==0&&(t=W(t.mul(new B.default("37481735321082")),64,256)),t}var Lm=(r,e,t)=>{let n=Tn.TickMath.convertI32ToSigned(t?r+r%(e??1):r-r%(e??1));return n>0?new B.default(jf(n)):new B.default(Uf(n))};function Um(r,e){if(!/^(\d+)(\.\d+)?$/.test(r))return BigInt(0);let[t,n=""]=r.split("."),o=(n+"0".repeat(e)).slice(0,e),s=(t+o).replace(/^0+/,"")||"0";return BigInt(s)}async function ce({address:r,coinType:e,coinAmount:t,coinDecimals:n,tx:o,mmt:a}){let s=Um(t,n),c;return Number(t)?c=await Wm(a,r,Q(e),s,o):[c]=o.moveCall({target:"0x2::coin::zero",typeArguments:[e],arguments:[]}),c}function Gm({mmt:r,tx:e,poolModel:t,selectedLowTick:n,selectedHighTick:o}){let a=Lm(Tn.TickMath.convertI32ToSigned(n),t.tickSpacing),s=Lm(Tn.TickMath.convertI32ToSigned(o),t.tickSpacing);return r.Position.openPosition({txb:e,pool:t,lowerTickSqrtPrice:a.toString(),upperTickSqrtPrice:s.toString()})}var Gf=(r,e)=>{let n=1e4-Math.floor(e*100);return r*BigInt(n)/BigInt(1e4)};function Mi(r,e,t){let n=Um(r,e);return Number(r)===0?BigInt(0):Gf(n,t)}async function Ve({poolId:r,currentSqrtPrice:e,tokenX:t,tokenY:n,slippagePercentage:o,isTokenX:a,suiClient:s}){let{object:c}=await s.getObject({objectId:r,include:{json:!0}}),m=c?.json?.sqrt_price??e,b=Tn.TickMath.sqrtPriceX64ToPrice(new B.default(m?.toString()),t.decimals,n.decimals),S=a?(100-o)/100:(100+o)/100,w=Tn.TickMath.priceToSqrtPriceX64(b.mul(S),t.decimals,n.decimals);return BigInt(w.toString())}var qm=async(r,e,t,n,o,a,s,c,m,b)=>{let S=await ce({mmt:r,address:t,coinType:a.tokenX.coinType,coinAmount:n,coinDecimals:a.tokenX.decimals,tx:e}),w=await ce({mmt:r,address:t,coinType:a.tokenY.coinType,coinAmount:o,coinDecimals:a.tokenY.decimals,tx:e}),C={poolId:s,tokenXType:a.tokenXType,tokenYType:a.tokenYType,tickSpacing:a.tickSpacing,isStable:a.isStable},x=Gm({mmt:r,tx:e,poolModel:C,selectedLowTick:c,selectedHighTick:m}),D=Mi(n,a.tokenX.decimals,b),O=Mi(o,a.tokenY.decimals,b);await r.Pool.addLiquidity({txb:e,pool:C,position:x,coinX:S,coinY:w,minAmountX:D,minAmountY:O,transferToAddress:t,useMvr:!0}),e.transferObjects([x],e.pure.address(t))},Fm=async(r,e,t,n,o,a,s,c,m,b,S)=>{try{let w=await ce({mmt:r,address:n,coinType:a?s.tokenX.coinType:s.tokenY.coinType,coinAmount:o,coinDecimals:a?s.tokenX.decimals:s.tokenY.decimals,tx:e}),C={poolId:s.poolId,tokenXType:Q(s.tokenX.coinType),tokenYType:Q(s.tokenY.coinType),tickSpacing:s.tickSpacing,isStable:s.isStable},x=Gm({mmt:r,tx:e,poolModel:C,selectedLowTick:c,selectedHighTick:m}),D=await Ve({suiClient:t,poolId:s.poolId,currentSqrtPrice:s.currentSqrtPrice,tokenX:s.tokenX,tokenY:s.tokenY,slippagePercentage:b,isTokenX:a});await r.Pool.zapInLiquidity({txb:e,pool:C,position:x,inputCoin:w,isXtoY:a,limitSqrtPrice:D,slippagePercentage:S,transferToAddress:n,useMvr:!0}),e.transferObjects([x],e.pure.address(n))}catch(w){console.error(w)}},Km=async(r,e,t,n,o,a,s,c)=>{let m=await ce({mmt:r,address:t,coinType:a.tokenX.coinType,coinAmount:n,coinDecimals:a.tokenX.decimals,tx:e}),b=await ce({mmt:r,address:t,coinType:a.tokenY.coinType,coinAmount:o,coinDecimals:a.tokenY.decimals,tx:e}),S={poolId:a.poolId,tokenXType:a.tokenXType,tokenYType:a.tokenYType,tickSpacing:a.tickSpacing,isStable:a.isStable},w=Mi(n,a.tokenX.decimals,c),C=Mi(o,a.tokenY.decimals,c);await r.Pool.addLiquidity({txb:e,pool:S,position:s,coinX:m,coinY:b,minAmountX:w,minAmountY:C,transferToAddress:t})},$m=async(r,e,t,n,o,a,s,c,m)=>{try{let b=await ce({mmt:r,address:t,coinType:o?a.tokenX.coinType:a.tokenY.coinType,coinAmount:n,coinDecimals:o?a.tokenX.decimals:a.tokenY.decimals,tx:e}),S={poolId:a.poolId,tokenXType:a.tokenX.coinType,tokenYType:a.tokenY.coinType,tickSpacing:a.tickSpacing,isStable:a.isStable},w=await Ve({suiClient:r.rpcClient,poolId:a.poolId,currentSqrtPrice:a.currentSqrtPrice,tokenX:a.tokenX,tokenY:a.tokenY,slippagePercentage:c,isTokenX:o});await r.Pool.zapInLiquidity({txb:e,pool:S,position:s,inputCoin:b,isXtoY:o,limitSqrtPrice:w,slippagePercentage:m,transferToAddress:t})}catch(b){throw console.error(b),b}},Vm=(r,e)=>BigInt(e===100?r:new jm.default(r).multipliedBy(e/100).toFixed(0)),Hm=async(r,e,t,n,o,a)=>{let s=Vm(t.liquidity,o),c=n.tokenX.coinType,m=n.tokenY.coinType,b={poolId:n.poolId,tokenXType:c,tokenYType:m,tickSpacing:n.tickSpacing,isStable:n.isStable};await r.Pool.removeLiquidity({txb:a,pool:b,positionId:t.objectId,liquidity:s,minAmountX:BigInt(0),minAmountY:BigInt(0),transferToAddress:e}),$e(r,e,t,n,a),o===100&&r.Position.closePosition({txb:a,positionId:t.objectId})},Xm=async({sdk:r,address:e,position:t,pool:n,withdrawPercentage:o,txb:a,targetCoinType:s,slippage:c})=>{let m=Vm(t.liquidity,o),b=Q(n.tokenX.coinType),S=Q(n.tokenY.coinType),w=Q(s)===S,C={poolId:n.poolId,tokenXType:b,tokenYType:S,tickSpacing:n.tickSpacing,isStable:n.isStable},x=r.Pool.removeLiquidity({txb:a,pool:C,positionId:t.objectId,liquidity:m,minAmountX:BigInt(0),minAmountY:BigInt(0)}),D=x?.removeLpCoinA,O=x?.removeLpCoinB;if(!D||!O)throw new Error("Remove liquidity Failed: empty remove result");let G=await Ve({suiClient:r.rpcClient,poolId:n.poolId,currentSqrtPrice:n.currentSqrtPrice,tokenX:n.tokenX,tokenY:n.tokenY,isTokenX:w,slippagePercentage:c}),U=w?D:O,K=a.moveCall({target:"0x2::coin::value",arguments:[U],typeArguments:[w?b:S]});a.transferObjects([w?O:D],e),r.Pool.swap({txb:a,transferToAddress:e,pool:C,limitSqrtPrice:G,amount:K,inputCoin:U,isXtoY:w}),$e(r,e,t,n,a),o===100&&r.Position.closePosition({txb:a,positionId:t.objectId})};var zm=require("@mmt-finance/clmm-sui-sdk"),Qm=require("@mmt-finance/ve-sdk-v1");function Rt(r){return new zm.MmtSDK({network:"mainnet",client:r})}function Qt(r){return new Qm.VeMMT(r,"mainnet")}var Oi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{address:a,amountA:s,amountB:c,pool:m,selectedLowTick:b,selectedHighTick:S,slippage:w}=o,C=new Ym.Transaction;return await qm(n,C,a,s,c,m,m.poolId,b,S,w),C}static fromData(t){return new r(t)}};var Jm=require("@mysten/sui/transactions");var Pi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{address:a,amount:s,isTokenX:c,pool:m,selectedLowTick:b,selectedHighTick:S,swapSlippage:w,addLiquiditySlippage:C}=o,x=new Jm.Transaction;return await Fm(n,x,t.suiGrpcClient,a,s,c,m,b,S,w,C),x}static fromData(t){return new r(t)}};var ad=require("@mysten/sui/transactions");var Sn="0x35169bc93e1fddfcf3a82a9eae726d349689ed59e4b065369af8789fe59f8608::mmt::MMT";var Qn=async r=>{let e=await r.getSyncEpochInfo();if(!e)throw new Error("Failed to sync epoch");return e},Zm=async(r,e,t,n,o,a,s,c)=>{let m=Number(n);if(!n||Number.isNaN(m)||m<=0)throw new Error(`Bond Failed: Invalid amount: ${n}. Amount must be greater than 0`);if(!a&&!s)throw new Error("Bond Failed: Failed to calculate unbond date");if(typeof s!="number"&&!a)throw new Error("Bond Failed: Invalid unbond date");let b=await ce({mmt:r,tx:c,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals});if(!b)throw new Error(`Bond Failed: Failed to get coin object for ${t.coinType}, amount: ${n}`);let S=await Qn(e);await e.syncOrAdvanceEpoch(c,S.currentEpoch,S.syncedEpoch);let w=c.getData().commands.length;a?await e.createMaxBond(c,b,o):await e.createBond(c,b,BigInt(s),o);let x=c.getData().commands.length;if(x===0)throw new Error(`Bond Failed: Transaction has no commands. enableAutoMaxBond: ${a}, unbondAt: ${s}, amount: ${n}`);if(x===w)throw new Error(`Bond Failed: No new commands were added by bond operation. Commands before: ${w}, after: ${x}`)},td=async(r,e,t,n,o,a,s,c)=>{let m=await Qn(r);if(await r.syncOrAdvanceEpoch(c,m.currentEpoch,m.syncedEpoch),await r.claimReward(c,t,e),o)a||await r.setNormal(c,t);else if(a)await r.setMaxBond(c,t);else{if(typeof s!="number")throw new Error("Extend Failed: Failed to calculate unbond date");if(s<n)throw new Error("Extend Failed: New duration cannot be less than current duration");await r.extend(c,t,s)}},ed=async(r,e,t,n,o)=>{let a=await Qn(r);await r.syncOrAdvanceEpoch(o,a.currentEpoch,a.syncedEpoch),await r.claimReward(o,t,e),await n.reduce(async(s,c)=>{await s,await r.claimReward(o,c,e),await r.merge(o,t,c)},Promise.resolve())},nd=async(r,e,t,n)=>{let o=await Qn(r);await r.syncOrAdvanceEpoch(n,o.currentEpoch,o.syncedEpoch),await r.claimReward(n,t,e),await r.unbond(n,t,e)},od=async(r,e,t,n)=>{if(t.length>0&&t.some(o=>o.userRewardAmount>0)){let o=await Qn(r);await r.syncOrAdvanceEpoch(n,o.currentEpoch,o.syncedEpoch),await t.reduce(async(a,s)=>{await a,s.userRewardAmount>0&&await r.claimReward(n,s.veId,e)},Promise.resolve())}},rd=async(r,e,t,n,o,a,s,c,m)=>{let b=Q(a),S=[];for(let K of n)if(K.userRewardAmount>0){let V=await e.buildClaimRewardCoin(o,K.veId);S.push(V)}let w=[];for(let K of S)Array.isArray(K)?w.push(...K):w.push(K);if(w.length===0)return;if(a===Q(Sn)){o.transferObjects(w,o.pure.address(t));return}let C=c?.[a]?.[Sn];if(!C||C.length===0)throw new Error(`No swap route found from ${Sn} to ${a}`);let[x,...D]=w;D.length>0&&o.mergeCoins(x,D);let O=x,G=o.moveCall({target:"0x2::coin::value",arguments:[O],typeArguments:[Sn]}),U=Q(Sn);for(let K=0;K<C.length;K++){let V=C[K],E=m.find(X=>X.poolId===V);if(!E)throw new Error(`Pool ${V} not found`);let Wt=Q(E.tokenXType||E.tokenX?.coinType||"")===U,le={poolId:E.poolId,tokenXType:E.tokenXType||E.tokenX?.coinType||"",tokenYType:E.tokenYType||E.tokenY?.coinType||"",tickSpacing:E.tickSpacing,isStable:E.isStable},Yn=await Ve({suiClient:r.rpcClient,poolId:E.poolId,currentSqrtPrice:E.currentSqrtPrice,tokenX:E.tokenX,tokenY:E.tokenY,slippagePercentage:s,isTokenX:Wt}),{outputCoin:wn,leftoverCoin:He}=r.Pool.swap({txb:o,pool:le,amount:G,inputCoin:O,isXtoY:Wt,limitSqrtPrice:Yn})||{};if(!wn||!He)throw new Error(`Swap Failed: empty swap result for pool ${V}`);if(o.transferObjects([He],o.pure.address(t)),O=wn,U=Wt?Q(E.tokenYType||E.tokenY?.coinType||""):Q(E.tokenXType||E.tokenX?.coinType||""),U===a){o.transferObjects([O],o.pure.address(t));return}G=o.moveCall({target:"0x2::coin::value",arguments:[O],typeArguments:[U]})}o.transferObjects([O],o.pure.address(t))};var Ri=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),o=Qt(t.suiGrpcClient),{params:a}=this.data,{address:s,positions:c,pools:m,veMMTs:b}=a,S=new ad.Transaction;for(let w of c){let C=m.find(x=>x.poolId===w.poolId);C&&$e(n,s,w,C,S)}return await od(o,s,b,S),S}static fromData(t){return new r(t)}};var id=require("@mysten/sui/transactions");var Bi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),o=Qt(t.suiGrpcClient),{params:a}=this.data,{claimVeMMTParams:s}=a,{address:c,veMMTs:m,targetCoinType:b,slippage:S,claimRoutes:w,pools:C}=s,x=new id.Transaction;return await Promise.all(a.claimParams.map(D=>_m({...D,sdk:n,txb:x}))),await rd(n,o,c,m,x,b,S,w,C),x}static fromData(t){return new r(t)}};var sd=require("@mysten/sui/transactions");var Ni=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{address:a,position:s,pool:c}=o,m=new sd.Transaction;return $e(n,a,s,c,m),m}static fromData(t){return new r(t)}};var cd=require("@mysten/sui/transactions");var Ei=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{address:a,amountA:s,amountB:c,pool:m,positionObjectId:b,slippage:S}=o,w=new cd.Transaction;return await Km(n,w,a,s,c,m,b,S),w}static fromData(t){return new r(t)}};var ld=require("@mysten/sui/transactions");var Wi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{address:a,amount:s,isTokenX:c,pool:m,positionObjectId:b,swapSlippage:S,addLiquiditySlippage:w}=o,C=new ld.Transaction;return await $m(n,C,a,s,c,m,b,S,w),C}static fromData(t){return new r(t)}};var pd=require("@mysten/sui/transactions");var _i=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),{params:o}=this.data,{pool:a,position:s,address:c,withdrawPercentage:m,zapOutOn:b,targetCoinType:S,slippage:w}=o,C=new pd.Transaction;return b?await Xm({sdk:n,address:c,position:s,pool:a,withdrawPercentage:m,txb:C,targetCoinType:S,slippage:w}):await Hm(n,c,s,a,m,C),C}static fromData(t){return new r(t)}};var ec=require("@mysten/sui/transactions"),nc=require("@suilend/springsui-sdk"),tc={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},ud=async(r,e,t)=>{let n=await nc.LstClient.initialize(r,r,tc),o=new ec.Transaction,[a]=o.splitCoins(o.gas,[BigInt(t)]),s=n.mint(o,a);return o.transferObjects([s],e),o},md=async(r,e,t)=>{let n=await nc.LstClient.initialize(r,r,tc),o=await r.listCoins({owner:e,coinType:tc.type,limit:1e3});if(o.objects.length===0)throw new Error("No lst coins found");let a=new ec.Transaction,s=o.objects[0];o.objects.length>1&&a.mergeCoins(s.objectId,o.objects.slice(1).map(b=>b.objectId));let[c]=a.splitCoins(s.objectId,[BigInt(t)]),m=n.redeem(a,c);return a.transferObjects([m],e),a};var Li=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:a}=n;return ud(t.suiGrpcClient,o,a)}static fromData(t){return new r(t)}};var yd=require("@mysten/sui/transactions");var fd=require("@mmt-finance/clmm-sui-sdk");function dd(r){return Array.isArray(r)&&(r.length===0||typeof r[0]=="string")}function qf(r){return typeof r=="object"&&r!==null&&"coinType"in r&&"decimals"in r}function Ff(r,e){if(!/^\d+$/.test(r))return r;if(e<=0)return r.replace(/^0+/,"")||"0";let t=BigInt(r),n=10n**BigInt(e),o=t/n,a=t%n;if(a===0n)return o.toString();let s=a.toString().padStart(e,"0").replace(/0+$/,"");return`${o}.${s}`}function Kf(r){return{poolSource:"mmt-v3",poolId:r.poolId,tokenXType:r.tokenXType,tokenYType:r.tokenYType,tickSpacing:r.tickSpacing,lpFeesPercent:r.lpFeesPercent,feeRate:Number(r.lpFeesPercent)||0,protocolFeesPercent:r.protocolFeesPercent,isStable:r.isStable,currentSqrtPrice:r.currentSqrtPrice,currentTickIndex:r.currentTickIndex,liquidity:r.liquidity,liquidityHM:r.liquidityHM,tokenXReserve:r.tokenXReserve,tokenYReserve:r.tokenYReserve,tvl:r.tvl,apy:r.apy,volume24h:r.volume24h,fees24h:r.fees24h,timestamp:r.timestamp,rewarders:(r.rewarders||[]).map(e=>({coinType:e.coin_type,flowRate:e.flow_rate,hasEnded:e.hasEnded,rewardAmount:e.reward_amount,rewardsAllocated:e.rewards_allocated})),tokenX:r.tokenX,tokenY:r.tokenY,aprBreakdown:{total:r.aprBreakdown?.total??r.apy??"0",fee:r.aprBreakdown?.fee??"0",rewards:(r.aprBreakdown?.rewards||[]).map(e=>({coinType:e.coinType,apr:e.rewarderApr?.toString?.()??String(e.rewarderApr??"0"),amountPerDay:Number(e.amountPerDay??0)}))}}}function $f(r,e){let t=Q(e);for(let n of r){if(Q(n.tokenX?.coinType||"")===t)return n.tokenX;if(Q(n.tokenY?.coinType||"")===t)return n.tokenY}}async function hd(r,e){if(e.mode==="aggregator")throw new Error("Swap Failed: aggregator mode is not supported in MSafe rebuild path yet");let t=e.address,n=e.slippage??e.slippagePct;if(typeof n!="number")throw new Error("Swap Failed: missing slippage");if(!dd(e.route)&&qf(e.tokenIn))return{route:e.route,tokenIn:e.tokenIn,amountIn:e.amountIn,address:t,slippage:n};if(!dd(e.route))throw new Error("Swap Failed: route must be NormalizedPool[] or poolId string[]");if(typeof e.tokenIn!="string")throw new Error("Swap Failed: tokenIn must be a coinType string when route is poolId[]");if(e.route.length===0)throw new Error("Swap Failed: empty route");let a=(await Promise.all(e.route.map(m=>r.Pool.getPool(m)))).map(Kf),s=$f(a,e.tokenIn);if(!s){let m=await r.Pool.getToken(e.tokenIn);s={coinType:m.coinType,tokenName:m.name,ticker:m.ticker,iconUrl:m.iconUrl,decimals:m.decimals,price:m.price,description:m.description,isVerified:m.isVerified}}let c=Ff(e.amountIn,s.decimals);return{route:a,tokenIn:s,amountIn:c,address:t,slippage:n}}var gd=async(r,e,t,n,o,a,s)=>{let c=await ce({mmt:r,tx:a,address:o,coinType:t.coinType,coinAmount:n,coinDecimals:t.decimals}),m=a.moveCall({target:"0x2::coin::value",typeArguments:[t.coinType],arguments:[c]}),b=t.coinType;for(let S=0;S<e.length;S+=1){let w=e[S],{poolId:C,tokenX:x,tokenY:D,isStable:O,currentSqrtPrice:G}=w;if(!x?.coinType||!D?.coinType)throw new Error(`Swap Failed: route[${S}] is missing tokenX/tokenY after resolve. poolId=${w.poolId}`);let{id:U,isReverse:K}=fd.Utils.mappedMmtV3Pool[C]||{id:C,isReverse:!1},V=Q(x.coinType)===Q(b);V=K?!V:V;let E=K?D:x,ye=K?x:D,Wt=await Ve({poolId:U,tokenX:E,tokenY:ye,slippagePercentage:s,isTokenX:V,suiClient:r.rpcClient,currentSqrtPrice:G}),le=r.Pool.swap({txb:a,pool:{poolId:U,tokenXType:E.coinType,tokenYType:ye.coinType,tickSpacing:w.tickSpacing,isStable:O},amount:m,inputCoin:c,isXtoY:V,limitSqrtPrice:Wt});if(!le?.outputCoin)throw new Error("Swap Failed: empty swap result");a.transferObjects([c],a.pure.address(o)),c=le.outputCoin,b=V?ye.coinType:E.coinType,m=a.moveCall({target:"0x2::coin::value",typeArguments:[b],arguments:[c]})}a.transferObjects([c],a.pure.address(o))};var ji=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),o=await hd(n,this.data.params),a=new yd.Transaction;return await gd(n,o.route,o.tokenIn,o.amountIn,o.address,a,o.slippage),a}static fromData(t){return new r(t)}};var Ui=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let{params:n}=this.data,{address:o,amount:a}=n;return md(t.suiGrpcClient,o,a)}static fromData(t){return new r(t)}};var bd=require("@mysten/sui/transactions");var Gi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Rt(t.suiGrpcClient),o=Qt(t.suiGrpcClient),{params:a}=this.data,{token:s,amount:c,address:m,enableAutoMaxBond:b,unbondAt:S}=a,w=new bd.Transaction;return await Zm(n,o,s,c,m,b,S,w),w}static fromData(t){return new r(t)}};var Td=require("@mysten/sui/transactions");var qi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Qt(t.suiGrpcClient),{params:o}=this.data,{address:a,veId:s,currentUnbondAt:c,isCurrentlyMaxBond:m,enableAutoMaxBond:b,unbondAt:S}=o,w=new Td.Transaction;return await td(n,a,s,c,m,b,S,w),w}static fromData(t){return new r(t)}};var Sd=require("@mysten/sui/transactions");var Fi=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Qt(t.suiGrpcClient),{params:o}=this.data,{address:a,veId:s,selectedVeMMTIds:c}=o,m=new Sd.Transaction;return await ed(n,a,s,c,m),m}static fromData(t){return new r(t)}};var wd=require("@mysten/sui/transactions");var Ki=class r extends k{constructor(t){super(t);this.data=t}data;txType;txSubType;async build(t){let n=Qt(t.suiGrpcClient),{params:o}=this.data,{address:a,veId:s}=o,c=new wd.Transaction;return await nd(n,a,s,c),c}static fromData(t){return new r(t)}};var $i=class{application="mmt-dex";supportSDK="@mysten/sui-v2";async deserialize(e){let{appContext:t}=e;return{txType:Id.TransactionType.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=ji.fromData(e.intentionData);break;case"AddLiquidity":t=Oi.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=Pi.fromData(e.intentionData);break;case"ClaimRewards":t=Ni.fromData(e.intentionData);break;case"ClaimAllRewards":t=Ri.fromData(e.intentionData);break;case"ClaimRewardsAs":t=Bi.fromData(e.intentionData);break;case"RemoveLiquidity":t=_i.fromData(e.intentionData);break;case"StakeXSui":t=Li.fromData(e.intentionData);break;case"UnstakeXSui":t=Ui.fromData(e.intentionData);break;case"ManageLiquidity":t=Ei.fromData(e.intentionData);break;case"ManageLiquiditySingleSide":t=Wi.fromData(e.intentionData);break;case"Bond":t=Gi.fromData(e.intentionData);break;case"Extend":t=qi.fromData(e.intentionData);break;case"Merge":t=Fi.fromData(e.intentionData);break;case"Unbond":t=Ki.fromData(e.intentionData);break;default:throw new Error(`not implemented ${e.txSubType}`)}return t.build({suiGrpcClient:e.suiGrpcClient,account:e.account,network:e.network})}};var Vf=Kr.fromHelpers([new Or,new qr,new vr,new Fr,new Zo,new pi,new $i,new xa,new yi,new Do,new Na,new Fa,new ao,new Ai,new Ha]);
2
2
  //# sourceMappingURL=index.js.map